{"version":3,"file":"bundle.js","sources":["bundle.js"],"sourcesContent":["(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c=\"function\"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error(\"Cannot find module '\"+i+\"'\");throw a.code=\"MODULE_NOT_FOUND\",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u=\"function\"==typeof require&&require,i=0;i toState has (\"internal.\")\r\n\t\t//if true .... set a flag on $rootScope to resolve cached results as empty array\r\n\t\tvar str = 'internal.'; // str to hold the state to consider\r\n\t\tif((!fromState.name.indexOf(str) && toState.name.indexOf(str) === -1) || (fromState.name.indexOf(str) === -1 && !toState.name.indexOf(str))){\r\n\t\t\t//transition from internal to external or vice versa\r\n\t\t\t$rootScope.willSwitch = true; //set a flag willSwitch on rootScope\r\n\t\t}\r\n\t\t\r\n\t\t//D-01377 \"Holidays Observed\" modal window remains open in external search page\r\n\t\t//broadcast a close modal message to modal controller child scope\r\n\t\t$rootScope.$broadcast('close_modal');\r\n\t});\r\n\t\r\n\t$rootScope.$on('$stateChangeSuccess', function(event, toState,toParams,fromState,fromParams) { \r\n\t\t//$rootScope.title= _.isUndefined(toState.title) ? defaultTitle : toState.title;\r\n\t\t$rootScope.previousPage = fromState.name;\t\r\n\t\t//D-01296 Locator Page Loads w/ Search Results\r\n\t\t//check if willSwitch flag is set to true.This means user tried to navigate from/to internal/external search\r\n\t\t//remove any cached data and set willSwitch to false again\r\n\t\tif($rootScope.willSwitch){\r\n\t\t\tSearchService.resetCachedResult();\r\n\t\t\t$rootScope.willSwitch = false;\r\n\t\t}\r\n\t\t\r\n\t\t$rootScope.browseUrlInfo = {};\r\n\t\t//captures the state name passed from previous page\r\n\t\t//value captured from url, so it's escaped\r\n\t\t//unescape only -\r\n\t\tif(toParams.state){\r\n\t\t\tvar selectedState = toParams.state;\r\n\t\t\tselectedState = selectedState.replace(/\\-/g, \" \");\r\n\t\t\tselectedState = _.find(US_STATES, 'name', selectedState.toUpperCase()); \r\n\t\t\tif(selectedState){\r\n\t\t\t\t$rootScope.browseUrlInfo.state = selectedState\r\n\t\t\t}\r\n\t\t}\r\n\t\t\t\r\n\t\t//captures the city name passed from previous page\r\n\t\t//value captured from url, so it's escaped\r\n\t\t//unescape only -\r\n\t\tif(toParams.city){\r\n\t\t\tvar selectedCity = toParams.city;\r\n\t\t\tselectedCity = selectedCity.replace(/\\-/g, \" \");\r\n\t\t\t$rootScope.browseUrlInfo.city = selectedCity;\r\n\t\t}\r\n\t\t\r\n\t\t//captures the branch/atm name passed from previous page\r\n\t\t//value captured from url, so it's escaped\r\n\t\t//unescape only -\r\n\t\tif(toParams.name){\r\n\t\t\tvar selectedLocation = toParams.name;\r\n\t\t\tselectedLocation = selectedLocation.replace(/\\-/g, \" \");\r\n\t\t\t$rootScope.browseUrlInfo.name = selectedLocation;\r\n\t\t}\r\n\t\t\r\n\t\t//captures the external id of selected location\r\n\t\tif(toParams.id){\r\n\t\t\t$rootScope.browseUrlInfo.id = toParams.id;\r\n\t\t}\r\n\t\t\r\n\t\t//captures the branch count for a selected city\r\n\t\tif(toParams.count){\r\n\t\t\t$rootScope.browseUrlInfo.count = toParams.count;\r\n\t\t}\r\n\t\t\r\n\t\t//captures the original state name passed from previous page\r\n\t\tif(toParams.stateOrigName){\r\n\t\t\tvar selectedState = toParams.stateOrigName;\r\n\t\t\tselectedState = _.find(US_STATES, 'name', selectedState.toUpperCase()); \r\n\t\t\tif(selectedState){\r\n\t\t\t\t$rootScope.browseUrlInfo.stateOrigName = selectedState;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\t//captures the original city name passed from previous page\r\n\t\tif(toParams.cityOrigName){\r\n\t\t\t$rootScope.browseUrlInfo.cityOrigName = toParams.cityOrigName;\r\n\t\t}\r\n\t\t\r\n\t\t//captures the original branch/atm name passed from previous page\r\n\t\tif(toParams.origName){\r\n\t\t\t$rootScope.browseUrlInfo.origName = toParams.origName;\r\n\t\t}\r\n\t\t\r\n\t\t//captures the isBrowseModule parameter passed from previous page\r\n\t\tif(toParams.isBrowseModule){\r\n\t\t\t$rootScope.browseUrlInfo.isBrowseModule = toParams.isBrowseModule;\r\n\t\t}\r\n\r\n\t\t//captures the location object parameter passed while page navigation\r\n\t\tif(toParams.locObjBreadCrumb){\r\n\t\t\t$rootScope.browseUrlInfo.locObjBreadCrumb = toParams.locObjBreadCrumb;\r\n\t\t}\r\n\t\t\r\n\t\t$rootScope.browseUrlInfo.toStateName = toState.name;\r\n\t\t$rootScope.browseUrlInfo.fromStateName = fromState.name;\r\n\t\t\r\n\t\t$rootScope.scrollPageToTop();\r\n\t\tvar hdrSpan = document.getElementById(\"hdrspancontainer\");\r\n if(hdrSpan){\r\n hdrSpan.tabIndex = \"-1\";\r\n hdrSpan.focus();\r\n }\r\n\t});\r\n\t\r\n\t//D-01296 Locator Page Loads w/ Search Results\r\n\t$rootScope.$on('$stateChangeError',function(){\r\n\t\t//set willSwitch flag to false\r\n\t\t$rootScope.willSwitch = false;\r\n\t});\r\n\t\r\n\tattachFastClick(document.body);\r\n}]);\r\n\r\nappModule.config(router);\n},{\"./modules/admin/header-footer-tiny\":13,\"./modules/browse-locations/browse\":16,\"./modules/common/common\":23,\"./modules/constants/constants\":49,\"./modules/directives/directives\":54,\"./modules/driving-directions/driving-directions\":61,\"./modules/error-pages/error-pages\":62,\"./modules/result-details/result-details\":68,\"./modules/search/search\":80,\"./router\":82,\"angular\":9,\"angular-animate\":2,\"angular-bootstrap\":3,\"angular-cookies\":4,\"angular-google-maps\":5,\"angular-media-queries\":6,\"angular-ui-router\":8,\"fastclick\":10,\"lodash\":11,\"ng-device-detector\":12,\"ngSanitize\":7}],2:[function(require,module,exports){\n/**\r\n * @license AngularJS v1.3.18\r\n * (c) 2010-2014 Google, Inc. http://angularjs.org\r\n * License: MIT\r\n */\r\n(function(window, angular, undefined) {'use strict';\r\n\r\n/* jshint maxlen: false */\r\n\r\n/**\r\n * @ngdoc module\r\n * @name ngAnimate\r\n * @description\r\n *\r\n * The `ngAnimate` module provides support for JavaScript, CSS3 transition and CSS3 keyframe animation hooks within existing core and custom directives.\r\n *\r\n *
\r\n *\r\n * # Usage\r\n *\r\n * To see animations in action, all that is required is to define the appropriate CSS classes\r\n * or to register a JavaScript animation via the `myModule.animation()` function. The directives that support animation automatically are:\r\n * `ngRepeat`, `ngInclude`, `ngIf`, `ngSwitch`, `ngShow`, `ngHide`, `ngView` and `ngClass`. Custom directives can take advantage of animation\r\n * by using the `$animate` service.\r\n *\r\n * Below is a more detailed breakdown of the supported animation events provided by pre-existing ng directives:\r\n *\r\n * | Directive | Supported Animations |\r\n * |----------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------|\r\n * | {@link ng.directive:ngRepeat#animations ngRepeat} | enter, leave and move |\r\n * | {@link ngRoute.directive:ngView#animations ngView} | enter and leave |\r\n * | {@link ng.directive:ngInclude#animations ngInclude} | enter and leave |\r\n * | {@link ng.directive:ngSwitch#animations ngSwitch} | enter and leave |\r\n * | {@link ng.directive:ngIf#animations ngIf} | enter and leave |\r\n * | {@link ng.directive:ngClass#animations ngClass} | add and remove (the CSS class(es) present) |\r\n * | {@link ng.directive:ngShow#animations ngShow} & {@link ng.directive:ngHide#animations ngHide} | add and remove (the ng-hide class value) |\r\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) |\r\n * | {@link module:ngMessages#animations ngMessages} | add and remove (ng-active & ng-inactive) |\r\n * | {@link module:ngMessages#animations ngMessage} | enter and leave |\r\n *\r\n * You can find out more information about animations upon visiting each directive page.\r\n *\r\n * Below is an example of how to apply animations to a directive that supports animation hooks:\r\n *\r\n * ```html\r\n * \r\n *\r\n * \r\n * \r\n * ```\r\n *\r\n * Keep in mind that, by default, if an animation is running, any child elements cannot be animated\r\n * until the parent element's animation has completed. This blocking feature can be overridden by\r\n * placing the `ng-animate-children` attribute on a parent container tag.\r\n *\r\n * ```html\r\n *
\r\n *
\r\n *
\r\n * ...\r\n *
\r\n *
\r\n *
\r\n * ```\r\n *\r\n * When the `on` expression value changes and an animation is triggered then each of the elements within\r\n * will all animate without the block being applied to child elements.\r\n *\r\n * ## Are animations run when the application starts?\r\n * No they are not. When an application is bootstrapped Angular will disable animations from running to avoid\r\n * a frenzy of animations from being triggered as soon as the browser has rendered the screen. For this to work,\r\n * Angular will wait for two digest cycles until enabling animations. From there on, any animation-triggering\r\n * layout changes in the application will trigger animations as normal.\r\n *\r\n * In addition, upon bootstrap, if the routing system or any directives or load remote data (via $http) then Angular\r\n * will automatically extend the wait time to enable animations once **all** of the outbound HTTP requests\r\n * are complete.\r\n *\r\n * ## CSS-defined Animations\r\n * The animate service will automatically apply two CSS classes to the animated element and these two CSS classes\r\n * are designed to contain the start and end CSS styling. Both CSS transitions and keyframe animations are supported\r\n * and can be used to play along with this naming structure.\r\n *\r\n * The following code below demonstrates how to perform animations using **CSS transitions** with Angular:\r\n *\r\n * ```html\r\n * \r\n *\r\n *
\r\n *
\r\n *
\r\n * ```\r\n *\r\n * The following code below demonstrates how to perform animations using **CSS animations** with Angular:\r\n *\r\n * ```html\r\n * \r\n *\r\n *
\r\n *
\r\n *
\r\n * ```\r\n *\r\n * Both CSS3 animations and transitions can be used together and the animate service will figure out the correct duration and delay timing.\r\n *\r\n * Upon DOM mutation, the event class is added first (something like `ng-enter`), then the browser prepares itself to add\r\n * the active class (in this case `ng-enter-active`) which then triggers the animation. The animation module will automatically\r\n * detect the CSS code to determine when the animation ends. Once the animation is over then both CSS classes will be\r\n * removed from the DOM. If a browser does not support CSS transitions or CSS animations then the animation will start and end\r\n * immediately resulting in a DOM element that is at its final state. This final state is when the DOM element\r\n * has no CSS transition/animation classes applied to it.\r\n *\r\n * ### Structural transition animations\r\n *\r\n * Structural transitions (such as enter, leave and move) will always apply a `0s none` transition\r\n * value to force the browser into rendering the styles defined in the setup (`.ng-enter`, `.ng-leave`\r\n * or `.ng-move`) class. This means that any active transition animations operating on the element\r\n * will be cut off to make way for the enter, leave or move animation.\r\n *\r\n * ### Class-based transition animations\r\n *\r\n * Class-based transitions refer to transition animations that are triggered when a CSS class is\r\n * added to or removed from the element (via `$animate.addClass`, `$animate.removeClass`,\r\n * `$animate.setClass`, or by directives such as `ngClass`, `ngModel` and `form`).\r\n * They are different when compared to structural animations since they **do not cancel existing\r\n * animations** nor do they **block successive transitions** from rendering on the same element.\r\n * This distinction allows for **multiple class-based transitions** to be performed on the same element.\r\n *\r\n * In addition to ngAnimate supporting the default (natural) functionality of class-based transition\r\n * animations, ngAnimate also decorates the element with starting and ending CSS classes to aid the\r\n * developer in further styling the element throughout the transition animation. Earlier versions\r\n * of ngAnimate may have caused natural CSS transitions to break and not render properly due to\r\n * $animate temporarily blocking transitions using `0s none` in order to allow the setup CSS class\r\n * (the `-add` or `-remove` class) to be applied without triggering an animation. However, as of\r\n * **version 1.3**, this workaround has been removed with ngAnimate and all non-ngAnimate CSS\r\n * class transitions are compatible with ngAnimate.\r\n *\r\n * There is, however, one special case when dealing with class-based transitions in ngAnimate.\r\n * When rendering class-based transitions that make use of the setup and active CSS classes\r\n * (e.g. `.fade-add` and `.fade-add-active` for when `.fade` is added) be sure to define\r\n * the transition value **on the active CSS class** and not the setup class.\r\n *\r\n * ```css\r\n * .fade-add {\r\n * /* remember to place a 0s transition here\r\n * to ensure that the styles are applied instantly\r\n * even if the element already has a transition style */\r\n * transition:0s linear all;\r\n *\r\n * /* starting CSS styles */\r\n * opacity:1;\r\n * }\r\n * .fade-add.fade-add-active {\r\n * /* this will be the length of the animation */\r\n * transition:1s linear all;\r\n * opacity:0;\r\n * }\r\n * ```\r\n *\r\n * The setup CSS class (in this case `.fade-add`) also has a transition style property, however, it\r\n * has a duration of zero. This may not be required, however, incase the browser is unable to render\r\n * the styling present in this CSS class instantly then it could be that the browser is attempting\r\n * to perform an unnecessary transition.\r\n *\r\n * This workaround, however, does not apply to standard class-based transitions that are rendered\r\n * when a CSS class containing a transition is applied to an element:\r\n *\r\n * ```css\r\n * /* this works as expected */\r\n * .fade {\r\n * transition:1s linear all;\r\n * opacity:0;\r\n * }\r\n * ```\r\n *\r\n * Please keep this in mind when coding the CSS markup that will be used within class-based transitions.\r\n * Also, try not to mix the two class-based animation flavors together since the CSS code may become\r\n * overly complex.\r\n *\r\n *\r\n * ### Preventing Collisions With Third Party Libraries\r\n *\r\n * Some third-party frameworks place animation duration defaults across many element or className\r\n * selectors in order to make their code small and reuseable. This can lead to issues with ngAnimate, which\r\n * is expecting actual animations on these elements and has to wait for their completion.\r\n *\r\n * You can prevent this unwanted behavior by using a prefix on all your animation classes:\r\n *\r\n * ```css\r\n * /* prefixed with animate- */\r\n * .animate-fade-add.animate-fade-add-active {\r\n * transition:1s linear all;\r\n * opacity:0;\r\n * }\r\n * ```\r\n *\r\n * You then configure `$animate` to enforce this prefix:\r\n *\r\n * ```js\r\n * $animateProvider.classNameFilter(/animate-/);\r\n * ```\r\n * \r\n *\r\n * ### CSS Staggering Animations\r\n * A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a\r\n * curtain-like effect. The ngAnimate module (versions >=1.2) supports staggering animations and the stagger effect can be\r\n * performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for\r\n * the animation. The style property expected within the stagger class can either be a **transition-delay** or an\r\n * **animation-delay** property (or both if your animation contains both transitions and keyframe animations).\r\n *\r\n * ```css\r\n * .my-animation.ng-enter {\r\n * /* standard transition code */\r\n * -webkit-transition: 1s linear all;\r\n * transition: 1s linear all;\r\n * opacity:0;\r\n * }\r\n * .my-animation.ng-enter-stagger {\r\n * /* this will have a 100ms delay between each successive leave animation */\r\n * -webkit-transition-delay: 0.1s;\r\n * transition-delay: 0.1s;\r\n *\r\n * /* in case the stagger doesn't work then these two values\r\n * must be set to 0 to avoid an accidental CSS inheritance */\r\n * -webkit-transition-duration: 0s;\r\n * transition-duration: 0s;\r\n * }\r\n * .my-animation.ng-enter.ng-enter-active {\r\n * /* standard transition styles */\r\n * opacity:1;\r\n * }\r\n * ```\r\n *\r\n * Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations\r\n * on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this\r\n * are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation\r\n * will also be reset if more than 10ms has passed after the last animation has been fired.\r\n *\r\n * The following code will issue the **ng-leave-stagger** event on the element provided:\r\n *\r\n * ```js\r\n * var kids = parent.children();\r\n *\r\n * $animate.leave(kids[0]); //stagger index=0\r\n * $animate.leave(kids[1]); //stagger index=1\r\n * $animate.leave(kids[2]); //stagger index=2\r\n * $animate.leave(kids[3]); //stagger index=3\r\n * $animate.leave(kids[4]); //stagger index=4\r\n *\r\n * $timeout(function() {\r\n * //stagger has reset itself\r\n * $animate.leave(kids[5]); //stagger index=0\r\n * $animate.leave(kids[6]); //stagger index=1\r\n * }, 100, false);\r\n * ```\r\n *\r\n * Stagger animations are currently only supported within CSS-defined animations.\r\n *\r\n * ## JavaScript-defined Animations\r\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\r\n * yet support CSS transitions/animations, then you can make use of JavaScript animations defined inside of your AngularJS module.\r\n *\r\n * ```js\r\n * //!annotate=\"YourApp\" Your AngularJS Module|Replace this or ngModule with the module that you used to define your application.\r\n * var ngModule = angular.module('YourApp', ['ngAnimate']);\r\n * ngModule.animation('.my-crazy-animation', function() {\r\n * return {\r\n * enter: function(element, done) {\r\n * //run the animation here and call done when the animation is complete\r\n * return function(cancelled) {\r\n * //this (optional) function will be called when the animation\r\n * //completes or when the animation is cancelled (the cancelled\r\n * //flag will be set to true if cancelled).\r\n * };\r\n * },\r\n * leave: function(element, done) { },\r\n * move: function(element, done) { },\r\n *\r\n * //animation that can be triggered before the class is added\r\n * beforeAddClass: function(element, className, done) { },\r\n *\r\n * //animation that can be triggered after the class is added\r\n * addClass: function(element, className, done) { },\r\n *\r\n * //animation that can be triggered before the class is removed\r\n * beforeRemoveClass: function(element, className, done) { },\r\n *\r\n * //animation that can be triggered after the class is removed\r\n * removeClass: function(element, className, done) { }\r\n * };\r\n * });\r\n * ```\r\n *\r\n * JavaScript-defined animations are created with a CSS-like class selector and a collection of events which are set to run\r\n * a javascript callback function. When an animation is triggered, $animate will look for a matching animation which fits\r\n * the element's CSS class attribute value and then run the matching animation event function (if found).\r\n * In other words, if the CSS classes present on the animated element match any of the JavaScript animations then the callback function will\r\n * be executed. It should be also noted that only simple, single class selectors are allowed (compound class selectors are not supported).\r\n *\r\n * Within a JavaScript animation, an object containing various event callback animation functions is expected to be returned.\r\n * As explained above, these callbacks are triggered based on the animation event. Therefore if an enter animation is run,\r\n * and the JavaScript animation is found, then the enter callback will handle that animation (in addition to the CSS keyframe animation\r\n * or transition code that is defined via a stylesheet).\r\n *\r\n *\r\n * ### Applying Directive-specific Styles to an Animation\r\n * In some cases a directive or service may want to provide `$animate` with extra details that the animation will\r\n * include into its animation. Let's say for example we wanted to render an animation that animates an element\r\n * towards the mouse coordinates as to where the user clicked last. By collecting the X/Y coordinates of the click\r\n * (via the event parameter) we can set the `top` and `left` styles into an object and pass that into our function\r\n * call to `$animate.addClass`.\r\n *\r\n * ```js\r\n * canvas.on('click', function(e) {\r\n * $animate.addClass(element, 'on', {\r\n * to: {\r\n * left : e.client.x + 'px',\r\n * top : e.client.y + 'px'\r\n * }\r\n * }):\r\n * });\r\n * ```\r\n *\r\n * Now when the animation runs, and a transition or keyframe animation is picked up, then the animation itself will\r\n * also include and transition the styling of the `left` and `top` properties into its running animation. If we want\r\n * to provide some starting animation values then we can do so by placing the starting animations styles into an object\r\n * called `from` in the same object as the `to` animations.\r\n *\r\n * ```js\r\n * canvas.on('click', function(e) {\r\n * $animate.addClass(element, 'on', {\r\n * from: {\r\n * position: 'absolute',\r\n * left: '0px',\r\n * top: '0px'\r\n * },\r\n * to: {\r\n * left : e.client.x + 'px',\r\n * top : e.client.y + 'px'\r\n * }\r\n * }):\r\n * });\r\n * ```\r\n *\r\n * Once the animation is complete or cancelled then the union of both the before and after styles are applied to the\r\n * element. If `ngAnimate` is not present then the styles will be applied immediately.\r\n *\r\n */\r\n\r\nangular.module('ngAnimate', ['ng'])\r\n\r\n /**\r\n * @ngdoc provider\r\n * @name $animateProvider\r\n * @description\r\n *\r\n * The `$animateProvider` allows developers to register JavaScript animation event handlers directly inside of a module.\r\n * When an animation is triggered, the $animate service will query the $animate service to find any animations that match\r\n * the provided name value.\r\n *\r\n * Requires the {@link ngAnimate `ngAnimate`} module to be installed.\r\n *\r\n * Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application.\r\n *\r\n */\r\n .directive('ngAnimateChildren', function() {\r\n var NG_ANIMATE_CHILDREN = '$$ngAnimateChildren';\r\n return function(scope, element, attrs) {\r\n var val = attrs.ngAnimateChildren;\r\n if (angular.isString(val) && val.length === 0) { //empty attribute\r\n element.data(NG_ANIMATE_CHILDREN, true);\r\n } else {\r\n scope.$watch(val, function(value) {\r\n element.data(NG_ANIMATE_CHILDREN, !!value);\r\n });\r\n }\r\n };\r\n })\r\n\r\n //this private service is only used within CSS-enabled animations\r\n //IE8 + IE9 do not support rAF natively, but that is fine since they\r\n //also don't support transitions and keyframes which means that the code\r\n //below will never be used by the two browsers.\r\n .factory('$$animateReflow', ['$$rAF', '$document', function($$rAF, $document) {\r\n var bod = $document[0].body;\r\n return function(fn) {\r\n //the returned function acts as the cancellation function\r\n return $$rAF(function() {\r\n //the line below will force the browser to perform a repaint\r\n //so that all the animated elements within the animation frame\r\n //will be properly updated and drawn on screen. This is\r\n //required to perform multi-class CSS based animations with\r\n //Firefox. DO NOT REMOVE THIS LINE. DO NOT OPTIMIZE THIS LINE.\r\n //THE MINIFIER WILL REMOVE IT OTHERWISE WHICH WILL RESULT IN AN\r\n //UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND WILL\r\n //TAKE YEARS AWAY FROM YOUR LIFE!\r\n fn(bod.offsetWidth);\r\n });\r\n };\r\n }])\r\n\r\n .config(['$provide', '$animateProvider', function($provide, $animateProvider) {\r\n var noop = angular.noop;\r\n var forEach = angular.forEach;\r\n var selectors = $animateProvider.$$selectors;\r\n var isArray = angular.isArray;\r\n var isString = angular.isString;\r\n var isObject = angular.isObject;\r\n\r\n var ELEMENT_NODE = 1;\r\n var NG_ANIMATE_STATE = '$$ngAnimateState';\r\n var NG_ANIMATE_CHILDREN = '$$ngAnimateChildren';\r\n var NG_ANIMATE_CLASS_NAME = 'ng-animate';\r\n var rootAnimateState = {running: true};\r\n\r\n function extractElementNode(element) {\r\n for (var i = 0; i < element.length; i++) {\r\n var elm = element[i];\r\n if (elm.nodeType == ELEMENT_NODE) {\r\n return elm;\r\n }\r\n }\r\n }\r\n\r\n function prepareElement(element) {\r\n return element && angular.element(element);\r\n }\r\n\r\n function stripCommentsFromElement(element) {\r\n return angular.element(extractElementNode(element));\r\n }\r\n\r\n function isMatchingElement(elm1, elm2) {\r\n return extractElementNode(elm1) == extractElementNode(elm2);\r\n }\r\n var $$jqLite;\r\n $provide.decorator('$animate',\r\n ['$delegate', '$$q', '$injector', '$sniffer', '$rootElement', '$$asyncCallback', '$rootScope', '$document', '$templateRequest', '$$jqLite',\r\n function($delegate, $$q, $injector, $sniffer, $rootElement, $$asyncCallback, $rootScope, $document, $templateRequest, $$$jqLite) {\r\n\r\n $$jqLite = $$$jqLite;\r\n $rootElement.data(NG_ANIMATE_STATE, rootAnimateState);\r\n\r\n // Wait until all directive and route-related templates are downloaded and\r\n // compiled. The $templateRequest.totalPendingRequests variable keeps track of\r\n // all of the remote templates being currently downloaded. If there are no\r\n // templates currently downloading then the watcher will still fire anyway.\r\n var deregisterWatch = $rootScope.$watch(\r\n function() { return $templateRequest.totalPendingRequests; },\r\n function(val, oldVal) {\r\n if (val !== 0) return;\r\n deregisterWatch();\r\n\r\n // Now that all templates have been downloaded, $animate will wait until\r\n // the post digest queue is empty before enabling animations. By having two\r\n // calls to $postDigest calls we can ensure that the flag is enabled at the\r\n // very end of the post digest queue. Since all of the animations in $animate\r\n // use $postDigest, it's important that the code below executes at the end.\r\n // This basically means that the page is fully downloaded and compiled before\r\n // any animations are triggered.\r\n $rootScope.$$postDigest(function() {\r\n $rootScope.$$postDigest(function() {\r\n rootAnimateState.running = false;\r\n });\r\n });\r\n }\r\n );\r\n\r\n var globalAnimationCounter = 0;\r\n var classNameFilter = $animateProvider.classNameFilter();\r\n var isAnimatableClassName = !classNameFilter\r\n ? function() { return true; }\r\n : function(className) {\r\n return classNameFilter.test(className);\r\n };\r\n\r\n function classBasedAnimationsBlocked(element, setter) {\r\n var data = element.data(NG_ANIMATE_STATE) || {};\r\n if (setter) {\r\n data.running = true;\r\n data.structural = true;\r\n element.data(NG_ANIMATE_STATE, data);\r\n }\r\n return data.disabled || (data.running && data.structural);\r\n }\r\n\r\n function runAnimationPostDigest(fn) {\r\n var cancelFn, defer = $$q.defer();\r\n defer.promise.$$cancelFn = function() {\r\n cancelFn && cancelFn();\r\n };\r\n $rootScope.$$postDigest(function() {\r\n cancelFn = fn(function() {\r\n defer.resolve();\r\n });\r\n });\r\n return defer.promise;\r\n }\r\n\r\n function parseAnimateOptions(options) {\r\n // some plugin code may still be passing in the callback\r\n // function as the last param for the $animate methods so\r\n // it's best to only allow string or array values for now\r\n if (isObject(options)) {\r\n if (options.tempClasses && isString(options.tempClasses)) {\r\n options.tempClasses = options.tempClasses.split(/\\s+/);\r\n }\r\n return options;\r\n }\r\n }\r\n\r\n function resolveElementClasses(element, cache, runningAnimations) {\r\n runningAnimations = runningAnimations || {};\r\n\r\n var lookup = {};\r\n forEach(runningAnimations, function(data, selector) {\r\n forEach(selector.split(' '), function(s) {\r\n lookup[s]=data;\r\n });\r\n });\r\n\r\n var hasClasses = Object.create(null);\r\n forEach((element.attr('class') || '').split(/\\s+/), function(className) {\r\n hasClasses[className] = true;\r\n });\r\n\r\n var toAdd = [], toRemove = [];\r\n forEach((cache && cache.classes) || [], function(status, className) {\r\n var hasClass = hasClasses[className];\r\n var matchingAnimation = lookup[className] || {};\r\n\r\n // When addClass and removeClass is called then $animate will check to\r\n // see if addClass and removeClass cancel each other out. When there are\r\n // more calls to removeClass than addClass then the count falls below 0\r\n // and then the removeClass animation will be allowed. Otherwise if the\r\n // count is above 0 then that means an addClass animation will commence.\r\n // Once an animation is allowed then the code will also check to see if\r\n // there exists any on-going animation that is already adding or remvoing\r\n // the matching CSS class.\r\n if (status === false) {\r\n //does it have the class or will it have the class\r\n if (hasClass || matchingAnimation.event == 'addClass') {\r\n toRemove.push(className);\r\n }\r\n } else if (status === true) {\r\n //is the class missing or will it be removed?\r\n if (!hasClass || matchingAnimation.event == 'removeClass') {\r\n toAdd.push(className);\r\n }\r\n }\r\n });\r\n\r\n return (toAdd.length + toRemove.length) > 0 && [toAdd.join(' '), toRemove.join(' ')];\r\n }\r\n\r\n function lookup(name) {\r\n if (name) {\r\n var matches = [],\r\n flagMap = {},\r\n classes = name.substr(1).split('.');\r\n\r\n //the empty string value is the default animation\r\n //operation which performs CSS transition and keyframe\r\n //animations sniffing. This is always included for each\r\n //element animation procedure if the browser supports\r\n //transitions and/or keyframe animations. The default\r\n //animation is added to the top of the list to prevent\r\n //any previous animations from affecting the element styling\r\n //prior to the element being animated.\r\n if ($sniffer.transitions || $sniffer.animations) {\r\n matches.push($injector.get(selectors['']));\r\n }\r\n\r\n for (var i=0; i < classes.length; i++) {\r\n var klass = classes[i],\r\n selectorFactoryName = selectors[klass];\r\n if (selectorFactoryName && !flagMap[klass]) {\r\n matches.push($injector.get(selectorFactoryName));\r\n flagMap[klass] = true;\r\n }\r\n }\r\n return matches;\r\n }\r\n }\r\n\r\n function animationRunner(element, animationEvent, className, options) {\r\n //transcluded directives may sometimes fire an animation using only comment nodes\r\n //best to catch this early on to prevent any animation operations from occurring\r\n var node = element[0];\r\n if (!node) {\r\n return;\r\n }\r\n\r\n if (options) {\r\n options.to = options.to || {};\r\n options.from = options.from || {};\r\n }\r\n\r\n var classNameAdd;\r\n var classNameRemove;\r\n if (isArray(className)) {\r\n classNameAdd = className[0];\r\n classNameRemove = className[1];\r\n if (!classNameAdd) {\r\n className = classNameRemove;\r\n animationEvent = 'removeClass';\r\n } else if (!classNameRemove) {\r\n className = classNameAdd;\r\n animationEvent = 'addClass';\r\n } else {\r\n className = classNameAdd + ' ' + classNameRemove;\r\n }\r\n }\r\n\r\n var isSetClassOperation = animationEvent == 'setClass';\r\n var isClassBased = isSetClassOperation\r\n || animationEvent == 'addClass'\r\n || animationEvent == 'removeClass'\r\n || animationEvent == 'animate';\r\n\r\n var currentClassName = element.attr('class');\r\n var classes = currentClassName + ' ' + className;\r\n if (!isAnimatableClassName(classes)) {\r\n return;\r\n }\r\n\r\n var beforeComplete = noop,\r\n beforeCancel = [],\r\n before = [],\r\n afterComplete = noop,\r\n afterCancel = [],\r\n after = [];\r\n\r\n var animationLookup = (' ' + classes).replace(/\\s+/g,'.');\r\n forEach(lookup(animationLookup), function(animationFactory) {\r\n var created = registerAnimation(animationFactory, animationEvent);\r\n if (!created && isSetClassOperation) {\r\n registerAnimation(animationFactory, 'addClass');\r\n registerAnimation(animationFactory, 'removeClass');\r\n }\r\n });\r\n\r\n function registerAnimation(animationFactory, event) {\r\n var afterFn = animationFactory[event];\r\n var beforeFn = animationFactory['before' + event.charAt(0).toUpperCase() + event.substr(1)];\r\n if (afterFn || beforeFn) {\r\n if (event == 'leave') {\r\n beforeFn = afterFn;\r\n //when set as null then animation knows to skip this phase\r\n afterFn = null;\r\n }\r\n after.push({\r\n event: event, fn: afterFn\r\n });\r\n before.push({\r\n event: event, fn: beforeFn\r\n });\r\n return true;\r\n }\r\n }\r\n\r\n function run(fns, cancellations, allCompleteFn) {\r\n var animations = [];\r\n forEach(fns, function(animation) {\r\n animation.fn && animations.push(animation);\r\n });\r\n\r\n var count = 0;\r\n function afterAnimationComplete(index) {\r\n if (cancellations) {\r\n (cancellations[index] || noop)();\r\n if (++count < animations.length) return;\r\n cancellations = null;\r\n }\r\n allCompleteFn();\r\n }\r\n\r\n //The code below adds directly to the array in order to work with\r\n //both sync and async animations. Sync animations are when the done()\r\n //operation is called right away. DO NOT REFACTOR!\r\n forEach(animations, function(animation, index) {\r\n var progress = function() {\r\n afterAnimationComplete(index);\r\n };\r\n switch (animation.event) {\r\n case 'setClass':\r\n cancellations.push(animation.fn(element, classNameAdd, classNameRemove, progress, options));\r\n break;\r\n case 'animate':\r\n cancellations.push(animation.fn(element, className, options.from, options.to, progress));\r\n break;\r\n case 'addClass':\r\n cancellations.push(animation.fn(element, classNameAdd || className, progress, options));\r\n break;\r\n case 'removeClass':\r\n cancellations.push(animation.fn(element, classNameRemove || className, progress, options));\r\n break;\r\n default:\r\n cancellations.push(animation.fn(element, progress, options));\r\n break;\r\n }\r\n });\r\n\r\n if (cancellations && cancellations.length === 0) {\r\n allCompleteFn();\r\n }\r\n }\r\n\r\n return {\r\n node: node,\r\n event: animationEvent,\r\n className: className,\r\n isClassBased: isClassBased,\r\n isSetClassOperation: isSetClassOperation,\r\n applyStyles: function() {\r\n if (options) {\r\n element.css(angular.extend(options.from || {}, options.to || {}));\r\n }\r\n },\r\n before: function(allCompleteFn) {\r\n beforeComplete = allCompleteFn;\r\n run(before, beforeCancel, function() {\r\n beforeComplete = noop;\r\n allCompleteFn();\r\n });\r\n },\r\n after: function(allCompleteFn) {\r\n afterComplete = allCompleteFn;\r\n run(after, afterCancel, function() {\r\n afterComplete = noop;\r\n allCompleteFn();\r\n });\r\n },\r\n cancel: function() {\r\n if (beforeCancel) {\r\n forEach(beforeCancel, function(cancelFn) {\r\n (cancelFn || noop)(true);\r\n });\r\n beforeComplete(true);\r\n }\r\n if (afterCancel) {\r\n forEach(afterCancel, function(cancelFn) {\r\n (cancelFn || noop)(true);\r\n });\r\n afterComplete(true);\r\n }\r\n }\r\n };\r\n }\r\n\r\n /**\r\n * @ngdoc service\r\n * @name $animate\r\n * @kind object\r\n *\r\n * @description\r\n * The `$animate` service provides animation detection support while performing DOM operations (enter, leave and move) as well as during addClass and removeClass operations.\r\n * When any of these operations are run, the $animate service\r\n * will examine any JavaScript-defined animations (which are defined by using the $animateProvider provider object)\r\n * as well as any CSS-defined animations against the CSS classes present on the element once the DOM operation is run.\r\n *\r\n * The `$animate` service is used behind the scenes with pre-existing directives and animation with these directives\r\n * will work out of the box without any extra configuration.\r\n *\r\n * Requires the {@link ngAnimate `ngAnimate`} module to be installed.\r\n *\r\n * Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application.\r\n * ## Callback Promises\r\n * With AngularJS 1.3, each of the animation methods, on the `$animate` service, return a promise when called. The\r\n * promise itself is then resolved once the animation has completed itself, has been cancelled or has been\r\n * skipped due to animations being disabled. (Note that even if the animation is cancelled it will still\r\n * call the resolve function of the animation.)\r\n *\r\n * ```js\r\n * $animate.enter(element, container).then(function() {\r\n * //...this is called once the animation is complete...\r\n * });\r\n * ```\r\n *\r\n * Also note that, due to the nature of the callback promise, if any Angular-specific code (like changing the scope,\r\n * location of the page, etc...) is executed within the callback promise then be sure to wrap the code using\r\n * `$scope.$apply(...)`;\r\n *\r\n * ```js\r\n * $animate.leave(element).then(function() {\r\n * $scope.$apply(function() {\r\n * $location.path('/new-page');\r\n * });\r\n * });\r\n * ```\r\n *\r\n * An animation can also be cancelled by calling the `$animate.cancel(promise)` method with the provided\r\n * promise that was returned when the animation was started.\r\n *\r\n * ```js\r\n * var promise = $animate.addClass(element, 'super-long-animation');\r\n * promise.then(function() {\r\n * //this will still be called even if cancelled\r\n * });\r\n *\r\n * element.on('click', function() {\r\n * //tooo lazy to wait for the animation to end\r\n * $animate.cancel(promise);\r\n * });\r\n * ```\r\n *\r\n * (Keep in mind that the promise cancellation is unique to `$animate` since promises in\r\n * general cannot be cancelled.)\r\n *\r\n */\r\n return {\r\n /**\r\n * @ngdoc method\r\n * @name $animate#animate\r\n * @kind function\r\n *\r\n * @description\r\n * Performs an inline animation on the element which applies the provided `to` and `from` CSS styles to the element.\r\n * If any detected CSS transition, keyframe or JavaScript matches the provided `className` value then the animation\r\n * will take on the provided styles. For example, if a transition animation is set for the given className then the\r\n * provided `from` and `to` styles will be applied alongside the given transition. If a JavaScript animation is\r\n * detected then the provided styles will be given in as function paramters.\r\n *\r\n * ```js\r\n * ngModule.animation('.my-inline-animation', function() {\r\n * return {\r\n * animate : function(element, className, from, to, done) {\r\n * //styles\r\n * }\r\n * }\r\n * });\r\n * ```\r\n *\r\n * Below is a breakdown of each step that occurs during the `animate` animation:\r\n *\r\n * | Animation Step | What the element class attribute looks like |\r\n * |-----------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------|\r\n * | 1. `$animate.animate(...)` is called | `class=\"my-animation\"` |\r\n * | 2. `$animate` waits for the next digest to start the animation | `class=\"my-animation ng-animate\"` |\r\n * | 3. `$animate` runs the JavaScript-defined animations detected on the element | `class=\"my-animation ng-animate\"` |\r\n * | 4. the `className` class value is added to the element | `class=\"my-animation ng-animate className\"` |\r\n * | 5. `$animate` scans the element styles to get the CSS transition/animation duration and delay | `class=\"my-animation ng-animate className\"` |\r\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\"` |\r\n * | 7. `$animate` applies the provided collection of `from` CSS styles to the element | `class=\"my-animation ng-animate className\"` |\r\n * | 8. `$animate` waits for a single animation frame (this performs a reflow) | `class=\"my-animation ng-animate className\"` |\r\n * | 9. `$animate` removes the CSS transition block placed on the element | `class=\"my-animation ng-animate className\"` |\r\n * | 10. the `className-active` class is added (this triggers the CSS transition/animation) | `class=\"my-animation ng-animate className className-active\"` |\r\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\"` |\r\n * | 12. `$animate` waits for the animation to complete (via events and timeout) | `class=\"my-animation ng-animate className className-active\"` |\r\n * | 13. The animation ends and all generated CSS classes are removed from the element | `class=\"my-animation\"` |\r\n * | 14. The returned promise is resolved. | `class=\"my-animation\"` |\r\n *\r\n * @param {DOMElement} element the element that will be the focus of the enter animation\r\n * @param {object} from a collection of CSS styles that will be applied to the element at the start of the animation\r\n * @param {object} to a collection of CSS styles that the element will animate towards\r\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`)\r\n * @param {object=} options an optional collection of options that will be picked up by the CSS transition/animation\r\n * @return {Promise} the animation callback promise\r\n */\r\n animate: function(element, from, to, className, options) {\r\n className = className || 'ng-inline-animate';\r\n options = parseAnimateOptions(options) || {};\r\n options.from = to ? from : null;\r\n options.to = to ? to : from;\r\n\r\n return runAnimationPostDigest(function(done) {\r\n return performAnimation('animate', className, stripCommentsFromElement(element), null, null, noop, options, done);\r\n });\r\n },\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $animate#enter\r\n * @kind function\r\n *\r\n * @description\r\n * Appends the element to the parentElement element that resides in the document and then runs the enter animation. Once\r\n * the animation is started, the following CSS classes will be present on the element for the duration of the animation:\r\n *\r\n * Below is a breakdown of each step that occurs during enter animation:\r\n *\r\n * | Animation Step | What the element class attribute looks like |\r\n * |-----------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------|\r\n * | 1. `$animate.enter(...)` is called | `class=\"my-animation\"` |\r\n * | 2. element is inserted into the `parentElement` element or beside the `afterElement` element | `class=\"my-animation\"` |\r\n * | 3. `$animate` waits for the next digest to start the animation | `class=\"my-animation ng-animate\"` |\r\n * | 4. `$animate` runs the JavaScript-defined animations detected on the element | `class=\"my-animation ng-animate\"` |\r\n * | 5. the `.ng-enter` class is added to the element | `class=\"my-animation ng-animate ng-enter\"` |\r\n * | 6. `$animate` scans the element styles to get the CSS transition/animation duration and delay | `class=\"my-animation ng-animate ng-enter\"` |\r\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\"` |\r\n * | 8. `$animate` waits for a single animation frame (this performs a reflow) | `class=\"my-animation ng-animate ng-enter\"` |\r\n * | 9. `$animate` removes the CSS transition block placed on the element | `class=\"my-animation ng-animate ng-enter\"` |\r\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\"` |\r\n * | 11. `$animate` waits for the animation to complete (via events and timeout) | `class=\"my-animation ng-animate ng-enter ng-enter-active\"` |\r\n * | 12. The animation ends and all generated CSS classes are removed from the element | `class=\"my-animation\"` |\r\n * | 13. The returned promise is resolved. | `class=\"my-animation\"` |\r\n *\r\n * @param {DOMElement} element the element that will be the focus of the enter animation\r\n * @param {DOMElement} parentElement the parent element of the element that will be the focus of the enter animation\r\n * @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the enter animation\r\n * @param {object=} options an optional collection of options that will be picked up by the CSS transition/animation\r\n * @return {Promise} the animation callback promise\r\n */\r\n enter: function(element, parentElement, afterElement, options) {\r\n options = parseAnimateOptions(options);\r\n element = angular.element(element);\r\n parentElement = prepareElement(parentElement);\r\n afterElement = prepareElement(afterElement);\r\n\r\n classBasedAnimationsBlocked(element, true);\r\n $delegate.enter(element, parentElement, afterElement);\r\n return runAnimationPostDigest(function(done) {\r\n return performAnimation('enter', 'ng-enter', stripCommentsFromElement(element), parentElement, afterElement, noop, options, done);\r\n });\r\n },\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $animate#leave\r\n * @kind function\r\n *\r\n * @description\r\n * Runs the leave animation operation and, upon completion, removes the element from the DOM. Once\r\n * the animation is started, the following CSS classes will be added for the duration of the animation:\r\n *\r\n * Below is a breakdown of each step that occurs during leave animation:\r\n *\r\n * | Animation Step | What the element class attribute looks like |\r\n * |-----------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------|\r\n * | 1. `$animate.leave(...)` is called | `class=\"my-animation\"` |\r\n * | 2. `$animate` runs the JavaScript-defined animations detected on the element | `class=\"my-animation ng-animate\"` |\r\n * | 3. `$animate` waits for the next digest to start the animation | `class=\"my-animation ng-animate\"` |\r\n * | 4. the `.ng-leave` class is added to the element | `class=\"my-animation ng-animate ng-leave\"` |\r\n * | 5. `$animate` scans the element styles to get the CSS transition/animation duration and delay | `class=\"my-animation ng-animate ng-leave\"` |\r\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\"` |\r\n * | 7. `$animate` waits for a single animation frame (this performs a reflow) | `class=\"my-animation ng-animate ng-leave\"` |\r\n * | 8. `$animate` removes the CSS transition block placed on the element | `class=\"my-animation ng-animate ng-leave\"` |\r\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\"` |\r\n * | 10. `$animate` waits for the animation to complete (via events and timeout) | `class=\"my-animation ng-animate ng-leave ng-leave-active\"` |\r\n * | 11. The animation ends and all generated CSS classes are removed from the element | `class=\"my-animation\"` |\r\n * | 12. The element is removed from the DOM | ... |\r\n * | 13. The returned promise is resolved. | ... |\r\n *\r\n * @param {DOMElement} element the element that will be the focus of the leave animation\r\n * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation\r\n * @return {Promise} the animation callback promise\r\n */\r\n leave: function(element, options) {\r\n options = parseAnimateOptions(options);\r\n element = angular.element(element);\r\n\r\n cancelChildAnimations(element);\r\n classBasedAnimationsBlocked(element, true);\r\n return runAnimationPostDigest(function(done) {\r\n return performAnimation('leave', 'ng-leave', stripCommentsFromElement(element), null, null, function() {\r\n $delegate.leave(element);\r\n }, options, done);\r\n });\r\n },\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $animate#move\r\n * @kind function\r\n *\r\n * @description\r\n * Fires the move DOM operation. Just before the animation starts, the animate service will either append it into the parentElement container or\r\n * add the element directly after the afterElement element if present. Then the move animation will be run. Once\r\n * the animation is started, the following CSS classes will be added for the duration of the animation:\r\n *\r\n * Below is a breakdown of each step that occurs during move animation:\r\n *\r\n * | Animation Step | What the element class attribute looks like |\r\n * |----------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------|\r\n * | 1. `$animate.move(...)` is called | `class=\"my-animation\"` |\r\n * | 2. element is moved into the parentElement element or beside the afterElement element | `class=\"my-animation\"` |\r\n * | 3. `$animate` waits for the next digest to start the animation | `class=\"my-animation ng-animate\"` |\r\n * | 4. `$animate` runs the JavaScript-defined animations detected on the element | `class=\"my-animation ng-animate\"` |\r\n * | 5. the `.ng-move` class is added to the element | `class=\"my-animation ng-animate ng-move\"` |\r\n * | 6. `$animate` scans the element styles to get the CSS transition/animation duration and delay | `class=\"my-animation ng-animate ng-move\"` |\r\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\"` |\r\n * | 8. `$animate` waits for a single animation frame (this performs a reflow) | `class=\"my-animation ng-animate ng-move\"` |\r\n * | 9. `$animate` removes the CSS transition block placed on the element | `class=\"my-animation ng-animate ng-move\"` |\r\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\"` |\r\n * | 11. `$animate` waits for the animation to complete (via events and timeout) | `class=\"my-animation ng-animate ng-move ng-move-active\"` |\r\n * | 12. The animation ends and all generated CSS classes are removed from the element | `class=\"my-animation\"` |\r\n * | 13. The returned promise is resolved. | `class=\"my-animation\"` |\r\n *\r\n * @param {DOMElement} element the element that will be the focus of the move animation\r\n * @param {DOMElement} parentElement the parentElement element of the element that will be the focus of the move animation\r\n * @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the move animation\r\n * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation\r\n * @return {Promise} the animation callback promise\r\n */\r\n move: function(element, parentElement, afterElement, options) {\r\n options = parseAnimateOptions(options);\r\n element = angular.element(element);\r\n parentElement = prepareElement(parentElement);\r\n afterElement = prepareElement(afterElement);\r\n\r\n cancelChildAnimations(element);\r\n classBasedAnimationsBlocked(element, true);\r\n $delegate.move(element, parentElement, afterElement);\r\n return runAnimationPostDigest(function(done) {\r\n return performAnimation('move', 'ng-move', stripCommentsFromElement(element), parentElement, afterElement, noop, options, done);\r\n });\r\n },\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $animate#addClass\r\n *\r\n * @description\r\n * Triggers a custom animation event based off the className variable and then attaches the className value to the element as a CSS class.\r\n * Unlike the other animation methods, the animate service will suffix the className value with {@type -add} in order to provide\r\n * the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if no CSS transitions\r\n * or keyframes are defined on the -add-active or base CSS class).\r\n *\r\n * Below is a breakdown of each step that occurs during addClass animation:\r\n *\r\n * | Animation Step | What the element class attribute looks like |\r\n * |--------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------|\r\n * | 1. `$animate.addClass(element, 'super')` is called | `class=\"my-animation\"` |\r\n * | 2. `$animate` runs the JavaScript-defined animations detected on the element | `class=\"my-animation ng-animate\"` |\r\n * | 3. the `.super-add` class is added to the element | `class=\"my-animation ng-animate super-add\"` |\r\n * | 4. `$animate` waits for a single animation frame (this performs a reflow) | `class=\"my-animation ng-animate super-add\"` |\r\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\"` |\r\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\"` |\r\n * | 7. `$animate` waits for the animation to complete (via events and timeout) | `class=\"my-animation ng-animate super super-add super-add-active\"` |\r\n * | 8. The animation ends and all generated CSS classes are removed from the element | `class=\"my-animation super\"` |\r\n * | 9. The super class is kept on the element | `class=\"my-animation super\"` |\r\n * | 10. The returned promise is resolved. | `class=\"my-animation super\"` |\r\n *\r\n * @param {DOMElement} element the element that will be animated\r\n * @param {string} className the CSS class that will be added to the element and then animated\r\n * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation\r\n * @return {Promise} the animation callback promise\r\n */\r\n addClass: function(element, className, options) {\r\n return this.setClass(element, className, [], options);\r\n },\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $animate#removeClass\r\n *\r\n * @description\r\n * Triggers a custom animation event based off the className variable and then removes the CSS class provided by the className value\r\n * from the element. Unlike the other animation methods, the animate service will suffix the className value with {@type -remove} in\r\n * order to provide the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if\r\n * no CSS transitions or keyframes are defined on the -remove or base CSS classes).\r\n *\r\n * Below is a breakdown of each step that occurs during removeClass animation:\r\n *\r\n * | Animation Step | What the element class attribute looks like |\r\n * |----------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------|\r\n * | 1. `$animate.removeClass(element, 'super')` is called | `class=\"my-animation super\"` |\r\n * | 2. `$animate` runs the JavaScript-defined animations detected on the element | `class=\"my-animation super ng-animate\"` |\r\n * | 3. the `.super-remove` class is added to the element | `class=\"my-animation super ng-animate super-remove\"` |\r\n * | 4. `$animate` waits for a single animation frame (this performs a reflow) | `class=\"my-animation super ng-animate super-remove\"` |\r\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\"` |\r\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\"` |\r\n * | 7. `$animate` waits for the animation to complete (via events and timeout) | `class=\"my-animation ng-animate super-remove super-remove-active\"` |\r\n * | 8. The animation ends and all generated CSS classes are removed from the element | `class=\"my-animation\"` |\r\n * | 9. The returned promise is resolved. | `class=\"my-animation\"` |\r\n *\r\n *\r\n * @param {DOMElement} element the element that will be animated\r\n * @param {string} className the CSS class that will be animated and then removed from the element\r\n * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation\r\n * @return {Promise} the animation callback promise\r\n */\r\n removeClass: function(element, className, options) {\r\n return this.setClass(element, [], className, options);\r\n },\r\n\r\n /**\r\n *\r\n * @ngdoc method\r\n * @name $animate#setClass\r\n *\r\n * @description Adds and/or removes the given CSS classes to and from the element.\r\n * Once complete, the `done()` callback will be fired (if provided).\r\n *\r\n * | Animation Step | What the element class attribute looks like |\r\n * |----------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------|\r\n * | 1. `$animate.setClass(element, 'on', 'off')` is called | `class=\"my-animation off\"` |\r\n * | 2. `$animate` runs the JavaScript-defined animations detected on the element | `class=\"my-animation ng-animate off\"` |\r\n * | 3. the `.on-add` and `.off-remove` classes are added to the element | `class=\"my-animation ng-animate on-add off-remove off\"` |\r\n * | 4. `$animate` waits for a single animation frame (this performs a reflow) | `class=\"my-animation ng-animate on-add off-remove off\"` |\r\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\"` |\r\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\"` |\r\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\"` |\r\n * | 8. The animation ends and all generated CSS classes are removed from the element | `class=\"my-animation on\"` |\r\n * | 9. The returned promise is resolved. | `class=\"my-animation on\"` |\r\n *\r\n * @param {DOMElement} element the element which will have its CSS classes changed\r\n * removed from it\r\n * @param {string} add the CSS classes which will be added to the element\r\n * @param {string} remove the CSS class which will be removed from the element\r\n * CSS classes have been set on the element\r\n * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation\r\n * @return {Promise} the animation callback promise\r\n */\r\n setClass: function(element, add, remove, options) {\r\n options = parseAnimateOptions(options);\r\n\r\n var STORAGE_KEY = '$$animateClasses';\r\n element = angular.element(element);\r\n element = stripCommentsFromElement(element);\r\n\r\n if (classBasedAnimationsBlocked(element)) {\r\n return $delegate.$$setClassImmediately(element, add, remove, options);\r\n }\r\n\r\n // we're using a combined array for both the add and remove\r\n // operations since the ORDER OF addClass and removeClass matters\r\n var classes, cache = element.data(STORAGE_KEY);\r\n var hasCache = !!cache;\r\n if (!cache) {\r\n cache = {};\r\n cache.classes = {};\r\n }\r\n classes = cache.classes;\r\n\r\n add = isArray(add) ? add : add.split(' ');\r\n forEach(add, function(c) {\r\n if (c && c.length) {\r\n classes[c] = true;\r\n }\r\n });\r\n\r\n remove = isArray(remove) ? remove : remove.split(' ');\r\n forEach(remove, function(c) {\r\n if (c && c.length) {\r\n classes[c] = false;\r\n }\r\n });\r\n\r\n if (hasCache) {\r\n if (options && cache.options) {\r\n cache.options = angular.extend(cache.options || {}, options);\r\n }\r\n\r\n //the digest cycle will combine all the animations into one function\r\n return cache.promise;\r\n } else {\r\n element.data(STORAGE_KEY, cache = {\r\n classes: classes,\r\n options: options\r\n });\r\n }\r\n\r\n return cache.promise = runAnimationPostDigest(function(done) {\r\n var cache, parentNode, parentElement, elementNode = extractElementNode(element);\r\n if (elementNode) {\r\n cache = element.data(STORAGE_KEY);\r\n element.removeData(STORAGE_KEY);\r\n\r\n parentElement = element.parent();\r\n parentNode = elementNode.parentNode;\r\n }\r\n\r\n // TODO(matsko): move this code into the animationsDisabled() function once #8092 is fixed\r\n if (!parentNode || parentNode['$$NG_REMOVED'] || elementNode['$$NG_REMOVED']) {\r\n done();\r\n return;\r\n }\r\n\r\n var state = element.data(NG_ANIMATE_STATE) || {};\r\n var classes = resolveElementClasses(element, cache, state.active);\r\n return !classes\r\n ? done()\r\n : performAnimation('setClass', classes, element, parentElement, null, function() {\r\n if (classes[0]) $delegate.$$addClassImmediately(element, classes[0]);\r\n if (classes[1]) $delegate.$$removeClassImmediately(element, classes[1]);\r\n }, cache.options, done);\r\n });\r\n },\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $animate#cancel\r\n * @kind function\r\n *\r\n * @param {Promise} animationPromise The animation promise that is returned when an animation is started.\r\n *\r\n * @description\r\n * Cancels the provided animation.\r\n */\r\n cancel: function(promise) {\r\n promise.$$cancelFn();\r\n },\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $animate#enabled\r\n * @kind function\r\n *\r\n * @param {boolean=} value If provided then set the animation on or off.\r\n * @param {DOMElement=} element If provided then the element will be used to represent the enable/disable operation\r\n * @return {boolean} Current animation state.\r\n *\r\n * @description\r\n * Globally enables/disables animations.\r\n *\r\n */\r\n enabled: function(value, element) {\r\n switch (arguments.length) {\r\n case 2:\r\n if (value) {\r\n cleanup(element);\r\n } else {\r\n var data = element.data(NG_ANIMATE_STATE) || {};\r\n data.disabled = true;\r\n element.data(NG_ANIMATE_STATE, data);\r\n }\r\n break;\r\n\r\n case 1:\r\n rootAnimateState.disabled = !value;\r\n break;\r\n\r\n default:\r\n value = !rootAnimateState.disabled;\r\n break;\r\n }\r\n return !!value;\r\n }\r\n };\r\n\r\n /*\r\n all animations call this shared animation triggering function internally.\r\n The animationEvent variable refers to the JavaScript animation event that will be triggered\r\n and the className value is the name of the animation that will be applied within the\r\n CSS code. Element, `parentElement` and `afterElement` are provided DOM elements for the animation\r\n and the onComplete callback will be fired once the animation is fully complete.\r\n */\r\n function performAnimation(animationEvent, className, element, parentElement, afterElement, domOperation, options, doneCallback) {\r\n var noopCancel = noop;\r\n var runner = animationRunner(element, animationEvent, className, options);\r\n if (!runner) {\r\n fireDOMOperation();\r\n fireBeforeCallbackAsync();\r\n fireAfterCallbackAsync();\r\n closeAnimation();\r\n return noopCancel;\r\n }\r\n\r\n animationEvent = runner.event;\r\n className = runner.className;\r\n var elementEvents = angular.element._data(runner.node);\r\n elementEvents = elementEvents && elementEvents.events;\r\n\r\n if (!parentElement) {\r\n parentElement = afterElement ? afterElement.parent() : element.parent();\r\n }\r\n\r\n //skip the animation if animations are disabled, a parent is already being animated,\r\n //the element is not currently attached to the document body or then completely close\r\n //the animation if any matching animations are not found at all.\r\n //NOTE: IE8 + IE9 should close properly (run closeAnimation()) in case an animation was found.\r\n if (animationsDisabled(element, parentElement)) {\r\n fireDOMOperation();\r\n fireBeforeCallbackAsync();\r\n fireAfterCallbackAsync();\r\n closeAnimation();\r\n return noopCancel;\r\n }\r\n\r\n var ngAnimateState = element.data(NG_ANIMATE_STATE) || {};\r\n var runningAnimations = ngAnimateState.active || {};\r\n var totalActiveAnimations = ngAnimateState.totalActive || 0;\r\n var lastAnimation = ngAnimateState.last;\r\n var skipAnimation = false;\r\n\r\n if (totalActiveAnimations > 0) {\r\n var animationsToCancel = [];\r\n if (!runner.isClassBased) {\r\n if (animationEvent == 'leave' && runningAnimations['ng-leave']) {\r\n skipAnimation = true;\r\n } else {\r\n //cancel all animations when a structural animation takes place\r\n for (var klass in runningAnimations) {\r\n animationsToCancel.push(runningAnimations[klass]);\r\n }\r\n ngAnimateState = {};\r\n cleanup(element, true);\r\n }\r\n } else if (lastAnimation.event == 'setClass') {\r\n animationsToCancel.push(lastAnimation);\r\n cleanup(element, className);\r\n } else if (runningAnimations[className]) {\r\n var current = runningAnimations[className];\r\n if (current.event == animationEvent) {\r\n skipAnimation = true;\r\n } else {\r\n animationsToCancel.push(current);\r\n cleanup(element, className);\r\n }\r\n }\r\n\r\n if (animationsToCancel.length > 0) {\r\n forEach(animationsToCancel, function(operation) {\r\n operation.cancel();\r\n });\r\n }\r\n }\r\n\r\n if (runner.isClassBased\r\n && !runner.isSetClassOperation\r\n && animationEvent != 'animate'\r\n && !skipAnimation) {\r\n skipAnimation = (animationEvent == 'addClass') == element.hasClass(className); //opposite of XOR\r\n }\r\n\r\n if (skipAnimation) {\r\n fireDOMOperation();\r\n fireBeforeCallbackAsync();\r\n fireAfterCallbackAsync();\r\n fireDoneCallbackAsync();\r\n return noopCancel;\r\n }\r\n\r\n runningAnimations = ngAnimateState.active || {};\r\n totalActiveAnimations = ngAnimateState.totalActive || 0;\r\n\r\n if (animationEvent == 'leave') {\r\n //there's no need to ever remove the listener since the element\r\n //will be removed (destroyed) after the leave animation ends or\r\n //is cancelled midway\r\n element.one('$destroy', function(e) {\r\n var element = angular.element(this);\r\n var state = element.data(NG_ANIMATE_STATE);\r\n if (state) {\r\n var activeLeaveAnimation = state.active['ng-leave'];\r\n if (activeLeaveAnimation) {\r\n activeLeaveAnimation.cancel();\r\n cleanup(element, 'ng-leave');\r\n }\r\n }\r\n });\r\n }\r\n\r\n //the ng-animate class does nothing, but it's here to allow for\r\n //parent animations to find and cancel child animations when needed\r\n $$jqLite.addClass(element, NG_ANIMATE_CLASS_NAME);\r\n if (options && options.tempClasses) {\r\n forEach(options.tempClasses, function(className) {\r\n $$jqLite.addClass(element, className);\r\n });\r\n }\r\n\r\n var localAnimationCount = globalAnimationCounter++;\r\n totalActiveAnimations++;\r\n runningAnimations[className] = runner;\r\n\r\n element.data(NG_ANIMATE_STATE, {\r\n last: runner,\r\n active: runningAnimations,\r\n index: localAnimationCount,\r\n totalActive: totalActiveAnimations\r\n });\r\n\r\n //first we run the before animations and when all of those are complete\r\n //then we perform the DOM operation and run the next set of animations\r\n fireBeforeCallbackAsync();\r\n runner.before(function(cancelled) {\r\n var data = element.data(NG_ANIMATE_STATE);\r\n cancelled = cancelled ||\r\n !data || !data.active[className] ||\r\n (runner.isClassBased && data.active[className].event != animationEvent);\r\n\r\n fireDOMOperation();\r\n if (cancelled === true) {\r\n closeAnimation();\r\n } else {\r\n fireAfterCallbackAsync();\r\n runner.after(closeAnimation);\r\n }\r\n });\r\n\r\n return runner.cancel;\r\n\r\n function fireDOMCallback(animationPhase) {\r\n var eventName = '$animate:' + animationPhase;\r\n if (elementEvents && elementEvents[eventName] && elementEvents[eventName].length > 0) {\r\n $$asyncCallback(function() {\r\n element.triggerHandler(eventName, {\r\n event: animationEvent,\r\n className: className\r\n });\r\n });\r\n }\r\n }\r\n\r\n function fireBeforeCallbackAsync() {\r\n fireDOMCallback('before');\r\n }\r\n\r\n function fireAfterCallbackAsync() {\r\n fireDOMCallback('after');\r\n }\r\n\r\n function fireDoneCallbackAsync() {\r\n fireDOMCallback('close');\r\n doneCallback();\r\n }\r\n\r\n //it is less complicated to use a flag than managing and canceling\r\n //timeouts containing multiple callbacks.\r\n function fireDOMOperation() {\r\n if (!fireDOMOperation.hasBeenRun) {\r\n fireDOMOperation.hasBeenRun = true;\r\n domOperation();\r\n }\r\n }\r\n\r\n function closeAnimation() {\r\n if (!closeAnimation.hasBeenRun) {\r\n if (runner) { //the runner doesn't exist if it fails to instantiate\r\n runner.applyStyles();\r\n }\r\n\r\n closeAnimation.hasBeenRun = true;\r\n if (options && options.tempClasses) {\r\n forEach(options.tempClasses, function(className) {\r\n $$jqLite.removeClass(element, className);\r\n });\r\n }\r\n\r\n var data = element.data(NG_ANIMATE_STATE);\r\n if (data) {\r\n\r\n /* only structural animations wait for reflow before removing an\r\n animation, but class-based animations don't. An example of this\r\n failing would be when a parent HTML tag has a ng-class attribute\r\n causing ALL directives below to skip animations during the digest */\r\n if (runner && runner.isClassBased) {\r\n cleanup(element, className);\r\n } else {\r\n $$asyncCallback(function() {\r\n var data = element.data(NG_ANIMATE_STATE) || {};\r\n if (localAnimationCount == data.index) {\r\n cleanup(element, className, animationEvent);\r\n }\r\n });\r\n element.data(NG_ANIMATE_STATE, data);\r\n }\r\n }\r\n fireDoneCallbackAsync();\r\n }\r\n }\r\n }\r\n\r\n function cancelChildAnimations(element) {\r\n var node = extractElementNode(element);\r\n if (node) {\r\n var nodes = angular.isFunction(node.getElementsByClassName) ?\r\n node.getElementsByClassName(NG_ANIMATE_CLASS_NAME) :\r\n node.querySelectorAll('.' + NG_ANIMATE_CLASS_NAME);\r\n forEach(nodes, function(element) {\r\n element = angular.element(element);\r\n var data = element.data(NG_ANIMATE_STATE);\r\n if (data && data.active) {\r\n forEach(data.active, function(runner) {\r\n runner.cancel();\r\n });\r\n }\r\n });\r\n }\r\n }\r\n\r\n function cleanup(element, className) {\r\n if (isMatchingElement(element, $rootElement)) {\r\n if (!rootAnimateState.disabled) {\r\n rootAnimateState.running = false;\r\n rootAnimateState.structural = false;\r\n }\r\n } else if (className) {\r\n var data = element.data(NG_ANIMATE_STATE) || {};\r\n\r\n var removeAnimations = className === true;\r\n if (!removeAnimations && data.active && data.active[className]) {\r\n data.totalActive--;\r\n delete data.active[className];\r\n }\r\n\r\n if (removeAnimations || !data.totalActive) {\r\n $$jqLite.removeClass(element, NG_ANIMATE_CLASS_NAME);\r\n element.removeData(NG_ANIMATE_STATE);\r\n }\r\n }\r\n }\r\n\r\n function animationsDisabled(element, parentElement) {\r\n if (rootAnimateState.disabled) {\r\n return true;\r\n }\r\n\r\n if (isMatchingElement(element, $rootElement)) {\r\n return rootAnimateState.running;\r\n }\r\n\r\n var allowChildAnimations, parentRunningAnimation, hasParent;\r\n do {\r\n //the element did not reach the root element which means that it\r\n //is not apart of the DOM. Therefore there is no reason to do\r\n //any animations on it\r\n if (parentElement.length === 0) break;\r\n\r\n var isRoot = isMatchingElement(parentElement, $rootElement);\r\n var state = isRoot ? rootAnimateState : (parentElement.data(NG_ANIMATE_STATE) || {});\r\n if (state.disabled) {\r\n return true;\r\n }\r\n\r\n //no matter what, for an animation to work it must reach the root element\r\n //this implies that the element is attached to the DOM when the animation is run\r\n if (isRoot) {\r\n hasParent = true;\r\n }\r\n\r\n //once a flag is found that is strictly false then everything before\r\n //it will be discarded and all child animations will be restricted\r\n if (allowChildAnimations !== false) {\r\n var animateChildrenFlag = parentElement.data(NG_ANIMATE_CHILDREN);\r\n if (angular.isDefined(animateChildrenFlag)) {\r\n allowChildAnimations = animateChildrenFlag;\r\n }\r\n }\r\n\r\n parentRunningAnimation = parentRunningAnimation ||\r\n state.running ||\r\n (state.last && !state.last.isClassBased);\r\n }\r\n while (parentElement = parentElement.parent());\r\n\r\n return !hasParent || (!allowChildAnimations && parentRunningAnimation);\r\n }\r\n }]);\r\n\r\n $animateProvider.register('', ['$window', '$sniffer', '$timeout', '$$animateReflow',\r\n function($window, $sniffer, $timeout, $$animateReflow) {\r\n // Detect proper transitionend/animationend event names.\r\n var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT;\r\n\r\n // If unprefixed events are not supported but webkit-prefixed are, use the latter.\r\n // Otherwise, just use W3C names, browsers not supporting them at all will just ignore them.\r\n // Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend`\r\n // but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`.\r\n // Register both events in case `window.onanimationend` is not supported because of that,\r\n // do the same for `transitionend` as Safari is likely to exhibit similar behavior.\r\n // Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit\r\n // therefore there is no reason to test anymore for other vendor prefixes: http://caniuse.com/#search=transition\r\n if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined) {\r\n CSS_PREFIX = '-webkit-';\r\n TRANSITION_PROP = 'WebkitTransition';\r\n TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend';\r\n } else {\r\n TRANSITION_PROP = 'transition';\r\n TRANSITIONEND_EVENT = 'transitionend';\r\n }\r\n\r\n if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined) {\r\n CSS_PREFIX = '-webkit-';\r\n ANIMATION_PROP = 'WebkitAnimation';\r\n ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend';\r\n } else {\r\n ANIMATION_PROP = 'animation';\r\n ANIMATIONEND_EVENT = 'animationend';\r\n }\r\n\r\n var DURATION_KEY = 'Duration';\r\n var PROPERTY_KEY = 'Property';\r\n var DELAY_KEY = 'Delay';\r\n var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount';\r\n var ANIMATION_PLAYSTATE_KEY = 'PlayState';\r\n var NG_ANIMATE_PARENT_KEY = '$$ngAnimateKey';\r\n var NG_ANIMATE_CSS_DATA_KEY = '$$ngAnimateCSS3Data';\r\n var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3;\r\n var CLOSING_TIME_BUFFER = 1.5;\r\n var ONE_SECOND = 1000;\r\n\r\n var lookupCache = {};\r\n var parentCounter = 0;\r\n var animationReflowQueue = [];\r\n var cancelAnimationReflow;\r\n function clearCacheAfterReflow() {\r\n if (!cancelAnimationReflow) {\r\n cancelAnimationReflow = $$animateReflow(function() {\r\n animationReflowQueue = [];\r\n cancelAnimationReflow = null;\r\n lookupCache = {};\r\n });\r\n }\r\n }\r\n\r\n function afterReflow(element, callback) {\r\n if (cancelAnimationReflow) {\r\n cancelAnimationReflow();\r\n }\r\n animationReflowQueue.push(callback);\r\n cancelAnimationReflow = $$animateReflow(function() {\r\n forEach(animationReflowQueue, function(fn) {\r\n fn();\r\n });\r\n\r\n animationReflowQueue = [];\r\n cancelAnimationReflow = null;\r\n lookupCache = {};\r\n });\r\n }\r\n\r\n var closingTimer = null;\r\n var closingTimestamp = 0;\r\n var animationElementQueue = [];\r\n function animationCloseHandler(element, totalTime) {\r\n var node = extractElementNode(element);\r\n element = angular.element(node);\r\n\r\n //this item will be garbage collected by the closing\r\n //animation timeout\r\n animationElementQueue.push(element);\r\n\r\n //but it may not need to cancel out the existing timeout\r\n //if the timestamp is less than the previous one\r\n var futureTimestamp = Date.now() + totalTime;\r\n if (futureTimestamp <= closingTimestamp) {\r\n return;\r\n }\r\n\r\n $timeout.cancel(closingTimer);\r\n\r\n closingTimestamp = futureTimestamp;\r\n closingTimer = $timeout(function() {\r\n closeAllAnimations(animationElementQueue);\r\n animationElementQueue = [];\r\n }, totalTime, false);\r\n }\r\n\r\n function closeAllAnimations(elements) {\r\n forEach(elements, function(element) {\r\n var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY);\r\n if (elementData) {\r\n forEach(elementData.closeAnimationFns, function(fn) {\r\n fn();\r\n });\r\n }\r\n });\r\n }\r\n\r\n function getElementAnimationDetails(element, cacheKey) {\r\n var data = cacheKey ? lookupCache[cacheKey] : null;\r\n if (!data) {\r\n var transitionDuration = 0;\r\n var transitionDelay = 0;\r\n var animationDuration = 0;\r\n var animationDelay = 0;\r\n\r\n //we want all the styles defined before and after\r\n forEach(element, function(element) {\r\n if (element.nodeType == ELEMENT_NODE) {\r\n var elementStyles = $window.getComputedStyle(element) || {};\r\n\r\n var transitionDurationStyle = elementStyles[TRANSITION_PROP + DURATION_KEY];\r\n transitionDuration = Math.max(parseMaxTime(transitionDurationStyle), transitionDuration);\r\n\r\n var transitionDelayStyle = elementStyles[TRANSITION_PROP + DELAY_KEY];\r\n transitionDelay = Math.max(parseMaxTime(transitionDelayStyle), transitionDelay);\r\n\r\n var animationDelayStyle = elementStyles[ANIMATION_PROP + DELAY_KEY];\r\n animationDelay = Math.max(parseMaxTime(elementStyles[ANIMATION_PROP + DELAY_KEY]), animationDelay);\r\n\r\n var aDuration = parseMaxTime(elementStyles[ANIMATION_PROP + DURATION_KEY]);\r\n\r\n if (aDuration > 0) {\r\n aDuration *= parseInt(elementStyles[ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY], 10) || 1;\r\n }\r\n animationDuration = Math.max(aDuration, animationDuration);\r\n }\r\n });\r\n data = {\r\n total: 0,\r\n transitionDelay: transitionDelay,\r\n transitionDuration: transitionDuration,\r\n animationDelay: animationDelay,\r\n animationDuration: animationDuration\r\n };\r\n if (cacheKey) {\r\n lookupCache[cacheKey] = data;\r\n }\r\n }\r\n return data;\r\n }\r\n\r\n function parseMaxTime(str) {\r\n var maxValue = 0;\r\n var values = isString(str) ?\r\n str.split(/\\s*,\\s*/) :\r\n [];\r\n forEach(values, function(value) {\r\n maxValue = Math.max(parseFloat(value) || 0, maxValue);\r\n });\r\n return maxValue;\r\n }\r\n\r\n function getCacheKey(element) {\r\n var parentElement = element.parent();\r\n var parentID = parentElement.data(NG_ANIMATE_PARENT_KEY);\r\n if (!parentID) {\r\n parentElement.data(NG_ANIMATE_PARENT_KEY, ++parentCounter);\r\n parentID = parentCounter;\r\n }\r\n return parentID + '-' + extractElementNode(element).getAttribute('class');\r\n }\r\n\r\n function animateSetup(animationEvent, element, className, styles) {\r\n var structural = ['ng-enter','ng-leave','ng-move'].indexOf(className) >= 0;\r\n\r\n var cacheKey = getCacheKey(element);\r\n var eventCacheKey = cacheKey + ' ' + className;\r\n var itemIndex = lookupCache[eventCacheKey] ? ++lookupCache[eventCacheKey].total : 0;\r\n\r\n var stagger = {};\r\n if (itemIndex > 0) {\r\n var staggerClassName = className + '-stagger';\r\n var staggerCacheKey = cacheKey + ' ' + staggerClassName;\r\n var applyClasses = !lookupCache[staggerCacheKey];\r\n\r\n applyClasses && $$jqLite.addClass(element, staggerClassName);\r\n\r\n stagger = getElementAnimationDetails(element, staggerCacheKey);\r\n\r\n applyClasses && $$jqLite.removeClass(element, staggerClassName);\r\n }\r\n\r\n $$jqLite.addClass(element, className);\r\n\r\n var formerData = element.data(NG_ANIMATE_CSS_DATA_KEY) || {};\r\n var timings = getElementAnimationDetails(element, eventCacheKey);\r\n var transitionDuration = timings.transitionDuration;\r\n var animationDuration = timings.animationDuration;\r\n\r\n if (structural && transitionDuration === 0 && animationDuration === 0) {\r\n $$jqLite.removeClass(element, className);\r\n return false;\r\n }\r\n\r\n var blockTransition = styles || (structural && transitionDuration > 0);\r\n var blockAnimation = animationDuration > 0 &&\r\n stagger.animationDelay > 0 &&\r\n stagger.animationDuration === 0;\r\n\r\n var closeAnimationFns = formerData.closeAnimationFns || [];\r\n element.data(NG_ANIMATE_CSS_DATA_KEY, {\r\n stagger: stagger,\r\n cacheKey: eventCacheKey,\r\n running: formerData.running || 0,\r\n itemIndex: itemIndex,\r\n blockTransition: blockTransition,\r\n closeAnimationFns: closeAnimationFns\r\n });\r\n\r\n var node = extractElementNode(element);\r\n\r\n if (blockTransition) {\r\n blockTransitions(node, true);\r\n if (styles) {\r\n element.css(styles);\r\n }\r\n }\r\n\r\n if (blockAnimation) {\r\n blockAnimations(node, true);\r\n }\r\n\r\n return true;\r\n }\r\n\r\n function animateRun(animationEvent, element, className, activeAnimationComplete, styles) {\r\n var node = extractElementNode(element);\r\n var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY);\r\n if (node.getAttribute('class').indexOf(className) == -1 || !elementData) {\r\n activeAnimationComplete();\r\n return;\r\n }\r\n\r\n var activeClassName = '';\r\n var pendingClassName = '';\r\n forEach(className.split(' '), function(klass, i) {\r\n var prefix = (i > 0 ? ' ' : '') + klass;\r\n activeClassName += prefix + '-active';\r\n pendingClassName += prefix + '-pending';\r\n });\r\n\r\n var style = '';\r\n var appliedStyles = [];\r\n var itemIndex = elementData.itemIndex;\r\n var stagger = elementData.stagger;\r\n var staggerTime = 0;\r\n if (itemIndex > 0) {\r\n var transitionStaggerDelay = 0;\r\n if (stagger.transitionDelay > 0 && stagger.transitionDuration === 0) {\r\n transitionStaggerDelay = stagger.transitionDelay * itemIndex;\r\n }\r\n\r\n var animationStaggerDelay = 0;\r\n if (stagger.animationDelay > 0 && stagger.animationDuration === 0) {\r\n animationStaggerDelay = stagger.animationDelay * itemIndex;\r\n appliedStyles.push(CSS_PREFIX + 'animation-play-state');\r\n }\r\n\r\n staggerTime = Math.round(Math.max(transitionStaggerDelay, animationStaggerDelay) * 100) / 100;\r\n }\r\n\r\n if (!staggerTime) {\r\n $$jqLite.addClass(element, activeClassName);\r\n if (elementData.blockTransition) {\r\n blockTransitions(node, false);\r\n }\r\n }\r\n\r\n var eventCacheKey = elementData.cacheKey + ' ' + activeClassName;\r\n var timings = getElementAnimationDetails(element, eventCacheKey);\r\n var maxDuration = Math.max(timings.transitionDuration, timings.animationDuration);\r\n if (maxDuration === 0) {\r\n $$jqLite.removeClass(element, activeClassName);\r\n animateClose(element, className);\r\n activeAnimationComplete();\r\n return;\r\n }\r\n\r\n if (!staggerTime && styles && Object.keys(styles).length > 0) {\r\n if (!timings.transitionDuration) {\r\n element.css('transition', timings.animationDuration + 's linear all');\r\n appliedStyles.push('transition');\r\n }\r\n element.css(styles);\r\n }\r\n\r\n var maxDelay = Math.max(timings.transitionDelay, timings.animationDelay);\r\n var maxDelayTime = maxDelay * ONE_SECOND;\r\n\r\n if (appliedStyles.length > 0) {\r\n //the element being animated may sometimes contain comment nodes in\r\n //the jqLite object, so we're safe to use a single variable to house\r\n //the styles since there is always only one element being animated\r\n var oldStyle = node.getAttribute('style') || '';\r\n if (oldStyle.charAt(oldStyle.length - 1) !== ';') {\r\n oldStyle += ';';\r\n }\r\n node.setAttribute('style', oldStyle + ' ' + style);\r\n }\r\n\r\n var startTime = Date.now();\r\n var css3AnimationEvents = ANIMATIONEND_EVENT + ' ' + TRANSITIONEND_EVENT;\r\n var animationTime = (maxDelay + maxDuration) * CLOSING_TIME_BUFFER;\r\n var totalTime = (staggerTime + animationTime) * ONE_SECOND;\r\n\r\n var staggerTimeout;\r\n if (staggerTime > 0) {\r\n $$jqLite.addClass(element, pendingClassName);\r\n staggerTimeout = $timeout(function() {\r\n staggerTimeout = null;\r\n\r\n if (timings.transitionDuration > 0) {\r\n blockTransitions(node, false);\r\n }\r\n if (timings.animationDuration > 0) {\r\n blockAnimations(node, false);\r\n }\r\n\r\n $$jqLite.addClass(element, activeClassName);\r\n $$jqLite.removeClass(element, pendingClassName);\r\n\r\n if (styles) {\r\n if (timings.transitionDuration === 0) {\r\n element.css('transition', timings.animationDuration + 's linear all');\r\n }\r\n element.css(styles);\r\n appliedStyles.push('transition');\r\n }\r\n }, staggerTime * ONE_SECOND, false);\r\n }\r\n\r\n element.on(css3AnimationEvents, onAnimationProgress);\r\n elementData.closeAnimationFns.push(function() {\r\n onEnd();\r\n activeAnimationComplete();\r\n });\r\n\r\n elementData.running++;\r\n animationCloseHandler(element, totalTime);\r\n return onEnd;\r\n\r\n // This will automatically be called by $animate so\r\n // there is no need to attach this internally to the\r\n // timeout done method.\r\n function onEnd() {\r\n element.off(css3AnimationEvents, onAnimationProgress);\r\n $$jqLite.removeClass(element, activeClassName);\r\n $$jqLite.removeClass(element, pendingClassName);\r\n if (staggerTimeout) {\r\n $timeout.cancel(staggerTimeout);\r\n }\r\n animateClose(element, className);\r\n var node = extractElementNode(element);\r\n for (var i in appliedStyles) {\r\n node.style.removeProperty(appliedStyles[i]);\r\n }\r\n }\r\n\r\n function onAnimationProgress(event) {\r\n event.stopPropagation();\r\n var ev = event.originalEvent || event;\r\n var timeStamp = ev.$manualTimeStamp || ev.timeStamp || Date.now();\r\n\r\n /* Firefox (or possibly just Gecko) likes to not round values up\r\n * when a ms measurement is used for the animation */\r\n var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES));\r\n\r\n /* $manualTimeStamp is a mocked timeStamp value which is set\r\n * within browserTrigger(). This is only here so that tests can\r\n * mock animations properly. Real events fallback to event.timeStamp,\r\n * or, if they don't, then a timeStamp is automatically created for them.\r\n * We're checking to see if the timeStamp surpasses the expected delay,\r\n * but we're using elapsedTime instead of the timeStamp on the 2nd\r\n * pre-condition since animations sometimes close off early */\r\n if (Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) {\r\n activeAnimationComplete();\r\n }\r\n }\r\n }\r\n\r\n function blockTransitions(node, bool) {\r\n node.style[TRANSITION_PROP + PROPERTY_KEY] = bool ? 'none' : '';\r\n }\r\n\r\n function blockAnimations(node, bool) {\r\n node.style[ANIMATION_PROP + ANIMATION_PLAYSTATE_KEY] = bool ? 'paused' : '';\r\n }\r\n\r\n function animateBefore(animationEvent, element, className, styles) {\r\n if (animateSetup(animationEvent, element, className, styles)) {\r\n return function(cancelled) {\r\n cancelled && animateClose(element, className);\r\n };\r\n }\r\n }\r\n\r\n function animateAfter(animationEvent, element, className, afterAnimationComplete, styles) {\r\n if (element.data(NG_ANIMATE_CSS_DATA_KEY)) {\r\n return animateRun(animationEvent, element, className, afterAnimationComplete, styles);\r\n } else {\r\n animateClose(element, className);\r\n afterAnimationComplete();\r\n }\r\n }\r\n\r\n function animate(animationEvent, element, className, animationComplete, options) {\r\n //If the animateSetup function doesn't bother returning a\r\n //cancellation function then it means that there is no animation\r\n //to perform at all\r\n var preReflowCancellation = animateBefore(animationEvent, element, className, options.from);\r\n if (!preReflowCancellation) {\r\n clearCacheAfterReflow();\r\n animationComplete();\r\n return;\r\n }\r\n\r\n //There are two cancellation functions: one is before the first\r\n //reflow animation and the second is during the active state\r\n //animation. The first function will take care of removing the\r\n //data from the element which will not make the 2nd animation\r\n //happen in the first place\r\n var cancel = preReflowCancellation;\r\n afterReflow(element, function() {\r\n //once the reflow is complete then we point cancel to\r\n //the new cancellation function which will remove all of the\r\n //animation properties from the active animation\r\n cancel = animateAfter(animationEvent, element, className, animationComplete, options.to);\r\n });\r\n\r\n return function(cancelled) {\r\n (cancel || noop)(cancelled);\r\n };\r\n }\r\n\r\n function animateClose(element, className) {\r\n $$jqLite.removeClass(element, className);\r\n var data = element.data(NG_ANIMATE_CSS_DATA_KEY);\r\n if (data) {\r\n if (data.running) {\r\n data.running--;\r\n }\r\n if (!data.running || data.running === 0) {\r\n element.removeData(NG_ANIMATE_CSS_DATA_KEY);\r\n }\r\n }\r\n }\r\n\r\n return {\r\n animate: function(element, className, from, to, animationCompleted, options) {\r\n options = options || {};\r\n options.from = from;\r\n options.to = to;\r\n return animate('animate', element, className, animationCompleted, options);\r\n },\r\n\r\n enter: function(element, animationCompleted, options) {\r\n options = options || {};\r\n return animate('enter', element, 'ng-enter', animationCompleted, options);\r\n },\r\n\r\n leave: function(element, animationCompleted, options) {\r\n options = options || {};\r\n return animate('leave', element, 'ng-leave', animationCompleted, options);\r\n },\r\n\r\n move: function(element, animationCompleted, options) {\r\n options = options || {};\r\n return animate('move', element, 'ng-move', animationCompleted, options);\r\n },\r\n\r\n beforeSetClass: function(element, add, remove, animationCompleted, options) {\r\n options = options || {};\r\n var className = suffixClasses(remove, '-remove') + ' ' +\r\n suffixClasses(add, '-add');\r\n var cancellationMethod = animateBefore('setClass', element, className, options.from);\r\n if (cancellationMethod) {\r\n afterReflow(element, animationCompleted);\r\n return cancellationMethod;\r\n }\r\n clearCacheAfterReflow();\r\n animationCompleted();\r\n },\r\n\r\n beforeAddClass: function(element, className, animationCompleted, options) {\r\n options = options || {};\r\n var cancellationMethod = animateBefore('addClass', element, suffixClasses(className, '-add'), options.from);\r\n if (cancellationMethod) {\r\n afterReflow(element, animationCompleted);\r\n return cancellationMethod;\r\n }\r\n clearCacheAfterReflow();\r\n animationCompleted();\r\n },\r\n\r\n beforeRemoveClass: function(element, className, animationCompleted, options) {\r\n options = options || {};\r\n var cancellationMethod = animateBefore('removeClass', element, suffixClasses(className, '-remove'), options.from);\r\n if (cancellationMethod) {\r\n afterReflow(element, animationCompleted);\r\n return cancellationMethod;\r\n }\r\n clearCacheAfterReflow();\r\n animationCompleted();\r\n },\r\n\r\n setClass: function(element, add, remove, animationCompleted, options) {\r\n options = options || {};\r\n remove = suffixClasses(remove, '-remove');\r\n add = suffixClasses(add, '-add');\r\n var className = remove + ' ' + add;\r\n return animateAfter('setClass', element, className, animationCompleted, options.to);\r\n },\r\n\r\n addClass: function(element, className, animationCompleted, options) {\r\n options = options || {};\r\n return animateAfter('addClass', element, suffixClasses(className, '-add'), animationCompleted, options.to);\r\n },\r\n\r\n removeClass: function(element, className, animationCompleted, options) {\r\n options = options || {};\r\n return animateAfter('removeClass', element, suffixClasses(className, '-remove'), animationCompleted, options.to);\r\n }\r\n };\r\n\r\n function suffixClasses(classes, suffix) {\r\n var className = '';\r\n classes = isArray(classes) ? classes : classes.split(/\\s+/);\r\n forEach(classes, function(klass, i) {\r\n if (klass && klass.length > 0) {\r\n className += (i > 0 ? ' ' : '') + klass + suffix;\r\n }\r\n });\r\n return className;\r\n }\r\n }]);\r\n }]);\r\n\r\n\r\n})(window, window.angular);\r\n\n},{}],3:[function(require,module,exports){\n/*\r\n * angular-ui-bootstrap\r\n * http://angular-ui.github.io/bootstrap/\r\n\r\n * Version: 0.13.4 - 2015-09-03\r\n * License: MIT\r\n */\r\nangular.module(\"ui.bootstrap\", [\"ui.bootstrap.tpls\", \"ui.bootstrap.collapse\",\"ui.bootstrap.accordion\",\"ui.bootstrap.alert\",\"ui.bootstrap.bindHtml\",\"ui.bootstrap.buttons\",\"ui.bootstrap.carousel\",\"ui.bootstrap.dateparser\",\"ui.bootstrap.position\",\"ui.bootstrap.datepicker\",\"ui.bootstrap.dropdown\",\"ui.bootstrap.modal\",\"ui.bootstrap.pagination\",\"ui.bootstrap.tooltip\",\"ui.bootstrap.popover\",\"ui.bootstrap.progressbar\",\"ui.bootstrap.rating\",\"ui.bootstrap.tabs\",\"ui.bootstrap.timepicker\",\"ui.bootstrap.transition\",\"ui.bootstrap.typeahead\"]);\r\nangular.module(\"ui.bootstrap.tpls\", [\"template/accordion/accordion-group.html\",\"template/accordion/accordion.html\",\"template/alert/alert.html\",\"template/carousel/carousel.html\",\"template/carousel/slide.html\",\"template/datepicker/datepicker.html\",\"template/datepicker/day.html\",\"template/datepicker/month.html\",\"template/datepicker/popup.html\",\"template/datepicker/year.html\",\"template/modal/backdrop.html\",\"template/modal/window.html\",\"template/pagination/pager.html\",\"template/pagination/pagination.html\",\"template/tooltip/tooltip-html-popup.html\",\"template/tooltip/tooltip-html-unsafe-popup.html\",\"template/tooltip/tooltip-popup.html\",\"template/tooltip/tooltip-template-popup.html\",\"template/popover/popover-html.html\",\"template/popover/popover-template.html\",\"template/popover/popover.html\",\"template/progressbar/bar.html\",\"template/progressbar/progress.html\",\"template/progressbar/progressbar.html\",\"template/rating/rating.html\",\"template/tabs/tab.html\",\"template/tabs/tabset.html\",\"template/timepicker/timepicker.html\",\"template/typeahead/typeahead-match.html\",\"template/typeahead/typeahead-popup.html\"]);\r\nangular.module('ui.bootstrap.collapse', [])\r\n\r\n .directive('collapse', ['$animate', function($animate) {\r\n return {\r\n link: function(scope, element, attrs) {\r\n function expand() {\r\n element.removeClass('collapse')\r\n .addClass('collapsing')\r\n .attr('aria-expanded', true)\r\n .attr('aria-hidden', false);\r\n\r\n $animate.addClass(element, 'in', {\r\n to: { height: element[0].scrollHeight + 'px' }\r\n }).then(expandDone);\r\n }\r\n\r\n function expandDone() {\r\n element.removeClass('collapsing');\r\n element.css({height: 'auto'});\r\n }\r\n\r\n function collapse() {\r\n if (!element.hasClass('collapse') && !element.hasClass('in')) {\r\n return collapseDone();\r\n }\r\n\r\n element\r\n // IMPORTANT: The height must be set before adding \"collapsing\" class.\r\n // Otherwise, the browser attempts to animate from height 0 (in\r\n // collapsing class) to the given height here.\r\n .css({height: element[0].scrollHeight + 'px'})\r\n // initially all panel collapse have the collapse class, this removal\r\n // prevents the animation from jumping to collapsed state\r\n .removeClass('collapse')\r\n .addClass('collapsing')\r\n .attr('aria-expanded', false)\r\n .attr('aria-hidden', true);\r\n\r\n $animate.removeClass(element, 'in', {\r\n to: {height: '0'}\r\n }).then(collapseDone);\r\n }\r\n\r\n function collapseDone() {\r\n element.css({height: '0'}); // Required so that collapse works when animation is disabled\r\n element.removeClass('collapsing');\r\n element.addClass('collapse');\r\n }\r\n\r\n scope.$watch(attrs.collapse, function(shouldCollapse) {\r\n if (shouldCollapse) {\r\n collapse();\r\n } else {\r\n expand();\r\n }\r\n });\r\n }\r\n };\r\n }]);\r\n\r\nangular.module('ui.bootstrap.accordion', ['ui.bootstrap.collapse'])\r\n\r\n.constant('accordionConfig', {\r\n closeOthers: true\r\n})\r\n\r\n.controller('AccordionController', ['$scope', '$attrs', 'accordionConfig', function($scope, $attrs, accordionConfig) {\r\n // This array keeps track of the accordion groups\r\n this.groups = [];\r\n\r\n // Ensure that all the groups in this accordion are closed, unless close-others explicitly says not to\r\n this.closeOthers = function(openGroup) {\r\n var closeOthers = angular.isDefined($attrs.closeOthers) ?\r\n $scope.$eval($attrs.closeOthers) : accordionConfig.closeOthers;\r\n if (closeOthers) {\r\n angular.forEach(this.groups, function(group) {\r\n if (group !== openGroup) {\r\n group.isOpen = false;\r\n }\r\n });\r\n }\r\n };\r\n\r\n // This is called from the accordion-group directive to add itself to the accordion\r\n this.addGroup = function(groupScope) {\r\n var that = this;\r\n this.groups.push(groupScope);\r\n\r\n groupScope.$on('$destroy', function(event) {\r\n that.removeGroup(groupScope);\r\n });\r\n };\r\n\r\n // This is called from the accordion-group directive when to remove itself\r\n this.removeGroup = function(group) {\r\n var index = this.groups.indexOf(group);\r\n if (index !== -1) {\r\n this.groups.splice(index, 1);\r\n }\r\n };\r\n\r\n}])\r\n\r\n// The accordion directive simply sets up the directive controller\r\n// and adds an accordion CSS class to itself element.\r\n.directive('accordion', function() {\r\n return {\r\n restrict: 'EA',\r\n controller: 'AccordionController',\r\n controllerAs: 'accordion',\r\n transclude: true,\r\n replace: false,\r\n templateUrl: function(element, attrs) {\r\n return attrs.templateUrl || 'template/accordion/accordion.html';\r\n }\r\n };\r\n})\r\n\r\n// The accordion-group directive indicates a block of html that will expand and collapse in an accordion\r\n.directive('accordionGroup', function() {\r\n return {\r\n require: '^accordion', // We need this directive to be inside an accordion\r\n restrict: 'EA',\r\n transclude: true, // It transcludes the contents of the directive into the template\r\n replace: true, // The element containing the directive will be replaced with the template\r\n templateUrl: function(element, attrs) {\r\n return attrs.templateUrl || 'template/accordion/accordion-group.html';\r\n },\r\n scope: {\r\n heading: '@', // Interpolate the heading attribute onto this scope\r\n isOpen: '=?',\r\n isDisabled: '=?'\r\n },\r\n controller: function() {\r\n this.setHeading = function(element) {\r\n this.heading = element;\r\n };\r\n },\r\n link: function(scope, element, attrs, accordionCtrl) {\r\n accordionCtrl.addGroup(scope);\r\n\r\n scope.openClass = attrs.openClass || 'panel-open';\r\n scope.panelClass = attrs.panelClass;\r\n scope.$watch('isOpen', function(value) {\r\n element.toggleClass(scope.openClass, value);\r\n if (value) {\r\n accordionCtrl.closeOthers(scope);\r\n }\r\n });\r\n\r\n scope.toggleOpen = function($event) {\r\n if (!scope.isDisabled) {\r\n if (!$event || $event.which === 32) {\r\n scope.isOpen = !scope.isOpen;\r\n }\r\n }\r\n };\r\n }\r\n };\r\n})\r\n\r\n// Use accordion-heading below an accordion-group to provide a heading containing HTML\r\n// \r\n// Heading containing HTML - \r\n// \r\n.directive('accordionHeading', function() {\r\n return {\r\n restrict: 'EA',\r\n transclude: true, // Grab the contents to be used as the heading\r\n template: '', // In effect remove this element!\r\n replace: true,\r\n require: '^accordionGroup',\r\n link: function(scope, element, attr, accordionGroupCtrl, transclude) {\r\n // Pass the heading to the accordion-group controller\r\n // so that it can be transcluded into the right place in the template\r\n // [The second parameter to transclude causes the elements to be cloned so that they work in ng-repeat]\r\n accordionGroupCtrl.setHeading(transclude(scope, angular.noop));\r\n }\r\n };\r\n})\r\n\r\n// Use in the accordion-group template to indicate where you want the heading to be transcluded\r\n// You must provide the property on the accordion-group controller that will hold the transcluded element\r\n//
\r\n// \r\n// ...\r\n//
\r\n.directive('accordionTransclude', function() {\r\n return {\r\n require: '^accordionGroup',\r\n link: function(scope, element, attr, controller) {\r\n scope.$watch(function() { return controller[attr.accordionTransclude]; }, function(heading) {\r\n if (heading) {\r\n element.find('span').html('');\r\n element.find('span').append(heading);\r\n }\r\n });\r\n }\r\n };\r\n})\r\n\r\n;\r\n\r\nangular.module('ui.bootstrap.alert', [])\r\n\r\n.controller('AlertController', ['$scope', '$attrs', function($scope, $attrs) {\r\n $scope.closeable = !!$attrs.close;\r\n this.close = $scope.close;\r\n}])\r\n\r\n.directive('alert', function() {\r\n return {\r\n controller: 'AlertController',\r\n controllerAs: 'alert',\r\n templateUrl: function(element, attrs) {\r\n return attrs.templateUrl || 'template/alert/alert.html';\r\n },\r\n transclude: true,\r\n replace: true,\r\n scope: {\r\n type: '@',\r\n close: '&'\r\n }\r\n };\r\n})\r\n\r\n.directive('dismissOnTimeout', ['$timeout', function($timeout) {\r\n return {\r\n require: 'alert',\r\n link: function(scope, element, attrs, alertCtrl) {\r\n $timeout(function() {\r\n alertCtrl.close();\r\n }, parseInt(attrs.dismissOnTimeout, 10));\r\n }\r\n };\r\n}]);\r\n\r\nangular.module('ui.bootstrap.bindHtml', [])\r\n\r\n .value('$bindHtmlUnsafeSuppressDeprecated', false)\r\n\r\n .directive('bindHtmlUnsafe', ['$log', '$bindHtmlUnsafeSuppressDeprecated', function ($log, $bindHtmlUnsafeSuppressDeprecated) {\r\n return function (scope, element, attr) {\r\n if (!$bindHtmlUnsafeSuppressDeprecated) {\r\n $log.warn('bindHtmlUnsafe is now deprecated. Use ngBindHtml instead');\r\n }\r\n element.addClass('ng-binding').data('$binding', attr.bindHtmlUnsafe);\r\n scope.$watch(attr.bindHtmlUnsafe, function bindHtmlUnsafeWatchAction(value) {\r\n element.html(value || '');\r\n });\r\n };\r\n }]);\r\nangular.module('ui.bootstrap.buttons', [])\r\n\r\n.constant('buttonConfig', {\r\n activeClass: 'active',\r\n toggleEvent: 'click'\r\n})\r\n\r\n.controller('ButtonsController', ['buttonConfig', function(buttonConfig) {\r\n this.activeClass = buttonConfig.activeClass || 'active';\r\n this.toggleEvent = buttonConfig.toggleEvent || 'click';\r\n}])\r\n\r\n.directive('btnRadio', function() {\r\n return {\r\n require: ['btnRadio', 'ngModel'],\r\n controller: 'ButtonsController',\r\n controllerAs: 'buttons',\r\n link: function(scope, element, attrs, ctrls) {\r\n var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];\r\n\r\n element.find('input').css({display: 'none'});\r\n\r\n //model -> UI\r\n ngModelCtrl.$render = function() {\r\n element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.btnRadio)));\r\n };\r\n\r\n //ui->model\r\n element.bind(buttonsCtrl.toggleEvent, function() {\r\n if (attrs.disabled) {\r\n return;\r\n }\r\n\r\n var isActive = element.hasClass(buttonsCtrl.activeClass);\r\n\r\n if (!isActive || angular.isDefined(attrs.uncheckable)) {\r\n scope.$apply(function() {\r\n ngModelCtrl.$setViewValue(isActive ? null : scope.$eval(attrs.btnRadio));\r\n ngModelCtrl.$render();\r\n });\r\n }\r\n });\r\n }\r\n };\r\n})\r\n\r\n.directive('btnCheckbox', ['$document', function($document) {\r\n return {\r\n require: ['btnCheckbox', 'ngModel'],\r\n controller: 'ButtonsController',\r\n controllerAs: 'button',\r\n link: function(scope, element, attrs, ctrls) {\r\n var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];\r\n\r\n element.find('input').css({display: 'none'});\r\n\r\n function getTrueValue() {\r\n return getCheckboxValue(attrs.btnCheckboxTrue, true);\r\n }\r\n\r\n function getFalseValue() {\r\n return getCheckboxValue(attrs.btnCheckboxFalse, false);\r\n }\r\n\r\n function getCheckboxValue(attributeValue, defaultValue) {\r\n var val = scope.$eval(attributeValue);\r\n return angular.isDefined(val) ? val : defaultValue;\r\n }\r\n\r\n //model -> UI\r\n ngModelCtrl.$render = function() {\r\n element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, getTrueValue()));\r\n };\r\n\r\n //ui->model\r\n element.bind(buttonsCtrl.toggleEvent, function() {\r\n if (attrs.disabled) {\r\n return;\r\n }\r\n\r\n scope.$apply(function() {\r\n ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue());\r\n ngModelCtrl.$render();\r\n });\r\n });\r\n\r\n //accessibility\r\n element.on('keypress', function(e) {\r\n if (attrs.disabled || e.which !== 32 || $document[0].activeElement !== element[0]) {\r\n return;\r\n }\r\n\r\n scope.$apply(function() {\r\n ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue());\r\n ngModelCtrl.$render();\r\n });\r\n });\r\n }\r\n };\r\n}]);\r\n\r\n/**\r\n* @ngdoc overview\r\n* @name ui.bootstrap.carousel\r\n*\r\n* @description\r\n* AngularJS version of an image carousel.\r\n*\r\n*/\r\nangular.module('ui.bootstrap.carousel', [])\r\n.controller('CarouselController', ['$scope', '$element', '$interval', '$animate', function ($scope, $element, $interval, $animate) {\r\n var self = this,\r\n slides = self.slides = $scope.slides = [],\r\n NEW_ANIMATE = angular.version.minor >= 4,\r\n NO_TRANSITION = 'uib-noTransition',\r\n SLIDE_DIRECTION = 'uib-slideDirection',\r\n currentIndex = -1,\r\n currentInterval, isPlaying;\r\n self.currentSlide = null;\r\n\r\n var destroyed = false;\r\n /* direction: \"prev\" or \"next\" */\r\n self.select = $scope.select = function(nextSlide, direction) {\r\n var nextIndex = $scope.indexOfSlide(nextSlide);\r\n //Decide direction if it's not given\r\n if (direction === undefined) {\r\n direction = nextIndex > self.getCurrentIndex() ? 'next' : 'prev';\r\n }\r\n //Prevent this user-triggered transition from occurring if there is already one in progress\r\n if (nextSlide && nextSlide !== self.currentSlide && !$scope.$currentTransition) {\r\n goNext(nextSlide, nextIndex, direction);\r\n }\r\n };\r\n\r\n function goNext(slide, index, direction) {\r\n // Scope has been destroyed, stop here.\r\n if (destroyed) { return; }\r\n\r\n angular.extend(slide, {direction: direction, active: true});\r\n angular.extend(self.currentSlide || {}, {direction: direction, active: false});\r\n if ($animate.enabled() && !$scope.noTransition && !$scope.$currentTransition &&\r\n slide.$element && self.slides.length > 1) {\r\n slide.$element.data(SLIDE_DIRECTION, slide.direction);\r\n if (self.currentSlide && self.currentSlide.$element) {\r\n self.currentSlide.$element.data(SLIDE_DIRECTION, slide.direction);\r\n }\r\n\r\n $scope.$currentTransition = true;\r\n if (NEW_ANIMATE) {\r\n $animate.on('addClass', slide.$element, function (element, phase) {\r\n if (phase === 'close') {\r\n $scope.$currentTransition = null;\r\n $animate.off('addClass', element);\r\n }\r\n });\r\n } else {\r\n slide.$element.one('$animate:close', function closeFn() {\r\n $scope.$currentTransition = null;\r\n });\r\n }\r\n }\r\n\r\n self.currentSlide = slide;\r\n currentIndex = index;\r\n\r\n //every time you change slides, reset the timer\r\n restartTimer();\r\n }\r\n\r\n $scope.$on('$destroy', function () {\r\n destroyed = true;\r\n });\r\n\r\n function getSlideByIndex(index) {\r\n if (angular.isUndefined(slides[index].index)) {\r\n return slides[index];\r\n }\r\n var i, len = slides.length;\r\n for (i = 0; i < slides.length; ++i) {\r\n if (slides[i].index == index) {\r\n return slides[i];\r\n }\r\n }\r\n }\r\n\r\n self.getCurrentIndex = function() {\r\n if (self.currentSlide && angular.isDefined(self.currentSlide.index)) {\r\n return +self.currentSlide.index;\r\n }\r\n return currentIndex;\r\n };\r\n\r\n /* Allow outside people to call indexOf on slides array */\r\n $scope.indexOfSlide = function(slide) {\r\n return angular.isDefined(slide.index) ? +slide.index : slides.indexOf(slide);\r\n };\r\n\r\n $scope.next = function() {\r\n var newIndex = (self.getCurrentIndex() + 1) % slides.length;\r\n\r\n if (newIndex === 0 && $scope.noWrap()) {\r\n $scope.pause();\r\n return;\r\n }\r\n\r\n return self.select(getSlideByIndex(newIndex), 'next');\r\n };\r\n\r\n $scope.prev = function() {\r\n var newIndex = self.getCurrentIndex() - 1 < 0 ? slides.length - 1 : self.getCurrentIndex() - 1;\r\n\r\n if ($scope.noWrap() && newIndex === slides.length - 1){\r\n $scope.pause();\r\n return;\r\n }\r\n\r\n return self.select(getSlideByIndex(newIndex), 'prev');\r\n };\r\n\r\n $scope.isActive = function(slide) {\r\n return self.currentSlide === slide;\r\n };\r\n\r\n $scope.$watch('interval', restartTimer);\r\n $scope.$on('$destroy', resetTimer);\r\n\r\n function restartTimer() {\r\n resetTimer();\r\n var interval = +$scope.interval;\r\n if (!isNaN(interval) && interval > 0) {\r\n currentInterval = $interval(timerFn, interval);\r\n }\r\n }\r\n\r\n function resetTimer() {\r\n if (currentInterval) {\r\n $interval.cancel(currentInterval);\r\n currentInterval = null;\r\n }\r\n }\r\n\r\n function timerFn() {\r\n var interval = +$scope.interval;\r\n if (isPlaying && !isNaN(interval) && interval > 0 && slides.length) {\r\n $scope.next();\r\n } else {\r\n $scope.pause();\r\n }\r\n }\r\n\r\n $scope.play = function() {\r\n if (!isPlaying) {\r\n isPlaying = true;\r\n restartTimer();\r\n }\r\n };\r\n $scope.pause = function() {\r\n if (!$scope.noPause) {\r\n isPlaying = false;\r\n resetTimer();\r\n }\r\n };\r\n\r\n self.addSlide = function(slide, element) {\r\n slide.$element = element;\r\n slides.push(slide);\r\n //if this is the first slide or the slide is set to active, select it\r\n if(slides.length === 1 || slide.active) {\r\n self.select(slides[slides.length-1]);\r\n if (slides.length == 1) {\r\n $scope.play();\r\n }\r\n } else {\r\n slide.active = false;\r\n }\r\n };\r\n\r\n self.removeSlide = function(slide) {\r\n if (angular.isDefined(slide.index)) {\r\n slides.sort(function(a, b) {\r\n return +a.index > +b.index;\r\n });\r\n }\r\n //get the index of the slide inside the carousel\r\n var index = slides.indexOf(slide);\r\n slides.splice(index, 1);\r\n if (slides.length > 0 && slide.active) {\r\n if (index >= slides.length) {\r\n self.select(slides[index-1]);\r\n } else {\r\n self.select(slides[index]);\r\n }\r\n } else if (currentIndex > index) {\r\n currentIndex--;\r\n }\r\n \r\n //clean the currentSlide when no more slide\r\n if (slides.length === 0) {\r\n self.currentSlide = null;\r\n }\r\n };\r\n\r\n $scope.$watch('noTransition', function(noTransition) {\r\n $element.data(NO_TRANSITION, noTransition);\r\n });\r\n\r\n}])\r\n\r\n/**\r\n * @ngdoc directive\r\n * @name ui.bootstrap.carousel.directive:carousel\r\n * @restrict EA\r\n *\r\n * @description\r\n * Carousel is the outer container for a set of image 'slides' to showcase.\r\n *\r\n * @param {number=} interval The time, in milliseconds, that it will take the carousel to go to the next slide.\r\n * @param {boolean=} noTransition Whether to disable transitions on the carousel.\r\n * @param {boolean=} noPause Whether to disable pausing on the carousel (by default, the carousel interval pauses on hover).\r\n *\r\n * @example\r\n\r\n \r\n \r\n \r\n \r\n
\r\n

Beautiful!

\r\n
\r\n
\r\n \r\n \r\n
\r\n

D'aww!

\r\n
\r\n
\r\n
\r\n
\r\n \r\n .carousel-indicators {\r\n top: auto;\r\n bottom: 15px;\r\n }\r\n \r\n
\r\n */\r\n.directive('carousel', [function() {\r\n return {\r\n restrict: 'EA',\r\n transclude: true,\r\n replace: true,\r\n controller: 'CarouselController',\r\n controllerAs: 'carousel',\r\n require: 'carousel',\r\n templateUrl: function(element, attrs) {\r\n return attrs.templateUrl || 'template/carousel/carousel.html';\r\n },\r\n scope: {\r\n interval: '=',\r\n noTransition: '=',\r\n noPause: '=',\r\n noWrap: '&'\r\n }\r\n };\r\n}])\r\n\r\n/**\r\n * @ngdoc directive\r\n * @name ui.bootstrap.carousel.directive:slide\r\n * @restrict EA\r\n *\r\n * @description\r\n * Creates a slide inside a {@link ui.bootstrap.carousel.directive:carousel carousel}. Must be placed as a child of a carousel element.\r\n *\r\n * @param {boolean=} active Model binding, whether or not this slide is currently active.\r\n * @param {number=} index The index of the slide. The slides will be sorted by this parameter.\r\n *\r\n * @example\r\n\r\n \r\n
\r\n \r\n \r\n \r\n
\r\n

Slide {{$index}}

\r\n

{{slide.text}}

\r\n
\r\n
\r\n
\r\n Interval, in milliseconds: \r\n
Enter a negative number to stop the interval.\r\n
\r\n
\r\n \r\nfunction CarouselDemoCtrl($scope) {\r\n $scope.myInterval = 5000;\r\n}\r\n \r\n \r\n .carousel-indicators {\r\n top: auto;\r\n bottom: 15px;\r\n }\r\n \r\n
\r\n*/\r\n\r\n.directive('slide', function() {\r\n return {\r\n require: '^carousel',\r\n restrict: 'EA',\r\n transclude: true,\r\n replace: true,\r\n templateUrl: function(element, attrs) {\r\n return attrs.templateUrl || 'template/carousel/slide.html';\r\n },\r\n scope: {\r\n active: '=?',\r\n actual: '=?',\r\n index: '=?'\r\n },\r\n link: function (scope, element, attrs, carouselCtrl) {\r\n carouselCtrl.addSlide(scope, element);\r\n //when the scope is destroyed then remove the slide from the current slides array\r\n scope.$on('$destroy', function() {\r\n carouselCtrl.removeSlide(scope);\r\n });\r\n\r\n scope.$watch('active', function(active) {\r\n if (active) {\r\n carouselCtrl.select(scope);\r\n }\r\n });\r\n }\r\n };\r\n})\r\n\r\n.animation('.item', [\r\n '$injector', '$animate',\r\nfunction ($injector, $animate) {\r\n var NO_TRANSITION = 'uib-noTransition',\r\n SLIDE_DIRECTION = 'uib-slideDirection',\r\n $animateCss = null;\r\n\r\n if ($injector.has('$animateCss')) {\r\n $animateCss = $injector.get('$animateCss');\r\n }\r\n\r\n function removeClass(element, className, callback) {\r\n element.removeClass(className);\r\n if (callback) {\r\n callback();\r\n }\r\n }\r\n\r\n return {\r\n beforeAddClass: function (element, className, done) {\r\n // Due to transclusion, noTransition property is on parent's scope\r\n if (className == 'active' && element.parent() &&\r\n !element.parent().data(NO_TRANSITION)) {\r\n var stopped = false;\r\n var direction = element.data(SLIDE_DIRECTION);\r\n var directionClass = direction == 'next' ? 'left' : 'right';\r\n var removeClassFn = removeClass.bind(this, element,\r\n directionClass + ' ' + direction, done);\r\n element.addClass(direction);\r\n\r\n if ($animateCss) {\r\n $animateCss(element, {addClass: directionClass})\r\n .start()\r\n .done(removeClassFn);\r\n } else {\r\n $animate.addClass(element, directionClass).then(function () {\r\n if (!stopped) {\r\n removeClassFn();\r\n }\r\n done();\r\n });\r\n }\r\n\r\n return function () {\r\n stopped = true;\r\n };\r\n }\r\n done();\r\n },\r\n beforeRemoveClass: function (element, className, done) {\r\n // Due to transclusion, noTransition property is on parent's scope\r\n if (className === 'active' && element.parent() &&\r\n !element.parent().data(NO_TRANSITION)) {\r\n var stopped = false;\r\n var direction = element.data(SLIDE_DIRECTION);\r\n var directionClass = direction == 'next' ? 'left' : 'right';\r\n var removeClassFn = removeClass.bind(this, element, directionClass, done);\r\n\r\n if ($animateCss) {\r\n $animateCss(element, {addClass: directionClass})\r\n .start()\r\n .done(removeClassFn);\r\n } else {\r\n $animate.addClass(element, directionClass).then(function () {\r\n if (!stopped) {\r\n removeClassFn();\r\n }\r\n done();\r\n });\r\n }\r\n return function () {\r\n stopped = true;\r\n };\r\n }\r\n done();\r\n }\r\n };\r\n\r\n}])\r\n\r\n\r\n;\r\n\r\nangular.module('ui.bootstrap.dateparser', [])\r\n\r\n.service('dateParser', ['$log', '$locale', 'orderByFilter', function($log, $locale, orderByFilter) {\r\n // Pulled from https://github.com/mbostock/d3/blob/master/src/format/requote.js\r\n var SPECIAL_CHARACTERS_REGEXP = /[\\\\\\^\\$\\*\\+\\?\\|\\[\\]\\(\\)\\.\\{\\}]/g;\r\n\r\n this.parsers = {};\r\n\r\n var formatCodeToRegex = {\r\n 'yyyy': {\r\n regex: '\\\\d{4}',\r\n apply: function(value) { this.year = +value; }\r\n },\r\n 'yy': {\r\n regex: '\\\\d{2}',\r\n apply: function(value) { this.year = +value + 2000; }\r\n },\r\n 'y': {\r\n regex: '\\\\d{1,4}',\r\n apply: function(value) { this.year = +value; }\r\n },\r\n 'MMMM': {\r\n regex: $locale.DATETIME_FORMATS.MONTH.join('|'),\r\n apply: function(value) { this.month = $locale.DATETIME_FORMATS.MONTH.indexOf(value); }\r\n },\r\n 'MMM': {\r\n regex: $locale.DATETIME_FORMATS.SHORTMONTH.join('|'),\r\n apply: function(value) { this.month = $locale.DATETIME_FORMATS.SHORTMONTH.indexOf(value); }\r\n },\r\n 'MM': {\r\n regex: '0[1-9]|1[0-2]',\r\n apply: function(value) { this.month = value - 1; }\r\n },\r\n 'M': {\r\n regex: '[1-9]|1[0-2]',\r\n apply: function(value) { this.month = value - 1; }\r\n },\r\n 'dd': {\r\n regex: '[0-2][0-9]{1}|3[0-1]{1}',\r\n apply: function(value) { this.date = +value; }\r\n },\r\n 'd': {\r\n regex: '[1-2]?[0-9]{1}|3[0-1]{1}',\r\n apply: function(value) { this.date = +value; }\r\n },\r\n 'EEEE': {\r\n regex: $locale.DATETIME_FORMATS.DAY.join('|')\r\n },\r\n 'EEE': {\r\n regex: $locale.DATETIME_FORMATS.SHORTDAY.join('|')\r\n },\r\n 'HH': {\r\n regex: '(?:0|1)[0-9]|2[0-3]',\r\n apply: function(value) { this.hours = +value; }\r\n },\r\n 'hh': {\r\n regex: '0[0-9]|1[0-2]',\r\n apply: function(value) { this.hours = +value; }\r\n },\r\n 'H': {\r\n regex: '1?[0-9]|2[0-3]',\r\n apply: function(value) { this.hours = +value; }\r\n },\r\n 'h': {\r\n regex: '[0-9]|1[0-2]',\r\n apply: function(value) { this.hours = +value; }\r\n },\r\n 'mm': {\r\n regex: '[0-5][0-9]',\r\n apply: function(value) { this.minutes = +value; }\r\n },\r\n 'm': {\r\n regex: '[0-9]|[1-5][0-9]',\r\n apply: function(value) { this.minutes = +value; }\r\n },\r\n 'sss': {\r\n regex: '[0-9][0-9][0-9]',\r\n apply: function(value) { this.milliseconds = +value; }\r\n },\r\n 'ss': {\r\n regex: '[0-5][0-9]',\r\n apply: function(value) { this.seconds = +value; }\r\n },\r\n 's': {\r\n regex: '[0-9]|[1-5][0-9]',\r\n apply: function(value) { this.seconds = +value; }\r\n },\r\n 'a': {\r\n regex: $locale.DATETIME_FORMATS.AMPMS.join('|'),\r\n apply: function(value) {\r\n if (this.hours === 12) {\r\n this.hours = 0;\r\n }\r\n\r\n if (value === 'PM') {\r\n this.hours += 12;\r\n }\r\n }\r\n }\r\n };\r\n\r\n function createParser(format) {\r\n var map = [], regex = format.split('');\r\n\r\n angular.forEach(formatCodeToRegex, function(data, code) {\r\n var index = format.indexOf(code);\r\n\r\n if (index > -1) {\r\n format = format.split('');\r\n\r\n regex[index] = '(' + data.regex + ')';\r\n format[index] = '$'; // Custom symbol to define consumed part of format\r\n for (var i = index + 1, n = index + code.length; i < n; i++) {\r\n regex[i] = '';\r\n format[i] = '$';\r\n }\r\n format = format.join('');\r\n\r\n map.push({ index: index, apply: data.apply });\r\n }\r\n });\r\n\r\n return {\r\n regex: new RegExp('^' + regex.join('') + '$'),\r\n map: orderByFilter(map, 'index')\r\n };\r\n }\r\n\r\n this.parse = function(input, format, baseDate) {\r\n if (!angular.isString(input) || !format) {\r\n return input;\r\n }\r\n\r\n format = $locale.DATETIME_FORMATS[format] || format;\r\n format = format.replace(SPECIAL_CHARACTERS_REGEXP, '\\\\$&');\r\n\r\n if (!this.parsers[format]) {\r\n this.parsers[format] = createParser(format);\r\n }\r\n\r\n var parser = this.parsers[format],\r\n regex = parser.regex,\r\n map = parser.map,\r\n results = input.match(regex);\r\n\r\n if (results && results.length) {\r\n var fields, dt;\r\n if (angular.isDate(baseDate) && !isNaN(baseDate.getTime())) {\r\n fields = {\r\n year: baseDate.getFullYear(),\r\n month: baseDate.getMonth(),\r\n date: baseDate.getDate(),\r\n hours: baseDate.getHours(),\r\n minutes: baseDate.getMinutes(),\r\n seconds: baseDate.getSeconds(),\r\n milliseconds: baseDate.getMilliseconds()\r\n };\r\n } else {\r\n if (baseDate) {\r\n $log.warn('dateparser:', 'baseDate is not a valid date');\r\n }\r\n fields = { year: 1900, month: 0, date: 1, hours: 0, minutes: 0, seconds: 0, milliseconds: 0 };\r\n }\r\n\r\n for (var i = 1, n = results.length; i < n; i++) {\r\n var mapper = map[i-1];\r\n if (mapper.apply) {\r\n mapper.apply.call(fields, results[i]);\r\n }\r\n }\r\n\r\n if (isValid(fields.year, fields.month, fields.date)) {\r\n dt = new Date(fields.year, fields.month, fields.date,\r\n fields.hours, fields.minutes, fields.seconds,\r\n fields.milliseconds || 0);\r\n }\r\n\r\n return dt;\r\n }\r\n };\r\n\r\n // Check if date is valid for specific month (and year for February).\r\n // Month: 0 = Jan, 1 = Feb, etc\r\n function isValid(year, month, date) {\r\n if (date < 1) {\r\n return false;\r\n }\r\n\r\n if (month === 1 && date > 28) {\r\n return date === 29 && ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0);\r\n }\r\n\r\n if (month === 3 || month === 5 || month === 8 || month === 10) {\r\n return date < 31;\r\n }\r\n\r\n return true;\r\n }\r\n}]);\r\n\r\nangular.module('ui.bootstrap.position', [])\r\n\r\n/**\r\n * A set of utility methods that can be use to retrieve position of DOM elements.\r\n * It is meant to be used where we need to absolute-position DOM elements in\r\n * relation to other, existing elements (this is the case for tooltips, popovers,\r\n * typeahead suggestions etc.).\r\n */\r\n .factory('$position', ['$document', '$window', function($document, $window) {\r\n function getStyle(el, cssprop) {\r\n if (el.currentStyle) { //IE\r\n return el.currentStyle[cssprop];\r\n } else if ($window.getComputedStyle) {\r\n return $window.getComputedStyle(el)[cssprop];\r\n }\r\n // finally try and get inline style\r\n return el.style[cssprop];\r\n }\r\n\r\n /**\r\n * Checks if a given element is statically positioned\r\n * @param element - raw DOM element\r\n */\r\n function isStaticPositioned(element) {\r\n return (getStyle(element, 'position') || 'static' ) === 'static';\r\n }\r\n\r\n /**\r\n * returns the closest, non-statically positioned parentOffset of a given element\r\n * @param element\r\n */\r\n var parentOffsetEl = function(element) {\r\n var docDomEl = $document[0];\r\n var offsetParent = element.offsetParent || docDomEl;\r\n while (offsetParent && offsetParent !== docDomEl && isStaticPositioned(offsetParent) ) {\r\n offsetParent = offsetParent.offsetParent;\r\n }\r\n return offsetParent || docDomEl;\r\n };\r\n\r\n return {\r\n /**\r\n * Provides read-only equivalent of jQuery's position function:\r\n * http://api.jquery.com/position/\r\n */\r\n position: function(element) {\r\n var elBCR = this.offset(element);\r\n var offsetParentBCR = { top: 0, left: 0 };\r\n var offsetParentEl = parentOffsetEl(element[0]);\r\n if (offsetParentEl != $document[0]) {\r\n offsetParentBCR = this.offset(angular.element(offsetParentEl));\r\n offsetParentBCR.top += offsetParentEl.clientTop - offsetParentEl.scrollTop;\r\n offsetParentBCR.left += offsetParentEl.clientLeft - offsetParentEl.scrollLeft;\r\n }\r\n\r\n var boundingClientRect = element[0].getBoundingClientRect();\r\n return {\r\n width: boundingClientRect.width || element.prop('offsetWidth'),\r\n height: boundingClientRect.height || element.prop('offsetHeight'),\r\n top: elBCR.top - offsetParentBCR.top,\r\n left: elBCR.left - offsetParentBCR.left\r\n };\r\n },\r\n\r\n /**\r\n * Provides read-only equivalent of jQuery's offset function:\r\n * http://api.jquery.com/offset/\r\n */\r\n offset: function(element) {\r\n var boundingClientRect = element[0].getBoundingClientRect();\r\n return {\r\n width: boundingClientRect.width || element.prop('offsetWidth'),\r\n height: boundingClientRect.height || element.prop('offsetHeight'),\r\n top: boundingClientRect.top + ($window.pageYOffset || $document[0].documentElement.scrollTop),\r\n left: boundingClientRect.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft)\r\n };\r\n },\r\n\r\n /**\r\n * Provides coordinates for the targetEl in relation to hostEl\r\n */\r\n positionElements: function(hostEl, targetEl, positionStr, appendToBody) {\r\n var positionStrParts = positionStr.split('-');\r\n var pos0 = positionStrParts[0], pos1 = positionStrParts[1] || 'center';\r\n\r\n var hostElPos,\r\n targetElWidth,\r\n targetElHeight,\r\n targetElPos;\r\n\r\n hostElPos = appendToBody ? this.offset(hostEl) : this.position(hostEl);\r\n\r\n targetElWidth = targetEl.prop('offsetWidth');\r\n targetElHeight = targetEl.prop('offsetHeight');\r\n\r\n var shiftWidth = {\r\n center: function() {\r\n return hostElPos.left + hostElPos.width / 2 - targetElWidth / 2;\r\n },\r\n left: function() {\r\n return hostElPos.left;\r\n },\r\n right: function() {\r\n return hostElPos.left + hostElPos.width;\r\n }\r\n };\r\n\r\n var shiftHeight = {\r\n center: function() {\r\n return hostElPos.top + hostElPos.height / 2 - targetElHeight / 2;\r\n },\r\n top: function() {\r\n return hostElPos.top;\r\n },\r\n bottom: function() {\r\n return hostElPos.top + hostElPos.height;\r\n }\r\n };\r\n\r\n switch (pos0) {\r\n case 'right':\r\n targetElPos = {\r\n top: shiftHeight[pos1](),\r\n left: shiftWidth[pos0]()\r\n };\r\n break;\r\n case 'left':\r\n targetElPos = {\r\n top: shiftHeight[pos1](),\r\n left: hostElPos.left - targetElWidth\r\n };\r\n break;\r\n case 'bottom':\r\n targetElPos = {\r\n top: shiftHeight[pos0](),\r\n left: shiftWidth[pos1]()\r\n };\r\n break;\r\n default:\r\n targetElPos = {\r\n top: hostElPos.top - targetElHeight,\r\n left: shiftWidth[pos1]()\r\n };\r\n break;\r\n }\r\n\r\n return targetElPos;\r\n }\r\n };\r\n }]);\r\n\r\nangular.module('ui.bootstrap.datepicker', ['ui.bootstrap.dateparser', 'ui.bootstrap.position'])\r\n\r\n.value('$datepickerSuppressError', false)\r\n\r\n.constant('datepickerConfig', {\r\n formatDay: 'dd',\r\n formatMonth: 'MMMM',\r\n formatYear: 'yyyy',\r\n formatDayHeader: 'EEE',\r\n formatDayTitle: 'MMMM yyyy',\r\n formatMonthTitle: 'yyyy',\r\n datepickerMode: 'day',\r\n minMode: 'day',\r\n maxMode: 'year',\r\n showWeeks: true,\r\n startingDay: 0,\r\n yearRange: 20,\r\n minDate: null,\r\n maxDate: null,\r\n shortcutPropagation: false\r\n})\r\n\r\n.controller('DatepickerController', ['$scope', '$attrs', '$parse', '$interpolate', '$log', 'dateFilter', 'datepickerConfig', '$datepickerSuppressError', function($scope, $attrs, $parse, $interpolate, $log, dateFilter, datepickerConfig, $datepickerSuppressError) {\r\n var self = this,\r\n ngModelCtrl = { $setViewValue: angular.noop }; // nullModelCtrl;\r\n\r\n // Modes chain\r\n this.modes = ['day', 'month', 'year'];\r\n\r\n // Configuration attributes\r\n angular.forEach(['formatDay', 'formatMonth', 'formatYear', 'formatDayHeader', 'formatDayTitle', 'formatMonthTitle',\r\n 'showWeeks', 'startingDay', 'yearRange', 'shortcutPropagation'], function(key, index) {\r\n self[key] = angular.isDefined($attrs[key]) ? (index < 6 ? $interpolate($attrs[key])($scope.$parent) : $scope.$parent.$eval($attrs[key])) : datepickerConfig[key];\r\n });\r\n\r\n // Watchable date attributes\r\n angular.forEach(['minDate', 'maxDate'], function(key) {\r\n if ($attrs[key]) {\r\n $scope.$parent.$watch($parse($attrs[key]), function(value) {\r\n self[key] = value ? new Date(value) : null;\r\n self.refreshView();\r\n });\r\n } else {\r\n self[key] = datepickerConfig[key] ? new Date(datepickerConfig[key]) : null;\r\n }\r\n });\r\n\r\n angular.forEach(['minMode', 'maxMode'], function(key) {\r\n if ($attrs[key]) {\r\n $scope.$parent.$watch($parse($attrs[key]), function(value) {\r\n self[key] = angular.isDefined(value) ? value : $attrs[key];\r\n $scope[key] = self[key];\r\n if ((key == 'minMode' && self.modes.indexOf($scope.datepickerMode) < self.modes.indexOf(self[key])) || (key == 'maxMode' && self.modes.indexOf($scope.datepickerMode) > self.modes.indexOf(self[key]))) {\r\n $scope.datepickerMode = self[key];\r\n }\r\n });\r\n } else {\r\n self[key] = datepickerConfig[key] || null;\r\n $scope[key] = self[key];\r\n }\r\n });\r\n\r\n $scope.datepickerMode = $scope.datepickerMode || datepickerConfig.datepickerMode;\r\n $scope.uniqueId = 'datepicker-' + $scope.$id + '-' + Math.floor(Math.random() * 10000);\r\n\r\n if (angular.isDefined($attrs.initDate)) {\r\n this.activeDate = $scope.$parent.$eval($attrs.initDate) || new Date();\r\n $scope.$parent.$watch($attrs.initDate, function(initDate) {\r\n if (initDate && (ngModelCtrl.$isEmpty(ngModelCtrl.$modelValue) || ngModelCtrl.$invalid)) {\r\n self.activeDate = initDate;\r\n self.refreshView();\r\n }\r\n });\r\n } else {\r\n this.activeDate = new Date();\r\n }\r\n\r\n $scope.isActive = function(dateObject) {\r\n if (self.compare(dateObject.date, self.activeDate) === 0) {\r\n $scope.activeDateId = dateObject.uid;\r\n return true;\r\n }\r\n return false;\r\n };\r\n\r\n this.init = function(ngModelCtrl_) {\r\n ngModelCtrl = ngModelCtrl_;\r\n\r\n ngModelCtrl.$render = function() {\r\n self.render();\r\n };\r\n };\r\n\r\n this.render = function() {\r\n if (ngModelCtrl.$viewValue) {\r\n var date = new Date(ngModelCtrl.$viewValue),\r\n isValid = !isNaN(date);\r\n\r\n if (isValid) {\r\n this.activeDate = date;\r\n } else if (!$datepickerSuppressError) {\r\n $log.error('Datepicker directive: \"ng-model\" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.');\r\n }\r\n }\r\n this.refreshView();\r\n };\r\n\r\n this.refreshView = function() {\r\n if (this.element) {\r\n this._refreshView();\r\n\r\n var date = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null;\r\n ngModelCtrl.$setValidity('dateDisabled', !date || (this.element && !this.isDisabled(date)));\r\n }\r\n };\r\n\r\n this.createDateObject = function(date, format) {\r\n var model = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null;\r\n return {\r\n date: date,\r\n label: dateFilter(date, format),\r\n selected: model && this.compare(date, model) === 0,\r\n disabled: this.isDisabled(date),\r\n current: this.compare(date, new Date()) === 0,\r\n customClass: this.customClass(date)\r\n };\r\n };\r\n\r\n this.isDisabled = function(date) {\r\n return ((this.minDate && this.compare(date, this.minDate) < 0) || (this.maxDate && this.compare(date, this.maxDate) > 0) || ($attrs.dateDisabled && $scope.dateDisabled({date: date, mode: $scope.datepickerMode})));\r\n };\r\n\r\n this.customClass = function(date) {\r\n return $scope.customClass({date: date, mode: $scope.datepickerMode});\r\n };\r\n\r\n // Split array into smaller arrays\r\n this.split = function(arr, size) {\r\n var arrays = [];\r\n while (arr.length > 0) {\r\n arrays.push(arr.splice(0, size));\r\n }\r\n return arrays;\r\n };\r\n\r\n // Fix a hard-reprodusible bug with timezones\r\n // The bug depends on OS, browser, current timezone and current date\r\n // i.e.\r\n // var date = new Date(2014, 0, 1);\r\n // console.log(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours());\r\n // can result in \"2013 11 31 23\" because of the bug.\r\n this.fixTimeZone = function(date) {\r\n var hours = date.getHours();\r\n date.setHours(hours === 23 ? hours + 2 : 0);\r\n };\r\n\r\n $scope.select = function(date) {\r\n if ($scope.datepickerMode === self.minMode) {\r\n var dt = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : new Date(0, 0, 0, 0, 0, 0, 0);\r\n dt.setFullYear(date.getFullYear(), date.getMonth(), date.getDate());\r\n ngModelCtrl.$setViewValue(dt);\r\n ngModelCtrl.$render();\r\n } else {\r\n self.activeDate = date;\r\n $scope.datepickerMode = self.modes[self.modes.indexOf($scope.datepickerMode) - 1];\r\n }\r\n };\r\n\r\n $scope.move = function(direction) {\r\n var year = self.activeDate.getFullYear() + direction * (self.step.years || 0),\r\n month = self.activeDate.getMonth() + direction * (self.step.months || 0);\r\n self.activeDate.setFullYear(year, month, 1);\r\n self.refreshView();\r\n };\r\n\r\n $scope.toggleMode = function(direction) {\r\n direction = direction || 1;\r\n\r\n if (($scope.datepickerMode === self.maxMode && direction === 1) || ($scope.datepickerMode === self.minMode && direction === -1)) {\r\n return;\r\n }\r\n\r\n $scope.datepickerMode = self.modes[self.modes.indexOf($scope.datepickerMode) + direction];\r\n };\r\n\r\n // Key event mapper\r\n $scope.keys = { 13: 'enter', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down' };\r\n\r\n var focusElement = function() {\r\n self.element[0].focus();\r\n };\r\n\r\n // Listen for focus requests from popup directive\r\n $scope.$on('datepicker.focus', focusElement);\r\n\r\n $scope.keydown = function(evt) {\r\n var key = $scope.keys[evt.which];\r\n\r\n if (!key || evt.shiftKey || evt.altKey) {\r\n return;\r\n }\r\n\r\n evt.preventDefault();\r\n if (!self.shortcutPropagation) {\r\n evt.stopPropagation();\r\n }\r\n\r\n if (key === 'enter' || key === 'space') {\r\n if (self.isDisabled(self.activeDate)) {\r\n return; // do nothing\r\n }\r\n $scope.select(self.activeDate);\r\n focusElement();\r\n } else if (evt.ctrlKey && (key === 'up' || key === 'down')) {\r\n $scope.toggleMode(key === 'up' ? 1 : -1);\r\n focusElement();\r\n } else {\r\n self.handleKeyDown(key, evt);\r\n self.refreshView();\r\n }\r\n };\r\n}])\r\n\r\n.directive('datepicker', function() {\r\n return {\r\n restrict: 'EA',\r\n replace: true,\r\n templateUrl: function(element, attrs) {\r\n return attrs.templateUrl || 'template/datepicker/datepicker.html';\r\n },\r\n scope: {\r\n datepickerMode: '=?',\r\n dateDisabled: '&',\r\n customClass: '&',\r\n shortcutPropagation: '&?'\r\n },\r\n require: ['datepicker', '^ngModel'],\r\n controller: 'DatepickerController',\r\n controllerAs: 'datepicker',\r\n link: function(scope, element, attrs, ctrls) {\r\n var datepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1];\r\n\r\n datepickerCtrl.init(ngModelCtrl);\r\n }\r\n };\r\n})\r\n\r\n.directive('daypicker', ['dateFilter', function(dateFilter) {\r\n return {\r\n restrict: 'EA',\r\n replace: true,\r\n templateUrl: 'template/datepicker/day.html',\r\n require: '^datepicker',\r\n link: function(scope, element, attrs, ctrl) {\r\n scope.showWeeks = ctrl.showWeeks;\r\n\r\n ctrl.step = { months: 1 };\r\n ctrl.element = element;\r\n\r\n var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\r\n function getDaysInMonth(year, month) {\r\n return ((month === 1) && (year % 4 === 0) && ((year % 100 !== 0) || (year % 400 === 0))) ? 29 : DAYS_IN_MONTH[month];\r\n }\r\n\r\n function getDates(startDate, n) {\r\n var dates = new Array(n), current = new Date(startDate), i = 0, date;\r\n while (i < n) {\r\n date = new Date(current);\r\n ctrl.fixTimeZone(date);\r\n dates[i++] = date;\r\n current.setDate(current.getDate() + 1);\r\n }\r\n return dates;\r\n }\r\n\r\n ctrl._refreshView = function() {\r\n var year = ctrl.activeDate.getFullYear(),\r\n month = ctrl.activeDate.getMonth(),\r\n firstDayOfMonth = new Date(year, month, 1),\r\n difference = ctrl.startingDay - firstDayOfMonth.getDay(),\r\n numDisplayedFromPreviousMonth = (difference > 0) ? 7 - difference : - difference,\r\n firstDate = new Date(firstDayOfMonth);\r\n\r\n if (numDisplayedFromPreviousMonth > 0) {\r\n firstDate.setDate(-numDisplayedFromPreviousMonth + 1);\r\n }\r\n\r\n // 42 is the number of days on a six-month calendar\r\n var days = getDates(firstDate, 42);\r\n for (var i = 0; i < 42; i ++) {\r\n days[i] = angular.extend(ctrl.createDateObject(days[i], ctrl.formatDay), {\r\n secondary: days[i].getMonth() !== month,\r\n uid: scope.uniqueId + '-' + i\r\n });\r\n }\r\n\r\n scope.labels = new Array(7);\r\n for (var j = 0; j < 7; j++) {\r\n scope.labels[j] = {\r\n abbr: dateFilter(days[j].date, ctrl.formatDayHeader),\r\n full: dateFilter(days[j].date, 'EEEE')\r\n };\r\n }\r\n\r\n scope.title = dateFilter(ctrl.activeDate, ctrl.formatDayTitle);\r\n scope.rows = ctrl.split(days, 7);\r\n\r\n if (scope.showWeeks) {\r\n scope.weekNumbers = [];\r\n var thursdayIndex = (4 + 7 - ctrl.startingDay) % 7,\r\n numWeeks = scope.rows.length;\r\n for (var curWeek = 0; curWeek < numWeeks; curWeek++) {\r\n scope.weekNumbers.push(\r\n getISO8601WeekNumber(scope.rows[curWeek][thursdayIndex].date));\r\n }\r\n }\r\n };\r\n\r\n ctrl.compare = function(date1, date2) {\r\n return (new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()) - new Date(date2.getFullYear(), date2.getMonth(), date2.getDate()));\r\n };\r\n\r\n function getISO8601WeekNumber(date) {\r\n var checkDate = new Date(date);\r\n checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); // Thursday\r\n var time = checkDate.getTime();\r\n checkDate.setMonth(0); // Compare with Jan 1\r\n checkDate.setDate(1);\r\n return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;\r\n }\r\n\r\n ctrl.handleKeyDown = function(key, evt) {\r\n var date = ctrl.activeDate.getDate();\r\n\r\n if (key === 'left') {\r\n date = date - 1; // up\r\n } else if (key === 'up') {\r\n date = date - 7; // down\r\n } else if (key === 'right') {\r\n date = date + 1; // down\r\n } else if (key === 'down') {\r\n date = date + 7;\r\n } else if (key === 'pageup' || key === 'pagedown') {\r\n var month = ctrl.activeDate.getMonth() + (key === 'pageup' ? - 1 : 1);\r\n ctrl.activeDate.setMonth(month, 1);\r\n date = Math.min(getDaysInMonth(ctrl.activeDate.getFullYear(), ctrl.activeDate.getMonth()), date);\r\n } else if (key === 'home') {\r\n date = 1;\r\n } else if (key === 'end') {\r\n date = getDaysInMonth(ctrl.activeDate.getFullYear(), ctrl.activeDate.getMonth());\r\n }\r\n ctrl.activeDate.setDate(date);\r\n };\r\n\r\n ctrl.refreshView();\r\n }\r\n };\r\n}])\r\n\r\n.directive('monthpicker', ['dateFilter', function(dateFilter) {\r\n return {\r\n restrict: 'EA',\r\n replace: true,\r\n templateUrl: 'template/datepicker/month.html',\r\n require: '^datepicker',\r\n link: function(scope, element, attrs, ctrl) {\r\n ctrl.step = { years: 1 };\r\n ctrl.element = element;\r\n\r\n ctrl._refreshView = function() {\r\n var months = new Array(12),\r\n year = ctrl.activeDate.getFullYear(),\r\n date;\r\n\r\n for (var i = 0; i < 12; i++) {\r\n date = new Date(year, i, 1);\r\n ctrl.fixTimeZone(date);\r\n months[i] = angular.extend(ctrl.createDateObject(date, ctrl.formatMonth), {\r\n uid: scope.uniqueId + '-' + i\r\n });\r\n }\r\n\r\n scope.title = dateFilter(ctrl.activeDate, ctrl.formatMonthTitle);\r\n scope.rows = ctrl.split(months, 3);\r\n };\r\n\r\n ctrl.compare = function(date1, date2) {\r\n return new Date(date1.getFullYear(), date1.getMonth()) - new Date(date2.getFullYear(), date2.getMonth());\r\n };\r\n\r\n ctrl.handleKeyDown = function(key, evt) {\r\n var date = ctrl.activeDate.getMonth();\r\n\r\n if (key === 'left') {\r\n date = date - 1; // up\r\n } else if (key === 'up') {\r\n date = date - 3; // down\r\n } else if (key === 'right') {\r\n date = date + 1; // down\r\n } else if (key === 'down') {\r\n date = date + 3;\r\n } else if (key === 'pageup' || key === 'pagedown') {\r\n var year = ctrl.activeDate.getFullYear() + (key === 'pageup' ? - 1 : 1);\r\n ctrl.activeDate.setFullYear(year);\r\n } else if (key === 'home') {\r\n date = 0;\r\n } else if (key === 'end') {\r\n date = 11;\r\n }\r\n ctrl.activeDate.setMonth(date);\r\n };\r\n\r\n ctrl.refreshView();\r\n }\r\n };\r\n}])\r\n\r\n.directive('yearpicker', ['dateFilter', function(dateFilter) {\r\n return {\r\n restrict: 'EA',\r\n replace: true,\r\n templateUrl: 'template/datepicker/year.html',\r\n require: '^datepicker',\r\n link: function(scope, element, attrs, ctrl) {\r\n var range = ctrl.yearRange;\r\n\r\n ctrl.step = { years: range };\r\n ctrl.element = element;\r\n\r\n function getStartingYear( year ) {\r\n return parseInt((year - 1) / range, 10) * range + 1;\r\n }\r\n\r\n ctrl._refreshView = function() {\r\n var years = new Array(range), date;\r\n\r\n for (var i = 0, start = getStartingYear(ctrl.activeDate.getFullYear()); i < range; i++) {\r\n date = new Date(start + i, 0, 1);\r\n ctrl.fixTimeZone(date);\r\n years[i] = angular.extend(ctrl.createDateObject(date, ctrl.formatYear), {\r\n uid: scope.uniqueId + '-' + i\r\n });\r\n }\r\n\r\n scope.title = [years[0].label, years[range - 1].label].join(' - ');\r\n scope.rows = ctrl.split(years, 5);\r\n };\r\n\r\n ctrl.compare = function(date1, date2) {\r\n return date1.getFullYear() - date2.getFullYear();\r\n };\r\n\r\n ctrl.handleKeyDown = function(key, evt) {\r\n var date = ctrl.activeDate.getFullYear();\r\n\r\n if (key === 'left') {\r\n date = date - 1; // up\r\n } else if (key === 'up') {\r\n date = date - 5; // down\r\n } else if (key === 'right') {\r\n date = date + 1; // down\r\n } else if (key === 'down') {\r\n date = date + 5;\r\n } else if (key === 'pageup' || key === 'pagedown') {\r\n date += (key === 'pageup' ? - 1 : 1) * ctrl.step.years;\r\n } else if (key === 'home') {\r\n date = getStartingYear(ctrl.activeDate.getFullYear());\r\n } else if (key === 'end') {\r\n date = getStartingYear(ctrl.activeDate.getFullYear()) + range - 1;\r\n }\r\n ctrl.activeDate.setFullYear(date);\r\n };\r\n\r\n ctrl.refreshView();\r\n }\r\n };\r\n}])\r\n\r\n.constant('datepickerPopupConfig', {\r\n datepickerPopup: 'yyyy-MM-dd',\r\n datepickerPopupTemplateUrl: 'template/datepicker/popup.html',\r\n datepickerTemplateUrl: 'template/datepicker/datepicker.html',\r\n html5Types: {\r\n date: 'yyyy-MM-dd',\r\n 'datetime-local': 'yyyy-MM-ddTHH:mm:ss.sss',\r\n 'month': 'yyyy-MM'\r\n },\r\n currentText: 'Today',\r\n clearText: 'Clear',\r\n closeText: 'Done',\r\n closeOnDateSelection: true,\r\n appendToBody: false,\r\n showButtonBar: true,\r\n onOpenFocus: true\r\n})\r\n\r\n.directive('datepickerPopup', ['$compile', '$parse', '$document', '$rootScope', '$position', 'dateFilter', 'dateParser', 'datepickerPopupConfig', '$timeout',\r\nfunction($compile, $parse, $document, $rootScope, $position, dateFilter, dateParser, datepickerPopupConfig, $timeout) {\r\n return {\r\n restrict: 'EA',\r\n require: 'ngModel',\r\n scope: {\r\n isOpen: '=?',\r\n currentText: '@',\r\n clearText: '@',\r\n closeText: '@',\r\n dateDisabled: '&',\r\n customClass: '&'\r\n },\r\n link: function(scope, element, attrs, ngModel) {\r\n var dateFormat,\r\n closeOnDateSelection = angular.isDefined(attrs.closeOnDateSelection) ? scope.$parent.$eval(attrs.closeOnDateSelection) : datepickerPopupConfig.closeOnDateSelection,\r\n appendToBody = angular.isDefined(attrs.datepickerAppendToBody) ? scope.$parent.$eval(attrs.datepickerAppendToBody) : datepickerPopupConfig.appendToBody,\r\n onOpenFocus = angular.isDefined(attrs.onOpenFocus) ? scope.$parent.$eval(attrs.onOpenFocus) : datepickerPopupConfig.onOpenFocus,\r\n datepickerPopupTemplateUrl = angular.isDefined(attrs.datepickerPopupTemplateUrl) ? attrs.datepickerPopupTemplateUrl : datepickerPopupConfig.datepickerPopupTemplateUrl,\r\n datepickerTemplateUrl = angular.isDefined(attrs.datepickerTemplateUrl) ? attrs.datepickerTemplateUrl : datepickerPopupConfig.datepickerTemplateUrl,\r\n cache = {};\r\n\r\n scope.showButtonBar = angular.isDefined(attrs.showButtonBar) ? scope.$parent.$eval(attrs.showButtonBar) : datepickerPopupConfig.showButtonBar;\r\n\r\n scope.getText = function(key) {\r\n return scope[key + 'Text'] || datepickerPopupConfig[key + 'Text'];\r\n };\r\n\r\n scope.isDisabled = function(date) {\r\n if (date === 'today') {\r\n date = new Date();\r\n }\r\n\r\n return ((scope.watchData.minDate && scope.compare(date, cache.minDate) < 0) ||\r\n (scope.watchData.maxDate && scope.compare(date, cache.maxDate) > 0));\r\n };\r\n\r\n scope.compare = function(date1, date2) {\r\n return (new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()) - new Date(date2.getFullYear(), date2.getMonth(), date2.getDate()));\r\n };\r\n\r\n var isHtml5DateInput = false;\r\n if (datepickerPopupConfig.html5Types[attrs.type]) {\r\n dateFormat = datepickerPopupConfig.html5Types[attrs.type];\r\n isHtml5DateInput = true;\r\n } else {\r\n dateFormat = attrs.datepickerPopup || datepickerPopupConfig.datepickerPopup;\r\n attrs.$observe('datepickerPopup', function(value, oldValue) {\r\n var newDateFormat = value || datepickerPopupConfig.datepickerPopup;\r\n // Invalidate the $modelValue to ensure that formatters re-run\r\n // FIXME: Refactor when PR is merged: https://github.com/angular/angular.js/pull/10764\r\n if (newDateFormat !== dateFormat) {\r\n dateFormat = newDateFormat;\r\n ngModel.$modelValue = null;\r\n\r\n if (!dateFormat) {\r\n throw new Error('datepickerPopup must have a date format specified.');\r\n }\r\n }\r\n });\r\n }\r\n\r\n if (!dateFormat) {\r\n throw new Error('datepickerPopup must have a date format specified.');\r\n }\r\n\r\n if (isHtml5DateInput && attrs.datepickerPopup) {\r\n throw new Error('HTML5 date input types do not support custom formats.');\r\n }\r\n\r\n // popup element used to display calendar\r\n var popupEl = angular.element('
');\r\n popupEl.attr({\r\n 'ng-model': 'date',\r\n 'ng-change': 'dateSelection(date)',\r\n 'template-url': datepickerPopupTemplateUrl\r\n });\r\n\r\n function cameltoDash(string) {\r\n return string.replace(/([A-Z])/g, function($1) { return '-' + $1.toLowerCase(); });\r\n }\r\n\r\n // datepicker element\r\n var datepickerEl = angular.element(popupEl.children()[0]);\r\n datepickerEl.attr('template-url', datepickerTemplateUrl);\r\n\r\n if (isHtml5DateInput) {\r\n if (attrs.type === 'month') {\r\n datepickerEl.attr('datepicker-mode', '\"month\"');\r\n datepickerEl.attr('min-mode', 'month');\r\n }\r\n }\r\n\r\n if (attrs.datepickerOptions) {\r\n var options = scope.$parent.$eval(attrs.datepickerOptions);\r\n if (options && options.initDate) {\r\n scope.initDate = options.initDate;\r\n datepickerEl.attr('init-date', 'initDate');\r\n delete options.initDate;\r\n }\r\n angular.forEach(options, function(value, option) {\r\n datepickerEl.attr( cameltoDash(option), value );\r\n });\r\n }\r\n\r\n scope.watchData = {};\r\n angular.forEach(['minMode', 'maxMode', 'minDate', 'maxDate', 'datepickerMode', 'initDate', 'shortcutPropagation'], function(key) {\r\n if (attrs[key]) {\r\n var getAttribute = $parse(attrs[key]);\r\n scope.$parent.$watch(getAttribute, function(value) {\r\n scope.watchData[key] = value;\r\n if (key === 'minDate' || key === 'maxDate') {\r\n cache[key] = new Date(value);\r\n }\r\n });\r\n datepickerEl.attr(cameltoDash(key), 'watchData.' + key);\r\n\r\n // Propagate changes from datepicker to outside\r\n if (key === 'datepickerMode') {\r\n var setAttribute = getAttribute.assign;\r\n scope.$watch('watchData.' + key, function(value, oldvalue) {\r\n if (angular.isFunction(setAttribute) && value !== oldvalue) {\r\n setAttribute(scope.$parent, value);\r\n }\r\n });\r\n }\r\n }\r\n });\r\n if (attrs.dateDisabled) {\r\n datepickerEl.attr('date-disabled', 'dateDisabled({ date: date, mode: mode })');\r\n }\r\n\r\n if (attrs.showWeeks) {\r\n datepickerEl.attr('show-weeks', attrs.showWeeks);\r\n }\r\n\r\n if (attrs.customClass) {\r\n datepickerEl.attr('custom-class', 'customClass({ date: date, mode: mode })');\r\n }\r\n\r\n function parseDate(viewValue) {\r\n if (angular.isNumber(viewValue)) {\r\n // presumably timestamp to date object\r\n viewValue = new Date(viewValue);\r\n }\r\n\r\n if (!viewValue) {\r\n return null;\r\n } else if (angular.isDate(viewValue) && !isNaN(viewValue)) {\r\n return viewValue;\r\n } else if (angular.isString(viewValue)) {\r\n var date = dateParser.parse(viewValue, dateFormat, scope.date);\r\n if (isNaN(date)) {\r\n return undefined;\r\n } else {\r\n return date;\r\n }\r\n } else {\r\n return undefined;\r\n }\r\n }\r\n\r\n function validator(modelValue, viewValue) {\r\n var value = modelValue || viewValue;\r\n\r\n if (!attrs.ngRequired && !value) {\r\n return true;\r\n }\r\n\r\n if (angular.isNumber(value)) {\r\n value = new Date(value);\r\n }\r\n if (!value) {\r\n return true;\r\n } else if (angular.isDate(value) && !isNaN(value)) {\r\n return true;\r\n } else if (angular.isString(value)) {\r\n var date = dateParser.parse(value, dateFormat);\r\n return !isNaN(date);\r\n } else {\r\n return false;\r\n }\r\n }\r\n\r\n if (!isHtml5DateInput) {\r\n // Internal API to maintain the correct ng-invalid-[key] class\r\n ngModel.$$parserName = 'date';\r\n ngModel.$validators.date = validator;\r\n ngModel.$parsers.unshift(parseDate);\r\n ngModel.$formatters.push(function(value) {\r\n scope.date = value;\r\n return ngModel.$isEmpty(value) ? value : dateFilter(value, dateFormat);\r\n });\r\n } else {\r\n ngModel.$formatters.push(function(value) {\r\n scope.date = value;\r\n return value;\r\n });\r\n }\r\n\r\n // Inner change\r\n scope.dateSelection = function(dt) {\r\n if (angular.isDefined(dt)) {\r\n scope.date = dt;\r\n }\r\n var date = scope.date ? dateFilter(scope.date, dateFormat) : null; // Setting to NULL is necessary for form validators to function\r\n element.val(date);\r\n ngModel.$setViewValue(date);\r\n\r\n if (closeOnDateSelection) {\r\n scope.isOpen = false;\r\n element[0].focus();\r\n }\r\n };\r\n\r\n // Detect changes in the view from the text box\r\n ngModel.$viewChangeListeners.push(function() {\r\n scope.date = dateParser.parse(ngModel.$viewValue, dateFormat, scope.date);\r\n });\r\n\r\n var documentClickBind = function(event) {\r\n if (scope.isOpen && !(element[0].contains(event.target) || popupEl[0].contains(event.target))) {\r\n scope.$apply(function() {\r\n scope.isOpen = false;\r\n });\r\n }\r\n };\r\n\r\n var inputKeydownBind = function(evt) {\r\n if (evt.which === 27 && scope.isOpen) {\r\n evt.preventDefault();\r\n evt.stopPropagation();\r\n scope.$apply(function() {\r\n scope.isOpen = false;\r\n });\r\n element[0].focus();\r\n } else if (evt.which === 40 && !scope.isOpen) {\r\n evt.preventDefault();\r\n evt.stopPropagation();\r\n scope.$apply(function() {\r\n scope.isOpen = true;\r\n });\r\n }\r\n };\r\n element.bind('keydown', inputKeydownBind);\r\n\r\n scope.keydown = function(evt) {\r\n if (evt.which === 27) {\r\n scope.isOpen = false;\r\n element[0].focus();\r\n }\r\n };\r\n\r\n scope.$watch('isOpen', function(value) {\r\n if (value) {\r\n scope.position = appendToBody ? $position.offset(element) : $position.position(element);\r\n scope.position.top = scope.position.top + element.prop('offsetHeight');\r\n\r\n $timeout(function() {\r\n if (onOpenFocus) {\r\n scope.$broadcast('datepicker.focus');\r\n }\r\n $document.bind('click', documentClickBind);\r\n }, 0, false);\r\n } else {\r\n $document.unbind('click', documentClickBind);\r\n }\r\n });\r\n\r\n scope.select = function(date) {\r\n if (date === 'today') {\r\n var today = new Date();\r\n if (angular.isDate(scope.date)) {\r\n date = new Date(scope.date);\r\n date.setFullYear(today.getFullYear(), today.getMonth(), today.getDate());\r\n } else {\r\n date = new Date(today.setHours(0, 0, 0, 0));\r\n }\r\n }\r\n scope.dateSelection(date);\r\n };\r\n\r\n scope.close = function() {\r\n scope.isOpen = false;\r\n element[0].focus();\r\n };\r\n\r\n var $popup = $compile(popupEl)(scope);\r\n // Prevent jQuery cache memory leak (template is now redundant after linking)\r\n popupEl.remove();\r\n\r\n if (appendToBody) {\r\n $document.find('body').append($popup);\r\n } else {\r\n element.after($popup);\r\n }\r\n\r\n scope.$on('$destroy', function() {\r\n if (scope.isOpen === true) {\r\n if (!$rootScope.$$phase) {\r\n scope.$apply(function() {\r\n scope.isOpen = false;\r\n });\r\n }\r\n }\r\n\r\n $popup.remove();\r\n element.unbind('keydown', inputKeydownBind);\r\n $document.unbind('click', documentClickBind);\r\n });\r\n }\r\n };\r\n}])\r\n\r\n.directive('datepickerPopupWrap', function() {\r\n return {\r\n restrict:'EA',\r\n replace: true,\r\n transclude: true,\r\n templateUrl: function(element, attrs) {\r\n return attrs.templateUrl || 'template/datepicker/popup.html';\r\n }\r\n };\r\n});\r\n\r\nangular.module('ui.bootstrap.dropdown', ['ui.bootstrap.position'])\r\n\r\n.constant('dropdownConfig', {\r\n openClass: 'open'\r\n})\r\n\r\n.service('dropdownService', ['$document', '$rootScope', function($document, $rootScope) {\r\n var openScope = null;\r\n\r\n this.open = function(dropdownScope) {\r\n if (!openScope) {\r\n $document.bind('click', closeDropdown);\r\n $document.bind('keydown', keybindFilter);\r\n }\r\n\r\n if (openScope && openScope !== dropdownScope) {\r\n openScope.isOpen = false;\r\n }\r\n\r\n openScope = dropdownScope;\r\n };\r\n\r\n this.close = function(dropdownScope) {\r\n if (openScope === dropdownScope) {\r\n openScope = null;\r\n $document.unbind('click', closeDropdown);\r\n $document.unbind('keydown', keybindFilter);\r\n }\r\n };\r\n\r\n var closeDropdown = function(evt) {\r\n // This method may still be called during the same mouse event that\r\n // unbound this event handler. So check openScope before proceeding.\r\n if (!openScope) { return; }\r\n\r\n if (evt && openScope.getAutoClose() === 'disabled') { return ; }\r\n\r\n var toggleElement = openScope.getToggleElement();\r\n if (evt && toggleElement && toggleElement[0].contains(evt.target)) {\r\n return;\r\n }\r\n\r\n var dropdownElement = openScope.getDropdownElement();\r\n if (evt && openScope.getAutoClose() === 'outsideClick' &&\r\n dropdownElement && dropdownElement[0].contains(evt.target)) {\r\n return;\r\n }\r\n\r\n openScope.isOpen = false;\r\n\r\n if (!$rootScope.$$phase) {\r\n openScope.$apply();\r\n }\r\n };\r\n\r\n var keybindFilter = function(evt) {\r\n if (evt.which === 27) {\r\n openScope.focusToggleElement();\r\n closeDropdown();\r\n } else if (openScope.isKeynavEnabled() && /(38|40)/.test(evt.which) && openScope.isOpen) {\r\n evt.preventDefault();\r\n evt.stopPropagation();\r\n openScope.focusDropdownEntry(evt.which);\r\n }\r\n };\r\n}])\r\n\r\n.controller('DropdownController', ['$scope', '$attrs', '$parse', 'dropdownConfig', 'dropdownService', '$animate', '$position', '$document', '$compile', '$templateRequest', function($scope, $attrs, $parse, dropdownConfig, dropdownService, $animate, $position, $document, $compile, $templateRequest) {\r\n var self = this,\r\n scope = $scope.$new(), // create a child scope so we are not polluting original one\r\n templateScope,\r\n openClass = dropdownConfig.openClass,\r\n getIsOpen,\r\n setIsOpen = angular.noop,\r\n toggleInvoker = $attrs.onToggle ? $parse($attrs.onToggle) : angular.noop,\r\n appendToBody = false,\r\n keynavEnabled = false,\r\n selectedOption = null,\r\n body = $document.find('body');\r\n\r\n this.init = function(element) {\r\n self.$element = element;\r\n\r\n if ($attrs.isOpen) {\r\n getIsOpen = $parse($attrs.isOpen);\r\n setIsOpen = getIsOpen.assign;\r\n\r\n $scope.$watch(getIsOpen, function(value) {\r\n scope.isOpen = !!value;\r\n });\r\n }\r\n\r\n appendToBody = angular.isDefined($attrs.dropdownAppendToBody);\r\n keynavEnabled = angular.isDefined($attrs.keyboardNav);\r\n\r\n if (appendToBody && self.dropdownMenu) {\r\n body.append(self.dropdownMenu);\r\n body.addClass('dropdown');\r\n element.on('$destroy', function handleDestroyEvent() {\r\n self.dropdownMenu.remove();\r\n });\r\n }\r\n };\r\n\r\n this.toggle = function(open) {\r\n return scope.isOpen = arguments.length ? !!open : !scope.isOpen;\r\n };\r\n\r\n // Allow other directives to watch status\r\n this.isOpen = function() {\r\n return scope.isOpen;\r\n };\r\n\r\n scope.getToggleElement = function() {\r\n return self.toggleElement;\r\n };\r\n\r\n scope.getAutoClose = function() {\r\n return $attrs.autoClose || 'always'; //or 'outsideClick' or 'disabled'\r\n };\r\n\r\n scope.getElement = function() {\r\n return self.$element;\r\n };\r\n\r\n scope.isKeynavEnabled = function() {\r\n return keynavEnabled;\r\n };\r\n\r\n scope.focusDropdownEntry = function(keyCode) {\r\n var elems = self.dropdownMenu ? //If append to body is used.\r\n (angular.element(self.dropdownMenu).find('a')) :\r\n (angular.element(self.$element).find('ul').eq(0).find('a'));\r\n\r\n switch (keyCode) {\r\n case (40): {\r\n if (!angular.isNumber(self.selectedOption)) {\r\n self.selectedOption = 0;\r\n } else {\r\n self.selectedOption = (self.selectedOption === elems.length -1 ?\r\n self.selectedOption :\r\n self.selectedOption + 1);\r\n }\r\n break;\r\n }\r\n case (38): {\r\n if (!angular.isNumber(self.selectedOption)) {\r\n self.selectedOption = elems.length - 1;\r\n } else {\r\n self.selectedOption = self.selectedOption === 0 ?\r\n 0 : self.selectedOption - 1;\r\n }\r\n break;\r\n }\r\n }\r\n elems[self.selectedOption].focus();\r\n };\r\n\r\n scope.getDropdownElement = function() {\r\n return self.dropdownMenu;\r\n };\r\n\r\n scope.focusToggleElement = function() {\r\n if (self.toggleElement) {\r\n self.toggleElement[0].focus();\r\n }\r\n };\r\n\r\n scope.$watch('isOpen', function(isOpen, wasOpen) {\r\n if (appendToBody && self.dropdownMenu) {\r\n var pos = $position.positionElements(self.$element, self.dropdownMenu, 'bottom-left', true);\r\n var css = {\r\n top: pos.top + 'px',\r\n display: isOpen ? 'block' : 'none'\r\n };\r\n\r\n var rightalign = self.dropdownMenu.hasClass('dropdown-menu-right');\r\n if (!rightalign) {\r\n css.left = pos.left + 'px';\r\n css.right = 'auto';\r\n } else {\r\n css.left = 'auto';\r\n css.right = (window.innerWidth - (pos.left + self.$element.prop('offsetWidth'))) + 'px';\r\n }\r\n\r\n self.dropdownMenu.css(css);\r\n }\r\n\r\n var openContainer = appendToBody ? body : self.$element;\r\n\r\n $animate[isOpen ? 'addClass' : 'removeClass'](openContainer, openClass).then(function() {\r\n if (angular.isDefined(isOpen) && isOpen !== wasOpen) {\r\n toggleInvoker($scope, { open: !!isOpen });\r\n }\r\n });\r\n\r\n if (isOpen) {\r\n if (self.dropdownMenuTemplateUrl) {\r\n $templateRequest(self.dropdownMenuTemplateUrl).then(function(tplContent) {\r\n templateScope = scope.$new();\r\n $compile(tplContent.trim())(templateScope, function(dropdownElement) {\r\n var newEl = dropdownElement;\r\n self.dropdownMenu.replaceWith(newEl);\r\n self.dropdownMenu = newEl;\r\n });\r\n });\r\n }\r\n\r\n scope.focusToggleElement();\r\n dropdownService.open(scope);\r\n } else {\r\n if (self.dropdownMenuTemplateUrl) {\r\n if (templateScope) {\r\n templateScope.$destroy();\r\n }\r\n var newEl = angular.element('');\r\n self.dropdownMenu.replaceWith(newEl);\r\n self.dropdownMenu = newEl;\r\n }\r\n\r\n dropdownService.close(scope);\r\n self.selectedOption = null;\r\n }\r\n\r\n if (angular.isFunction(setIsOpen)) {\r\n setIsOpen($scope, isOpen);\r\n }\r\n });\r\n\r\n $scope.$on('$locationChangeSuccess', function() {\r\n if (scope.getAutoClose() !== 'disabled') {\r\n scope.isOpen = false;\r\n }\r\n });\r\n\r\n var offDestroy = $scope.$on('$destroy', function() {\r\n scope.$destroy();\r\n });\r\n scope.$on('$destroy', offDestroy);\r\n}])\r\n\r\n.directive('dropdown', function() {\r\n return {\r\n controller: 'DropdownController',\r\n link: function(scope, element, attrs, dropdownCtrl) {\r\n dropdownCtrl.init( element );\r\n element.addClass('dropdown');\r\n }\r\n };\r\n})\r\n\r\n.directive('dropdownMenu', function() {\r\n return {\r\n restrict: 'AC',\r\n require: '?^dropdown',\r\n link: function(scope, element, attrs, dropdownCtrl) {\r\n if (!dropdownCtrl) {\r\n return;\r\n }\r\n var tplUrl = attrs.templateUrl;\r\n if (tplUrl) {\r\n dropdownCtrl.dropdownMenuTemplateUrl = tplUrl;\r\n }\r\n if (!dropdownCtrl.dropdownMenu) {\r\n dropdownCtrl.dropdownMenu = element;\r\n }\r\n }\r\n };\r\n})\r\n\r\n.directive('keyboardNav', function() {\r\n return {\r\n restrict: 'A',\r\n require: '?^dropdown',\r\n link: function (scope, element, attrs, dropdownCtrl) {\r\n\r\n element.bind('keydown', function(e) {\r\n if ([38, 40].indexOf(e.which) !== -1) {\r\n e.preventDefault();\r\n e.stopPropagation();\r\n\r\n var elems = dropdownCtrl.dropdownMenu.find('a');\r\n\r\n switch (e.which) {\r\n case (40): { // Down\r\n if (!angular.isNumber(dropdownCtrl.selectedOption)) {\r\n dropdownCtrl.selectedOption = 0;\r\n } else {\r\n dropdownCtrl.selectedOption = dropdownCtrl.selectedOption === elems.length -1 ?\r\n dropdownCtrl.selectedOption : dropdownCtrl.selectedOption + 1;\r\n }\r\n break;\r\n }\r\n case (38): { // Up\r\n if (!angular.isNumber(dropdownCtrl.selectedOption)) {\r\n dropdownCtrl.selectedOption = elems.length - 1;\r\n } else {\r\n dropdownCtrl.selectedOption = dropdownCtrl.selectedOption === 0 ?\r\n 0 : dropdownCtrl.selectedOption - 1;\r\n }\r\n break;\r\n }\r\n }\r\n elems[dropdownCtrl.selectedOption].focus();\r\n }\r\n });\r\n }\r\n };\r\n})\r\n\r\n.directive('dropdownToggle', function() {\r\n return {\r\n require: '?^dropdown',\r\n link: function(scope, element, attrs, dropdownCtrl) {\r\n if (!dropdownCtrl) {\r\n return;\r\n }\r\n\r\n element.addClass('dropdown-toggle');\r\n\r\n dropdownCtrl.toggleElement = element;\r\n\r\n var toggleDropdown = function(event) {\r\n event.preventDefault();\r\n\r\n if (!element.hasClass('disabled') && !attrs.disabled) {\r\n scope.$apply(function() {\r\n dropdownCtrl.toggle();\r\n });\r\n }\r\n };\r\n\r\n element.bind('click', toggleDropdown);\r\n\r\n // WAI-ARIA\r\n element.attr({ 'aria-haspopup': true, 'aria-expanded': false });\r\n scope.$watch(dropdownCtrl.isOpen, function( isOpen ) {\r\n element.attr('aria-expanded', !!isOpen);\r\n });\r\n\r\n scope.$on('$destroy', function() {\r\n element.unbind('click', toggleDropdown);\r\n });\r\n }\r\n };\r\n});\r\n\r\nangular.module('ui.bootstrap.modal', [])\r\n\r\n/**\r\n * A helper, internal data structure that acts as a map but also allows getting / removing\r\n * elements in the LIFO order\r\n */\r\n .factory('$$stackedMap', function() {\r\n return {\r\n createNew: function() {\r\n var stack = [];\r\n\r\n return {\r\n add: function(key, value) {\r\n stack.push({\r\n key: key,\r\n value: value\r\n });\r\n },\r\n get: function(key) {\r\n for (var i = 0; i < stack.length; i++) {\r\n if (key == stack[i].key) {\r\n return stack[i];\r\n }\r\n }\r\n },\r\n keys: function() {\r\n var keys = [];\r\n for (var i = 0; i < stack.length; i++) {\r\n keys.push(stack[i].key);\r\n }\r\n return keys;\r\n },\r\n top: function() {\r\n return stack[stack.length - 1];\r\n },\r\n remove: function(key) {\r\n var idx = -1;\r\n for (var i = 0; i < stack.length; i++) {\r\n if (key == stack[i].key) {\r\n idx = i;\r\n break;\r\n }\r\n }\r\n return stack.splice(idx, 1)[0];\r\n },\r\n removeTop: function() {\r\n return stack.splice(stack.length - 1, 1)[0];\r\n },\r\n length: function() {\r\n return stack.length;\r\n }\r\n };\r\n }\r\n };\r\n })\r\n\r\n/**\r\n * A helper, internal data structure that stores all references attached to key\r\n */\r\n .factory('$$multiMap', function() {\r\n return {\r\n createNew: function() {\r\n var map = {};\r\n\r\n return {\r\n entries: function() {\r\n return Object.keys(map).map(function(key) {\r\n return {\r\n key: key,\r\n value: map[key]\r\n };\r\n });\r\n },\r\n get: function(key) {\r\n return map[key];\r\n },\r\n hasKey: function(key) {\r\n return !!map[key];\r\n },\r\n keys: function() {\r\n return Object.keys(map);\r\n },\r\n put: function(key, value) {\r\n if (!map[key]) {\r\n map[key] = [];\r\n }\r\n\r\n map[key].push(value);\r\n },\r\n remove: function(key, value) {\r\n var values = map[key];\r\n\r\n if (!values) {\r\n return;\r\n }\r\n\r\n var idx = values.indexOf(value);\r\n\r\n if (idx !== -1) {\r\n values.splice(idx, 1);\r\n }\r\n\r\n if (!values.length) {\r\n delete map[key];\r\n }\r\n }\r\n };\r\n }\r\n };\r\n })\r\n\r\n/**\r\n * A helper directive for the $modal service. It creates a backdrop element.\r\n */\r\n .directive('modalBackdrop', [\r\n '$animate', '$injector', '$modalStack',\r\n function($animate , $injector, $modalStack) {\r\n var $animateCss = null;\r\n\r\n if ($injector.has('$animateCss')) {\r\n $animateCss = $injector.get('$animateCss');\r\n }\r\n\r\n return {\r\n restrict: 'EA',\r\n replace: true,\r\n templateUrl: 'template/modal/backdrop.html',\r\n compile: function(tElement, tAttrs) {\r\n tElement.addClass(tAttrs.backdropClass);\r\n return linkFn;\r\n }\r\n };\r\n\r\n function linkFn(scope, element, attrs) {\r\n if (attrs.modalInClass) {\r\n if ($animateCss) {\r\n $animateCss(element, {\r\n addClass: attrs.modalInClass\r\n }).start();\r\n } else {\r\n $animate.addClass(element, attrs.modalInClass);\r\n }\r\n\r\n scope.$on($modalStack.NOW_CLOSING_EVENT, function(e, setIsAsync) {\r\n var done = setIsAsync();\r\n if ($animateCss) {\r\n $animateCss(element, {\r\n removeClass: attrs.modalInClass\r\n }).start().then(done);\r\n } else {\r\n $animate.removeClass(element, attrs.modalInClass).then(done);\r\n }\r\n });\r\n }\r\n }\r\n }])\r\n\r\n .directive('modalWindow', [\r\n '$modalStack', '$q', '$animate', '$injector',\r\n function($modalStack , $q , $animate, $injector) {\r\n var $animateCss = null;\r\n\r\n if ($injector.has('$animateCss')) {\r\n $animateCss = $injector.get('$animateCss');\r\n }\r\n\r\n return {\r\n restrict: 'EA',\r\n scope: {\r\n index: '@'\r\n },\r\n replace: true,\r\n transclude: true,\r\n templateUrl: function(tElement, tAttrs) {\r\n return tAttrs.templateUrl || 'template/modal/window.html';\r\n },\r\n link: function(scope, element, attrs) {\r\n element.addClass(attrs.windowClass || '');\r\n scope.size = attrs.size;\r\n\r\n scope.close = function(evt) {\r\n var modal = $modalStack.getTop();\r\n if (modal && modal.value.backdrop && modal.value.backdrop !== 'static' && (evt.target === evt.currentTarget)) {\r\n evt.preventDefault();\r\n evt.stopPropagation();\r\n $modalStack.dismiss(modal.key, 'backdrop click');\r\n }\r\n };\r\n\r\n // This property is only added to the scope for the purpose of detecting when this directive is rendered.\r\n // We can detect that by using this property in the template associated with this directive and then use\r\n // {@link Attribute#$observe} on it. For more details please see {@link TableColumnResize}.\r\n scope.$isRendered = true;\r\n\r\n // Deferred object that will be resolved when this modal is render.\r\n var modalRenderDeferObj = $q.defer();\r\n // Observe function will be called on next digest cycle after compilation, ensuring that the DOM is ready.\r\n // In order to use this way of finding whether DOM is ready, we need to observe a scope property used in modal's template.\r\n attrs.$observe('modalRender', function(value) {\r\n if (value == 'true') {\r\n modalRenderDeferObj.resolve();\r\n }\r\n });\r\n\r\n modalRenderDeferObj.promise.then(function() {\r\n var animationPromise = null;\r\n\r\n if (attrs.modalInClass) {\r\n if ($animateCss) {\r\n animationPromise = $animateCss(element, {\r\n addClass: attrs.modalInClass\r\n }).start();\r\n } else {\r\n animationPromise = $animate.addClass(element, attrs.modalInClass);\r\n }\r\n\r\n scope.$on($modalStack.NOW_CLOSING_EVENT, function(e, setIsAsync) {\r\n var done = setIsAsync();\r\n if ($animateCss) {\r\n $animateCss(element, {\r\n removeClass: attrs.modalInClass\r\n }).start().then(done);\r\n } else {\r\n $animate.removeClass(element, attrs.modalInClass).then(done);\r\n }\r\n });\r\n }\r\n\r\n\r\n $q.when(animationPromise).then(function() {\r\n var inputsWithAutofocus = element[0].querySelectorAll('[autofocus]');\r\n /**\r\n * Auto-focusing of a freshly-opened modal element causes any child elements\r\n * with the autofocus attribute to lose focus. This is an issue on touch\r\n * based devices which will show and then hide the onscreen keyboard.\r\n * Attempts to refocus the autofocus element via JavaScript will not reopen\r\n * the onscreen keyboard. Fixed by updated the focusing logic to only autofocus\r\n * the modal element if the modal does not contain an autofocus element.\r\n */\r\n if (inputsWithAutofocus.length) {\r\n inputsWithAutofocus[0].focus();\r\n } else {\r\n element[0].focus();\r\n }\r\n });\r\n\r\n // Notify {@link $modalStack} that modal is rendered.\r\n var modal = $modalStack.getTop();\r\n if (modal) {\r\n $modalStack.modalRendered(modal.key);\r\n }\r\n });\r\n }\r\n };\r\n }])\r\n\r\n .directive('modalAnimationClass', [\r\n function () {\r\n return {\r\n compile: function(tElement, tAttrs) {\r\n if (tAttrs.modalAnimation) {\r\n tElement.addClass(tAttrs.modalAnimationClass);\r\n }\r\n }\r\n };\r\n }])\r\n\r\n .directive('modalTransclude', function() {\r\n return {\r\n link: function($scope, $element, $attrs, controller, $transclude) {\r\n $transclude($scope.$parent, function(clone) {\r\n $element.empty();\r\n $element.append(clone);\r\n });\r\n }\r\n };\r\n })\r\n\r\n .factory('$modalStack', [\r\n '$animate', '$timeout', '$document', '$compile', '$rootScope',\r\n '$q',\r\n '$injector',\r\n '$$multiMap',\r\n '$$stackedMap',\r\n function($animate , $timeout , $document , $compile , $rootScope ,\r\n $q,\r\n $injector,\r\n $$multiMap,\r\n $$stackedMap) {\r\n var $animateCss = null;\r\n\r\n if ($injector.has('$animateCss')) {\r\n $animateCss = $injector.get('$animateCss');\r\n }\r\n\r\n var OPENED_MODAL_CLASS = 'modal-open';\r\n\r\n var backdropDomEl, backdropScope;\r\n var openedWindows = $$stackedMap.createNew();\r\n var openedClasses = $$multiMap.createNew();\r\n var $modalStack = {\r\n NOW_CLOSING_EVENT: 'modal.stack.now-closing'\r\n };\r\n\r\n //Modal focus behavior\r\n var focusableElementList;\r\n var focusIndex = 0;\r\n var tababbleSelector = 'a[href], area[href], input:not([disabled]), ' +\r\n 'button:not([disabled]),select:not([disabled]), textarea:not([disabled]), ' +\r\n 'iframe, object, embed, *[tabindex], *[contenteditable=true]';\r\n\r\n function backdropIndex() {\r\n var topBackdropIndex = -1;\r\n var opened = openedWindows.keys();\r\n for (var i = 0; i < opened.length; i++) {\r\n if (openedWindows.get(opened[i]).value.backdrop) {\r\n topBackdropIndex = i;\r\n }\r\n }\r\n return topBackdropIndex;\r\n }\r\n\r\n $rootScope.$watch(backdropIndex, function(newBackdropIndex) {\r\n if (backdropScope) {\r\n backdropScope.index = newBackdropIndex;\r\n }\r\n });\r\n\r\n function removeModalWindow(modalInstance, elementToReceiveFocus) {\r\n var body = $document.find('body').eq(0);\r\n var modalWindow = openedWindows.get(modalInstance).value;\r\n\r\n //clean up the stack\r\n openedWindows.remove(modalInstance);\r\n\r\n removeAfterAnimate(modalWindow.modalDomEl, modalWindow.modalScope, function() {\r\n var modalBodyClass = modalWindow.openedClass || OPENED_MODAL_CLASS;\r\n openedClasses.remove(modalBodyClass, modalInstance);\r\n body.toggleClass(modalBodyClass, openedClasses.hasKey(modalBodyClass));\r\n });\r\n checkRemoveBackdrop();\r\n\r\n //move focus to specified element if available, or else to body\r\n if (elementToReceiveFocus && elementToReceiveFocus.focus) {\r\n elementToReceiveFocus.focus();\r\n } else {\r\n body.focus();\r\n }\r\n }\r\n\r\n function checkRemoveBackdrop() {\r\n //remove backdrop if no longer needed\r\n if (backdropDomEl && backdropIndex() == -1) {\r\n var backdropScopeRef = backdropScope;\r\n removeAfterAnimate(backdropDomEl, backdropScope, function() {\r\n backdropScopeRef = null;\r\n });\r\n backdropDomEl = undefined;\r\n backdropScope = undefined;\r\n }\r\n }\r\n\r\n function removeAfterAnimate(domEl, scope, done) {\r\n var asyncDeferred;\r\n var asyncPromise = null;\r\n var setIsAsync = function() {\r\n if (!asyncDeferred) {\r\n asyncDeferred = $q.defer();\r\n asyncPromise = asyncDeferred.promise;\r\n }\r\n\r\n return function asyncDone() {\r\n asyncDeferred.resolve();\r\n };\r\n };\r\n scope.$broadcast($modalStack.NOW_CLOSING_EVENT, setIsAsync);\r\n\r\n // Note that it's intentional that asyncPromise might be null.\r\n // That's when setIsAsync has not been called during the\r\n // NOW_CLOSING_EVENT broadcast.\r\n return $q.when(asyncPromise).then(afterAnimating);\r\n\r\n function afterAnimating() {\r\n if (afterAnimating.done) {\r\n return;\r\n }\r\n afterAnimating.done = true;\r\n\r\n if ($animateCss) {\r\n $animateCss(domEl, {\r\n event: 'leave'\r\n }).start().then(function() {\r\n domEl.remove();\r\n });\r\n } else {\r\n $animate.leave(domEl);\r\n }\r\n scope.$destroy();\r\n if (done) {\r\n done();\r\n }\r\n }\r\n }\r\n\r\n $document.bind('keydown', function(evt) {\r\n if (evt.isDefaultPrevented()) {\r\n return evt;\r\n }\r\n\r\n var modal = openedWindows.top();\r\n if (modal && modal.value.keyboard) {\r\n switch (evt.which){\r\n case 27: {\r\n evt.preventDefault();\r\n $rootScope.$apply(function() {\r\n $modalStack.dismiss(modal.key, 'escape key press');\r\n });\r\n break;\r\n }\r\n case 9: {\r\n $modalStack.loadFocusElementList(modal);\r\n var focusChanged = false;\r\n if (evt.shiftKey) {\r\n if ($modalStack.isFocusInFirstItem(evt)) {\r\n focusChanged = $modalStack.focusLastFocusableElement();\r\n }\r\n } else {\r\n if ($modalStack.isFocusInLastItem(evt)) {\r\n focusChanged = $modalStack.focusFirstFocusableElement();\r\n }\r\n }\r\n\r\n if (focusChanged) {\r\n evt.preventDefault();\r\n evt.stopPropagation();\r\n }\r\n break;\r\n }\r\n }\r\n }\r\n });\r\n\r\n $modalStack.open = function(modalInstance, modal) {\r\n var modalOpener = $document[0].activeElement,\r\n modalBodyClass = modal.openedClass || OPENED_MODAL_CLASS;\r\n\r\n openedWindows.add(modalInstance, {\r\n deferred: modal.deferred,\r\n renderDeferred: modal.renderDeferred,\r\n modalScope: modal.scope,\r\n backdrop: modal.backdrop,\r\n keyboard: modal.keyboard,\r\n openedClass: modal.openedClass\r\n });\r\n\r\n openedClasses.put(modalBodyClass, modalInstance);\r\n\r\n var body = $document.find('body').eq(0),\r\n currBackdropIndex = backdropIndex();\r\n\r\n if (currBackdropIndex >= 0 && !backdropDomEl) {\r\n backdropScope = $rootScope.$new(true);\r\n backdropScope.index = currBackdropIndex;\r\n var angularBackgroundDomEl = angular.element('
');\r\n angularBackgroundDomEl.attr('backdrop-class', modal.backdropClass);\r\n if (modal.animation) {\r\n angularBackgroundDomEl.attr('modal-animation', 'true');\r\n }\r\n backdropDomEl = $compile(angularBackgroundDomEl)(backdropScope);\r\n body.append(backdropDomEl);\r\n }\r\n\r\n var angularDomEl = angular.element('
');\r\n angularDomEl.attr({\r\n 'template-url': modal.windowTemplateUrl,\r\n 'window-class': modal.windowClass,\r\n 'size': modal.size,\r\n 'index': openedWindows.length() - 1,\r\n 'animate': 'animate'\r\n }).html(modal.content);\r\n if (modal.animation) {\r\n angularDomEl.attr('modal-animation', 'true');\r\n }\r\n\r\n var modalDomEl = $compile(angularDomEl)(modal.scope);\r\n openedWindows.top().value.modalDomEl = modalDomEl;\r\n openedWindows.top().value.modalOpener = modalOpener;\r\n body.append(modalDomEl);\r\n body.addClass(modalBodyClass);\r\n\r\n $modalStack.clearFocusListCache();\r\n };\r\n\r\n function broadcastClosing(modalWindow, resultOrReason, closing) {\r\n return !modalWindow.value.modalScope.$broadcast('modal.closing', resultOrReason, closing).defaultPrevented;\r\n }\r\n\r\n $modalStack.close = function(modalInstance, result) {\r\n var modalWindow = openedWindows.get(modalInstance);\r\n if (modalWindow && broadcastClosing(modalWindow, result, true)) {\r\n modalWindow.value.modalScope.$$uibDestructionScheduled = true;\r\n modalWindow.value.deferred.resolve(result);\r\n removeModalWindow(modalInstance, modalWindow.value.modalOpener);\r\n return true;\r\n }\r\n return !modalWindow;\r\n };\r\n\r\n $modalStack.dismiss = function(modalInstance, reason) {\r\n var modalWindow = openedWindows.get(modalInstance);\r\n if (modalWindow && broadcastClosing(modalWindow, reason, false)) {\r\n modalWindow.value.modalScope.$$uibDestructionScheduled = true;\r\n modalWindow.value.deferred.reject(reason);\r\n removeModalWindow(modalInstance, modalWindow.value.modalOpener);\r\n return true;\r\n }\r\n return !modalWindow;\r\n };\r\n\r\n $modalStack.dismissAll = function(reason) {\r\n var topModal = this.getTop();\r\n while (topModal && this.dismiss(topModal.key, reason)) {\r\n topModal = this.getTop();\r\n }\r\n };\r\n\r\n $modalStack.getTop = function() {\r\n return openedWindows.top();\r\n };\r\n\r\n $modalStack.modalRendered = function(modalInstance) {\r\n var modalWindow = openedWindows.get(modalInstance);\r\n if (modalWindow) {\r\n modalWindow.value.renderDeferred.resolve();\r\n }\r\n };\r\n\r\n $modalStack.focusFirstFocusableElement = function() {\r\n if (focusableElementList.length > 0) {\r\n focusableElementList[0].focus();\r\n return true;\r\n }\r\n return false;\r\n };\r\n $modalStack.focusLastFocusableElement = function() {\r\n if (focusableElementList.length > 0) {\r\n focusableElementList[focusableElementList.length - 1].focus();\r\n return true;\r\n }\r\n return false;\r\n };\r\n\r\n $modalStack.isFocusInFirstItem = function(evt) {\r\n if (focusableElementList.length > 0) {\r\n return (evt.target || evt.srcElement) == focusableElementList[0];\r\n }\r\n return false;\r\n };\r\n\r\n $modalStack.isFocusInLastItem = function(evt) {\r\n if (focusableElementList.length > 0) {\r\n return (evt.target || evt.srcElement) == focusableElementList[focusableElementList.length - 1];\r\n }\r\n return false;\r\n };\r\n\r\n $modalStack.clearFocusListCache = function() {\r\n focusableElementList = [];\r\n focusIndex = 0;\r\n };\r\n\r\n $modalStack.loadFocusElementList = function(modalWindow) {\r\n if (focusableElementList === undefined || !focusableElementList.length0) {\r\n if (modalWindow) {\r\n var modalDomE1 = modalWindow.value.modalDomEl;\r\n if (modalDomE1 && modalDomE1.length) {\r\n focusableElementList = modalDomE1[0].querySelectorAll(tababbleSelector);\r\n }\r\n }\r\n }\r\n };\r\n\r\n return $modalStack;\r\n }])\r\n\r\n .provider('$modal', function() {\r\n var $modalProvider = {\r\n options: {\r\n animation: true,\r\n backdrop: true, //can also be false or 'static'\r\n keyboard: true\r\n },\r\n $get: ['$injector', '$rootScope', '$q', '$templateRequest', '$controller', '$modalStack',\r\n function ($injector, $rootScope, $q, $templateRequest, $controller, $modalStack) {\r\n var $modal = {};\r\n\r\n function getTemplatePromise(options) {\r\n return options.template ? $q.when(options.template) :\r\n $templateRequest(angular.isFunction(options.templateUrl) ? (options.templateUrl)() : options.templateUrl);\r\n }\r\n\r\n function getResolvePromises(resolves) {\r\n var promisesArr = [];\r\n angular.forEach(resolves, function(value) {\r\n if (angular.isFunction(value) || angular.isArray(value)) {\r\n promisesArr.push($q.when($injector.invoke(value)));\r\n } else if (angular.isString(value)) {\r\n promisesArr.push($q.when($injector.get(value)));\r\n } else {\r\n promisesArr.push($q.when(value));\r\n }\r\n });\r\n return promisesArr;\r\n }\r\n\r\n var promiseChain = null;\r\n $modal.getPromiseChain = function() {\r\n return promiseChain;\r\n };\r\n\r\n $modal.open = function (modalOptions) {\r\n\r\n var modalResultDeferred = $q.defer();\r\n var modalOpenedDeferred = $q.defer();\r\n var modalRenderDeferred = $q.defer();\r\n\r\n //prepare an instance of a modal to be injected into controllers and returned to a caller\r\n var modalInstance = {\r\n result: modalResultDeferred.promise,\r\n opened: modalOpenedDeferred.promise,\r\n rendered: modalRenderDeferred.promise,\r\n close: function (result) {\r\n return $modalStack.close(modalInstance, result);\r\n },\r\n dismiss: function (reason) {\r\n return $modalStack.dismiss(modalInstance, reason);\r\n }\r\n };\r\n\r\n //merge and clean up options\r\n modalOptions = angular.extend({}, $modalProvider.options, modalOptions);\r\n modalOptions.resolve = modalOptions.resolve || {};\r\n\r\n //verify options\r\n if (!modalOptions.template && !modalOptions.templateUrl) {\r\n throw new Error('One of template or templateUrl options is required.');\r\n }\r\n\r\n var templateAndResolvePromise =\r\n $q.all([getTemplatePromise(modalOptions)].concat(getResolvePromises(modalOptions.resolve)));\r\n\r\n // Wait for the resolution of the existing promise chain.\r\n // Then switch to our own combined promise dependency (regardless of how the previous modal fared).\r\n // Then add to $modalStack and resolve opened.\r\n // Finally clean up the chain variable if no subsequent modal has overwritten it.\r\n var samePromise;\r\n samePromise = promiseChain = $q.all([promiseChain])\r\n .then(function() { return templateAndResolvePromise; }, function() { return templateAndResolvePromise; })\r\n .then(function resolveSuccess(tplAndVars) {\r\n\r\n var modalScope = (modalOptions.scope || $rootScope).$new();\r\n modalScope.$close = modalInstance.close;\r\n modalScope.$dismiss = modalInstance.dismiss;\r\n\r\n modalScope.$on('$destroy', function() {\r\n if (!modalScope.$$uibDestructionScheduled) {\r\n modalScope.$dismiss('$uibUnscheduledDestruction');\r\n }\r\n });\r\n\r\n var ctrlInstance, ctrlLocals = {};\r\n var resolveIter = 1;\r\n\r\n //controllers\r\n if (modalOptions.controller) {\r\n ctrlLocals.$scope = modalScope;\r\n ctrlLocals.$modalInstance = modalInstance;\r\n angular.forEach(modalOptions.resolve, function(value, key) {\r\n ctrlLocals[key] = tplAndVars[resolveIter++];\r\n });\r\n\r\n ctrlInstance = $controller(modalOptions.controller, ctrlLocals);\r\n if (modalOptions.controllerAs) {\r\n if (modalOptions.bindToController) {\r\n angular.extend(ctrlInstance, modalScope);\r\n }\r\n\r\n modalScope[modalOptions.controllerAs] = ctrlInstance;\r\n }\r\n }\r\n\r\n $modalStack.open(modalInstance, {\r\n scope: modalScope,\r\n deferred: modalResultDeferred,\r\n renderDeferred: modalRenderDeferred,\r\n content: tplAndVars[0],\r\n animation: modalOptions.animation,\r\n backdrop: modalOptions.backdrop,\r\n keyboard: modalOptions.keyboard,\r\n backdropClass: modalOptions.backdropClass,\r\n windowClass: modalOptions.windowClass,\r\n windowTemplateUrl: modalOptions.windowTemplateUrl,\r\n size: modalOptions.size,\r\n openedClass: modalOptions.openedClass\r\n });\r\n modalOpenedDeferred.resolve(true);\r\n\r\n }, function resolveError(reason) {\r\n modalOpenedDeferred.reject(reason);\r\n modalResultDeferred.reject(reason);\r\n })\r\n .finally(function() {\r\n if (promiseChain === samePromise) {\r\n promiseChain = null;\r\n }\r\n });\r\n\r\n return modalInstance;\r\n };\r\n\r\n return $modal;\r\n }]\r\n };\r\n\r\n return $modalProvider;\r\n });\r\n\r\nangular.module('ui.bootstrap.pagination', [])\r\n.controller('PaginationController', ['$scope', '$attrs', '$parse', function($scope, $attrs, $parse) {\r\n var self = this,\r\n ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl\r\n setNumPages = $attrs.numPages ? $parse($attrs.numPages).assign : angular.noop;\r\n\r\n this.init = function(ngModelCtrl_, config) {\r\n ngModelCtrl = ngModelCtrl_;\r\n this.config = config;\r\n\r\n ngModelCtrl.$render = function() {\r\n self.render();\r\n };\r\n\r\n if ($attrs.itemsPerPage) {\r\n $scope.$parent.$watch($parse($attrs.itemsPerPage), function(value) {\r\n self.itemsPerPage = parseInt(value, 10);\r\n $scope.totalPages = self.calculateTotalPages();\r\n });\r\n } else {\r\n this.itemsPerPage = config.itemsPerPage;\r\n }\r\n\r\n $scope.$watch('totalItems', function() {\r\n $scope.totalPages = self.calculateTotalPages();\r\n });\r\n\r\n $scope.$watch('totalPages', function(value) {\r\n setNumPages($scope.$parent, value); // Readonly variable\r\n\r\n if ( $scope.page > value ) {\r\n $scope.selectPage(value);\r\n } else {\r\n ngModelCtrl.$render();\r\n }\r\n });\r\n };\r\n\r\n this.calculateTotalPages = function() {\r\n var totalPages = this.itemsPerPage < 1 ? 1 : Math.ceil($scope.totalItems / this.itemsPerPage);\r\n return Math.max(totalPages || 0, 1);\r\n };\r\n\r\n this.render = function() {\r\n $scope.page = parseInt(ngModelCtrl.$viewValue, 10) || 1;\r\n };\r\n\r\n $scope.selectPage = function(page, evt) {\r\n if (evt) {\r\n evt.preventDefault();\r\n }\r\n\r\n var clickAllowed = !$scope.ngDisabled || !evt;\r\n if (clickAllowed && $scope.page !== page && page > 0 && page <= $scope.totalPages) {\r\n if (evt && evt.target) {\r\n evt.target.blur();\r\n }\r\n ngModelCtrl.$setViewValue(page);\r\n ngModelCtrl.$render();\r\n }\r\n };\r\n\r\n $scope.getText = function(key) {\r\n return $scope[key + 'Text'] || self.config[key + 'Text'];\r\n };\r\n\r\n $scope.noPrevious = function() {\r\n return $scope.page === 1;\r\n };\r\n\r\n $scope.noNext = function() {\r\n return $scope.page === $scope.totalPages;\r\n };\r\n}])\r\n\r\n.constant('paginationConfig', {\r\n itemsPerPage: 10,\r\n boundaryLinks: false,\r\n directionLinks: true,\r\n firstText: 'First',\r\n previousText: 'Previous',\r\n nextText: 'Next',\r\n lastText: 'Last',\r\n rotate: true\r\n})\r\n\r\n.directive('pagination', ['$parse', 'paginationConfig', function($parse, paginationConfig) {\r\n return {\r\n restrict: 'EA',\r\n scope: {\r\n totalItems: '=',\r\n firstText: '@',\r\n previousText: '@',\r\n nextText: '@',\r\n lastText: '@',\r\n ngDisabled:'='\r\n },\r\n require: ['pagination', '?ngModel'],\r\n controller: 'PaginationController',\r\n controllerAs: 'pagination',\r\n templateUrl: function(element, attrs) {\r\n return attrs.templateUrl || 'template/pagination/pagination.html';\r\n },\r\n replace: true,\r\n link: function(scope, element, attrs, ctrls) {\r\n var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1];\r\n\r\n if (!ngModelCtrl) {\r\n return; // do nothing if no ng-model\r\n }\r\n\r\n // Setup configuration parameters\r\n var maxSize = angular.isDefined(attrs.maxSize) ? scope.$parent.$eval(attrs.maxSize) : paginationConfig.maxSize,\r\n rotate = angular.isDefined(attrs.rotate) ? scope.$parent.$eval(attrs.rotate) : paginationConfig.rotate;\r\n scope.boundaryLinks = angular.isDefined(attrs.boundaryLinks) ? scope.$parent.$eval(attrs.boundaryLinks) : paginationConfig.boundaryLinks;\r\n scope.directionLinks = angular.isDefined(attrs.directionLinks) ? scope.$parent.$eval(attrs.directionLinks) : paginationConfig.directionLinks;\r\n\r\n paginationCtrl.init(ngModelCtrl, paginationConfig);\r\n\r\n if (attrs.maxSize) {\r\n scope.$parent.$watch($parse(attrs.maxSize), function(value) {\r\n maxSize = parseInt(value, 10);\r\n paginationCtrl.render();\r\n });\r\n }\r\n\r\n // Create page object used in template\r\n function makePage(number, text, isActive) {\r\n return {\r\n number: number,\r\n text: text,\r\n active: isActive\r\n };\r\n }\r\n\r\n function getPages(currentPage, totalPages) {\r\n var pages = [];\r\n\r\n // Default page limits\r\n var startPage = 1, endPage = totalPages;\r\n var isMaxSized = angular.isDefined(maxSize) && maxSize < totalPages;\r\n\r\n // recompute if maxSize\r\n if (isMaxSized) {\r\n if (rotate) {\r\n // Current page is displayed in the middle of the visible ones\r\n startPage = Math.max(currentPage - Math.floor(maxSize/2), 1);\r\n endPage = startPage + maxSize - 1;\r\n\r\n // Adjust if limit is exceeded\r\n if (endPage > totalPages) {\r\n endPage = totalPages;\r\n startPage = endPage - maxSize + 1;\r\n }\r\n } else {\r\n // Visible pages are paginated with maxSize\r\n startPage = ((Math.ceil(currentPage / maxSize) - 1) * maxSize) + 1;\r\n\r\n // Adjust last page if limit is exceeded\r\n endPage = Math.min(startPage + maxSize - 1, totalPages);\r\n }\r\n }\r\n\r\n // Add page number links\r\n for (var number = startPage; number <= endPage; number++) {\r\n var page = makePage(number, number, number === currentPage);\r\n pages.push(page);\r\n }\r\n\r\n // Add links to move between page sets\r\n if (isMaxSized && ! rotate) {\r\n if (startPage > 1) {\r\n var previousPageSet = makePage(startPage - 1, '...', false);\r\n pages.unshift(previousPageSet);\r\n }\r\n\r\n if (endPage < totalPages) {\r\n var nextPageSet = makePage(endPage + 1, '...', false);\r\n pages.push(nextPageSet);\r\n }\r\n }\r\n\r\n return pages;\r\n }\r\n\r\n var originalRender = paginationCtrl.render;\r\n paginationCtrl.render = function() {\r\n originalRender();\r\n if (scope.page > 0 && scope.page <= scope.totalPages) {\r\n scope.pages = getPages(scope.page, scope.totalPages);\r\n }\r\n };\r\n }\r\n };\r\n}])\r\n\r\n.constant('pagerConfig', {\r\n itemsPerPage: 10,\r\n previousText: '« Previous',\r\n nextText: 'Next »',\r\n align: true\r\n})\r\n\r\n.directive('pager', ['pagerConfig', function(pagerConfig) {\r\n return {\r\n restrict: 'EA',\r\n scope: {\r\n totalItems: '=',\r\n previousText: '@',\r\n nextText: '@',\r\n ngDisabled: '='\r\n },\r\n require: ['pager', '?ngModel'],\r\n controller: 'PaginationController',\r\n controllerAs: 'pagination',\r\n templateUrl: function(element, attrs) {\r\n return attrs.templateUrl || 'template/pagination/pager.html';\r\n },\r\n replace: true,\r\n link: function(scope, element, attrs, ctrls) {\r\n var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1];\r\n\r\n if (!ngModelCtrl) {\r\n return; // do nothing if no ng-model\r\n }\r\n\r\n scope.align = angular.isDefined(attrs.align) ? scope.$parent.$eval(attrs.align) : pagerConfig.align;\r\n paginationCtrl.init(ngModelCtrl, pagerConfig);\r\n }\r\n };\r\n}]);\r\n\r\n/**\r\n * The following features are still outstanding: animation as a\r\n * function, placement as a function, inside, support for more triggers than\r\n * just mouse enter/leave, html tooltips, and selector delegation.\r\n */\r\nangular.module('ui.bootstrap.tooltip', ['ui.bootstrap.position', 'ui.bootstrap.bindHtml'])\r\n\r\n/**\r\n * The $tooltip service creates tooltip- and popover-like directives as well as\r\n * houses global options for them.\r\n */\r\n.provider('$tooltip', function() {\r\n // The default options tooltip and popover.\r\n var defaultOptions = {\r\n placement: 'top',\r\n animation: true,\r\n popupDelay: 0,\r\n useContentExp: false\r\n };\r\n\r\n // Default hide triggers for each show trigger\r\n var triggerMap = {\r\n 'mouseenter': 'mouseleave',\r\n 'click': 'click',\r\n 'focus': 'blur',\r\n 'none': ''\r\n };\r\n\r\n // The options specified to the provider globally.\r\n var globalOptions = {};\r\n\r\n /**\r\n * `options({})` allows global configuration of all tooltips in the\r\n * application.\r\n *\r\n * var app = angular.module( 'App', ['ui.bootstrap.tooltip'], function( $tooltipProvider ) {\r\n * // place tooltips left instead of top by default\r\n * $tooltipProvider.options( { placement: 'left' } );\r\n * });\r\n */\r\n\tthis.options = function(value) {\r\n\t\tangular.extend(globalOptions, value);\r\n\t};\r\n\r\n /**\r\n * This allows you to extend the set of trigger mappings available. E.g.:\r\n *\r\n * $tooltipProvider.setTriggers( 'openTrigger': 'closeTrigger' );\r\n */\r\n this.setTriggers = function setTriggers(triggers) {\r\n angular.extend(triggerMap, triggers);\r\n };\r\n\r\n /**\r\n * This is a helper function for translating camel-case to snake-case.\r\n */\r\n function snake_case(name) {\r\n var regexp = /[A-Z]/g;\r\n var separator = '-';\r\n return name.replace(regexp, function(letter, pos) {\r\n return (pos ? separator : '') + letter.toLowerCase();\r\n });\r\n }\r\n\r\n /**\r\n * Returns the actual instance of the $tooltip service.\r\n * TODO support multiple triggers\r\n */\r\n this.$get = ['$window', '$compile', '$timeout', '$document', '$position', '$interpolate', '$rootScope', '$parse', function($window, $compile, $timeout, $document, $position, $interpolate, $rootScope, $parse) {\r\n return function $tooltip(type, prefix, defaultTriggerShow, options) {\r\n options = angular.extend({}, defaultOptions, globalOptions, options);\r\n\r\n /**\r\n * Returns an object of show and hide triggers.\r\n *\r\n * If a trigger is supplied,\r\n * it is used to show the tooltip; otherwise, it will use the `trigger`\r\n * option passed to the `$tooltipProvider.options` method; else it will\r\n * default to the trigger supplied to this directive factory.\r\n *\r\n * The hide trigger is based on the show trigger. If the `trigger` option\r\n * was passed to the `$tooltipProvider.options` method, it will use the\r\n * mapped trigger from `triggerMap` or the passed trigger if the map is\r\n * undefined; otherwise, it uses the `triggerMap` value of the show\r\n * trigger; else it will just use the show trigger.\r\n */\r\n function getTriggers(trigger) {\r\n var show = (trigger || options.trigger || defaultTriggerShow).split(' ');\r\n var hide = show.map(function(trigger) {\r\n return triggerMap[trigger] || trigger;\r\n });\r\n return {\r\n show: show,\r\n hide: hide\r\n };\r\n }\r\n\r\n var directiveName = snake_case(type);\r\n\r\n var startSym = $interpolate.startSymbol();\r\n var endSym = $interpolate.endSymbol();\r\n var template =\r\n '
'+\r\n '
';\r\n\r\n return {\r\n restrict: 'EA',\r\n compile: function(tElem, tAttrs) {\r\n var tooltipLinker = $compile( template );\r\n\r\n return function link(scope, element, attrs, tooltipCtrl) {\r\n var tooltip;\r\n var tooltipLinkedScope;\r\n var transitionTimeout;\r\n var popupTimeout;\r\n var positionTimeout;\r\n var appendToBody = angular.isDefined(options.appendToBody) ? options.appendToBody : false;\r\n var triggers = getTriggers(undefined);\r\n var hasEnableExp = angular.isDefined(attrs[prefix + 'Enable']);\r\n var ttScope = scope.$new(true);\r\n var repositionScheduled = false;\r\n var isOpenExp = angular.isDefined(attrs[prefix + 'IsOpen']) ? $parse(attrs[prefix + 'IsOpen']) : false;\r\n\r\n var positionTooltip = function() {\r\n if (!tooltip) { return; }\r\n\r\n if (!positionTimeout) {\r\n positionTimeout = $timeout(function() {\r\n // Reset the positioning and box size for correct width and height values.\r\n tooltip.css({ top: 0, left: 0, width: 'auto', height: 'auto' });\r\n\r\n var ttBox = $position.position(tooltip);\r\n var ttCss = $position.positionElements(element, tooltip, ttScope.placement, appendToBody);\r\n ttCss.top += 'px';\r\n ttCss.left += 'px';\r\n\r\n ttCss.width = ttBox.width + 'px';\r\n ttCss.height = ttBox.height + 'px';\r\n\r\n // Now set the calculated positioning and size.\r\n tooltip.css(ttCss);\r\n\r\n positionTimeout = null;\r\n\r\n }, 0, false);\r\n }\r\n };\r\n\r\n // Set up the correct scope to allow transclusion later\r\n ttScope.origScope = scope;\r\n\r\n // By default, the tooltip is not open.\r\n // TODO add ability to start tooltip opened\r\n ttScope.isOpen = false;\r\n\r\n function toggleTooltipBind() {\r\n if (!ttScope.isOpen) {\r\n showTooltipBind();\r\n } else {\r\n hideTooltipBind();\r\n }\r\n }\r\n\r\n // Show the tooltip with delay if specified, otherwise show it immediately\r\n function showTooltipBind() {\r\n if (hasEnableExp && !scope.$eval(attrs[prefix + 'Enable'])) {\r\n return;\r\n }\r\n\r\n prepareTooltip();\r\n\r\n if (ttScope.popupDelay) {\r\n // Do nothing if the tooltip was already scheduled to pop-up.\r\n // This happens if show is triggered multiple times before any hide is triggered.\r\n if (!popupTimeout) {\r\n popupTimeout = $timeout(show, ttScope.popupDelay, false);\r\n }\r\n } else {\r\n show();\r\n }\r\n }\r\n\r\n function hideTooltipBind () {\r\n hide();\r\n if (!$rootScope.$$phase) {\r\n $rootScope.$digest();\r\n }\r\n }\r\n\r\n // Show the tooltip popup element.\r\n function show() {\r\n popupTimeout = null;\r\n\r\n // If there is a pending remove transition, we must cancel it, lest the\r\n // tooltip be mysteriously removed.\r\n if (transitionTimeout) {\r\n $timeout.cancel(transitionTimeout);\r\n transitionTimeout = null;\r\n }\r\n\r\n // Don't show empty tooltips.\r\n if (!(options.useContentExp ? ttScope.contentExp() : ttScope.content)) {\r\n return angular.noop;\r\n }\r\n\r\n createTooltip();\r\n\r\n // And show the tooltip.\r\n ttScope.isOpen = true;\r\n if (isOpenExp) {\r\n isOpenExp.assign(ttScope.origScope, ttScope.isOpen);\r\n }\r\n\r\n if (!$rootScope.$$phase) {\r\n ttScope.$apply(); // digest required as $apply is not called\r\n }\r\n\r\n tooltip.css({ display: 'block' });\r\n\r\n positionTooltip();\r\n }\r\n\r\n // Hide the tooltip popup element.\r\n function hide() {\r\n // First things first: we don't show it anymore.\r\n ttScope.isOpen = false;\r\n if (isOpenExp) {\r\n isOpenExp.assign(ttScope.origScope, ttScope.isOpen);\r\n }\r\n\r\n //if tooltip is going to be shown after delay, we must cancel this\r\n $timeout.cancel(popupTimeout);\r\n popupTimeout = null;\r\n\r\n $timeout.cancel(positionTimeout);\r\n positionTimeout = null;\r\n\r\n // And now we remove it from the DOM. However, if we have animation, we\r\n // need to wait for it to expire beforehand.\r\n // FIXME: this is a placeholder for a port of the transitions library.\r\n if (ttScope.animation) {\r\n if (!transitionTimeout) {\r\n transitionTimeout = $timeout(removeTooltip, 500);\r\n }\r\n } else {\r\n removeTooltip();\r\n }\r\n }\r\n\r\n function createTooltip() {\r\n // There can only be one tooltip element per directive shown at once.\r\n if (tooltip) {\r\n removeTooltip();\r\n }\r\n tooltipLinkedScope = ttScope.$new();\r\n tooltip = tooltipLinker(tooltipLinkedScope, function(tooltip) {\r\n if (appendToBody) {\r\n $document.find('body').append(tooltip);\r\n } else {\r\n element.after(tooltip);\r\n }\r\n });\r\n\r\n if (options.useContentExp) {\r\n tooltipLinkedScope.$watch('contentExp()', function(val) {\r\n if (!val && ttScope.isOpen) {\r\n hide();\r\n }\r\n });\r\n\r\n tooltipLinkedScope.$watch(function() {\r\n if (!repositionScheduled) {\r\n repositionScheduled = true;\r\n tooltipLinkedScope.$$postDigest(function() {\r\n repositionScheduled = false;\r\n if (ttScope.isOpen) {\r\n positionTooltip();\r\n }\r\n });\r\n }\r\n });\r\n\r\n }\r\n }\r\n\r\n function removeTooltip() {\r\n transitionTimeout = null;\r\n if (tooltip) {\r\n tooltip.remove();\r\n tooltip = null;\r\n }\r\n if (tooltipLinkedScope) {\r\n tooltipLinkedScope.$destroy();\r\n tooltipLinkedScope = null;\r\n }\r\n }\r\n\r\n function prepareTooltip() {\r\n prepPopupClass();\r\n prepPlacement();\r\n prepPopupDelay();\r\n }\r\n\r\n ttScope.contentExp = function() {\r\n return scope.$eval(attrs[type]);\r\n };\r\n\r\n /**\r\n * Observe the relevant attributes.\r\n */\r\n if (!options.useContentExp) {\r\n attrs.$observe(type, function(val) {\r\n ttScope.content = val;\r\n\r\n if (!val && ttScope.isOpen) {\r\n hide();\r\n } else {\r\n positionTooltip();\r\n }\r\n });\r\n }\r\n\r\n attrs.$observe('disabled', function(val) {\r\n if (popupTimeout && val) {\r\n $timeout.cancel(popupTimeout);\r\n popupTimeout = null;\r\n }\r\n\r\n if (val && ttScope.isOpen) {\r\n hide();\r\n }\r\n });\r\n\r\n attrs.$observe(prefix + 'Title', function(val) {\r\n ttScope.title = val;\r\n positionTooltip();\r\n });\r\n\r\n attrs.$observe(prefix + 'Placement', function() {\r\n if (ttScope.isOpen) {\r\n prepPlacement();\r\n positionTooltip();\r\n }\r\n });\r\n\r\n if (isOpenExp) {\r\n scope.$watch(isOpenExp, function(val) {\r\n if (val !== ttScope.isOpen) {\r\n toggleTooltipBind();\r\n }\r\n });\r\n }\r\n\r\n function prepPopupClass() {\r\n ttScope.popupClass = attrs[prefix + 'Class'];\r\n }\r\n\r\n function prepPlacement() {\r\n var val = attrs[prefix + 'Placement'];\r\n ttScope.placement = angular.isDefined(val) ? val : options.placement;\r\n }\r\n\r\n function prepPopupDelay() {\r\n var val = attrs[prefix + 'PopupDelay'];\r\n var delay = parseInt(val, 10);\r\n ttScope.popupDelay = !isNaN(delay) ? delay : options.popupDelay;\r\n }\r\n\r\n var unregisterTriggers = function() {\r\n triggers.show.forEach(function(trigger) {\r\n element.unbind(trigger, showTooltipBind);\r\n });\r\n triggers.hide.forEach(function(trigger) {\r\n element.unbind(trigger, hideTooltipBind);\r\n });\r\n };\r\n\r\n function prepTriggers() {\r\n var val = attrs[prefix + 'Trigger'];\r\n unregisterTriggers();\r\n\r\n triggers = getTriggers(val);\r\n\r\n if (triggers.show !== 'none') {\r\n triggers.show.forEach(function(trigger, idx) {\r\n // Using raw addEventListener due to jqLite/jQuery bug - #4060\r\n if (trigger === triggers.hide[idx]) {\r\n element[0].addEventListener(trigger, toggleTooltipBind);\r\n } else if (trigger) {\r\n element[0].addEventListener(trigger, showTooltipBind);\r\n element[0].addEventListener(triggers.hide[idx], hideTooltipBind);\r\n }\r\n });\r\n }\r\n }\r\n prepTriggers();\r\n\r\n var animation = scope.$eval(attrs[prefix + 'Animation']);\r\n ttScope.animation = angular.isDefined(animation) ? !!animation : options.animation;\r\n\r\n var appendToBodyVal = scope.$eval(attrs[prefix + 'AppendToBody']);\r\n appendToBody = angular.isDefined(appendToBodyVal) ? appendToBodyVal : appendToBody;\r\n\r\n // if a tooltip is attached to we need to remove it on\r\n // location change as its parent scope will probably not be destroyed\r\n // by the change.\r\n if (appendToBody) {\r\n scope.$on('$locationChangeSuccess', function closeTooltipOnLocationChangeSuccess() {\r\n if (ttScope.isOpen) {\r\n hide();\r\n }\r\n });\r\n }\r\n\r\n // Make sure tooltip is destroyed and removed.\r\n scope.$on('$destroy', function onDestroyTooltip() {\r\n $timeout.cancel(transitionTimeout);\r\n $timeout.cancel(popupTimeout);\r\n $timeout.cancel(positionTimeout);\r\n unregisterTriggers();\r\n removeTooltip();\r\n ttScope = null;\r\n });\r\n };\r\n }\r\n };\r\n };\r\n }];\r\n})\r\n\r\n// This is mostly ngInclude code but with a custom scope\r\n.directive('tooltipTemplateTransclude', [\r\n '$animate', '$sce', '$compile', '$templateRequest',\r\nfunction ($animate , $sce , $compile , $templateRequest) {\r\n return {\r\n link: function(scope, elem, attrs) {\r\n var origScope = scope.$eval(attrs.tooltipTemplateTranscludeScope);\r\n\r\n var changeCounter = 0,\r\n currentScope,\r\n previousElement,\r\n currentElement;\r\n\r\n var cleanupLastIncludeContent = function() {\r\n if (previousElement) {\r\n previousElement.remove();\r\n previousElement = null;\r\n }\r\n if (currentScope) {\r\n currentScope.$destroy();\r\n currentScope = null;\r\n }\r\n if (currentElement) {\r\n $animate.leave(currentElement).then(function() {\r\n previousElement = null;\r\n });\r\n previousElement = currentElement;\r\n currentElement = null;\r\n }\r\n };\r\n\r\n scope.$watch($sce.parseAsResourceUrl(attrs.tooltipTemplateTransclude), function(src) {\r\n var thisChangeId = ++changeCounter;\r\n\r\n if (src) {\r\n //set the 2nd param to true to ignore the template request error so that the inner\r\n //contents and scope can be cleaned up.\r\n $templateRequest(src, true).then(function(response) {\r\n if (thisChangeId !== changeCounter) { return; }\r\n var newScope = origScope.$new();\r\n var template = response;\r\n\r\n var clone = $compile(template)(newScope, function(clone) {\r\n cleanupLastIncludeContent();\r\n $animate.enter(clone, elem);\r\n });\r\n\r\n currentScope = newScope;\r\n currentElement = clone;\r\n\r\n currentScope.$emit('$includeContentLoaded', src);\r\n }, function() {\r\n if (thisChangeId === changeCounter) {\r\n cleanupLastIncludeContent();\r\n scope.$emit('$includeContentError', src);\r\n }\r\n });\r\n scope.$emit('$includeContentRequested', src);\r\n } else {\r\n cleanupLastIncludeContent();\r\n }\r\n });\r\n\r\n scope.$on('$destroy', cleanupLastIncludeContent);\r\n }\r\n };\r\n}])\r\n\r\n/**\r\n * Note that it's intentional that these classes are *not* applied through $animate.\r\n * They must not be animated as they're expected to be present on the tooltip on\r\n * initialization.\r\n */\r\n.directive('tooltipClasses', function() {\r\n return {\r\n restrict: 'A',\r\n link: function(scope, element, attrs) {\r\n if (scope.placement) {\r\n element.addClass(scope.placement);\r\n }\r\n if (scope.popupClass) {\r\n element.addClass(scope.popupClass);\r\n }\r\n if (scope.animation()) {\r\n element.addClass(attrs.tooltipAnimationClass);\r\n }\r\n }\r\n };\r\n})\r\n\r\n.directive('tooltipPopup', function() {\r\n return {\r\n restrict: 'EA',\r\n replace: true,\r\n scope: { content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },\r\n templateUrl: 'template/tooltip/tooltip-popup.html'\r\n };\r\n})\r\n\r\n.directive('tooltip', [ '$tooltip', function($tooltip) {\r\n return $tooltip('tooltip', 'tooltip', 'mouseenter');\r\n}])\r\n\r\n.directive('tooltipTemplatePopup', function() {\r\n return {\r\n restrict: 'EA',\r\n replace: true,\r\n scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&',\r\n originScope: '&' },\r\n templateUrl: 'template/tooltip/tooltip-template-popup.html'\r\n };\r\n})\r\n\r\n.directive('tooltipTemplate', ['$tooltip', function($tooltip) {\r\n return $tooltip('tooltipTemplate', 'tooltip', 'mouseenter', {\r\n useContentExp: true\r\n });\r\n}])\r\n\r\n.directive('tooltipHtmlPopup', function() {\r\n return {\r\n restrict: 'EA',\r\n replace: true,\r\n scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },\r\n templateUrl: 'template/tooltip/tooltip-html-popup.html'\r\n };\r\n})\r\n\r\n.directive('tooltipHtml', ['$tooltip', function($tooltip) {\r\n return $tooltip('tooltipHtml', 'tooltip', 'mouseenter', {\r\n useContentExp: true\r\n });\r\n}])\r\n\r\n/*\r\nDeprecated\r\n*/\r\n.directive('tooltipHtmlUnsafePopup', function() {\r\n return {\r\n restrict: 'EA',\r\n replace: true,\r\n scope: { content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },\r\n templateUrl: 'template/tooltip/tooltip-html-unsafe-popup.html'\r\n };\r\n})\r\n\r\n.value('tooltipHtmlUnsafeSuppressDeprecated', false)\r\n.directive('tooltipHtmlUnsafe', [\r\n '$tooltip', 'tooltipHtmlUnsafeSuppressDeprecated', '$log',\r\nfunction($tooltip , tooltipHtmlUnsafeSuppressDeprecated , $log) {\r\n if (!tooltipHtmlUnsafeSuppressDeprecated) {\r\n $log.warn('tooltip-html-unsafe is now deprecated. Use tooltip-html or tooltip-template instead.');\r\n }\r\n return $tooltip('tooltipHtmlUnsafe', 'tooltip', 'mouseenter');\r\n}]);\r\n\r\n/**\r\n * The following features are still outstanding: popup delay, animation as a\r\n * function, placement as a function, inside, support for more triggers than\r\n * just mouse enter/leave, and selector delegatation.\r\n */\r\nangular.module( 'ui.bootstrap.popover', ['ui.bootstrap.tooltip'])\r\n\r\n.directive('popoverTemplatePopup', function() {\r\n return {\r\n restrict: 'EA',\r\n replace: true,\r\n scope: { title: '@', contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&',\r\n originScope: '&' },\r\n templateUrl: 'template/popover/popover-template.html'\r\n };\r\n})\r\n\r\n.directive('popoverTemplate', ['$tooltip', function($tooltip) {\r\n return $tooltip('popoverTemplate', 'popover', 'click', {\r\n useContentExp: true\r\n });\r\n}])\r\n\r\n.directive('popoverHtmlPopup', function() {\r\n return {\r\n restrict: 'EA',\r\n replace: true,\r\n scope: { contentExp: '&', title: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },\r\n templateUrl: 'template/popover/popover-html.html'\r\n };\r\n})\r\n\r\n.directive('popoverHtml', ['$tooltip', function($tooltip) {\r\n return $tooltip( 'popoverHtml', 'popover', 'click', {\r\n useContentExp: true\r\n });\r\n}])\r\n\r\n.directive('popoverPopup', function() {\r\n return {\r\n restrict: 'EA',\r\n replace: true,\r\n scope: { title: '@', content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },\r\n templateUrl: 'template/popover/popover.html'\r\n };\r\n})\r\n\r\n.directive('popover', ['$tooltip', function($tooltip) {\r\n return $tooltip( 'popover', 'popover', 'click' );\r\n}]);\r\n\r\nangular.module('ui.bootstrap.progressbar', [])\r\n\r\n.constant('progressConfig', {\r\n animate: true,\r\n max: 100\r\n})\r\n\r\n.value('$progressSuppressWarning', false)\r\n\r\n.controller('ProgressController', ['$scope', '$attrs', 'progressConfig', function($scope, $attrs, progressConfig) {\r\n var self = this,\r\n animate = angular.isDefined($attrs.animate) ? $scope.$parent.$eval($attrs.animate) : progressConfig.animate;\r\n\r\n this.bars = [];\r\n $scope.max = angular.isDefined($scope.max) ? $scope.max : progressConfig.max;\r\n\r\n this.addBar = function(bar, element) {\r\n if (!animate) {\r\n element.css({'transition': 'none'});\r\n }\r\n\r\n this.bars.push(bar);\r\n\r\n bar.max = $scope.max;\r\n\r\n bar.$watch('value', function(value) {\r\n bar.recalculatePercentage();\r\n });\r\n\r\n bar.recalculatePercentage = function() {\r\n bar.percent = +(100 * bar.value / bar.max).toFixed(2);\r\n\r\n var totalPercentage = self.bars.reduce(function(total, bar) {\r\n return total + bar.percent;\r\n }, 0);\r\n\r\n if (totalPercentage > 100) {\r\n bar.percent -= totalPercentage - 100;\r\n }\r\n };\r\n\r\n bar.$on('$destroy', function() {\r\n element = null;\r\n self.removeBar(bar);\r\n });\r\n };\r\n\r\n this.removeBar = function(bar) {\r\n this.bars.splice(this.bars.indexOf(bar), 1);\r\n };\r\n\r\n $scope.$watch('max', function(max) {\r\n self.bars.forEach(function(bar) {\r\n bar.max = $scope.max;\r\n bar.recalculatePercentage();\r\n });\r\n });\r\n}])\r\n\r\n.directive('uibProgress', function() {\r\n return {\r\n restrict: 'EA',\r\n replace: true,\r\n transclude: true,\r\n controller: 'ProgressController',\r\n require: 'uibProgress',\r\n scope: {\r\n max: '=?'\r\n },\r\n templateUrl: 'template/progressbar/progress.html'\r\n };\r\n})\r\n\r\n.directive('progress', ['$log', '$progressSuppressWarning', function($log, $progressSuppressWarning) {\r\n return {\r\n restrict: 'EA',\r\n replace: true,\r\n transclude: true,\r\n controller: 'ProgressController',\r\n require: 'progress',\r\n scope: {\r\n max: '=?'\r\n },\r\n templateUrl: 'template/progressbar/progress.html',\r\n link: function() {\r\n if ($progressSuppressWarning) {\r\n $log.warn('progress is now deprecated. Use uib-progress instead');\r\n }\r\n }\r\n };\r\n}])\r\n\r\n.directive('uibBar', function() {\r\n return {\r\n restrict: 'EA',\r\n replace: true,\r\n transclude: true,\r\n require: '^uibProgress',\r\n scope: {\r\n value: '=',\r\n type: '@'\r\n },\r\n templateUrl: 'template/progressbar/bar.html',\r\n link: function(scope, element, attrs, progressCtrl) {\r\n progressCtrl.addBar(scope, element);\r\n }\r\n };\r\n})\r\n\r\n.directive('bar', ['$log', '$progressSuppressWarning', function($log, $progressSuppressWarning) {\r\n return {\r\n restrict: 'EA',\r\n replace: true,\r\n transclude: true,\r\n require: '^progress',\r\n scope: {\r\n value: '=',\r\n type: '@'\r\n },\r\n templateUrl: 'template/progressbar/bar.html',\r\n link: function(scope, element, attrs, progressCtrl) {\r\n if ($progressSuppressWarning) {\r\n $log.warn('bar is now deprecated. Use uib-bar instead');\r\n }\r\n progressCtrl.addBar(scope, element);\r\n }\r\n };\r\n}])\r\n\r\n.directive('progressbar', function() {\r\n return {\r\n restrict: 'EA',\r\n replace: true,\r\n transclude: true,\r\n controller: 'ProgressController',\r\n scope: {\r\n value: '=',\r\n max: '=?',\r\n type: '@'\r\n },\r\n templateUrl: 'template/progressbar/progressbar.html',\r\n link: function(scope, element, attrs, progressCtrl) {\r\n progressCtrl.addBar(scope, angular.element(element.children()[0]));\r\n }\r\n };\r\n});\r\n\r\nangular.module('ui.bootstrap.rating', [])\r\n\r\n.constant('ratingConfig', {\r\n max: 5,\r\n stateOn: null,\r\n stateOff: null,\r\n titles : ['one', 'two', 'three', 'four', 'five']\r\n})\r\n\r\n.controller('RatingController', ['$scope', '$attrs', 'ratingConfig', function($scope, $attrs, ratingConfig) {\r\n var ngModelCtrl = { $setViewValue: angular.noop };\r\n\r\n this.init = function(ngModelCtrl_) {\r\n ngModelCtrl = ngModelCtrl_;\r\n ngModelCtrl.$render = this.render;\r\n\r\n ngModelCtrl.$formatters.push(function(value) {\r\n if (angular.isNumber(value) && value << 0 !== value) {\r\n value = Math.round(value);\r\n }\r\n return value;\r\n });\r\n\r\n this.stateOn = angular.isDefined($attrs.stateOn) ? $scope.$parent.$eval($attrs.stateOn) : ratingConfig.stateOn;\r\n this.stateOff = angular.isDefined($attrs.stateOff) ? $scope.$parent.$eval($attrs.stateOff) : ratingConfig.stateOff;\r\n var tmpTitles = angular.isDefined($attrs.titles) ? $scope.$parent.$eval($attrs.titles) : ratingConfig.titles ; \r\n this.titles = angular.isArray(tmpTitles) && tmpTitles.length > 0 ?\r\n tmpTitles : ratingConfig.titles;\r\n \r\n var ratingStates = angular.isDefined($attrs.ratingStates) ?\r\n $scope.$parent.$eval($attrs.ratingStates) :\r\n new Array(angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : ratingConfig.max);\r\n $scope.range = this.buildTemplateObjects(ratingStates);\r\n };\r\n\r\n this.buildTemplateObjects = function(states) {\r\n for (var i = 0, n = states.length; i < n; i++) {\r\n states[i] = angular.extend({ index: i }, { stateOn: this.stateOn, stateOff: this.stateOff, title: this.getTitle(i) }, states[i]);\r\n }\r\n return states;\r\n };\r\n \r\n this.getTitle = function(index) {\r\n if (index >= this.titles.length) {\r\n return index + 1;\r\n } else {\r\n return this.titles[index];\r\n }\r\n };\r\n \r\n $scope.rate = function(value) {\r\n if (!$scope.readonly && value >= 0 && value <= $scope.range.length) {\r\n ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue === value ? 0 : value);\r\n ngModelCtrl.$render();\r\n }\r\n };\r\n\r\n $scope.enter = function(value) {\r\n if (!$scope.readonly) {\r\n $scope.value = value;\r\n }\r\n $scope.onHover({value: value});\r\n };\r\n\r\n $scope.reset = function() {\r\n $scope.value = ngModelCtrl.$viewValue;\r\n $scope.onLeave();\r\n };\r\n\r\n $scope.onKeydown = function(evt) {\r\n if (/(37|38|39|40)/.test(evt.which)) {\r\n evt.preventDefault();\r\n evt.stopPropagation();\r\n $scope.rate($scope.value + (evt.which === 38 || evt.which === 39 ? 1 : -1));\r\n }\r\n };\r\n\r\n this.render = function() {\r\n $scope.value = ngModelCtrl.$viewValue;\r\n };\r\n}])\r\n\r\n.directive('rating', function() {\r\n return {\r\n restrict: 'EA',\r\n require: ['rating', 'ngModel'],\r\n scope: {\r\n readonly: '=?',\r\n onHover: '&',\r\n onLeave: '&'\r\n },\r\n controller: 'RatingController',\r\n templateUrl: 'template/rating/rating.html',\r\n replace: true,\r\n link: function(scope, element, attrs, ctrls) {\r\n var ratingCtrl = ctrls[0], ngModelCtrl = ctrls[1];\r\n ratingCtrl.init( ngModelCtrl );\r\n }\r\n };\r\n});\r\n\r\n\r\n/**\r\n * @ngdoc overview\r\n * @name ui.bootstrap.tabs\r\n *\r\n * @description\r\n * AngularJS version of the tabs directive.\r\n */\r\n\r\nangular.module('ui.bootstrap.tabs', [])\r\n\r\n.controller('TabsetController', ['$scope', function TabsetCtrl($scope) {\r\n var ctrl = this,\r\n tabs = ctrl.tabs = $scope.tabs = [];\r\n\r\n ctrl.select = function(selectedTab) {\r\n angular.forEach(tabs, function(tab) {\r\n if (tab.active && tab !== selectedTab) {\r\n tab.active = false;\r\n tab.onDeselect();\r\n selectedTab.selectCalled = false;\r\n }\r\n });\r\n selectedTab.active = true;\r\n // only call select if it has not already been called\r\n if (!selectedTab.selectCalled) {\r\n selectedTab.onSelect();\r\n selectedTab.selectCalled = true;\r\n }\r\n };\r\n\r\n ctrl.addTab = function addTab(tab) {\r\n tabs.push(tab);\r\n // we can't run the select function on the first tab\r\n // since that would select it twice\r\n if (tabs.length === 1 && tab.active !== false) {\r\n tab.active = true;\r\n } else if (tab.active) {\r\n ctrl.select(tab);\r\n } else {\r\n tab.active = false;\r\n }\r\n };\r\n\r\n ctrl.removeTab = function removeTab(tab) {\r\n var index = tabs.indexOf(tab);\r\n //Select a new tab if the tab to be removed is selected and not destroyed\r\n if (tab.active && tabs.length > 1 && !destroyed) {\r\n //If this is the last tab, select the previous tab. else, the next tab.\r\n var newActiveIndex = index == tabs.length - 1 ? index - 1 : index + 1;\r\n ctrl.select(tabs[newActiveIndex]);\r\n }\r\n tabs.splice(index, 1);\r\n };\r\n\r\n var destroyed;\r\n $scope.$on('$destroy', function() {\r\n destroyed = true;\r\n });\r\n}])\r\n\r\n/**\r\n * @ngdoc directive\r\n * @name ui.bootstrap.tabs.directive:tabset\r\n * @restrict EA\r\n *\r\n * @description\r\n * Tabset is the outer container for the tabs directive\r\n *\r\n * @param {boolean=} vertical Whether or not to use vertical styling for the tabs.\r\n * @param {boolean=} justified Whether or not to use justified styling for the tabs.\r\n *\r\n * @example\r\n\r\n \r\n \r\n First Content!\r\n Second Content!\r\n \r\n
\r\n \r\n First Vertical Content!\r\n Second Vertical Content!\r\n \r\n \r\n First Justified Content!\r\n Second Justified Content!\r\n \r\n
\r\n
\r\n */\r\n.directive('tabset', function() {\r\n return {\r\n restrict: 'EA',\r\n transclude: true,\r\n replace: true,\r\n scope: {\r\n type: '@'\r\n },\r\n controller: 'TabsetController',\r\n templateUrl: 'template/tabs/tabset.html',\r\n link: function(scope, element, attrs) {\r\n scope.vertical = angular.isDefined(attrs.vertical) ? scope.$parent.$eval(attrs.vertical) : false;\r\n scope.justified = angular.isDefined(attrs.justified) ? scope.$parent.$eval(attrs.justified) : false;\r\n }\r\n };\r\n})\r\n\r\n/**\r\n * @ngdoc directive\r\n * @name ui.bootstrap.tabs.directive:tab\r\n * @restrict EA\r\n *\r\n * @param {string=} heading The visible heading, or title, of the tab. Set HTML headings with {@link ui.bootstrap.tabs.directive:tabHeading tabHeading}.\r\n * @param {string=} select An expression to evaluate when the tab is selected.\r\n * @param {boolean=} active A binding, telling whether or not this tab is selected.\r\n * @param {boolean=} disabled A binding, telling whether or not this tab is disabled.\r\n *\r\n * @description\r\n * Creates a tab with a heading and content. Must be placed within a {@link ui.bootstrap.tabs.directive:tabset tabset}.\r\n *\r\n * @example\r\n\r\n \r\n
\r\n \r\n \r\n
\r\n \r\n First Tab\r\n \r\n Alert me!\r\n Second Tab, with alert callback and html heading!\r\n \r\n \r\n {{item.content}}\r\n \r\n \r\n
\r\n
\r\n \r\n function TabsDemoCtrl($scope) {\r\n $scope.items = [\r\n { title:\"Dynamic Title 1\", content:\"Dynamic Item 0\" },\r\n { title:\"Dynamic Title 2\", content:\"Dynamic Item 1\", disabled: true }\r\n ];\r\n\r\n $scope.alertMe = function() {\r\n setTimeout(function() {\r\n alert(\"You've selected the alert tab!\");\r\n });\r\n };\r\n };\r\n \r\n
\r\n */\r\n\r\n/**\r\n * @ngdoc directive\r\n * @name ui.bootstrap.tabs.directive:tabHeading\r\n * @restrict EA\r\n *\r\n * @description\r\n * Creates an HTML heading for a {@link ui.bootstrap.tabs.directive:tab tab}. Must be placed as a child of a tab element.\r\n *\r\n * @example\r\n\r\n \r\n \r\n \r\n HTML in my titles?!\r\n And some content, too!\r\n \r\n \r\n Icon heading?!?\r\n That's right.\r\n \r\n \r\n \r\n\r\n */\r\n.directive('tab', ['$parse', '$log', function($parse, $log) {\r\n return {\r\n require: '^tabset',\r\n restrict: 'EA',\r\n replace: true,\r\n templateUrl: 'template/tabs/tab.html',\r\n transclude: true,\r\n scope: {\r\n active: '=?',\r\n heading: '@',\r\n onSelect: '&select', //This callback is called in contentHeadingTransclude\r\n //once it inserts the tab's content into the dom\r\n onDeselect: '&deselect'\r\n },\r\n controller: function() {\r\n //Empty controller so other directives can require being 'under' a tab\r\n },\r\n link: function(scope, elm, attrs, tabsetCtrl, transclude) {\r\n scope.$watch('active', function(active) {\r\n if (active) {\r\n tabsetCtrl.select(scope);\r\n }\r\n });\r\n\r\n scope.disabled = false;\r\n if (attrs.disable) {\r\n scope.$parent.$watch($parse(attrs.disable), function(value) {\r\n scope.disabled = !! value;\r\n });\r\n }\r\n\r\n // Deprecation support of \"disabled\" parameter\r\n // fix(tab): IE9 disabled attr renders grey text on enabled tab #2677\r\n // This code is duplicated from the lines above to make it easy to remove once\r\n // the feature has been completely deprecated\r\n if (attrs.disabled) {\r\n $log.warn('Use of \"disabled\" attribute has been deprecated, please use \"disable\"');\r\n scope.$parent.$watch($parse(attrs.disabled), function(value) {\r\n scope.disabled = !! value;\r\n });\r\n }\r\n\r\n scope.select = function() {\r\n if (!scope.disabled) {\r\n scope.active = true;\r\n }\r\n };\r\n\r\n tabsetCtrl.addTab(scope);\r\n scope.$on('$destroy', function() {\r\n tabsetCtrl.removeTab(scope);\r\n });\r\n\r\n //We need to transclude later, once the content container is ready.\r\n //when this link happens, we're inside a tab heading.\r\n scope.$transcludeFn = transclude;\r\n }\r\n };\r\n}])\r\n\r\n.directive('tabHeadingTransclude', function() {\r\n return {\r\n restrict: 'A',\r\n require: '^tab',\r\n link: function(scope, elm, attrs, tabCtrl) {\r\n scope.$watch('headingElement', function updateHeadingElement(heading) {\r\n if (heading) {\r\n elm.html('');\r\n elm.append(heading);\r\n }\r\n });\r\n }\r\n };\r\n})\r\n\r\n.directive('tabContentTransclude', function() {\r\n return {\r\n restrict: 'A',\r\n require: '^tabset',\r\n link: function(scope, elm, attrs) {\r\n var tab = scope.$eval(attrs.tabContentTransclude);\r\n\r\n //Now our tab is ready to be transcluded: both the tab heading area\r\n //and the tab content area are loaded. Transclude 'em both.\r\n tab.$transcludeFn(tab.$parent, function(contents) {\r\n angular.forEach(contents, function(node) {\r\n if (isTabHeading(node)) {\r\n //Let tabHeadingTransclude know.\r\n tab.headingElement = node;\r\n } else {\r\n elm.append(node);\r\n }\r\n });\r\n });\r\n }\r\n };\r\n\r\n function isTabHeading(node) {\r\n return node.tagName && (\r\n node.hasAttribute('tab-heading') ||\r\n node.hasAttribute('data-tab-heading') ||\r\n node.hasAttribute('x-tab-heading') ||\r\n node.tagName.toLowerCase() === 'tab-heading' ||\r\n node.tagName.toLowerCase() === 'data-tab-heading' ||\r\n node.tagName.toLowerCase() === 'x-tab-heading'\r\n );\r\n }\r\n});\r\n\r\nangular.module('ui.bootstrap.timepicker', [])\r\n\r\n.constant('timepickerConfig', {\r\n hourStep: 1,\r\n minuteStep: 1,\r\n showMeridian: true,\r\n meridians: null,\r\n readonlyInput: false,\r\n mousewheel: true,\r\n arrowkeys: true,\r\n showSpinners: true\r\n})\r\n\r\n.controller('TimepickerController', ['$scope', '$attrs', '$parse', '$log', '$locale', 'timepickerConfig', function($scope, $attrs, $parse, $log, $locale, timepickerConfig) {\r\n var selected = new Date(),\r\n ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl\r\n meridians = angular.isDefined($attrs.meridians) ? $scope.$parent.$eval($attrs.meridians) : timepickerConfig.meridians || $locale.DATETIME_FORMATS.AMPMS;\r\n\r\n this.init = function(ngModelCtrl_, inputs) {\r\n ngModelCtrl = ngModelCtrl_;\r\n ngModelCtrl.$render = this.render;\r\n\r\n ngModelCtrl.$formatters.unshift(function(modelValue) {\r\n return modelValue ? new Date(modelValue) : null;\r\n });\r\n\r\n var hoursInputEl = inputs.eq(0),\r\n minutesInputEl = inputs.eq(1);\r\n\r\n var mousewheel = angular.isDefined($attrs.mousewheel) ? $scope.$parent.$eval($attrs.mousewheel) : timepickerConfig.mousewheel;\r\n if (mousewheel) {\r\n this.setupMousewheelEvents(hoursInputEl, minutesInputEl);\r\n }\r\n\r\n var arrowkeys = angular.isDefined($attrs.arrowkeys) ? $scope.$parent.$eval($attrs.arrowkeys) : timepickerConfig.arrowkeys;\r\n if (arrowkeys) {\r\n this.setupArrowkeyEvents(hoursInputEl, minutesInputEl);\r\n }\r\n\r\n $scope.readonlyInput = angular.isDefined($attrs.readonlyInput) ? $scope.$parent.$eval($attrs.readonlyInput) : timepickerConfig.readonlyInput;\r\n this.setupInputEvents(hoursInputEl, minutesInputEl);\r\n };\r\n\r\n var hourStep = timepickerConfig.hourStep;\r\n if ($attrs.hourStep) {\r\n $scope.$parent.$watch($parse($attrs.hourStep), function(value) {\r\n hourStep = parseInt(value, 10);\r\n });\r\n }\r\n\r\n var minuteStep = timepickerConfig.minuteStep;\r\n if ($attrs.minuteStep) {\r\n $scope.$parent.$watch($parse($attrs.minuteStep), function(value) {\r\n minuteStep = parseInt(value, 10);\r\n });\r\n }\r\n\r\n var min;\r\n $scope.$parent.$watch($parse($attrs.min), function(value) {\r\n var dt = new Date(value);\r\n min = isNaN(dt) ? undefined : dt;\r\n });\r\n\r\n var max;\r\n $scope.$parent.$watch($parse($attrs.max), function(value) {\r\n var dt = new Date(value);\r\n max = isNaN(dt) ? undefined : dt;\r\n });\r\n\r\n $scope.noIncrementHours = function() {\r\n var incrementedSelected = addMinutes(selected, hourStep * 60);\r\n return incrementedSelected > max ||\r\n (incrementedSelected < selected && incrementedSelected < min);\r\n };\r\n\r\n $scope.noDecrementHours = function() {\r\n var decrementedSelected = addMinutes(selected, -hourStep * 60);\r\n return decrementedSelected < min ||\r\n (decrementedSelected > selected && decrementedSelected > max);\r\n };\r\n\r\n $scope.noIncrementMinutes = function() {\r\n var incrementedSelected = addMinutes(selected, minuteStep);\r\n return incrementedSelected > max ||\r\n (incrementedSelected < selected && incrementedSelected < min);\r\n };\r\n\r\n $scope.noDecrementMinutes = function() {\r\n var decrementedSelected = addMinutes(selected, -minuteStep);\r\n return decrementedSelected < min ||\r\n (decrementedSelected > selected && decrementedSelected > max);\r\n };\r\n\r\n $scope.noToggleMeridian = function() {\r\n if (selected.getHours() < 13) {\r\n return addMinutes(selected, 12 * 60) > max;\r\n } else {\r\n return addMinutes(selected, -12 * 60) < min;\r\n }\r\n };\r\n\r\n // 12H / 24H mode\r\n $scope.showMeridian = timepickerConfig.showMeridian;\r\n if ($attrs.showMeridian) {\r\n $scope.$parent.$watch($parse($attrs.showMeridian), function(value) {\r\n $scope.showMeridian = !!value;\r\n\r\n if (ngModelCtrl.$error.time) {\r\n // Evaluate from template\r\n var hours = getHoursFromTemplate(), minutes = getMinutesFromTemplate();\r\n if (angular.isDefined(hours) && angular.isDefined(minutes)) {\r\n selected.setHours(hours);\r\n refresh();\r\n }\r\n } else {\r\n updateTemplate();\r\n }\r\n });\r\n }\r\n\r\n // Get $scope.hours in 24H mode if valid\r\n function getHoursFromTemplate() {\r\n var hours = parseInt($scope.hours, 10);\r\n var valid = $scope.showMeridian ? (hours > 0 && hours < 13) : (hours >= 0 && hours < 24);\r\n if (!valid) {\r\n return undefined;\r\n }\r\n\r\n if ($scope.showMeridian) {\r\n if (hours === 12) {\r\n hours = 0;\r\n }\r\n if ($scope.meridian === meridians[1]) {\r\n hours = hours + 12;\r\n }\r\n }\r\n return hours;\r\n }\r\n\r\n function getMinutesFromTemplate() {\r\n var minutes = parseInt($scope.minutes, 10);\r\n return (minutes >= 0 && minutes < 60) ? minutes : undefined;\r\n }\r\n\r\n function pad(value) {\r\n return (angular.isDefined(value) && value.toString().length < 2) ? '0' + value : value.toString();\r\n }\r\n\r\n // Respond on mousewheel spin\r\n this.setupMousewheelEvents = function(hoursInputEl, minutesInputEl) {\r\n var isScrollingUp = function(e) {\r\n if (e.originalEvent) {\r\n e = e.originalEvent;\r\n }\r\n //pick correct delta variable depending on event\r\n var delta = (e.wheelDelta) ? e.wheelDelta : -e.deltaY;\r\n return (e.detail || delta > 0);\r\n };\r\n\r\n hoursInputEl.bind('mousewheel wheel', function(e) {\r\n $scope.$apply(isScrollingUp(e) ? $scope.incrementHours() : $scope.decrementHours());\r\n e.preventDefault();\r\n });\r\n\r\n minutesInputEl.bind('mousewheel wheel', function(e) {\r\n $scope.$apply(isScrollingUp(e) ? $scope.incrementMinutes() : $scope.decrementMinutes());\r\n e.preventDefault();\r\n });\r\n\r\n };\r\n\r\n // Respond on up/down arrowkeys\r\n this.setupArrowkeyEvents = function(hoursInputEl, minutesInputEl) {\r\n hoursInputEl.bind('keydown', function(e) {\r\n if (e.which === 38) { // up\r\n e.preventDefault();\r\n $scope.incrementHours();\r\n $scope.$apply();\r\n } else if (e.which === 40) { // down\r\n e.preventDefault();\r\n $scope.decrementHours();\r\n $scope.$apply();\r\n }\r\n });\r\n\r\n minutesInputEl.bind('keydown', function(e) {\r\n if (e.which === 38) { // up\r\n e.preventDefault();\r\n $scope.incrementMinutes();\r\n $scope.$apply();\r\n } else if (e.which === 40) { // down\r\n e.preventDefault();\r\n $scope.decrementMinutes();\r\n $scope.$apply();\r\n }\r\n });\r\n };\r\n\r\n this.setupInputEvents = function(hoursInputEl, minutesInputEl) {\r\n if ($scope.readonlyInput) {\r\n $scope.updateHours = angular.noop;\r\n $scope.updateMinutes = angular.noop;\r\n return;\r\n }\r\n\r\n var invalidate = function(invalidHours, invalidMinutes) {\r\n ngModelCtrl.$setViewValue(null);\r\n ngModelCtrl.$setValidity('time', false);\r\n if (angular.isDefined(invalidHours)) {\r\n $scope.invalidHours = invalidHours;\r\n }\r\n if (angular.isDefined(invalidMinutes)) {\r\n $scope.invalidMinutes = invalidMinutes;\r\n }\r\n };\r\n\r\n $scope.updateHours = function() {\r\n var hours = getHoursFromTemplate(),\r\n minutes = getMinutesFromTemplate();\r\n\r\n if (angular.isDefined(hours) && angular.isDefined(minutes)) {\r\n selected.setHours(hours);\r\n if (selected < min || selected > max) {\r\n invalidate(true);\r\n } else {\r\n refresh('h');\r\n }\r\n } else {\r\n invalidate(true);\r\n }\r\n };\r\n\r\n hoursInputEl.bind('blur', function(e) {\r\n if (!$scope.invalidHours && $scope.hours < 10) {\r\n $scope.$apply(function() {\r\n $scope.hours = pad($scope.hours);\r\n });\r\n }\r\n });\r\n\r\n $scope.updateMinutes = function() {\r\n var minutes = getMinutesFromTemplate(),\r\n hours = getHoursFromTemplate();\r\n\r\n if (angular.isDefined(minutes) && angular.isDefined(hours)) {\r\n selected.setMinutes(minutes);\r\n if (selected < min || selected > max) {\r\n invalidate(undefined, true);\r\n } else {\r\n refresh('m');\r\n }\r\n } else {\r\n invalidate(undefined, true);\r\n }\r\n };\r\n\r\n minutesInputEl.bind('blur', function(e) {\r\n if (!$scope.invalidMinutes && $scope.minutes < 10) {\r\n $scope.$apply(function() {\r\n $scope.minutes = pad($scope.minutes);\r\n });\r\n }\r\n });\r\n\r\n };\r\n\r\n this.render = function() {\r\n var date = ngModelCtrl.$viewValue;\r\n\r\n if (isNaN(date)) {\r\n ngModelCtrl.$setValidity('time', false);\r\n $log.error('Timepicker directive: \"ng-model\" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.');\r\n } else {\r\n if (date) {\r\n selected = date;\r\n }\r\n\r\n if (selected < min || selected > max) {\r\n ngModelCtrl.$setValidity('time', false);\r\n $scope.invalidHours = true;\r\n $scope.invalidMinutes = true;\r\n } else {\r\n makeValid();\r\n }\r\n updateTemplate();\r\n }\r\n };\r\n\r\n // Call internally when we know that model is valid.\r\n function refresh(keyboardChange) {\r\n makeValid();\r\n ngModelCtrl.$setViewValue(new Date(selected));\r\n updateTemplate(keyboardChange);\r\n }\r\n\r\n function makeValid() {\r\n ngModelCtrl.$setValidity('time', true);\r\n $scope.invalidHours = false;\r\n $scope.invalidMinutes = false;\r\n }\r\n\r\n function updateTemplate(keyboardChange) {\r\n var hours = selected.getHours(), minutes = selected.getMinutes();\r\n\r\n if ($scope.showMeridian) {\r\n hours = (hours === 0 || hours === 12) ? 12 : hours % 12; // Convert 24 to 12 hour system\r\n }\r\n\r\n $scope.hours = keyboardChange === 'h' ? hours : pad(hours);\r\n if (keyboardChange !== 'm') {\r\n $scope.minutes = pad(minutes);\r\n }\r\n $scope.meridian = selected.getHours() < 12 ? meridians[0] : meridians[1];\r\n }\r\n\r\n function addMinutes(date, minutes) {\r\n var dt = new Date(date.getTime() + minutes * 60000);\r\n var newDate = new Date(date);\r\n newDate.setHours(dt.getHours(), dt.getMinutes());\r\n return newDate;\r\n }\r\n\r\n function addMinutesToSelected(minutes) {\r\n selected = addMinutes(selected, minutes);\r\n refresh();\r\n }\r\n\r\n $scope.showSpinners = angular.isDefined($attrs.showSpinners) ?\r\n $scope.$parent.$eval($attrs.showSpinners) : timepickerConfig.showSpinners;\r\n\r\n $scope.incrementHours = function() {\r\n if (!$scope.noIncrementHours()) {\r\n addMinutesToSelected(hourStep * 60);\r\n }\r\n };\r\n\r\n $scope.decrementHours = function() {\r\n if (!$scope.noDecrementHours()) {\r\n addMinutesToSelected(-hourStep * 60);\r\n }\r\n };\r\n\r\n $scope.incrementMinutes = function() {\r\n if (!$scope.noIncrementMinutes()) {\r\n addMinutesToSelected(minuteStep);\r\n }\r\n };\r\n\r\n $scope.decrementMinutes = function() {\r\n if (!$scope.noDecrementMinutes()) {\r\n addMinutesToSelected(-minuteStep);\r\n }\r\n };\r\n\r\n $scope.toggleMeridian = function() {\r\n if (!$scope.noToggleMeridian()) {\r\n addMinutesToSelected(12 * 60 * (selected.getHours() < 12 ? 1 : -1));\r\n }\r\n };\r\n}])\r\n\r\n.directive('timepicker', function() {\r\n return {\r\n restrict: 'EA',\r\n require: ['timepicker', '?^ngModel'],\r\n controller:'TimepickerController',\r\n controllerAs: 'timepicker',\r\n replace: true,\r\n scope: {},\r\n templateUrl: function(element, attrs) {\r\n return attrs.templateUrl || 'template/timepicker/timepicker.html';\r\n },\r\n link: function(scope, element, attrs, ctrls) {\r\n var timepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1];\r\n\r\n if (ngModelCtrl) {\r\n timepickerCtrl.init(ngModelCtrl, element.find('input'));\r\n }\r\n }\r\n };\r\n});\r\n\r\nangular.module('ui.bootstrap.transition', [])\r\n\r\n.value('$transitionSuppressDeprecated', false)\r\n/**\r\n * $transition service provides a consistent interface to trigger CSS 3 transitions and to be informed when they complete.\r\n * @param {DOMElement} element The DOMElement that will be animated.\r\n * @param {string|object|function} trigger The thing that will cause the transition to start:\r\n * - As a string, it represents the css class to be added to the element.\r\n * - As an object, it represents a hash of style attributes to be applied to the element.\r\n * - As a function, it represents a function to be called that will cause the transition to occur.\r\n * @return {Promise} A promise that is resolved when the transition finishes.\r\n */\r\n.factory('$transition', [\r\n '$q', '$timeout', '$rootScope', '$log', '$transitionSuppressDeprecated',\r\nfunction($q , $timeout , $rootScope , $log , $transitionSuppressDeprecated) {\r\n\r\n if (!$transitionSuppressDeprecated) {\r\n $log.warn('$transition is now deprecated. Use $animate from ngAnimate instead.');\r\n }\r\n\r\n var $transition = function(element, trigger, options) {\r\n options = options || {};\r\n var deferred = $q.defer();\r\n var endEventName = $transition[options.animation ? 'animationEndEventName' : 'transitionEndEventName'];\r\n\r\n var transitionEndHandler = function(event) {\r\n $rootScope.$apply(function() {\r\n element.unbind(endEventName, transitionEndHandler);\r\n deferred.resolve(element);\r\n });\r\n };\r\n\r\n if (endEventName) {\r\n element.bind(endEventName, transitionEndHandler);\r\n }\r\n\r\n // Wrap in a timeout to allow the browser time to update the DOM before the transition is to occur\r\n $timeout(function() {\r\n if ( angular.isString(trigger) ) {\r\n element.addClass(trigger);\r\n } else if ( angular.isFunction(trigger) ) {\r\n trigger(element);\r\n } else if ( angular.isObject(trigger) ) {\r\n element.css(trigger);\r\n }\r\n //If browser does not support transitions, instantly resolve\r\n if ( !endEventName ) {\r\n deferred.resolve(element);\r\n }\r\n });\r\n\r\n // Add our custom cancel function to the promise that is returned\r\n // We can call this if we are about to run a new transition, which we know will prevent this transition from ending,\r\n // i.e. it will therefore never raise a transitionEnd event for that transition\r\n deferred.promise.cancel = function() {\r\n if ( endEventName ) {\r\n element.unbind(endEventName, transitionEndHandler);\r\n }\r\n deferred.reject('Transition cancelled');\r\n };\r\n\r\n return deferred.promise;\r\n };\r\n\r\n // Work out the name of the transitionEnd event\r\n var transElement = document.createElement('trans');\r\n var transitionEndEventNames = {\r\n 'WebkitTransition': 'webkitTransitionEnd',\r\n 'MozTransition': 'transitionend',\r\n 'OTransition': 'oTransitionEnd',\r\n 'transition': 'transitionend'\r\n };\r\n var animationEndEventNames = {\r\n 'WebkitTransition': 'webkitAnimationEnd',\r\n 'MozTransition': 'animationend',\r\n 'OTransition': 'oAnimationEnd',\r\n 'transition': 'animationend'\r\n };\r\n function findEndEventName(endEventNames) {\r\n for (var name in endEventNames){\r\n if (transElement.style[name] !== undefined) {\r\n return endEventNames[name];\r\n }\r\n }\r\n }\r\n $transition.transitionEndEventName = findEndEventName(transitionEndEventNames);\r\n $transition.animationEndEventName = findEndEventName(animationEndEventNames);\r\n return $transition;\r\n}]);\r\n\r\nangular.module('ui.bootstrap.typeahead', ['ui.bootstrap.position'])\r\n\r\n/**\r\n * A helper service that can parse typeahead's syntax (string provided by users)\r\n * Extracted to a separate service for ease of unit testing\r\n */\r\n .factory('typeaheadParser', ['$parse', function($parse) {\r\n\r\n // 00000111000000000000022200000000000000003333333333333330000000000044000\r\n var TYPEAHEAD_REGEXP = /^\\s*([\\s\\S]+?)(?:\\s+as\\s+([\\s\\S]+?))?\\s+for\\s+(?:([\\$\\w][\\$\\w\\d]*))\\s+in\\s+([\\s\\S]+?)$/;\r\n\r\n return {\r\n parse: function(input) {\r\n var match = input.match(TYPEAHEAD_REGEXP);\r\n if (!match) {\r\n throw new Error(\r\n 'Expected typeahead specification in form of \"_modelValue_ (as _label_)? for _item_ in _collection_\"' +\r\n ' but got \"' + input + '\".');\r\n }\r\n\r\n return {\r\n itemName:match[3],\r\n source:$parse(match[4]),\r\n viewMapper:$parse(match[2] || match[1]),\r\n modelMapper:$parse(match[1])\r\n };\r\n }\r\n };\r\n}])\r\n\r\n .directive('typeahead', ['$compile', '$parse', '$q', '$timeout', '$document', '$window', '$rootScope', '$position', 'typeaheadParser',\r\n function($compile, $parse, $q, $timeout, $document, $window, $rootScope, $position, typeaheadParser) {\r\n var HOT_KEYS = [9, 13, 27, 38, 40];\r\n var eventDebounceTime = 200;\r\n\r\n return {\r\n require: ['ngModel', '^?ngModelOptions'],\r\n link: function(originalScope, element, attrs, ctrls) {\r\n var modelCtrl = ctrls[0];\r\n var ngModelOptions = ctrls[1];\r\n //SUPPORTED ATTRIBUTES (OPTIONS)\r\n\r\n //minimal no of characters that needs to be entered before typeahead kicks-in\r\n var minLength = originalScope.$eval(attrs.typeaheadMinLength);\r\n if (!minLength && minLength !== 0) {\r\n minLength = 1;\r\n }\r\n\r\n //minimal wait time after last character typed before typeahead kicks-in\r\n var waitTime = originalScope.$eval(attrs.typeaheadWaitMs) || 0;\r\n\r\n //should it restrict model values to the ones selected from the popup only?\r\n var isEditable = originalScope.$eval(attrs.typeaheadEditable) !== false;\r\n\r\n //binding to a variable that indicates if matches are being retrieved asynchronously\r\n var isLoadingSetter = $parse(attrs.typeaheadLoading).assign || angular.noop;\r\n\r\n //a callback executed when a match is selected\r\n var onSelectCallback = $parse(attrs.typeaheadOnSelect);\r\n\r\n //should it select highlighted popup value when losing focus?\r\n var isSelectOnBlur = angular.isDefined(attrs.typeaheadSelectOnBlur) ? originalScope.$eval(attrs.typeaheadSelectOnBlur) : false;\r\n\r\n //binding to a variable that indicates if there were no results after the query is completed\r\n var isNoResultsSetter = $parse(attrs.typeaheadNoResults).assign || angular.noop;\r\n\r\n var inputFormatter = attrs.typeaheadInputFormatter ? $parse(attrs.typeaheadInputFormatter) : undefined;\r\n\r\n var appendToBody = attrs.typeaheadAppendToBody ? originalScope.$eval(attrs.typeaheadAppendToBody) : false;\r\n\r\n var focusFirst = originalScope.$eval(attrs.typeaheadFocusFirst) !== false;\r\n\r\n //If input matches an item of the list exactly, select it automatically\r\n var selectOnExact = attrs.typeaheadSelectOnExact ? originalScope.$eval(attrs.typeaheadSelectOnExact) : false;\r\n\r\n //INTERNAL VARIABLES\r\n\r\n //model setter executed upon match selection\r\n var parsedModel = $parse(attrs.ngModel);\r\n var invokeModelSetter = $parse(attrs.ngModel + '($$$p)');\r\n var $setModelValue = function(scope, newValue) {\r\n if (angular.isFunction(parsedModel(originalScope)) &&\r\n ngModelOptions && ngModelOptions.$options && ngModelOptions.$options.getterSetter) {\r\n return invokeModelSetter(scope, {$$$p: newValue});\r\n } else {\r\n return parsedModel.assign(scope, newValue);\r\n }\r\n };\r\n\r\n //expressions used by typeahead\r\n var parserResult = typeaheadParser.parse(attrs.typeahead);\r\n\r\n var hasFocus;\r\n\r\n //Used to avoid bug in iOS webview where iOS keyboard does not fire\r\n //mousedown & mouseup events\r\n //Issue #3699\r\n var selected;\r\n\r\n //create a child scope for the typeahead directive so we are not polluting original scope\r\n //with typeahead-specific data (matches, query etc.)\r\n var scope = originalScope.$new();\r\n var offDestroy = originalScope.$on('$destroy', function() {\r\n\t\t\t scope.$destroy();\r\n });\r\n scope.$on('$destroy', offDestroy);\r\n\r\n // WAI-ARIA\r\n var popupId = 'typeahead-' + scope.$id + '-' + Math.floor(Math.random() * 10000);\r\n element.attr({\r\n 'aria-autocomplete': 'list',\r\n 'aria-expanded': false,\r\n 'aria-owns': popupId\r\n });\r\n\r\n //pop-up element used to display matches\r\n var popUpEl = angular.element('
');\r\n popUpEl.attr({\r\n id: popupId,\r\n matches: 'matches',\r\n active: 'activeIdx',\r\n select: 'select(activeIdx)',\r\n 'move-in-progress': 'moveInProgress',\r\n query: 'query',\r\n position: 'position'\r\n });\r\n //custom item template\r\n if (angular.isDefined(attrs.typeaheadTemplateUrl)) {\r\n popUpEl.attr('template-url', attrs.typeaheadTemplateUrl);\r\n }\r\n\r\n if (angular.isDefined(attrs.typeaheadPopupTemplateUrl)) {\r\n popUpEl.attr('popup-template-url', attrs.typeaheadPopupTemplateUrl);\r\n }\r\n\r\n var resetMatches = function() {\r\n scope.matches = [];\r\n scope.activeIdx = -1;\r\n element.attr('aria-expanded', false);\r\n };\r\n\r\n var getMatchId = function(index) {\r\n return popupId + '-option-' + index;\r\n };\r\n\r\n // Indicate that the specified match is the active (pre-selected) item in the list owned by this typeahead.\r\n // This attribute is added or removed automatically when the `activeIdx` changes.\r\n scope.$watch('activeIdx', function(index) {\r\n if (index < 0) {\r\n element.removeAttr('aria-activedescendant');\r\n } else {\r\n element.attr('aria-activedescendant', getMatchId(index));\r\n }\r\n });\r\n\r\n var inputIsExactMatch = function(inputValue, index) {\r\n if (scope.matches.length > index && inputValue) {\r\n return inputValue.toUpperCase() === scope.matches[index].label.toUpperCase();\r\n }\r\n\r\n return false;\r\n };\r\n\r\n var getMatchesAsync = function(inputValue) {\r\n var locals = {$viewValue: inputValue};\r\n isLoadingSetter(originalScope, true);\r\n isNoResultsSetter(originalScope, false);\r\n $q.when(parserResult.source(originalScope, locals)).then(function(matches) {\r\n //it might happen that several async queries were in progress if a user were typing fast\r\n //but we are interested only in responses that correspond to the current view value\r\n var onCurrentRequest = (inputValue === modelCtrl.$viewValue);\r\n if (onCurrentRequest && hasFocus) {\r\n if (matches && matches.length > 0) {\r\n\r\n scope.activeIdx = focusFirst ? 0 : -1;\r\n isNoResultsSetter(originalScope, false);\r\n scope.matches.length = 0;\r\n\r\n //transform labels\r\n for (var i = 0; i < matches.length; i++) {\r\n locals[parserResult.itemName] = matches[i];\r\n scope.matches.push({\r\n id: getMatchId(i),\r\n label: parserResult.viewMapper(scope, locals),\r\n model: matches[i]\r\n });\r\n }\r\n\r\n scope.query = inputValue;\r\n //position pop-up with matches - we need to re-calculate its position each time we are opening a window\r\n //with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page\r\n //due to other elements being rendered\r\n recalculatePosition();\r\n\r\n element.attr('aria-expanded', true);\r\n\r\n //Select the single remaining option if user input matches\r\n if (selectOnExact && scope.matches.length === 1 && inputIsExactMatch(inputValue, 0)) {\r\n scope.select(0);\r\n }\r\n } else {\r\n resetMatches();\r\n isNoResultsSetter(originalScope, true);\r\n }\r\n }\r\n if (onCurrentRequest) {\r\n isLoadingSetter(originalScope, false);\r\n }\r\n }, function() {\r\n resetMatches();\r\n isLoadingSetter(originalScope, false);\r\n isNoResultsSetter(originalScope, true);\r\n });\r\n };\r\n\r\n // bind events only if appendToBody params exist - performance feature\r\n if (appendToBody) {\r\n angular.element($window).bind('resize', fireRecalculating);\r\n $document.find('body').bind('scroll', fireRecalculating);\r\n }\r\n\r\n // Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later\r\n var timeoutEventPromise;\r\n\r\n // Default progress type\r\n scope.moveInProgress = false;\r\n\r\n function fireRecalculating() {\r\n if (!scope.moveInProgress) {\r\n scope.moveInProgress = true;\r\n scope.$digest();\r\n }\r\n\r\n // Cancel previous timeout\r\n if (timeoutEventPromise) {\r\n $timeout.cancel(timeoutEventPromise);\r\n }\r\n\r\n // Debounced executing recalculate after events fired\r\n timeoutEventPromise = $timeout(function() {\r\n // if popup is visible\r\n if (scope.matches.length) {\r\n recalculatePosition();\r\n }\r\n\r\n scope.moveInProgress = false;\r\n scope.$digest();\r\n }, eventDebounceTime);\r\n }\r\n\r\n // recalculate actual position and set new values to scope\r\n // after digest loop is popup in right position\r\n function recalculatePosition() {\r\n scope.position = appendToBody ? $position.offset(element) : $position.position(element);\r\n scope.position.top += element.prop('offsetHeight');\r\n }\r\n\r\n resetMatches();\r\n\r\n //we need to propagate user's query so we can higlight matches\r\n scope.query = undefined;\r\n\r\n //Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later\r\n var timeoutPromise;\r\n\r\n var scheduleSearchWithTimeout = function(inputValue) {\r\n timeoutPromise = $timeout(function() {\r\n getMatchesAsync(inputValue);\r\n }, waitTime);\r\n };\r\n\r\n var cancelPreviousTimeout = function() {\r\n if (timeoutPromise) {\r\n $timeout.cancel(timeoutPromise);\r\n }\r\n };\r\n\r\n //plug into $parsers pipeline to open a typeahead on view changes initiated from DOM\r\n //$parsers kick-in on all the changes coming from the view as well as manually triggered by $setViewValue\r\n modelCtrl.$parsers.unshift(function(inputValue) {\r\n hasFocus = true;\r\n\r\n if (minLength === 0 || inputValue && inputValue.length >= minLength) {\r\n if (waitTime > 0) {\r\n cancelPreviousTimeout();\r\n scheduleSearchWithTimeout(inputValue);\r\n } else {\r\n getMatchesAsync(inputValue);\r\n }\r\n } else {\r\n isLoadingSetter(originalScope, false);\r\n cancelPreviousTimeout();\r\n resetMatches();\r\n }\r\n\r\n if (isEditable) {\r\n return inputValue;\r\n } else {\r\n if (!inputValue) {\r\n // Reset in case user had typed something previously.\r\n modelCtrl.$setValidity('editable', true);\r\n return null;\r\n } else {\r\n modelCtrl.$setValidity('editable', false);\r\n return undefined;\r\n }\r\n }\r\n });\r\n\r\n modelCtrl.$formatters.push(function(modelValue) {\r\n var candidateViewValue, emptyViewValue;\r\n var locals = {};\r\n\r\n // The validity may be set to false via $parsers (see above) if\r\n // the model is restricted to selected values. If the model\r\n // is set manually it is considered to be valid.\r\n if (!isEditable) {\r\n modelCtrl.$setValidity('editable', true);\r\n }\r\n\r\n if (inputFormatter) {\r\n locals.$model = modelValue;\r\n return inputFormatter(originalScope, locals);\r\n } else {\r\n //it might happen that we don't have enough info to properly render input value\r\n //we need to check for this situation and simply return model value if we can't apply custom formatting\r\n locals[parserResult.itemName] = modelValue;\r\n candidateViewValue = parserResult.viewMapper(originalScope, locals);\r\n locals[parserResult.itemName] = undefined;\r\n emptyViewValue = parserResult.viewMapper(originalScope, locals);\r\n\r\n return candidateViewValue!== emptyViewValue ? candidateViewValue : modelValue;\r\n }\r\n });\r\n\r\n scope.select = function(activeIdx) {\r\n //called from within the $digest() cycle\r\n var locals = {};\r\n var model, item;\r\n\r\n selected = true;\r\n locals[parserResult.itemName] = item = scope.matches[activeIdx].model;\r\n model = parserResult.modelMapper(originalScope, locals);\r\n $setModelValue(originalScope, model);\r\n modelCtrl.$setValidity('editable', true);\r\n modelCtrl.$setValidity('parse', true);\r\n\r\n onSelectCallback(originalScope, {\r\n $item: item,\r\n $model: model,\r\n $label: parserResult.viewMapper(originalScope, locals)\r\n });\r\n\r\n resetMatches();\r\n\r\n //return focus to the input element if a match was selected via a mouse click event\r\n // use timeout to avoid $rootScope:inprog error\r\n if (scope.$eval(attrs.typeaheadFocusOnSelect) !== false) {\r\n $timeout(function() { element[0].focus(); }, 0, false);\r\n }\r\n };\r\n\r\n //bind keyboard events: arrows up(38) / down(40), enter(13) and tab(9), esc(27)\r\n element.bind('keydown', function(evt) {\r\n //typeahead is open and an \"interesting\" key was pressed\r\n if (scope.matches.length === 0 || HOT_KEYS.indexOf(evt.which) === -1) {\r\n return;\r\n }\r\n\r\n // if there's nothing selected (i.e. focusFirst) and enter or tab is hit, clear the results\r\n if (scope.activeIdx === -1 && (evt.which === 9 || evt.which === 13)) {\r\n resetMatches();\r\n scope.$digest();\r\n return;\r\n }\r\n\r\n evt.preventDefault();\r\n\r\n if (evt.which === 40) {\r\n scope.activeIdx = (scope.activeIdx + 1) % scope.matches.length;\r\n scope.$digest();\r\n\r\n } else if (evt.which === 38) {\r\n scope.activeIdx = (scope.activeIdx > 0 ? scope.activeIdx : scope.matches.length) - 1;\r\n scope.$digest();\r\n\r\n } else if (evt.which === 13 || evt.which === 9) {\r\n scope.$apply(function () {\r\n scope.select(scope.activeIdx);\r\n });\r\n\r\n } else if (evt.which === 27) {\r\n evt.stopPropagation();\r\n\r\n resetMatches();\r\n scope.$digest();\r\n }\r\n });\r\n\r\n element.bind('blur', function() {\r\n if (isSelectOnBlur && scope.matches.length && scope.activeIdx !== -1 && !selected) {\r\n selected = true;\r\n scope.$apply(function() {\r\n scope.select(scope.activeIdx);\r\n });\r\n }\r\n hasFocus = false;\r\n selected = false;\r\n });\r\n\r\n // Keep reference to click handler to unbind it.\r\n var dismissClickHandler = function(evt) {\r\n // Issue #3973\r\n // Firefox treats right click as a click on document\r\n if (element[0] !== evt.target && evt.which !== 3 && scope.matches.length !== 0) {\r\n resetMatches();\r\n if (!$rootScope.$$phase) {\r\n scope.$digest();\r\n }\r\n }\r\n };\r\n\r\n $document.bind('click', dismissClickHandler);\r\n\r\n originalScope.$on('$destroy', function() {\r\n $document.unbind('click', dismissClickHandler);\r\n if (appendToBody) {\r\n $popup.remove();\r\n }\r\n // Prevent jQuery cache memory leak\r\n popUpEl.remove();\r\n });\r\n\r\n var $popup = $compile(popUpEl)(scope);\r\n\r\n if (appendToBody) {\r\n $document.find('body').append($popup);\r\n } else {\r\n element.after($popup);\r\n }\r\n }\r\n };\r\n\r\n }])\r\n\r\n .directive('typeaheadPopup', function() {\r\n return {\r\n restrict: 'EA',\r\n scope: {\r\n matches: '=',\r\n query: '=',\r\n active: '=',\r\n position: '&',\r\n moveInProgress: '=',\r\n select: '&'\r\n },\r\n replace: true,\r\n templateUrl: function(element, attrs) {\r\n return attrs.popupTemplateUrl || 'template/typeahead/typeahead-popup.html';\r\n },\r\n link: function(scope, element, attrs) {\r\n scope.templateUrl = attrs.templateUrl;\r\n\r\n scope.isOpen = function() {\r\n return scope.matches.length > 0;\r\n };\r\n\r\n scope.isActive = function(matchIdx) {\r\n return scope.active == matchIdx;\r\n };\r\n\r\n scope.selectActive = function(matchIdx) {\r\n scope.active = matchIdx;\r\n };\r\n\r\n scope.selectMatch = function(activeIdx) {\r\n scope.select({activeIdx:activeIdx});\r\n };\r\n }\r\n };\r\n })\r\n\r\n .directive('typeaheadMatch', ['$templateRequest', '$compile', '$parse', function($templateRequest, $compile, $parse) {\r\n return {\r\n restrict: 'EA',\r\n scope: {\r\n index: '=',\r\n match: '=',\r\n query: '='\r\n },\r\n link:function(scope, element, attrs) {\r\n var tplUrl = $parse(attrs.templateUrl)(scope.$parent) || 'template/typeahead/typeahead-match.html';\r\n $templateRequest(tplUrl).then(function(tplContent) {\r\n $compile(tplContent.trim())(scope, function(clonedElement) {\r\n element.replaceWith(clonedElement);\r\n });\r\n });\r\n }\r\n };\r\n }])\r\n\r\n .filter('typeaheadHighlight', ['$sce', '$injector', '$log', function($sce, $injector, $log) {\r\n var isSanitizePresent;\r\n isSanitizePresent = $injector.has('$sanitize');\r\n\r\n function escapeRegexp(queryToEscape) {\r\n // Regex: capture the whole query string and replace it with the string that will be used to match\r\n // the results, for example if the capture is \"a\" the result will be \\a\r\n return queryToEscape.replace(/([.?*+^$[\\]\\\\(){}|-])/g, '\\\\$1');\r\n }\r\n\r\n function containsHtml(matchItem) {\r\n return /<.*>/g.test(matchItem);\r\n }\r\n\r\n return function(matchItem, query) {\r\n if (!isSanitizePresent && containsHtml(matchItem)) {\r\n $log.warn('Unsafe use of typeahead please use ngSanitize'); // Warn the user about the danger\r\n }\r\n matchItem = query? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '$&') : matchItem; // Replaces the capture string with a the same string inside of a \"strong\" tag\r\n if (!isSanitizePresent) {\r\n matchItem = $sce.trustAsHtml(matchItem); // If $sanitize is not present we pack the string in a $sce object for the ng-bind-html directive\r\n }\r\n return matchItem;\r\n };\r\n }]);\r\n\r\nangular.module(\"template/accordion/accordion-group.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/accordion/accordion-group.html\",\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"

\\n\" +\r\n \" {{heading}}\\n\" +\r\n \"

\\n\" +\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"\t
\\n\" +\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/accordion/accordion.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/accordion/accordion.html\",\r\n \"
\");\r\n}]);\r\n\r\nangular.module(\"template/alert/alert.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/alert/alert.html\",\r\n \"
\\n\" +\r\n \" \\n\" +\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/carousel/carousel.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/carousel/carousel.html\",\r\n \"
\\n\" +\r\n \"
    1\\\">\\n\" +\r\n \"
  1. \\n\" +\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \" 1\\\">\\n\" +\r\n \" 1\\\">\\n\" +\r\n \"
\\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/carousel/slide.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/carousel/slide.html\",\r\n \"
\\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/datepicker/datepicker.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/datepicker/datepicker.html\",\r\n \"
\\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \"
\");\r\n}]);\r\n\r\nangular.module(\"template/datepicker/day.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/datepicker/day.html\",\r\n \"\\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \"
{{::label.abbr}}
{{ weekNumbers[$index] }}\\n\" +\r\n \" \\n\" +\r\n \"
\\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/datepicker/month.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/datepicker/month.html\",\r\n \"\\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \"
\\n\" +\r\n \" \\n\" +\r\n \"
\\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/datepicker/popup.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/datepicker/popup.html\",\r\n \"\\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/datepicker/year.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/datepicker/year.html\",\r\n \"\\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \"
\\n\" +\r\n \" \\n\" +\r\n \"
\\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/modal/backdrop.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/modal/backdrop.html\",\r\n \"
\\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/modal/window.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/modal/window.html\",\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/pagination/pager.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/pagination/pager.html\",\r\n \"\\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/pagination/pagination.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/pagination/pagination.html\",\r\n \"\\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/tooltip/tooltip-html-popup.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/tooltip/tooltip-html-popup.html\",\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/tooltip/tooltip-html-unsafe-popup.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/tooltip/tooltip-html-unsafe-popup.html\",\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/tooltip/tooltip-popup.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/tooltip/tooltip-popup.html\",\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/tooltip/tooltip-template-popup.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/tooltip/tooltip-template-popup.html\",\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/popover/popover-html.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/popover/popover-html.html\",\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"\\n\" +\r\n \"
\\n\" +\r\n \"

\\n\" +\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/popover/popover-template.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/popover/popover-template.html\",\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"\\n\" +\r\n \"
\\n\" +\r\n \"

\\n\" +\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/popover/popover.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/popover/popover.html\",\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"\\n\" +\r\n \"
\\n\" +\r\n \"

\\n\" +\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/progressbar/bar.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/progressbar/bar.html\",\r\n \"
\\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/progressbar/progress.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/progressbar/progress.html\",\r\n \"
\");\r\n}]);\r\n\r\nangular.module(\"template/progressbar/progressbar.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/progressbar/progressbar.html\",\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"
\\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/rating/rating.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/rating/rating.html\",\r\n \"\\n\" +\r\n \" ({{ $index < value ? '*' : ' ' }})\\n\" +\r\n \" \\n\" +\r\n \"\\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/tabs/tab.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/tabs/tab.html\",\r\n \"
  • \\n\" +\r\n \" {{heading}}\\n\" +\r\n \"
  • \\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/tabs/tabset.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/tabs/tabset.html\",\r\n \"
    \\n\" +\r\n \" \\n\" +\r\n \"
    \\n\" +\r\n \"
    \\n\" +\r\n \"
    \\n\" +\r\n \"
    \\n\" +\r\n \"
    \\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/timepicker/timepicker.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/timepicker/timepicker.html\",\r\n \"\\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \" \\n\" +\r\n \"
     
    \\n\" +\r\n \" \\n\" +\r\n \" :\\n\" +\r\n \" \\n\" +\r\n \"
     
    \\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/typeahead/typeahead-match.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/typeahead/typeahead-match.html\",\r\n \"\\n\" +\r\n \"\");\r\n}]);\r\n\r\nangular.module(\"template/typeahead/typeahead-popup.html\", []).run([\"$templateCache\", function($templateCache) {\r\n $templateCache.put(\"template/typeahead/typeahead-popup.html\",\r\n \"\\n\" +\r\n \"\");\r\n}]);\r\n!angular.$$csp() && angular.element(document).find('head').prepend('');\n},{}],4:[function(require,module,exports){\n/**\r\n * @license AngularJS v1.4.0-build.3787+sha.2b64f6e\r\n * (c) 2010-2015 Google, Inc. http://angularjs.org\r\n * License: MIT\r\n */\r\n(function(window, angular, undefined) {'use strict';\r\n\r\n /**\r\n * @ngdoc module\r\n * @name ngCookies\r\n * @description\r\n *\r\n * # ngCookies\r\n *\r\n * The `ngCookies` module provides a convenient wrapper for reading and writing browser cookies.\r\n *\r\n *\r\n *
    \r\n *\r\n * See {@link ngCookies.$cookies `$cookies`} and\r\n * {@link ngCookies.$cookieStore `$cookieStore`} for usage.\r\n */\r\n\r\n\r\n angular.module('ngCookies', ['ng']).\r\n /**\r\n * @ngdoc service\r\n * @name $cookies\r\n *\r\n * @description\r\n * Provides read/write access to browser's cookies.\r\n *\r\n * Only a simple Object is exposed and by adding or removing properties to/from this object, new\r\n * cookies are created/deleted at the end of current $eval.\r\n * The object's properties can only be strings.\r\n *\r\n * Requires the {@link ngCookies `ngCookies`} module to be installed.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * angular.module('cookiesExample', ['ngCookies'])\r\n * .controller('ExampleController', ['$cookies', function($cookies) {\r\n * // Retrieving a cookie\r\n * var favoriteCookie = $cookies.myFavorite;\r\n * // Setting a cookie\r\n * $cookies.myFavorite = 'oatmeal';\r\n * }]);\r\n * ```\r\n */\r\n factory('$cookies', ['$rootScope', '$browser', function($rootScope, $browser) {\r\n var cookies = {},\r\n lastCookies = {},\r\n lastBrowserCookies,\r\n runEval = false,\r\n copy = angular.copy,\r\n isUndefined = angular.isUndefined;\r\n\r\n //creates a poller fn that copies all cookies from the $browser to service & inits the service\r\n $browser.addPollFn(function() {\r\n var currentCookies = $browser.cookies();\r\n if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl\r\n lastBrowserCookies = currentCookies;\r\n copy(currentCookies, lastCookies);\r\n copy(currentCookies, cookies);\r\n if (runEval) $rootScope.$apply();\r\n }\r\n })();\r\n\r\n runEval = true;\r\n\r\n //at the end of each eval, push cookies\r\n //TODO: this should happen before the \"delayed\" watches fire, because if some cookies are not\r\n // strings or browser refuses to store some cookies, we update the model in the push fn.\r\n $rootScope.$watch(push);\r\n\r\n return cookies;\r\n\r\n\r\n /**\r\n * Pushes all the cookies from the service to the browser and verifies if all cookies were\r\n * stored.\r\n */\r\n function push() {\r\n var name,\r\n value,\r\n browserCookies,\r\n updated;\r\n\r\n //delete any cookies deleted in $cookies\r\n for (name in lastCookies) {\r\n if (isUndefined(cookies[name])) {\r\n $browser.cookies(name, undefined);\r\n }\r\n }\r\n\r\n //update all cookies updated in $cookies\r\n for (name in cookies) {\r\n value = cookies[name];\r\n if (!angular.isString(value)) {\r\n value = '' + value;\r\n cookies[name] = value;\r\n }\r\n if (value !== lastCookies[name]) {\r\n $browser.cookies(name, value);\r\n updated = true;\r\n }\r\n }\r\n\r\n //verify what was actually stored\r\n if (updated) {\r\n updated = false;\r\n browserCookies = $browser.cookies();\r\n\r\n for (name in cookies) {\r\n if (cookies[name] !== browserCookies[name]) {\r\n //delete or reset all cookies that the browser dropped from $cookies\r\n if (isUndefined(browserCookies[name])) {\r\n delete cookies[name];\r\n } else {\r\n cookies[name] = browserCookies[name];\r\n }\r\n updated = true;\r\n }\r\n }\r\n }\r\n }\r\n }]).\r\n\r\n\r\n /**\r\n * @ngdoc service\r\n * @name $cookieStore\r\n * @requires $cookies\r\n *\r\n * @description\r\n * Provides a key-value (string-object) storage, that is backed by session cookies.\r\n * Objects put or retrieved from this storage are automatically serialized or\r\n * deserialized by angular's toJson/fromJson.\r\n *\r\n * Requires the {@link ngCookies `ngCookies`} module to be installed.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * angular.module('cookieStoreExample', ['ngCookies'])\r\n * .controller('ExampleController', ['$cookieStore', function($cookieStore) {\r\n * // Put cookie\r\n * $cookieStore.put('myFavorite','oatmeal');\r\n * // Get cookie\r\n * var favoriteCookie = $cookieStore.get('myFavorite');\r\n * // Removing a cookie\r\n * $cookieStore.remove('myFavorite');\r\n * }]);\r\n * ```\r\n */\r\n factory('$cookieStore', ['$cookies', function($cookies) {\r\n\r\n return {\r\n /**\r\n * @ngdoc method\r\n * @name $cookieStore#get\r\n *\r\n * @description\r\n * Returns the value of given cookie key\r\n *\r\n * @param {string} key Id to use for lookup.\r\n * @returns {Object} Deserialized cookie value.\r\n */\r\n get: function(key) {\r\n var value = $cookies[key];\r\n return value ? angular.fromJson(value) : value;\r\n },\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $cookieStore#put\r\n *\r\n * @description\r\n * Sets a value for given cookie key\r\n *\r\n * @param {string} key Id for the `value`.\r\n * @param {Object} value Value to be stored.\r\n */\r\n put: function(key, value) {\r\n $cookies[key] = angular.toJson(value);\r\n },\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $cookieStore#remove\r\n *\r\n * @description\r\n * Remove given cookie\r\n *\r\n * @param {string} key Id of the key-value pair to delete.\r\n */\r\n remove: function(key) {\r\n delete $cookies[key];\r\n }\r\n };\r\n\r\n }]);\r\n\r\n\r\n})(window, window.angular);\n},{}],5:[function(require,module,exports){\n/*! angular-google-maps 2.1.6 2015-08-27\r\n * AngularJS directives for Google Maps\r\n * git: https://github.com/angular-ui/angular-google-maps.git\r\n */\r\n;\r\n(function( window, angular, undefined ){\r\n 'use strict';\r\n/*\r\n!\r\nThe MIT License\r\n\r\nCopyright (c) 2010-2013 Google, Inc. http://angularjs.org\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the 'Software'), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in\r\nall copies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\nTHE SOFTWARE.\r\n\r\nangular-google-maps\r\nhttps://github.com/angular-ui/angular-google-maps\r\n\r\n@authors\r\nNicolas Laplante - https://plus.google.com/108189012221374960701\r\nNicholas McCready - https://twitter.com/nmccready\r\n */\r\n\r\n(function() {\r\n angular.module('uiGmapgoogle-maps.providers', []);\r\n\r\n angular.module('uiGmapgoogle-maps.wrapped', []);\r\n\r\n angular.module('uiGmapgoogle-maps.extensions', ['uiGmapgoogle-maps.wrapped', 'uiGmapgoogle-maps.providers']);\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api.utils', ['uiGmapgoogle-maps.extensions']);\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api.managers', []);\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api.options', ['uiGmapgoogle-maps.directives.api.utils']);\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api.options.builders', []);\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api.models.child', ['uiGmapgoogle-maps.directives.api.utils', 'uiGmapgoogle-maps.directives.api.options', 'uiGmapgoogle-maps.directives.api.options.builders']);\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api.models.parent', ['uiGmapgoogle-maps.directives.api.managers', 'uiGmapgoogle-maps.directives.api.models.child', 'uiGmapgoogle-maps.providers']);\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api', ['uiGmapgoogle-maps.directives.api.models.parent']);\r\n\r\n angular.module('uiGmapgoogle-maps', ['uiGmapgoogle-maps.directives.api', 'uiGmapgoogle-maps.providers']);\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module('uiGmapgoogle-maps.providers').factory('uiGmapMapScriptLoader', [\r\n '$q', 'uiGmapuuid', function($q, uuid) {\r\n var getScriptUrl, includeScript, isGoogleMapsLoaded, scriptId;\r\n scriptId = void 0;\r\n getScriptUrl = function(options) {\r\n if (options.china) {\r\n return 'http://maps.google.cn/maps/api/js?';\r\n } else {\r\n if (options.transport === 'auto') {\r\n return '//maps.googleapis.com/maps/api/js?';\r\n } else {\r\n return options.transport + '://maps.googleapis.com/maps/api/js?';\r\n }\r\n }\r\n };\r\n includeScript = function(options) {\r\n var omitOptions, query, script;\r\n omitOptions = ['transport', 'isGoogleMapsForWork', 'china'];\r\n if (options.isGoogleMapsForWork) {\r\n omitOptions.push('key');\r\n }\r\n query = _.map(_.omit(options, omitOptions), function(v, k) {\r\n return k + '=' + v;\r\n });\r\n if (scriptId) {\r\n document.getElementById(scriptId).remove();\r\n }\r\n query = query.join('&');\r\n script = document.createElement('script');\r\n script.id = scriptId = \"ui_gmap_map_load_\" + (uuid.generate());\r\n script.type = 'text/javascript';\r\n script.src = getScriptUrl(options) + query;\r\n return document.body.appendChild(script);\r\n };\r\n isGoogleMapsLoaded = function() {\r\n return angular.isDefined(window.google) && angular.isDefined(window.google.maps);\r\n };\r\n return {\r\n load: function(options) {\r\n var deferred, randomizedFunctionName;\r\n deferred = $q.defer();\r\n if (isGoogleMapsLoaded()) {\r\n deferred.resolve(window.google.maps);\r\n return deferred.promise;\r\n }\r\n randomizedFunctionName = options.callback = 'onGoogleMapsReady' + Math.round(Math.random() * 1000);\r\n window[randomizedFunctionName] = function() {\r\n window[randomizedFunctionName] = null;\r\n deferred.resolve(window.google.maps);\r\n };\r\n if (window.navigator.connection && window.Connection && window.navigator.connection.type === window.Connection.NONE) {\r\n document.addEventListener('online', function() {\r\n if (!isGoogleMapsLoaded()) {\r\n return includeScript(options);\r\n }\r\n });\r\n } else {\r\n includeScript(options);\r\n }\r\n return deferred.promise;\r\n }\r\n };\r\n }\r\n ]).provider('uiGmapGoogleMapApi', function() {\r\n this.options = {\r\n transport: 'https',\r\n isGoogleMapsForWork: false,\r\n china: false,\r\n v: '3',\r\n libraries: '',\r\n language: 'en',\r\n sensor: 'false'\r\n };\r\n this.configure = function(options) {\r\n angular.extend(this.options, options);\r\n };\r\n this.$get = [\r\n 'uiGmapMapScriptLoader', (function(_this) {\r\n return function(loader) {\r\n return loader.load(_this.options);\r\n };\r\n })(this)\r\n ];\r\n return this;\r\n });\r\n\r\n}).call(this);\r\n;(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },\r\n extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.extensions').service('uiGmapExtendGWin', function() {\r\n return {\r\n init: _.once(function() {\r\n var uiGmapInfoBox;\r\n if (!(google || (typeof google !== \"undefined\" && google !== null ? google.maps : void 0) || (google.maps.InfoWindow != null))) {\r\n return;\r\n }\r\n google.maps.InfoWindow.prototype._open = google.maps.InfoWindow.prototype.open;\r\n google.maps.InfoWindow.prototype._close = google.maps.InfoWindow.prototype.close;\r\n google.maps.InfoWindow.prototype._isOpen = false;\r\n google.maps.InfoWindow.prototype.open = function(map, anchor, recurse) {\r\n if (recurse != null) {\r\n return;\r\n }\r\n this._isOpen = true;\r\n this._open(map, anchor, true);\r\n };\r\n google.maps.InfoWindow.prototype.close = function(recurse) {\r\n if (recurse != null) {\r\n return;\r\n }\r\n this._isOpen = false;\r\n this._close(true);\r\n };\r\n google.maps.InfoWindow.prototype.isOpen = function(val) {\r\n if (val == null) {\r\n val = void 0;\r\n }\r\n if (val == null) {\r\n return this._isOpen;\r\n } else {\r\n return this._isOpen = val;\r\n }\r\n };\r\n\r\n /*\r\n Do the same for InfoBox\r\n TODO: Clean this up so the logic is defined once, wait until develop becomes master as this will be easier\r\n */\r\n if (window.InfoBox) {\r\n window.InfoBox.prototype._open = window.InfoBox.prototype.open;\r\n window.InfoBox.prototype._close = window.InfoBox.prototype.close;\r\n window.InfoBox.prototype._isOpen = false;\r\n window.InfoBox.prototype.open = function(map, anchor) {\r\n this._isOpen = true;\r\n this._open(map, anchor);\r\n };\r\n window.InfoBox.prototype.close = function() {\r\n this._isOpen = false;\r\n this._close();\r\n };\r\n window.InfoBox.prototype.isOpen = function(val) {\r\n if (val == null) {\r\n val = void 0;\r\n }\r\n if (val == null) {\r\n return this._isOpen;\r\n } else {\r\n return this._isOpen = val;\r\n }\r\n };\r\n uiGmapInfoBox = (function(superClass) {\r\n extend(uiGmapInfoBox, superClass);\r\n\r\n function uiGmapInfoBox(opts) {\r\n this.getOrigCloseBoxImg_ = bind(this.getOrigCloseBoxImg_, this);\r\n this.getCloseBoxDiv_ = bind(this.getCloseBoxDiv_, this);\r\n var box;\r\n box = new window.InfoBox(opts);\r\n _.extend(this, box);\r\n if (opts.closeBoxDiv != null) {\r\n this.closeBoxDiv_ = opts.closeBoxDiv;\r\n }\r\n }\r\n\r\n uiGmapInfoBox.prototype.getCloseBoxDiv_ = function() {\r\n return this.closeBoxDiv_;\r\n };\r\n\r\n uiGmapInfoBox.prototype.getCloseBoxImg_ = function() {\r\n var div, img;\r\n div = this.getCloseBoxDiv_();\r\n img = this.getOrigCloseBoxImg_();\r\n return div || img;\r\n };\r\n\r\n uiGmapInfoBox.prototype.getOrigCloseBoxImg_ = function() {\r\n var img;\r\n img = \"\";\r\n if (this.closeBoxURL_ !== \"\") {\r\n img = \"\";\r\n }\r\n return img;\r\n };\r\n\r\n return uiGmapInfoBox;\r\n\r\n })(window.InfoBox);\r\n window.uiGmapInfoBox = uiGmapInfoBox;\r\n }\r\n if (window.MarkerLabel_) {\r\n return window.MarkerLabel_.prototype.setContent = function() {\r\n var content;\r\n content = this.marker_.get('labelContent');\r\n if (!content || _.isEqual(this.oldContent, content)) {\r\n return;\r\n }\r\n if (typeof (content != null ? content.nodeType : void 0) === 'undefined') {\r\n this.labelDiv_.innerHTML = content;\r\n this.eventDiv_.innerHTML = this.labelDiv_.innerHTML;\r\n this.oldContent = content;\r\n } else {\r\n this.labelDiv_.innerHTML = '';\r\n this.labelDiv_.appendChild(content);\r\n content = content.cloneNode(true);\r\n this.labelDiv_.innerHTML = '';\r\n this.eventDiv_.appendChild(content);\r\n this.oldContent = content;\r\n }\r\n };\r\n }\r\n })\r\n };\r\n });\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module('uiGmapgoogle-maps.extensions').service('uiGmapLodash', function() {\r\n var baseGet, baseToString, get, reIsDeepProp, reIsPlainProp, rePropName, toObject, toPath;\r\n if (_.get == null) {\r\n reIsDeepProp = /\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\n\\\\]|\\\\.)*?\\1)\\]/;\r\n reIsPlainProp = /^\\w*$/;\r\n rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\n\\\\]|\\\\.)*?)\\2)\\]/g;\r\n\r\n /**\r\n * Converts `value` to an object if it's not one.\r\n *\r\n * @private\r\n * @param {*} value The value to process.\r\n * @returns {Object} Returns the object.\r\n */\r\n toObject = function(value) {\r\n if (_.isObject(value)) {\r\n return value;\r\n } else {\r\n return Object(value);\r\n }\r\n };\r\n\r\n /**\r\n * Converts `value` to a string if it's not one. An empty string is returned\r\n * for `null` or `undefined` values.\r\n *\r\n * @private\r\n * @param {*} value The value to process.\r\n * @returns {string} Returns the string.\r\n */\r\n baseToString = function(value) {\r\n if (value === null) {\r\n return '';\r\n } else {\r\n return value + '';\r\n }\r\n };\r\n\r\n /**\r\n * Converts `value` to property path array if it's not one.\r\n *\r\n * @private\r\n * @param {*} value The value to process.\r\n * @returns {Array} Returns the property path array.\r\n */\r\n toPath = function(value) {\r\n var result;\r\n if (_.isArray(value)) {\r\n return value;\r\n }\r\n result = [];\r\n baseToString(value).replace(rePropName, function(match, number, quote, string) {\r\n result.push(quote ? string.replace(reEscapeChar, '$1') : number || match);\r\n });\r\n return result;\r\n };\r\n\r\n /**\r\n * The base implementation of `get` without support for string paths\r\n * and default values.\r\n *\r\n * @private\r\n * @param {Object} object The object to query.\r\n * @param {Array} path The path of the property to get.\r\n * @param {string} [pathKey] The key representation of path.\r\n * @returns {*} Returns the resolved value.\r\n */\r\n baseGet = function(object, path, pathKey) {\r\n var index, length;\r\n if (object === null) {\r\n return;\r\n }\r\n if (pathKey !== void 0 && pathKey in toObject(object)) {\r\n path = [pathKey];\r\n }\r\n index = 0;\r\n length = path.length;\r\n while (!_.isUndefined(object) && index < length) {\r\n object = object[path[index++]];\r\n }\r\n if (index && index === length) {\r\n return object;\r\n } else {\r\n return void 0;\r\n }\r\n };\r\n\r\n /**\r\n * Gets the property value at `path` of `object`. If the resolved value is\r\n * `undefined` the `defaultValue` is used in its place.\r\n *\r\n * @static\r\n * @memberOf _\r\n * @category Object\r\n * @param {Object} object The object to query.\r\n * @param {Array|string} path The path of the property to get.\r\n * @param {*} [defaultValue] The value returned if the resolved value is `undefined`.\r\n * @returns {*} Returns the resolved value.\r\n * @example\r\n *\r\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\r\n *\r\n * _.get(object, 'a[0].b.c');\r\n * // => 3\r\n *\r\n * _.get(object, ['a', '0', 'b', 'c']);\r\n * // => 3\r\n *\r\n * _.get(object, 'a.b.c', 'default');\r\n * // => 'default'\r\n */\r\n get = function(object, path, defaultValue) {\r\n var result;\r\n result = object === null ? void 0 : baseGet(object, toPath(path), path + '');\r\n if (result === void 0) {\r\n return defaultValue;\r\n } else {\r\n return result;\r\n }\r\n };\r\n _.get = get;\r\n }\r\n\r\n /*\r\n Author Nick McCready\r\n Intersection of Objects if the arrays have something in common each intersecting object will be returned\r\n in an new array.\r\n */\r\n this.intersectionObjects = function(array1, array2, comparison) {\r\n var res;\r\n if (comparison == null) {\r\n comparison = void 0;\r\n }\r\n res = _.map(array1, (function(_this) {\r\n return function(obj1) {\r\n return _.find(array2, function(obj2) {\r\n if (comparison != null) {\r\n return comparison(obj1, obj2);\r\n } else {\r\n return _.isEqual(obj1, obj2);\r\n }\r\n });\r\n };\r\n })(this));\r\n return _.filter(res, function(o) {\r\n return o != null;\r\n });\r\n };\r\n this.containsObject = _.includeObject = function(obj, target, comparison) {\r\n if (comparison == null) {\r\n comparison = void 0;\r\n }\r\n if (obj === null) {\r\n return false;\r\n }\r\n return _.any(obj, (function(_this) {\r\n return function(value) {\r\n if (comparison != null) {\r\n return comparison(value, target);\r\n } else {\r\n return _.isEqual(value, target);\r\n }\r\n };\r\n })(this));\r\n };\r\n this.differenceObjects = function(array1, array2, comparison) {\r\n if (comparison == null) {\r\n comparison = void 0;\r\n }\r\n return _.filter(array1, (function(_this) {\r\n return function(value) {\r\n return !_this.containsObject(array2, value, comparison);\r\n };\r\n })(this));\r\n };\r\n this.withoutObjects = this.differenceObjects;\r\n this.indexOfObject = function(array, item, comparison, isSorted) {\r\n var i, length;\r\n if (array == null) {\r\n return -1;\r\n }\r\n i = 0;\r\n length = array.length;\r\n if (isSorted) {\r\n if (typeof isSorted === \"number\") {\r\n i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted);\r\n } else {\r\n i = _.sortedIndex(array, item);\r\n return (array[i] === item ? i : -1);\r\n }\r\n }\r\n while (i < length) {\r\n if (comparison != null) {\r\n if (comparison(array[i], item)) {\r\n return i;\r\n }\r\n } else {\r\n if (_.isEqual(array[i], item)) {\r\n return i;\r\n }\r\n }\r\n i++;\r\n }\r\n return -1;\r\n };\r\n this.isNullOrUndefined = function(thing) {\r\n return _.isNull(thing || _.isUndefined(thing));\r\n };\r\n return this;\r\n });\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module('uiGmapgoogle-maps.extensions').factory('uiGmapString', function() {\r\n return function(str) {\r\n this.contains = function(value, fromIndex) {\r\n return str.indexOf(value, fromIndex) !== -1;\r\n };\r\n return this;\r\n };\r\n });\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmap_sync', [\r\n function() {\r\n return {\r\n fakePromise: function() {\r\n var _cb;\r\n _cb = void 0;\r\n return {\r\n then: function(cb) {\r\n return _cb = cb;\r\n },\r\n resolve: function() {\r\n return _cb.apply(void 0, arguments);\r\n }\r\n };\r\n }\r\n };\r\n }\r\n ]).service('uiGmap_async', [\r\n '$timeout', 'uiGmapPromise', 'uiGmapLogger', '$q', 'uiGmapDataStructures', 'uiGmapGmapUtil', function($timeout, uiGmapPromise, $log, $q, uiGmapDataStructures, uiGmapGmapUtil) {\r\n var ExposedPromise, PromiseQueueManager, SniffedPromise, _getArrayAndKeys, _getIterateeValue, defaultChunkSize, doChunk, doSkippPromise, each, errorObject, isInProgress, kickPromise, logTryCatch, managePromiseQueue, map, maybeCancelPromises, promiseStatus, promiseTypes, tryCatch;\r\n promiseTypes = uiGmapPromise.promiseTypes;\r\n isInProgress = uiGmapPromise.isInProgress;\r\n promiseStatus = uiGmapPromise.promiseStatus;\r\n ExposedPromise = uiGmapPromise.ExposedPromise;\r\n SniffedPromise = uiGmapPromise.SniffedPromise;\r\n kickPromise = function(sniffedPromise, cancelCb) {\r\n var promise;\r\n promise = sniffedPromise.promise();\r\n promise.promiseType = sniffedPromise.promiseType;\r\n if (promise.$$state) {\r\n $log.debug(\"promiseType: \" + promise.promiseType + \", state: \" + (promiseStatus(promise.$$state.status)));\r\n }\r\n promise.cancelCb = cancelCb;\r\n return promise;\r\n };\r\n doSkippPromise = function(sniffedPromise, lastPromise) {\r\n if (sniffedPromise.promiseType === promiseTypes.create && lastPromise.promiseType !== promiseTypes[\"delete\"] && lastPromise.promiseType !== promiseTypes.init) {\r\n $log.debug(\"lastPromise.promiseType \" + lastPromise.promiseType + \", newPromiseType: \" + sniffedPromise.promiseType + \", SKIPPED MUST COME AFTER DELETE ONLY\");\r\n return true;\r\n }\r\n return false;\r\n };\r\n maybeCancelPromises = function(queue, sniffedPromise, lastPromise) {\r\n var first;\r\n if (sniffedPromise.promiseType === promiseTypes[\"delete\"] && lastPromise.promiseType !== promiseTypes[\"delete\"]) {\r\n if ((lastPromise.cancelCb != null) && _.isFunction(lastPromise.cancelCb) && isInProgress(lastPromise)) {\r\n $log.debug(\"promiseType: \" + sniffedPromise.promiseType + \", CANCELING LAST PROMISE type: \" + lastPromise.promiseType);\r\n lastPromise.cancelCb('cancel safe');\r\n first = queue.peek();\r\n if ((first != null) && isInProgress(first)) {\r\n if (first.hasOwnProperty(\"cancelCb\") && _.isFunction(first.cancelCb)) {\r\n $log.debug(\"promiseType: \" + first.promiseType + \", CANCELING FIRST PROMISE type: \" + first.promiseType);\r\n return first.cancelCb('cancel safe');\r\n } else {\r\n return $log.warn('first promise was not cancelable');\r\n }\r\n }\r\n }\r\n }\r\n };\r\n\r\n /*\r\n From a High Level:\r\n This is a SniffedPromiseQueueManager (looking to rename) where the queue is existingPiecesObj.existingPieces.\r\n This is a function and should not be considered a class.\r\n So it is run to manage the state (cancel, skip, link) as needed.\r\n Purpose:\r\n The whole point is to check if there is existing async work going on. If so we wait on it.\r\n \r\n arguments:\r\n - existingPiecesObj = Queue\r\n - sniffedPromise = object wrapper holding a function to a pending (function) promise (promise: fnPromise)\r\n with its intended type.\r\n - cancelCb = callback which accepts a string, this string is intended to be returned at the end of _async.each iterator\r\n \r\n Where the cancelCb passed msg is 'cancel safe' _async.each will drop out and fall through. Thus canceling the promise\r\n gracefully without messing up state.\r\n \r\n Synopsis:\r\n \r\n - Promises have been broken down to 4 states create, update,delete (3 main) and init. (Helps boil down problems in ordering)\r\n where (init) is special to indicate that it is one of the first or to allow a create promise to work beyond being after a delete\r\n \r\n - Every Promise that comes is is enqueue and linked to the last promise in the queue.\r\n \r\n - A promise can be skipped or canceled to save cycles.\r\n \r\n Saved Cycles:\r\n - Skipped - This will only happen if async work comes in out of order. Where a pending create promise (un-executed) comes in\r\n after a delete promise.\r\n - Canceled - Where an incoming promise (un-executed promise) is of type delete and the any lastPromise is not a delete type.\r\n \r\n \r\n NOTE:\r\n - You should not muck with existingPieces as its state is dependent on this functional loop.\r\n - PromiseQueueManager should not be thought of as a class that has a life expectancy (it has none). It's sole\r\n purpose is to link, skip, and kill promises. It also manages the promise queue existingPieces.\r\n */\r\n PromiseQueueManager = function(existingPiecesObj, sniffedPromise, cancelCb) {\r\n var lastPromise, newPromise;\r\n if (!existingPiecesObj.existingPieces) {\r\n existingPiecesObj.existingPieces = new uiGmapDataStructures.Queue();\r\n return existingPiecesObj.existingPieces.enqueue(kickPromise(sniffedPromise, cancelCb));\r\n } else {\r\n lastPromise = _.last(existingPiecesObj.existingPieces._content);\r\n if (doSkippPromise(sniffedPromise, lastPromise)) {\r\n return;\r\n }\r\n maybeCancelPromises(existingPiecesObj.existingPieces, sniffedPromise, lastPromise);\r\n newPromise = ExposedPromise(lastPromise[\"finally\"](function() {\r\n return kickPromise(sniffedPromise, cancelCb);\r\n }));\r\n newPromise.cancelCb = cancelCb;\r\n newPromise.promiseType = sniffedPromise.promiseType;\r\n existingPiecesObj.existingPieces.enqueue(newPromise);\r\n return lastPromise[\"finally\"](function() {\r\n return existingPiecesObj.existingPieces.dequeue();\r\n });\r\n }\r\n };\r\n managePromiseQueue = function(objectToLock, promiseType, msg, cancelCb, fnPromise) {\r\n var cancelLogger;\r\n if (msg == null) {\r\n msg = '';\r\n }\r\n cancelLogger = function(msg) {\r\n $log.debug(msg + \": \" + msg);\r\n if ((cancelCb != null) && _.isFunction(cancelCb)) {\r\n return cancelCb(msg);\r\n }\r\n };\r\n return PromiseQueueManager(objectToLock, SniffedPromise(fnPromise, promiseType), cancelLogger);\r\n };\r\n defaultChunkSize = 80;\r\n errorObject = {\r\n value: null\r\n };\r\n tryCatch = function(fn, ctx, args) {\r\n var e;\r\n try {\r\n return fn.apply(ctx, args);\r\n } catch (_error) {\r\n e = _error;\r\n errorObject.value = e;\r\n return errorObject;\r\n }\r\n };\r\n logTryCatch = function(fn, ctx, deferred, args) {\r\n var msg, result;\r\n result = tryCatch(fn, ctx, args);\r\n if (result === errorObject) {\r\n msg = \"error within chunking iterator: \" + errorObject.value;\r\n $log.error(msg);\r\n deferred.reject(msg);\r\n }\r\n if (result === 'cancel safe') {\r\n return false;\r\n }\r\n return true;\r\n };\r\n _getIterateeValue = function(collection, array, index) {\r\n var _isArray, valOrKey;\r\n _isArray = collection === array;\r\n valOrKey = array[index];\r\n if (_isArray) {\r\n return valOrKey;\r\n }\r\n return collection[valOrKey];\r\n };\r\n _getArrayAndKeys = function(collection, keys, bailOutCb, cb) {\r\n var array;\r\n if (angular.isArray(collection)) {\r\n array = collection;\r\n } else {\r\n array = keys ? keys : Object.keys(_.omit(collection, ['length', 'forEach', 'map']));\r\n keys = array;\r\n }\r\n if (cb == null) {\r\n cb = bailOutCb;\r\n }\r\n if (angular.isArray(array) && (array === void 0 || (array != null ? array.length : void 0) <= 0)) {\r\n if (cb !== bailOutCb) {\r\n return bailOutCb();\r\n }\r\n }\r\n return cb(array, keys);\r\n };\r\n\r\n /*\r\n Author: Nicholas McCready & jfriend00\r\n _async handles things asynchronous-like :), to allow the UI to be free'd to do other things\r\n Code taken from http://stackoverflow.com/questions/10344498/best-way-to-iterate-over-an-array-without-blocking-the-ui\r\n \r\n The design of any functionality of _async is to be like lodash/underscore and replicate it but call things\r\n asynchronously underneath. Each should be sufficient for most things to be derived from.\r\n \r\n Optional Asynchronous Chunking via promises.\r\n */\r\n doChunk = function(collection, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index, _keys) {\r\n return _getArrayAndKeys(collection, _keys, function(array, keys) {\r\n var cnt, i, keepGoing, val;\r\n if (chunkSizeOrDontChunk && chunkSizeOrDontChunk < array.length) {\r\n cnt = chunkSizeOrDontChunk;\r\n } else {\r\n cnt = array.length;\r\n }\r\n i = index;\r\n keepGoing = true;\r\n while (keepGoing && cnt-- && i < (array ? array.length : i + 1)) {\r\n val = _getIterateeValue(collection, array, i);\r\n keepGoing = angular.isFunction(val) ? true : logTryCatch(chunkCb, void 0, overallD, [val, i]);\r\n ++i;\r\n }\r\n if (array) {\r\n if (keepGoing && i < array.length) {\r\n index = i;\r\n if (chunkSizeOrDontChunk) {\r\n if ((pauseCb != null) && _.isFunction(pauseCb)) {\r\n logTryCatch(pauseCb, void 0, overallD, []);\r\n }\r\n return $timeout(function() {\r\n return doChunk(collection, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index, keys);\r\n }, pauseMilli, false);\r\n }\r\n } else {\r\n return overallD.resolve();\r\n }\r\n }\r\n });\r\n };\r\n each = function(collection, chunk, chunkSizeOrDontChunk, pauseCb, index, pauseMilli, _keys) {\r\n var error, overallD, ret;\r\n if (chunkSizeOrDontChunk == null) {\r\n chunkSizeOrDontChunk = defaultChunkSize;\r\n }\r\n if (index == null) {\r\n index = 0;\r\n }\r\n if (pauseMilli == null) {\r\n pauseMilli = 1;\r\n }\r\n ret = void 0;\r\n overallD = uiGmapPromise.defer();\r\n ret = overallD.promise;\r\n if (!pauseMilli) {\r\n error = 'pause (delay) must be set from _async!';\r\n $log.error(error);\r\n overallD.reject(error);\r\n return ret;\r\n }\r\n return _getArrayAndKeys(collection, _keys, function() {\r\n overallD.resolve();\r\n return ret;\r\n }, function(array, keys) {\r\n doChunk(collection, chunkSizeOrDontChunk, pauseMilli, chunk, pauseCb, overallD, index, keys);\r\n return ret;\r\n });\r\n };\r\n map = function(collection, iterator, chunkSizeOrDontChunk, pauseCb, index, pauseMilli, _keys) {\r\n var results;\r\n results = [];\r\n return _getArrayAndKeys(collection, _keys, function() {\r\n return uiGmapPromise.resolve(results);\r\n }, function(array, keys) {\r\n return each(collection, function(o) {\r\n return results.push(iterator(o));\r\n }, chunkSizeOrDontChunk, pauseCb, index, pauseMilli, keys).then(function() {\r\n return results;\r\n });\r\n });\r\n };\r\n return {\r\n each: each,\r\n map: map,\r\n managePromiseQueue: managePromiseQueue,\r\n promiseLock: managePromiseQueue,\r\n defaultChunkSize: defaultChunkSize,\r\n chunkSizeFrom: function(fromSize, ret) {\r\n if (ret == null) {\r\n ret = void 0;\r\n }\r\n if (_.isNumber(fromSize)) {\r\n ret = fromSize;\r\n }\r\n if (uiGmapGmapUtil.isFalse(fromSize) || fromSize === false) {\r\n ret = false;\r\n }\r\n return ret;\r\n }\r\n };\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapBaseObject', function() {\r\n var BaseObject, baseObjectKeywords;\r\n baseObjectKeywords = ['extended', 'included'];\r\n BaseObject = (function() {\r\n function BaseObject() {}\r\n\r\n BaseObject.extend = function(obj) {\r\n var key, ref, value;\r\n for (key in obj) {\r\n value = obj[key];\r\n if (indexOf.call(baseObjectKeywords, key) < 0) {\r\n this[key] = value;\r\n }\r\n }\r\n if ((ref = obj.extended) != null) {\r\n ref.apply(this);\r\n }\r\n return this;\r\n };\r\n\r\n BaseObject.include = function(obj) {\r\n var key, ref, value;\r\n for (key in obj) {\r\n value = obj[key];\r\n if (indexOf.call(baseObjectKeywords, key) < 0) {\r\n this.prototype[key] = value;\r\n }\r\n }\r\n if ((ref = obj.included) != null) {\r\n ref.apply(this);\r\n }\r\n return this;\r\n };\r\n\r\n return BaseObject;\r\n\r\n })();\r\n return BaseObject;\r\n });\r\n\r\n}).call(this);\r\n;\r\n/*\r\n Useful function callbacks that should be defined at later time.\r\n Mainly to be used for specs to verify creation / linking.\r\n\r\n This is to lead a common design in notifying child stuff.\r\n */\r\n\r\n(function() {\r\n angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapChildEvents', function() {\r\n return {\r\n onChildCreation: function(child) {}\r\n };\r\n });\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapCtrlHandle', [\r\n '$q', function($q) {\r\n var CtrlHandle;\r\n return CtrlHandle = {\r\n handle: function($scope, $element) {\r\n $scope.$on('$destroy', function() {\r\n return CtrlHandle.handle($scope);\r\n });\r\n $scope.deferred = $q.defer();\r\n return {\r\n getScope: function() {\r\n return $scope;\r\n }\r\n };\r\n },\r\n mapPromise: function(scope, ctrl) {\r\n var mapScope;\r\n mapScope = ctrl.getScope();\r\n mapScope.deferred.promise.then(function(map) {\r\n return scope.map = map;\r\n });\r\n return mapScope.deferred.promise;\r\n }\r\n };\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module(\"uiGmapgoogle-maps.directives.api.utils\").service(\"uiGmapEventsHelper\", [\r\n \"uiGmapLogger\", function($log) {\r\n var _getEventsObj, _hasEvents;\r\n _hasEvents = function(obj) {\r\n return angular.isDefined(obj.events) && (obj.events != null) && angular.isObject(obj.events);\r\n };\r\n _getEventsObj = function(scope, model) {\r\n if (_hasEvents(scope)) {\r\n return scope;\r\n }\r\n if (_hasEvents(model)) {\r\n return model;\r\n }\r\n };\r\n return {\r\n setEvents: function(gObject, scope, model, ignores) {\r\n var eventObj;\r\n eventObj = _getEventsObj(scope, model);\r\n if (eventObj != null) {\r\n return _.compact(_.map(eventObj.events, function(eventHandler, eventName) {\r\n var doIgnore;\r\n if (ignores) {\r\n doIgnore = _(ignores).contains(eventName);\r\n }\r\n if (eventObj.events.hasOwnProperty(eventName) && angular.isFunction(eventObj.events[eventName]) && !doIgnore) {\r\n return google.maps.event.addListener(gObject, eventName, function() {\r\n if (!scope.$evalAsync) {\r\n scope.$evalAsync = function() {};\r\n }\r\n return scope.$evalAsync(eventHandler.apply(scope, [gObject, eventName, model, arguments]));\r\n });\r\n }\r\n }));\r\n }\r\n },\r\n removeEvents: function(listeners) {\r\n var key, l;\r\n if (!listeners) {\r\n return;\r\n }\r\n for (key in listeners) {\r\n l = listeners[key];\r\n if (l) {\r\n google.maps.event.removeListener(l);\r\n }\r\n }\r\n }\r\n };\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapFitHelper', [\r\n 'uiGmapLogger', function($log) {\r\n return {\r\n fit: function(markersOrPoints, gMap) {\r\n var bounds, everSet, key, markerOrPoint, point;\r\n if (gMap && (markersOrPoints != null ? markersOrPoints.length : void 0)) {\r\n bounds = new google.maps.LatLngBounds();\r\n everSet = false;\r\n for (key in markersOrPoints) {\r\n markerOrPoint = markersOrPoints[key];\r\n if (markerOrPoint) {\r\n if (!everSet) {\r\n everSet = true;\r\n }\r\n point = _.isFunction(markerOrPoint.getPosition) ? markerOrPoint.getPosition() : markerOrPoint;\r\n }\r\n bounds.extend(point);\r\n }\r\n if (everSet) {\r\n return gMap.fitBounds(bounds);\r\n }\r\n }\r\n }\r\n };\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapGmapUtil', [\r\n 'uiGmapLogger', '$compile', function(Logger, $compile) {\r\n var _isFalse, _isTruthy, getCoords, getLatitude, getLongitude, validateCoords;\r\n _isTruthy = function(value, bool, optionsArray) {\r\n return value === bool || optionsArray.indexOf(value) !== -1;\r\n };\r\n _isFalse = function(value) {\r\n return _isTruthy(value, false, ['false', 'FALSE', 0, 'n', 'N', 'no', 'NO']);\r\n };\r\n getLatitude = function(value) {\r\n if (Array.isArray(value) && value.length === 2) {\r\n return value[1];\r\n } else if (angular.isDefined(value.type) && value.type === 'Point') {\r\n return value.coordinates[1];\r\n } else {\r\n return value.latitude;\r\n }\r\n };\r\n getLongitude = function(value) {\r\n if (Array.isArray(value) && value.length === 2) {\r\n return value[0];\r\n } else if (angular.isDefined(value.type) && value.type === 'Point') {\r\n return value.coordinates[0];\r\n } else {\r\n return value.longitude;\r\n }\r\n };\r\n getCoords = function(value) {\r\n if (!value) {\r\n return;\r\n }\r\n if (Array.isArray(value) && value.length === 2) {\r\n return new google.maps.LatLng(value[1], value[0]);\r\n } else if (angular.isDefined(value.type) && value.type === 'Point') {\r\n return new google.maps.LatLng(value.coordinates[1], value.coordinates[0]);\r\n } else {\r\n return new google.maps.LatLng(value.latitude, value.longitude);\r\n }\r\n };\r\n validateCoords = function(coords) {\r\n if (angular.isUndefined(coords)) {\r\n return false;\r\n }\r\n if (_.isArray(coords)) {\r\n if (coords.length === 2) {\r\n return true;\r\n }\r\n } else if ((coords != null) && (coords != null ? coords.type : void 0)) {\r\n if (coords.type === 'Point' && _.isArray(coords.coordinates) && coords.coordinates.length === 2) {\r\n return true;\r\n }\r\n }\r\n if (coords && angular.isDefined((coords != null ? coords.latitude : void 0) && angular.isDefined(coords != null ? coords.longitude : void 0))) {\r\n return true;\r\n }\r\n return false;\r\n };\r\n return {\r\n setCoordsFromEvent: function(prevValue, newLatLon) {\r\n if (!prevValue) {\r\n return;\r\n }\r\n if (Array.isArray(prevValue) && prevValue.length === 2) {\r\n prevValue[1] = newLatLon.lat();\r\n prevValue[0] = newLatLon.lng();\r\n } else if (angular.isDefined(prevValue.type) && prevValue.type === 'Point') {\r\n prevValue.coordinates[1] = newLatLon.lat();\r\n prevValue.coordinates[0] = newLatLon.lng();\r\n } else {\r\n prevValue.latitude = newLatLon.lat();\r\n prevValue.longitude = newLatLon.lng();\r\n }\r\n return prevValue;\r\n },\r\n getLabelPositionPoint: function(anchor) {\r\n var xPos, yPos;\r\n if (anchor === void 0) {\r\n return void 0;\r\n }\r\n anchor = /^([-\\d\\.]+)\\s([-\\d\\.]+)$/.exec(anchor);\r\n xPos = parseFloat(anchor[1]);\r\n yPos = parseFloat(anchor[2]);\r\n if ((xPos != null) && (yPos != null)) {\r\n return new google.maps.Point(xPos, yPos);\r\n }\r\n },\r\n createWindowOptions: function(gMarker, scope, content, defaults) {\r\n var options;\r\n if ((content != null) && (defaults != null) && ($compile != null)) {\r\n options = angular.extend({}, defaults, {\r\n content: this.buildContent(scope, defaults, content),\r\n position: defaults.position != null ? defaults.position : angular.isObject(gMarker) ? gMarker.getPosition() : getCoords(scope.coords)\r\n });\r\n if ((gMarker != null) && ((options != null ? options.pixelOffset : void 0) == null)) {\r\n if (options.boxClass == null) {\r\n\r\n } else {\r\n options.pixelOffset = {\r\n height: 0,\r\n width: -2\r\n };\r\n }\r\n }\r\n return options;\r\n } else {\r\n if (!defaults) {\r\n Logger.error('infoWindow defaults not defined');\r\n if (!content) {\r\n return Logger.error('infoWindow content not defined');\r\n }\r\n } else {\r\n return defaults;\r\n }\r\n }\r\n },\r\n buildContent: function(scope, defaults, content) {\r\n var parsed, ret;\r\n if (defaults.content != null) {\r\n ret = defaults.content;\r\n } else {\r\n if ($compile != null) {\r\n content = content.replace(/^\\s+|\\s+$/g, '');\r\n parsed = content === '' ? '' : $compile(content)(scope);\r\n if (parsed.length > 0) {\r\n ret = parsed[0];\r\n }\r\n } else {\r\n ret = content;\r\n }\r\n }\r\n return ret;\r\n },\r\n defaultDelay: 50,\r\n isTrue: function(value) {\r\n return _isTruthy(value, true, ['true', 'TRUE', 1, 'y', 'Y', 'yes', 'YES']);\r\n },\r\n isFalse: _isFalse,\r\n isFalsy: function(value) {\r\n return _isTruthy(value, false, [void 0, null]) || _isFalse(value);\r\n },\r\n getCoords: getCoords,\r\n validateCoords: validateCoords,\r\n equalCoords: function(coord1, coord2) {\r\n return getLatitude(coord1) === getLatitude(coord2) && getLongitude(coord1) === getLongitude(coord2);\r\n },\r\n validatePath: function(path) {\r\n var array, i, polygon, trackMaxVertices;\r\n i = 0;\r\n if (angular.isUndefined(path.type)) {\r\n if (!Array.isArray(path) || path.length < 2) {\r\n return false;\r\n }\r\n while (i < path.length) {\r\n if (!((angular.isDefined(path[i].latitude) && angular.isDefined(path[i].longitude)) || (typeof path[i].lat === 'function' && typeof path[i].lng === 'function'))) {\r\n return false;\r\n }\r\n i++;\r\n }\r\n return true;\r\n } else {\r\n if (angular.isUndefined(path.coordinates)) {\r\n return false;\r\n }\r\n if (path.type === 'Polygon') {\r\n if (path.coordinates[0].length < 4) {\r\n return false;\r\n }\r\n array = path.coordinates[0];\r\n } else if (path.type === 'MultiPolygon') {\r\n trackMaxVertices = {\r\n max: 0,\r\n index: 0\r\n };\r\n _.forEach(path.coordinates, function(polygon, index) {\r\n if (polygon[0].length > this.max) {\r\n this.max = polygon[0].length;\r\n return this.index = index;\r\n }\r\n }, trackMaxVertices);\r\n polygon = path.coordinates[trackMaxVertices.index];\r\n array = polygon[0];\r\n if (array.length < 4) {\r\n return false;\r\n }\r\n } else if (path.type === 'LineString') {\r\n if (path.coordinates.length < 2) {\r\n return false;\r\n }\r\n array = path.coordinates;\r\n } else {\r\n return false;\r\n }\r\n while (i < array.length) {\r\n if (array[i].length !== 2) {\r\n return false;\r\n }\r\n i++;\r\n }\r\n return true;\r\n }\r\n },\r\n convertPathPoints: function(path) {\r\n var array, i, latlng, result, trackMaxVertices;\r\n i = 0;\r\n result = new google.maps.MVCArray();\r\n if (angular.isUndefined(path.type)) {\r\n while (i < path.length) {\r\n latlng;\r\n if (angular.isDefined(path[i].latitude) && angular.isDefined(path[i].longitude)) {\r\n latlng = new google.maps.LatLng(path[i].latitude, path[i].longitude);\r\n } else if (typeof path[i].lat === 'function' && typeof path[i].lng === 'function') {\r\n latlng = path[i];\r\n }\r\n result.push(latlng);\r\n i++;\r\n }\r\n } else {\r\n array;\r\n if (path.type === 'Polygon') {\r\n array = path.coordinates[0];\r\n } else if (path.type === 'MultiPolygon') {\r\n trackMaxVertices = {\r\n max: 0,\r\n index: 0\r\n };\r\n _.forEach(path.coordinates, function(polygon, index) {\r\n if (polygon[0].length > this.max) {\r\n this.max = polygon[0].length;\r\n return this.index = index;\r\n }\r\n }, trackMaxVertices);\r\n array = path.coordinates[trackMaxVertices.index][0];\r\n } else if (path.type === 'LineString') {\r\n array = path.coordinates;\r\n }\r\n while (i < array.length) {\r\n result.push(new google.maps.LatLng(array[i][1], array[i][0]));\r\n i++;\r\n }\r\n }\r\n return result;\r\n },\r\n getPath: function(object, key) {\r\n var obj;\r\n if ((key == null) || !_.isString(key)) {\r\n return key;\r\n }\r\n obj = object;\r\n _.each(key.split('.'), function(value) {\r\n if (obj) {\r\n return obj = obj[value];\r\n }\r\n });\r\n return obj;\r\n },\r\n validateBoundPoints: function(bounds) {\r\n if (angular.isUndefined(bounds.sw.latitude) || angular.isUndefined(bounds.sw.longitude) || angular.isUndefined(bounds.ne.latitude) || angular.isUndefined(bounds.ne.longitude)) {\r\n return false;\r\n }\r\n return true;\r\n },\r\n convertBoundPoints: function(bounds) {\r\n var result;\r\n result = new google.maps.LatLngBounds(new google.maps.LatLng(bounds.sw.latitude, bounds.sw.longitude), new google.maps.LatLng(bounds.ne.latitude, bounds.ne.longitude));\r\n return result;\r\n },\r\n fitMapBounds: function(map, bounds) {\r\n return map.fitBounds(bounds);\r\n }\r\n };\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapIsReady', [\r\n '$q', '$timeout', function($q, $timeout) {\r\n var _checkIfReady, _ctr, _promises, _proms;\r\n _ctr = 0;\r\n _proms = [];\r\n _promises = function() {\r\n return $q.all(_proms);\r\n };\r\n _checkIfReady = function(deferred, expectedInstances, retriesLeft) {\r\n return $timeout(function() {\r\n if (retriesLeft <= 0) {\r\n deferred.reject('Your maps are not found we have checked the maximum amount of times. :)');\r\n return;\r\n }\r\n if (_ctr !== expectedInstances) {\r\n _checkIfReady(deferred, expectedInstances, retriesLeft - 1);\r\n } else {\r\n deferred.resolve(_promises());\r\n }\r\n }, 100);\r\n };\r\n return {\r\n spawn: function() {\r\n var d;\r\n d = $q.defer();\r\n _proms.push(d.promise);\r\n _ctr += 1;\r\n return {\r\n instance: _ctr,\r\n deferred: d\r\n };\r\n },\r\n promises: _promises,\r\n instances: function() {\r\n return _ctr;\r\n },\r\n promise: function(expectedInstances, numRetries) {\r\n var d;\r\n if (expectedInstances == null) {\r\n expectedInstances = 1;\r\n }\r\n if (numRetries == null) {\r\n numRetries = 50;\r\n }\r\n d = $q.defer();\r\n _checkIfReady(d, expectedInstances, numRetries);\r\n return d.promise;\r\n },\r\n reset: function() {\r\n _ctr = 0;\r\n _proms.length = 0;\r\n },\r\n decrement: function() {\r\n if (_ctr > 0) {\r\n _ctr -= 1;\r\n }\r\n if (_proms.length) {\r\n _proms.length -= 1;\r\n }\r\n }\r\n };\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module(\"uiGmapgoogle-maps.directives.api.utils\").factory(\"uiGmapLinked\", [\r\n \"uiGmapBaseObject\", function(BaseObject) {\r\n var Linked;\r\n Linked = (function(superClass) {\r\n extend(Linked, superClass);\r\n\r\n function Linked(scope, element, attrs, ctrls) {\r\n this.scope = scope;\r\n this.element = element;\r\n this.attrs = attrs;\r\n this.ctrls = ctrls;\r\n }\r\n\r\n return Linked;\r\n\r\n })(BaseObject);\r\n return Linked;\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapLogger', [\r\n '$log', function($log) {\r\n var LEVELS, Logger, log, maybeExecLevel;\r\n LEVELS = {\r\n log: 1,\r\n info: 2,\r\n debug: 3,\r\n warn: 4,\r\n error: 5,\r\n none: 6\r\n };\r\n maybeExecLevel = function(level, current, fn) {\r\n if (level >= current) {\r\n return fn();\r\n }\r\n };\r\n log = function(logLevelFnName, msg) {\r\n if ($log != null) {\r\n return $log[logLevelFnName](msg);\r\n } else {\r\n return console[logLevelFnName](msg);\r\n }\r\n };\r\n Logger = (function() {\r\n function Logger() {\r\n var logFns;\r\n this.doLog = true;\r\n logFns = {};\r\n ['log', 'info', 'debug', 'warn', 'error'].forEach((function(_this) {\r\n return function(level) {\r\n return logFns[level] = function(msg) {\r\n if (_this.doLog) {\r\n return maybeExecLevel(LEVELS[level], _this.currentLevel, function() {\r\n return log(level, msg);\r\n });\r\n }\r\n };\r\n };\r\n })(this));\r\n this.LEVELS = LEVELS;\r\n this.currentLevel = LEVELS.error;\r\n this.log = logFns['log'];\r\n this.info = logFns['info'];\r\n this.debug = logFns['debug'];\r\n this.warn = logFns['warn'];\r\n this.error = logFns['error'];\r\n }\r\n\r\n Logger.prototype.spawn = function() {\r\n return new Logger();\r\n };\r\n\r\n Logger.prototype.setLog = function(someLogger) {\r\n return $log = someLogger;\r\n };\r\n\r\n return Logger;\r\n\r\n })();\r\n return new Logger();\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },\r\n extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapModelKey', [\r\n 'uiGmapBaseObject', 'uiGmapGmapUtil', 'uiGmapPromise', '$q', '$timeout', function(BaseObject, GmapUtil, uiGmapPromise, $q, $timeout) {\r\n var ModelKey;\r\n return ModelKey = (function(superClass) {\r\n extend(ModelKey, superClass);\r\n\r\n function ModelKey(scope1) {\r\n this.scope = scope1;\r\n this.modelsLength = bind(this.modelsLength, this);\r\n this.updateChild = bind(this.updateChild, this);\r\n this.destroy = bind(this.destroy, this);\r\n this.onDestroy = bind(this.onDestroy, this);\r\n this.setChildScope = bind(this.setChildScope, this);\r\n this.getChanges = bind(this.getChanges, this);\r\n this.getProp = bind(this.getProp, this);\r\n this.setIdKey = bind(this.setIdKey, this);\r\n this.modelKeyComparison = bind(this.modelKeyComparison, this);\r\n ModelKey.__super__.constructor.call(this);\r\n this[\"interface\"] = {};\r\n this[\"interface\"].scopeKeys = [];\r\n this.defaultIdKey = 'id';\r\n this.idKey = void 0;\r\n }\r\n\r\n ModelKey.prototype.evalModelHandle = function(model, modelKey) {\r\n if ((model == null) || (modelKey == null)) {\r\n return;\r\n }\r\n if (modelKey === 'self') {\r\n return model;\r\n } else {\r\n if (_.isFunction(modelKey)) {\r\n modelKey = modelKey();\r\n }\r\n return GmapUtil.getPath(model, modelKey);\r\n }\r\n };\r\n\r\n ModelKey.prototype.modelKeyComparison = function(model1, model2) {\r\n var hasCoords, isEqual, scope;\r\n hasCoords = _.contains(this[\"interface\"].scopeKeys, 'coords');\r\n if (hasCoords && (this.scope.coords != null) || !hasCoords) {\r\n scope = this.scope;\r\n }\r\n if (scope == null) {\r\n throw 'No scope set!';\r\n }\r\n if (hasCoords) {\r\n isEqual = GmapUtil.equalCoords(this.scopeOrModelVal('coords', scope, model1), this.scopeOrModelVal('coords', scope, model2));\r\n if (!isEqual) {\r\n return isEqual;\r\n }\r\n }\r\n isEqual = _.every(_.without(this[\"interface\"].scopeKeys, 'coords'), (function(_this) {\r\n return function(k) {\r\n return _this.scopeOrModelVal(scope[k], scope, model1) === _this.scopeOrModelVal(scope[k], scope, model2);\r\n };\r\n })(this));\r\n return isEqual;\r\n };\r\n\r\n ModelKey.prototype.setIdKey = function(scope) {\r\n return this.idKey = scope.idKey != null ? scope.idKey : this.defaultIdKey;\r\n };\r\n\r\n ModelKey.prototype.setVal = function(model, key, newValue) {\r\n var thingToSet;\r\n thingToSet = this.modelOrKey(model, key);\r\n thingToSet = newValue;\r\n return model;\r\n };\r\n\r\n ModelKey.prototype.modelOrKey = function(model, key) {\r\n if (key == null) {\r\n return;\r\n }\r\n if (key !== 'self') {\r\n return GmapUtil.getPath(model, key);\r\n }\r\n return model;\r\n };\r\n\r\n ModelKey.prototype.getProp = function(propName, scope, model) {\r\n return this.scopeOrModelVal(propName, scope, model);\r\n };\r\n\r\n\r\n /*\r\n For the cases were watching a large object we only want to know the list of props\r\n that actually changed.\r\n Also we want to limit the amount of props we analyze to whitelisted props that are\r\n actually tracked by scope. (should make things faster with whitelisted)\r\n */\r\n\r\n ModelKey.prototype.getChanges = function(now, prev, whitelistedProps) {\r\n var c, changes, prop;\r\n if (whitelistedProps) {\r\n prev = _.pick(prev, whitelistedProps);\r\n now = _.pick(now, whitelistedProps);\r\n }\r\n changes = {};\r\n prop = {};\r\n c = {};\r\n for (prop in now) {\r\n if (!prev || prev[prop] !== now[prop]) {\r\n if (_.isArray(now[prop])) {\r\n changes[prop] = now[prop];\r\n } else if (_.isObject(now[prop])) {\r\n c = this.getChanges(now[prop], (prev ? prev[prop] : null));\r\n if (!_.isEmpty(c)) {\r\n changes[prop] = c;\r\n }\r\n } else {\r\n changes[prop] = now[prop];\r\n }\r\n }\r\n }\r\n return changes;\r\n };\r\n\r\n ModelKey.prototype.scopeOrModelVal = function(key, scope, model, doWrap) {\r\n var maybeWrap, modelKey, modelProp, scopeProp;\r\n if (doWrap == null) {\r\n doWrap = false;\r\n }\r\n maybeWrap = function(isScope, ret, doWrap) {\r\n if (doWrap == null) {\r\n doWrap = false;\r\n }\r\n if (doWrap) {\r\n return {\r\n isScope: isScope,\r\n value: ret\r\n };\r\n }\r\n return ret;\r\n };\r\n scopeProp = _.get(scope, key);\r\n if (_.isFunction(scopeProp)) {\r\n return maybeWrap(true, scopeProp(model), doWrap);\r\n }\r\n if (_.isObject(scopeProp)) {\r\n return maybeWrap(true, scopeProp, doWrap);\r\n }\r\n if (!_.isString(scopeProp)) {\r\n return maybeWrap(true, scopeProp, doWrap);\r\n }\r\n modelKey = scopeProp;\r\n if (!modelKey) {\r\n modelProp = _.get(model, key);\r\n } else {\r\n modelProp = modelKey === 'self' ? model : _.get(model, modelKey);\r\n }\r\n if (_.isFunction(modelProp)) {\r\n return maybeWrap(false, modelProp(), doWrap);\r\n }\r\n return maybeWrap(false, modelProp, doWrap);\r\n };\r\n\r\n ModelKey.prototype.setChildScope = function(keys, childScope, model) {\r\n var isScopeObj, key, name, newValue;\r\n for (key in keys) {\r\n name = keys[key];\r\n isScopeObj = this.scopeOrModelVal(name, childScope, model, true);\r\n if ((isScopeObj != null ? isScopeObj.value : void 0) != null) {\r\n newValue = isScopeObj.value;\r\n if (newValue !== childScope[name]) {\r\n childScope[name] = newValue;\r\n }\r\n }\r\n }\r\n return childScope.model = model;\r\n };\r\n\r\n ModelKey.prototype.onDestroy = function(scope) {};\r\n\r\n ModelKey.prototype.destroy = function(manualOverride) {\r\n var ref;\r\n if (manualOverride == null) {\r\n manualOverride = false;\r\n }\r\n if ((this.scope != null) && !((ref = this.scope) != null ? ref.$$destroyed : void 0) && (this.needToManualDestroy || manualOverride)) {\r\n return this.scope.$destroy();\r\n } else {\r\n return this.clean();\r\n }\r\n };\r\n\r\n ModelKey.prototype.updateChild = function(child, model) {\r\n if (model[this.idKey] == null) {\r\n this.$log.error(\"Model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key.\");\r\n return;\r\n }\r\n return child.updateModel(model);\r\n };\r\n\r\n ModelKey.prototype.modelsLength = function(arrayOrObjModels) {\r\n var len, toCheck;\r\n if (arrayOrObjModels == null) {\r\n arrayOrObjModels = void 0;\r\n }\r\n len = 0;\r\n toCheck = arrayOrObjModels ? arrayOrObjModels : this.scope.models;\r\n if (toCheck == null) {\r\n return len;\r\n }\r\n if (angular.isArray(toCheck) || (toCheck.length != null)) {\r\n len = toCheck.length;\r\n } else {\r\n len = Object.keys(toCheck).length;\r\n }\r\n return len;\r\n };\r\n\r\n return ModelKey;\r\n\r\n })(BaseObject);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapModelsWatcher', [\r\n 'uiGmapLogger', 'uiGmap_async', '$q', 'uiGmapPromise', function(Logger, _async, $q, uiGmapPromise) {\r\n return {\r\n didQueueInitPromise: function(existingPiecesObj, scope) {\r\n if (scope.models.length === 0) {\r\n _async.promiseLock(existingPiecesObj, uiGmapPromise.promiseTypes.init, null, null, ((function(_this) {\r\n return function() {\r\n return uiGmapPromise.resolve();\r\n };\r\n })(this)));\r\n return true;\r\n }\r\n return false;\r\n },\r\n figureOutState: function(idKey, scope, childObjects, comparison, callBack) {\r\n var adds, children, mappedScopeModelIds, removals, updates;\r\n adds = [];\r\n mappedScopeModelIds = {};\r\n removals = [];\r\n updates = [];\r\n scope.models.forEach(function(m) {\r\n var child;\r\n if (m[idKey] != null) {\r\n mappedScopeModelIds[m[idKey]] = {};\r\n if (childObjects.get(m[idKey]) == null) {\r\n return adds.push(m);\r\n } else {\r\n child = childObjects.get(m[idKey]);\r\n if (!comparison(m, child.clonedModel, scope)) {\r\n return updates.push({\r\n model: m,\r\n child: child\r\n });\r\n }\r\n }\r\n } else {\r\n return Logger.error(' id missing for model #{m.toString()},\\ncan not use do comparison/insertion');\r\n }\r\n });\r\n children = childObjects.values();\r\n children.forEach(function(c) {\r\n var id;\r\n if (c == null) {\r\n Logger.error('child undefined in ModelsWatcher.');\r\n return;\r\n }\r\n if (c.model == null) {\r\n Logger.error('child.model undefined in ModelsWatcher.');\r\n return;\r\n }\r\n id = c.model[idKey];\r\n if (mappedScopeModelIds[id] == null) {\r\n return removals.push(c);\r\n }\r\n });\r\n return {\r\n adds: adds,\r\n removals: removals,\r\n updates: updates\r\n };\r\n }\r\n };\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapPromise', [\r\n '$q', '$timeout', 'uiGmapLogger', function($q, $timeout, $log) {\r\n var ExposedPromise, SniffedPromise, defer, isInProgress, isResolved, promise, promiseStatus, promiseStatuses, promiseTypes, resolve, strPromiseStatuses;\r\n promiseTypes = {\r\n create: 'create',\r\n update: 'update',\r\n \"delete\": 'delete',\r\n init: 'init'\r\n };\r\n promiseStatuses = {\r\n IN_PROGRESS: 0,\r\n RESOLVED: 1,\r\n REJECTED: 2\r\n };\r\n strPromiseStatuses = (function() {\r\n var obj;\r\n obj = {};\r\n obj[\"\" + promiseStatuses.IN_PROGRESS] = 'in-progress';\r\n obj[\"\" + promiseStatuses.RESOLVED] = 'resolved';\r\n obj[\"\" + promiseStatuses.REJECTED] = 'rejected';\r\n return obj;\r\n })();\r\n isInProgress = function(promise) {\r\n if (promise.$$state) {\r\n return promise.$$state.status === promiseStatuses.IN_PROGRESS;\r\n }\r\n if (!promise.hasOwnProperty(\"$$v\")) {\r\n return true;\r\n }\r\n };\r\n isResolved = function(promise) {\r\n if (promise.$$state) {\r\n return promise.$$state.status === promiseStatuses.RESOLVED;\r\n }\r\n if (promise.hasOwnProperty(\"$$v\")) {\r\n return true;\r\n }\r\n };\r\n promiseStatus = function(status) {\r\n return strPromiseStatuses[status] || 'done w error';\r\n };\r\n ExposedPromise = function(promise) {\r\n var cancelDeferred, combined, wrapped;\r\n cancelDeferred = $q.defer();\r\n combined = $q.all([promise, cancelDeferred.promise]);\r\n wrapped = $q.defer();\r\n promise.then(cancelDeferred.resolve, (function() {}), function(notify) {\r\n cancelDeferred.notify(notify);\r\n return wrapped.notify(notify);\r\n });\r\n combined.then(function(successes) {\r\n return wrapped.resolve(successes[0] || successes[1]);\r\n }, function(error) {\r\n return wrapped.reject(error);\r\n });\r\n wrapped.promise.cancel = function(reason) {\r\n if (reason == null) {\r\n reason = 'canceled';\r\n }\r\n return cancelDeferred.reject(reason);\r\n };\r\n wrapped.promise.notify = function(msg) {\r\n if (msg == null) {\r\n msg = 'cancel safe';\r\n }\r\n wrapped.notify(msg);\r\n if (promise.hasOwnProperty('notify')) {\r\n return promise.notify(msg);\r\n }\r\n };\r\n if (promise.promiseType != null) {\r\n wrapped.promise.promiseType = promise.promiseType;\r\n }\r\n return wrapped.promise;\r\n };\r\n SniffedPromise = function(fnPromise, promiseType) {\r\n return {\r\n promise: fnPromise,\r\n promiseType: promiseType\r\n };\r\n };\r\n defer = function() {\r\n return $q.defer();\r\n };\r\n resolve = function() {\r\n var d;\r\n d = $q.defer();\r\n d.resolve.apply(void 0, arguments);\r\n return d.promise;\r\n };\r\n promise = function(fnToWrap) {\r\n var d;\r\n if (!_.isFunction(fnToWrap)) {\r\n $log.error(\"uiGmapPromise.promise() only accepts functions\");\r\n return;\r\n }\r\n d = $q.defer();\r\n $timeout(function() {\r\n var result;\r\n result = fnToWrap();\r\n return d.resolve(result);\r\n });\r\n return d.promise;\r\n };\r\n return {\r\n defer: defer,\r\n promise: promise,\r\n resolve: resolve,\r\n promiseTypes: promiseTypes,\r\n isInProgress: isInProgress,\r\n isResolved: isResolved,\r\n promiseStatus: promiseStatus,\r\n ExposedPromise: ExposedPromise,\r\n SniffedPromise: SniffedPromise\r\n };\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };\r\n\r\n angular.module(\"uiGmapgoogle-maps.directives.api.utils\").factory(\"uiGmapPropMap\", function() {\r\n\r\n /*\r\n Simple Object Map with a length property to make it easy to track length/size\r\n */\r\n var PropMap;\r\n return PropMap = (function() {\r\n function PropMap() {\r\n this.removeAll = bind(this.removeAll, this);\r\n this.slice = bind(this.slice, this);\r\n this.push = bind(this.push, this);\r\n this.keys = bind(this.keys, this);\r\n this.values = bind(this.values, this);\r\n this.remove = bind(this.remove, this);\r\n this.put = bind(this.put, this);\r\n this.stateChanged = bind(this.stateChanged, this);\r\n this.get = bind(this.get, this);\r\n this.length = 0;\r\n this.dict = {};\r\n this.didValsStateChange = false;\r\n this.didKeysStateChange = false;\r\n this.allVals = [];\r\n this.allKeys = [];\r\n }\r\n\r\n PropMap.prototype.get = function(key) {\r\n return this.dict[key];\r\n };\r\n\r\n PropMap.prototype.stateChanged = function() {\r\n this.didValsStateChange = true;\r\n return this.didKeysStateChange = true;\r\n };\r\n\r\n PropMap.prototype.put = function(key, value) {\r\n if (this.get(key) == null) {\r\n this.length++;\r\n }\r\n this.stateChanged();\r\n return this.dict[key] = value;\r\n };\r\n\r\n PropMap.prototype.remove = function(key, isSafe) {\r\n var value;\r\n if (isSafe == null) {\r\n isSafe = false;\r\n }\r\n if (isSafe && !this.get(key)) {\r\n return void 0;\r\n }\r\n value = this.dict[key];\r\n delete this.dict[key];\r\n this.length--;\r\n this.stateChanged();\r\n return value;\r\n };\r\n\r\n PropMap.prototype.valuesOrKeys = function(str) {\r\n var keys, vals;\r\n if (str == null) {\r\n str = 'Keys';\r\n }\r\n if (!this[\"did\" + str + \"StateChange\"]) {\r\n return this['all' + str];\r\n }\r\n vals = [];\r\n keys = [];\r\n _.each(this.dict, function(v, k) {\r\n vals.push(v);\r\n return keys.push(k);\r\n });\r\n this.didKeysStateChange = false;\r\n this.didValsStateChange = false;\r\n this.allVals = vals;\r\n this.allKeys = keys;\r\n return this['all' + str];\r\n };\r\n\r\n PropMap.prototype.values = function() {\r\n return this.valuesOrKeys('Vals');\r\n };\r\n\r\n PropMap.prototype.keys = function() {\r\n return this.valuesOrKeys();\r\n };\r\n\r\n PropMap.prototype.push = function(obj, key) {\r\n if (key == null) {\r\n key = \"key\";\r\n }\r\n return this.put(obj[key], obj);\r\n };\r\n\r\n PropMap.prototype.slice = function() {\r\n return this.keys().map((function(_this) {\r\n return function(k) {\r\n return _this.remove(k);\r\n };\r\n })(this));\r\n };\r\n\r\n PropMap.prototype.removeAll = function() {\r\n return this.slice();\r\n };\r\n\r\n PropMap.prototype.each = function(cb) {\r\n return _.each(this.dict, function(v, k) {\r\n return cb(v);\r\n });\r\n };\r\n\r\n PropMap.prototype.map = function(cb) {\r\n return _.map(this.dict, function(v, k) {\r\n return cb(v);\r\n });\r\n };\r\n\r\n return PropMap;\r\n\r\n })();\r\n });\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module(\"uiGmapgoogle-maps.directives.api.utils\").factory(\"uiGmapPropertyAction\", [\r\n \"uiGmapLogger\", function(Logger) {\r\n var PropertyAction;\r\n PropertyAction = function(setterFn) {\r\n this.setIfChange = function(newVal, oldVal) {\r\n var callingKey;\r\n callingKey = this.exp;\r\n if (!_.isEqual(oldVal, newVal)) {\r\n return setterFn(callingKey, newVal);\r\n }\r\n };\r\n this.sic = this.setIfChange;\r\n return this;\r\n };\r\n return PropertyAction;\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api.managers').factory('uiGmapClustererMarkerManager', [\r\n 'uiGmapLogger', 'uiGmapFitHelper', 'uiGmapPropMap', 'uiGmapEventsHelper', function($log, FitHelper, PropMap, EventsHelper) {\r\n var ClustererMarkerManager;\r\n ClustererMarkerManager = (function() {\r\n ClustererMarkerManager.type = 'ClustererMarkerManager';\r\n\r\n function ClustererMarkerManager(gMap, opt_markers, opt_options, opt_events) {\r\n if (opt_markers == null) {\r\n opt_markers = {};\r\n }\r\n this.opt_options = opt_options != null ? opt_options : {};\r\n this.opt_events = opt_events;\r\n this.checkSync = bind(this.checkSync, this);\r\n this.getGMarkers = bind(this.getGMarkers, this);\r\n this.fit = bind(this.fit, this);\r\n this.destroy = bind(this.destroy, this);\r\n this.attachEvents = bind(this.attachEvents, this);\r\n this.clear = bind(this.clear, this);\r\n this.draw = bind(this.draw, this);\r\n this.removeMany = bind(this.removeMany, this);\r\n this.remove = bind(this.remove, this);\r\n this.addMany = bind(this.addMany, this);\r\n this.update = bind(this.update, this);\r\n this.add = bind(this.add, this);\r\n this.type = ClustererMarkerManager.type;\r\n this.clusterer = new NgMapMarkerClusterer(gMap, opt_markers, this.opt_options);\r\n this.propMapGMarkers = new PropMap();\r\n this.attachEvents(this.opt_events, 'opt_events');\r\n this.clusterer.setIgnoreHidden(true);\r\n this.noDrawOnSingleAddRemoves = true;\r\n $log.info(this);\r\n }\r\n\r\n ClustererMarkerManager.prototype.checkKey = function(gMarker) {\r\n var msg;\r\n if (gMarker.key == null) {\r\n msg = 'gMarker.key undefined and it is REQUIRED!!';\r\n return $log.error(msg);\r\n }\r\n };\r\n\r\n ClustererMarkerManager.prototype.add = function(gMarker) {\r\n this.checkKey(gMarker);\r\n this.clusterer.addMarker(gMarker, this.noDrawOnSingleAddRemoves);\r\n this.propMapGMarkers.put(gMarker.key, gMarker);\r\n return this.checkSync();\r\n };\r\n\r\n ClustererMarkerManager.prototype.update = function(gMarker) {\r\n this.remove(gMarker);\r\n return this.add(gMarker);\r\n };\r\n\r\n ClustererMarkerManager.prototype.addMany = function(gMarkers) {\r\n return gMarkers.forEach((function(_this) {\r\n return function(gMarker) {\r\n return _this.add(gMarker);\r\n };\r\n })(this));\r\n };\r\n\r\n ClustererMarkerManager.prototype.remove = function(gMarker) {\r\n var exists;\r\n this.checkKey(gMarker);\r\n exists = this.propMapGMarkers.get(gMarker.key);\r\n if (exists) {\r\n this.clusterer.removeMarker(gMarker, this.noDrawOnSingleAddRemoves);\r\n this.propMapGMarkers.remove(gMarker.key);\r\n }\r\n return this.checkSync();\r\n };\r\n\r\n ClustererMarkerManager.prototype.removeMany = function(gMarkers) {\r\n return gMarkers.forEach((function(_this) {\r\n return function(gMarker) {\r\n return _this.remove(gMarker);\r\n };\r\n })(this));\r\n };\r\n\r\n ClustererMarkerManager.prototype.draw = function() {\r\n return this.clusterer.repaint();\r\n };\r\n\r\n ClustererMarkerManager.prototype.clear = function() {\r\n this.removeMany(this.getGMarkers());\r\n return this.clusterer.repaint();\r\n };\r\n\r\n ClustererMarkerManager.prototype.attachEvents = function(options, optionsName) {\r\n var eventHandler, eventName, results;\r\n this.listeners = [];\r\n if (angular.isDefined(options) && (options != null) && angular.isObject(options)) {\r\n results = [];\r\n for (eventName in options) {\r\n eventHandler = options[eventName];\r\n if (options.hasOwnProperty(eventName) && angular.isFunction(options[eventName])) {\r\n $log.info(optionsName + \": Attaching event: \" + eventName + \" to clusterer\");\r\n results.push(this.listeners.push(google.maps.event.addListener(this.clusterer, eventName, options[eventName])));\r\n } else {\r\n results.push(void 0);\r\n }\r\n }\r\n return results;\r\n }\r\n };\r\n\r\n ClustererMarkerManager.prototype.clearEvents = function() {\r\n EventsHelper.removeEvents(this.listeners);\r\n return this.listeners = [];\r\n };\r\n\r\n ClustererMarkerManager.prototype.destroy = function() {\r\n this.clearEvents();\r\n return this.clear();\r\n };\r\n\r\n ClustererMarkerManager.prototype.fit = function() {\r\n return FitHelper.fit(this.getGMarkers(), this.clusterer.getMap());\r\n };\r\n\r\n ClustererMarkerManager.prototype.getGMarkers = function() {\r\n return this.clusterer.getMarkers().values();\r\n };\r\n\r\n ClustererMarkerManager.prototype.checkSync = function() {};\r\n\r\n return ClustererMarkerManager;\r\n\r\n })();\r\n return ClustererMarkerManager;\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };\r\n\r\n angular.module(\"uiGmapgoogle-maps.directives.api.managers\").factory(\"uiGmapMarkerManager\", [\r\n \"uiGmapLogger\", \"uiGmapFitHelper\", \"uiGmapPropMap\", function(Logger, FitHelper, PropMap) {\r\n var MarkerManager;\r\n MarkerManager = (function() {\r\n MarkerManager.type = 'MarkerManager';\r\n\r\n function MarkerManager(gMap, opt_markers, opt_options) {\r\n this.getGMarkers = bind(this.getGMarkers, this);\r\n this.fit = bind(this.fit, this);\r\n this.handleOptDraw = bind(this.handleOptDraw, this);\r\n this.clear = bind(this.clear, this);\r\n this.destroy = bind(this.destroy, this);\r\n this.draw = bind(this.draw, this);\r\n this.removeMany = bind(this.removeMany, this);\r\n this.remove = bind(this.remove, this);\r\n this.addMany = bind(this.addMany, this);\r\n this.update = bind(this.update, this);\r\n this.add = bind(this.add, this);\r\n this.type = MarkerManager.type;\r\n this.gMap = gMap;\r\n this.gMarkers = new PropMap();\r\n this.$log = Logger;\r\n this.$log.info(this);\r\n }\r\n\r\n MarkerManager.prototype.add = function(gMarker, optDraw) {\r\n var exists, msg;\r\n if (optDraw == null) {\r\n optDraw = true;\r\n }\r\n if (gMarker.key == null) {\r\n msg = \"gMarker.key undefined and it is REQUIRED!!\";\r\n Logger.error(msg);\r\n throw msg;\r\n }\r\n exists = this.gMarkers.get(gMarker.key);\r\n if (!exists) {\r\n this.handleOptDraw(gMarker, optDraw, true);\r\n return this.gMarkers.put(gMarker.key, gMarker);\r\n }\r\n };\r\n\r\n MarkerManager.prototype.update = function(gMarker, optDraw) {\r\n if (optDraw == null) {\r\n optDraw = true;\r\n }\r\n this.remove(gMarker, optDraw);\r\n return this.add(gMarker, optDraw);\r\n };\r\n\r\n MarkerManager.prototype.addMany = function(gMarkers) {\r\n return gMarkers.forEach((function(_this) {\r\n return function(gMarker) {\r\n return _this.add(gMarker);\r\n };\r\n })(this));\r\n };\r\n\r\n MarkerManager.prototype.remove = function(gMarker, optDraw) {\r\n if (optDraw == null) {\r\n optDraw = true;\r\n }\r\n this.handleOptDraw(gMarker, optDraw, false);\r\n if (this.gMarkers.get(gMarker.key)) {\r\n return this.gMarkers.remove(gMarker.key);\r\n }\r\n };\r\n\r\n MarkerManager.prototype.removeMany = function(gMarkers) {\r\n return gMarkers.forEach((function(_this) {\r\n return function(marker) {\r\n return _this.remove(marker);\r\n };\r\n })(this));\r\n };\r\n\r\n MarkerManager.prototype.draw = function() {\r\n var deletes;\r\n deletes = [];\r\n this.gMarkers.each((function(_this) {\r\n return function(gMarker) {\r\n if (!gMarker.isDrawn) {\r\n if (gMarker.doAdd) {\r\n gMarker.setMap(_this.gMap);\r\n return gMarker.isDrawn = true;\r\n } else {\r\n return deletes.push(gMarker);\r\n }\r\n }\r\n };\r\n })(this));\r\n return deletes.forEach((function(_this) {\r\n return function(gMarker) {\r\n gMarker.isDrawn = false;\r\n return _this.remove(gMarker, true);\r\n };\r\n })(this));\r\n };\r\n\r\n MarkerManager.prototype.destroy = function() {\r\n return this.clear();\r\n };\r\n\r\n MarkerManager.prototype.clear = function() {\r\n this.gMarkers.each(function(gMarker) {\r\n return gMarker.setMap(null);\r\n });\r\n delete this.gMarkers;\r\n return this.gMarkers = new PropMap();\r\n };\r\n\r\n MarkerManager.prototype.handleOptDraw = function(gMarker, optDraw, doAdd) {\r\n if (optDraw === true) {\r\n if (doAdd) {\r\n gMarker.setMap(this.gMap);\r\n } else {\r\n gMarker.setMap(null);\r\n }\r\n return gMarker.isDrawn = true;\r\n } else {\r\n gMarker.isDrawn = false;\r\n return gMarker.doAdd = doAdd;\r\n }\r\n };\r\n\r\n MarkerManager.prototype.fit = function() {\r\n return FitHelper.fit(this.getGMarkers(), this.gMap);\r\n };\r\n\r\n MarkerManager.prototype.getGMarkers = function() {\r\n return this.gMarkers.values();\r\n };\r\n\r\n return MarkerManager;\r\n\r\n })();\r\n return MarkerManager;\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api.managers').factory('uiGmapSpiderfierMarkerManager', [\r\n 'uiGmapLogger', 'uiGmapFitHelper', 'uiGmapPropMap', 'uiGmapMarkerSpiderfier', function($log, FitHelper, PropMap, MarkerSpiderfier) {\r\n var SpiderfierMarkerManager;\r\n return SpiderfierMarkerManager = (function() {\r\n SpiderfierMarkerManager.type = 'SpiderfierMarkerManager';\r\n\r\n function SpiderfierMarkerManager(gMap, opt_markers, opt_options, opt_events, scope) {\r\n if (opt_markers == null) {\r\n opt_markers = {};\r\n }\r\n this.opt_options = opt_options != null ? opt_options : {};\r\n this.opt_events = opt_events;\r\n this.scope = scope;\r\n this.checkSync = bind(this.checkSync, this);\r\n this.isSpiderfied = bind(this.isSpiderfied, this);\r\n this.getGMarkers = bind(this.getGMarkers, this);\r\n this.fit = bind(this.fit, this);\r\n this.destroy = bind(this.destroy, this);\r\n this.attachEvents = bind(this.attachEvents, this);\r\n this.clear = bind(this.clear, this);\r\n this.draw = bind(this.draw, this);\r\n this.removeMany = bind(this.removeMany, this);\r\n this.remove = bind(this.remove, this);\r\n this.addMany = bind(this.addMany, this);\r\n this.update = bind(this.update, this);\r\n this.add = bind(this.add, this);\r\n this.type = SpiderfierMarkerManager.type;\r\n this.markerSpiderfier = new MarkerSpiderfier(gMap, this.opt_options);\r\n this.propMapGMarkers = new PropMap();\r\n this.attachEvents(this.opt_events, 'opt_events');\r\n this.noDrawOnSingleAddRemoves = true;\r\n $log.info(this);\r\n }\r\n\r\n SpiderfierMarkerManager.prototype.checkKey = function(gMarker) {\r\n var msg;\r\n if (gMarker.key == null) {\r\n msg = 'gMarker.key undefined and it is REQUIRED!!';\r\n return $log.error(msg);\r\n }\r\n };\r\n\r\n SpiderfierMarkerManager.prototype.add = function(gMarker) {\r\n gMarker.setMap(this.markerSpiderfier.map);\r\n this.checkKey(gMarker);\r\n this.markerSpiderfier.addMarker(gMarker, this.noDrawOnSingleAddRemoves);\r\n this.propMapGMarkers.put(gMarker.key, gMarker);\r\n return this.checkSync();\r\n };\r\n\r\n SpiderfierMarkerManager.prototype.update = function(gMarker) {\r\n this.remove(gMarker);\r\n return this.add(gMarker);\r\n };\r\n\r\n SpiderfierMarkerManager.prototype.addMany = function(gMarkers) {\r\n return gMarkers.forEach((function(_this) {\r\n return function(gMarker) {\r\n return _this.add(gMarker);\r\n };\r\n })(this));\r\n };\r\n\r\n SpiderfierMarkerManager.prototype.remove = function(gMarker) {\r\n var exists;\r\n this.checkKey(gMarker);\r\n exists = this.propMapGMarkers.get(gMarker.key);\r\n if (exists) {\r\n gMarker.setMap(null);\r\n this.markerSpiderfier.removeMarker(gMarker, this.noDrawOnSingleAddRemoves);\r\n this.propMapGMarkers.remove(gMarker.key);\r\n }\r\n return this.checkSync();\r\n };\r\n\r\n SpiderfierMarkerManager.prototype.removeMany = function(gMarkers) {\r\n return gMarkers.forEach((function(_this) {\r\n return function(gMarker) {\r\n return _this.remove(gMarker);\r\n };\r\n })(this));\r\n };\r\n\r\n SpiderfierMarkerManager.prototype.draw = function() {};\r\n\r\n SpiderfierMarkerManager.prototype.clear = function() {\r\n return this.removeMany(this.getGMarkers());\r\n };\r\n\r\n SpiderfierMarkerManager.prototype.attachEvents = function(options, optionsName) {\r\n if (angular.isDefined(options) && (options != null) && angular.isObject(options)) {\r\n return _.each(options, (function(_this) {\r\n return function(eventHandler, eventName) {\r\n if (options.hasOwnProperty(eventName) && angular.isFunction(options[eventName])) {\r\n $log.info(optionsName + \": Attaching event: \" + eventName + \" to markerSpiderfier\");\r\n return _this.markerSpiderfier.addListener(eventName, function() {\r\n if (eventName === 'spiderfy' || eventName === 'unspiderfy') {\r\n return _this.scope.$evalAsync(options[eventName].apply(options, arguments));\r\n } else {\r\n return _this.scope.$evalAsync(options[eventName].apply(options, [arguments[0], eventName, arguments[0].model, arguments]));\r\n }\r\n });\r\n }\r\n };\r\n })(this));\r\n }\r\n };\r\n\r\n SpiderfierMarkerManager.prototype.clearEvents = function(options, optionsName) {\r\n var eventHandler, eventName;\r\n if (angular.isDefined(options) && (options != null) && angular.isObject(options)) {\r\n for (eventName in options) {\r\n eventHandler = options[eventName];\r\n if (options.hasOwnProperty(eventName) && angular.isFunction(options[eventName])) {\r\n $log.info(optionsName + \": Clearing event: \" + eventName + \" to markerSpiderfier\");\r\n this.markerSpiderfier.clearListeners(eventName);\r\n }\r\n }\r\n }\r\n };\r\n\r\n SpiderfierMarkerManager.prototype.destroy = function() {\r\n this.clearEvents(this.opt_events, 'opt_events');\r\n return this.clear();\r\n };\r\n\r\n SpiderfierMarkerManager.prototype.fit = function() {\r\n return FitHelper.fit(this.getGMarkers(), this.markerSpiderfier.map);\r\n };\r\n\r\n SpiderfierMarkerManager.prototype.getGMarkers = function() {\r\n return this.markerSpiderfier.getMarkers();\r\n };\r\n\r\n SpiderfierMarkerManager.prototype.isSpiderfied = function() {\r\n return _.find(this.getGMarkers(), function(gMarker) {\r\n return (gMarker != null ? gMarker._omsData : void 0) != null;\r\n });\r\n };\r\n\r\n SpiderfierMarkerManager.prototype.checkSync = function() {};\r\n\r\n return SpiderfierMarkerManager;\r\n\r\n })();\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module('uiGmapgoogle-maps').factory('uiGmapadd-events', [\r\n '$timeout', function($timeout) {\r\n var addEvent, addEvents;\r\n addEvent = function(target, eventName, handler) {\r\n return google.maps.event.addListener(target, eventName, function() {\r\n handler.apply(this, arguments);\r\n return $timeout((function() {}), true);\r\n });\r\n };\r\n addEvents = function(target, eventName, handler) {\r\n var remove;\r\n if (handler) {\r\n return addEvent(target, eventName, handler);\r\n }\r\n remove = [];\r\n angular.forEach(eventName, function(_handler, key) {\r\n return remove.push(addEvent(target, key, _handler));\r\n });\r\n return function() {\r\n angular.forEach(remove, function(listener) {\r\n return google.maps.event.removeListener(listener);\r\n });\r\n return remove = null;\r\n };\r\n };\r\n return addEvents;\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module('uiGmapgoogle-maps').factory('uiGmaparray-sync', [\r\n 'uiGmapadd-events', function(mapEvents) {\r\n return function(mapArray, scope, pathEval, pathChangedFn) {\r\n var geojsonArray, geojsonHandlers, geojsonWatcher, isSetFromScope, legacyHandlers, legacyWatcher, mapArrayListener, scopePath, watchListener;\r\n isSetFromScope = false;\r\n scopePath = scope.$eval(pathEval);\r\n if (!scope[\"static\"]) {\r\n legacyHandlers = {\r\n set_at: function(index) {\r\n var value;\r\n if (isSetFromScope) {\r\n return;\r\n }\r\n value = mapArray.getAt(index);\r\n if (!value) {\r\n return;\r\n }\r\n if (!value.lng || !value.lat) {\r\n return scopePath[index] = value;\r\n } else {\r\n scopePath[index].latitude = value.lat();\r\n return scopePath[index].longitude = value.lng();\r\n }\r\n },\r\n insert_at: function(index) {\r\n var value;\r\n if (isSetFromScope) {\r\n return;\r\n }\r\n value = mapArray.getAt(index);\r\n if (!value) {\r\n return;\r\n }\r\n if (!value.lng || !value.lat) {\r\n return scopePath.splice(index, 0, value);\r\n } else {\r\n return scopePath.splice(index, 0, {\r\n latitude: value.lat(),\r\n longitude: value.lng()\r\n });\r\n }\r\n },\r\n remove_at: function(index) {\r\n if (isSetFromScope) {\r\n return;\r\n }\r\n return scopePath.splice(index, 1);\r\n }\r\n };\r\n geojsonArray;\r\n if (scopePath.type === 'Polygon') {\r\n geojsonArray = scopePath.coordinates[0];\r\n } else if (scopePath.type === 'LineString') {\r\n geojsonArray = scopePath.coordinates;\r\n }\r\n geojsonHandlers = {\r\n set_at: function(index) {\r\n var value;\r\n if (isSetFromScope) {\r\n return;\r\n }\r\n value = mapArray.getAt(index);\r\n if (!value) {\r\n return;\r\n }\r\n if (!value.lng || !value.lat) {\r\n return;\r\n }\r\n geojsonArray[index][1] = value.lat();\r\n return geojsonArray[index][0] = value.lng();\r\n },\r\n insert_at: function(index) {\r\n var value;\r\n if (isSetFromScope) {\r\n return;\r\n }\r\n value = mapArray.getAt(index);\r\n if (!value) {\r\n return;\r\n }\r\n if (!value.lng || !value.lat) {\r\n return;\r\n }\r\n return geojsonArray.splice(index, 0, [value.lng(), value.lat()]);\r\n },\r\n remove_at: function(index) {\r\n if (isSetFromScope) {\r\n return;\r\n }\r\n return geojsonArray.splice(index, 1);\r\n }\r\n };\r\n mapArrayListener = mapEvents(mapArray, angular.isUndefined(scopePath.type) ? legacyHandlers : geojsonHandlers);\r\n }\r\n legacyWatcher = function(newPath) {\r\n var changed, i, l, newLength, newValue, oldArray, oldLength, oldValue;\r\n isSetFromScope = true;\r\n oldArray = mapArray;\r\n changed = false;\r\n if (newPath) {\r\n i = 0;\r\n oldLength = oldArray.getLength();\r\n newLength = newPath.length;\r\n l = Math.min(oldLength, newLength);\r\n newValue = void 0;\r\n while (i < l) {\r\n oldValue = oldArray.getAt(i);\r\n newValue = newPath[i];\r\n if (typeof newValue.equals === 'function') {\r\n if (!newValue.equals(oldValue)) {\r\n oldArray.setAt(i, newValue);\r\n changed = true;\r\n }\r\n } else {\r\n if ((oldValue.lat() !== newValue.latitude) || (oldValue.lng() !== newValue.longitude)) {\r\n oldArray.setAt(i, new google.maps.LatLng(newValue.latitude, newValue.longitude));\r\n changed = true;\r\n }\r\n }\r\n i++;\r\n }\r\n while (i < newLength) {\r\n newValue = newPath[i];\r\n if (typeof newValue.lat === 'function' && typeof newValue.lng === 'function') {\r\n oldArray.push(newValue);\r\n } else {\r\n oldArray.push(new google.maps.LatLng(newValue.latitude, newValue.longitude));\r\n }\r\n changed = true;\r\n i++;\r\n }\r\n while (i < oldLength) {\r\n oldArray.pop();\r\n changed = true;\r\n i++;\r\n }\r\n }\r\n isSetFromScope = false;\r\n if (changed) {\r\n return pathChangedFn(oldArray);\r\n }\r\n };\r\n geojsonWatcher = function(newPath) {\r\n var array, changed, i, l, newLength, newValue, oldArray, oldLength, oldValue;\r\n isSetFromScope = true;\r\n oldArray = mapArray;\r\n changed = false;\r\n if (newPath) {\r\n array;\r\n if (scopePath.type === 'Polygon') {\r\n array = newPath.coordinates[0];\r\n } else if (scopePath.type === 'LineString') {\r\n array = newPath.coordinates;\r\n }\r\n i = 0;\r\n oldLength = oldArray.getLength();\r\n newLength = array.length;\r\n l = Math.min(oldLength, newLength);\r\n newValue = void 0;\r\n while (i < l) {\r\n oldValue = oldArray.getAt(i);\r\n newValue = array[i];\r\n if ((oldValue.lat() !== newValue[1]) || (oldValue.lng() !== newValue[0])) {\r\n oldArray.setAt(i, new google.maps.LatLng(newValue[1], newValue[0]));\r\n changed = true;\r\n }\r\n i++;\r\n }\r\n while (i < newLength) {\r\n newValue = array[i];\r\n oldArray.push(new google.maps.LatLng(newValue[1], newValue[0]));\r\n changed = true;\r\n i++;\r\n }\r\n while (i < oldLength) {\r\n oldArray.pop();\r\n changed = true;\r\n i++;\r\n }\r\n }\r\n isSetFromScope = false;\r\n if (changed) {\r\n return pathChangedFn(oldArray);\r\n }\r\n };\r\n watchListener;\r\n if (!scope[\"static\"]) {\r\n if (angular.isUndefined(scopePath.type)) {\r\n watchListener = scope.$watchCollection(pathEval, legacyWatcher);\r\n } else {\r\n watchListener = scope.$watch(pathEval, geojsonWatcher, true);\r\n }\r\n }\r\n return function() {\r\n if (mapArrayListener) {\r\n mapArrayListener();\r\n mapArrayListener = null;\r\n }\r\n if (watchListener) {\r\n watchListener();\r\n return watchListener = null;\r\n }\r\n };\r\n };\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module(\"uiGmapgoogle-maps.directives.api.utils\").factory(\"uiGmapChromeFixes\", [\r\n '$timeout', function($timeout) {\r\n return {\r\n maybeRepaint: function(el) {\r\n if (el) {\r\n el.style.opacity = 0.9;\r\n return $timeout(function() {\r\n return el.style.opacity = 1;\r\n });\r\n }\r\n }\r\n };\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module('uiGmapgoogle-maps').service('uiGmapObjectIterators', function() {\r\n var _ignores, _iterators, _slapForEach, _slapMap;\r\n _ignores = ['length', 'forEach', 'map'];\r\n _iterators = [];\r\n _slapForEach = function(object) {\r\n object.forEach = function(cb) {\r\n return _.each(_.omit(object, _ignores), function(val) {\r\n if (!_.isFunction(val)) {\r\n return cb(val);\r\n }\r\n });\r\n };\r\n return object;\r\n };\r\n _iterators.push(_slapForEach);\r\n _slapMap = function(object) {\r\n object.map = function(cb) {\r\n return _.map(_.omit(object, _ignores), function(val) {\r\n if (!_.isFunction(val)) {\r\n return cb(val);\r\n }\r\n });\r\n };\r\n return object;\r\n };\r\n _iterators.push(_slapMap);\r\n return {\r\n slapMap: _slapMap,\r\n slapForEach: _slapForEach,\r\n slapAll: function(object) {\r\n _iterators.forEach(function(it) {\r\n return it(object);\r\n });\r\n return object;\r\n }\r\n };\r\n });\r\n\r\n}).call(this);\r\n;(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },\r\n extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api.options.builders').service('uiGmapCommonOptionsBuilder', [\r\n 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapModelKey', function(BaseObject, $log, ModelKey) {\r\n var CommonOptionsBuilder;\r\n return CommonOptionsBuilder = (function(superClass) {\r\n extend(CommonOptionsBuilder, superClass);\r\n\r\n function CommonOptionsBuilder() {\r\n this.watchProps = bind(this.watchProps, this);\r\n this.buildOpts = bind(this.buildOpts, this);\r\n return CommonOptionsBuilder.__super__.constructor.apply(this, arguments);\r\n }\r\n\r\n CommonOptionsBuilder.prototype.props = [\r\n 'clickable', 'draggable', 'editable', 'visible', {\r\n prop: 'stroke',\r\n isColl: true\r\n }\r\n ];\r\n\r\n CommonOptionsBuilder.prototype.getCorrectModel = function(scope) {\r\n if (angular.isDefined(scope != null ? scope.model : void 0)) {\r\n return scope.model;\r\n } else {\r\n return scope;\r\n }\r\n };\r\n\r\n CommonOptionsBuilder.prototype.buildOpts = function(customOpts, cachedEval, forEachOpts) {\r\n var model, opts, stroke;\r\n if (customOpts == null) {\r\n customOpts = {};\r\n }\r\n if (forEachOpts == null) {\r\n forEachOpts = {};\r\n }\r\n if (!this.scope) {\r\n $log.error('this.scope not defined in CommonOptionsBuilder can not buildOpts');\r\n return;\r\n }\r\n if (!this.map) {\r\n $log.error('this.map not defined in CommonOptionsBuilder can not buildOpts');\r\n return;\r\n }\r\n model = this.getCorrectModel(this.scope);\r\n stroke = this.scopeOrModelVal('stroke', this.scope, model);\r\n opts = angular.extend(customOpts, this.DEFAULTS, {\r\n map: this.map,\r\n strokeColor: stroke != null ? stroke.color : void 0,\r\n strokeOpacity: stroke != null ? stroke.opacity : void 0,\r\n strokeWeight: stroke != null ? stroke.weight : void 0\r\n });\r\n angular.forEach(angular.extend(forEachOpts, {\r\n clickable: true,\r\n draggable: false,\r\n editable: false,\r\n \"static\": false,\r\n fit: false,\r\n visible: true,\r\n zIndex: 0,\r\n icons: []\r\n }), (function(_this) {\r\n return function(defaultValue, key) {\r\n var val;\r\n val = cachedEval ? cachedEval[key] : _this.scopeOrModelVal(key, _this.scope, model);\r\n if (angular.isUndefined(val)) {\r\n return opts[key] = defaultValue;\r\n } else {\r\n return opts[key] = model[key];\r\n }\r\n };\r\n })(this));\r\n if (opts[\"static\"]) {\r\n opts.editable = false;\r\n }\r\n return opts;\r\n };\r\n\r\n CommonOptionsBuilder.prototype.watchProps = function(props) {\r\n if (props == null) {\r\n props = this.props;\r\n }\r\n return props.forEach((function(_this) {\r\n return function(prop) {\r\n if ((_this.attrs[prop] != null) || (_this.attrs[prop != null ? prop.prop : void 0] != null)) {\r\n if (prop != null ? prop.isColl : void 0) {\r\n return _this.scope.$watchCollection(prop.prop, _this.setMyOptions);\r\n } else {\r\n return _this.scope.$watch(prop, _this.setMyOptions);\r\n }\r\n }\r\n };\r\n })(this));\r\n };\r\n\r\n return CommonOptionsBuilder;\r\n\r\n })(ModelKey);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api.options.builders').factory('uiGmapPolylineOptionsBuilder', [\r\n 'uiGmapCommonOptionsBuilder', function(CommonOptionsBuilder) {\r\n var PolylineOptionsBuilder;\r\n return PolylineOptionsBuilder = (function(superClass) {\r\n extend(PolylineOptionsBuilder, superClass);\r\n\r\n function PolylineOptionsBuilder() {\r\n return PolylineOptionsBuilder.__super__.constructor.apply(this, arguments);\r\n }\r\n\r\n PolylineOptionsBuilder.prototype.buildOpts = function(pathPoints, cachedEval) {\r\n return PolylineOptionsBuilder.__super__.buildOpts.call(this, {\r\n path: pathPoints\r\n }, cachedEval, {\r\n geodesic: false\r\n });\r\n };\r\n\r\n return PolylineOptionsBuilder;\r\n\r\n })(CommonOptionsBuilder);\r\n }\r\n ]).factory('uiGmapShapeOptionsBuilder', [\r\n 'uiGmapCommonOptionsBuilder', function(CommonOptionsBuilder) {\r\n var ShapeOptionsBuilder;\r\n return ShapeOptionsBuilder = (function(superClass) {\r\n extend(ShapeOptionsBuilder, superClass);\r\n\r\n function ShapeOptionsBuilder() {\r\n return ShapeOptionsBuilder.__super__.constructor.apply(this, arguments);\r\n }\r\n\r\n ShapeOptionsBuilder.prototype.buildOpts = function(customOpts, cachedEval, forEachOpts) {\r\n var fill, model;\r\n model = this.getCorrectModel(this.scope);\r\n fill = cachedEval ? cachedEval['fill'] : this.scopeOrModelVal('fill', this.scope, model);\r\n customOpts = angular.extend(customOpts, {\r\n fillColor: fill != null ? fill.color : void 0,\r\n fillOpacity: fill != null ? fill.opacity : void 0\r\n });\r\n return ShapeOptionsBuilder.__super__.buildOpts.call(this, customOpts, cachedEval, forEachOpts);\r\n };\r\n\r\n return ShapeOptionsBuilder;\r\n\r\n })(CommonOptionsBuilder);\r\n }\r\n ]).factory('uiGmapPolygonOptionsBuilder', [\r\n 'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) {\r\n var PolygonOptionsBuilder;\r\n return PolygonOptionsBuilder = (function(superClass) {\r\n extend(PolygonOptionsBuilder, superClass);\r\n\r\n function PolygonOptionsBuilder() {\r\n return PolygonOptionsBuilder.__super__.constructor.apply(this, arguments);\r\n }\r\n\r\n PolygonOptionsBuilder.prototype.buildOpts = function(pathPoints, cachedEval) {\r\n return PolygonOptionsBuilder.__super__.buildOpts.call(this, {\r\n path: pathPoints\r\n }, cachedEval, {\r\n geodesic: false\r\n });\r\n };\r\n\r\n return PolygonOptionsBuilder;\r\n\r\n })(ShapeOptionsBuilder);\r\n }\r\n ]).factory('uiGmapRectangleOptionsBuilder', [\r\n 'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) {\r\n var RectangleOptionsBuilder;\r\n return RectangleOptionsBuilder = (function(superClass) {\r\n extend(RectangleOptionsBuilder, superClass);\r\n\r\n function RectangleOptionsBuilder() {\r\n return RectangleOptionsBuilder.__super__.constructor.apply(this, arguments);\r\n }\r\n\r\n RectangleOptionsBuilder.prototype.buildOpts = function(bounds, cachedEval) {\r\n return RectangleOptionsBuilder.__super__.buildOpts.call(this, {\r\n bounds: bounds\r\n }, cachedEval);\r\n };\r\n\r\n return RectangleOptionsBuilder;\r\n\r\n })(ShapeOptionsBuilder);\r\n }\r\n ]).factory('uiGmapCircleOptionsBuilder', [\r\n 'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) {\r\n var CircleOptionsBuilder;\r\n return CircleOptionsBuilder = (function(superClass) {\r\n extend(CircleOptionsBuilder, superClass);\r\n\r\n function CircleOptionsBuilder() {\r\n return CircleOptionsBuilder.__super__.constructor.apply(this, arguments);\r\n }\r\n\r\n CircleOptionsBuilder.prototype.buildOpts = function(center, radius, cachedEval) {\r\n return CircleOptionsBuilder.__super__.buildOpts.call(this, {\r\n center: center,\r\n radius: radius\r\n }, cachedEval);\r\n };\r\n\r\n return CircleOptionsBuilder;\r\n\r\n })(ShapeOptionsBuilder);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module('uiGmapgoogle-maps.directives.api.options').service('uiGmapMarkerOptions', [\r\n 'uiGmapLogger', 'uiGmapGmapUtil', function($log, GmapUtil) {\r\n return _.extend(GmapUtil, {\r\n createOptions: function(coords, icon, defaults, map) {\r\n var opts;\r\n if (defaults == null) {\r\n defaults = {};\r\n }\r\n opts = angular.extend({}, defaults, {\r\n position: defaults.position != null ? defaults.position : GmapUtil.getCoords(coords),\r\n visible: defaults.visible != null ? defaults.visible : GmapUtil.validateCoords(coords)\r\n });\r\n if ((defaults.icon != null) || (icon != null)) {\r\n opts = angular.extend(opts, {\r\n icon: defaults.icon != null ? defaults.icon : icon\r\n });\r\n }\r\n if (map != null) {\r\n opts.map = map;\r\n }\r\n return opts;\r\n },\r\n isLabel: function(options) {\r\n if (options == null) {\r\n return false;\r\n }\r\n return (options.labelContent != null) || (options.labelAnchor != null) || (options.labelClass != null) || (options.labelStyle != null) || (options.labelVisible != null);\r\n }\r\n });\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },\r\n extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapBasePolyChildModel', [\r\n 'uiGmapLogger', '$timeout', 'uiGmaparray-sync', 'uiGmapGmapUtil', 'uiGmapEventsHelper', function($log, $timeout, arraySync, GmapUtil, EventsHelper) {\r\n return function(Builder, gFactory) {\r\n var BasePolyChildModel;\r\n return BasePolyChildModel = (function(superClass) {\r\n extend(BasePolyChildModel, superClass);\r\n\r\n BasePolyChildModel.include(GmapUtil);\r\n\r\n function BasePolyChildModel(scope, attrs, map, defaults, model, gObjectChangeCb) {\r\n var create;\r\n this.scope = scope;\r\n this.attrs = attrs;\r\n this.map = map;\r\n this.defaults = defaults;\r\n this.model = model;\r\n this.clean = bind(this.clean, this);\r\n this.clonedModel = _.clone(this.model, true);\r\n this.isDragging = false;\r\n this.internalEvents = {\r\n dragend: (function(_this) {\r\n return function() {\r\n return _.defer(function() {\r\n return _this.isDragging = false;\r\n });\r\n };\r\n })(this),\r\n dragstart: (function(_this) {\r\n return function() {\r\n return _this.isDragging = true;\r\n };\r\n })(this)\r\n };\r\n create = (function(_this) {\r\n return function() {\r\n var maybeCachedEval;\r\n if (_this.isDragging) {\r\n return;\r\n }\r\n _this.pathPoints = _this.convertPathPoints(_this.scope.path);\r\n if (_this.gObject != null) {\r\n _this.clean();\r\n }\r\n if (_this.scope.model != null) {\r\n maybeCachedEval = _this.scope;\r\n }\r\n if (_this.pathPoints.length > 0) {\r\n _this.gObject = gFactory(_this.buildOpts(_this.pathPoints, maybeCachedEval));\r\n }\r\n if (_this.gObject) {\r\n arraySync(_this.gObject.getPath(), _this.scope, 'path', function(pathPoints) {\r\n _this.pathPoints = pathPoints;\r\n if (gObjectChangeCb != null) {\r\n return gObjectChangeCb();\r\n }\r\n });\r\n if (angular.isDefined(_this.scope.events) && angular.isObject(_this.scope.events)) {\r\n _this.listeners = _this.model ? EventsHelper.setEvents(_this.gObject, _this.scope, _this.model) : EventsHelper.setEvents(_this.gObject, _this.scope, _this.scope);\r\n }\r\n return _this.internalListeners = _this.model ? EventsHelper.setEvents(_this.gObject, {\r\n events: _this.internalEvents\r\n }, _this.model) : EventsHelper.setEvents(_this.gObject, {\r\n events: _this.internalEvents\r\n }, _this.scope);\r\n }\r\n };\r\n })(this);\r\n create();\r\n this.scope.$watch('path', (function(_this) {\r\n return function(newValue, oldValue) {\r\n if (!_.isEqual(newValue, oldValue) || !_this.gObject) {\r\n return create();\r\n }\r\n };\r\n })(this), true);\r\n if (!this.scope[\"static\"] && angular.isDefined(this.scope.editable)) {\r\n this.scope.$watch('editable', (function(_this) {\r\n return function(newValue, oldValue) {\r\n var ref;\r\n if (newValue !== oldValue) {\r\n newValue = !_this.isFalse(newValue);\r\n return (ref = _this.gObject) != null ? ref.setEditable(newValue) : void 0;\r\n }\r\n };\r\n })(this), true);\r\n }\r\n if (angular.isDefined(this.scope.draggable)) {\r\n this.scope.$watch('draggable', (function(_this) {\r\n return function(newValue, oldValue) {\r\n var ref;\r\n if (newValue !== oldValue) {\r\n newValue = !_this.isFalse(newValue);\r\n return (ref = _this.gObject) != null ? ref.setDraggable(newValue) : void 0;\r\n }\r\n };\r\n })(this), true);\r\n }\r\n if (angular.isDefined(this.scope.visible)) {\r\n this.scope.$watch('visible', (function(_this) {\r\n return function(newValue, oldValue) {\r\n var ref;\r\n if (newValue !== oldValue) {\r\n newValue = !_this.isFalse(newValue);\r\n }\r\n return (ref = _this.gObject) != null ? ref.setVisible(newValue) : void 0;\r\n };\r\n })(this), true);\r\n }\r\n if (angular.isDefined(this.scope.geodesic)) {\r\n this.scope.$watch('geodesic', (function(_this) {\r\n return function(newValue, oldValue) {\r\n var ref;\r\n if (newValue !== oldValue) {\r\n newValue = !_this.isFalse(newValue);\r\n return (ref = _this.gObject) != null ? ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0;\r\n }\r\n };\r\n })(this), true);\r\n }\r\n if (angular.isDefined(this.scope.stroke) && angular.isDefined(this.scope.stroke.weight)) {\r\n this.scope.$watch('stroke.weight', (function(_this) {\r\n return function(newValue, oldValue) {\r\n var ref;\r\n if (newValue !== oldValue) {\r\n return (ref = _this.gObject) != null ? ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0;\r\n }\r\n };\r\n })(this), true);\r\n }\r\n if (angular.isDefined(this.scope.stroke) && angular.isDefined(this.scope.stroke.color)) {\r\n this.scope.$watch('stroke.color', (function(_this) {\r\n return function(newValue, oldValue) {\r\n var ref;\r\n if (newValue !== oldValue) {\r\n return (ref = _this.gObject) != null ? ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0;\r\n }\r\n };\r\n })(this), true);\r\n }\r\n if (angular.isDefined(this.scope.stroke) && angular.isDefined(this.scope.stroke.opacity)) {\r\n this.scope.$watch('stroke.opacity', (function(_this) {\r\n return function(newValue, oldValue) {\r\n var ref;\r\n if (newValue !== oldValue) {\r\n return (ref = _this.gObject) != null ? ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0;\r\n }\r\n };\r\n })(this), true);\r\n }\r\n if (angular.isDefined(this.scope.icons)) {\r\n this.scope.$watch('icons', (function(_this) {\r\n return function(newValue, oldValue) {\r\n var ref;\r\n if (newValue !== oldValue) {\r\n return (ref = _this.gObject) != null ? ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0;\r\n }\r\n };\r\n })(this), true);\r\n }\r\n this.scope.$on('$destroy', (function(_this) {\r\n return function() {\r\n _this.clean();\r\n return _this.scope = null;\r\n };\r\n })(this));\r\n if (angular.isDefined(this.scope.fill) && angular.isDefined(this.scope.fill.color)) {\r\n this.scope.$watch('fill.color', (function(_this) {\r\n return function(newValue, oldValue) {\r\n if (newValue !== oldValue) {\r\n return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath()));\r\n }\r\n };\r\n })(this));\r\n }\r\n if (angular.isDefined(this.scope.fill) && angular.isDefined(this.scope.fill.opacity)) {\r\n this.scope.$watch('fill.opacity', (function(_this) {\r\n return function(newValue, oldValue) {\r\n if (newValue !== oldValue) {\r\n return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath()));\r\n }\r\n };\r\n })(this));\r\n }\r\n if (angular.isDefined(this.scope.zIndex)) {\r\n this.scope.$watch('zIndex', (function(_this) {\r\n return function(newValue, oldValue) {\r\n if (newValue !== oldValue) {\r\n return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath()));\r\n }\r\n };\r\n })(this));\r\n }\r\n }\r\n\r\n BasePolyChildModel.prototype.clean = function() {\r\n var ref;\r\n EventsHelper.removeEvents(this.listeners);\r\n EventsHelper.removeEvents(this.internalListeners);\r\n if ((ref = this.gObject) != null) {\r\n ref.setMap(null);\r\n }\r\n return this.gObject = null;\r\n };\r\n\r\n return BasePolyChildModel;\r\n\r\n })(Builder);\r\n };\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;\r\n/*\r\n@authors\r\nNicholas McCready - https://twitter.com/nmccready\r\nOriginal idea from: http://stackoverflow.com/questions/22758950/google-map-drawing-freehand , &\r\n http://jsfiddle.net/YsQdh/88/\r\n */\r\n\r\n(function() {\r\n angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapDrawFreeHandChildModel', [\r\n 'uiGmapLogger', '$q', function($log, $q) {\r\n var drawFreeHand, freeHandMgr;\r\n drawFreeHand = function(map, polys, done) {\r\n var move, poly;\r\n poly = new google.maps.Polyline({\r\n map: map,\r\n clickable: false\r\n });\r\n move = google.maps.event.addListener(map, 'mousemove', function(e) {\r\n return poly.getPath().push(e.latLng);\r\n });\r\n google.maps.event.addListenerOnce(map, 'mouseup', function(e) {\r\n var path;\r\n google.maps.event.removeListener(move);\r\n path = poly.getPath();\r\n poly.setMap(null);\r\n polys.push(new google.maps.Polygon({\r\n map: map,\r\n path: path\r\n }));\r\n poly = null;\r\n google.maps.event.clearListeners(map.getDiv(), 'mousedown');\r\n return done();\r\n });\r\n return void 0;\r\n };\r\n freeHandMgr = function(map1, scope) {\r\n var disableMap, enableMap;\r\n this.map = map1;\r\n disableMap = (function(_this) {\r\n return function() {\r\n var mapOptions;\r\n mapOptions = {\r\n draggable: false,\r\n disableDefaultUI: true,\r\n scrollwheel: false,\r\n disableDoubleClickZoom: false\r\n };\r\n $log.info('disabling map move');\r\n return _this.map.setOptions(mapOptions);\r\n };\r\n })(this);\r\n enableMap = (function(_this) {\r\n return function() {\r\n var mapOptions, ref;\r\n mapOptions = {\r\n draggable: true,\r\n disableDefaultUI: false,\r\n scrollwheel: true,\r\n disableDoubleClickZoom: true\r\n };\r\n if ((ref = _this.deferred) != null) {\r\n ref.resolve();\r\n }\r\n return _.defer(function() {\r\n return _this.map.setOptions(_.extend(mapOptions, scope.options));\r\n });\r\n };\r\n })(this);\r\n this.engage = (function(_this) {\r\n return function(polys1) {\r\n _this.polys = polys1;\r\n _this.deferred = $q.defer();\r\n disableMap();\r\n $log.info('DrawFreeHandChildModel is engaged (drawing).');\r\n google.maps.event.addDomListener(_this.map.getDiv(), 'mousedown', function(e) {\r\n return drawFreeHand(_this.map, _this.polys, enableMap);\r\n });\r\n return _this.deferred.promise;\r\n };\r\n })(this);\r\n return this;\r\n };\r\n return freeHandMgr;\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },\r\n extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapMarkerChildModel', [\r\n 'uiGmapModelKey', 'uiGmapGmapUtil', 'uiGmapLogger', 'uiGmapEventsHelper', 'uiGmapPropertyAction', 'uiGmapMarkerOptions', 'uiGmapIMarker', 'uiGmapMarkerManager', 'uiGmapPromise', function(ModelKey, GmapUtil, $log, EventsHelper, PropertyAction, MarkerOptions, IMarker, MarkerManager, uiGmapPromise) {\r\n var MarkerChildModel;\r\n MarkerChildModel = (function(superClass) {\r\n var destroy;\r\n\r\n extend(MarkerChildModel, superClass);\r\n\r\n MarkerChildModel.include(GmapUtil);\r\n\r\n MarkerChildModel.include(EventsHelper);\r\n\r\n MarkerChildModel.include(MarkerOptions);\r\n\r\n destroy = function(child) {\r\n if ((child != null ? child.gObject : void 0) != null) {\r\n child.removeEvents(child.externalListeners);\r\n child.removeEvents(child.internalListeners);\r\n if (child != null ? child.gObject : void 0) {\r\n if (child.removeFromManager) {\r\n child.gManager.remove(child.gObject);\r\n }\r\n child.gObject.setMap(null);\r\n return child.gObject = null;\r\n }\r\n }\r\n };\r\n\r\n function MarkerChildModel(scope, model1, keys, gMap, defaults, doClick, gManager, doDrawSelf, trackModel, needRedraw) {\r\n var action;\r\n this.model = model1;\r\n this.keys = keys;\r\n this.gMap = gMap;\r\n this.defaults = defaults;\r\n this.doClick = doClick;\r\n this.gManager = gManager;\r\n this.doDrawSelf = doDrawSelf != null ? doDrawSelf : true;\r\n this.trackModel = trackModel != null ? trackModel : true;\r\n this.needRedraw = needRedraw != null ? needRedraw : false;\r\n this.internalEvents = bind(this.internalEvents, this);\r\n this.setLabelOptions = bind(this.setLabelOptions, this);\r\n this.setOptions = bind(this.setOptions, this);\r\n this.setIcon = bind(this.setIcon, this);\r\n this.setCoords = bind(this.setCoords, this);\r\n this.isNotValid = bind(this.isNotValid, this);\r\n this.maybeSetScopeValue = bind(this.maybeSetScopeValue, this);\r\n this.createMarker = bind(this.createMarker, this);\r\n this.setMyScope = bind(this.setMyScope, this);\r\n this.updateModel = bind(this.updateModel, this);\r\n this.handleModelChanges = bind(this.handleModelChanges, this);\r\n this.destroy = bind(this.destroy, this);\r\n this.clonedModel = _.clone(this.model, true);\r\n this.deferred = uiGmapPromise.defer();\r\n _.each(this.keys, (function(_this) {\r\n return function(v, k) {\r\n var keyValue;\r\n keyValue = _this.keys[k];\r\n if ((keyValue != null) && !_.isFunction(keyValue) && _.isString(keyValue)) {\r\n return _this[k + 'Key'] = keyValue;\r\n }\r\n };\r\n })(this));\r\n this.idKey = this.idKeyKey || 'id';\r\n if (this.model[this.idKey] != null) {\r\n this.id = this.model[this.idKey];\r\n }\r\n MarkerChildModel.__super__.constructor.call(this, scope);\r\n this.scope.getGMarker = (function(_this) {\r\n return function() {\r\n return _this.gObject;\r\n };\r\n })(this);\r\n this.firstTime = true;\r\n if (this.trackModel) {\r\n this.scope.model = this.model;\r\n this.scope.$watch('model', (function(_this) {\r\n return function(newValue, oldValue) {\r\n if (newValue !== oldValue) {\r\n return _this.handleModelChanges(newValue, oldValue);\r\n }\r\n };\r\n })(this), true);\r\n } else {\r\n action = new PropertyAction((function(_this) {\r\n return function(calledKey, newVal) {\r\n if (!_this.firstTime) {\r\n return _this.setMyScope(calledKey, scope);\r\n }\r\n };\r\n })(this), false);\r\n _.each(this.keys, function(v, k) {\r\n return scope.$watch(k, action.sic, true);\r\n });\r\n }\r\n this.scope.$on('$destroy', (function(_this) {\r\n return function() {\r\n return destroy(_this);\r\n };\r\n })(this));\r\n this.createMarker(this.model);\r\n $log.info(this);\r\n }\r\n\r\n MarkerChildModel.prototype.destroy = function(removeFromManager) {\r\n if (removeFromManager == null) {\r\n removeFromManager = true;\r\n }\r\n this.removeFromManager = removeFromManager;\r\n return this.scope.$destroy();\r\n };\r\n\r\n MarkerChildModel.prototype.handleModelChanges = function(newValue, oldValue) {\r\n var changes, ctr, len;\r\n changes = this.getChanges(newValue, oldValue, IMarker.keys);\r\n if (!this.firstTime) {\r\n ctr = 0;\r\n len = _.keys(changes).length;\r\n return _.each(changes, (function(_this) {\r\n return function(v, k) {\r\n var doDraw;\r\n ctr += 1;\r\n doDraw = len === ctr;\r\n _this.setMyScope(k, newValue, oldValue, false, true, doDraw);\r\n return _this.needRedraw = true;\r\n };\r\n })(this));\r\n }\r\n };\r\n\r\n MarkerChildModel.prototype.updateModel = function(model) {\r\n this.clonedModel = _.clone(model, true);\r\n return this.setMyScope('all', model, this.model);\r\n };\r\n\r\n MarkerChildModel.prototype.renderGMarker = function(doDraw, validCb) {\r\n var coords, isSpiderfied, ref;\r\n if (doDraw == null) {\r\n doDraw = true;\r\n }\r\n coords = this.getProp('coords', this.scope, this.model);\r\n if (((ref = this.gManager) != null ? ref.isSpiderfied : void 0) != null) {\r\n isSpiderfied = this.gManager.isSpiderfied();\r\n }\r\n if (coords != null) {\r\n if (!this.validateCoords(coords)) {\r\n $log.debug('MarkerChild does not have coords yet. They may be defined later.');\r\n return;\r\n }\r\n if (validCb != null) {\r\n validCb();\r\n }\r\n if (doDraw && this.gObject) {\r\n this.gManager.add(this.gObject);\r\n }\r\n if (isSpiderfied) {\r\n return this.gManager.markerSpiderfier.spiderListener(this.gObject, window.event);\r\n }\r\n } else {\r\n if (doDraw && this.gObject) {\r\n return this.gManager.remove(this.gObject);\r\n }\r\n }\r\n };\r\n\r\n MarkerChildModel.prototype.setMyScope = function(thingThatChanged, model, oldModel, isInit, doDraw) {\r\n var justCreated;\r\n if (oldModel == null) {\r\n oldModel = void 0;\r\n }\r\n if (isInit == null) {\r\n isInit = false;\r\n }\r\n if (doDraw == null) {\r\n doDraw = true;\r\n }\r\n if (model == null) {\r\n model = this.model;\r\n } else {\r\n this.model = model;\r\n }\r\n if (!this.gObject) {\r\n this.setOptions(this.scope, doDraw);\r\n justCreated = true;\r\n }\r\n switch (thingThatChanged) {\r\n case 'all':\r\n return _.each(this.keys, (function(_this) {\r\n return function(v, k) {\r\n return _this.setMyScope(k, model, oldModel, isInit, doDraw);\r\n };\r\n })(this));\r\n case 'icon':\r\n return this.maybeSetScopeValue('icon', model, oldModel, this.iconKey, this.evalModelHandle, isInit, this.setIcon, doDraw);\r\n case 'coords':\r\n return this.maybeSetScopeValue('coords', model, oldModel, this.coordsKey, this.evalModelHandle, isInit, this.setCoords, doDraw);\r\n case 'options':\r\n if (!justCreated) {\r\n return this.createMarker(model, oldModel, isInit, doDraw);\r\n }\r\n }\r\n };\r\n\r\n MarkerChildModel.prototype.createMarker = function(model, oldModel, isInit, doDraw) {\r\n if (oldModel == null) {\r\n oldModel = void 0;\r\n }\r\n if (isInit == null) {\r\n isInit = false;\r\n }\r\n if (doDraw == null) {\r\n doDraw = true;\r\n }\r\n this.maybeSetScopeValue('options', model, oldModel, this.optionsKey, this.evalModelHandle, isInit, this.setOptions, doDraw);\r\n return this.firstTime = false;\r\n };\r\n\r\n MarkerChildModel.prototype.maybeSetScopeValue = function(scopePropName, model, oldModel, modelKey, evaluate, isInit, gSetter, doDraw) {\r\n if (gSetter == null) {\r\n gSetter = void 0;\r\n }\r\n if (doDraw == null) {\r\n doDraw = true;\r\n }\r\n if (gSetter != null) {\r\n return gSetter(this.scope, doDraw);\r\n }\r\n };\r\n\r\n if (MarkerChildModel.doDrawSelf && doDraw) {\r\n MarkerChildModel.gManager.draw();\r\n }\r\n\r\n MarkerChildModel.prototype.isNotValid = function(scope, doCheckGmarker) {\r\n var hasIdenticalScopes, hasNoGmarker;\r\n if (doCheckGmarker == null) {\r\n doCheckGmarker = true;\r\n }\r\n hasNoGmarker = !doCheckGmarker ? false : this.gObject === void 0;\r\n hasIdenticalScopes = !this.trackModel ? scope.$id !== this.scope.$id : false;\r\n return hasIdenticalScopes || hasNoGmarker;\r\n };\r\n\r\n MarkerChildModel.prototype.setCoords = function(scope, doDraw) {\r\n if (doDraw == null) {\r\n doDraw = true;\r\n }\r\n if (this.isNotValid(scope) || (this.gObject == null)) {\r\n return;\r\n }\r\n return this.renderGMarker(doDraw, (function(_this) {\r\n return function() {\r\n var newGValue, newModelVal, oldGValue;\r\n newModelVal = _this.getProp('coords', scope, _this.model);\r\n newGValue = _this.getCoords(newModelVal);\r\n oldGValue = _this.gObject.getPosition();\r\n if ((oldGValue != null) && (newGValue != null)) {\r\n if (newGValue.lng() === oldGValue.lng() && newGValue.lat() === oldGValue.lat()) {\r\n return;\r\n }\r\n }\r\n _this.gObject.setPosition(newGValue);\r\n return _this.gObject.setVisible(_this.validateCoords(newModelVal));\r\n };\r\n })(this));\r\n };\r\n\r\n MarkerChildModel.prototype.setIcon = function(scope, doDraw) {\r\n if (doDraw == null) {\r\n doDraw = true;\r\n }\r\n if (this.isNotValid(scope) || (this.gObject == null)) {\r\n return;\r\n }\r\n return this.renderGMarker(doDraw, (function(_this) {\r\n return function() {\r\n var coords, newValue, oldValue;\r\n oldValue = _this.gObject.getIcon();\r\n newValue = _this.getProp('icon', scope, _this.model);\r\n if (oldValue === newValue) {\r\n return;\r\n }\r\n _this.gObject.setIcon(newValue);\r\n coords = _this.getProp('coords', scope, _this.model);\r\n _this.gObject.setPosition(_this.getCoords(coords));\r\n return _this.gObject.setVisible(_this.validateCoords(coords));\r\n };\r\n })(this));\r\n };\r\n\r\n MarkerChildModel.prototype.setOptions = function(scope, doDraw) {\r\n var ref;\r\n if (doDraw == null) {\r\n doDraw = true;\r\n }\r\n if (this.isNotValid(scope, false)) {\r\n return;\r\n }\r\n this.renderGMarker(doDraw, (function(_this) {\r\n return function() {\r\n var _options, coords, icon;\r\n coords = _this.getProp('coords', scope, _this.model);\r\n icon = _this.getProp('icon', scope, _this.model);\r\n _options = _this.getProp('options', scope, _this.model);\r\n _this.opts = _this.createOptions(coords, icon, _options);\r\n if (_this.isLabel(_this.gObject) !== _this.isLabel(_this.opts) && (_this.gObject != null)) {\r\n _this.gManager.remove(_this.gObject);\r\n _this.gObject = void 0;\r\n }\r\n if (_this.gObject != null) {\r\n _this.gObject.setOptions(_this.setLabelOptions(_this.opts));\r\n }\r\n if (!_this.gObject) {\r\n if (_this.isLabel(_this.opts)) {\r\n _this.gObject = new MarkerWithLabel(_this.setLabelOptions(_this.opts));\r\n } else if (_this.opts.content) {\r\n _this.gObject = new RichMarker(_this.opts);\r\n _this.gObject.getIcon = _this.gObject.getContent;\r\n _this.gObject.setIcon = _this.gObject.setContent;\r\n } else {\r\n _this.gObject = new google.maps.Marker(_this.opts);\r\n }\r\n _.extend(_this.gObject, {\r\n model: _this.model\r\n });\r\n }\r\n if (_this.externalListeners) {\r\n _this.removeEvents(_this.externalListeners);\r\n }\r\n if (_this.internalListeners) {\r\n _this.removeEvents(_this.internalListeners);\r\n }\r\n _this.externalListeners = _this.setEvents(_this.gObject, _this.scope, _this.model, ['dragend']);\r\n _this.internalListeners = _this.setEvents(_this.gObject, {\r\n events: _this.internalEvents(),\r\n $evalAsync: function() {}\r\n }, _this.model);\r\n if (_this.id != null) {\r\n return _this.gObject.key = _this.id;\r\n }\r\n };\r\n })(this));\r\n if (this.gObject && (this.gObject.getMap() || this.gManager.type !== MarkerManager.type)) {\r\n this.deferred.resolve(this.gObject);\r\n } else {\r\n if (!this.gObject) {\r\n return this.deferred.reject('gObject is null');\r\n }\r\n if (!(((ref = this.gObject) != null ? ref.getMap() : void 0) && this.gManager.type === MarkerManager.type)) {\r\n $log.debug('gObject has no map yet');\r\n this.deferred.resolve(this.gObject);\r\n }\r\n }\r\n if (this.model[this.fitKey]) {\r\n return this.gManager.fit();\r\n }\r\n };\r\n\r\n MarkerChildModel.prototype.setLabelOptions = function(opts) {\r\n if (opts.labelAnchor) {\r\n opts.labelAnchor = this.getLabelPositionPoint(opts.labelAnchor);\r\n }\r\n return opts;\r\n };\r\n\r\n MarkerChildModel.prototype.internalEvents = function() {\r\n return {\r\n dragend: (function(_this) {\r\n return function(marker, eventName, model, mousearg) {\r\n var events, modelToSet, newCoords;\r\n modelToSet = _this.trackModel ? _this.scope.model : _this.model;\r\n newCoords = _this.setCoordsFromEvent(_this.modelOrKey(modelToSet, _this.coordsKey), _this.gObject.getPosition());\r\n modelToSet = _this.setVal(model, _this.coordsKey, newCoords);\r\n events = _this.scope.events;\r\n if ((events != null ? events.dragend : void 0) != null) {\r\n events.dragend(marker, eventName, modelToSet, mousearg);\r\n }\r\n return _this.scope.$apply();\r\n };\r\n })(this),\r\n click: (function(_this) {\r\n return function(marker, eventName, model, mousearg) {\r\n var click;\r\n click = _this.getProp('click', _this.scope, _this.model);\r\n if (_this.doClick && (click != null)) {\r\n return _this.scope.$evalAsync(click(marker, eventName, _this.model, mousearg));\r\n }\r\n };\r\n })(this)\r\n };\r\n };\r\n\r\n return MarkerChildModel;\r\n\r\n })(ModelKey);\r\n return MarkerChildModel;\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygonChildModel', [\r\n 'uiGmapBasePolyChildModel', 'uiGmapPolygonOptionsBuilder', function(BaseGen, Builder) {\r\n var PolygonChildModel, base, gFactory;\r\n gFactory = function(opts) {\r\n return new google.maps.Polygon(opts);\r\n };\r\n base = new BaseGen(Builder, gFactory);\r\n return PolygonChildModel = (function(superClass) {\r\n extend(PolygonChildModel, superClass);\r\n\r\n function PolygonChildModel() {\r\n return PolygonChildModel.__super__.constructor.apply(this, arguments);\r\n }\r\n\r\n return PolygonChildModel;\r\n\r\n })(base);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolylineChildModel', [\r\n 'uiGmapBasePolyChildModel', 'uiGmapPolylineOptionsBuilder', function(BaseGen, Builder) {\r\n var PolylineChildModel, base, gFactory;\r\n gFactory = function(opts) {\r\n return new google.maps.Polyline(opts);\r\n };\r\n base = BaseGen(Builder, gFactory);\r\n return PolylineChildModel = (function(superClass) {\r\n extend(PolylineChildModel, superClass);\r\n\r\n function PolylineChildModel() {\r\n return PolylineChildModel.__super__.constructor.apply(this, arguments);\r\n }\r\n\r\n return PolylineChildModel;\r\n\r\n })(base);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },\r\n extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapWindowChildModel', [\r\n 'uiGmapBaseObject', 'uiGmapGmapUtil', 'uiGmapLogger', '$compile', '$http', '$templateCache', 'uiGmapChromeFixes', 'uiGmapEventsHelper', function(BaseObject, GmapUtil, $log, $compile, $http, $templateCache, ChromeFixes, EventsHelper) {\r\n var WindowChildModel;\r\n WindowChildModel = (function(superClass) {\r\n extend(WindowChildModel, superClass);\r\n\r\n WindowChildModel.include(GmapUtil);\r\n\r\n WindowChildModel.include(EventsHelper);\r\n\r\n function WindowChildModel(model1, scope1, opts, isIconVisibleOnClick, mapCtrl, markerScope, element, needToManualDestroy, markerIsVisibleAfterWindowClose) {\r\n var maybeMarker;\r\n this.model = model1;\r\n this.scope = scope1;\r\n this.opts = opts;\r\n this.isIconVisibleOnClick = isIconVisibleOnClick;\r\n this.mapCtrl = mapCtrl;\r\n this.markerScope = markerScope;\r\n this.element = element;\r\n this.needToManualDestroy = needToManualDestroy != null ? needToManualDestroy : false;\r\n this.markerIsVisibleAfterWindowClose = markerIsVisibleAfterWindowClose != null ? markerIsVisibleAfterWindowClose : true;\r\n this.updateModel = bind(this.updateModel, this);\r\n this.destroy = bind(this.destroy, this);\r\n this.remove = bind(this.remove, this);\r\n this.getLatestPosition = bind(this.getLatestPosition, this);\r\n this.hideWindow = bind(this.hideWindow, this);\r\n this.showWindow = bind(this.showWindow, this);\r\n this.handleClick = bind(this.handleClick, this);\r\n this.watchOptions = bind(this.watchOptions, this);\r\n this.watchCoords = bind(this.watchCoords, this);\r\n this.createGWin = bind(this.createGWin, this);\r\n this.watchElement = bind(this.watchElement, this);\r\n this.watchAndDoShow = bind(this.watchAndDoShow, this);\r\n this.doShow = bind(this.doShow, this);\r\n this.clonedModel = _.clone(this.model, true);\r\n this.getGmarker = function() {\r\n var ref, ref1;\r\n if (((ref = this.markerScope) != null ? ref['getGMarker'] : void 0) != null) {\r\n return (ref1 = this.markerScope) != null ? ref1.getGMarker() : void 0;\r\n }\r\n };\r\n this.listeners = [];\r\n this.createGWin();\r\n maybeMarker = this.getGmarker();\r\n if (maybeMarker != null) {\r\n maybeMarker.setClickable(true);\r\n }\r\n this.watchElement();\r\n this.watchOptions();\r\n this.watchCoords();\r\n this.watchAndDoShow();\r\n this.scope.$on('$destroy', (function(_this) {\r\n return function() {\r\n return _this.destroy();\r\n };\r\n })(this));\r\n $log.info(this);\r\n }\r\n\r\n WindowChildModel.prototype.doShow = function(wasOpen) {\r\n if (this.scope.show === true || wasOpen) {\r\n return this.showWindow();\r\n } else {\r\n return this.hideWindow();\r\n }\r\n };\r\n\r\n WindowChildModel.prototype.watchAndDoShow = function() {\r\n if (this.model.show != null) {\r\n this.scope.show = this.model.show;\r\n }\r\n this.scope.$watch('show', this.doShow, true);\r\n return this.doShow();\r\n };\r\n\r\n WindowChildModel.prototype.watchElement = function() {\r\n return this.scope.$watch((function(_this) {\r\n return function() {\r\n var ref, wasOpen;\r\n if (!(_this.element || _this.html)) {\r\n return;\r\n }\r\n if (_this.html !== _this.element.html() && _this.gObject) {\r\n if ((ref = _this.opts) != null) {\r\n ref.content = void 0;\r\n }\r\n wasOpen = _this.gObject.isOpen();\r\n _this.remove();\r\n return _this.createGWin(wasOpen);\r\n }\r\n };\r\n })(this));\r\n };\r\n\r\n WindowChildModel.prototype.createGWin = function(isOpen) {\r\n var _opts, defaults, maybeMarker, ref, ref1;\r\n if (isOpen == null) {\r\n isOpen = false;\r\n }\r\n maybeMarker = this.getGmarker();\r\n defaults = {};\r\n if (this.opts != null) {\r\n if (this.scope.coords) {\r\n this.opts.position = this.getCoords(this.scope.coords);\r\n }\r\n defaults = this.opts;\r\n }\r\n if (this.element) {\r\n this.html = _.isObject(this.element) ? this.element.html() : this.element;\r\n }\r\n _opts = this.scope.options ? this.scope.options : defaults;\r\n this.opts = this.createWindowOptions(maybeMarker, this.markerScope || this.scope, this.html, _opts);\r\n if (this.opts != null) {\r\n if (!this.gObject) {\r\n if (this.opts.boxClass && (window.InfoBox && typeof window.InfoBox === 'function')) {\r\n this.gObject = new window.InfoBox(this.opts);\r\n } else {\r\n this.gObject = new google.maps.InfoWindow(this.opts);\r\n }\r\n this.listeners.push(google.maps.event.addListener(this.gObject, 'domready', function() {\r\n return ChromeFixes.maybeRepaint(this.content);\r\n }));\r\n this.listeners.push(google.maps.event.addListener(this.gObject, 'closeclick', (function(_this) {\r\n return function() {\r\n if (maybeMarker) {\r\n maybeMarker.setAnimation(_this.oldMarkerAnimation);\r\n if (_this.markerIsVisibleAfterWindowClose) {\r\n _.delay(function() {\r\n maybeMarker.setVisible(false);\r\n return maybeMarker.setVisible(_this.markerIsVisibleAfterWindowClose);\r\n }, 250);\r\n }\r\n }\r\n _this.gObject.close();\r\n _this.model.show = false;\r\n if (_this.scope.closeClick != null) {\r\n return _this.scope.$evalAsync(_this.scope.closeClick());\r\n } else {\r\n return _this.scope.$evalAsync();\r\n }\r\n };\r\n })(this)));\r\n }\r\n this.gObject.setContent(this.opts.content);\r\n this.handleClick(((ref = this.scope) != null ? (ref1 = ref.options) != null ? ref1.forceClick : void 0 : void 0) || isOpen);\r\n return this.doShow(this.gObject.isOpen());\r\n }\r\n };\r\n\r\n WindowChildModel.prototype.watchCoords = function() {\r\n var scope;\r\n scope = this.markerScope != null ? this.markerScope : this.scope;\r\n return scope.$watch('coords', (function(_this) {\r\n return function(newValue, oldValue) {\r\n var pos;\r\n if (newValue !== oldValue) {\r\n if (newValue == null) {\r\n _this.hideWindow();\r\n } else if (!_this.validateCoords(newValue)) {\r\n $log.error(\"WindowChildMarker cannot render marker as scope.coords as no position on marker: \" + (JSON.stringify(_this.model)));\r\n return;\r\n }\r\n pos = _this.getCoords(newValue);\r\n _this.doShow();\r\n _this.gObject.setPosition(pos);\r\n if (_this.opts) {\r\n return _this.opts.position = pos;\r\n }\r\n }\r\n };\r\n })(this), true);\r\n };\r\n\r\n WindowChildModel.prototype.watchOptions = function() {\r\n return this.scope.$watch('options', (function(_this) {\r\n return function(newValue, oldValue) {\r\n if (newValue !== oldValue) {\r\n _this.opts = newValue;\r\n if (_this.gObject != null) {\r\n _this.gObject.setOptions(_this.opts);\r\n if ((_this.opts.visible != null) && _this.opts.visible) {\r\n return _this.showWindow();\r\n } else if (_this.opts.visible != null) {\r\n return _this.hideWindow();\r\n }\r\n }\r\n }\r\n };\r\n })(this), true);\r\n };\r\n\r\n WindowChildModel.prototype.handleClick = function(forceClick) {\r\n var click, maybeMarker;\r\n if (this.gObject == null) {\r\n return;\r\n }\r\n maybeMarker = this.getGmarker();\r\n click = (function(_this) {\r\n return function() {\r\n if (_this.gObject == null) {\r\n _this.createGWin();\r\n }\r\n _this.showWindow();\r\n if (maybeMarker != null) {\r\n _this.initialMarkerVisibility = maybeMarker.getVisible();\r\n _this.oldMarkerAnimation = maybeMarker.getAnimation();\r\n return maybeMarker.setVisible(_this.isIconVisibleOnClick);\r\n }\r\n };\r\n })(this);\r\n if (forceClick) {\r\n click();\r\n }\r\n if (maybeMarker) {\r\n return this.listeners = this.listeners.concat(this.setEvents(maybeMarker, {\r\n events: {\r\n click: click\r\n }\r\n }, this.model));\r\n }\r\n };\r\n\r\n WindowChildModel.prototype.showWindow = function() {\r\n var compiled, show, templateScope;\r\n if (this.gObject != null) {\r\n show = (function(_this) {\r\n return function() {\r\n var isOpen, maybeMarker, pos;\r\n if (!_this.gObject.isOpen()) {\r\n maybeMarker = _this.getGmarker();\r\n if ((_this.gObject != null) && (_this.gObject.getPosition != null)) {\r\n pos = _this.gObject.getPosition();\r\n }\r\n if (maybeMarker) {\r\n pos = maybeMarker.getPosition();\r\n }\r\n if (!pos) {\r\n return;\r\n }\r\n _this.gObject.open(_this.mapCtrl, maybeMarker);\r\n isOpen = _this.gObject.isOpen();\r\n if (_this.model.show !== isOpen) {\r\n return _this.model.show = isOpen;\r\n }\r\n }\r\n };\r\n })(this);\r\n if (this.scope.templateUrl) {\r\n return $http.get(this.scope.templateUrl, {\r\n cache: $templateCache\r\n }).then((function(_this) {\r\n return function(content) {\r\n var compiled, templateScope;\r\n templateScope = _this.scope.$new();\r\n if (angular.isDefined(_this.scope.templateParameter)) {\r\n templateScope.parameter = _this.scope.templateParameter;\r\n }\r\n compiled = $compile(content.data)(templateScope);\r\n _this.gObject.setContent(compiled[0]);\r\n return show();\r\n };\r\n })(this));\r\n } else if (this.scope.template) {\r\n templateScope = this.scope.$new();\r\n if (angular.isDefined(this.scope.templateParameter)) {\r\n templateScope.parameter = this.scope.templateParameter;\r\n }\r\n compiled = $compile(this.scope.template)(templateScope);\r\n this.gObject.setContent(compiled[0]);\r\n return show();\r\n } else {\r\n return show();\r\n }\r\n }\r\n };\r\n\r\n WindowChildModel.prototype.hideWindow = function() {\r\n if ((this.gObject != null) && this.gObject.isOpen()) {\r\n return this.gObject.close();\r\n }\r\n };\r\n\r\n WindowChildModel.prototype.getLatestPosition = function(overridePos) {\r\n var maybeMarker;\r\n maybeMarker = this.getGmarker();\r\n if ((this.gObject != null) && (maybeMarker != null) && !overridePos) {\r\n return this.gObject.setPosition(maybeMarker.getPosition());\r\n } else {\r\n if (overridePos) {\r\n return this.gObject.setPosition(overridePos);\r\n }\r\n }\r\n };\r\n\r\n WindowChildModel.prototype.remove = function() {\r\n this.hideWindow();\r\n this.removeEvents(this.listeners);\r\n this.listeners.length = 0;\r\n delete this.gObject;\r\n return delete this.opts;\r\n };\r\n\r\n WindowChildModel.prototype.destroy = function(manualOverride) {\r\n var ref;\r\n if (manualOverride == null) {\r\n manualOverride = false;\r\n }\r\n this.remove();\r\n if ((this.scope != null) && !((ref = this.scope) != null ? ref.$$destroyed : void 0) && (this.needToManualDestroy || manualOverride)) {\r\n return this.scope.$destroy();\r\n }\r\n };\r\n\r\n WindowChildModel.prototype.updateModel = function(model) {\r\n this.clonedModel = _.clone(model, true);\r\n return _.extend(this.model, this.clonedModel);\r\n };\r\n\r\n return WindowChildModel;\r\n\r\n })(BaseObject);\r\n return WindowChildModel;\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },\r\n extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapBasePolysParentModel', [\r\n '$timeout', 'uiGmapLogger', 'uiGmapModelKey', 'uiGmapModelsWatcher', 'uiGmapPropMap', 'uiGmap_async', 'uiGmapPromise', 'uiGmapFitHelper', function($timeout, $log, ModelKey, ModelsWatcher, PropMap, _async, uiGmapPromise, FitHelper) {\r\n return function(IPoly, PolyChildModel, gObjectName) {\r\n var BasePolysParentModel;\r\n return BasePolysParentModel = (function(superClass) {\r\n extend(BasePolysParentModel, superClass);\r\n\r\n BasePolysParentModel.include(ModelsWatcher);\r\n\r\n function BasePolysParentModel(scope, element, attrs, gMap1, defaults) {\r\n this.element = element;\r\n this.attrs = attrs;\r\n this.gMap = gMap1;\r\n this.defaults = defaults;\r\n this.maybeFit = bind(this.maybeFit, this);\r\n this.createChild = bind(this.createChild, this);\r\n this.pieceMeal = bind(this.pieceMeal, this);\r\n this.createAllNew = bind(this.createAllNew, this);\r\n this.watchIdKey = bind(this.watchIdKey, this);\r\n this.createChildScopes = bind(this.createChildScopes, this);\r\n this.watchDestroy = bind(this.watchDestroy, this);\r\n this.onDestroy = bind(this.onDestroy, this);\r\n this.rebuildAll = bind(this.rebuildAll, this);\r\n this.doINeedToWipe = bind(this.doINeedToWipe, this);\r\n this.watchModels = bind(this.watchModels, this);\r\n BasePolysParentModel.__super__.constructor.call(this, scope);\r\n this[\"interface\"] = IPoly;\r\n this.$log = $log;\r\n this.plurals = new PropMap();\r\n _.each(IPoly.scopeKeys, (function(_this) {\r\n return function(name) {\r\n return _this[name + 'Key'] = void 0;\r\n };\r\n })(this));\r\n this.models = void 0;\r\n this.firstTime = true;\r\n this.$log.info(this);\r\n this.createChildScopes();\r\n }\r\n\r\n BasePolysParentModel.prototype.watchModels = function(scope) {\r\n\r\n /*\r\n This was watchCollection but not all model changes were being caught.\r\n TODO: Make the directive flexible in overriding whether we watch models (and depth) via watch or watchColleciton.\r\n */\r\n return scope.$watch('models', (function(_this) {\r\n return function(newValue, oldValue) {\r\n if (newValue !== oldValue) {\r\n if (_this.doINeedToWipe(newValue) || scope.doRebuildAll) {\r\n return _this.rebuildAll(scope, true, true);\r\n } else {\r\n return _this.createChildScopes(false);\r\n }\r\n }\r\n };\r\n })(this), true);\r\n };\r\n\r\n BasePolysParentModel.prototype.doINeedToWipe = function(newValue) {\r\n var newValueIsEmpty;\r\n newValueIsEmpty = newValue != null ? newValue.length === 0 : true;\r\n return this.plurals.length > 0 && newValueIsEmpty;\r\n };\r\n\r\n BasePolysParentModel.prototype.rebuildAll = function(scope, doCreate, doDelete) {\r\n return this.onDestroy(doDelete).then((function(_this) {\r\n return function() {\r\n if (doCreate) {\r\n return _this.createChildScopes();\r\n }\r\n };\r\n })(this));\r\n };\r\n\r\n BasePolysParentModel.prototype.onDestroy = function(scope) {\r\n BasePolysParentModel.__super__.onDestroy.call(this, this.scope);\r\n return _async.promiseLock(this, uiGmapPromise.promiseTypes[\"delete\"], void 0, void 0, (function(_this) {\r\n return function() {\r\n return _async.each(_this.plurals.values(), function(child) {\r\n return child.destroy(true);\r\n }, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() {\r\n var ref;\r\n return (ref = _this.plurals) != null ? ref.removeAll() : void 0;\r\n });\r\n };\r\n })(this));\r\n };\r\n\r\n BasePolysParentModel.prototype.watchDestroy = function(scope) {\r\n return scope.$on('$destroy', (function(_this) {\r\n return function() {\r\n return _this.rebuildAll(scope, false, true);\r\n };\r\n })(this));\r\n };\r\n\r\n BasePolysParentModel.prototype.createChildScopes = function(isCreatingFromScratch) {\r\n if (isCreatingFromScratch == null) {\r\n isCreatingFromScratch = true;\r\n }\r\n if (angular.isUndefined(this.scope.models)) {\r\n this.$log.error(\"No models to create \" + gObjectName + \"s from! I Need direct models!\");\r\n return;\r\n }\r\n if ((this.gMap == null) || (this.scope.models == null)) {\r\n return;\r\n }\r\n this.watchIdKey(this.scope);\r\n if (isCreatingFromScratch) {\r\n return this.createAllNew(this.scope, false);\r\n } else {\r\n return this.pieceMeal(this.scope, false);\r\n }\r\n };\r\n\r\n BasePolysParentModel.prototype.watchIdKey = function(scope) {\r\n this.setIdKey(scope);\r\n return scope.$watch('idKey', (function(_this) {\r\n return function(newValue, oldValue) {\r\n if (newValue !== oldValue && (newValue == null)) {\r\n _this.idKey = newValue;\r\n return _this.rebuildAll(scope, true, true);\r\n }\r\n };\r\n })(this));\r\n };\r\n\r\n BasePolysParentModel.prototype.createAllNew = function(scope, isArray) {\r\n var maybeCanceled;\r\n if (isArray == null) {\r\n isArray = false;\r\n }\r\n this.models = scope.models;\r\n if (this.firstTime) {\r\n this.watchModels(scope);\r\n this.watchDestroy(scope);\r\n }\r\n if (this.didQueueInitPromise(this, scope)) {\r\n return;\r\n }\r\n maybeCanceled = null;\r\n return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) {\r\n return maybeCanceled = canceledMsg;\r\n }), (function(_this) {\r\n return function() {\r\n return _async.map(scope.models, function(model) {\r\n var child;\r\n child = _this.createChild(model, _this.gMap);\r\n if (maybeCanceled) {\r\n $log.debug('createNew should fall through safely');\r\n child.isEnabled = false;\r\n }\r\n maybeCanceled;\r\n return child.pathPoints.getArray();\r\n }, _async.chunkSizeFrom(scope.chunk)).then(function(pathPoints) {\r\n _this.maybeFit(pathPoints);\r\n return _this.firstTime = false;\r\n });\r\n };\r\n })(this));\r\n };\r\n\r\n BasePolysParentModel.prototype.pieceMeal = function(scope, isArray) {\r\n var maybeCanceled, payload;\r\n if (isArray == null) {\r\n isArray = true;\r\n }\r\n if (scope.$$destroyed) {\r\n return;\r\n }\r\n maybeCanceled = null;\r\n payload = null;\r\n this.models = scope.models;\r\n if ((scope != null) && this.modelsLength() && this.plurals.length) {\r\n return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) {\r\n return maybeCanceled = canceledMsg;\r\n }), (function(_this) {\r\n return function() {\r\n return uiGmapPromise.promise(function() {\r\n return _this.figureOutState(_this.idKey, scope, _this.plurals, _this.modelKeyComparison);\r\n }).then(function(state) {\r\n payload = state;\r\n if (payload.updates.length) {\r\n _async.each(payload.updates, function(obj) {\r\n _.extend(obj.child.scope, obj.model);\r\n return obj.child.model = obj.model;\r\n });\r\n }\r\n return _async.each(payload.removals, function(child) {\r\n if (child != null) {\r\n child.destroy();\r\n _this.plurals.remove(child.model[_this.idKey]);\r\n return maybeCanceled;\r\n }\r\n }, _async.chunkSizeFrom(scope.chunk));\r\n }).then(function() {\r\n return _async.each(payload.adds, function(modelToAdd) {\r\n if (maybeCanceled) {\r\n $log.debug('pieceMeal should fall through safely');\r\n }\r\n _this.createChild(modelToAdd, _this.gMap);\r\n return maybeCanceled;\r\n }, _async.chunkSizeFrom(scope.chunk)).then(function() {\r\n return _this.maybeFit();\r\n });\r\n });\r\n };\r\n })(this));\r\n } else {\r\n this.inProgress = false;\r\n return this.rebuildAll(this.scope, true, true);\r\n }\r\n };\r\n\r\n BasePolysParentModel.prototype.createChild = function(model, gMap) {\r\n var child, childScope;\r\n childScope = this.scope.$new(false);\r\n this.setChildScope(IPoly.scopeKeys, childScope, model);\r\n childScope.$watch('model', (function(_this) {\r\n return function(newValue, oldValue) {\r\n if (newValue !== oldValue) {\r\n return _this.setChildScope(childScope, newValue);\r\n }\r\n };\r\n })(this), true);\r\n childScope[\"static\"] = this.scope[\"static\"];\r\n child = new PolyChildModel(childScope, this.attrs, gMap, this.defaults, model, (function(_this) {\r\n return function() {\r\n return _this.maybeFit();\r\n };\r\n })(this));\r\n if (model[this.idKey] == null) {\r\n this.$log.error(gObjectName + \" model has no id to assign a child to.\\nThis is required for performance. Please assign id,\\nor redirect id to a different key.\");\r\n return;\r\n }\r\n this.plurals.put(model[this.idKey], child);\r\n return child;\r\n };\r\n\r\n BasePolysParentModel.prototype.maybeFit = function(pathPoints) {\r\n if (pathPoints == null) {\r\n pathPoints = this.plurals.map(function(p) {\r\n return p.pathPoints;\r\n });\r\n }\r\n if (this.scope.fit) {\r\n pathPoints = _.flatten(pathPoints);\r\n return FitHelper.fit(pathPoints, this.gMap);\r\n }\r\n };\r\n\r\n return BasePolysParentModel;\r\n\r\n })(ModelKey);\r\n };\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapCircleParentModel', [\r\n 'uiGmapLogger', '$timeout', 'uiGmapGmapUtil', 'uiGmapEventsHelper', 'uiGmapCircleOptionsBuilder', function($log, $timeout, GmapUtil, EventsHelper, Builder) {\r\n var CircleParentModel, _settingFromDirective;\r\n _settingFromDirective = function(scope, fn) {\r\n scope.settingFromDirective = true;\r\n fn();\r\n return $timeout(function() {\r\n return scope.settingFromDirective = false;\r\n });\r\n };\r\n return CircleParentModel = (function(superClass) {\r\n extend(CircleParentModel, superClass);\r\n\r\n CircleParentModel.include(GmapUtil);\r\n\r\n CircleParentModel.include(EventsHelper);\r\n\r\n function CircleParentModel(scope, element, attrs, map, DEFAULTS) {\r\n var clean, gObject, lastRadius;\r\n this.attrs = attrs;\r\n this.map = map;\r\n this.DEFAULTS = DEFAULTS;\r\n this.scope = scope;\r\n lastRadius = null;\r\n clean = (function(_this) {\r\n return function() {\r\n lastRadius = null;\r\n if (_this.listeners != null) {\r\n _this.removeEvents(_this.listeners);\r\n return _this.listeners = void 0;\r\n }\r\n };\r\n })(this);\r\n gObject = new google.maps.Circle(this.buildOpts(GmapUtil.getCoords(scope.center), scope.radius));\r\n this.setMyOptions = (function(_this) {\r\n return function(newVals, oldVals) {\r\n if (scope.settingFromDirective) {\r\n return;\r\n }\r\n if (!_.isEqual(newVals, oldVals)) {\r\n return gObject.setOptions(_this.buildOpts(GmapUtil.getCoords(scope.center), scope.radius));\r\n }\r\n };\r\n })(this);\r\n this.props = this.props.concat([\r\n {\r\n prop: 'center',\r\n isColl: true\r\n }, {\r\n prop: 'fill',\r\n isColl: true\r\n }, 'radius', 'zIndex'\r\n ]);\r\n this.watchProps();\r\n if (this.scope.control != null) {\r\n this.scope.control.getCircle = function() {\r\n return gObject;\r\n };\r\n }\r\n clean();\r\n this.listeners = this.setEvents(gObject, scope, scope, ['radius_changed']) || [];\r\n this.listeners.push(google.maps.event.addListener(gObject, 'radius_changed', function() {\r\n\r\n /*\r\n possible google bug, and or because a circle has two radii\r\n radius_changed appears to fire twice (original and new) which is not too helpful\r\n therefore we will check for radius changes manually and bail out if nothing has changed\r\n */\r\n var newRadius, work;\r\n newRadius = gObject.getRadius();\r\n if (newRadius === lastRadius) {\r\n return;\r\n }\r\n lastRadius = newRadius;\r\n work = function() {\r\n return _settingFromDirective(scope, function() {\r\n var ref, ref1;\r\n if (newRadius !== scope.radius) {\r\n scope.radius = newRadius;\r\n }\r\n if (((ref = scope.events) != null ? ref.radius_changed : void 0) && _.isFunction((ref1 = scope.events) != null ? ref1.radius_changed : void 0)) {\r\n return scope.events.radius_changed(gObject, 'radius_changed', scope, arguments);\r\n }\r\n });\r\n };\r\n if (!angular.mock) {\r\n return scope.$evalAsync(function() {\r\n return work();\r\n });\r\n } else {\r\n return work();\r\n }\r\n }));\r\n this.listeners.push(google.maps.event.addListener(gObject, 'center_changed', function() {\r\n return scope.$evalAsync(function() {\r\n return _settingFromDirective(scope, function() {\r\n if (angular.isDefined(scope.center.type)) {\r\n scope.center.coordinates[1] = gObject.getCenter().lat();\r\n return scope.center.coordinates[0] = gObject.getCenter().lng();\r\n } else {\r\n scope.center.latitude = gObject.getCenter().lat();\r\n return scope.center.longitude = gObject.getCenter().lng();\r\n }\r\n });\r\n });\r\n }));\r\n scope.$on('$destroy', (function(_this) {\r\n return function() {\r\n clean();\r\n return gObject.setMap(null);\r\n };\r\n })(this));\r\n $log.info(this);\r\n }\r\n\r\n return CircleParentModel;\r\n\r\n })(Builder);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapDrawingManagerParentModel', [\r\n 'uiGmapLogger', '$timeout', 'uiGmapBaseObject', 'uiGmapEventsHelper', function($log, $timeout, BaseObject, EventsHelper) {\r\n var DrawingManagerParentModel;\r\n return DrawingManagerParentModel = (function(superClass) {\r\n extend(DrawingManagerParentModel, superClass);\r\n\r\n DrawingManagerParentModel.include(EventsHelper);\r\n\r\n function DrawingManagerParentModel(scope, element, attrs, map) {\r\n var gObject, listeners;\r\n this.scope = scope;\r\n this.attrs = attrs;\r\n this.map = map;\r\n gObject = new google.maps.drawing.DrawingManager(this.scope.options);\r\n gObject.setMap(this.map);\r\n listeners = void 0;\r\n if (this.scope.control != null) {\r\n this.scope.control.getDrawingManager = function() {\r\n return gObject;\r\n };\r\n }\r\n if (!this.scope[\"static\"] && this.scope.options) {\r\n this.scope.$watch('options', function(newValue) {\r\n return gObject != null ? gObject.setOptions(newValue) : void 0;\r\n }, true);\r\n }\r\n if (this.scope.events != null) {\r\n listeners = this.setEvents(gObject, this.scope, this.scope);\r\n this.scope.$watch('events', (function(_this) {\r\n return function(newValue, oldValue) {\r\n if (!_.isEqual(newValue, oldValue)) {\r\n if (listeners != null) {\r\n _this.removeEvents(listeners);\r\n }\r\n return listeners = _this.setEvents(gObject, _this.scope, _this.scope);\r\n }\r\n };\r\n })(this));\r\n }\r\n this.scope.$on('$destroy', (function(_this) {\r\n return function() {\r\n if (listeners != null) {\r\n _this.removeEvents(listeners);\r\n }\r\n gObject.setMap(null);\r\n return gObject = null;\r\n };\r\n })(this));\r\n }\r\n\r\n return DrawingManagerParentModel;\r\n\r\n })(BaseObject);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;\r\n/*\r\n\t- interface for all markers to derrive from\r\n \t- to enforce a minimum set of requirements\r\n \t\t- attributes\r\n \t\t\t- coords\r\n \t\t\t- icon\r\n\t\t- implementation needed on watches\r\n */\r\n\r\n(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },\r\n extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module(\"uiGmapgoogle-maps.directives.api.models.parent\").factory(\"uiGmapIMarkerParentModel\", [\r\n \"uiGmapModelKey\", \"uiGmapLogger\", function(ModelKey, Logger) {\r\n var IMarkerParentModel;\r\n IMarkerParentModel = (function(superClass) {\r\n extend(IMarkerParentModel, superClass);\r\n\r\n IMarkerParentModel.prototype.DEFAULTS = {};\r\n\r\n function IMarkerParentModel(scope1, element, attrs, map) {\r\n this.scope = scope1;\r\n this.element = element;\r\n this.attrs = attrs;\r\n this.map = map;\r\n this.onWatch = bind(this.onWatch, this);\r\n this.watch = bind(this.watch, this);\r\n this.validateScope = bind(this.validateScope, this);\r\n IMarkerParentModel.__super__.constructor.call(this, this.scope);\r\n this.$log = Logger;\r\n if (!this.validateScope(this.scope)) {\r\n throw new String(\"Unable to construct IMarkerParentModel due to invalid scope\");\r\n }\r\n this.doClick = angular.isDefined(this.attrs.click);\r\n if (this.scope.options != null) {\r\n this.DEFAULTS = this.scope.options;\r\n }\r\n this.watch('coords', this.scope);\r\n this.watch('icon', this.scope);\r\n this.watch('options', this.scope);\r\n this.scope.$on(\"$destroy\", (function(_this) {\r\n return function() {\r\n return _this.onDestroy(_this.scope);\r\n };\r\n })(this));\r\n }\r\n\r\n IMarkerParentModel.prototype.validateScope = function(scope) {\r\n var ret;\r\n if (scope == null) {\r\n this.$log.error(this.constructor.name + \": invalid scope used\");\r\n return false;\r\n }\r\n ret = scope.coords != null;\r\n if (!ret) {\r\n this.$log.error(this.constructor.name + \": no valid coords attribute found\");\r\n return false;\r\n }\r\n return ret;\r\n };\r\n\r\n IMarkerParentModel.prototype.watch = function(propNameToWatch, scope, equalityCheck) {\r\n if (equalityCheck == null) {\r\n equalityCheck = true;\r\n }\r\n return scope.$watch(propNameToWatch, (function(_this) {\r\n return function(newValue, oldValue) {\r\n if (!_.isEqual(newValue, oldValue)) {\r\n return _this.onWatch(propNameToWatch, scope, newValue, oldValue);\r\n }\r\n };\r\n })(this), equalityCheck);\r\n };\r\n\r\n IMarkerParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) {};\r\n\r\n return IMarkerParentModel;\r\n\r\n })(ModelKey);\r\n return IMarkerParentModel;\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module(\"uiGmapgoogle-maps.directives.api.models.parent\").factory(\"uiGmapIWindowParentModel\", [\r\n \"uiGmapModelKey\", \"uiGmapGmapUtil\", \"uiGmapLogger\", function(ModelKey, GmapUtil, Logger) {\r\n var IWindowParentModel;\r\n return IWindowParentModel = (function(superClass) {\r\n extend(IWindowParentModel, superClass);\r\n\r\n IWindowParentModel.include(GmapUtil);\r\n\r\n function IWindowParentModel(scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache) {\r\n IWindowParentModel.__super__.constructor.call(this, scope);\r\n this.$log = Logger;\r\n this.$timeout = $timeout;\r\n this.$compile = $compile;\r\n this.$http = $http;\r\n this.$templateCache = $templateCache;\r\n this.DEFAULTS = {};\r\n if (scope.options != null) {\r\n this.DEFAULTS = scope.options;\r\n }\r\n }\r\n\r\n IWindowParentModel.prototype.getItem = function(scope, modelsPropToIterate, index) {\r\n if (modelsPropToIterate === 'models') {\r\n return scope[modelsPropToIterate][index];\r\n }\r\n return scope[modelsPropToIterate].get(index);\r\n };\r\n\r\n return IWindowParentModel;\r\n\r\n })(ModelKey);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },\r\n extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapLayerParentModel', [\r\n 'uiGmapBaseObject', 'uiGmapLogger', '$timeout', function(BaseObject, Logger, $timeout) {\r\n var LayerParentModel;\r\n LayerParentModel = (function(superClass) {\r\n extend(LayerParentModel, superClass);\r\n\r\n function LayerParentModel(scope, element, attrs, gMap, onLayerCreated, $log) {\r\n this.scope = scope;\r\n this.element = element;\r\n this.attrs = attrs;\r\n this.gMap = gMap;\r\n this.onLayerCreated = onLayerCreated != null ? onLayerCreated : void 0;\r\n this.$log = $log != null ? $log : Logger;\r\n this.createGoogleLayer = bind(this.createGoogleLayer, this);\r\n if (this.attrs.type == null) {\r\n this.$log.info('type attribute for the layer directive is mandatory. Layer creation aborted!!');\r\n return;\r\n }\r\n this.createGoogleLayer();\r\n this.doShow = true;\r\n if (angular.isDefined(this.attrs.show)) {\r\n this.doShow = this.scope.show;\r\n }\r\n if (this.doShow && (this.gMap != null)) {\r\n this.gObject.setMap(this.gMap);\r\n }\r\n this.scope.$watch('show', (function(_this) {\r\n return function(newValue, oldValue) {\r\n if (newValue !== oldValue) {\r\n _this.doShow = newValue;\r\n if (newValue) {\r\n return _this.gObject.setMap(_this.gMap);\r\n } else {\r\n return _this.gObject.setMap(null);\r\n }\r\n }\r\n };\r\n })(this), true);\r\n this.scope.$watch('options', (function(_this) {\r\n return function(newValue, oldValue) {\r\n if (newValue !== oldValue && _this.doShow) {\r\n return _this.gObject.setOptions(newValue);\r\n }\r\n };\r\n })(this), true);\r\n this.scope.$on('$destroy', (function(_this) {\r\n return function() {\r\n return _this.gObject.setMap(null);\r\n };\r\n })(this));\r\n }\r\n\r\n LayerParentModel.prototype.createGoogleLayer = function() {\r\n var base;\r\n if (this.attrs.options == null) {\r\n this.gObject = this.attrs.namespace === void 0 ? new google.maps[this.attrs.type]() : new google.maps[this.attrs.namespace][this.attrs.type]();\r\n } else {\r\n this.gObject = this.attrs.namespace === void 0 ? new google.maps[this.attrs.type](this.scope.options) : new google.maps[this.attrs.namespace][this.attrs.type](this.scope.options);\r\n }\r\n if ((this.gObject != null) && this.doShow) {\r\n this.gObject.setMap(this.gMap);\r\n }\r\n if ((this.gObject != null) && (this.onLayerCreated != null)) {\r\n return typeof (base = this.onLayerCreated(this.scope, this.gObject)) === \"function\" ? base(this.gObject) : void 0;\r\n }\r\n };\r\n\r\n return LayerParentModel;\r\n\r\n })(BaseObject);\r\n return LayerParentModel;\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },\r\n extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapMapTypeParentModel', [\r\n 'uiGmapBaseObject', 'uiGmapLogger', function(BaseObject, Logger) {\r\n var MapTypeParentModel;\r\n MapTypeParentModel = (function(superClass) {\r\n extend(MapTypeParentModel, superClass);\r\n\r\n function MapTypeParentModel(scope, element, attrs, gMap, $log) {\r\n this.scope = scope;\r\n this.element = element;\r\n this.attrs = attrs;\r\n this.gMap = gMap;\r\n this.$log = $log != null ? $log : Logger;\r\n this.hideOverlay = bind(this.hideOverlay, this);\r\n this.showOverlay = bind(this.showOverlay, this);\r\n this.refreshMapType = bind(this.refreshMapType, this);\r\n this.createMapType = bind(this.createMapType, this);\r\n if (this.attrs.options == null) {\r\n this.$log.info('options attribute for the map-type directive is mandatory. Map type creation aborted!!');\r\n return;\r\n }\r\n this.id = this.gMap.overlayMapTypesCount = this.gMap.overlayMapTypesCount + 1 || 0;\r\n this.doShow = true;\r\n this.createMapType();\r\n if (angular.isDefined(this.attrs.show)) {\r\n this.doShow = this.scope.show;\r\n }\r\n if (this.doShow && (this.gMap != null)) {\r\n this.showOverlay();\r\n }\r\n this.scope.$watch('show', (function(_this) {\r\n return function(newValue, oldValue) {\r\n if (newValue !== oldValue) {\r\n _this.doShow = newValue;\r\n if (newValue) {\r\n return _this.showOverlay();\r\n } else {\r\n return _this.hideOverlay();\r\n }\r\n }\r\n };\r\n })(this), true);\r\n this.scope.$watch('options', (function(_this) {\r\n return function(newValue, oldValue) {\r\n if (!_.isEqual(newValue, oldValue)) {\r\n return _this.refreshMapType();\r\n }\r\n };\r\n })(this), true);\r\n if (angular.isDefined(this.attrs.refresh)) {\r\n this.scope.$watch('refresh', (function(_this) {\r\n return function(newValue, oldValue) {\r\n if (!_.isEqual(newValue, oldValue)) {\r\n return _this.refreshMapType();\r\n }\r\n };\r\n })(this), true);\r\n }\r\n this.scope.$on('$destroy', (function(_this) {\r\n return function() {\r\n _this.hideOverlay();\r\n return _this.mapType = null;\r\n };\r\n })(this));\r\n }\r\n\r\n MapTypeParentModel.prototype.createMapType = function() {\r\n if (this.scope.options.getTile != null) {\r\n this.mapType = this.scope.options;\r\n } else if (this.scope.options.getTileUrl != null) {\r\n this.mapType = new google.maps.ImageMapType(this.scope.options);\r\n } else {\r\n this.$log.info('options should provide either getTile or getTileUrl methods. Map type creation aborted!!');\r\n return;\r\n }\r\n if (this.attrs.id && this.scope.id) {\r\n this.gMap.mapTypes.set(this.scope.id, this.mapType);\r\n if (!angular.isDefined(this.attrs.show)) {\r\n this.doShow = false;\r\n }\r\n }\r\n return this.mapType.layerId = this.id;\r\n };\r\n\r\n MapTypeParentModel.prototype.refreshMapType = function() {\r\n this.hideOverlay();\r\n this.mapType = null;\r\n this.createMapType();\r\n if (this.doShow && (this.gMap != null)) {\r\n return this.showOverlay();\r\n }\r\n };\r\n\r\n MapTypeParentModel.prototype.showOverlay = function() {\r\n return this.gMap.overlayMapTypes.push(this.mapType);\r\n };\r\n\r\n MapTypeParentModel.prototype.hideOverlay = function() {\r\n var found;\r\n found = false;\r\n return this.gMap.overlayMapTypes.forEach((function(_this) {\r\n return function(mapType, index) {\r\n if (!found && mapType.layerId === _this.id) {\r\n found = true;\r\n _this.gMap.overlayMapTypes.removeAt(index);\r\n }\r\n };\r\n })(this));\r\n };\r\n\r\n return MapTypeParentModel;\r\n\r\n })(BaseObject);\r\n return MapTypeParentModel;\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },\r\n extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module(\"uiGmapgoogle-maps.directives.api.models.parent\").factory(\"uiGmapMarkersParentModel\", [\r\n \"uiGmapIMarkerParentModel\", \"uiGmapModelsWatcher\", \"uiGmapPropMap\", \"uiGmapMarkerChildModel\", \"uiGmap_async\", \"uiGmapClustererMarkerManager\", \"uiGmapMarkerManager\", \"$timeout\", \"uiGmapIMarker\", \"uiGmapPromise\", \"uiGmapGmapUtil\", \"uiGmapLogger\", \"uiGmapSpiderfierMarkerManager\", function(IMarkerParentModel, ModelsWatcher, PropMap, MarkerChildModel, _async, ClustererMarkerManager, MarkerManager, $timeout, IMarker, uiGmapPromise, GmapUtil, $log, SpiderfierMarkerManager) {\r\n var MarkersParentModel, _setPlurals;\r\n _setPlurals = function(val, objToSet) {\r\n objToSet.plurals = new PropMap();\r\n objToSet.scope.plurals = objToSet.plurals;\r\n return objToSet;\r\n };\r\n MarkersParentModel = (function(superClass) {\r\n extend(MarkersParentModel, superClass);\r\n\r\n MarkersParentModel.include(GmapUtil);\r\n\r\n MarkersParentModel.include(ModelsWatcher);\r\n\r\n function MarkersParentModel(scope, element, attrs, map) {\r\n this.maybeExecMappedEvent = bind(this.maybeExecMappedEvent, this);\r\n this.onDestroy = bind(this.onDestroy, this);\r\n this.newChildMarker = bind(this.newChildMarker, this);\r\n this.pieceMeal = bind(this.pieceMeal, this);\r\n this.rebuildAll = bind(this.rebuildAll, this);\r\n this.createAllNew = bind(this.createAllNew, this);\r\n this.bindToTypeEvents = bind(this.bindToTypeEvents, this);\r\n this.createChildScopes = bind(this.createChildScopes, this);\r\n this.validateScope = bind(this.validateScope, this);\r\n this.onWatch = bind(this.onWatch, this);\r\n var self;\r\n MarkersParentModel.__super__.constructor.call(this, scope, element, attrs, map);\r\n this[\"interface\"] = IMarker;\r\n self = this;\r\n _setPlurals(new PropMap(), this);\r\n this.scope.pluralsUpdate = {\r\n updateCtr: 0\r\n };\r\n this.$log.info(this);\r\n this.doRebuildAll = this.scope.doRebuildAll != null ? this.scope.doRebuildAll : false;\r\n this.setIdKey(this.scope);\r\n this.scope.$watch('doRebuildAll', (function(_this) {\r\n return function(newValue, oldValue) {\r\n if (newValue !== oldValue) {\r\n return _this.doRebuildAll = newValue;\r\n }\r\n };\r\n })(this));\r\n if (!this.modelsLength()) {\r\n this.modelsRendered = false;\r\n }\r\n this.scope.$watch('models', (function(_this) {\r\n return function(newValue, oldValue) {\r\n if (!_.isEqual(newValue, oldValue) || !_this.modelsRendered) {\r\n if (newValue.length === 0 && oldValue.length === 0) {\r\n return;\r\n }\r\n _this.modelsRendered = true;\r\n return _this.onWatch('models', _this.scope, newValue, oldValue);\r\n }\r\n };\r\n })(this), !this.isTrue(attrs.modelsbyref));\r\n this.watch('doCluster', this.scope);\r\n this.watch('type', this.scope);\r\n this.watch('clusterOptions', this.scope);\r\n this.watch('clusterEvents', this.scope);\r\n this.watch('typeOptions', this.scope);\r\n this.watch('typeEvents', this.scope);\r\n this.watch('fit', this.scope);\r\n this.watch('idKey', this.scope);\r\n this.gManager = void 0;\r\n this.createAllNew(this.scope);\r\n }\r\n\r\n MarkersParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) {\r\n if (propNameToWatch === \"idKey\" && newValue !== oldValue) {\r\n this.idKey = newValue;\r\n }\r\n if (this.doRebuildAll || (propNameToWatch === 'doCluster' || propNameToWatch === 'type')) {\r\n return this.rebuildAll(scope);\r\n } else {\r\n return this.pieceMeal(scope);\r\n }\r\n };\r\n\r\n MarkersParentModel.prototype.validateScope = function(scope) {\r\n var modelsNotDefined;\r\n modelsNotDefined = angular.isUndefined(scope.models) || scope.models === void 0;\r\n if (modelsNotDefined) {\r\n this.$log.error(this.constructor.name + \": no valid models attribute found\");\r\n }\r\n return MarkersParentModel.__super__.validateScope.call(this, scope) || modelsNotDefined;\r\n };\r\n\r\n\r\n /*\r\n Not used internally by this parent\r\n created for consistency for external control in the API\r\n */\r\n\r\n MarkersParentModel.prototype.createChildScopes = function(isCreatingFromScratch) {\r\n if ((this.gMap == null) || (this.scope.models == null)) {\r\n return;\r\n }\r\n if (isCreatingFromScratch) {\r\n return this.createAllNew(this.scope, false);\r\n } else {\r\n return this.pieceMeal(this.scope, false);\r\n }\r\n };\r\n\r\n MarkersParentModel.prototype.bindToTypeEvents = function(typeEvents, events) {\r\n var internalHandles, self;\r\n if (events == null) {\r\n events = ['click', 'mouseout', 'mouseover'];\r\n }\r\n\r\n /*\r\n You should only be binding to events that produce groups/clusters of somthing.\r\n Otherwise use the orginal event handle.\r\n For Example: Click on a cluster pushes a cluster/group obj through which has getMarkers\r\n However Spiderfy's click is for a single marker so this is not ideal for that.\r\n */\r\n self = this;\r\n if (!this.origTypeEvents) {\r\n this.origTypeEvents = {};\r\n _.each(events, (function(_this) {\r\n return function(eventName) {\r\n return _this.origTypeEvents[eventName] = typeEvents != null ? typeEvents[eventName] : void 0;\r\n };\r\n })(this));\r\n } else {\r\n angular.extend(typeEvents, this.origTypeEvents);\r\n }\r\n internalHandles = {};\r\n _.each(events, (function(_this) {\r\n return function(eventName) {\r\n return internalHandles[eventName] = function(group) {\r\n return self.maybeExecMappedEvent(group, eventName);\r\n };\r\n };\r\n })(this));\r\n return angular.extend(typeEvents, internalHandles);\r\n };\r\n\r\n MarkersParentModel.prototype.createAllNew = function(scope) {\r\n var isSpiderfied, maybeCanceled, typeEvents, typeOptions;\r\n if (this.gManager != null) {\r\n if (this.gManager instanceof SpiderfierMarkerManager) {\r\n isSpiderfied = this.gManager.isSpiderfied();\r\n }\r\n this.gManager.clear();\r\n delete this.gManager;\r\n }\r\n typeEvents = scope.typeEvents || scope.clusterEvents;\r\n typeOptions = scope.typeOptions || scope.clusterOptions;\r\n if (scope.doCluster || scope.type === 'cluster') {\r\n if (typeEvents != null) {\r\n this.bindToTypeEvents(typeEvents);\r\n }\r\n this.gManager = new ClustererMarkerManager(this.map, void 0, typeOptions, typeEvents);\r\n } else if (scope.type === 'spider') {\r\n if (typeEvents != null) {\r\n this.bindToTypeEvents(typeEvents, ['spiderfy', 'unspiderfy']);\r\n }\r\n this.gManager = new SpiderfierMarkerManager(this.map, void 0, typeOptions, typeEvents, this.scope);\r\n if (isSpiderfied) {\r\n this.gManager.spiderfy();\r\n }\r\n } else {\r\n this.gManager = new MarkerManager(this.map);\r\n }\r\n if (this.didQueueInitPromise(this, scope)) {\r\n return;\r\n }\r\n maybeCanceled = null;\r\n return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) {\r\n return maybeCanceled = canceledMsg;\r\n }), (function(_this) {\r\n return function() {\r\n return _async.each(scope.models, function(model) {\r\n _this.newChildMarker(model, scope);\r\n return maybeCanceled;\r\n }, _async.chunkSizeFrom(scope.chunk)).then(function() {\r\n _this.modelsRendered = true;\r\n if (scope.fit) {\r\n _this.gManager.fit();\r\n }\r\n _this.gManager.draw();\r\n return _this.scope.pluralsUpdate.updateCtr += 1;\r\n }, _async.chunkSizeFrom(scope.chunk));\r\n };\r\n })(this));\r\n };\r\n\r\n MarkersParentModel.prototype.rebuildAll = function(scope) {\r\n var ref;\r\n if (!scope.doRebuild && scope.doRebuild !== void 0) {\r\n return;\r\n }\r\n if ((ref = this.scope.plurals) != null ? ref.length : void 0) {\r\n return this.onDestroy(scope).then((function(_this) {\r\n return function() {\r\n return _this.createAllNew(scope);\r\n };\r\n })(this));\r\n } else {\r\n return this.createAllNew(scope);\r\n }\r\n };\r\n\r\n MarkersParentModel.prototype.pieceMeal = function(scope) {\r\n var maybeCanceled, payload;\r\n if (scope.$$destroyed) {\r\n return;\r\n }\r\n maybeCanceled = null;\r\n payload = null;\r\n if (this.modelsLength() && this.scope.plurals.length) {\r\n return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) {\r\n return maybeCanceled = canceledMsg;\r\n }), (function(_this) {\r\n return function() {\r\n return uiGmapPromise.promise((function() {\r\n return _this.figureOutState(_this.idKey, scope, _this.scope.plurals, _this.modelKeyComparison);\r\n })).then(function(state) {\r\n payload = state;\r\n return _async.each(payload.removals, function(child) {\r\n if (child != null) {\r\n if (child.destroy != null) {\r\n child.destroy();\r\n }\r\n _this.scope.plurals.remove(child.id);\r\n return maybeCanceled;\r\n }\r\n }, _async.chunkSizeFrom(scope.chunk));\r\n }).then(function() {\r\n return _async.each(payload.adds, function(modelToAdd) {\r\n _this.newChildMarker(modelToAdd, scope);\r\n return maybeCanceled;\r\n }, _async.chunkSizeFrom(scope.chunk));\r\n }).then(function() {\r\n return _async.each(payload.updates, function(update) {\r\n _this.updateChild(update.child, update.model);\r\n return maybeCanceled;\r\n }, _async.chunkSizeFrom(scope.chunk));\r\n }).then(function() {\r\n if (payload.adds.length > 0 || payload.removals.length > 0 || payload.updates.length > 0) {\r\n scope.plurals = _this.scope.plurals;\r\n if (scope.fit) {\r\n _this.gManager.fit();\r\n }\r\n _this.gManager.draw();\r\n }\r\n return _this.scope.pluralsUpdate.updateCtr += 1;\r\n });\r\n };\r\n })(this));\r\n } else {\r\n this.inProgress = false;\r\n return this.rebuildAll(scope);\r\n }\r\n };\r\n\r\n MarkersParentModel.prototype.newChildMarker = function(model, scope) {\r\n var child, childScope, doDrawSelf, keys;\r\n if (model[this.idKey] == null) {\r\n this.$log.error(\"Marker model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key.\");\r\n return;\r\n }\r\n this.$log.info('child', child, 'markers', this.scope.markerModels);\r\n childScope = scope.$new(false);\r\n childScope.events = scope.events;\r\n keys = {};\r\n IMarker.scopeKeys.forEach(function(k) {\r\n return keys[k] = scope[k];\r\n });\r\n child = new MarkerChildModel(childScope, model, keys, this.map, this.DEFAULTS, this.doClick, this.gManager, doDrawSelf = false);\r\n this.scope.plurals.put(model[this.idKey], child);\r\n return child;\r\n };\r\n\r\n MarkersParentModel.prototype.onDestroy = function(scope) {\r\n MarkersParentModel.__super__.onDestroy.call(this, scope);\r\n return _async.promiseLock(this, uiGmapPromise.promiseTypes[\"delete\"], void 0, void 0, (function(_this) {\r\n return function() {\r\n return _async.each(_this.scope.plurals.values(), function(model) {\r\n if (model != null) {\r\n return model.destroy(false);\r\n }\r\n }, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() {\r\n if (_this.gManager != null) {\r\n _this.gManager.destroy();\r\n }\r\n _this.plurals.removeAll();\r\n if (_this.plurals !== _this.scope.plurals) {\r\n console.error('plurals out of sync for MarkersParentModel');\r\n }\r\n return _this.scope.pluralsUpdate.updateCtr += 1;\r\n });\r\n };\r\n })(this));\r\n };\r\n\r\n MarkersParentModel.prototype.maybeExecMappedEvent = function(group, fnName) {\r\n var pair, typeEvents;\r\n if (this.scope.$$destroyed) {\r\n return;\r\n }\r\n typeEvents = this.scope.typeEvents || this.scope.clusterEvents;\r\n if (_.isFunction(typeEvents != null ? typeEvents[fnName] : void 0)) {\r\n pair = this.mapTypeToPlurals(group);\r\n if (this.origTypeEvents[fnName]) {\r\n return this.origTypeEvents[fnName](pair.group, pair.mapped);\r\n }\r\n }\r\n };\r\n\r\n MarkersParentModel.prototype.mapTypeToPlurals = function(group) {\r\n var arrayToMap, mapped, ref;\r\n if (_.isArray(group)) {\r\n arrayToMap = group;\r\n } else if (_.isFunction(group.getMarkers)) {\r\n arrayToMap = group.getMarkers();\r\n }\r\n if (arrayToMap == null) {\r\n $log.error(\"Unable to map event as we cannot find the array group to map\");\r\n return;\r\n }\r\n if ((ref = this.scope.plurals.values()) != null ? ref.length : void 0) {\r\n mapped = arrayToMap.map((function(_this) {\r\n return function(g) {\r\n return _this.scope.plurals.get(g.key).model;\r\n };\r\n })(this));\r\n } else {\r\n mapped = [];\r\n }\r\n return {\r\n cluster: group,\r\n mapped: mapped,\r\n group: group\r\n };\r\n };\r\n\r\n MarkersParentModel.prototype.getItem = function(scope, modelsPropToIterate, index) {\r\n if (modelsPropToIterate === 'models') {\r\n return scope[modelsPropToIterate][index];\r\n }\r\n return scope[modelsPropToIterate].get(index);\r\n };\r\n\r\n return MarkersParentModel;\r\n\r\n })(IMarkerParentModel);\r\n return MarkersParentModel;\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n ['Polygon', 'Polyline'].forEach(function(name) {\r\n return angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory(\"uiGmap\" + name + \"sParentModel\", [\r\n 'uiGmapBasePolysParentModel', \"uiGmap\" + name + \"ChildModel\", \"uiGmapI\" + name, function(BasePolysParentModel, ChildModel, IPoly) {\r\n return BasePolysParentModel(IPoly, ChildModel, name);\r\n }\r\n ]);\r\n });\r\n\r\n}).call(this);\r\n;(function() {\r\n var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapRectangleParentModel', [\r\n 'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapEventsHelper', 'uiGmapRectangleOptionsBuilder', function($log, GmapUtil, EventsHelper, Builder) {\r\n var RectangleParentModel;\r\n return RectangleParentModel = (function(superClass) {\r\n extend(RectangleParentModel, superClass);\r\n\r\n RectangleParentModel.include(GmapUtil);\r\n\r\n RectangleParentModel.include(EventsHelper);\r\n\r\n function RectangleParentModel(scope, element, attrs, map, DEFAULTS) {\r\n var bounds, clear, createBounds, dragging, fit, gObject, init, listeners, myListeners, settingBoundsFromScope, updateBounds;\r\n this.scope = scope;\r\n this.attrs = attrs;\r\n this.map = map;\r\n this.DEFAULTS = DEFAULTS;\r\n bounds = void 0;\r\n dragging = false;\r\n myListeners = [];\r\n listeners = void 0;\r\n fit = (function(_this) {\r\n return function() {\r\n if (_this.isTrue(_this.attrs.fit)) {\r\n return _this.fitMapBounds(_this.map, bounds);\r\n }\r\n };\r\n })(this);\r\n createBounds = (function(_this) {\r\n return function() {\r\n var ref, ref1, ref2;\r\n if ((_this.scope.bounds != null) && (((ref = _this.scope.bounds) != null ? ref.sw : void 0) != null) && (((ref1 = _this.scope.bounds) != null ? ref1.ne : void 0) != null) && _this.validateBoundPoints(_this.scope.bounds)) {\r\n bounds = _this.convertBoundPoints(_this.scope.bounds);\r\n return $log.info(\"new new bounds created: \" + (JSON.stringify(bounds)));\r\n } else if ((_this.scope.bounds.getNorthEast != null) && (_this.scope.bounds.getSouthWest != null)) {\r\n return bounds = _this.scope.bounds;\r\n } else {\r\n if (_this.scope.bounds != null) {\r\n return $log.error(\"Invalid bounds for newValue: \" + (JSON.stringify((ref2 = _this.scope) != null ? ref2.bounds : void 0)));\r\n }\r\n }\r\n };\r\n })(this);\r\n createBounds();\r\n gObject = new google.maps.Rectangle(this.buildOpts(bounds));\r\n $log.info(\"gObject (rectangle) created: \" + gObject);\r\n settingBoundsFromScope = false;\r\n updateBounds = (function(_this) {\r\n return function() {\r\n var b, ne, sw;\r\n b = gObject.getBounds();\r\n ne = b.getNorthEast();\r\n sw = b.getSouthWest();\r\n if (settingBoundsFromScope) {\r\n return;\r\n }\r\n return _this.scope.$evalAsync(function(s) {\r\n if ((s.bounds != null) && (s.bounds.sw != null) && (s.bounds.ne != null)) {\r\n s.bounds.ne = {\r\n latitude: ne.lat(),\r\n longitude: ne.lng()\r\n };\r\n s.bounds.sw = {\r\n latitude: sw.lat(),\r\n longitude: sw.lng()\r\n };\r\n }\r\n if ((s.bounds.getNorthEast != null) && (s.bounds.getSouthWest != null)) {\r\n return s.bounds = b;\r\n }\r\n });\r\n };\r\n })(this);\r\n init = (function(_this) {\r\n return function() {\r\n fit();\r\n _this.removeEvents(myListeners);\r\n myListeners.push(google.maps.event.addListener(gObject, 'dragstart', function() {\r\n return dragging = true;\r\n }));\r\n myListeners.push(google.maps.event.addListener(gObject, 'dragend', function() {\r\n dragging = false;\r\n return updateBounds();\r\n }));\r\n return myListeners.push(google.maps.event.addListener(gObject, 'bounds_changed', function() {\r\n if (dragging) {\r\n return;\r\n }\r\n return updateBounds();\r\n }));\r\n };\r\n })(this);\r\n clear = (function(_this) {\r\n return function() {\r\n _this.removeEvents(myListeners);\r\n if (listeners != null) {\r\n _this.removeEvents(listeners);\r\n }\r\n return gObject.setMap(null);\r\n };\r\n })(this);\r\n if (bounds != null) {\r\n init();\r\n }\r\n this.scope.$watch('bounds', (function(newValue, oldValue) {\r\n var isNew;\r\n if (_.isEqual(newValue, oldValue) && (bounds != null) || dragging) {\r\n return;\r\n }\r\n settingBoundsFromScope = true;\r\n if (newValue == null) {\r\n clear();\r\n return;\r\n }\r\n if (bounds == null) {\r\n isNew = true;\r\n } else {\r\n fit();\r\n }\r\n createBounds();\r\n gObject.setBounds(bounds);\r\n settingBoundsFromScope = false;\r\n if (isNew && (bounds != null)) {\r\n return init();\r\n }\r\n }), true);\r\n this.setMyOptions = (function(_this) {\r\n return function(newVals, oldVals) {\r\n if (!_.isEqual(newVals, oldVals)) {\r\n if ((bounds != null) && (newVals != null)) {\r\n return gObject.setOptions(_this.buildOpts(bounds));\r\n }\r\n }\r\n };\r\n })(this);\r\n this.props.push('bounds');\r\n this.watchProps(this.props);\r\n if (this.attrs.events != null) {\r\n listeners = this.setEvents(gObject, this.scope, this.scope);\r\n this.scope.$watch('events', (function(_this) {\r\n return function(newValue, oldValue) {\r\n if (!_.isEqual(newValue, oldValue)) {\r\n if (listeners != null) {\r\n _this.removeEvents(listeners);\r\n }\r\n return listeners = _this.setEvents(gObject, _this.scope, _this.scope);\r\n }\r\n };\r\n })(this));\r\n }\r\n this.scope.$on('$destroy', (function(_this) {\r\n return function() {\r\n return clear();\r\n };\r\n })(this));\r\n $log.info(this);\r\n }\r\n\r\n return RectangleParentModel;\r\n\r\n })(Builder);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },\r\n extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapSearchBoxParentModel', [\r\n 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapEventsHelper', '$timeout', '$http', '$templateCache', function(BaseObject, Logger, EventsHelper, $timeout, $http, $templateCache) {\r\n var SearchBoxParentModel;\r\n SearchBoxParentModel = (function(superClass) {\r\n extend(SearchBoxParentModel, superClass);\r\n\r\n SearchBoxParentModel.include(EventsHelper);\r\n\r\n function SearchBoxParentModel(scope, element, attrs, gMap, ctrlPosition, template, $log) {\r\n var controlDiv;\r\n this.scope = scope;\r\n this.element = element;\r\n this.attrs = attrs;\r\n this.gMap = gMap;\r\n this.ctrlPosition = ctrlPosition;\r\n this.template = template;\r\n this.$log = $log != null ? $log : Logger;\r\n this.setVisibility = bind(this.setVisibility, this);\r\n this.getBounds = bind(this.getBounds, this);\r\n this.setBounds = bind(this.setBounds, this);\r\n this.createSearchBox = bind(this.createSearchBox, this);\r\n this.addToParentDiv = bind(this.addToParentDiv, this);\r\n this.addAsMapControl = bind(this.addAsMapControl, this);\r\n this.init = bind(this.init, this);\r\n if (this.attrs.template == null) {\r\n this.$log.error('template attribute for the search-box directive is mandatory. Places Search Box creation aborted!!');\r\n return;\r\n }\r\n if (angular.isUndefined(this.scope.options)) {\r\n this.scope.options = {};\r\n this.scope.options.visible = true;\r\n }\r\n if (angular.isUndefined(this.scope.options.visible)) {\r\n this.scope.options.visible = true;\r\n }\r\n if (angular.isUndefined(this.scope.options.autocomplete)) {\r\n this.scope.options.autocomplete = false;\r\n }\r\n this.visible = this.scope.options.visible;\r\n this.autocomplete = this.scope.options.autocomplete;\r\n controlDiv = angular.element('
    ');\r\n controlDiv.append(this.template);\r\n this.input = controlDiv.find('input')[0];\r\n this.init();\r\n }\r\n\r\n SearchBoxParentModel.prototype.init = function() {\r\n this.createSearchBox();\r\n this.scope.$watch('options', (function(_this) {\r\n return function(newValue, oldValue) {\r\n if (angular.isObject(newValue)) {\r\n if (newValue.bounds != null) {\r\n _this.setBounds(newValue.bounds);\r\n }\r\n if (newValue.visible != null) {\r\n if (_this.visible !== newValue.visible) {\r\n return _this.setVisibility(newValue.visible);\r\n }\r\n }\r\n }\r\n };\r\n })(this), true);\r\n if (this.attrs.parentdiv != null) {\r\n this.addToParentDiv();\r\n } else {\r\n this.addAsMapControl();\r\n }\r\n if (this.autocomplete) {\r\n this.listener = google.maps.event.addListener(this.gObject, 'place_changed', (function(_this) {\r\n return function() {\r\n return _this.places = _this.gObject.getPlace();\r\n };\r\n })(this));\r\n } else {\r\n this.listener = google.maps.event.addListener(this.gObject, 'places_changed', (function(_this) {\r\n return function() {\r\n return _this.places = _this.gObject.getPlaces();\r\n };\r\n })(this));\r\n }\r\n this.listeners = this.setEvents(this.gObject, this.scope, this.scope);\r\n this.$log.info(this);\r\n return this.scope.$on('$destroy', (function(_this) {\r\n return function() {\r\n return _this.gObject = null;\r\n };\r\n })(this));\r\n };\r\n\r\n SearchBoxParentModel.prototype.addAsMapControl = function() {\r\n return this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].push(this.input);\r\n };\r\n\r\n SearchBoxParentModel.prototype.addToParentDiv = function() {\r\n this.parentDiv = angular.element(document.getElementById(this.scope.parentdiv));\r\n return this.parentDiv.append(this.input);\r\n };\r\n\r\n SearchBoxParentModel.prototype.createSearchBox = function() {\r\n if (this.autocomplete) {\r\n return this.gObject = new google.maps.places.Autocomplete(this.input, this.scope.options);\r\n } else {\r\n return this.gObject = new google.maps.places.SearchBox(this.input, this.scope.options);\r\n }\r\n };\r\n\r\n SearchBoxParentModel.prototype.setBounds = function(bounds) {\r\n if (angular.isUndefined(bounds.isEmpty)) {\r\n this.$log.error('Error: SearchBoxParentModel setBounds. Bounds not an instance of LatLngBounds.');\r\n } else {\r\n if (bounds.isEmpty() === false) {\r\n if (this.gObject != null) {\r\n return this.gObject.setBounds(bounds);\r\n }\r\n }\r\n }\r\n };\r\n\r\n SearchBoxParentModel.prototype.getBounds = function() {\r\n return this.gObject.getBounds();\r\n };\r\n\r\n SearchBoxParentModel.prototype.setVisibility = function(val) {\r\n if (this.attrs.parentdiv != null) {\r\n if (val === false) {\r\n this.parentDiv.addClass(\"ng-hide\");\r\n } else {\r\n this.parentDiv.removeClass(\"ng-hide\");\r\n }\r\n } else {\r\n if (val === false) {\r\n this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].clear();\r\n } else {\r\n this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].push(this.input);\r\n }\r\n }\r\n return this.visible = val;\r\n };\r\n\r\n return SearchBoxParentModel;\r\n\r\n })(BaseObject);\r\n return SearchBoxParentModel;\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;\r\n/*\r\n\tWindowsChildModel generator where there are many ChildModels to a parent.\r\n */\r\n\r\n(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },\r\n extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapWindowsParentModel', [\r\n 'uiGmapIWindowParentModel', 'uiGmapModelsWatcher', 'uiGmapPropMap', 'uiGmapWindowChildModel', 'uiGmapLinked', 'uiGmap_async', 'uiGmapLogger', '$timeout', '$compile', '$http', '$templateCache', '$interpolate', 'uiGmapPromise', 'uiGmapIWindow', 'uiGmapGmapUtil', function(IWindowParentModel, ModelsWatcher, PropMap, WindowChildModel, Linked, _async, $log, $timeout, $compile, $http, $templateCache, $interpolate, uiGmapPromise, IWindow, GmapUtil) {\r\n var WindowsParentModel;\r\n WindowsParentModel = (function(superClass) {\r\n extend(WindowsParentModel, superClass);\r\n\r\n WindowsParentModel.include(ModelsWatcher);\r\n\r\n function WindowsParentModel(scope, element, attrs, ctrls, gMap1, markersScope) {\r\n this.gMap = gMap1;\r\n this.markersScope = markersScope;\r\n this.modelKeyComparison = bind(this.modelKeyComparison, this);\r\n this.interpolateContent = bind(this.interpolateContent, this);\r\n this.setChildScope = bind(this.setChildScope, this);\r\n this.createWindow = bind(this.createWindow, this);\r\n this.setContentKeys = bind(this.setContentKeys, this);\r\n this.pieceMeal = bind(this.pieceMeal, this);\r\n this.createAllNew = bind(this.createAllNew, this);\r\n this.watchIdKey = bind(this.watchIdKey, this);\r\n this.createChildScopes = bind(this.createChildScopes, this);\r\n this.watchOurScope = bind(this.watchOurScope, this);\r\n this.watchDestroy = bind(this.watchDestroy, this);\r\n this.onDestroy = bind(this.onDestroy, this);\r\n this.rebuildAll = bind(this.rebuildAll, this);\r\n this.doINeedToWipe = bind(this.doINeedToWipe, this);\r\n this.watchModels = bind(this.watchModels, this);\r\n this.go = bind(this.go, this);\r\n WindowsParentModel.__super__.constructor.call(this, scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache);\r\n this[\"interface\"] = IWindow;\r\n this.plurals = new PropMap();\r\n _.each(IWindow.scopeKeys, (function(_this) {\r\n return function(name) {\r\n return _this[name + 'Key'] = void 0;\r\n };\r\n })(this));\r\n this.linked = new Linked(scope, element, attrs, ctrls);\r\n this.contentKeys = void 0;\r\n this.isIconVisibleOnClick = void 0;\r\n this.firstTime = true;\r\n this.firstWatchModels = true;\r\n this.$log.info(self);\r\n this.parentScope = void 0;\r\n this.go(scope);\r\n }\r\n\r\n WindowsParentModel.prototype.go = function(scope) {\r\n this.watchOurScope(scope);\r\n this.doRebuildAll = this.scope.doRebuildAll != null ? this.scope.doRebuildAll : false;\r\n scope.$watch('doRebuildAll', (function(_this) {\r\n return function(newValue, oldValue) {\r\n if (newValue !== oldValue) {\r\n return _this.doRebuildAll = newValue;\r\n }\r\n };\r\n })(this));\r\n return this.createChildScopes();\r\n };\r\n\r\n WindowsParentModel.prototype.watchModels = function(scope) {\r\n var itemToWatch;\r\n itemToWatch = this.markersScope != null ? 'pluralsUpdate' : 'models';\r\n return scope.$watch(itemToWatch, (function(_this) {\r\n return function(newValue, oldValue) {\r\n var doScratch;\r\n if (!_.isEqual(newValue, oldValue) || _this.firstWatchModels) {\r\n _this.firstWatchModels = false;\r\n if (_this.doRebuildAll || _this.doINeedToWipe(scope.models)) {\r\n return _this.rebuildAll(scope, true, true);\r\n } else {\r\n doScratch = _this.plurals.length === 0;\r\n if (_this.existingPieces != null) {\r\n return _.last(_this.existingPieces._content).then(function() {\r\n return _this.createChildScopes(doScratch);\r\n });\r\n } else {\r\n return _this.createChildScopes(doScratch);\r\n }\r\n }\r\n }\r\n };\r\n })(this), true);\r\n };\r\n\r\n WindowsParentModel.prototype.doINeedToWipe = function(newValue) {\r\n var newValueIsEmpty;\r\n newValueIsEmpty = newValue != null ? newValue.length === 0 : true;\r\n return this.plurals.length > 0 && newValueIsEmpty;\r\n };\r\n\r\n WindowsParentModel.prototype.rebuildAll = function(scope, doCreate, doDelete) {\r\n return this.onDestroy(doDelete).then((function(_this) {\r\n return function() {\r\n if (doCreate) {\r\n return _this.createChildScopes();\r\n }\r\n };\r\n })(this));\r\n };\r\n\r\n WindowsParentModel.prototype.onDestroy = function(scope) {\r\n WindowsParentModel.__super__.onDestroy.call(this, this.scope);\r\n return _async.promiseLock(this, uiGmapPromise.promiseTypes[\"delete\"], void 0, void 0, (function(_this) {\r\n return function() {\r\n return _async.each(_this.plurals.values(), function(child) {\r\n return child.destroy();\r\n }, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() {\r\n var ref;\r\n return (ref = _this.plurals) != null ? ref.removeAll() : void 0;\r\n });\r\n };\r\n })(this));\r\n };\r\n\r\n WindowsParentModel.prototype.watchDestroy = function(scope) {\r\n return scope.$on('$destroy', (function(_this) {\r\n return function() {\r\n _this.firstWatchModels = true;\r\n _this.firstTime = true;\r\n return _this.rebuildAll(scope, false, true);\r\n };\r\n })(this));\r\n };\r\n\r\n WindowsParentModel.prototype.watchOurScope = function(scope) {\r\n return _.each(IWindow.scopeKeys, (function(_this) {\r\n return function(name) {\r\n var nameKey;\r\n nameKey = name + 'Key';\r\n return _this[nameKey] = typeof scope[name] === 'function' ? scope[name]() : scope[name];\r\n };\r\n })(this));\r\n };\r\n\r\n WindowsParentModel.prototype.createChildScopes = function(isCreatingFromScratch) {\r\n var modelsNotDefined, ref, ref1;\r\n if (isCreatingFromScratch == null) {\r\n isCreatingFromScratch = true;\r\n }\r\n\r\n /*\r\n being that we cannot tell the difference in Key String vs. a normal value string (TemplateUrl)\r\n we will assume that all scope values are string expressions either pointing to a key (propName) or using\r\n 'self' to point the model as container/object of interest.\r\n \r\n This may force redundant information into the model, but this appears to be the most flexible approach.\r\n */\r\n this.isIconVisibleOnClick = true;\r\n if (angular.isDefined(this.linked.attrs.isiconvisibleonclick)) {\r\n this.isIconVisibleOnClick = this.linked.scope.isIconVisibleOnClick;\r\n }\r\n modelsNotDefined = angular.isUndefined(this.linked.scope.models);\r\n if (modelsNotDefined && (this.markersScope === void 0 || (((ref = this.markersScope) != null ? ref.plurals : void 0) === void 0 || ((ref1 = this.markersScope) != null ? ref1.models : void 0) === void 0))) {\r\n this.$log.error('No models to create windows from! Need direct models or models derived from markers!');\r\n return;\r\n }\r\n if (this.gMap != null) {\r\n if (this.linked.scope.models != null) {\r\n this.watchIdKey(this.linked.scope);\r\n if (isCreatingFromScratch) {\r\n return this.createAllNew(this.linked.scope, false);\r\n } else {\r\n return this.pieceMeal(this.linked.scope, false);\r\n }\r\n } else {\r\n this.parentScope = this.markersScope;\r\n this.watchIdKey(this.parentScope);\r\n if (isCreatingFromScratch) {\r\n return this.createAllNew(this.markersScope, true, 'plurals', false);\r\n } else {\r\n return this.pieceMeal(this.markersScope, true, 'plurals', false);\r\n }\r\n }\r\n }\r\n };\r\n\r\n WindowsParentModel.prototype.watchIdKey = function(scope) {\r\n this.setIdKey(scope);\r\n return scope.$watch('idKey', (function(_this) {\r\n return function(newValue, oldValue) {\r\n if (newValue !== oldValue && (newValue == null)) {\r\n _this.idKey = newValue;\r\n return _this.rebuildAll(scope, true, true);\r\n }\r\n };\r\n })(this));\r\n };\r\n\r\n WindowsParentModel.prototype.createAllNew = function(scope, hasGMarker, modelsPropToIterate, isArray) {\r\n var maybeCanceled;\r\n if (modelsPropToIterate == null) {\r\n modelsPropToIterate = 'models';\r\n }\r\n if (isArray == null) {\r\n isArray = false;\r\n }\r\n if (this.firstTime) {\r\n this.watchModels(scope);\r\n this.watchDestroy(scope);\r\n }\r\n this.setContentKeys(scope.models);\r\n if (this.didQueueInitPromise(this, scope)) {\r\n return;\r\n }\r\n maybeCanceled = null;\r\n return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) {\r\n return maybeCanceled = canceledMsg;\r\n }), (function(_this) {\r\n return function() {\r\n return _async.each(scope.models, function(model) {\r\n var gMarker, ref;\r\n gMarker = hasGMarker ? (ref = _this.getItem(scope, modelsPropToIterate, model[_this.idKey])) != null ? ref.gObject : void 0 : void 0;\r\n if (!maybeCanceled) {\r\n if (!gMarker && _this.markersScope) {\r\n $log.error('Unable to get gMarker from markersScope!');\r\n }\r\n _this.createWindow(model, gMarker, _this.gMap);\r\n }\r\n return maybeCanceled;\r\n }, _async.chunkSizeFrom(scope.chunk)).then(function() {\r\n return _this.firstTime = false;\r\n });\r\n };\r\n })(this));\r\n };\r\n\r\n WindowsParentModel.prototype.pieceMeal = function(scope, hasGMarker, modelsPropToIterate, isArray) {\r\n var maybeCanceled, payload;\r\n if (modelsPropToIterate == null) {\r\n modelsPropToIterate = 'models';\r\n }\r\n if (isArray == null) {\r\n isArray = true;\r\n }\r\n if (scope.$$destroyed) {\r\n return;\r\n }\r\n maybeCanceled = null;\r\n payload = null;\r\n if ((scope != null) && this.modelsLength() && this.plurals.length) {\r\n return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) {\r\n return maybeCanceled = canceledMsg;\r\n }), (function(_this) {\r\n return function() {\r\n return uiGmapPromise.promise((function() {\r\n return _this.figureOutState(_this.idKey, scope, _this.plurals, _this.modelKeyComparison);\r\n })).then(function(state) {\r\n payload = state;\r\n return _async.each(payload.removals, function(child) {\r\n if (child != null) {\r\n _this.plurals.remove(child.id);\r\n if (child.destroy != null) {\r\n child.destroy(true);\r\n }\r\n return maybeCanceled;\r\n }\r\n }, _async.chunkSizeFrom(scope.chunk));\r\n }).then(function() {\r\n return _async.each(payload.adds, function(modelToAdd) {\r\n var gMarker, ref;\r\n gMarker = (ref = _this.getItem(scope, modelsPropToIterate, modelToAdd[_this.idKey])) != null ? ref.gObject : void 0;\r\n if (!gMarker) {\r\n throw 'Gmarker undefined';\r\n }\r\n _this.createWindow(modelToAdd, gMarker, _this.gMap);\r\n return maybeCanceled;\r\n });\r\n }).then(function() {\r\n return _async.each(payload.updates, function(update) {\r\n _this.updateChild(update.child, update.model);\r\n return maybeCanceled;\r\n }, _async.chunkSizeFrom(scope.chunk));\r\n });\r\n };\r\n })(this));\r\n } else {\r\n $log.debug('pieceMeal: rebuildAll');\r\n return this.rebuildAll(this.scope, true, true);\r\n }\r\n };\r\n\r\n WindowsParentModel.prototype.setContentKeys = function(models) {\r\n if (this.modelsLength(models)) {\r\n return this.contentKeys = Object.keys(models[0]);\r\n }\r\n };\r\n\r\n WindowsParentModel.prototype.createWindow = function(model, gMarker, gMap) {\r\n var child, childScope, fakeElement, opts, ref, ref1;\r\n childScope = this.linked.scope.$new(false);\r\n this.setChildScope(childScope, model);\r\n childScope.$watch('model', (function(_this) {\r\n return function(newValue, oldValue) {\r\n if (newValue !== oldValue) {\r\n return _this.setChildScope(childScope, newValue);\r\n }\r\n };\r\n })(this), true);\r\n fakeElement = {\r\n html: (function(_this) {\r\n return function() {\r\n return _this.interpolateContent(_this.linked.element.html(), model);\r\n };\r\n })(this)\r\n };\r\n this.DEFAULTS = this.scopeOrModelVal(this.optionsKey, this.scope, model) || {};\r\n opts = this.createWindowOptions(gMarker, childScope, fakeElement.html(), this.DEFAULTS);\r\n child = new WindowChildModel(model, childScope, opts, this.isIconVisibleOnClick, gMap, (ref = this.markersScope) != null ? (ref1 = ref.plurals.get(model[this.idKey])) != null ? ref1.scope : void 0 : void 0, fakeElement, false, true);\r\n if (model[this.idKey] == null) {\r\n this.$log.error('Window model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key.');\r\n return;\r\n }\r\n this.plurals.put(model[this.idKey], child);\r\n return child;\r\n };\r\n\r\n WindowsParentModel.prototype.setChildScope = function(childScope, model) {\r\n _.each(IWindow.scopeKeys, (function(_this) {\r\n return function(name) {\r\n var nameKey, newValue;\r\n nameKey = name + 'Key';\r\n newValue = _this[nameKey] === 'self' ? model : model[_this[nameKey]];\r\n if (newValue !== childScope[name]) {\r\n return childScope[name] = newValue;\r\n }\r\n };\r\n })(this));\r\n return childScope.model = model;\r\n };\r\n\r\n WindowsParentModel.prototype.interpolateContent = function(content, model) {\r\n var exp, i, interpModel, key, len, ref;\r\n if (this.contentKeys === void 0 || this.contentKeys.length === 0) {\r\n return;\r\n }\r\n exp = $interpolate(content);\r\n interpModel = {};\r\n ref = this.contentKeys;\r\n for (i = 0, len = ref.length; i < len; i++) {\r\n key = ref[i];\r\n interpModel[key] = model[key];\r\n }\r\n return exp(interpModel);\r\n };\r\n\r\n WindowsParentModel.prototype.modelKeyComparison = function(model1, model2) {\r\n var isEqual, scope;\r\n scope = this.scope.coords != null ? this.scope : this.parentScope;\r\n if (scope == null) {\r\n throw 'No scope or parentScope set!';\r\n }\r\n isEqual = GmapUtil.equalCoords(this.evalModelHandle(model1, scope.coords), this.evalModelHandle(model2, scope.coords));\r\n if (!isEqual) {\r\n return isEqual;\r\n }\r\n isEqual = _.every(_.without(this[\"interface\"].scopeKeys, 'coords'), (function(_this) {\r\n return function(k) {\r\n return _this.evalModelHandle(model1, scope[k]) === _this.evalModelHandle(model2, scope[k]);\r\n };\r\n })(this));\r\n return isEqual;\r\n };\r\n\r\n return WindowsParentModel;\r\n\r\n })(IWindowParentModel);\r\n return WindowsParentModel;\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module(\"uiGmapgoogle-maps.directives.api\").factory(\"uiGmapCircle\", [\r\n \"uiGmapICircle\", \"uiGmapCircleParentModel\", function(ICircle, CircleParentModel) {\r\n return _.extend(ICircle, {\r\n link: function(scope, element, attrs, mapCtrl) {\r\n return mapCtrl.getScope().deferred.promise.then((function(_this) {\r\n return function(map) {\r\n return new CircleParentModel(scope, element, attrs, map);\r\n };\r\n })(this));\r\n }\r\n });\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },\r\n extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module(\"uiGmapgoogle-maps.directives.api\").factory(\"uiGmapControl\", [\r\n \"uiGmapIControl\", \"$http\", \"$templateCache\", \"$compile\", \"$controller\", 'uiGmapGoogleMapApi', function(IControl, $http, $templateCache, $compile, $controller, GoogleMapApi) {\r\n var Control;\r\n return Control = (function(superClass) {\r\n extend(Control, superClass);\r\n\r\n function Control() {\r\n this.link = bind(this.link, this);\r\n Control.__super__.constructor.call(this);\r\n }\r\n\r\n Control.prototype.link = function(scope, element, attrs, ctrl) {\r\n return GoogleMapApi.then((function(_this) {\r\n return function(maps) {\r\n var index, position;\r\n if (angular.isUndefined(scope.template)) {\r\n _this.$log.error('mapControl: could not find a valid template property');\r\n return;\r\n }\r\n index = angular.isDefined(scope.index && !isNaN(parseInt(scope.index))) ? parseInt(scope.index) : void 0;\r\n position = angular.isDefined(scope.position) ? scope.position.toUpperCase().replace(/-/g, '_') : 'TOP_CENTER';\r\n if (!maps.ControlPosition[position]) {\r\n _this.$log.error('mapControl: invalid position property');\r\n return;\r\n }\r\n return IControl.mapPromise(scope, ctrl).then(function(map) {\r\n var control, controlDiv;\r\n control = void 0;\r\n controlDiv = angular.element('
    ');\r\n return $http.get(scope.template, {\r\n cache: $templateCache\r\n }).success(function(template) {\r\n var templateCtrl, templateScope;\r\n templateScope = scope.$new();\r\n controlDiv.append(template);\r\n if (angular.isDefined(scope.controller)) {\r\n templateCtrl = $controller(scope.controller, {\r\n $scope: templateScope\r\n });\r\n controlDiv.children().data('$ngControllerController', templateCtrl);\r\n }\r\n control = $compile(controlDiv.children())(templateScope);\r\n if (index) {\r\n return control[0].index = index;\r\n }\r\n }).error(function(error) {\r\n return _this.$log.error('mapControl: template could not be found');\r\n }).then(function() {\r\n return map.controls[google.maps.ControlPosition[position]].push(control[0]);\r\n });\r\n });\r\n };\r\n })(this));\r\n };\r\n\r\n return Control;\r\n\r\n })(IControl);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapDragZoom', [\r\n 'uiGmapCtrlHandle', 'uiGmapPropertyAction', function(CtrlHandle, PropertyAction) {\r\n return {\r\n restrict: 'EMA',\r\n transclude: true,\r\n template: '
    ',\r\n require: '^' + 'uiGmapGoogleMap',\r\n scope: {\r\n keyboardkey: '=',\r\n options: '=',\r\n spec: '='\r\n },\r\n controller: [\r\n '$scope', '$element', function($scope, $element) {\r\n $scope.ctrlType = 'uiGmapDragZoom';\r\n return _.extend(this, CtrlHandle.handle($scope, $element));\r\n }\r\n ],\r\n link: function(scope, element, attrs, ctrl) {\r\n return CtrlHandle.mapPromise(scope, ctrl).then(function(map) {\r\n var enableKeyDragZoom, setKeyAction, setOptionsAction;\r\n enableKeyDragZoom = function(opts) {\r\n map.enableKeyDragZoom(opts);\r\n if (scope.spec) {\r\n return scope.spec.enableKeyDragZoom(opts);\r\n }\r\n };\r\n setKeyAction = new PropertyAction(function(key, newVal) {\r\n if (newVal) {\r\n return enableKeyDragZoom({\r\n key: newVal\r\n });\r\n } else {\r\n return enableKeyDragZoom();\r\n }\r\n });\r\n setOptionsAction = new PropertyAction(function(key, newVal) {\r\n if (newVal) {\r\n return enableKeyDragZoom(newVal);\r\n }\r\n });\r\n scope.$watch('keyboardkey', setKeyAction.sic);\r\n setKeyAction.sic(scope.keyboardkey);\r\n scope.$watch('options', setOptionsAction.sic);\r\n return setOptionsAction.sic(scope.options);\r\n });\r\n }\r\n };\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module(\"uiGmapgoogle-maps.directives.api\").factory(\"uiGmapDrawingManager\", [\r\n \"uiGmapIDrawingManager\", \"uiGmapDrawingManagerParentModel\", function(IDrawingManager, DrawingManagerParentModel) {\r\n return _.extend(IDrawingManager, {\r\n link: function(scope, element, attrs, mapCtrl) {\r\n return mapCtrl.getScope().deferred.promise.then(function(map) {\r\n return new DrawingManagerParentModel(scope, element, attrs, map);\r\n });\r\n }\r\n });\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;\r\n/*\r\n - Link up Polygons to be sent back to a controller\r\n - inject the draw function into a controllers scope so that controller can call the directive to draw on demand\r\n - draw function creates the DrawFreeHandChildModel which manages itself\r\n */\r\n\r\n(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },\r\n extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapApiFreeDrawPolygons', [\r\n 'uiGmapLogger', 'uiGmapBaseObject', 'uiGmapCtrlHandle', 'uiGmapDrawFreeHandChildModel', 'uiGmapLodash', function($log, BaseObject, CtrlHandle, DrawFreeHandChildModel, uiGmapLodash) {\r\n var FreeDrawPolygons;\r\n return FreeDrawPolygons = (function(superClass) {\r\n extend(FreeDrawPolygons, superClass);\r\n\r\n function FreeDrawPolygons() {\r\n this.link = bind(this.link, this);\r\n return FreeDrawPolygons.__super__.constructor.apply(this, arguments);\r\n }\r\n\r\n FreeDrawPolygons.include(CtrlHandle);\r\n\r\n FreeDrawPolygons.prototype.restrict = 'EMA';\r\n\r\n FreeDrawPolygons.prototype.replace = true;\r\n\r\n FreeDrawPolygons.prototype.require = '^' + 'uiGmapGoogleMap';\r\n\r\n FreeDrawPolygons.prototype.scope = {\r\n polygons: '=',\r\n draw: '='\r\n };\r\n\r\n FreeDrawPolygons.prototype.link = function(scope, element, attrs, ctrl) {\r\n return this.mapPromise(scope, ctrl).then((function(_this) {\r\n return function(map) {\r\n var freeHand, listener;\r\n if (!scope.polygons) {\r\n return $log.error('No polygons to bind to!');\r\n }\r\n if (!_.isArray(scope.polygons)) {\r\n return $log.error('Free Draw Polygons must be of type Array!');\r\n }\r\n freeHand = new DrawFreeHandChildModel(map, ctrl.getScope());\r\n listener = void 0;\r\n return scope.draw = function() {\r\n if (typeof listener === \"function\") {\r\n listener();\r\n }\r\n return freeHand.engage(scope.polygons).then(function() {\r\n var firstTime;\r\n firstTime = true;\r\n return listener = scope.$watchCollection('polygons', function(newValue, oldValue) {\r\n var removals;\r\n if (firstTime || newValue === oldValue) {\r\n firstTime = false;\r\n return;\r\n }\r\n removals = uiGmapLodash.differenceObjects(oldValue, newValue);\r\n return removals.forEach(function(p) {\r\n return p.setMap(null);\r\n });\r\n });\r\n });\r\n };\r\n };\r\n })(this));\r\n };\r\n\r\n return FreeDrawPolygons;\r\n\r\n })(BaseObject);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module(\"uiGmapgoogle-maps.directives.api\").service(\"uiGmapICircle\", [\r\n function() {\r\n var DEFAULTS;\r\n DEFAULTS = {};\r\n return {\r\n restrict: \"EA\",\r\n replace: true,\r\n require: '^' + 'uiGmapGoogleMap',\r\n scope: {\r\n center: \"=center\",\r\n radius: \"=radius\",\r\n stroke: \"=stroke\",\r\n fill: \"=fill\",\r\n clickable: \"=\",\r\n draggable: \"=\",\r\n editable: \"=\",\r\n geodesic: \"=\",\r\n icons: \"=icons\",\r\n visible: \"=\",\r\n events: \"=\",\r\n control: \"=\",\r\n zIndex: \"=zindex\"\r\n }\r\n };\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;\r\n/*\r\n - interface for all controls to derive from\r\n - to enforce a minimum set of requirements\r\n\t- attributes\r\n\t\t- template\r\n\t\t- position\r\n\t\t- controller\r\n\t\t- index\r\n */\r\n\r\n(function() {\r\n var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module(\"uiGmapgoogle-maps.directives.api\").factory(\"uiGmapIControl\", [\r\n \"uiGmapBaseObject\", \"uiGmapLogger\", \"uiGmapCtrlHandle\", function(BaseObject, Logger, CtrlHandle) {\r\n var IControl;\r\n return IControl = (function(superClass) {\r\n extend(IControl, superClass);\r\n\r\n IControl.extend(CtrlHandle);\r\n\r\n function IControl() {\r\n this.restrict = 'EA';\r\n this.replace = true;\r\n this.require = '^' + 'uiGmapGoogleMap';\r\n this.scope = {\r\n template: '@template',\r\n position: '@position',\r\n controller: '@controller',\r\n index: '@index'\r\n };\r\n this.$log = Logger;\r\n }\r\n\r\n IControl.prototype.link = function(scope, element, attrs, ctrl) {\r\n throw new Exception(\"Not implemented!!\");\r\n };\r\n\r\n return IControl;\r\n\r\n })(BaseObject);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapIDrawingManager', [\r\n function() {\r\n return {\r\n restrict: 'EA',\r\n replace: true,\r\n require: '^' + 'uiGmapGoogleMap',\r\n scope: {\r\n \"static\": '@',\r\n control: '=',\r\n options: '=',\r\n events: '='\r\n }\r\n };\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIMarker', [\r\n 'uiGmapBaseObject', 'uiGmapCtrlHandle', function(BaseObject, CtrlHandle) {\r\n var IMarker;\r\n return IMarker = (function(superClass) {\r\n extend(IMarker, superClass);\r\n\r\n IMarker.scope = {\r\n coords: '=coords',\r\n icon: '=icon',\r\n click: '&click',\r\n options: '=options',\r\n events: '=events',\r\n fit: '=fit',\r\n idKey: '=idkey',\r\n control: '=control'\r\n };\r\n\r\n IMarker.scopeKeys = _.keys(IMarker.scope);\r\n\r\n IMarker.keys = IMarker.scopeKeys;\r\n\r\n IMarker.extend(CtrlHandle);\r\n\r\n function IMarker() {\r\n this.restrict = 'EMA';\r\n this.require = '^' + 'uiGmapGoogleMap';\r\n this.priority = -1;\r\n this.transclude = true;\r\n this.replace = true;\r\n this.scope = _.extend(this.scope || {}, IMarker.scope);\r\n }\r\n\r\n return IMarker;\r\n\r\n })(BaseObject);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIPolygon', [\r\n 'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapCtrlHandle', function(GmapUtil, BaseObject, Logger, CtrlHandle) {\r\n var IPolygon;\r\n return IPolygon = (function(superClass) {\r\n extend(IPolygon, superClass);\r\n\r\n IPolygon.scope = {\r\n path: '=path',\r\n stroke: '=stroke',\r\n clickable: '=',\r\n draggable: '=',\r\n editable: '=',\r\n geodesic: '=',\r\n fill: '=',\r\n icons: '=icons',\r\n visible: '=',\r\n \"static\": '=',\r\n events: '=',\r\n zIndex: '=zindex',\r\n fit: '=',\r\n control: '=control'\r\n };\r\n\r\n IPolygon.scopeKeys = _.keys(IPolygon.scope);\r\n\r\n IPolygon.include(GmapUtil);\r\n\r\n IPolygon.extend(CtrlHandle);\r\n\r\n function IPolygon() {}\r\n\r\n IPolygon.prototype.restrict = 'EMA';\r\n\r\n IPolygon.prototype.replace = true;\r\n\r\n IPolygon.prototype.require = '^' + 'uiGmapGoogleMap';\r\n\r\n IPolygon.prototype.scope = IPolygon.scope;\r\n\r\n IPolygon.prototype.DEFAULTS = {};\r\n\r\n IPolygon.prototype.$log = Logger;\r\n\r\n return IPolygon;\r\n\r\n })(BaseObject);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIPolyline', [\r\n 'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapCtrlHandle', function(GmapUtil, BaseObject, Logger, CtrlHandle) {\r\n var IPolyline;\r\n return IPolyline = (function(superClass) {\r\n extend(IPolyline, superClass);\r\n\r\n IPolyline.scope = {\r\n path: '=',\r\n stroke: '=',\r\n clickable: '=',\r\n draggable: '=',\r\n editable: '=',\r\n geodesic: '=',\r\n icons: '=',\r\n visible: '=',\r\n \"static\": '=',\r\n fit: '=',\r\n events: '=',\r\n zIndex: '=zindex'\r\n };\r\n\r\n IPolyline.scopeKeys = _.keys(IPolyline.scope);\r\n\r\n IPolyline.include(GmapUtil);\r\n\r\n IPolyline.extend(CtrlHandle);\r\n\r\n function IPolyline() {}\r\n\r\n IPolyline.prototype.restrict = 'EMA';\r\n\r\n IPolyline.prototype.replace = true;\r\n\r\n IPolyline.prototype.require = '^' + 'uiGmapGoogleMap';\r\n\r\n IPolyline.prototype.scope = IPolyline.scope;\r\n\r\n IPolyline.prototype.DEFAULTS = {};\r\n\r\n IPolyline.prototype.$log = Logger;\r\n\r\n return IPolyline;\r\n\r\n })(BaseObject);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapIRectangle', [\r\n function() {\r\n 'use strict';\r\n var DEFAULTS;\r\n DEFAULTS = {};\r\n return {\r\n restrict: 'EMA',\r\n require: '^' + 'uiGmapGoogleMap',\r\n replace: true,\r\n scope: {\r\n bounds: '=',\r\n stroke: '=',\r\n clickable: '=',\r\n draggable: '=',\r\n editable: '=',\r\n fill: '=',\r\n visible: '=',\r\n events: '='\r\n }\r\n };\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIWindow', [\r\n 'uiGmapBaseObject', 'uiGmapChildEvents', 'uiGmapCtrlHandle', function(BaseObject, ChildEvents, CtrlHandle) {\r\n var IWindow;\r\n return IWindow = (function(superClass) {\r\n extend(IWindow, superClass);\r\n\r\n IWindow.scope = {\r\n coords: '=coords',\r\n template: '=template',\r\n templateUrl: '=templateurl',\r\n templateParameter: '=templateparameter',\r\n isIconVisibleOnClick: '=isiconvisibleonclick',\r\n closeClick: '&closeclick',\r\n options: '=options',\r\n control: '=control',\r\n show: '=show'\r\n };\r\n\r\n IWindow.scopeKeys = _.keys(IWindow.scope);\r\n\r\n IWindow.include(ChildEvents);\r\n\r\n IWindow.extend(CtrlHandle);\r\n\r\n function IWindow() {\r\n this.restrict = 'EMA';\r\n this.template = void 0;\r\n this.transclude = true;\r\n this.priority = -100;\r\n this.require = '^' + 'uiGmapGoogleMap';\r\n this.replace = true;\r\n this.scope = _.extend(this.scope || {}, IWindow.scope);\r\n }\r\n\r\n return IWindow;\r\n\r\n })(BaseObject);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },\r\n extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapMap', [\r\n '$timeout', '$q', 'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapCtrlHandle', 'uiGmapIsReady', 'uiGmapuuid', 'uiGmapExtendGWin', 'uiGmapExtendMarkerClusterer', 'uiGmapGoogleMapsUtilV3', 'uiGmapGoogleMapApi', 'uiGmapEventsHelper', function($timeout, $q, $log, GmapUtil, BaseObject, CtrlHandle, IsReady, uuid, ExtendGWin, ExtendMarkerClusterer, GoogleMapsUtilV3, GoogleMapApi, EventsHelper) {\r\n 'use strict';\r\n var DEFAULTS, Map, initializeItems;\r\n DEFAULTS = void 0;\r\n initializeItems = [GoogleMapsUtilV3, ExtendGWin, ExtendMarkerClusterer];\r\n return Map = (function(superClass) {\r\n extend(Map, superClass);\r\n\r\n Map.include(GmapUtil);\r\n\r\n function Map() {\r\n this.link = bind(this.link, this);\r\n var ctrlFn, self;\r\n ctrlFn = function($scope) {\r\n var ctrlObj, retCtrl;\r\n retCtrl = void 0;\r\n $scope.$on('$destroy', function() {\r\n return IsReady.decrement();\r\n });\r\n ctrlObj = CtrlHandle.handle($scope);\r\n $scope.ctrlType = 'Map';\r\n $scope.deferred.promise.then(function() {\r\n return initializeItems.forEach(function(i) {\r\n return i.init();\r\n });\r\n });\r\n ctrlObj.getMap = function() {\r\n return $scope.map;\r\n };\r\n retCtrl = _.extend(this, ctrlObj);\r\n return retCtrl;\r\n };\r\n this.controller = ['$scope', ctrlFn];\r\n self = this;\r\n }\r\n\r\n Map.prototype.restrict = 'EMA';\r\n\r\n Map.prototype.transclude = true;\r\n\r\n Map.prototype.replace = false;\r\n\r\n Map.prototype.template = '
    ';\r\n\r\n Map.prototype.scope = {\r\n center: '=',\r\n zoom: '=',\r\n dragging: '=',\r\n control: '=',\r\n options: '=',\r\n events: '=',\r\n eventOpts: '=',\r\n styles: '=',\r\n bounds: '=',\r\n update: '='\r\n };\r\n\r\n Map.prototype.link = function(scope, element, attrs) {\r\n var listeners, unbindCenterWatch;\r\n listeners = [];\r\n scope.$on('$destroy', function() {\r\n return EventsHelper.removeEvents(listeners);\r\n });\r\n scope.idleAndZoomChanged = false;\r\n if (scope.center == null) {\r\n unbindCenterWatch = scope.$watch('center', (function(_this) {\r\n return function() {\r\n if (!scope.center) {\r\n return;\r\n }\r\n unbindCenterWatch();\r\n return _this.link(scope, element, attrs);\r\n };\r\n })(this));\r\n return;\r\n }\r\n return GoogleMapApi.then((function(_this) {\r\n return function(maps) {\r\n var _gMap, customListeners, disabledEvents, dragging, el, eventName, getEventHandler, mapOptions, maybeHookToEvent, opts, ref, resolveSpawned, settingFromDirective, spawned, type, updateCenter, zoomPromise;\r\n DEFAULTS = {\r\n mapTypeId: maps.MapTypeId.ROADMAP\r\n };\r\n spawned = IsReady.spawn();\r\n resolveSpawned = function() {\r\n return spawned.deferred.resolve({\r\n instance: spawned.instance,\r\n map: _gMap\r\n });\r\n };\r\n if (!_this.validateCoords(scope.center)) {\r\n $log.error('angular-google-maps: could not find a valid center property');\r\n return;\r\n }\r\n if (!angular.isDefined(scope.zoom)) {\r\n $log.error('angular-google-maps: map zoom property not set');\r\n return;\r\n }\r\n el = angular.element(element);\r\n el.addClass('angular-google-map');\r\n opts = {\r\n options: {}\r\n };\r\n if (attrs.options) {\r\n opts.options = scope.options;\r\n }\r\n if (attrs.styles) {\r\n opts.styles = scope.styles;\r\n }\r\n if (attrs.type) {\r\n type = attrs.type.toUpperCase();\r\n if (google.maps.MapTypeId.hasOwnProperty(type)) {\r\n opts.mapTypeId = google.maps.MapTypeId[attrs.type.toUpperCase()];\r\n } else {\r\n $log.error(\"angular-google-maps: invalid map type '\" + attrs.type + \"'\");\r\n }\r\n }\r\n mapOptions = angular.extend({}, DEFAULTS, opts, {\r\n center: _this.getCoords(scope.center),\r\n zoom: scope.zoom,\r\n bounds: scope.bounds\r\n });\r\n _gMap = new google.maps.Map(el.find('div')[1], mapOptions);\r\n _gMap['uiGmap_id'] = uuid.generate();\r\n dragging = false;\r\n listeners.push(google.maps.event.addListenerOnce(_gMap, 'idle', function() {\r\n scope.deferred.resolve(_gMap);\r\n return resolveSpawned();\r\n }));\r\n disabledEvents = attrs.events && (((ref = scope.events) != null ? ref.blacklist : void 0) != null) ? scope.events.blacklist : [];\r\n if (_.isString(disabledEvents)) {\r\n disabledEvents = [disabledEvents];\r\n }\r\n maybeHookToEvent = function(eventName, fn, prefn) {\r\n if (!_.contains(disabledEvents, eventName)) {\r\n if (prefn) {\r\n prefn();\r\n }\r\n return listeners.push(google.maps.event.addListener(_gMap, eventName, function() {\r\n var ref1;\r\n if (!((ref1 = scope.update) != null ? ref1.lazy : void 0)) {\r\n return fn();\r\n }\r\n }));\r\n }\r\n };\r\n if (!_.contains(disabledEvents, 'all')) {\r\n maybeHookToEvent('dragstart', function() {\r\n dragging = true;\r\n return scope.$evalAsync(function(s) {\r\n if (s.dragging != null) {\r\n return s.dragging = dragging;\r\n }\r\n });\r\n });\r\n maybeHookToEvent('dragend', function() {\r\n dragging = false;\r\n return scope.$evalAsync(function(s) {\r\n if (s.dragging != null) {\r\n return s.dragging = dragging;\r\n }\r\n });\r\n });\r\n updateCenter = function(c, s) {\r\n if (c == null) {\r\n c = _gMap.center;\r\n }\r\n if (s == null) {\r\n s = scope;\r\n }\r\n if (_.contains(disabledEvents, 'center')) {\r\n return;\r\n }\r\n if (angular.isDefined(s.center.type)) {\r\n if (s.center.coordinates[1] !== c.lat()) {\r\n s.center.coordinates[1] = c.lat();\r\n }\r\n if (s.center.coordinates[0] !== c.lng()) {\r\n return s.center.coordinates[0] = c.lng();\r\n }\r\n } else {\r\n if (s.center.latitude !== c.lat()) {\r\n s.center.latitude = c.lat();\r\n }\r\n if (s.center.longitude !== c.lng()) {\r\n return s.center.longitude = c.lng();\r\n }\r\n }\r\n };\r\n settingFromDirective = false;\r\n maybeHookToEvent('idle', function() {\r\n var b, ne, sw;\r\n b = _gMap.getBounds();\r\n ne = b.getNorthEast();\r\n sw = b.getSouthWest();\r\n settingFromDirective = true;\r\n return scope.$evalAsync(function(s) {\r\n updateCenter();\r\n if (s.bounds !== null && s.bounds !== undefined && s.bounds !== void 0 && !_.contains(disabledEvents, 'bounds')) {\r\n s.bounds.northeast = {\r\n latitude: ne.lat(),\r\n longitude: ne.lng()\r\n };\r\n s.bounds.southwest = {\r\n latitude: sw.lat(),\r\n longitude: sw.lng()\r\n };\r\n }\r\n if (!_.contains(disabledEvents, 'zoom')) {\r\n s.zoom = _gMap.zoom;\r\n scope.idleAndZoomChanged = !scope.idleAndZoomChanged;\r\n }\r\n return settingFromDirective = false;\r\n });\r\n });\r\n }\r\n if (angular.isDefined(scope.events) && scope.events !== null && angular.isObject(scope.events)) {\r\n getEventHandler = function(eventName) {\r\n return function() {\r\n return scope.events[eventName].apply(scope, [_gMap, eventName, arguments]);\r\n };\r\n };\r\n customListeners = [];\r\n for (eventName in scope.events) {\r\n if (scope.events.hasOwnProperty(eventName) && angular.isFunction(scope.events[eventName])) {\r\n customListeners.push(google.maps.event.addListener(_gMap, eventName, getEventHandler(eventName)));\r\n }\r\n }\r\n listeners.concat(customListeners);\r\n }\r\n _gMap.getOptions = function() {\r\n return mapOptions;\r\n };\r\n scope.map = _gMap;\r\n if ((attrs.control != null) && (scope.control != null)) {\r\n scope.control.refresh = function(maybeCoords) {\r\n var coords, ref1, ref2;\r\n if (_gMap == null) {\r\n return;\r\n }\r\n if (((typeof google !== \"undefined\" && google !== null ? (ref1 = google.maps) != null ? (ref2 = ref1.event) != null ? ref2.trigger : void 0 : void 0 : void 0) != null) && (_gMap != null)) {\r\n google.maps.event.trigger(_gMap, 'resize');\r\n }\r\n if (((maybeCoords != null ? maybeCoords.latitude : void 0) != null) && ((maybeCoords != null ? maybeCoords.longitude : void 0) != null)) {\r\n coords = _this.getCoords(maybeCoords);\r\n if (_this.isTrue(attrs.pan)) {\r\n return _gMap.panTo(coords);\r\n } else {\r\n return _gMap.setCenter(coords);\r\n }\r\n }\r\n };\r\n scope.control.getGMap = function() {\r\n return _gMap;\r\n };\r\n scope.control.getMapOptions = function() {\r\n return mapOptions;\r\n };\r\n scope.control.getCustomEventListeners = function() {\r\n return customListeners;\r\n };\r\n scope.control.removeEvents = function(yourListeners) {\r\n return EventsHelper.removeEvents(yourListeners);\r\n };\r\n }\r\n scope.$watch('center', function(newValue, oldValue) {\r\n var coords, settingCenterFromScope;\r\n if (newValue === oldValue || settingFromDirective) {\r\n return;\r\n }\r\n coords = _this.getCoords(scope.center);\r\n if (coords.lat() === _gMap.center.lat() && coords.lng() === _gMap.center.lng()) {\r\n return;\r\n }\r\n settingCenterFromScope = true;\r\n if (!dragging) {\r\n if (!_this.validateCoords(newValue)) {\r\n $log.error(\"Invalid center for newValue: \" + (JSON.stringify(newValue)));\r\n }\r\n if (_this.isTrue(attrs.pan) && scope.zoom === _gMap.zoom) {\r\n _gMap.panTo(coords);\r\n } else {\r\n _gMap.setCenter(coords);\r\n }\r\n }\r\n return settingCenterFromScope = false;\r\n }, true);\r\n zoomPromise = null;\r\n scope.$watch('zoom', function(newValue, oldValue) {\r\n var ref1, ref2, settingZoomFromScope;\r\n if (newValue == null) {\r\n return;\r\n }\r\n if (_.isEqual(newValue, oldValue) || (_gMap != null ? _gMap.getZoom() : void 0) === (scope != null ? scope.zoom : void 0) || settingFromDirective) {\r\n return;\r\n }\r\n settingZoomFromScope = true;\r\n if (zoomPromise != null) {\r\n $timeout.cancel(zoomPromise);\r\n }\r\n return zoomPromise = $timeout(function() {\r\n _gMap.setZoom(newValue);\r\n return settingZoomFromScope = false;\r\n }, ((ref1 = scope.eventOpts) != null ? (ref2 = ref1.debounce) != null ? ref2.zoomMs : void 0 : void 0) + 20, false);\r\n });\r\n scope.$watch('bounds', function(newValue, oldValue) {\r\n var bounds, ne, ref1, ref2, ref3, ref4, sw;\r\n if (newValue === oldValue) {\r\n return;\r\n }\r\n if (((newValue != null ? (ref1 = newValue.northeast) != null ? ref1.latitude : void 0 : void 0) == null) || ((newValue != null ? (ref2 = newValue.northeast) != null ? ref2.longitude : void 0 : void 0) == null) || ((newValue != null ? (ref3 = newValue.southwest) != null ? ref3.latitude : void 0 : void 0) == null) || ((newValue != null ? (ref4 = newValue.southwest) != null ? ref4.longitude : void 0 : void 0) == null)) {\r\n $log.error(\"Invalid map bounds for new value: \" + (JSON.stringify(newValue)));\r\n return;\r\n }\r\n ne = new google.maps.LatLng(newValue.northeast.latitude, newValue.northeast.longitude);\r\n sw = new google.maps.LatLng(newValue.southwest.latitude, newValue.southwest.longitude);\r\n bounds = new google.maps.LatLngBounds(sw, ne);\r\n return _gMap.fitBounds(bounds);\r\n });\r\n return ['options', 'styles'].forEach(function(toWatch) {\r\n return scope.$watch(toWatch, function(newValue, oldValue) {\r\n var watchItem;\r\n watchItem = this.exp;\r\n if (_.isEqual(newValue, oldValue)) {\r\n return;\r\n }\r\n if (watchItem === 'options') {\r\n opts.options = newValue;\r\n } else {\r\n opts.options[watchItem] = newValue;\r\n }\r\n if (_gMap != null) {\r\n return _gMap.setOptions(opts);\r\n }\r\n }, true);\r\n });\r\n };\r\n })(this));\r\n };\r\n\r\n return Map;\r\n\r\n })(BaseObject);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },\r\n extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module(\"uiGmapgoogle-maps.directives.api\").factory(\"uiGmapMarker\", [\r\n \"uiGmapIMarker\", \"uiGmapMarkerChildModel\", \"uiGmapMarkerManager\", \"uiGmapLogger\", function(IMarker, MarkerChildModel, MarkerManager, $log) {\r\n var Marker;\r\n return Marker = (function(superClass) {\r\n extend(Marker, superClass);\r\n\r\n function Marker() {\r\n this.link = bind(this.link, this);\r\n Marker.__super__.constructor.call(this);\r\n this.template = '';\r\n $log.info(this);\r\n }\r\n\r\n Marker.prototype.controller = [\r\n '$scope', '$element', function($scope, $element) {\r\n $scope.ctrlType = 'Marker';\r\n return _.extend(this, IMarker.handle($scope, $element));\r\n }\r\n ];\r\n\r\n Marker.prototype.link = function(scope, element, attrs, ctrl) {\r\n var mapPromise;\r\n mapPromise = IMarker.mapPromise(scope, ctrl);\r\n mapPromise.then((function(_this) {\r\n return function(map) {\r\n var doClick, doDrawSelf, gManager, keys, m, trackModel;\r\n gManager = new MarkerManager(map);\r\n keys = _.object(IMarker.keys, IMarker.keys);\r\n m = new MarkerChildModel(scope, scope, keys, map, {}, doClick = true, gManager, doDrawSelf = false, trackModel = false);\r\n m.deferred.promise.then(function(gMarker) {\r\n return scope.deferred.resolve(gMarker);\r\n });\r\n if (scope.control != null) {\r\n return scope.control.getGMarkers = gManager.getGMarkers;\r\n }\r\n };\r\n })(this));\r\n return scope.$on('$destroy', (function(_this) {\r\n return function() {\r\n var gManager;\r\n if (typeof gManager !== \"undefined\" && gManager !== null) {\r\n gManager.clear();\r\n }\r\n return gManager = null;\r\n };\r\n })(this));\r\n };\r\n\r\n return Marker;\r\n\r\n })(IMarker);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module(\"uiGmapgoogle-maps.directives.api\").factory(\"uiGmapMarkers\", [\r\n \"uiGmapIMarker\", \"uiGmapPlural\", \"uiGmapMarkersParentModel\", \"uiGmap_sync\", \"uiGmapLogger\", function(IMarker, Plural, MarkersParentModel, _sync, $log) {\r\n var Markers;\r\n return Markers = (function(superClass) {\r\n extend(Markers, superClass);\r\n\r\n function Markers() {\r\n Markers.__super__.constructor.call(this);\r\n this.template = '';\r\n Plural.extend(this, {\r\n doCluster: '=?docluster',\r\n clusterOptions: '=clusteroptions',\r\n clusterEvents: '=clusterevents',\r\n modelsByRef: '=modelsbyref',\r\n type: '=?type',\r\n typeOptions: '=?typeoptions',\r\n typeEvents: '=?typeevents'\r\n });\r\n $log.info(this);\r\n }\r\n\r\n Markers.prototype.controller = [\r\n '$scope', '$element', function($scope, $element) {\r\n $scope.ctrlType = 'Markers';\r\n return _.extend(this, IMarker.handle($scope, $element));\r\n }\r\n ];\r\n\r\n Markers.prototype.link = function(scope, element, attrs, ctrl) {\r\n var parentModel, ready;\r\n parentModel = void 0;\r\n ready = function() {\r\n return scope.deferred.resolve();\r\n };\r\n return IMarker.mapPromise(scope, ctrl).then(function(map) {\r\n var mapScope;\r\n mapScope = ctrl.getScope();\r\n mapScope.$watch('idleAndZoomChanged', function() {\r\n return _.defer(parentModel.gManager.draw);\r\n });\r\n parentModel = new MarkersParentModel(scope, element, attrs, map);\r\n Plural.link(scope, parentModel);\r\n if (scope.control != null) {\r\n scope.control.getGMarkers = function() {\r\n var ref;\r\n return (ref = parentModel.gManager) != null ? ref.getGMarkers() : void 0;\r\n };\r\n scope.control.getChildMarkers = function() {\r\n return parentModel.plurals;\r\n };\r\n }\r\n return _.last(parentModel.existingPieces._content).then(function() {\r\n return ready();\r\n });\r\n });\r\n };\r\n\r\n return Markers;\r\n\r\n })(IMarker);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapPlural', [\r\n function() {\r\n var _initControl;\r\n _initControl = function(scope, parent) {\r\n if (scope.control == null) {\r\n return;\r\n }\r\n scope.control.updateModels = function(models) {\r\n scope.models = models;\r\n return parent.createChildScopes(false);\r\n };\r\n scope.control.newModels = function(models) {\r\n scope.models = models;\r\n return parent.rebuildAll(scope, true, true);\r\n };\r\n scope.control.clean = function() {\r\n return parent.rebuildAll(scope, false, true);\r\n };\r\n scope.control.getPlurals = function() {\r\n return parent.plurals;\r\n };\r\n scope.control.getManager = function() {\r\n return parent.gManager;\r\n };\r\n scope.control.hasManager = function() {\r\n return (parent.gManager != null) === true;\r\n };\r\n return scope.control.managerDraw = function() {\r\n var ref;\r\n if (scope.control.hasManager()) {\r\n return (ref = scope.control.getManager()) != null ? ref.draw() : void 0;\r\n }\r\n };\r\n };\r\n return {\r\n extend: function(obj, obj2) {\r\n return _.extend(obj.scope || {}, obj2 || {}, {\r\n idKey: '=idkey',\r\n doRebuildAll: '=dorebuildall',\r\n models: '=models',\r\n chunk: '=chunk',\r\n cleanchunk: '=cleanchunk',\r\n control: '=control'\r\n });\r\n },\r\n link: function(scope, parent) {\r\n return _initControl(scope, parent);\r\n }\r\n };\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },\r\n extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygon', [\r\n 'uiGmapIPolygon', '$timeout', 'uiGmapPolygonChildModel', function(IPolygon, $timeout, PolygonChild) {\r\n var Polygon;\r\n return Polygon = (function(superClass) {\r\n extend(Polygon, superClass);\r\n\r\n function Polygon() {\r\n this.link = bind(this.link, this);\r\n return Polygon.__super__.constructor.apply(this, arguments);\r\n }\r\n\r\n Polygon.prototype.link = function(scope, element, attrs, mapCtrl) {\r\n var children, promise;\r\n children = [];\r\n promise = IPolygon.mapPromise(scope, mapCtrl);\r\n if (scope.control != null) {\r\n scope.control.getInstance = this;\r\n scope.control.polygons = children;\r\n scope.control.promise = promise;\r\n }\r\n return promise.then((function(_this) {\r\n return function(map) {\r\n return children.push(new PolygonChild(scope, attrs, map, _this.DEFAULTS));\r\n };\r\n })(this));\r\n };\r\n\r\n return Polygon;\r\n\r\n })(IPolygon);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },\r\n extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygons', [\r\n 'uiGmapIPolygon', '$timeout', 'uiGmapPolygonsParentModel', 'uiGmapPlural', function(Interface, $timeout, ParentModel, Plural) {\r\n var Polygons;\r\n return Polygons = (function(superClass) {\r\n extend(Polygons, superClass);\r\n\r\n function Polygons() {\r\n this.link = bind(this.link, this);\r\n Polygons.__super__.constructor.call(this);\r\n Plural.extend(this);\r\n this.$log.info(this);\r\n }\r\n\r\n Polygons.prototype.link = function(scope, element, attrs, mapCtrl) {\r\n return mapCtrl.getScope().deferred.promise.then((function(_this) {\r\n return function(map) {\r\n if (angular.isUndefined(scope.path) || scope.path === null) {\r\n _this.$log.warn('polygons: no valid path attribute found');\r\n }\r\n if (!scope.models) {\r\n _this.$log.warn('polygons: no models found to create from');\r\n }\r\n return Plural.link(scope, new ParentModel(scope, element, attrs, map, _this.DEFAULTS));\r\n };\r\n })(this));\r\n };\r\n\r\n return Polygons;\r\n\r\n })(Interface);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },\r\n extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolyline', [\r\n 'uiGmapIPolyline', '$timeout', 'uiGmapPolylineChildModel', function(IPolyline, $timeout, PolylineChildModel) {\r\n var Polyline;\r\n return Polyline = (function(superClass) {\r\n extend(Polyline, superClass);\r\n\r\n function Polyline() {\r\n this.link = bind(this.link, this);\r\n return Polyline.__super__.constructor.apply(this, arguments);\r\n }\r\n\r\n Polyline.prototype.link = function(scope, element, attrs, mapCtrl) {\r\n return IPolyline.mapPromise(scope, mapCtrl).then((function(_this) {\r\n return function(map) {\r\n if (angular.isUndefined(scope.path) || scope.path === null || !_this.validatePath(scope.path)) {\r\n _this.$log.warn('polyline: no valid path attribute found');\r\n }\r\n return new PolylineChildModel(scope, attrs, map, _this.DEFAULTS);\r\n };\r\n })(this));\r\n };\r\n\r\n return Polyline;\r\n\r\n })(IPolyline);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },\r\n extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolylines', [\r\n 'uiGmapIPolyline', '$timeout', 'uiGmapPolylinesParentModel', 'uiGmapPlural', function(IPolyline, $timeout, PolylinesParentModel, Plural) {\r\n var Polylines;\r\n return Polylines = (function(superClass) {\r\n extend(Polylines, superClass);\r\n\r\n function Polylines() {\r\n this.link = bind(this.link, this);\r\n Polylines.__super__.constructor.call(this);\r\n Plural.extend(this);\r\n this.$log.info(this);\r\n }\r\n\r\n Polylines.prototype.link = function(scope, element, attrs, mapCtrl) {\r\n return mapCtrl.getScope().deferred.promise.then((function(_this) {\r\n return function(map) {\r\n if (angular.isUndefined(scope.path) || scope.path === null) {\r\n _this.$log.warn('polylines: no valid path attribute found');\r\n }\r\n if (!scope.models) {\r\n _this.$log.warn('polylines: no models found to create from');\r\n }\r\n return Plural.link(scope, new PolylinesParentModel(scope, element, attrs, map, _this.DEFAULTS));\r\n };\r\n })(this));\r\n };\r\n\r\n return Polylines;\r\n\r\n })(IPolyline);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapRectangle', [\r\n 'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapIRectangle', 'uiGmapRectangleParentModel', function($log, GmapUtil, IRectangle, RectangleParentModel) {\r\n return _.extend(IRectangle, {\r\n link: function(scope, element, attrs, mapCtrl) {\r\n return mapCtrl.getScope().deferred.promise.then((function(_this) {\r\n return function(map) {\r\n return new RectangleParentModel(scope, element, attrs, map);\r\n };\r\n })(this));\r\n }\r\n });\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },\r\n extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapWindow', [\r\n 'uiGmapIWindow', 'uiGmapGmapUtil', 'uiGmapWindowChildModel', 'uiGmapLodash', 'uiGmapLogger', function(IWindow, GmapUtil, WindowChildModel, uiGmapLodash, $log) {\r\n var Window;\r\n return Window = (function(superClass) {\r\n extend(Window, superClass);\r\n\r\n Window.include(GmapUtil);\r\n\r\n function Window() {\r\n this.link = bind(this.link, this);\r\n Window.__super__.constructor.call(this);\r\n this.require = ['^' + 'uiGmapGoogleMap', '^?' + 'uiGmapMarker'];\r\n this.template = '';\r\n $log.debug(this);\r\n this.childWindows = [];\r\n }\r\n\r\n Window.prototype.link = function(scope, element, attrs, ctrls) {\r\n var markerCtrl, markerScope;\r\n markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1] : void 0;\r\n markerScope = markerCtrl != null ? markerCtrl.getScope() : void 0;\r\n this.mapPromise = IWindow.mapPromise(scope, ctrls[0]);\r\n return this.mapPromise.then((function(_this) {\r\n return function(mapCtrl) {\r\n var isIconVisibleOnClick;\r\n isIconVisibleOnClick = true;\r\n if (angular.isDefined(attrs.isiconvisibleonclick)) {\r\n isIconVisibleOnClick = scope.isIconVisibleOnClick;\r\n }\r\n if (!markerCtrl) {\r\n _this.init(scope, element, isIconVisibleOnClick, mapCtrl);\r\n return;\r\n }\r\n return markerScope.deferred.promise.then(function(gMarker) {\r\n return _this.init(scope, element, isIconVisibleOnClick, mapCtrl, markerScope);\r\n });\r\n };\r\n })(this));\r\n };\r\n\r\n Window.prototype.init = function(scope, element, isIconVisibleOnClick, mapCtrl, markerScope) {\r\n var childWindow, defaults, gMarker, hasScopeCoords, opts;\r\n defaults = scope.options != null ? scope.options : {};\r\n hasScopeCoords = (scope != null) && this.validateCoords(scope.coords);\r\n if ((markerScope != null ? markerScope['getGMarker'] : void 0) != null) {\r\n gMarker = markerScope.getGMarker();\r\n }\r\n opts = hasScopeCoords ? this.createWindowOptions(gMarker, scope, element.html(), defaults) : defaults;\r\n if (mapCtrl != null) {\r\n childWindow = new WindowChildModel({}, scope, opts, isIconVisibleOnClick, mapCtrl, markerScope, element);\r\n this.childWindows.push(childWindow);\r\n scope.$on('$destroy', (function(_this) {\r\n return function() {\r\n _this.childWindows = uiGmapLodash.withoutObjects(_this.childWindows, [childWindow], function(child1, child2) {\r\n return child1.scope.$id === child2.scope.$id;\r\n });\r\n return _this.childWindows.length = 0;\r\n };\r\n })(this));\r\n }\r\n if (scope.control != null) {\r\n scope.control.getGWindows = (function(_this) {\r\n return function() {\r\n return _this.childWindows.map(function(child) {\r\n return child.gObject;\r\n });\r\n };\r\n })(this);\r\n scope.control.getChildWindows = (function(_this) {\r\n return function() {\r\n return _this.childWindows;\r\n };\r\n })(this);\r\n scope.control.getPlurals = scope.control.getChildWindows;\r\n scope.control.showWindow = (function(_this) {\r\n return function() {\r\n return _this.childWindows.map(function(child) {\r\n return child.showWindow();\r\n });\r\n };\r\n })(this);\r\n scope.control.hideWindow = (function(_this) {\r\n return function() {\r\n return _this.childWindows.map(function(child) {\r\n return child.hideWindow();\r\n });\r\n };\r\n })(this);\r\n }\r\n if ((this.onChildCreation != null) && (childWindow != null)) {\r\n return this.onChildCreation(childWindow);\r\n }\r\n };\r\n\r\n return Window;\r\n\r\n })(IWindow);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },\r\n extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\r\n hasProp = {}.hasOwnProperty;\r\n\r\n angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapWindows', [\r\n 'uiGmapIWindow', 'uiGmapPlural', 'uiGmapWindowsParentModel', 'uiGmapPromise', 'uiGmapLogger', function(IWindow, Plural, WindowsParentModel, uiGmapPromise, $log) {\r\n\r\n /*\r\n Windows directive where many windows map to the models property\r\n */\r\n var Windows;\r\n return Windows = (function(superClass) {\r\n extend(Windows, superClass);\r\n\r\n function Windows() {\r\n this.init = bind(this.init, this);\r\n this.link = bind(this.link, this);\r\n Windows.__super__.constructor.call(this);\r\n this.require = ['^' + 'uiGmapGoogleMap', '^?' + 'uiGmapMarkers'];\r\n this.template = '';\r\n Plural.extend(this);\r\n $log.debug(this);\r\n }\r\n\r\n Windows.prototype.link = function(scope, element, attrs, ctrls) {\r\n var mapScope, markerCtrl, markerScope;\r\n mapScope = ctrls[0].getScope();\r\n markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1] : void 0;\r\n markerScope = markerCtrl != null ? markerCtrl.getScope() : void 0;\r\n return mapScope.deferred.promise.then((function(_this) {\r\n return function(map) {\r\n var promise, ref;\r\n promise = (markerScope != null ? (ref = markerScope.deferred) != null ? ref.promise : void 0 : void 0) || uiGmapPromise.resolve();\r\n return promise.then(function() {\r\n var pieces, ref1;\r\n pieces = (ref1 = _this.parentModel) != null ? ref1.existingPieces : void 0;\r\n if (pieces) {\r\n return pieces.then(function() {\r\n return _this.init(scope, element, attrs, ctrls, map, markerScope);\r\n });\r\n } else {\r\n return _this.init(scope, element, attrs, ctrls, map, markerScope);\r\n }\r\n });\r\n };\r\n })(this));\r\n };\r\n\r\n Windows.prototype.init = function(scope, element, attrs, ctrls, map, additionalScope) {\r\n var parentModel;\r\n parentModel = new WindowsParentModel(scope, element, attrs, ctrls, map, additionalScope);\r\n Plural.link(scope, parentModel);\r\n if (scope.control != null) {\r\n scope.control.getGWindows = (function(_this) {\r\n return function() {\r\n return parentModel.plurals.map(function(child) {\r\n return child.gObject;\r\n });\r\n };\r\n })(this);\r\n return scope.control.getChildWindows = (function(_this) {\r\n return function() {\r\n return parentModel.plurals;\r\n };\r\n })(this);\r\n }\r\n };\r\n\r\n return Windows;\r\n\r\n })(IWindow);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;\r\n/*\r\n@authors\r\nNicolas Laplante - https://plus.google.com/108189012221374960701\r\nNicholas McCready - https://twitter.com/nmccready\r\nNick Baugh - https://github.com/niftylettuce\r\n */\r\n\r\n(function() {\r\n angular.module(\"uiGmapgoogle-maps\").directive(\"uiGmapGoogleMap\", [\r\n \"uiGmapMap\", function(Map) {\r\n return new Map();\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;\r\n/*\r\n@authors\r\nNicolas Laplante - https://plus.google.com/108189012221374960701\r\nNicholas McCready - https://twitter.com/nmccready\r\n */\r\n\r\n\r\n/*\r\nMap marker directive\r\n\r\nThis directive is used to create a marker on an existing map.\r\nThis directive creates a new scope.\r\n\r\n{attribute coords required} object containing latitude and longitude properties\r\n{attribute icon optional} string url to image used for marker icon\r\n{attribute animate optional} if set to false, the marker won't be animated (on by default)\r\n */\r\n\r\n(function() {\r\n angular.module('uiGmapgoogle-maps').directive('uiGmapMarker', [\r\n '$timeout', 'uiGmapMarker', function($timeout, Marker) {\r\n return new Marker($timeout);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;\r\n/*\r\n@authors\r\nNicolas Laplante - https://plus.google.com/108189012221374960701\r\nNicholas McCready - https://twitter.com/nmccready\r\n */\r\n\r\n\r\n/*\r\nMap marker directive\r\n\r\nThis directive is used to create a marker on an existing map.\r\nThis directive creates a new scope.\r\n\r\n{attribute coords required} object containing latitude and longitude properties\r\n{attribute icon optional} string url to image used for marker icon\r\n{attribute animate optional} if set to false, the marker won't be animated (on by default)\r\n */\r\n\r\n(function() {\r\n angular.module('uiGmapgoogle-maps').directive('uiGmapMarkers', [\r\n '$timeout', 'uiGmapMarkers', function($timeout, Markers) {\r\n return new Markers($timeout);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;\r\n/*\r\n@authors\r\nNicolas Laplante - https://plus.google.com/108189012221374960701\r\nNicholas McCready - https://twitter.com/nmccready\r\nRick Huizinga - https://plus.google.com/+RickHuizinga\r\n */\r\n\r\n(function() {\r\n angular.module('uiGmapgoogle-maps').directive('uiGmapPolygon', [\r\n 'uiGmapPolygon', function(Polygon) {\r\n return new Polygon();\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;\r\n/*\r\n@authors\r\nJulian Popescu - https://github.com/jpopesculian\r\nRick Huizinga - https://plus.google.com/+RickHuizinga\r\n */\r\n\r\n(function() {\r\n angular.module('uiGmapgoogle-maps').directive(\"uiGmapCircle\", [\r\n \"uiGmapCircle\", function(Circle) {\r\n return Circle;\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;\r\n/*\r\n@authors\r\nNicolas Laplante - https://plus.google.com/108189012221374960701\r\nNicholas McCready - https://twitter.com/nmccready\r\n */\r\n\r\n(function() {\r\n angular.module(\"uiGmapgoogle-maps\").directive(\"uiGmapPolyline\", [\r\n \"uiGmapPolyline\", function(Polyline) {\r\n return new Polyline();\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;\r\n/*\r\n@authors\r\nNicolas Laplante - https://plus.google.com/108189012221374960701\r\nNicholas McCready - https://twitter.com/nmccready\r\n */\r\n\r\n(function() {\r\n angular.module('uiGmapgoogle-maps').directive('uiGmapPolylines', [\r\n 'uiGmapPolylines', function(Polylines) {\r\n return new Polylines();\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;\r\n/*\r\n@authors\r\nNicolas Laplante - https://plus.google.com/108189012221374960701\r\nNicholas McCready - https://twitter.com/nmccready\r\nChentsu Lin - https://github.com/ChenTsuLin\r\n */\r\n\r\n(function() {\r\n angular.module(\"uiGmapgoogle-maps\").directive(\"uiGmapRectangle\", [\r\n \"uiGmapLogger\", \"uiGmapRectangle\", function($log, Rectangle) {\r\n return Rectangle;\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;\r\n/*\r\n@authors\r\nNicolas Laplante - https://plus.google.com/108189012221374960701\r\nNicholas McCready - https://twitter.com/nmccready\r\n */\r\n\r\n\r\n/*\r\nMap info window directive\r\n\r\nThis directive is used to create an info window on an existing map.\r\nThis directive creates a new scope.\r\n\r\n{attribute coords required} object containing latitude and longitude properties\r\n{attribute show optional} map will show when this expression returns true\r\n */\r\n\r\n(function() {\r\n angular.module(\"uiGmapgoogle-maps\").directive(\"uiGmapWindow\", [\r\n \"$timeout\", \"$compile\", \"$http\", \"$templateCache\", \"uiGmapWindow\", function($timeout, $compile, $http, $templateCache, Window) {\r\n return new Window($timeout, $compile, $http, $templateCache);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;\r\n/*\r\n@authors\r\nNicolas Laplante - https://plus.google.com/108189012221374960701\r\nNicholas McCready - https://twitter.com/nmccready\r\n */\r\n\r\n\r\n/*\r\nMap info window directive\r\n\r\nThis directive is used to create an info window on an existing map.\r\nThis directive creates a new scope.\r\n\r\n{attribute coords required} object containing latitude and longitude properties\r\n{attribute show optional} map will show when this expression returns true\r\n */\r\n\r\n(function() {\r\n angular.module(\"uiGmapgoogle-maps\").directive(\"uiGmapWindows\", [\r\n \"$timeout\", \"$compile\", \"$http\", \"$templateCache\", \"$interpolate\", \"uiGmapWindows\", function($timeout, $compile, $http, $templateCache, $interpolate, Windows) {\r\n return new Windows($timeout, $compile, $http, $templateCache, $interpolate);\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;\r\n/*\r\n@authors:\r\n- Nicolas Laplante https://plus.google.com/108189012221374960701\r\n- Nicholas McCready - https://twitter.com/nmccready\r\n */\r\n\r\n\r\n/*\r\nMap Layer directive\r\n\r\nThis directive is used to create any type of Layer from the google maps sdk.\r\nThis directive creates a new scope.\r\n\r\n{attribute show optional} true (default) shows the trafficlayer otherwise it is hidden\r\n */\r\n\r\n(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };\r\n\r\n angular.module('uiGmapgoogle-maps').directive('uiGmapLayer', [\r\n '$timeout', 'uiGmapLogger', 'uiGmapLayerParentModel', function($timeout, Logger, LayerParentModel) {\r\n var Layer;\r\n Layer = (function() {\r\n function Layer() {\r\n this.link = bind(this.link, this);\r\n this.$log = Logger;\r\n this.restrict = 'EMA';\r\n this.require = '^' + 'uiGmapGoogleMap';\r\n this.priority = -1;\r\n this.transclude = true;\r\n this.template = '';\r\n this.replace = true;\r\n this.scope = {\r\n show: '=show',\r\n type: '=type',\r\n namespace: '=namespace',\r\n options: '=options',\r\n onCreated: '&oncreated'\r\n };\r\n }\r\n\r\n Layer.prototype.link = function(scope, element, attrs, mapCtrl) {\r\n return mapCtrl.getScope().deferred.promise.then((function(_this) {\r\n return function(map) {\r\n if (scope.onCreated != null) {\r\n return new LayerParentModel(scope, element, attrs, map, scope.onCreated);\r\n } else {\r\n return new LayerParentModel(scope, element, attrs, map);\r\n }\r\n };\r\n })(this));\r\n };\r\n\r\n return Layer;\r\n\r\n })();\r\n return new Layer();\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;\r\n/*\r\n@authors\r\nAdam Kreitals, kreitals@hotmail.com\r\n */\r\n\r\n\r\n/*\r\nmapControl directive\r\n\r\nThis directive is used to create a custom control element on an existing map.\r\nThis directive creates a new scope.\r\n\r\n{attribute template required} \tstring url of the template to be used for the control\r\n{attribute position optional} \tstring position of the control of the form top-left or TOP_LEFT defaults to TOP_CENTER\r\n{attribute controller optional}\tstring controller to be applied to the template\r\n{attribute index optional}\t\tnumber index for controlling the order of similarly positioned mapControl elements\r\n */\r\n\r\n(function() {\r\n angular.module(\"uiGmapgoogle-maps\").directive(\"uiGmapMapControl\", [\r\n \"uiGmapControl\", function(Control) {\r\n return new Control();\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;\r\n/*\r\n@authors\r\nNicholas McCready - https://twitter.com/nmccready\r\n */\r\n\r\n(function() {\r\n angular.module('uiGmapgoogle-maps').directive('uiGmapDragZoom', [\r\n 'uiGmapDragZoom', function(DragZoom) {\r\n return DragZoom;\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module('uiGmapgoogle-maps').directive(\"uiGmapDrawingManager\", [\r\n \"uiGmapDrawingManager\", function(DrawingManager) {\r\n return DrawingManager;\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;\r\n/*\r\n@authors\r\nNicholas McCready - https://twitter.com/nmccready\r\n * Brunt of the work is in DrawFreeHandChildModel\r\n */\r\n\r\n(function() {\r\n angular.module('uiGmapgoogle-maps').directive('uiGmapFreeDrawPolygons', [\r\n 'uiGmapApiFreeDrawPolygons', function(FreeDrawPolygons) {\r\n return new FreeDrawPolygons();\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;\r\n/*\r\nMap Layer directive\r\n\r\nThis directive is used to create any type of Layer from the google maps sdk.\r\nThis directive creates a new scope.\r\n\r\n{attribute show optional} true (default) shows the trafficlayer otherwise it is hidden\r\n */\r\n\r\n(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };\r\n\r\n angular.module(\"uiGmapgoogle-maps\").directive(\"uiGmapMapType\", [\r\n \"$timeout\", \"uiGmapLogger\", \"uiGmapMapTypeParentModel\", function($timeout, Logger, MapTypeParentModel) {\r\n var MapType;\r\n MapType = (function() {\r\n function MapType() {\r\n this.link = bind(this.link, this);\r\n this.$log = Logger;\r\n this.restrict = \"EMA\";\r\n this.require = '^' + 'uiGmapGoogleMap';\r\n this.priority = -1;\r\n this.transclude = true;\r\n this.template = '';\r\n this.replace = true;\r\n this.scope = {\r\n show: \"=show\",\r\n options: '=options',\r\n refresh: '=refresh',\r\n id: '@'\r\n };\r\n }\r\n\r\n MapType.prototype.link = function(scope, element, attrs, mapCtrl) {\r\n return mapCtrl.getScope().deferred.promise.then((function(_this) {\r\n return function(map) {\r\n return new MapTypeParentModel(scope, element, attrs, map);\r\n };\r\n })(this));\r\n };\r\n\r\n return MapType;\r\n\r\n })();\r\n return new MapType();\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;\r\n/*\r\n@authors\r\nNicolas Laplante - https://plus.google.com/108189012221374960701\r\nNicholas McCready - https://twitter.com/nmccready\r\nRick Huizinga - https://plus.google.com/+RickHuizinga\r\n */\r\n\r\n(function() {\r\n angular.module('uiGmapgoogle-maps').directive('uiGmapPolygons', [\r\n 'uiGmapPolygons', function(Polygons) {\r\n return new Polygons();\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;\r\n/*\r\n@authors:\r\n- Nicolas Laplante https://plus.google.com/108189012221374960701\r\n- Nicholas McCready - https://twitter.com/nmccready\r\n- Carrie Kengle - http://about.me/carrie\r\n */\r\n\r\n\r\n/*\r\nPlaces Search Box directive\r\n\r\nThis directive is used to create a Places Search Box.\r\nThis directive creates a new scope.\r\n\r\n{attribute input required} HTMLInputElement\r\n{attribute options optional} The options that can be set on a SearchBox object (google.maps.places.SearchBoxOptions object specification)\r\n */\r\n\r\n(function() {\r\n var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };\r\n\r\n angular.module('uiGmapgoogle-maps').directive('uiGmapSearchBox', [\r\n 'uiGmapGoogleMapApi', 'uiGmapLogger', 'uiGmapSearchBoxParentModel', '$http', '$templateCache', '$compile', function(GoogleMapApi, Logger, SearchBoxParentModel, $http, $templateCache, $compile) {\r\n var SearchBox;\r\n SearchBox = (function() {\r\n SearchBox.prototype.require = 'ngModel';\r\n\r\n function SearchBox() {\r\n this.link = bind(this.link, this);\r\n this.$log = Logger;\r\n this.restrict = 'EMA';\r\n this.require = '^' + 'uiGmapGoogleMap';\r\n this.priority = -1;\r\n this.transclude = true;\r\n this.template = '';\r\n this.replace = true;\r\n this.scope = {\r\n template: '=template',\r\n events: '=events',\r\n position: '=?position',\r\n options: '=?options',\r\n parentdiv: '=?parentdiv',\r\n ngModel: \"=?\"\r\n };\r\n }\r\n\r\n SearchBox.prototype.link = function(scope, element, attrs, mapCtrl) {\r\n return GoogleMapApi.then((function(_this) {\r\n return function(maps) {\r\n if (scope.template == null) {\r\n $templateCache.put('uigmap-searchbox-default.tpl.html', '');\r\n scope.template = 'uigmap-searchbox-default.tpl.html';\r\n }\r\n return $http.get(scope.template, {\r\n cache: $templateCache\r\n }).success(function(template) {\r\n if (angular.isUndefined(scope.events)) {\r\n _this.$log.error('searchBox: the events property is required');\r\n return;\r\n }\r\n return mapCtrl.getScope().deferred.promise.then(function(map) {\r\n var ctrlPosition;\r\n ctrlPosition = angular.isDefined(scope.position) ? scope.position.toUpperCase().replace(/-/g, '_') : 'TOP_LEFT';\r\n if (!maps.ControlPosition[ctrlPosition]) {\r\n _this.$log.error('searchBox: invalid position property');\r\n return;\r\n }\r\n return new SearchBoxParentModel(scope, element, attrs, map, ctrlPosition, $compile(template)(scope));\r\n });\r\n });\r\n };\r\n })(this));\r\n };\r\n\r\n return SearchBox;\r\n\r\n })();\r\n return new SearchBox();\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;(function() {\r\n angular.module('uiGmapgoogle-maps').directive('uiGmapShow', [\r\n '$animate', 'uiGmapLogger', function($animate, $log) {\r\n return {\r\n scope: {\r\n 'uiGmapShow': '=',\r\n 'uiGmapAfterShow': '&',\r\n 'uiGmapAfterHide': '&'\r\n },\r\n link: function(scope, element) {\r\n var angular_post_1_3_handle, angular_pre_1_3_handle, handle;\r\n angular_post_1_3_handle = function(animateAction, cb) {\r\n return $animate[animateAction](element, 'ng-hide').then(function() {\r\n return cb();\r\n });\r\n };\r\n angular_pre_1_3_handle = function(animateAction, cb) {\r\n return $animate[animateAction](element, 'ng-hide', cb);\r\n };\r\n handle = function(animateAction, cb) {\r\n if (angular.version.major > 1) {\r\n return $log.error(\"uiGmapShow is not supported for Angular Major greater than 1.\\nYour Major is \" + angular.version.major + \"\\\"\");\r\n }\r\n if (angular.version.major === 1 && angular.version.minor < 3) {\r\n return angular_pre_1_3_handle(animateAction, cb);\r\n }\r\n return angular_post_1_3_handle(animateAction, cb);\r\n };\r\n return scope.$watch('uiGmapShow', function(show) {\r\n if (show) {\r\n handle('removeClass', scope.uiGmapAfterShow);\r\n }\r\n if (!show) {\r\n return handle('addClass', scope.uiGmapAfterHide);\r\n }\r\n });\r\n }\r\n };\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;\r\n/*\r\n@authors:\r\n- Nicholas McCready - https://twitter.com/nmccready\r\n */\r\n\r\n\r\n/*\r\nStreetViewPanorama Directive to care of basic initialization of StreetViewPanorama\r\n */\r\n\r\n(function() {\r\n angular.module('uiGmapgoogle-maps').directive('uiGmapStreetViewPanorama', [\r\n 'uiGmapGoogleMapApi', 'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapEventsHelper', function(GoogleMapApi, $log, GmapUtil, EventsHelper) {\r\n var name;\r\n name = 'uiGmapStreetViewPanorama';\r\n return {\r\n restrict: 'EMA',\r\n template: '
    ',\r\n replace: true,\r\n scope: {\r\n focalcoord: '=',\r\n radius: '=?',\r\n events: '=?',\r\n options: '=?',\r\n control: '=?',\r\n povoptions: '=?',\r\n imagestatus: '='\r\n },\r\n link: function(scope, element, attrs) {\r\n return GoogleMapApi.then((function(_this) {\r\n return function(maps) {\r\n var clean, create, didCreateOptionsFromDirective, firstTime, handleSettings, listeners, opts, pano, povOpts, sv;\r\n pano = void 0;\r\n sv = void 0;\r\n didCreateOptionsFromDirective = false;\r\n listeners = void 0;\r\n opts = null;\r\n povOpts = null;\r\n clean = function() {\r\n EventsHelper.removeEvents(listeners);\r\n if (pano != null) {\r\n pano.unbind('position');\r\n pano.setVisible(false);\r\n }\r\n if (sv != null) {\r\n if ((sv != null ? sv.setVisible : void 0) != null) {\r\n sv.setVisible(false);\r\n }\r\n return sv = void 0;\r\n }\r\n };\r\n handleSettings = function(perspectivePoint, focalPoint) {\r\n var heading;\r\n heading = google.maps.geometry.spherical.computeHeading(perspectivePoint, focalPoint);\r\n didCreateOptionsFromDirective = true;\r\n scope.radius = scope.radius || 50;\r\n povOpts = angular.extend({\r\n heading: heading,\r\n zoom: 1,\r\n pitch: 0\r\n }, scope.povoptions || {});\r\n opts = opts = angular.extend({\r\n navigationControl: false,\r\n addressControl: false,\r\n linksControl: false,\r\n position: perspectivePoint,\r\n pov: povOpts,\r\n visible: true\r\n }, scope.options || {});\r\n return didCreateOptionsFromDirective = false;\r\n };\r\n create = function() {\r\n var focalPoint;\r\n if (!scope.focalcoord) {\r\n $log.error(name + \": focalCoord needs to be defined\");\r\n return;\r\n }\r\n if (!scope.radius) {\r\n $log.error(name + \": needs a radius to set the camera view from its focal target.\");\r\n return;\r\n }\r\n clean();\r\n if (sv == null) {\r\n sv = new google.maps.StreetViewService();\r\n }\r\n if (scope.events) {\r\n listeners = EventsHelper.setEvents(sv, scope, scope);\r\n }\r\n focalPoint = GmapUtil.getCoords(scope.focalcoord);\r\n return sv.getPanoramaByLocation(focalPoint, scope.radius, function(streetViewPanoramaData, status) {\r\n var ele, perspectivePoint, ref;\r\n if (scope.imagestatus != null) {\r\n scope.imagestatus = status;\r\n }\r\n if (((ref = scope.events) != null ? ref.image_status_changed : void 0) != null) {\r\n scope.events.image_status_changed(sv, 'image_status_changed', scope, status);\r\n }\r\n if (status === \"OK\") {\r\n perspectivePoint = streetViewPanoramaData.location.latLng;\r\n handleSettings(perspectivePoint, focalPoint);\r\n ele = element[0];\r\n return pano = new google.maps.StreetViewPanorama(ele, opts);\r\n }\r\n });\r\n };\r\n if (scope.control != null) {\r\n scope.control.getOptions = function() {\r\n return opts;\r\n };\r\n scope.control.getPovOptions = function() {\r\n return povOpts;\r\n };\r\n scope.control.getGObject = function() {\r\n return sv;\r\n };\r\n scope.control.getGPano = function() {\r\n return pano;\r\n };\r\n }\r\n scope.$watch('options', function(newValue, oldValue) {\r\n if (newValue === oldValue || newValue === opts || didCreateOptionsFromDirective) {\r\n return;\r\n }\r\n return create();\r\n });\r\n firstTime = true;\r\n scope.$watch('focalcoord', function(newValue, oldValue) {\r\n if (newValue === oldValue && !firstTime) {\r\n return;\r\n }\r\n if (newValue == null) {\r\n return;\r\n }\r\n firstTime = false;\r\n return create();\r\n });\r\n return scope.$on('$destroy', function() {\r\n return clean();\r\n });\r\n };\r\n })(this));\r\n }\r\n };\r\n }\r\n ]);\r\n\r\n}).call(this);\r\n;angular.module('uiGmapgoogle-maps.wrapped')\r\n.service('uiGmapuuid', function() {\r\n //BEGIN REPLACE\r\n /*\r\n Version: core-1.0\r\n The MIT License: Copyright (c) 2012 LiosK.\r\n*/\r\nfunction UUID(){}UUID.generate=function(){var a=UUID._gri,b=UUID._ha;return b(a(32),8)+\"-\"+b(a(16),4)+\"-\"+b(16384|a(12),4)+\"-\"+b(32768|a(14),4)+\"-\"+b(a(48),12)};UUID._gri=function(a){return 0>a?NaN:30>=a?0|Math.random()*(1<=a?(0|1073741824*Math.random())+1073741824*(0|Math.random()*(1<>>=1,e+=e)d&1&&(c=e+c);return c};\r\n\r\n //END REPLACE\r\nreturn UUID;\r\n});\r\n;// wrap the utility libraries needed in ./lib\r\n// http://google-maps-utility-library-v3.googlecode.com/svn/\r\nangular.module('uiGmapgoogle-maps.wrapped')\r\n.service('uiGmapGoogleMapsUtilV3', function () {\r\n return {\r\n init: _.once(function () {\r\n //BEGIN REPLACE\r\n /**\r\n * @name InfoBox\r\n * @version 1.1.13 [March 19, 2014]\r\n * @author Gary Little (inspired by proof-of-concept code from Pamela Fox of Google)\r\n * @copyright Copyright 2010 Gary Little [gary at luxcentral.com]\r\n * @fileoverview InfoBox extends the Google Maps JavaScript API V3 OverlayView class.\r\n *

    \r\n * An InfoBox behaves like a google.maps.InfoWindow, but it supports several\r\n * additional properties for advanced styling. An InfoBox can also be used as a map label.\r\n *

    \r\n * An InfoBox also fires the same events as a google.maps.InfoWindow.\r\n */\r\n\r\n/*!\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n\r\n/*jslint browser:true */\r\n/*global google */\r\n\r\n/**\r\n * @name InfoBoxOptions\r\n * @class This class represents the optional parameter passed to the {@link InfoBox} constructor.\r\n * @property {string|Node} content The content of the InfoBox (plain text or an HTML DOM node).\r\n * @property {boolean} [disableAutoPan=false] Disable auto-pan on open.\r\n * @property {number} maxWidth The maximum width (in pixels) of the InfoBox. Set to 0 if no maximum.\r\n * @property {Size} pixelOffset The offset (in pixels) from the top left corner of the InfoBox\r\n * (or the bottom left corner if the alignBottom property is true)\r\n * to the map pixel corresponding to position.\r\n * @property {LatLng} position The geographic location at which to display the InfoBox.\r\n * @property {number} zIndex The CSS z-index style value for the InfoBox.\r\n * Note: This value overrides a zIndex setting specified in the boxStyle property.\r\n * @property {string} [boxClass=\"infoBox\"] The name of the CSS class defining the styles for the InfoBox container.\r\n * @property {Object} [boxStyle] An object literal whose properties define specific CSS\r\n * style values to be applied to the InfoBox. Style values defined here override those that may\r\n * be defined in the boxClass style sheet. If this property is changed after the\r\n * InfoBox has been created, all previously set styles (except those defined in the style sheet)\r\n * are removed from the InfoBox before the new style values are applied.\r\n * @property {string} closeBoxMargin The CSS margin style value for the close box.\r\n * The default is \"2px\" (a 2-pixel margin on all sides).\r\n * @property {string} closeBoxURL The URL of the image representing the close box.\r\n * Note: The default is the URL for Google's standard close box.\r\n * Set this property to \"\" if no close box is required.\r\n * @property {Size} infoBoxClearance Minimum offset (in pixels) from the InfoBox to the\r\n * map edge after an auto-pan.\r\n * @property {boolean} [isHidden=false] Hide the InfoBox on open.\r\n * [Deprecated in favor of the visible property.]\r\n * @property {boolean} [visible=true] Show the InfoBox on open.\r\n * @property {boolean} alignBottom Align the bottom left corner of the InfoBox to the position\r\n * location (default is false which means that the top left corner of the InfoBox is aligned).\r\n * @property {string} pane The pane where the InfoBox is to appear (default is \"floatPane\").\r\n * Set the pane to \"mapPane\" if the InfoBox is being used as a map label.\r\n * Valid pane names are the property names for the google.maps.MapPanes object.\r\n * @property {boolean} enableEventPropagation Propagate mousedown, mousemove, mouseover, mouseout,\r\n * mouseup, click, dblclick, touchstart, touchend, touchmove, and contextmenu events in the InfoBox\r\n * (default is false to mimic the behavior of a google.maps.InfoWindow). Set\r\n * this property to true if the InfoBox is being used as a map label.\r\n */\r\n\r\n/**\r\n * Creates an InfoBox with the options specified in {@link InfoBoxOptions}.\r\n * Call InfoBox.open to add the box to the map.\r\n * @constructor\r\n * @param {InfoBoxOptions} [opt_opts]\r\n */\r\nfunction InfoBox(opt_opts) {\r\n\r\n opt_opts = opt_opts || {};\r\n\r\n google.maps.OverlayView.apply(this, arguments);\r\n\r\n // Standard options (in common with google.maps.InfoWindow):\r\n //\r\n this.content_ = opt_opts.content || \"\";\r\n this.disableAutoPan_ = opt_opts.disableAutoPan || false;\r\n this.maxWidth_ = opt_opts.maxWidth || 0;\r\n this.pixelOffset_ = opt_opts.pixelOffset || new google.maps.Size(0, 0);\r\n this.position_ = opt_opts.position || new google.maps.LatLng(0, 0);\r\n this.zIndex_ = opt_opts.zIndex || null;\r\n\r\n // Additional options (unique to InfoBox):\r\n //\r\n this.boxClass_ = opt_opts.boxClass || \"infoBox\";\r\n this.boxStyle_ = opt_opts.boxStyle || {};\r\n this.closeBoxMargin_ = opt_opts.closeBoxMargin || \"2px\";\r\n this.closeBoxURL_ = opt_opts.closeBoxURL || \"http://www.google.com/intl/en_us/mapfiles/close.gif\";\r\n if (opt_opts.closeBoxURL === \"\") {\r\n this.closeBoxURL_ = \"\";\r\n }\r\n this.infoBoxClearance_ = opt_opts.infoBoxClearance || new google.maps.Size(1, 1);\r\n\r\n if (typeof opt_opts.visible === \"undefined\") {\r\n if (typeof opt_opts.isHidden === \"undefined\") {\r\n opt_opts.visible = true;\r\n } else {\r\n opt_opts.visible = !opt_opts.isHidden;\r\n }\r\n }\r\n this.isHidden_ = !opt_opts.visible;\r\n\r\n this.alignBottom_ = opt_opts.alignBottom || false;\r\n this.pane_ = opt_opts.pane || \"floatPane\";\r\n this.enableEventPropagation_ = opt_opts.enableEventPropagation || false;\r\n\r\n this.div_ = null;\r\n this.closeListener_ = null;\r\n this.moveListener_ = null;\r\n this.contextListener_ = null;\r\n this.eventListeners_ = null;\r\n this.fixedWidthSet_ = null;\r\n}\r\n\r\n/* InfoBox extends OverlayView in the Google Maps API v3.\r\n */\r\nInfoBox.prototype = new google.maps.OverlayView();\r\n\r\n/**\r\n * Creates the DIV representing the InfoBox.\r\n * @private\r\n */\r\nInfoBox.prototype.createInfoBoxDiv_ = function () {\r\n\r\n var i;\r\n var events;\r\n var bw;\r\n var me = this;\r\n\r\n // This handler prevents an event in the InfoBox from being passed on to the map.\r\n //\r\n var cancelHandler = function (e) {\r\n e.cancelBubble = true;\r\n if (e.stopPropagation) {\r\n e.stopPropagation();\r\n }\r\n };\r\n\r\n // This handler ignores the current event in the InfoBox and conditionally prevents\r\n // the event from being passed on to the map. It is used for the contextmenu event.\r\n //\r\n var ignoreHandler = function (e) {\r\n\r\n e.returnValue = false;\r\n\r\n if (e.preventDefault) {\r\n\r\n e.preventDefault();\r\n }\r\n\r\n if (!me.enableEventPropagation_) {\r\n\r\n cancelHandler(e);\r\n }\r\n };\r\n\r\n if (!this.div_) {\r\n\r\n this.div_ = document.createElement(\"div\");\r\n\r\n this.setBoxStyle_();\r\n\r\n if (typeof this.content_.nodeType === \"undefined\") {\r\n this.div_.innerHTML = this.getCloseBoxImg_() + this.content_;\r\n } else {\r\n this.div_.innerHTML = this.getCloseBoxImg_();\r\n this.div_.appendChild(this.content_);\r\n }\r\n\r\n // Add the InfoBox DIV to the DOM\r\n this.getPanes()[this.pane_].appendChild(this.div_);\r\n\r\n this.addClickHandler_();\r\n\r\n if (this.div_.style.width) {\r\n\r\n this.fixedWidthSet_ = true;\r\n\r\n } else {\r\n\r\n if (this.maxWidth_ !== 0 && this.div_.offsetWidth > this.maxWidth_) {\r\n\r\n this.div_.style.width = this.maxWidth_;\r\n this.div_.style.overflow = \"auto\";\r\n this.fixedWidthSet_ = true;\r\n\r\n } else { // The following code is needed to overcome problems with MSIE\r\n\r\n bw = this.getBoxWidths_();\r\n\r\n this.div_.style.width = (this.div_.offsetWidth - bw.left - bw.right) + \"px\";\r\n this.fixedWidthSet_ = false;\r\n }\r\n }\r\n\r\n this.panBox_(this.disableAutoPan_);\r\n\r\n if (!this.enableEventPropagation_) {\r\n\r\n this.eventListeners_ = [];\r\n\r\n // Cancel event propagation.\r\n //\r\n // Note: mousemove not included (to resolve Issue 152)\r\n events = [\"mousedown\", \"mouseover\", \"mouseout\", \"mouseup\",\r\n \"click\", \"dblclick\", \"touchstart\", \"touchend\", \"touchmove\"];\r\n\r\n for (i = 0; i < events.length; i++) {\r\n\r\n this.eventListeners_.push(google.maps.event.addDomListener(this.div_, events[i], cancelHandler));\r\n }\r\n \r\n // Workaround for Google bug that causes the cursor to change to a pointer\r\n // when the mouse moves over a marker underneath InfoBox.\r\n this.eventListeners_.push(google.maps.event.addDomListener(this.div_, \"mouseover\", function (e) {\r\n this.style.cursor = \"default\";\r\n }));\r\n }\r\n\r\n this.contextListener_ = google.maps.event.addDomListener(this.div_, \"contextmenu\", ignoreHandler);\r\n\r\n /**\r\n * This event is fired when the DIV containing the InfoBox's content is attached to the DOM.\r\n * @name InfoBox#domready\r\n * @event\r\n */\r\n google.maps.event.trigger(this, \"domready\");\r\n }\r\n};\r\n\r\n/**\r\n * Returns the HTML tag for the close box.\r\n * @private\r\n */\r\nInfoBox.prototype.getCloseBoxImg_ = function () {\r\n\r\n var img = \"\";\r\n\r\n if (this.closeBoxURL_ !== \"\") {\r\n\r\n img = \"\";\r\n }\r\n\r\n return img;\r\n};\r\n\r\n/**\r\n * Adds the click handler to the InfoBox close box.\r\n * @private\r\n */\r\nInfoBox.prototype.addClickHandler_ = function () {\r\n\r\n var closeBox;\r\n\r\n if (this.closeBoxURL_ !== \"\") {\r\n\r\n closeBox = this.div_.firstChild;\r\n this.closeListener_ = google.maps.event.addDomListener(closeBox, \"click\", this.getCloseClickHandler_());\r\n\r\n } else {\r\n\r\n this.closeListener_ = null;\r\n }\r\n};\r\n\r\n/**\r\n * Returns the function to call when the user clicks the close box of an InfoBox.\r\n * @private\r\n */\r\nInfoBox.prototype.getCloseClickHandler_ = function () {\r\n\r\n var me = this;\r\n\r\n return function (e) {\r\n\r\n // 1.0.3 fix: Always prevent propagation of a close box click to the map:\r\n e.cancelBubble = true;\r\n\r\n if (e.stopPropagation) {\r\n\r\n e.stopPropagation();\r\n }\r\n\r\n /**\r\n * This event is fired when the InfoBox's close box is clicked.\r\n * @name InfoBox#closeclick\r\n * @event\r\n */\r\n google.maps.event.trigger(me, \"closeclick\");\r\n\r\n me.close();\r\n };\r\n};\r\n\r\n/**\r\n * Pans the map so that the InfoBox appears entirely within the map's visible area.\r\n * @private\r\n */\r\nInfoBox.prototype.panBox_ = function (disablePan) {\r\n\r\n var map;\r\n var bounds;\r\n var xOffset = 0, yOffset = 0;\r\n\r\n if (!disablePan) {\r\n\r\n map = this.getMap();\r\n\r\n if (map instanceof google.maps.Map) { // Only pan if attached to map, not panorama\r\n\r\n if (!map.getBounds().contains(this.position_)) {\r\n // Marker not in visible area of map, so set center\r\n // of map to the marker position first.\r\n map.setCenter(this.position_);\r\n }\r\n\r\n bounds = map.getBounds();\r\n\r\n var mapDiv = map.getDiv();\r\n var mapWidth = mapDiv.offsetWidth;\r\n var mapHeight = mapDiv.offsetHeight;\r\n var iwOffsetX = this.pixelOffset_.width;\r\n var iwOffsetY = this.pixelOffset_.height;\r\n var iwWidth = this.div_.offsetWidth;\r\n var iwHeight = this.div_.offsetHeight;\r\n var padX = this.infoBoxClearance_.width;\r\n var padY = this.infoBoxClearance_.height;\r\n var pixPosition = this.getProjection().fromLatLngToContainerPixel(this.position_);\r\n\r\n if (pixPosition.x < (-iwOffsetX + padX)) {\r\n xOffset = pixPosition.x + iwOffsetX - padX;\r\n } else if ((pixPosition.x + iwWidth + iwOffsetX + padX) > mapWidth) {\r\n xOffset = pixPosition.x + iwWidth + iwOffsetX + padX - mapWidth;\r\n }\r\n if (this.alignBottom_) {\r\n if (pixPosition.y < (-iwOffsetY + padY + iwHeight)) {\r\n yOffset = pixPosition.y + iwOffsetY - padY - iwHeight;\r\n } else if ((pixPosition.y + iwOffsetY + padY) > mapHeight) {\r\n yOffset = pixPosition.y + iwOffsetY + padY - mapHeight;\r\n }\r\n } else {\r\n if (pixPosition.y < (-iwOffsetY + padY)) {\r\n yOffset = pixPosition.y + iwOffsetY - padY;\r\n } else if ((pixPosition.y + iwHeight + iwOffsetY + padY) > mapHeight) {\r\n yOffset = pixPosition.y + iwHeight + iwOffsetY + padY - mapHeight;\r\n }\r\n }\r\n\r\n if (!(xOffset === 0 && yOffset === 0)) {\r\n\r\n // Move the map to the shifted center.\r\n //\r\n var c = map.getCenter();\r\n map.panBy(xOffset, yOffset);\r\n }\r\n }\r\n }\r\n};\r\n\r\n/**\r\n * Sets the style of the InfoBox by setting the style sheet and applying\r\n * other specific styles requested.\r\n * @private\r\n */\r\nInfoBox.prototype.setBoxStyle_ = function () {\r\n\r\n var i, boxStyle;\r\n\r\n if (this.div_) {\r\n\r\n // Apply style values from the style sheet defined in the boxClass parameter:\r\n this.div_.className = this.boxClass_;\r\n\r\n // Clear existing inline style values:\r\n this.div_.style.cssText = \"\";\r\n\r\n // Apply style values defined in the boxStyle parameter:\r\n boxStyle = this.boxStyle_;\r\n for (i in boxStyle) {\r\n\r\n if (boxStyle.hasOwnProperty(i)) {\r\n\r\n this.div_.style[i] = boxStyle[i];\r\n }\r\n }\r\n\r\n // Fix for iOS disappearing InfoBox problem.\r\n // See http://stackoverflow.com/questions/9229535/google-maps-markers-disappear-at-certain-zoom-level-only-on-iphone-ipad\r\n this.div_.style.WebkitTransform = \"translateZ(0)\";\r\n\r\n // Fix up opacity style for benefit of MSIE:\r\n //\r\n if (typeof this.div_.style.opacity !== \"undefined\" && this.div_.style.opacity !== \"\") {\r\n // See http://www.quirksmode.org/css/opacity.html\r\n this.div_.style.MsFilter = \"\\\"progid:DXImageTransform.Microsoft.Alpha(Opacity=\" + (this.div_.style.opacity * 100) + \")\\\"\";\r\n this.div_.style.filter = \"alpha(opacity=\" + (this.div_.style.opacity * 100) + \")\";\r\n }\r\n\r\n // Apply required styles:\r\n //\r\n this.div_.style.position = \"absolute\";\r\n this.div_.style.visibility = 'hidden';\r\n if (this.zIndex_ !== null) {\r\n\r\n this.div_.style.zIndex = this.zIndex_;\r\n }\r\n }\r\n};\r\n\r\n/**\r\n * Get the widths of the borders of the InfoBox.\r\n * @private\r\n * @return {Object} widths object (top, bottom left, right)\r\n */\r\nInfoBox.prototype.getBoxWidths_ = function () {\r\n\r\n var computedStyle;\r\n var bw = {top: 0, bottom: 0, left: 0, right: 0};\r\n var box = this.div_;\r\n\r\n if (document.defaultView && document.defaultView.getComputedStyle) {\r\n\r\n computedStyle = box.ownerDocument.defaultView.getComputedStyle(box, \"\");\r\n\r\n if (computedStyle) {\r\n\r\n // The computed styles are always in pixel units (good!)\r\n bw.top = parseInt(computedStyle.borderTopWidth, 10) || 0;\r\n bw.bottom = parseInt(computedStyle.borderBottomWidth, 10) || 0;\r\n bw.left = parseInt(computedStyle.borderLeftWidth, 10) || 0;\r\n bw.right = parseInt(computedStyle.borderRightWidth, 10) || 0;\r\n }\r\n\r\n } else if (document.documentElement.currentStyle) { // MSIE\r\n\r\n if (box.currentStyle) {\r\n\r\n // The current styles may not be in pixel units, but assume they are (bad!)\r\n bw.top = parseInt(box.currentStyle.borderTopWidth, 10) || 0;\r\n bw.bottom = parseInt(box.currentStyle.borderBottomWidth, 10) || 0;\r\n bw.left = parseInt(box.currentStyle.borderLeftWidth, 10) || 0;\r\n bw.right = parseInt(box.currentStyle.borderRightWidth, 10) || 0;\r\n }\r\n }\r\n\r\n return bw;\r\n};\r\n\r\n/**\r\n * Invoked when close is called. Do not call it directly.\r\n */\r\nInfoBox.prototype.onRemove = function () {\r\n\r\n if (this.div_) {\r\n\r\n this.div_.parentNode.removeChild(this.div_);\r\n this.div_ = null;\r\n }\r\n};\r\n\r\n/**\r\n * Draws the InfoBox based on the current map projection and zoom level.\r\n */\r\nInfoBox.prototype.draw = function () {\r\n\r\n this.createInfoBoxDiv_();\r\n\r\n var pixPosition = this.getProjection().fromLatLngToDivPixel(this.position_);\r\n\r\n this.div_.style.left = (pixPosition.x + this.pixelOffset_.width) + \"px\";\r\n \r\n if (this.alignBottom_) {\r\n this.div_.style.bottom = -(pixPosition.y + this.pixelOffset_.height) + \"px\";\r\n } else {\r\n this.div_.style.top = (pixPosition.y + this.pixelOffset_.height) + \"px\";\r\n }\r\n\r\n if (this.isHidden_) {\r\n\r\n this.div_.style.visibility = \"hidden\";\r\n\r\n } else {\r\n\r\n this.div_.style.visibility = \"visible\";\r\n }\r\n};\r\n\r\n/**\r\n * Sets the options for the InfoBox. Note that changes to the maxWidth,\r\n * closeBoxMargin, closeBoxURL, and enableEventPropagation\r\n * properties have no affect until the current InfoBox is closed and a new one\r\n * is opened.\r\n * @param {InfoBoxOptions} opt_opts\r\n */\r\nInfoBox.prototype.setOptions = function (opt_opts) {\r\n if (typeof opt_opts.boxClass !== \"undefined\") { // Must be first\r\n\r\n this.boxClass_ = opt_opts.boxClass;\r\n this.setBoxStyle_();\r\n }\r\n if (typeof opt_opts.boxStyle !== \"undefined\") { // Must be second\r\n\r\n this.boxStyle_ = opt_opts.boxStyle;\r\n this.setBoxStyle_();\r\n }\r\n if (typeof opt_opts.content !== \"undefined\") {\r\n\r\n this.setContent(opt_opts.content);\r\n }\r\n if (typeof opt_opts.disableAutoPan !== \"undefined\") {\r\n\r\n this.disableAutoPan_ = opt_opts.disableAutoPan;\r\n }\r\n if (typeof opt_opts.maxWidth !== \"undefined\") {\r\n\r\n this.maxWidth_ = opt_opts.maxWidth;\r\n }\r\n if (typeof opt_opts.pixelOffset !== \"undefined\") {\r\n\r\n this.pixelOffset_ = opt_opts.pixelOffset;\r\n }\r\n if (typeof opt_opts.alignBottom !== \"undefined\") {\r\n\r\n this.alignBottom_ = opt_opts.alignBottom;\r\n }\r\n if (typeof opt_opts.position !== \"undefined\") {\r\n\r\n this.setPosition(opt_opts.position);\r\n }\r\n if (typeof opt_opts.zIndex !== \"undefined\") {\r\n\r\n this.setZIndex(opt_opts.zIndex);\r\n }\r\n if (typeof opt_opts.closeBoxMargin !== \"undefined\") {\r\n\r\n this.closeBoxMargin_ = opt_opts.closeBoxMargin;\r\n }\r\n if (typeof opt_opts.closeBoxURL !== \"undefined\") {\r\n\r\n this.closeBoxURL_ = opt_opts.closeBoxURL;\r\n }\r\n if (typeof opt_opts.infoBoxClearance !== \"undefined\") {\r\n\r\n this.infoBoxClearance_ = opt_opts.infoBoxClearance;\r\n }\r\n if (typeof opt_opts.isHidden !== \"undefined\") {\r\n\r\n this.isHidden_ = opt_opts.isHidden;\r\n }\r\n if (typeof opt_opts.visible !== \"undefined\") {\r\n\r\n this.isHidden_ = !opt_opts.visible;\r\n }\r\n if (typeof opt_opts.enableEventPropagation !== \"undefined\") {\r\n\r\n this.enableEventPropagation_ = opt_opts.enableEventPropagation;\r\n }\r\n\r\n if (this.div_) {\r\n\r\n this.draw();\r\n }\r\n};\r\n\r\n/**\r\n * Sets the content of the InfoBox.\r\n * The content can be plain text or an HTML DOM node.\r\n * @param {string|Node} content\r\n */\r\nInfoBox.prototype.setContent = function (content) {\r\n this.content_ = content;\r\n\r\n if (this.div_) {\r\n\r\n if (this.closeListener_) {\r\n\r\n google.maps.event.removeListener(this.closeListener_);\r\n this.closeListener_ = null;\r\n }\r\n\r\n // Odd code required to make things work with MSIE.\r\n //\r\n if (!this.fixedWidthSet_) {\r\n\r\n this.div_.style.width = \"\";\r\n }\r\n\r\n if (typeof content.nodeType === \"undefined\") {\r\n this.div_.innerHTML = this.getCloseBoxImg_() + content;\r\n } else {\r\n this.div_.innerHTML = this.getCloseBoxImg_();\r\n this.div_.appendChild(content);\r\n }\r\n\r\n // Perverse code required to make things work with MSIE.\r\n // (Ensures the close box does, in fact, float to the right.)\r\n //\r\n if (!this.fixedWidthSet_) {\r\n this.div_.style.width = this.div_.offsetWidth + \"px\";\r\n if (typeof content.nodeType === \"undefined\") {\r\n this.div_.innerHTML = this.getCloseBoxImg_() + content;\r\n } else {\r\n this.div_.innerHTML = this.getCloseBoxImg_();\r\n this.div_.appendChild(content);\r\n }\r\n }\r\n\r\n this.addClickHandler_();\r\n }\r\n\r\n /**\r\n * This event is fired when the content of the InfoBox changes.\r\n * @name InfoBox#content_changed\r\n * @event\r\n */\r\n google.maps.event.trigger(this, \"content_changed\");\r\n};\r\n\r\n/**\r\n * Sets the geographic location of the InfoBox.\r\n * @param {LatLng} latlng\r\n */\r\nInfoBox.prototype.setPosition = function (latlng) {\r\n\r\n this.position_ = latlng;\r\n\r\n if (this.div_) {\r\n\r\n this.draw();\r\n }\r\n\r\n /**\r\n * This event is fired when the position of the InfoBox changes.\r\n * @name InfoBox#position_changed\r\n * @event\r\n */\r\n google.maps.event.trigger(this, \"position_changed\");\r\n};\r\n\r\n/**\r\n * Sets the zIndex style for the InfoBox.\r\n * @param {number} index\r\n */\r\nInfoBox.prototype.setZIndex = function (index) {\r\n\r\n this.zIndex_ = index;\r\n\r\n if (this.div_) {\r\n\r\n this.div_.style.zIndex = index;\r\n }\r\n\r\n /**\r\n * This event is fired when the zIndex of the InfoBox changes.\r\n * @name InfoBox#zindex_changed\r\n * @event\r\n */\r\n google.maps.event.trigger(this, \"zindex_changed\");\r\n};\r\n\r\n/**\r\n * Sets the visibility of the InfoBox.\r\n * @param {boolean} isVisible\r\n */\r\nInfoBox.prototype.setVisible = function (isVisible) {\r\n\r\n this.isHidden_ = !isVisible;\r\n if (this.div_) {\r\n this.div_.style.visibility = (this.isHidden_ ? \"hidden\" : \"visible\");\r\n }\r\n};\r\n\r\n/**\r\n * Returns the content of the InfoBox.\r\n * @returns {string}\r\n */\r\nInfoBox.prototype.getContent = function () {\r\n\r\n return this.content_;\r\n};\r\n\r\n/**\r\n * Returns the geographic location of the InfoBox.\r\n * @returns {LatLng}\r\n */\r\nInfoBox.prototype.getPosition = function () {\r\n\r\n return this.position_;\r\n};\r\n\r\n/**\r\n * Returns the zIndex for the InfoBox.\r\n * @returns {number}\r\n */\r\nInfoBox.prototype.getZIndex = function () {\r\n\r\n return this.zIndex_;\r\n};\r\n\r\n/**\r\n * Returns a flag indicating whether the InfoBox is visible.\r\n * @returns {boolean}\r\n */\r\nInfoBox.prototype.getVisible = function () {\r\n\r\n var isVisible;\r\n\r\n if ((typeof this.getMap() === \"undefined\") || (this.getMap() === null)) {\r\n isVisible = false;\r\n } else {\r\n isVisible = !this.isHidden_;\r\n }\r\n return isVisible;\r\n};\r\n\r\n/**\r\n * Shows the InfoBox. [Deprecated; use setVisible instead.]\r\n */\r\nInfoBox.prototype.show = function () {\r\n\r\n this.isHidden_ = false;\r\n if (this.div_) {\r\n this.div_.style.visibility = \"visible\";\r\n }\r\n};\r\n\r\n/**\r\n * Hides the InfoBox. [Deprecated; use setVisible instead.]\r\n */\r\nInfoBox.prototype.hide = function () {\r\n\r\n this.isHidden_ = true;\r\n if (this.div_) {\r\n this.div_.style.visibility = \"hidden\";\r\n }\r\n};\r\n\r\n/**\r\n * Adds the InfoBox to the specified map or Street View panorama. If anchor\r\n * (usually a google.maps.Marker) is specified, the position\r\n * of the InfoBox is set to the position of the anchor. If the\r\n * anchor is dragged to a new location, the InfoBox moves as well.\r\n * @param {Map|StreetViewPanorama} map\r\n * @param {MVCObject} [anchor]\r\n */\r\nInfoBox.prototype.open = function (map, anchor) {\r\n\r\n var me = this;\r\n\r\n if (anchor) {\r\n\r\n this.position_ = anchor.getPosition();\r\n this.moveListener_ = google.maps.event.addListener(anchor, \"position_changed\", function () {\r\n me.setPosition(this.getPosition());\r\n });\r\n }\r\n\r\n this.setMap(map);\r\n\r\n if (this.div_) {\r\n\r\n this.panBox_();\r\n }\r\n};\r\n\r\n/**\r\n * Removes the InfoBox from the map.\r\n */\r\nInfoBox.prototype.close = function () {\r\n\r\n var i;\r\n\r\n if (this.closeListener_) {\r\n\r\n google.maps.event.removeListener(this.closeListener_);\r\n this.closeListener_ = null;\r\n }\r\n\r\n if (this.eventListeners_) {\r\n \r\n for (i = 0; i < this.eventListeners_.length; i++) {\r\n\r\n google.maps.event.removeListener(this.eventListeners_[i]);\r\n }\r\n this.eventListeners_ = null;\r\n }\r\n\r\n if (this.moveListener_) {\r\n\r\n google.maps.event.removeListener(this.moveListener_);\r\n this.moveListener_ = null;\r\n }\r\n\r\n if (this.contextListener_) {\r\n\r\n google.maps.event.removeListener(this.contextListener_);\r\n this.contextListener_ = null;\r\n }\r\n\r\n this.setMap(null);\r\n};\r\n\r\n/**\r\n * @name KeyDragZoom for V3\r\n * @version 2.0.9 [December 17, 2012] NOT YET RELEASED\r\n * @author: Nianwei Liu [nianwei at gmail dot com] & Gary Little [gary at luxcentral dot com]\r\n * @fileoverview This library adds a drag zoom capability to a V3 Google map.\r\n * When drag zoom is enabled, holding down a designated hot key (shift | ctrl | alt)\r\n * while dragging a box around an area of interest will zoom the map in to that area when\r\n * the mouse button is released. Optionally, a visual control can also be supplied for turning\r\n * a drag zoom operation on and off.\r\n * Only one line of code is needed: google.maps.Map.enableKeyDragZoom();\r\n *

    \r\n * NOTE: Do not use Ctrl as the hot key with Google Maps JavaScript API V3 since, unlike with V2,\r\n * it causes a context menu to appear when running on the Macintosh.\r\n *

    \r\n * Note that if the map's container has a border around it, the border widths must be specified\r\n * in pixel units (or as thin, medium, or thick). This is required because of an MSIE limitation.\r\n *

    NL: 2009-05-28: initial port to core API V3.\r\n *
    NL: 2009-11-02: added a temp fix for -moz-transform for FF3.5.x using code from Paul Kulchenko (http://notebook.kulchenko.com/maps/gridmove).\r\n *
    NL: 2010-02-02: added a fix for IE flickering on divs onmousemove, caused by scroll value when get mouse position.\r\n *
    GL: 2010-06-15: added a visual control option.\r\n */\r\n/*!\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n(function () {\r\n /*jslint browser:true */\r\n /*global window,google */\r\n /* Utility functions use \"var funName=function()\" syntax to allow use of the */\r\n /* Dean Edwards Packer compression tool (with Shrink variables, without Base62 encode). */\r\n\r\n /**\r\n * Converts \"thin\", \"medium\", and \"thick\" to pixel widths\r\n * in an MSIE environment. Not called for other browsers\r\n * because getComputedStyle() returns pixel widths automatically.\r\n * @param {string} widthValue The value of the border width parameter.\r\n */\r\n var toPixels = function (widthValue) {\r\n var px;\r\n switch (widthValue) {\r\n case \"thin\":\r\n px = \"2px\";\r\n break;\r\n case \"medium\":\r\n px = \"4px\";\r\n break;\r\n case \"thick\":\r\n px = \"6px\";\r\n break;\r\n default:\r\n px = widthValue;\r\n }\r\n return px;\r\n };\r\n /**\r\n * Get the widths of the borders of an HTML element.\r\n *\r\n * @param {Node} h The HTML element.\r\n * @return {Object} The width object {top, bottom left, right}.\r\n */\r\n var getBorderWidths = function (h) {\r\n var computedStyle;\r\n var bw = {};\r\n if (document.defaultView && document.defaultView.getComputedStyle) {\r\n computedStyle = h.ownerDocument.defaultView.getComputedStyle(h, \"\");\r\n if (computedStyle) {\r\n // The computed styles are always in pixel units (good!)\r\n bw.top = parseInt(computedStyle.borderTopWidth, 10) || 0;\r\n bw.bottom = parseInt(computedStyle.borderBottomWidth, 10) || 0;\r\n bw.left = parseInt(computedStyle.borderLeftWidth, 10) || 0;\r\n bw.right = parseInt(computedStyle.borderRightWidth, 10) || 0;\r\n return bw;\r\n }\r\n } else if (document.documentElement.currentStyle) { // MSIE\r\n if (h.currentStyle) {\r\n // The current styles may not be in pixel units so try to convert (bad!)\r\n bw.top = parseInt(toPixels(h.currentStyle.borderTopWidth), 10) || 0;\r\n bw.bottom = parseInt(toPixels(h.currentStyle.borderBottomWidth), 10) || 0;\r\n bw.left = parseInt(toPixels(h.currentStyle.borderLeftWidth), 10) || 0;\r\n bw.right = parseInt(toPixels(h.currentStyle.borderRightWidth), 10) || 0;\r\n return bw;\r\n }\r\n }\r\n // Shouldn't get this far for any modern browser\r\n bw.top = parseInt(h.style[\"border-top-width\"], 10) || 0;\r\n bw.bottom = parseInt(h.style[\"border-bottom-width\"], 10) || 0;\r\n bw.left = parseInt(h.style[\"border-left-width\"], 10) || 0;\r\n bw.right = parseInt(h.style[\"border-right-width\"], 10) || 0;\r\n return bw;\r\n };\r\n\r\n // Page scroll values for use by getMousePosition. To prevent flickering on MSIE\r\n // they are calculated only when the document actually scrolls, not every time the\r\n // mouse moves (as they would be if they were calculated inside getMousePosition).\r\n var scroll = {\r\n x: 0,\r\n y: 0\r\n };\r\n var getScrollValue = function (e) {\r\n scroll.x = (typeof document.documentElement.scrollLeft !== \"undefined\" ? document.documentElement.scrollLeft : document.body.scrollLeft);\r\n scroll.y = (typeof document.documentElement.scrollTop !== \"undefined\" ? document.documentElement.scrollTop : document.body.scrollTop);\r\n };\r\n getScrollValue();\r\n\r\n /**\r\n * Get the position of the mouse relative to the document.\r\n * @param {Event} e The mouse event.\r\n * @return {Object} The position object {left, top}.\r\n */\r\n var getMousePosition = function (e) {\r\n var posX = 0, posY = 0;\r\n e = e || window.event;\r\n if (typeof e.pageX !== \"undefined\") {\r\n posX = e.pageX;\r\n posY = e.pageY;\r\n } else if (typeof e.clientX !== \"undefined\") { // MSIE\r\n posX = e.clientX + scroll.x;\r\n posY = e.clientY + scroll.y;\r\n }\r\n return {\r\n left: posX,\r\n top: posY\r\n };\r\n };\r\n /**\r\n * Get the position of an HTML element relative to the document.\r\n * @param {Node} h The HTML element.\r\n * @return {Object} The position object {left, top}.\r\n */\r\n var getElementPosition = function (h) {\r\n var posX = h.offsetLeft;\r\n var posY = h.offsetTop;\r\n var parent = h.offsetParent;\r\n // Add offsets for all ancestors in the hierarchy\r\n while (parent !== null) {\r\n // Adjust for scrolling elements which may affect the map position.\r\n //\r\n // See http://www.howtocreate.co.uk/tutorials/javascript/browserspecific\r\n //\r\n // \"...make sure that every element [on a Web page] with an overflow\r\n // of anything other than visible also has a position style set to\r\n // something other than the default static...\"\r\n if (parent !== document.body && parent !== document.documentElement) {\r\n posX -= parent.scrollLeft;\r\n posY -= parent.scrollTop;\r\n }\r\n // See http://groups.google.com/group/google-maps-js-api-v3/browse_thread/thread/4cb86c0c1037a5e5\r\n // Example: http://notebook.kulchenko.com/maps/gridmove\r\n var m = parent;\r\n // This is the \"normal\" way to get offset information:\r\n var moffx = m.offsetLeft;\r\n var moffy = m.offsetTop;\r\n // This covers those cases where a transform is used:\r\n if (!moffx && !moffy && window.getComputedStyle) {\r\n var matrix = document.defaultView.getComputedStyle(m, null).MozTransform ||\r\n document.defaultView.getComputedStyle(m, null).WebkitTransform;\r\n if (matrix) {\r\n if (typeof matrix === \"string\") {\r\n var parms = matrix.split(\",\");\r\n moffx += parseInt(parms[4], 10) || 0;\r\n moffy += parseInt(parms[5], 10) || 0;\r\n }\r\n }\r\n }\r\n posX += moffx;\r\n posY += moffy;\r\n parent = parent.offsetParent;\r\n }\r\n return {\r\n left: posX,\r\n top: posY\r\n };\r\n };\r\n /**\r\n * Set the properties of an object to those from another object.\r\n * @param {Object} obj The target object.\r\n * @param {Object} vals The source object.\r\n */\r\n var setVals = function (obj, vals) {\r\n if (obj && vals) {\r\n for (var x in vals) {\r\n if (vals.hasOwnProperty(x)) {\r\n obj[x] = vals[x];\r\n }\r\n }\r\n }\r\n return obj;\r\n };\r\n /**\r\n * Set the opacity. If op is not passed in, this function just performs an MSIE fix.\r\n * @param {Node} h The HTML element.\r\n * @param {number} op The opacity value (0-1).\r\n */\r\n var setOpacity = function (h, op) {\r\n if (typeof op !== \"undefined\") {\r\n h.style.opacity = op;\r\n }\r\n if (typeof h.style.opacity !== \"undefined\" && h.style.opacity !== \"\") {\r\n h.style.filter = \"alpha(opacity=\" + (h.style.opacity * 100) + \")\";\r\n }\r\n };\r\n /**\r\n * @name KeyDragZoomOptions\r\n * @class This class represents the optional parameter passed into google.maps.Map.enableKeyDragZoom.\r\n * @property {string} [key=\"shift\"] The hot key to hold down to activate a drag zoom, shift | ctrl | alt.\r\n * NOTE: Do not use Ctrl as the hot key with Google Maps JavaScript API V3 since, unlike with V2,\r\n * it causes a context menu to appear when running on the Macintosh. Also note that the\r\n * alt hot key refers to the Option key on a Macintosh.\r\n * @property {Object} [boxStyle={border: \"4px solid #736AFF\"}]\r\n * An object literal defining the CSS styles of the zoom box.\r\n * Border widths must be specified in pixel units (or as thin, medium, or thick).\r\n * @property {Object} [veilStyle={backgroundColor: \"gray\", opacity: 0.25, cursor: \"crosshair\"}]\r\n * An object literal defining the CSS styles of the veil pane which covers the map when a drag\r\n * zoom is activated. The previous name for this property was paneStyle but the use\r\n * of this name is now deprecated.\r\n * @property {boolean} [noZoom=false] A flag indicating whether to disable zooming after an area is\r\n * selected. Set this to true to allow KeyDragZoom to be used as a simple area\r\n * selection tool.\r\n * @property {boolean} [visualEnabled=false] A flag indicating whether a visual control is to be used.\r\n * @property {string} [visualClass=\"\"] The name of the CSS class defining the styles for the visual\r\n * control. To prevent the visual control from being printed, set this property to the name of\r\n * a class, defined inside a @media print rule, which sets the CSS\r\n * display style to none.\r\n * @property {ControlPosition} [visualPosition=google.maps.ControlPosition.LEFT_TOP]\r\n * The position of the visual control.\r\n * @property {Size} [visualPositionOffset=google.maps.Size(35, 0)] The width and height values\r\n * provided by this property are the offsets (in pixels) from the location at which the control\r\n * would normally be drawn to the desired drawing location.\r\n * @property {number} [visualPositionIndex=null] The index of the visual control.\r\n * The index is for controlling the placement of the control relative to other controls at the\r\n * position given by visualPosition; controls with a lower index are placed first.\r\n * Use a negative value to place the control before any default controls. No index is\r\n * generally required.\r\n * @property {String} [visualSprite=\"http://maps.gstatic.com/mapfiles/ftr/controls/dragzoom_btn.png\"]\r\n * The URL of the sprite image used for showing the visual control in the on, off, and hot\r\n * (i.e., when the mouse is over the control) states. The three images within the sprite must\r\n * be the same size and arranged in on-hot-off order in a single row with no spaces between images.\r\n * @property {Size} [visualSize=google.maps.Size(20, 20)] The width and height values provided by\r\n * this property are the size (in pixels) of each of the images within visualSprite.\r\n * @property {Object} [visualTips={off: \"Turn on drag zoom mode\", on: \"Turn off drag zoom mode\"}]\r\n * An object literal defining the help tips that appear when\r\n * the mouse moves over the visual control. The off property is the tip to be shown\r\n * when the control is off and the on property is the tip to be shown when the\r\n * control is on.\r\n */\r\n /**\r\n * @name DragZoom\r\n * @class This class represents a drag zoom object for a map. The object is activated by holding down the hot key\r\n * or by turning on the visual control.\r\n * This object is created when google.maps.Map.enableKeyDragZoom is called; it cannot be created directly.\r\n * Use google.maps.Map.getDragZoomObject to gain access to this object in order to attach event listeners.\r\n * @param {Map} map The map to which the DragZoom object is to be attached.\r\n * @param {KeyDragZoomOptions} [opt_zoomOpts] The optional parameters.\r\n */\r\n function DragZoom(map, opt_zoomOpts) {\r\n var me = this;\r\n var ov = new google.maps.OverlayView();\r\n ov.onAdd = function () {\r\n me.init_(map, opt_zoomOpts);\r\n };\r\n ov.draw = function () {\r\n };\r\n ov.onRemove = function () {\r\n };\r\n ov.setMap(map);\r\n this.prjov_ = ov;\r\n }\r\n /**\r\n * Initialize the tool.\r\n * @param {Map} map The map to which the DragZoom object is to be attached.\r\n * @param {KeyDragZoomOptions} [opt_zoomOpts] The optional parameters.\r\n */\r\n DragZoom.prototype.init_ = function (map, opt_zoomOpts) {\r\n var i;\r\n var me = this;\r\n this.map_ = map;\r\n opt_zoomOpts = opt_zoomOpts || {};\r\n this.key_ = opt_zoomOpts.key || \"shift\";\r\n this.key_ = this.key_.toLowerCase();\r\n this.borderWidths_ = getBorderWidths(this.map_.getDiv());\r\n this.veilDiv_ = [];\r\n for (i = 0; i < 4; i++) {\r\n this.veilDiv_[i] = document.createElement(\"div\");\r\n // Prevents selection of other elements on the webpage\r\n // when a drag zoom operation is in progress:\r\n this.veilDiv_[i].onselectstart = function () {\r\n return false;\r\n };\r\n // Apply default style values for the veil:\r\n setVals(this.veilDiv_[i].style, {\r\n backgroundColor: \"gray\",\r\n opacity: 0.25,\r\n cursor: \"crosshair\"\r\n });\r\n // Apply style values specified in veilStyle parameter:\r\n setVals(this.veilDiv_[i].style, opt_zoomOpts.paneStyle); // Old option name was \"paneStyle\"\r\n setVals(this.veilDiv_[i].style, opt_zoomOpts.veilStyle); // New name is \"veilStyle\"\r\n // Apply mandatory style values:\r\n setVals(this.veilDiv_[i].style, {\r\n position: \"absolute\",\r\n overflow: \"hidden\",\r\n display: \"none\"\r\n });\r\n // Workaround for Firefox Shift-Click problem:\r\n if (this.key_ === \"shift\") {\r\n this.veilDiv_[i].style.MozUserSelect = \"none\";\r\n }\r\n setOpacity(this.veilDiv_[i]);\r\n // An IE fix: If the background is transparent it cannot capture mousedown\r\n // events, so if it is, change the background to white with 0 opacity.\r\n if (this.veilDiv_[i].style.backgroundColor === \"transparent\") {\r\n this.veilDiv_[i].style.backgroundColor = \"white\";\r\n setOpacity(this.veilDiv_[i], 0);\r\n }\r\n this.map_.getDiv().appendChild(this.veilDiv_[i]);\r\n }\r\n\r\n this.noZoom_ = opt_zoomOpts.noZoom || false;\r\n this.visualEnabled_ = opt_zoomOpts.visualEnabled || false;\r\n this.visualClass_ = opt_zoomOpts.visualClass || \"\";\r\n this.visualPosition_ = opt_zoomOpts.visualPosition || google.maps.ControlPosition.LEFT_TOP;\r\n this.visualPositionOffset_ = opt_zoomOpts.visualPositionOffset || new google.maps.Size(35, 0);\r\n this.visualPositionIndex_ = opt_zoomOpts.visualPositionIndex || null;\r\n this.visualSprite_ = opt_zoomOpts.visualSprite || \"http\" + (document.location.protocol === \"https:\" ? \"s\" : \"\") + \"://maps.gstatic.com/mapfiles/ftr/controls/dragzoom_btn.png\";\r\n this.visualSize_ = opt_zoomOpts.visualSize || new google.maps.Size(20, 20);\r\n this.visualTips_ = opt_zoomOpts.visualTips || {};\r\n this.visualTips_.off = this.visualTips_.off || \"Turn on drag zoom mode\";\r\n this.visualTips_.on = this.visualTips_.on || \"Turn off drag zoom mode\";\r\n\r\n this.boxDiv_ = document.createElement(\"div\");\r\n // Apply default style values for the zoom box:\r\n setVals(this.boxDiv_.style, {\r\n border: \"4px solid #736AFF\"\r\n });\r\n // Apply style values specified in boxStyle parameter:\r\n setVals(this.boxDiv_.style, opt_zoomOpts.boxStyle);\r\n // Apply mandatory style values:\r\n setVals(this.boxDiv_.style, {\r\n position: \"absolute\",\r\n display: \"none\"\r\n });\r\n setOpacity(this.boxDiv_);\r\n this.map_.getDiv().appendChild(this.boxDiv_);\r\n this.boxBorderWidths_ = getBorderWidths(this.boxDiv_);\r\n\r\n this.listeners_ = [\r\n google.maps.event.addDomListener(document, \"keydown\", function (e) {\r\n me.onKeyDown_(e);\r\n }),\r\n google.maps.event.addDomListener(document, \"keyup\", function (e) {\r\n me.onKeyUp_(e);\r\n }),\r\n google.maps.event.addDomListener(this.veilDiv_[0], \"mousedown\", function (e) {\r\n me.onMouseDown_(e);\r\n }),\r\n google.maps.event.addDomListener(this.veilDiv_[1], \"mousedown\", function (e) {\r\n me.onMouseDown_(e);\r\n }),\r\n google.maps.event.addDomListener(this.veilDiv_[2], \"mousedown\", function (e) {\r\n me.onMouseDown_(e);\r\n }),\r\n google.maps.event.addDomListener(this.veilDiv_[3], \"mousedown\", function (e) {\r\n me.onMouseDown_(e);\r\n }),\r\n google.maps.event.addDomListener(document, \"mousedown\", function (e) {\r\n me.onMouseDownDocument_(e);\r\n }),\r\n google.maps.event.addDomListener(document, \"mousemove\", function (e) {\r\n me.onMouseMove_(e);\r\n }),\r\n google.maps.event.addDomListener(document, \"mouseup\", function (e) {\r\n me.onMouseUp_(e);\r\n }),\r\n google.maps.event.addDomListener(window, \"scroll\", getScrollValue)\r\n ];\r\n\r\n this.hotKeyDown_ = false;\r\n this.mouseDown_ = false;\r\n this.dragging_ = false;\r\n this.startPt_ = null;\r\n this.endPt_ = null;\r\n this.mapWidth_ = null;\r\n this.mapHeight_ = null;\r\n this.mousePosn_ = null;\r\n this.mapPosn_ = null;\r\n\r\n if (this.visualEnabled_) {\r\n this.buttonDiv_ = this.initControl_(this.visualPositionOffset_);\r\n if (this.visualPositionIndex_ !== null) {\r\n this.buttonDiv_.index = this.visualPositionIndex_;\r\n }\r\n this.map_.controls[this.visualPosition_].push(this.buttonDiv_);\r\n this.controlIndex_ = this.map_.controls[this.visualPosition_].length - 1;\r\n }\r\n };\r\n /**\r\n * Initializes the visual control and returns its DOM element.\r\n * @param {Size} offset The offset of the control from its normal position.\r\n * @return {Node} The DOM element containing the visual control.\r\n */\r\n DragZoom.prototype.initControl_ = function (offset) {\r\n var control;\r\n var image;\r\n var me = this;\r\n \r\n control = document.createElement(\"div\");\r\n control.className = this.visualClass_;\r\n control.style.position = \"relative\";\r\n control.style.overflow = \"hidden\";\r\n control.style.height = this.visualSize_.height + \"px\";\r\n control.style.width = this.visualSize_.width + \"px\";\r\n control.title = this.visualTips_.off;\r\n image = document.createElement(\"img\");\r\n image.src = this.visualSprite_;\r\n image.style.position = \"absolute\";\r\n image.style.left = -(this.visualSize_.width * 2) + \"px\";\r\n image.style.top = 0 + \"px\";\r\n control.appendChild(image);\r\n control.onclick = function (e) {\r\n me.hotKeyDown_ = !me.hotKeyDown_;\r\n if (me.hotKeyDown_) {\r\n me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 0) + \"px\";\r\n me.buttonDiv_.title = me.visualTips_.on;\r\n me.activatedByControl_ = true;\r\n google.maps.event.trigger(me, \"activate\");\r\n } else {\r\n me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 2) + \"px\";\r\n me.buttonDiv_.title = me.visualTips_.off;\r\n google.maps.event.trigger(me, \"deactivate\");\r\n }\r\n me.onMouseMove_(e); // Updates the veil\r\n };\r\n control.onmouseover = function () {\r\n me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 1) + \"px\";\r\n };\r\n control.onmouseout = function () {\r\n if (me.hotKeyDown_) {\r\n me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 0) + \"px\";\r\n me.buttonDiv_.title = me.visualTips_.on;\r\n } else {\r\n me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 2) + \"px\";\r\n me.buttonDiv_.title = me.visualTips_.off;\r\n }\r\n };\r\n control.ondragstart = function () {\r\n return false;\r\n };\r\n setVals(control.style, {\r\n cursor: \"pointer\",\r\n marginTop: offset.height + \"px\",\r\n marginLeft: offset.width + \"px\"\r\n });\r\n return control;\r\n };\r\n /**\r\n * Returns true if the hot key is being pressed when an event occurs.\r\n * @param {Event} e The keyboard event.\r\n * @return {boolean} Flag indicating whether the hot key is down.\r\n */\r\n DragZoom.prototype.isHotKeyDown_ = function (e) {\r\n var isHot;\r\n e = e || window.event;\r\n isHot = (e.shiftKey && this.key_ === \"shift\") || (e.altKey && this.key_ === \"alt\") || (e.ctrlKey && this.key_ === \"ctrl\");\r\n if (!isHot) {\r\n // Need to look at keyCode for Opera because it\r\n // doesn't set the shiftKey, altKey, ctrlKey properties\r\n // unless a non-modifier event is being reported.\r\n //\r\n // See http://cross-browser.com/x/examples/shift_mode.php\r\n // Also see http://unixpapa.com/js/key.html\r\n switch (e.keyCode) {\r\n case 16:\r\n if (this.key_ === \"shift\") {\r\n isHot = true;\r\n }\r\n break;\r\n case 17:\r\n if (this.key_ === \"ctrl\") {\r\n isHot = true;\r\n }\r\n break;\r\n case 18:\r\n if (this.key_ === \"alt\") {\r\n isHot = true;\r\n }\r\n break;\r\n }\r\n }\r\n return isHot;\r\n };\r\n /**\r\n * Returns true if the mouse is on top of the map div.\r\n * The position is captured in onMouseMove_.\r\n * @return {boolean}\r\n */\r\n DragZoom.prototype.isMouseOnMap_ = function () {\r\n var mousePosn = this.mousePosn_;\r\n if (mousePosn) {\r\n var mapPosn = this.mapPosn_;\r\n var mapDiv = this.map_.getDiv();\r\n return mousePosn.left > mapPosn.left && mousePosn.left < (mapPosn.left + mapDiv.offsetWidth) &&\r\n mousePosn.top > mapPosn.top && mousePosn.top < (mapPosn.top + mapDiv.offsetHeight);\r\n } else {\r\n // if user never moved mouse\r\n return false;\r\n }\r\n };\r\n /**\r\n * Show the veil if the hot key is down and the mouse is over the map,\r\n * otherwise hide the veil.\r\n */\r\n DragZoom.prototype.setVeilVisibility_ = function () {\r\n var i;\r\n if (this.map_ && this.hotKeyDown_ && this.isMouseOnMap_()) {\r\n var mapDiv = this.map_.getDiv();\r\n this.mapWidth_ = mapDiv.offsetWidth - (this.borderWidths_.left + this.borderWidths_.right);\r\n this.mapHeight_ = mapDiv.offsetHeight - (this.borderWidths_.top + this.borderWidths_.bottom);\r\n if (this.activatedByControl_) { // Veil covers entire map (except control)\r\n var left = parseInt(this.buttonDiv_.style.left, 10) + this.visualPositionOffset_.width;\r\n var top = parseInt(this.buttonDiv_.style.top, 10) + this.visualPositionOffset_.height;\r\n var width = this.visualSize_.width;\r\n var height = this.visualSize_.height;\r\n // Left veil rectangle:\r\n this.veilDiv_[0].style.top = \"0px\";\r\n this.veilDiv_[0].style.left = \"0px\";\r\n this.veilDiv_[0].style.width = left + \"px\";\r\n this.veilDiv_[0].style.height = this.mapHeight_ + \"px\";\r\n // Right veil rectangle:\r\n this.veilDiv_[1].style.top = \"0px\";\r\n this.veilDiv_[1].style.left = (left + width) + \"px\";\r\n this.veilDiv_[1].style.width = (this.mapWidth_ - (left + width)) + \"px\";\r\n this.veilDiv_[1].style.height = this.mapHeight_ + \"px\";\r\n // Top veil rectangle:\r\n this.veilDiv_[2].style.top = \"0px\";\r\n this.veilDiv_[2].style.left = left + \"px\";\r\n this.veilDiv_[2].style.width = width + \"px\";\r\n this.veilDiv_[2].style.height = top + \"px\";\r\n // Bottom veil rectangle:\r\n this.veilDiv_[3].style.top = (top + height) + \"px\";\r\n this.veilDiv_[3].style.left = left + \"px\";\r\n this.veilDiv_[3].style.width = width + \"px\";\r\n this.veilDiv_[3].style.height = (this.mapHeight_ - (top + height)) + \"px\";\r\n for (i = 0; i < this.veilDiv_.length; i++) {\r\n this.veilDiv_[i].style.display = \"block\";\r\n }\r\n } else {\r\n this.veilDiv_[0].style.left = \"0px\";\r\n this.veilDiv_[0].style.top = \"0px\";\r\n this.veilDiv_[0].style.width = this.mapWidth_ + \"px\";\r\n this.veilDiv_[0].style.height = this.mapHeight_ + \"px\";\r\n for (i = 1; i < this.veilDiv_.length; i++) {\r\n this.veilDiv_[i].style.width = \"0px\";\r\n this.veilDiv_[i].style.height = \"0px\";\r\n }\r\n for (i = 0; i < this.veilDiv_.length; i++) {\r\n this.veilDiv_[i].style.display = \"block\";\r\n }\r\n }\r\n } else {\r\n for (i = 0; i < this.veilDiv_.length; i++) {\r\n this.veilDiv_[i].style.display = \"none\";\r\n }\r\n }\r\n };\r\n /**\r\n * Handle key down. Show the veil if the hot key has been pressed.\r\n * @param {Event} e The keyboard event.\r\n */\r\n DragZoom.prototype.onKeyDown_ = function (e) {\r\n if (this.map_ && !this.hotKeyDown_ && this.isHotKeyDown_(e)) {\r\n this.mapPosn_ = getElementPosition(this.map_.getDiv());\r\n this.hotKeyDown_ = true;\r\n this.activatedByControl_ = false;\r\n this.setVeilVisibility_();\r\n /**\r\n * This event is fired when the hot key is pressed.\r\n * @name DragZoom#activate\r\n * @event\r\n */\r\n google.maps.event.trigger(this, \"activate\");\r\n }\r\n };\r\n /**\r\n * Get the google.maps.Point of the mouse position.\r\n * @param {Event} e The mouse event.\r\n * @return {Point} The mouse position.\r\n */\r\n DragZoom.prototype.getMousePoint_ = function (e) {\r\n var mousePosn = getMousePosition(e);\r\n var p = new google.maps.Point();\r\n p.x = mousePosn.left - this.mapPosn_.left - this.borderWidths_.left;\r\n p.y = mousePosn.top - this.mapPosn_.top - this.borderWidths_.top;\r\n p.x = Math.min(p.x, this.mapWidth_);\r\n p.y = Math.min(p.y, this.mapHeight_);\r\n p.x = Math.max(p.x, 0);\r\n p.y = Math.max(p.y, 0);\r\n return p;\r\n };\r\n /**\r\n * Handle mouse down.\r\n * @param {Event} e The mouse event.\r\n */\r\n DragZoom.prototype.onMouseDown_ = function (e) {\r\n if (this.map_ && this.hotKeyDown_) {\r\n this.mapPosn_ = getElementPosition(this.map_.getDiv());\r\n this.dragging_ = true;\r\n this.startPt_ = this.endPt_ = this.getMousePoint_(e);\r\n this.boxDiv_.style.width = this.boxDiv_.style.height = \"0px\";\r\n var prj = this.prjov_.getProjection();\r\n var latlng = prj.fromContainerPixelToLatLng(this.startPt_);\r\n /**\r\n * This event is fired when the drag operation begins.\r\n * The parameter passed is the geographic position of the starting point.\r\n * @name DragZoom#dragstart\r\n * @param {LatLng} latlng The geographic position of the starting point.\r\n * @event\r\n */\r\n google.maps.event.trigger(this, \"dragstart\", latlng);\r\n }\r\n };\r\n /**\r\n * Handle mouse down at the document level.\r\n * @param {Event} e The mouse event.\r\n */\r\n DragZoom.prototype.onMouseDownDocument_ = function (e) {\r\n this.mouseDown_ = true;\r\n };\r\n /**\r\n * Handle mouse move.\r\n * @param {Event} e The mouse event.\r\n */\r\n DragZoom.prototype.onMouseMove_ = function (e) {\r\n this.mousePosn_ = getMousePosition(e);\r\n if (this.dragging_) {\r\n this.endPt_ = this.getMousePoint_(e);\r\n var left = Math.min(this.startPt_.x, this.endPt_.x);\r\n var top = Math.min(this.startPt_.y, this.endPt_.y);\r\n var width = Math.abs(this.startPt_.x - this.endPt_.x);\r\n var height = Math.abs(this.startPt_.y - this.endPt_.y);\r\n // For benefit of MSIE 7/8 ensure following values are not negative:\r\n var boxWidth = Math.max(0, width - (this.boxBorderWidths_.left + this.boxBorderWidths_.right));\r\n var boxHeight = Math.max(0, height - (this.boxBorderWidths_.top + this.boxBorderWidths_.bottom));\r\n // Left veil rectangle:\r\n this.veilDiv_[0].style.top = \"0px\";\r\n this.veilDiv_[0].style.left = \"0px\";\r\n this.veilDiv_[0].style.width = left + \"px\";\r\n this.veilDiv_[0].style.height = this.mapHeight_ + \"px\";\r\n // Right veil rectangle:\r\n this.veilDiv_[1].style.top = \"0px\";\r\n this.veilDiv_[1].style.left = (left + width) + \"px\";\r\n this.veilDiv_[1].style.width = (this.mapWidth_ - (left + width)) + \"px\";\r\n this.veilDiv_[1].style.height = this.mapHeight_ + \"px\";\r\n // Top veil rectangle:\r\n this.veilDiv_[2].style.top = \"0px\";\r\n this.veilDiv_[2].style.left = left + \"px\";\r\n this.veilDiv_[2].style.width = width + \"px\";\r\n this.veilDiv_[2].style.height = top + \"px\";\r\n // Bottom veil rectangle:\r\n this.veilDiv_[3].style.top = (top + height) + \"px\";\r\n this.veilDiv_[3].style.left = left + \"px\";\r\n this.veilDiv_[3].style.width = width + \"px\";\r\n this.veilDiv_[3].style.height = (this.mapHeight_ - (top + height)) + \"px\";\r\n // Selection rectangle:\r\n this.boxDiv_.style.top = top + \"px\";\r\n this.boxDiv_.style.left = left + \"px\";\r\n this.boxDiv_.style.width = boxWidth + \"px\";\r\n this.boxDiv_.style.height = boxHeight + \"px\";\r\n this.boxDiv_.style.display = \"block\";\r\n /**\r\n * This event is fired repeatedly while the user drags a box across the area of interest.\r\n * The southwest and northeast point are passed as parameters of type google.maps.Point\r\n * (for performance reasons), relative to the map container. Also passed is the projection object\r\n * so that the event listener, if necessary, can convert the pixel positions to geographic\r\n * coordinates using google.maps.MapCanvasProjection.fromContainerPixelToLatLng.\r\n * @name DragZoom#drag\r\n * @param {Point} southwestPixel The southwest point of the selection area.\r\n * @param {Point} northeastPixel The northeast point of the selection area.\r\n * @param {MapCanvasProjection} prj The projection object.\r\n * @event\r\n */\r\n google.maps.event.trigger(this, \"drag\", new google.maps.Point(left, top + height), new google.maps.Point(left + width, top), this.prjov_.getProjection());\r\n } else if (!this.mouseDown_) {\r\n this.mapPosn_ = getElementPosition(this.map_.getDiv());\r\n this.setVeilVisibility_();\r\n }\r\n };\r\n /**\r\n * Handle mouse up.\r\n * @param {Event} e The mouse event.\r\n */\r\n DragZoom.prototype.onMouseUp_ = function (e) {\r\n var z;\r\n var me = this;\r\n this.mouseDown_ = false;\r\n if (this.dragging_) {\r\n if ((this.getMousePoint_(e).x === this.startPt_.x) && (this.getMousePoint_(e).y === this.startPt_.y)) {\r\n this.onKeyUp_(e); // Cancel event\r\n return;\r\n }\r\n var left = Math.min(this.startPt_.x, this.endPt_.x);\r\n var top = Math.min(this.startPt_.y, this.endPt_.y);\r\n var width = Math.abs(this.startPt_.x - this.endPt_.x);\r\n var height = Math.abs(this.startPt_.y - this.endPt_.y);\r\n // Google Maps API bug: setCenter() doesn't work as expected if the map has a\r\n // border on the left or top. The code here includes a workaround for this problem.\r\n var kGoogleCenteringBug = true;\r\n if (kGoogleCenteringBug) {\r\n left += this.borderWidths_.left;\r\n top += this.borderWidths_.top;\r\n }\r\n\r\n var prj = this.prjov_.getProjection();\r\n var sw = prj.fromContainerPixelToLatLng(new google.maps.Point(left, top + height));\r\n var ne = prj.fromContainerPixelToLatLng(new google.maps.Point(left + width, top));\r\n var bnds = new google.maps.LatLngBounds(sw, ne);\r\n\r\n if (this.noZoom_) {\r\n this.boxDiv_.style.display = \"none\";\r\n } else {\r\n // Sometimes fitBounds causes a zoom OUT, so restore original zoom level if this happens.\r\n z = this.map_.getZoom();\r\n this.map_.fitBounds(bnds);\r\n if (this.map_.getZoom() < z) {\r\n this.map_.setZoom(z);\r\n }\r\n\r\n // Redraw box after zoom:\r\n var swPt = prj.fromLatLngToContainerPixel(sw);\r\n var nePt = prj.fromLatLngToContainerPixel(ne);\r\n if (kGoogleCenteringBug) {\r\n swPt.x -= this.borderWidths_.left;\r\n swPt.y -= this.borderWidths_.top;\r\n nePt.x -= this.borderWidths_.left;\r\n nePt.y -= this.borderWidths_.top;\r\n }\r\n this.boxDiv_.style.left = swPt.x + \"px\";\r\n this.boxDiv_.style.top = nePt.y + \"px\";\r\n this.boxDiv_.style.width = (Math.abs(nePt.x - swPt.x) - (this.boxBorderWidths_.left + this.boxBorderWidths_.right)) + \"px\";\r\n this.boxDiv_.style.height = (Math.abs(nePt.y - swPt.y) - (this.boxBorderWidths_.top + this.boxBorderWidths_.bottom)) + \"px\";\r\n // Hide box asynchronously after 1 second:\r\n setTimeout(function () {\r\n me.boxDiv_.style.display = \"none\";\r\n }, 1000);\r\n }\r\n this.dragging_ = false;\r\n this.onMouseMove_(e); // Updates the veil\r\n /**\r\n * This event is fired when the drag operation ends.\r\n * The parameter passed is the geographic bounds of the selected area.\r\n * Note that this event is not fired if the hot key is released before the drag operation ends.\r\n * @name DragZoom#dragend\r\n * @param {LatLngBounds} bnds The geographic bounds of the selected area.\r\n * @event\r\n */\r\n google.maps.event.trigger(this, \"dragend\", bnds);\r\n // if the hot key isn't down, the drag zoom must have been activated by turning\r\n // on the visual control. In this case, finish up by simulating a key up event.\r\n if (!this.isHotKeyDown_(e)) {\r\n this.onKeyUp_(e);\r\n }\r\n }\r\n };\r\n /**\r\n * Handle key up.\r\n * @param {Event} e The keyboard event.\r\n */\r\n DragZoom.prototype.onKeyUp_ = function (e) {\r\n var i;\r\n var left, top, width, height, prj, sw, ne;\r\n var bnds = null;\r\n if (this.map_ && this.hotKeyDown_) {\r\n this.hotKeyDown_ = false;\r\n if (this.dragging_) {\r\n this.boxDiv_.style.display = \"none\";\r\n this.dragging_ = false;\r\n // Calculate the bounds when drag zoom was cancelled\r\n left = Math.min(this.startPt_.x, this.endPt_.x);\r\n top = Math.min(this.startPt_.y, this.endPt_.y);\r\n width = Math.abs(this.startPt_.x - this.endPt_.x);\r\n height = Math.abs(this.startPt_.y - this.endPt_.y);\r\n prj = this.prjov_.getProjection();\r\n sw = prj.fromContainerPixelToLatLng(new google.maps.Point(left, top + height));\r\n ne = prj.fromContainerPixelToLatLng(new google.maps.Point(left + width, top));\r\n bnds = new google.maps.LatLngBounds(sw, ne);\r\n }\r\n for (i = 0; i < this.veilDiv_.length; i++) {\r\n this.veilDiv_[i].style.display = \"none\";\r\n }\r\n if (this.visualEnabled_) {\r\n this.buttonDiv_.firstChild.style.left = -(this.visualSize_.width * 2) + \"px\";\r\n this.buttonDiv_.title = this.visualTips_.off;\r\n this.buttonDiv_.style.display = \"\";\r\n }\r\n /**\r\n * This event is fired when the hot key is released.\r\n * The parameter passed is the geographic bounds of the selected area immediately\r\n * before the hot key was released.\r\n * @name DragZoom#deactivate\r\n * @param {LatLngBounds} bnds The geographic bounds of the selected area immediately\r\n * before the hot key was released.\r\n * @event\r\n */\r\n google.maps.event.trigger(this, \"deactivate\", bnds);\r\n }\r\n };\r\n /**\r\n * @name google.maps.Map\r\n * @class These are new methods added to the Google Maps JavaScript API V3's\r\n * Map\r\n * class.\r\n */\r\n /**\r\n * Enables drag zoom. The user can zoom to an area of interest by holding down the hot key\r\n * (shift | ctrl | alt ) while dragging a box around the area or by turning\r\n * on the visual control then dragging a box around the area.\r\n * @param {KeyDragZoomOptions} opt_zoomOpts The optional parameters.\r\n */\r\n google.maps.Map.prototype.enableKeyDragZoom = function (opt_zoomOpts) {\r\n this.dragZoom_ = new DragZoom(this, opt_zoomOpts);\r\n };\r\n /**\r\n * Disables drag zoom.\r\n */\r\n google.maps.Map.prototype.disableKeyDragZoom = function () {\r\n var i;\r\n var d = this.dragZoom_;\r\n if (d) {\r\n for (i = 0; i < d.listeners_.length; ++i) {\r\n google.maps.event.removeListener(d.listeners_[i]);\r\n }\r\n this.getDiv().removeChild(d.boxDiv_);\r\n for (i = 0; i < d.veilDiv_.length; i++) {\r\n this.getDiv().removeChild(d.veilDiv_[i]);\r\n }\r\n if (d.visualEnabled_) {\r\n // Remove the custom control:\r\n this.controls[d.visualPosition_].removeAt(d.controlIndex_);\r\n }\r\n d.prjov_.setMap(null);\r\n this.dragZoom_ = null;\r\n }\r\n };\r\n /**\r\n * Returns true if the drag zoom feature has been enabled.\r\n * @return {boolean}\r\n */\r\n google.maps.Map.prototype.keyDragZoomEnabled = function () {\r\n return this.dragZoom_ !== null;\r\n };\r\n /**\r\n * Returns the DragZoom object which is created when google.maps.Map.enableKeyDragZoom is called.\r\n * With this object you can use google.maps.event.addListener to attach event listeners\r\n * for the \"activate\", \"deactivate\", \"dragstart\", \"drag\", and \"dragend\" events.\r\n * @return {DragZoom}\r\n */\r\n google.maps.Map.prototype.getDragZoomObject = function () {\r\n return this.dragZoom_;\r\n };\r\n})();\r\n/**\r\n * @name MarkerClustererPlus for Google Maps V3\r\n * @version 2.1.1 [November 4, 2013]\r\n * @author Gary Little\r\n * @fileoverview\r\n * The library creates and manages per-zoom-level clusters for large amounts of markers.\r\n *

    \r\n * This is an enhanced V3 implementation of the\r\n * V2 MarkerClusterer by Xiaoxi Wu. It is based on the\r\n * V3 MarkerClusterer port by Luke Mahe. MarkerClustererPlus was created by Gary Little.\r\n *

    \r\n * v2.0 release: MarkerClustererPlus v2.0 is backward compatible with MarkerClusterer v1.0. It\r\n * adds support for the ignoreHidden, title, batchSizeIE,\r\n * and calculator properties as well as support for four more events. It also allows\r\n * greater control over the styling of the text that appears on the cluster marker. The\r\n * documentation has been significantly improved and the overall code has been simplified and\r\n * polished. Very large numbers of markers can now be managed without causing Javascript timeout\r\n * errors on Internet Explorer. Note that the name of the clusterclick event has been\r\n * deprecated. The new name is click, so please change your application code now.\r\n */\r\n\r\n/**\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n\r\n\r\n/**\r\n * @name ClusterIconStyle\r\n * @class This class represents the object for values in the styles array passed\r\n * to the {@link MarkerClusterer} constructor. The element in this array that is used to\r\n * style the cluster icon is determined by calling the calculator function.\r\n *\r\n * @property {string} url The URL of the cluster icon image file. Required.\r\n * @property {number} height The display height (in pixels) of the cluster icon. Required.\r\n * @property {number} width The display width (in pixels) of the cluster icon. Required.\r\n * @property {Array} [anchorText] The position (in pixels) from the center of the cluster icon to\r\n * where the text label is to be centered and drawn. The format is [yoffset, xoffset]\r\n * where yoffset increases as you go down from center and xoffset\r\n * increases to the right of center. The default is [0, 0].\r\n * @property {Array} [anchorIcon] The anchor position (in pixels) of the cluster icon. This is the\r\n * spot on the cluster icon that is to be aligned with the cluster position. The format is\r\n * [yoffset, xoffset] where yoffset increases as you go down and\r\n * xoffset increases to the right of the top-left corner of the icon. The default\r\n * anchor position is the center of the cluster icon.\r\n * @property {string} [textColor=\"black\"] The color of the label text shown on the\r\n * cluster icon.\r\n * @property {number} [textSize=11] The size (in pixels) of the label text shown on the\r\n * cluster icon.\r\n * @property {string} [textDecoration=\"none\"] The value of the CSS text-decoration\r\n * property for the label text shown on the cluster icon.\r\n * @property {string} [fontWeight=\"bold\"] The value of the CSS font-weight\r\n * property for the label text shown on the cluster icon.\r\n * @property {string} [fontStyle=\"normal\"] The value of the CSS font-style\r\n * property for the label text shown on the cluster icon.\r\n * @property {string} [fontFamily=\"Arial,sans-serif\"] The value of the CSS font-family\r\n * property for the label text shown on the cluster icon.\r\n * @property {string} [backgroundPosition=\"0 0\"] The position of the cluster icon image\r\n * within the image defined by url. The format is \"xpos ypos\"\r\n * (the same format as for the CSS background-position property). You must set\r\n * this property appropriately when the image defined by url represents a sprite\r\n * containing multiple images. Note that the position must be specified in px units.\r\n */\r\n/**\r\n * @name ClusterIconInfo\r\n * @class This class is an object containing general information about a cluster icon. This is\r\n * the object that a calculator function returns.\r\n *\r\n * @property {string} text The text of the label to be shown on the cluster icon.\r\n * @property {number} index The index plus 1 of the element in the styles\r\n * array to be used to style the cluster icon.\r\n * @property {string} title The tooltip to display when the mouse moves over the cluster icon.\r\n * If this value is undefined or \"\", title is set to the\r\n * value of the title property passed to the MarkerClusterer.\r\n */\r\n/**\r\n * A cluster icon.\r\n *\r\n * @constructor\r\n * @extends google.maps.OverlayView\r\n * @param {Cluster} cluster The cluster with which the icon is to be associated.\r\n * @param {Array} [styles] An array of {@link ClusterIconStyle} defining the cluster icons\r\n * to use for various cluster sizes.\r\n * @private\r\n */\r\nfunction ClusterIcon(cluster, styles) {\r\n cluster.getMarkerClusterer().extend(ClusterIcon, google.maps.OverlayView);\r\n\r\n this.cluster_ = cluster;\r\n this.className_ = cluster.getMarkerClusterer().getClusterClass();\r\n this.styles_ = styles;\r\n this.center_ = null;\r\n this.div_ = null;\r\n this.sums_ = null;\r\n this.visible_ = false;\r\n\r\n this.setMap(cluster.getMap()); // Note: this causes onAdd to be called\r\n}\r\n\r\n\r\n/**\r\n * Adds the icon to the DOM.\r\n */\r\nClusterIcon.prototype.onAdd = function () {\r\n var cClusterIcon = this;\r\n var cMouseDownInCluster;\r\n var cDraggingMapByCluster;\r\n\r\n this.div_ = document.createElement(\"div\");\r\n this.div_.className = this.className_;\r\n if (this.visible_) {\r\n this.show();\r\n }\r\n\r\n this.getPanes().overlayMouseTarget.appendChild(this.div_);\r\n\r\n // Fix for Issue 157\r\n this.boundsChangedListener_ = google.maps.event.addListener(this.getMap(), \"bounds_changed\", function () {\r\n cDraggingMapByCluster = cMouseDownInCluster;\r\n });\r\n\r\n google.maps.event.addDomListener(this.div_, \"mousedown\", function () {\r\n cMouseDownInCluster = true;\r\n cDraggingMapByCluster = false;\r\n });\r\n\r\n google.maps.event.addDomListener(this.div_, \"click\", function (e) {\r\n cMouseDownInCluster = false;\r\n if (!cDraggingMapByCluster) {\r\n var theBounds;\r\n var mz;\r\n var mc = cClusterIcon.cluster_.getMarkerClusterer();\r\n /**\r\n * This event is fired when a cluster marker is clicked.\r\n * @name MarkerClusterer#click\r\n * @param {Cluster} c The cluster that was clicked.\r\n * @event\r\n */\r\n google.maps.event.trigger(mc, \"click\", cClusterIcon.cluster_);\r\n google.maps.event.trigger(mc, \"clusterclick\", cClusterIcon.cluster_); // deprecated name\r\n\r\n // The default click handler follows. Disable it by setting\r\n // the zoomOnClick property to false.\r\n if (mc.getZoomOnClick()) {\r\n // Zoom into the cluster.\r\n mz = mc.getMaxZoom();\r\n theBounds = cClusterIcon.cluster_.getBounds();\r\n mc.getMap().fitBounds(theBounds);\r\n // There is a fix for Issue 170 here:\r\n setTimeout(function () {\r\n mc.getMap().fitBounds(theBounds);\r\n // Don't zoom beyond the max zoom level\r\n if (mz !== null && (mc.getMap().getZoom() > mz)) {\r\n mc.getMap().setZoom(mz + 1);\r\n }\r\n }, 100);\r\n }\r\n\r\n // Prevent event propagation to the map:\r\n e.cancelBubble = true;\r\n if (e.stopPropagation) {\r\n e.stopPropagation();\r\n }\r\n }\r\n });\r\n\r\n google.maps.event.addDomListener(this.div_, \"mouseover\", function () {\r\n var mc = cClusterIcon.cluster_.getMarkerClusterer();\r\n /**\r\n * This event is fired when the mouse moves over a cluster marker.\r\n * @name MarkerClusterer#mouseover\r\n * @param {Cluster} c The cluster that the mouse moved over.\r\n * @event\r\n */\r\n google.maps.event.trigger(mc, \"mouseover\", cClusterIcon.cluster_);\r\n });\r\n\r\n google.maps.event.addDomListener(this.div_, \"mouseout\", function () {\r\n var mc = cClusterIcon.cluster_.getMarkerClusterer();\r\n /**\r\n * This event is fired when the mouse moves out of a cluster marker.\r\n * @name MarkerClusterer#mouseout\r\n * @param {Cluster} c The cluster that the mouse moved out of.\r\n * @event\r\n */\r\n google.maps.event.trigger(mc, \"mouseout\", cClusterIcon.cluster_);\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Removes the icon from the DOM.\r\n */\r\nClusterIcon.prototype.onRemove = function () {\r\n if (this.div_ && this.div_.parentNode) {\r\n this.hide();\r\n google.maps.event.removeListener(this.boundsChangedListener_);\r\n google.maps.event.clearInstanceListeners(this.div_);\r\n this.div_.parentNode.removeChild(this.div_);\r\n this.div_ = null;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Draws the icon.\r\n */\r\nClusterIcon.prototype.draw = function () {\r\n if (this.visible_) {\r\n var pos = this.getPosFromLatLng_(this.center_);\r\n this.div_.style.top = pos.y + \"px\";\r\n this.div_.style.left = pos.x + \"px\";\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Hides the icon.\r\n */\r\nClusterIcon.prototype.hide = function () {\r\n if (this.div_) {\r\n this.div_.style.display = \"none\";\r\n }\r\n this.visible_ = false;\r\n};\r\n\r\n\r\n/**\r\n * Positions and shows the icon.\r\n */\r\nClusterIcon.prototype.show = function () {\r\n if (this.div_) {\r\n var img = \"\";\r\n // NOTE: values must be specified in px units\r\n var bp = this.backgroundPosition_.split(\" \");\r\n var spriteH = parseInt(bp[0].trim(), 10);\r\n var spriteV = parseInt(bp[1].trim(), 10);\r\n var pos = this.getPosFromLatLng_(this.center_);\r\n this.div_.style.cssText = this.createCss(pos);\r\n img = \"\";\r\n this.div_.innerHTML = img + \"

    \" + this.sums_.text + \"
    \";\r\n if (typeof this.sums_.title === \"undefined\" || this.sums_.title === \"\") {\r\n this.div_.title = this.cluster_.getMarkerClusterer().getTitle();\r\n } else {\r\n this.div_.title = this.sums_.title;\r\n }\r\n this.div_.style.display = \"\";\r\n }\r\n this.visible_ = true;\r\n};\r\n\r\n\r\n/**\r\n * Sets the icon styles to the appropriate element in the styles array.\r\n *\r\n * @param {ClusterIconInfo} sums The icon label text and styles index.\r\n */\r\nClusterIcon.prototype.useStyle = function (sums) {\r\n this.sums_ = sums;\r\n var index = Math.max(0, sums.index - 1);\r\n index = Math.min(this.styles_.length - 1, index);\r\n var style = this.styles_[index];\r\n this.url_ = style.url;\r\n this.height_ = style.height;\r\n this.width_ = style.width;\r\n this.anchorText_ = style.anchorText || [0, 0];\r\n this.anchorIcon_ = style.anchorIcon || [parseInt(this.height_ / 2, 10), parseInt(this.width_ / 2, 10)];\r\n this.textColor_ = style.textColor || \"black\";\r\n this.textSize_ = style.textSize || 11;\r\n this.textDecoration_ = style.textDecoration || \"none\";\r\n this.fontWeight_ = style.fontWeight || \"bold\";\r\n this.fontStyle_ = style.fontStyle || \"normal\";\r\n this.fontFamily_ = style.fontFamily || \"Arial,sans-serif\";\r\n this.backgroundPosition_ = style.backgroundPosition || \"0 0\";\r\n};\r\n\r\n\r\n/**\r\n * Sets the position at which to center the icon.\r\n *\r\n * @param {google.maps.LatLng} center The latlng to set as the center.\r\n */\r\nClusterIcon.prototype.setCenter = function (center) {\r\n this.center_ = center;\r\n};\r\n\r\n\r\n/**\r\n * Creates the cssText style parameter based on the position of the icon.\r\n *\r\n * @param {google.maps.Point} pos The position of the icon.\r\n * @return {string} The CSS style text.\r\n */\r\nClusterIcon.prototype.createCss = function (pos) {\r\n var style = [];\r\n style.push(\"cursor: pointer;\");\r\n style.push(\"position: absolute; top: \" + pos.y + \"px; left: \" + pos.x + \"px;\");\r\n style.push(\"width: \" + this.width_ + \"px; height: \" + this.height_ + \"px;\");\r\n return style.join(\"\");\r\n};\r\n\r\n\r\n/**\r\n * Returns the position at which to place the DIV depending on the latlng.\r\n *\r\n * @param {google.maps.LatLng} latlng The position in latlng.\r\n * @return {google.maps.Point} The position in pixels.\r\n */\r\nClusterIcon.prototype.getPosFromLatLng_ = function (latlng) {\r\n var pos = this.getProjection().fromLatLngToDivPixel(latlng);\r\n pos.x -= this.anchorIcon_[1];\r\n pos.y -= this.anchorIcon_[0];\r\n pos.x = parseInt(pos.x, 10);\r\n pos.y = parseInt(pos.y, 10);\r\n return pos;\r\n};\r\n\r\n\r\n/**\r\n * Creates a single cluster that manages a group of proximate markers.\r\n * Used internally, do not call this constructor directly.\r\n * @constructor\r\n * @param {MarkerClusterer} mc The MarkerClusterer object with which this\r\n * cluster is associated.\r\n */\r\nfunction Cluster(mc) {\r\n this.markerClusterer_ = mc;\r\n this.map_ = mc.getMap();\r\n this.gridSize_ = mc.getGridSize();\r\n this.minClusterSize_ = mc.getMinimumClusterSize();\r\n this.averageCenter_ = mc.getAverageCenter();\r\n this.markers_ = [];\r\n this.center_ = null;\r\n this.bounds_ = null;\r\n this.clusterIcon_ = new ClusterIcon(this, mc.getStyles());\r\n}\r\n\r\n\r\n/**\r\n * Returns the number of markers managed by the cluster. You can call this from\r\n * a click, mouseover, or mouseout event handler\r\n * for the MarkerClusterer object.\r\n *\r\n * @return {number} The number of markers in the cluster.\r\n */\r\nCluster.prototype.getSize = function () {\r\n return this.markers_.length;\r\n};\r\n\r\n\r\n/**\r\n * Returns the array of markers managed by the cluster. You can call this from\r\n * a click, mouseover, or mouseout event handler\r\n * for the MarkerClusterer object.\r\n *\r\n * @return {Array} The array of markers in the cluster.\r\n */\r\nCluster.prototype.getMarkers = function () {\r\n return this.markers_;\r\n};\r\n\r\n\r\n/**\r\n * Returns the center of the cluster. You can call this from\r\n * a click, mouseover, or mouseout event handler\r\n * for the MarkerClusterer object.\r\n *\r\n * @return {google.maps.LatLng} The center of the cluster.\r\n */\r\nCluster.prototype.getCenter = function () {\r\n return this.center_;\r\n};\r\n\r\n\r\n/**\r\n * Returns the map with which the cluster is associated.\r\n *\r\n * @return {google.maps.Map} The map.\r\n * @ignore\r\n */\r\nCluster.prototype.getMap = function () {\r\n return this.map_;\r\n};\r\n\r\n\r\n/**\r\n * Returns the MarkerClusterer object with which the cluster is associated.\r\n *\r\n * @return {MarkerClusterer} The associated marker clusterer.\r\n * @ignore\r\n */\r\nCluster.prototype.getMarkerClusterer = function () {\r\n return this.markerClusterer_;\r\n};\r\n\r\n\r\n/**\r\n * Returns the bounds of the cluster.\r\n *\r\n * @return {google.maps.LatLngBounds} the cluster bounds.\r\n * @ignore\r\n */\r\nCluster.prototype.getBounds = function () {\r\n var i;\r\n var bounds = new google.maps.LatLngBounds(this.center_, this.center_);\r\n var markers = this.getMarkers();\r\n for (i = 0; i < markers.length; i++) {\r\n bounds.extend(markers[i].getPosition());\r\n }\r\n return bounds;\r\n};\r\n\r\n\r\n/**\r\n * Removes the cluster from the map.\r\n *\r\n * @ignore\r\n */\r\nCluster.prototype.remove = function () {\r\n this.clusterIcon_.setMap(null);\r\n this.markers_ = [];\r\n delete this.markers_;\r\n};\r\n\r\n\r\n/**\r\n * Adds a marker to the cluster.\r\n *\r\n * @param {google.maps.Marker} marker The marker to be added.\r\n * @return {boolean} True if the marker was added.\r\n * @ignore\r\n */\r\nCluster.prototype.addMarker = function (marker) {\r\n var i;\r\n var mCount;\r\n var mz;\r\n\r\n if (this.isMarkerAlreadyAdded_(marker)) {\r\n return false;\r\n }\r\n\r\n if (!this.center_) {\r\n this.center_ = marker.getPosition();\r\n this.calculateBounds_();\r\n } else {\r\n if (this.averageCenter_) {\r\n var l = this.markers_.length + 1;\r\n var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l;\r\n var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l;\r\n this.center_ = new google.maps.LatLng(lat, lng);\r\n this.calculateBounds_();\r\n }\r\n }\r\n\r\n marker.isAdded = true;\r\n this.markers_.push(marker);\r\n\r\n mCount = this.markers_.length;\r\n mz = this.markerClusterer_.getMaxZoom();\r\n if (mz !== null && this.map_.getZoom() > mz) {\r\n // Zoomed in past max zoom, so show the marker.\r\n if (marker.getMap() !== this.map_) {\r\n marker.setMap(this.map_);\r\n }\r\n } else if (mCount < this.minClusterSize_) {\r\n // Min cluster size not reached so show the marker.\r\n if (marker.getMap() !== this.map_) {\r\n marker.setMap(this.map_);\r\n }\r\n } else if (mCount === this.minClusterSize_) {\r\n // Hide the markers that were showing.\r\n for (i = 0; i < mCount; i++) {\r\n this.markers_[i].setMap(null);\r\n }\r\n } else {\r\n marker.setMap(null);\r\n }\r\n\r\n this.updateIcon_();\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * Determines if a marker lies within the cluster's bounds.\r\n *\r\n * @param {google.maps.Marker} marker The marker to check.\r\n * @return {boolean} True if the marker lies in the bounds.\r\n * @ignore\r\n */\r\nCluster.prototype.isMarkerInClusterBounds = function (marker) {\r\n return this.bounds_.contains(marker.getPosition());\r\n};\r\n\r\n\r\n/**\r\n * Calculates the extended bounds of the cluster with the grid.\r\n */\r\nCluster.prototype.calculateBounds_ = function () {\r\n var bounds = new google.maps.LatLngBounds(this.center_, this.center_);\r\n this.bounds_ = this.markerClusterer_.getExtendedBounds(bounds);\r\n};\r\n\r\n\r\n/**\r\n * Updates the cluster icon.\r\n */\r\nCluster.prototype.updateIcon_ = function () {\r\n var mCount = this.markers_.length;\r\n var mz = this.markerClusterer_.getMaxZoom();\r\n\r\n if (mz !== null && this.map_.getZoom() > mz) {\r\n this.clusterIcon_.hide();\r\n return;\r\n }\r\n\r\n if (mCount < this.minClusterSize_) {\r\n // Min cluster size not yet reached.\r\n this.clusterIcon_.hide();\r\n return;\r\n }\r\n\r\n var numStyles = this.markerClusterer_.getStyles().length;\r\n var sums = this.markerClusterer_.getCalculator()(this.markers_, numStyles);\r\n this.clusterIcon_.setCenter(this.center_);\r\n this.clusterIcon_.useStyle(sums);\r\n this.clusterIcon_.show();\r\n};\r\n\r\n\r\n/**\r\n * Determines if a marker has already been added to the cluster.\r\n *\r\n * @param {google.maps.Marker} marker The marker to check.\r\n * @return {boolean} True if the marker has already been added.\r\n */\r\nCluster.prototype.isMarkerAlreadyAdded_ = function (marker) {\r\n var i;\r\n if (this.markers_.indexOf) {\r\n return this.markers_.indexOf(marker) !== -1;\r\n } else {\r\n for (i = 0; i < this.markers_.length; i++) {\r\n if (marker === this.markers_[i]) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * @name MarkerClustererOptions\r\n * @class This class represents the optional parameter passed to\r\n * the {@link MarkerClusterer} constructor.\r\n * @property {number} [gridSize=60] The grid size of a cluster in pixels. The grid is a square.\r\n * @property {number} [maxZoom=null] The maximum zoom level at which clustering is enabled or\r\n * null if clustering is to be enabled at all zoom levels.\r\n * @property {boolean} [zoomOnClick=true] Whether to zoom the map when a cluster marker is\r\n * clicked. You may want to set this to false if you have installed a handler\r\n * for the click event and it deals with zooming on its own.\r\n * @property {boolean} [averageCenter=false] Whether the position of a cluster marker should be\r\n * the average position of all markers in the cluster. If set to false, the\r\n * cluster marker is positioned at the location of the first marker added to the cluster.\r\n * @property {number} [minimumClusterSize=2] The minimum number of markers needed in a cluster\r\n * before the markers are hidden and a cluster marker appears.\r\n * @property {boolean} [ignoreHidden=false] Whether to ignore hidden markers in clusters. You\r\n * may want to set this to true to ensure that hidden markers are not included\r\n * in the marker count that appears on a cluster marker (this count is the value of the\r\n * text property of the result returned by the default calculator).\r\n * If set to true and you change the visibility of a marker being clustered, be\r\n * sure to also call MarkerClusterer.repaint().\r\n * @property {string} [title=\"\"] The tooltip to display when the mouse moves over a cluster\r\n * marker. (Alternatively, you can use a custom calculator function to specify a\r\n * different tooltip for each cluster marker.)\r\n * @property {function} [calculator=MarkerClusterer.CALCULATOR] The function used to determine\r\n * the text to be displayed on a cluster marker and the index indicating which style to use\r\n * for the cluster marker. The input parameters for the function are (1) the array of markers\r\n * represented by a cluster marker and (2) the number of cluster icon styles. It returns a\r\n * {@link ClusterIconInfo} object. The default calculator returns a\r\n * text property which is the number of markers in the cluster and an\r\n * index property which is one higher than the lowest integer such that\r\n * 10^i exceeds the number of markers in the cluster, or the size of the styles\r\n * array, whichever is less. The styles array element used has an index of\r\n * index minus 1. For example, the default calculator returns a\r\n * text value of \"125\" and an index of 3\r\n * for a cluster icon representing 125 markers so the element used in the styles\r\n * array is 2. A calculator may also return a title\r\n * property that contains the text of the tooltip to be used for the cluster marker. If\r\n * title is not defined, the tooltip is set to the value of the title\r\n * property for the MarkerClusterer.\r\n * @property {string} [clusterClass=\"cluster\"] The name of the CSS class defining general styles\r\n * for the cluster markers. Use this class to define CSS styles that are not set up by the code\r\n * that processes the styles array.\r\n * @property {Array} [styles] An array of {@link ClusterIconStyle} elements defining the styles\r\n * of the cluster markers to be used. The element to be used to style a given cluster marker\r\n * is determined by the function defined by the calculator property.\r\n * The default is an array of {@link ClusterIconStyle} elements whose properties are derived\r\n * from the values for imagePath, imageExtension, and\r\n * imageSizes.\r\n * @property {boolean} [enableRetinaIcons=false] Whether to allow the use of cluster icons that\r\n * have sizes that are some multiple (typically double) of their actual display size. Icons such\r\n * as these look better when viewed on high-resolution monitors such as Apple's Retina displays.\r\n * Note: if this property is true, sprites cannot be used as cluster icons.\r\n * @property {number} [batchSize=MarkerClusterer.BATCH_SIZE] Set this property to the\r\n * number of markers to be processed in a single batch when using a browser other than\r\n * Internet Explorer (for Internet Explorer, use the batchSizeIE property instead).\r\n * @property {number} [batchSizeIE=MarkerClusterer.BATCH_SIZE_IE] When Internet Explorer is\r\n * being used, markers are processed in several batches with a small delay inserted between\r\n * each batch in an attempt to avoid Javascript timeout errors. Set this property to the\r\n * number of markers to be processed in a single batch; select as high a number as you can\r\n * without causing a timeout error in the browser. This number might need to be as low as 100\r\n * if 15,000 markers are being managed, for example.\r\n * @property {string} [imagePath=MarkerClusterer.IMAGE_PATH]\r\n * The full URL of the root name of the group of image files to use for cluster icons.\r\n * The complete file name is of the form imagePathn.imageExtension\r\n * where n is the image file number (1, 2, etc.).\r\n * @property {string} [imageExtension=MarkerClusterer.IMAGE_EXTENSION]\r\n * The extension name for the cluster icon image files (e.g., \"png\" or\r\n * \"jpg\").\r\n * @property {Array} [imageSizes=MarkerClusterer.IMAGE_SIZES]\r\n * An array of numbers containing the widths of the group of\r\n * imagePathn.imageExtension image files.\r\n * (The images are assumed to be square.)\r\n */\r\n/**\r\n * Creates a MarkerClusterer object with the options specified in {@link MarkerClustererOptions}.\r\n * @constructor\r\n * @extends google.maps.OverlayView\r\n * @param {google.maps.Map} map The Google map to attach to.\r\n * @param {Array.} [opt_markers] The markers to be added to the cluster.\r\n * @param {MarkerClustererOptions} [opt_options] The optional parameters.\r\n */\r\nfunction MarkerClusterer(map, opt_markers, opt_options) {\r\n // MarkerClusterer implements google.maps.OverlayView interface. We use the\r\n // extend function to extend MarkerClusterer with google.maps.OverlayView\r\n // because it might not always be available when the code is defined so we\r\n // look for it at the last possible moment. If it doesn't exist now then\r\n // there is no point going ahead :)\r\n this.extend(MarkerClusterer, google.maps.OverlayView);\r\n\r\n opt_markers = opt_markers || [];\r\n opt_options = opt_options || {};\r\n\r\n this.markers_ = [];\r\n this.clusters_ = [];\r\n this.listeners_ = [];\r\n this.activeMap_ = null;\r\n this.ready_ = false;\r\n\r\n this.gridSize_ = opt_options.gridSize || 60;\r\n this.minClusterSize_ = opt_options.minimumClusterSize || 2;\r\n this.maxZoom_ = opt_options.maxZoom || null;\r\n this.styles_ = opt_options.styles || [];\r\n this.title_ = opt_options.title || \"\";\r\n this.zoomOnClick_ = true;\r\n if (opt_options.zoomOnClick !== undefined) {\r\n this.zoomOnClick_ = opt_options.zoomOnClick;\r\n }\r\n this.averageCenter_ = false;\r\n if (opt_options.averageCenter !== undefined) {\r\n this.averageCenter_ = opt_options.averageCenter;\r\n }\r\n this.ignoreHidden_ = false;\r\n if (opt_options.ignoreHidden !== undefined) {\r\n this.ignoreHidden_ = opt_options.ignoreHidden;\r\n }\r\n this.enableRetinaIcons_ = false;\r\n if (opt_options.enableRetinaIcons !== undefined) {\r\n this.enableRetinaIcons_ = opt_options.enableRetinaIcons;\r\n }\r\n this.imagePath_ = opt_options.imagePath || MarkerClusterer.IMAGE_PATH;\r\n this.imageExtension_ = opt_options.imageExtension || MarkerClusterer.IMAGE_EXTENSION;\r\n this.imageSizes_ = opt_options.imageSizes || MarkerClusterer.IMAGE_SIZES;\r\n this.calculator_ = opt_options.calculator || MarkerClusterer.CALCULATOR;\r\n this.batchSize_ = opt_options.batchSize || MarkerClusterer.BATCH_SIZE;\r\n this.batchSizeIE_ = opt_options.batchSizeIE || MarkerClusterer.BATCH_SIZE_IE;\r\n this.clusterClass_ = opt_options.clusterClass || \"cluster\";\r\n\r\n if (navigator.userAgent.toLowerCase().indexOf(\"msie\") !== -1) {\r\n // Try to avoid IE timeout when processing a huge number of markers:\r\n this.batchSize_ = this.batchSizeIE_;\r\n }\r\n\r\n this.setupStyles_();\r\n\r\n this.addMarkers(opt_markers, true);\r\n this.setMap(map); // Note: this causes onAdd to be called\r\n}\r\n\r\n\r\n/**\r\n * Implementation of the onAdd interface method.\r\n * @ignore\r\n */\r\nMarkerClusterer.prototype.onAdd = function () {\r\n var cMarkerClusterer = this;\r\n\r\n this.activeMap_ = this.getMap();\r\n this.ready_ = true;\r\n\r\n this.repaint();\r\n\r\n // Add the map event listeners\r\n this.listeners_ = [\r\n google.maps.event.addListener(this.getMap(), \"zoom_changed\", function () {\r\n cMarkerClusterer.resetViewport_(false);\r\n // Workaround for this Google bug: when map is at level 0 and \"-\" of\r\n // zoom slider is clicked, a \"zoom_changed\" event is fired even though\r\n // the map doesn't zoom out any further. In this situation, no \"idle\"\r\n // event is triggered so the cluster markers that have been removed\r\n // do not get redrawn. Same goes for a zoom in at maxZoom.\r\n if (this.getZoom() === (this.get(\"minZoom\") || 0) || this.getZoom() === this.get(\"maxZoom\")) {\r\n google.maps.event.trigger(this, \"idle\");\r\n }\r\n }),\r\n google.maps.event.addListener(this.getMap(), \"idle\", function () {\r\n cMarkerClusterer.redraw_();\r\n })\r\n ];\r\n};\r\n\r\n\r\n/**\r\n * Implementation of the onRemove interface method.\r\n * Removes map event listeners and all cluster icons from the DOM.\r\n * All managed markers are also put back on the map.\r\n * @ignore\r\n */\r\nMarkerClusterer.prototype.onRemove = function () {\r\n var i;\r\n\r\n // Put all the managed markers back on the map:\r\n for (i = 0; i < this.markers_.length; i++) {\r\n if (this.markers_[i].getMap() !== this.activeMap_) {\r\n this.markers_[i].setMap(this.activeMap_);\r\n }\r\n }\r\n\r\n // Remove all clusters:\r\n for (i = 0; i < this.clusters_.length; i++) {\r\n this.clusters_[i].remove();\r\n }\r\n this.clusters_ = [];\r\n\r\n // Remove map event listeners:\r\n for (i = 0; i < this.listeners_.length; i++) {\r\n google.maps.event.removeListener(this.listeners_[i]);\r\n }\r\n this.listeners_ = [];\r\n\r\n this.activeMap_ = null;\r\n this.ready_ = false;\r\n};\r\n\r\n\r\n/**\r\n * Implementation of the draw interface method.\r\n * @ignore\r\n */\r\nMarkerClusterer.prototype.draw = function () {};\r\n\r\n\r\n/**\r\n * Sets up the styles object.\r\n */\r\nMarkerClusterer.prototype.setupStyles_ = function () {\r\n var i, size;\r\n if (this.styles_.length > 0) {\r\n return;\r\n }\r\n\r\n for (i = 0; i < this.imageSizes_.length; i++) {\r\n size = this.imageSizes_[i];\r\n this.styles_.push({\r\n url: this.imagePath_ + (i + 1) + \".\" + this.imageExtension_,\r\n height: size,\r\n width: size\r\n });\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Fits the map to the bounds of the markers managed by the clusterer.\r\n */\r\nMarkerClusterer.prototype.fitMapToMarkers = function () {\r\n var i;\r\n var markers = this.getMarkers();\r\n var bounds = new google.maps.LatLngBounds();\r\n for (i = 0; i < markers.length; i++) {\r\n bounds.extend(markers[i].getPosition());\r\n }\r\n\r\n this.getMap().fitBounds(bounds);\r\n};\r\n\r\n\r\n/**\r\n * Returns the value of the gridSize property.\r\n *\r\n * @return {number} The grid size.\r\n */\r\nMarkerClusterer.prototype.getGridSize = function () {\r\n return this.gridSize_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the value of the gridSize property.\r\n *\r\n * @param {number} gridSize The grid size.\r\n */\r\nMarkerClusterer.prototype.setGridSize = function (gridSize) {\r\n this.gridSize_ = gridSize;\r\n};\r\n\r\n\r\n/**\r\n * Returns the value of the minimumClusterSize property.\r\n *\r\n * @return {number} The minimum cluster size.\r\n */\r\nMarkerClusterer.prototype.getMinimumClusterSize = function () {\r\n return this.minClusterSize_;\r\n};\r\n\r\n/**\r\n * Sets the value of the minimumClusterSize property.\r\n *\r\n * @param {number} minimumClusterSize The minimum cluster size.\r\n */\r\nMarkerClusterer.prototype.setMinimumClusterSize = function (minimumClusterSize) {\r\n this.minClusterSize_ = minimumClusterSize;\r\n};\r\n\r\n\r\n/**\r\n * Returns the value of the maxZoom property.\r\n *\r\n * @return {number} The maximum zoom level.\r\n */\r\nMarkerClusterer.prototype.getMaxZoom = function () {\r\n return this.maxZoom_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the value of the maxZoom property.\r\n *\r\n * @param {number} maxZoom The maximum zoom level.\r\n */\r\nMarkerClusterer.prototype.setMaxZoom = function (maxZoom) {\r\n this.maxZoom_ = maxZoom;\r\n};\r\n\r\n\r\n/**\r\n * Returns the value of the styles property.\r\n *\r\n * @return {Array} The array of styles defining the cluster markers to be used.\r\n */\r\nMarkerClusterer.prototype.getStyles = function () {\r\n return this.styles_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the value of the styles property.\r\n *\r\n * @param {Array.} styles The array of styles to use.\r\n */\r\nMarkerClusterer.prototype.setStyles = function (styles) {\r\n this.styles_ = styles;\r\n};\r\n\r\n\r\n/**\r\n * Returns the value of the title property.\r\n *\r\n * @return {string} The content of the title text.\r\n */\r\nMarkerClusterer.prototype.getTitle = function () {\r\n return this.title_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the value of the title property.\r\n *\r\n * @param {string} title The value of the title property.\r\n */\r\nMarkerClusterer.prototype.setTitle = function (title) {\r\n this.title_ = title;\r\n};\r\n\r\n\r\n/**\r\n * Returns the value of the zoomOnClick property.\r\n *\r\n * @return {boolean} True if zoomOnClick property is set.\r\n */\r\nMarkerClusterer.prototype.getZoomOnClick = function () {\r\n return this.zoomOnClick_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the value of the zoomOnClick property.\r\n *\r\n * @param {boolean} zoomOnClick The value of the zoomOnClick property.\r\n */\r\nMarkerClusterer.prototype.setZoomOnClick = function (zoomOnClick) {\r\n this.zoomOnClick_ = zoomOnClick;\r\n};\r\n\r\n\r\n/**\r\n * Returns the value of the averageCenter property.\r\n *\r\n * @return {boolean} True if averageCenter property is set.\r\n */\r\nMarkerClusterer.prototype.getAverageCenter = function () {\r\n return this.averageCenter_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the value of the averageCenter property.\r\n *\r\n * @param {boolean} averageCenter The value of the averageCenter property.\r\n */\r\nMarkerClusterer.prototype.setAverageCenter = function (averageCenter) {\r\n this.averageCenter_ = averageCenter;\r\n};\r\n\r\n\r\n/**\r\n * Returns the value of the ignoreHidden property.\r\n *\r\n * @return {boolean} True if ignoreHidden property is set.\r\n */\r\nMarkerClusterer.prototype.getIgnoreHidden = function () {\r\n return this.ignoreHidden_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the value of the ignoreHidden property.\r\n *\r\n * @param {boolean} ignoreHidden The value of the ignoreHidden property.\r\n */\r\nMarkerClusterer.prototype.setIgnoreHidden = function (ignoreHidden) {\r\n this.ignoreHidden_ = ignoreHidden;\r\n};\r\n\r\n\r\n/**\r\n * Returns the value of the enableRetinaIcons property.\r\n *\r\n * @return {boolean} True if enableRetinaIcons property is set.\r\n */\r\nMarkerClusterer.prototype.getEnableRetinaIcons = function () {\r\n return this.enableRetinaIcons_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the value of the enableRetinaIcons property.\r\n *\r\n * @param {boolean} enableRetinaIcons The value of the enableRetinaIcons property.\r\n */\r\nMarkerClusterer.prototype.setEnableRetinaIcons = function (enableRetinaIcons) {\r\n this.enableRetinaIcons_ = enableRetinaIcons;\r\n};\r\n\r\n\r\n/**\r\n * Returns the value of the imageExtension property.\r\n *\r\n * @return {string} The value of the imageExtension property.\r\n */\r\nMarkerClusterer.prototype.getImageExtension = function () {\r\n return this.imageExtension_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the value of the imageExtension property.\r\n *\r\n * @param {string} imageExtension The value of the imageExtension property.\r\n */\r\nMarkerClusterer.prototype.setImageExtension = function (imageExtension) {\r\n this.imageExtension_ = imageExtension;\r\n};\r\n\r\n\r\n/**\r\n * Returns the value of the imagePath property.\r\n *\r\n * @return {string} The value of the imagePath property.\r\n */\r\nMarkerClusterer.prototype.getImagePath = function () {\r\n return this.imagePath_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the value of the imagePath property.\r\n *\r\n * @param {string} imagePath The value of the imagePath property.\r\n */\r\nMarkerClusterer.prototype.setImagePath = function (imagePath) {\r\n this.imagePath_ = imagePath;\r\n};\r\n\r\n\r\n/**\r\n * Returns the value of the imageSizes property.\r\n *\r\n * @return {Array} The value of the imageSizes property.\r\n */\r\nMarkerClusterer.prototype.getImageSizes = function () {\r\n return this.imageSizes_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the value of the imageSizes property.\r\n *\r\n * @param {Array} imageSizes The value of the imageSizes property.\r\n */\r\nMarkerClusterer.prototype.setImageSizes = function (imageSizes) {\r\n this.imageSizes_ = imageSizes;\r\n};\r\n\r\n\r\n/**\r\n * Returns the value of the calculator property.\r\n *\r\n * @return {function} the value of the calculator property.\r\n */\r\nMarkerClusterer.prototype.getCalculator = function () {\r\n return this.calculator_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the value of the calculator property.\r\n *\r\n * @param {function(Array., number)} calculator The value\r\n * of the calculator property.\r\n */\r\nMarkerClusterer.prototype.setCalculator = function (calculator) {\r\n this.calculator_ = calculator;\r\n};\r\n\r\n\r\n/**\r\n * Returns the value of the batchSizeIE property.\r\n *\r\n * @return {number} the value of the batchSizeIE property.\r\n */\r\nMarkerClusterer.prototype.getBatchSizeIE = function () {\r\n return this.batchSizeIE_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the value of the batchSizeIE property.\r\n *\r\n * @param {number} batchSizeIE The value of the batchSizeIE property.\r\n */\r\nMarkerClusterer.prototype.setBatchSizeIE = function (batchSizeIE) {\r\n this.batchSizeIE_ = batchSizeIE;\r\n};\r\n\r\n\r\n/**\r\n * Returns the value of the clusterClass property.\r\n *\r\n * @return {string} the value of the clusterClass property.\r\n */\r\nMarkerClusterer.prototype.getClusterClass = function () {\r\n return this.clusterClass_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the value of the clusterClass property.\r\n *\r\n * @param {string} clusterClass The value of the clusterClass property.\r\n */\r\nMarkerClusterer.prototype.setClusterClass = function (clusterClass) {\r\n this.clusterClass_ = clusterClass;\r\n};\r\n\r\n\r\n/**\r\n * Returns the array of markers managed by the clusterer.\r\n *\r\n * @return {Array} The array of markers managed by the clusterer.\r\n */\r\nMarkerClusterer.prototype.getMarkers = function () {\r\n return this.markers_;\r\n};\r\n\r\n\r\n/**\r\n * Returns the number of markers managed by the clusterer.\r\n *\r\n * @return {number} The number of markers.\r\n */\r\nMarkerClusterer.prototype.getTotalMarkers = function () {\r\n return this.markers_.length;\r\n};\r\n\r\n\r\n/**\r\n * Returns the current array of clusters formed by the clusterer.\r\n *\r\n * @return {Array} The array of clusters formed by the clusterer.\r\n */\r\nMarkerClusterer.prototype.getClusters = function () {\r\n return this.clusters_;\r\n};\r\n\r\n\r\n/**\r\n * Returns the number of clusters formed by the clusterer.\r\n *\r\n * @return {number} The number of clusters formed by the clusterer.\r\n */\r\nMarkerClusterer.prototype.getTotalClusters = function () {\r\n return this.clusters_.length;\r\n};\r\n\r\n\r\n/**\r\n * Adds a marker to the clusterer. The clusters are redrawn unless\r\n * opt_nodraw is set to true.\r\n *\r\n * @param {google.maps.Marker} marker The marker to add.\r\n * @param {boolean} [opt_nodraw] Set to true to prevent redrawing.\r\n */\r\nMarkerClusterer.prototype.addMarker = function (marker, opt_nodraw) {\r\n this.pushMarkerTo_(marker);\r\n if (!opt_nodraw) {\r\n this.redraw_();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Adds an array of markers to the clusterer. The clusters are redrawn unless\r\n * opt_nodraw is set to true.\r\n *\r\n * @param {Array.} markers The markers to add.\r\n * @param {boolean} [opt_nodraw] Set to true to prevent redrawing.\r\n */\r\nMarkerClusterer.prototype.addMarkers = function (markers, opt_nodraw) {\r\n var key;\r\n for (key in markers) {\r\n if (markers.hasOwnProperty(key)) {\r\n this.pushMarkerTo_(markers[key]);\r\n }\r\n } \r\n if (!opt_nodraw) {\r\n this.redraw_();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Pushes a marker to the clusterer.\r\n *\r\n * @param {google.maps.Marker} marker The marker to add.\r\n */\r\nMarkerClusterer.prototype.pushMarkerTo_ = function (marker) {\r\n // If the marker is draggable add a listener so we can update the clusters on the dragend:\r\n if (marker.getDraggable()) {\r\n var cMarkerClusterer = this;\r\n google.maps.event.addListener(marker, \"dragend\", function () {\r\n if (cMarkerClusterer.ready_) {\r\n this.isAdded = false;\r\n cMarkerClusterer.repaint();\r\n }\r\n });\r\n }\r\n marker.isAdded = false;\r\n this.markers_.push(marker);\r\n};\r\n\r\n\r\n/**\r\n * Removes a marker from the cluster. The clusters are redrawn unless\r\n * opt_nodraw is set to true. Returns true if the\r\n * marker was removed from the clusterer.\r\n *\r\n * @param {google.maps.Marker} marker The marker to remove.\r\n * @param {boolean} [opt_nodraw] Set to true to prevent redrawing.\r\n * @return {boolean} True if the marker was removed from the clusterer.\r\n */\r\nMarkerClusterer.prototype.removeMarker = function (marker, opt_nodraw) {\r\n var removed = this.removeMarker_(marker);\r\n\r\n if (!opt_nodraw && removed) {\r\n this.repaint();\r\n }\r\n\r\n return removed;\r\n};\r\n\r\n\r\n/**\r\n * Removes an array of markers from the cluster. The clusters are redrawn unless\r\n * opt_nodraw is set to true. Returns true if markers\r\n * were removed from the clusterer.\r\n *\r\n * @param {Array.} markers The markers to remove.\r\n * @param {boolean} [opt_nodraw] Set to true to prevent redrawing.\r\n * @return {boolean} True if markers were removed from the clusterer.\r\n */\r\nMarkerClusterer.prototype.removeMarkers = function (markers, opt_nodraw) {\r\n var i, r;\r\n var removed = false;\r\n\r\n for (i = 0; i < markers.length; i++) {\r\n r = this.removeMarker_(markers[i]);\r\n removed = removed || r;\r\n }\r\n\r\n if (!opt_nodraw && removed) {\r\n this.repaint();\r\n }\r\n\r\n return removed;\r\n};\r\n\r\n\r\n/**\r\n * Removes a marker and returns true if removed, false if not.\r\n *\r\n * @param {google.maps.Marker} marker The marker to remove\r\n * @return {boolean} Whether the marker was removed or not\r\n */\r\nMarkerClusterer.prototype.removeMarker_ = function (marker) {\r\n var i;\r\n var index = -1;\r\n if (this.markers_.indexOf) {\r\n index = this.markers_.indexOf(marker);\r\n } else {\r\n for (i = 0; i < this.markers_.length; i++) {\r\n if (marker === this.markers_[i]) {\r\n index = i;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n if (index === -1) {\r\n // Marker is not in our list of markers, so do nothing:\r\n return false;\r\n }\r\n\r\n marker.setMap(null);\r\n this.markers_.splice(index, 1); // Remove the marker from the list of managed markers\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * Removes all clusters and markers from the map and also removes all markers\r\n * managed by the clusterer.\r\n */\r\nMarkerClusterer.prototype.clearMarkers = function () {\r\n this.resetViewport_(true);\r\n this.markers_ = [];\r\n};\r\n\r\n\r\n/**\r\n * Recalculates and redraws all the marker clusters from scratch.\r\n * Call this after changing any properties.\r\n */\r\nMarkerClusterer.prototype.repaint = function () {\r\n var oldClusters = this.clusters_.slice();\r\n this.clusters_ = [];\r\n this.resetViewport_(false);\r\n this.redraw_();\r\n\r\n // Remove the old clusters.\r\n // Do it in a timeout to prevent blinking effect.\r\n setTimeout(function () {\r\n var i;\r\n for (i = 0; i < oldClusters.length; i++) {\r\n oldClusters[i].remove();\r\n }\r\n }, 0);\r\n};\r\n\r\n\r\n/**\r\n * Returns the current bounds extended by the grid size.\r\n *\r\n * @param {google.maps.LatLngBounds} bounds The bounds to extend.\r\n * @return {google.maps.LatLngBounds} The extended bounds.\r\n * @ignore\r\n */\r\nMarkerClusterer.prototype.getExtendedBounds = function (bounds) {\r\n var projection = this.getProjection();\r\n\r\n // Turn the bounds into latlng.\r\n var tr = new google.maps.LatLng(bounds.getNorthEast().lat(),\r\n bounds.getNorthEast().lng());\r\n var bl = new google.maps.LatLng(bounds.getSouthWest().lat(),\r\n bounds.getSouthWest().lng());\r\n\r\n // Convert the points to pixels and the extend out by the grid size.\r\n var trPix = projection.fromLatLngToDivPixel(tr);\r\n trPix.x += this.gridSize_;\r\n trPix.y -= this.gridSize_;\r\n\r\n var blPix = projection.fromLatLngToDivPixel(bl);\r\n blPix.x -= this.gridSize_;\r\n blPix.y += this.gridSize_;\r\n\r\n // Convert the pixel points back to LatLng\r\n var ne = projection.fromDivPixelToLatLng(trPix);\r\n var sw = projection.fromDivPixelToLatLng(blPix);\r\n\r\n // Extend the bounds to contain the new bounds.\r\n bounds.extend(ne);\r\n bounds.extend(sw);\r\n\r\n return bounds;\r\n};\r\n\r\n\r\n/**\r\n * Redraws all the clusters.\r\n */\r\nMarkerClusterer.prototype.redraw_ = function () {\r\n this.createClusters_(0);\r\n};\r\n\r\n\r\n/**\r\n * Removes all clusters from the map. The markers are also removed from the map\r\n * if opt_hide is set to true.\r\n *\r\n * @param {boolean} [opt_hide] Set to true to also remove the markers\r\n * from the map.\r\n */\r\nMarkerClusterer.prototype.resetViewport_ = function (opt_hide) {\r\n var i, marker;\r\n // Remove all the clusters\r\n for (i = 0; i < this.clusters_.length; i++) {\r\n this.clusters_[i].remove();\r\n }\r\n this.clusters_ = [];\r\n\r\n // Reset the markers to not be added and to be removed from the map.\r\n for (i = 0; i < this.markers_.length; i++) {\r\n marker = this.markers_[i];\r\n marker.isAdded = false;\r\n if (opt_hide) {\r\n marker.setMap(null);\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Calculates the distance between two latlng locations in km.\r\n *\r\n * @param {google.maps.LatLng} p1 The first lat lng point.\r\n * @param {google.maps.LatLng} p2 The second lat lng point.\r\n * @return {number} The distance between the two points in km.\r\n * @see http://www.movable-type.co.uk/scripts/latlong.html\r\n*/\r\nMarkerClusterer.prototype.distanceBetweenPoints_ = function (p1, p2) {\r\n var R = 6371; // Radius of the Earth in km\r\n var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;\r\n var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;\r\n var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +\r\n Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) *\r\n Math.sin(dLon / 2) * Math.sin(dLon / 2);\r\n var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\r\n var d = R * c;\r\n return d;\r\n};\r\n\r\n\r\n/**\r\n * Determines if a marker is contained in a bounds.\r\n *\r\n * @param {google.maps.Marker} marker The marker to check.\r\n * @param {google.maps.LatLngBounds} bounds The bounds to check against.\r\n * @return {boolean} True if the marker is in the bounds.\r\n */\r\nMarkerClusterer.prototype.isMarkerInBounds_ = function (marker, bounds) {\r\n return bounds.contains(marker.getPosition());\r\n};\r\n\r\n\r\n/**\r\n * Adds a marker to a cluster, or creates a new cluster.\r\n *\r\n * @param {google.maps.Marker} marker The marker to add.\r\n */\r\nMarkerClusterer.prototype.addToClosestCluster_ = function (marker) {\r\n var i, d, cluster, center;\r\n var distance = 40000; // Some large number\r\n var clusterToAddTo = null;\r\n for (i = 0; i < this.clusters_.length; i++) {\r\n cluster = this.clusters_[i];\r\n center = cluster.getCenter();\r\n if (center) {\r\n d = this.distanceBetweenPoints_(center, marker.getPosition());\r\n if (d < distance) {\r\n distance = d;\r\n clusterToAddTo = cluster;\r\n }\r\n }\r\n }\r\n\r\n if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) {\r\n clusterToAddTo.addMarker(marker);\r\n } else {\r\n cluster = new Cluster(this);\r\n cluster.addMarker(marker);\r\n this.clusters_.push(cluster);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Creates the clusters. This is done in batches to avoid timeout errors\r\n * in some browsers when there is a huge number of markers.\r\n *\r\n * @param {number} iFirst The index of the first marker in the batch of\r\n * markers to be added to clusters.\r\n */\r\nMarkerClusterer.prototype.createClusters_ = function (iFirst) {\r\n var i, marker;\r\n var mapBounds;\r\n var cMarkerClusterer = this;\r\n if (!this.ready_) {\r\n return;\r\n }\r\n\r\n // Cancel previous batch processing if we're working on the first batch:\r\n if (iFirst === 0) {\r\n /**\r\n * This event is fired when the MarkerClusterer begins\r\n * clustering markers.\r\n * @name MarkerClusterer#clusteringbegin\r\n * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.\r\n * @event\r\n */\r\n google.maps.event.trigger(this, \"clusteringbegin\", this);\r\n\r\n if (typeof this.timerRefStatic !== \"undefined\") {\r\n clearTimeout(this.timerRefStatic);\r\n delete this.timerRefStatic;\r\n }\r\n }\r\n\r\n // Get our current map view bounds.\r\n // Create a new bounds object so we don't affect the map.\r\n //\r\n // See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug:\r\n if (this.getMap().getZoom() > 3) {\r\n mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(),\r\n this.getMap().getBounds().getNorthEast());\r\n } else {\r\n mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625));\r\n }\r\n var bounds = this.getExtendedBounds(mapBounds);\r\n\r\n var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length);\r\n\r\n for (i = iFirst; i < iLast; i++) {\r\n marker = this.markers_[i];\r\n if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) {\r\n if (!this.ignoreHidden_ || (this.ignoreHidden_ && marker.getVisible())) {\r\n this.addToClosestCluster_(marker);\r\n }\r\n }\r\n }\r\n\r\n if (iLast < this.markers_.length) {\r\n this.timerRefStatic = setTimeout(function () {\r\n cMarkerClusterer.createClusters_(iLast);\r\n }, 0);\r\n } else {\r\n delete this.timerRefStatic;\r\n\r\n /**\r\n * This event is fired when the MarkerClusterer stops\r\n * clustering markers.\r\n * @name MarkerClusterer#clusteringend\r\n * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.\r\n * @event\r\n */\r\n google.maps.event.trigger(this, \"clusteringend\", this);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Extends an object's prototype by another's.\r\n *\r\n * @param {Object} obj1 The object to be extended.\r\n * @param {Object} obj2 The object to extend with.\r\n * @return {Object} The new extended object.\r\n * @ignore\r\n */\r\nMarkerClusterer.prototype.extend = function (obj1, obj2) {\r\n return (function (object) {\r\n var property;\r\n for (property in object.prototype) {\r\n this.prototype[property] = object.prototype[property];\r\n }\r\n return this;\r\n }).apply(obj1, [obj2]);\r\n};\r\n\r\n\r\n/**\r\n * The default function for determining the label text and style\r\n * for a cluster icon.\r\n *\r\n * @param {Array.} markers The array of markers represented by the cluster.\r\n * @param {number} numStyles The number of marker styles available.\r\n * @return {ClusterIconInfo} The information resource for the cluster.\r\n * @constant\r\n * @ignore\r\n */\r\nMarkerClusterer.CALCULATOR = function (markers, numStyles) {\r\n var index = 0;\r\n var title = \"\";\r\n var count = markers.length.toString();\r\n\r\n var dv = count;\r\n while (dv !== 0) {\r\n dv = parseInt(dv / 10, 10);\r\n index++;\r\n }\r\n\r\n index = Math.min(index, numStyles);\r\n return {\r\n text: count,\r\n index: index,\r\n title: title\r\n };\r\n};\r\n\r\n\r\n/**\r\n * The number of markers to process in one batch.\r\n *\r\n * @type {number}\r\n * @constant\r\n */\r\nMarkerClusterer.BATCH_SIZE = 2000;\r\n\r\n\r\n/**\r\n * The number of markers to process in one batch (IE only).\r\n *\r\n * @type {number}\r\n * @constant\r\n */\r\nMarkerClusterer.BATCH_SIZE_IE = 500;\r\n\r\n\r\n/**\r\n * The default root name for the marker cluster images.\r\n *\r\n * @type {string}\r\n * @constant\r\n */\r\nMarkerClusterer.IMAGE_PATH = \"http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/images/m\";\r\n\r\n\r\n/**\r\n * The default extension name for the marker cluster images.\r\n *\r\n * @type {string}\r\n * @constant\r\n */\r\nMarkerClusterer.IMAGE_EXTENSION = \"png\";\r\n\r\n\r\n/**\r\n * The default array of sizes for the marker cluster images.\r\n *\r\n * @type {Array.}\r\n * @constant\r\n */\r\nMarkerClusterer.IMAGE_SIZES = [53, 56, 66, 78, 90];\r\n\r\n/**\r\n * @name MarkerWithLabel for V3\r\n * @version 1.1.10 [April 8, 2014]\r\n * @author Gary Little (inspired by code from Marc Ridey of Google).\r\n * @copyright Copyright 2012 Gary Little [gary at luxcentral.com]\r\n * @fileoverview MarkerWithLabel extends the Google Maps JavaScript API V3\r\n * google.maps.Marker class.\r\n *

    \r\n * MarkerWithLabel allows you to define markers with associated labels. As you would expect,\r\n * if the marker is draggable, so too will be the label. In addition, a marker with a label\r\n * responds to all mouse events in the same manner as a regular marker. It also fires mouse\r\n * events and \"property changed\" events just as a regular marker would. Version 1.1 adds\r\n * support for the raiseOnDrag feature introduced in API V3.3.\r\n *

    \r\n * If you drag a marker by its label, you can cancel the drag and return the marker to its\r\n * original position by pressing the Esc key. This doesn't work if you drag the marker\r\n * itself because this feature is not (yet) supported in the google.maps.Marker class.\r\n */\r\n\r\n/*!\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n\r\n/*jslint browser:true */\r\n/*global document,google */\r\n\r\n/**\r\n * @param {Function} childCtor Child class.\r\n * @param {Function} parentCtor Parent class.\r\n * @private\r\n */\r\nfunction inherits(childCtor, parentCtor) {\r\n /* @constructor */\r\n function tempCtor() {}\r\n tempCtor.prototype = parentCtor.prototype;\r\n childCtor.superClass_ = parentCtor.prototype;\r\n childCtor.prototype = new tempCtor();\r\n /* @override */\r\n childCtor.prototype.constructor = childCtor;\r\n}\r\n\r\n/**\r\n * This constructor creates a label and associates it with a marker.\r\n * It is for the private use of the MarkerWithLabel class.\r\n * @constructor\r\n * @param {Marker} marker The marker with which the label is to be associated.\r\n * @param {string} crossURL The URL of the cross image =.\r\n * @param {string} handCursor The URL of the hand cursor.\r\n * @private\r\n */\r\nfunction MarkerLabel_(marker, crossURL, handCursorURL) {\r\n this.marker_ = marker;\r\n this.handCursorURL_ = marker.handCursorURL;\r\n\r\n this.labelDiv_ = document.createElement(\"div\");\r\n this.labelDiv_.style.cssText = \"position: absolute; overflow: hidden;\";\r\n\r\n // Set up the DIV for handling mouse events in the label. This DIV forms a transparent veil\r\n // in the \"overlayMouseTarget\" pane, a veil that covers just the label. This is done so that\r\n // events can be captured even if the label is in the shadow of a google.maps.InfoWindow.\r\n // Code is included here to ensure the veil is always exactly the same size as the label.\r\n this.eventDiv_ = document.createElement(\"div\");\r\n this.eventDiv_.style.cssText = this.labelDiv_.style.cssText;\r\n\r\n // This is needed for proper behavior on MSIE:\r\n this.eventDiv_.setAttribute(\"onselectstart\", \"return false;\");\r\n this.eventDiv_.setAttribute(\"ondragstart\", \"return false;\");\r\n\r\n // Get the DIV for the \"X\" to be displayed when the marker is raised.\r\n this.crossDiv_ = MarkerLabel_.getSharedCross(crossURL);\r\n}\r\n\r\ninherits(MarkerLabel_, google.maps.OverlayView);\r\n\r\n/**\r\n * Returns the DIV for the cross used when dragging a marker when the\r\n * raiseOnDrag parameter set to true. One cross is shared with all markers.\r\n * @param {string} crossURL The URL of the cross image =.\r\n * @private\r\n */\r\nMarkerLabel_.getSharedCross = function (crossURL) {\r\n var div;\r\n if (typeof MarkerLabel_.getSharedCross.crossDiv === \"undefined\") {\r\n div = document.createElement(\"img\");\r\n div.style.cssText = \"position: absolute; z-index: 1000002; display: none;\";\r\n // Hopefully Google never changes the standard \"X\" attributes:\r\n div.style.marginLeft = \"-8px\";\r\n div.style.marginTop = \"-9px\";\r\n div.src = crossURL;\r\n MarkerLabel_.getSharedCross.crossDiv = div;\r\n }\r\n return MarkerLabel_.getSharedCross.crossDiv;\r\n};\r\n\r\n/**\r\n * Adds the DIV representing the label to the DOM. This method is called\r\n * automatically when the marker's setMap method is called.\r\n * @private\r\n */\r\nMarkerLabel_.prototype.onAdd = function () {\r\n var me = this;\r\n var cMouseIsDown = false;\r\n var cDraggingLabel = false;\r\n var cSavedZIndex;\r\n var cLatOffset, cLngOffset;\r\n var cIgnoreClick;\r\n var cRaiseEnabled;\r\n var cStartPosition;\r\n var cStartCenter;\r\n // Constants:\r\n var cRaiseOffset = 20;\r\n var cDraggingCursor = \"url(\" + this.handCursorURL_ + \")\";\r\n\r\n // Stops all processing of an event.\r\n //\r\n var cAbortEvent = function (e) {\r\n if (e.preventDefault) {\r\n e.preventDefault();\r\n }\r\n e.cancelBubble = true;\r\n if (e.stopPropagation) {\r\n e.stopPropagation();\r\n }\r\n };\r\n\r\n var cStopBounce = function () {\r\n me.marker_.setAnimation(null);\r\n };\r\n\r\n this.getPanes().overlayImage.appendChild(this.labelDiv_);\r\n this.getPanes().overlayMouseTarget.appendChild(this.eventDiv_);\r\n // One cross is shared with all markers, so only add it once:\r\n if (typeof MarkerLabel_.getSharedCross.processed === \"undefined\") {\r\n this.getPanes().overlayImage.appendChild(this.crossDiv_);\r\n MarkerLabel_.getSharedCross.processed = true;\r\n }\r\n\r\n this.listeners_ = [\r\n google.maps.event.addDomListener(this.eventDiv_, \"mouseover\", function (e) {\r\n if (me.marker_.getDraggable() || me.marker_.getClickable()) {\r\n this.style.cursor = \"pointer\";\r\n google.maps.event.trigger(me.marker_, \"mouseover\", e);\r\n }\r\n }),\r\n google.maps.event.addDomListener(this.eventDiv_, \"mouseout\", function (e) {\r\n if ((me.marker_.getDraggable() || me.marker_.getClickable()) && !cDraggingLabel) {\r\n this.style.cursor = me.marker_.getCursor();\r\n google.maps.event.trigger(me.marker_, \"mouseout\", e);\r\n }\r\n }),\r\n google.maps.event.addDomListener(this.eventDiv_, \"mousedown\", function (e) {\r\n cDraggingLabel = false;\r\n if (me.marker_.getDraggable()) {\r\n cMouseIsDown = true;\r\n this.style.cursor = cDraggingCursor;\r\n }\r\n if (me.marker_.getDraggable() || me.marker_.getClickable()) {\r\n google.maps.event.trigger(me.marker_, \"mousedown\", e);\r\n cAbortEvent(e); // Prevent map pan when starting a drag on a label\r\n }\r\n }),\r\n google.maps.event.addDomListener(document, \"mouseup\", function (mEvent) {\r\n var position;\r\n if (cMouseIsDown) {\r\n cMouseIsDown = false;\r\n me.eventDiv_.style.cursor = \"pointer\";\r\n google.maps.event.trigger(me.marker_, \"mouseup\", mEvent);\r\n }\r\n if (cDraggingLabel) {\r\n if (cRaiseEnabled) { // Lower the marker & label\r\n position = me.getProjection().fromLatLngToDivPixel(me.marker_.getPosition());\r\n position.y += cRaiseOffset;\r\n me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position));\r\n // This is not the same bouncing style as when the marker portion is dragged,\r\n // but it will have to do:\r\n try { // Will fail if running Google Maps API earlier than V3.3\r\n me.marker_.setAnimation(google.maps.Animation.BOUNCE);\r\n setTimeout(cStopBounce, 1406);\r\n } catch (e) {}\r\n }\r\n me.crossDiv_.style.display = \"none\";\r\n me.marker_.setZIndex(cSavedZIndex);\r\n cIgnoreClick = true; // Set flag to ignore the click event reported after a label drag\r\n cDraggingLabel = false;\r\n mEvent.latLng = me.marker_.getPosition();\r\n google.maps.event.trigger(me.marker_, \"dragend\", mEvent);\r\n }\r\n }),\r\n google.maps.event.addListener(me.marker_.getMap(), \"mousemove\", function (mEvent) {\r\n var position;\r\n if (cMouseIsDown) {\r\n if (cDraggingLabel) {\r\n // Change the reported location from the mouse position to the marker position:\r\n mEvent.latLng = new google.maps.LatLng(mEvent.latLng.lat() - cLatOffset, mEvent.latLng.lng() - cLngOffset);\r\n position = me.getProjection().fromLatLngToDivPixel(mEvent.latLng);\r\n if (cRaiseEnabled) {\r\n me.crossDiv_.style.left = position.x + \"px\";\r\n me.crossDiv_.style.top = position.y + \"px\";\r\n me.crossDiv_.style.display = \"\";\r\n position.y -= cRaiseOffset;\r\n }\r\n me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position));\r\n if (cRaiseEnabled) { // Don't raise the veil; this hack needed to make MSIE act properly\r\n me.eventDiv_.style.top = (position.y + cRaiseOffset) + \"px\";\r\n }\r\n google.maps.event.trigger(me.marker_, \"drag\", mEvent);\r\n } else {\r\n // Calculate offsets from the click point to the marker position:\r\n cLatOffset = mEvent.latLng.lat() - me.marker_.getPosition().lat();\r\n cLngOffset = mEvent.latLng.lng() - me.marker_.getPosition().lng();\r\n cSavedZIndex = me.marker_.getZIndex();\r\n cStartPosition = me.marker_.getPosition();\r\n cStartCenter = me.marker_.getMap().getCenter();\r\n cRaiseEnabled = me.marker_.get(\"raiseOnDrag\");\r\n cDraggingLabel = true;\r\n me.marker_.setZIndex(1000000); // Moves the marker & label to the foreground during a drag\r\n mEvent.latLng = me.marker_.getPosition();\r\n google.maps.event.trigger(me.marker_, \"dragstart\", mEvent);\r\n }\r\n }\r\n }),\r\n google.maps.event.addDomListener(document, \"keydown\", function (e) {\r\n if (cDraggingLabel) {\r\n if (e.keyCode === 27) { // Esc key\r\n cRaiseEnabled = false;\r\n me.marker_.setPosition(cStartPosition);\r\n me.marker_.getMap().setCenter(cStartCenter);\r\n google.maps.event.trigger(document, \"mouseup\", e);\r\n }\r\n }\r\n }),\r\n google.maps.event.addDomListener(this.eventDiv_, \"click\", function (e) {\r\n if (me.marker_.getDraggable() || me.marker_.getClickable()) {\r\n if (cIgnoreClick) { // Ignore the click reported when a label drag ends\r\n cIgnoreClick = false;\r\n } else {\r\n google.maps.event.trigger(me.marker_, \"click\", e);\r\n cAbortEvent(e); // Prevent click from being passed on to map\r\n }\r\n }\r\n }),\r\n google.maps.event.addDomListener(this.eventDiv_, \"dblclick\", function (e) {\r\n if (me.marker_.getDraggable() || me.marker_.getClickable()) {\r\n google.maps.event.trigger(me.marker_, \"dblclick\", e);\r\n cAbortEvent(e); // Prevent map zoom when double-clicking on a label\r\n }\r\n }),\r\n google.maps.event.addListener(this.marker_, \"dragstart\", function (mEvent) {\r\n if (!cDraggingLabel) {\r\n cRaiseEnabled = this.get(\"raiseOnDrag\");\r\n }\r\n }),\r\n google.maps.event.addListener(this.marker_, \"drag\", function (mEvent) {\r\n if (!cDraggingLabel) {\r\n if (cRaiseEnabled) {\r\n me.setPosition(cRaiseOffset);\r\n // During a drag, the marker's z-index is temporarily set to 1000000 to\r\n // ensure it appears above all other markers. Also set the label's z-index\r\n // to 1000000 (plus or minus 1 depending on whether the label is supposed\r\n // to be above or below the marker).\r\n me.labelDiv_.style.zIndex = 1000000 + (this.get(\"labelInBackground\") ? -1 : +1);\r\n }\r\n }\r\n }),\r\n google.maps.event.addListener(this.marker_, \"dragend\", function (mEvent) {\r\n if (!cDraggingLabel) {\r\n if (cRaiseEnabled) {\r\n me.setPosition(0); // Also restores z-index of label\r\n }\r\n }\r\n }),\r\n google.maps.event.addListener(this.marker_, \"position_changed\", function () {\r\n me.setPosition();\r\n }),\r\n google.maps.event.addListener(this.marker_, \"zindex_changed\", function () {\r\n me.setZIndex();\r\n }),\r\n google.maps.event.addListener(this.marker_, \"visible_changed\", function () {\r\n me.setVisible();\r\n }),\r\n google.maps.event.addListener(this.marker_, \"labelvisible_changed\", function () {\r\n me.setVisible();\r\n }),\r\n google.maps.event.addListener(this.marker_, \"title_changed\", function () {\r\n me.setTitle();\r\n }),\r\n google.maps.event.addListener(this.marker_, \"labelcontent_changed\", function () {\r\n me.setContent();\r\n }),\r\n google.maps.event.addListener(this.marker_, \"labelanchor_changed\", function () {\r\n me.setAnchor();\r\n }),\r\n google.maps.event.addListener(this.marker_, \"labelclass_changed\", function () {\r\n me.setStyles();\r\n }),\r\n google.maps.event.addListener(this.marker_, \"labelstyle_changed\", function () {\r\n me.setStyles();\r\n })\r\n ];\r\n};\r\n\r\n/**\r\n * Removes the DIV for the label from the DOM. It also removes all event handlers.\r\n * This method is called automatically when the marker's setMap(null)\r\n * method is called.\r\n * @private\r\n */\r\nMarkerLabel_.prototype.onRemove = function () {\r\n var i;\r\n this.labelDiv_.parentNode.removeChild(this.labelDiv_);\r\n this.eventDiv_.parentNode.removeChild(this.eventDiv_);\r\n\r\n // Remove event listeners:\r\n for (i = 0; i < this.listeners_.length; i++) {\r\n google.maps.event.removeListener(this.listeners_[i]);\r\n }\r\n};\r\n\r\n/**\r\n * Draws the label on the map.\r\n * @private\r\n */\r\nMarkerLabel_.prototype.draw = function () {\r\n this.setContent();\r\n this.setTitle();\r\n this.setStyles();\r\n};\r\n\r\n/**\r\n * Sets the content of the label.\r\n * The content can be plain text or an HTML DOM node.\r\n * @private\r\n */\r\nMarkerLabel_.prototype.setContent = function () {\r\n var content = this.marker_.get(\"labelContent\");\r\n if (typeof content.nodeType === \"undefined\") {\r\n this.labelDiv_.innerHTML = content;\r\n this.eventDiv_.innerHTML = this.labelDiv_.innerHTML;\r\n } else {\r\n this.labelDiv_.innerHTML = \"\"; // Remove current content\r\n this.labelDiv_.appendChild(content);\r\n content = content.cloneNode(true);\r\n this.eventDiv_.innerHTML = \"\"; // Remove current content\r\n this.eventDiv_.appendChild(content);\r\n }\r\n};\r\n\r\n/**\r\n * Sets the content of the tool tip for the label. It is\r\n * always set to be the same as for the marker itself.\r\n * @private\r\n */\r\nMarkerLabel_.prototype.setTitle = function () {\r\n this.eventDiv_.title = this.marker_.getTitle() || \"\";\r\n};\r\n\r\n/**\r\n * Sets the style of the label by setting the style sheet and applying\r\n * other specific styles requested.\r\n * @private\r\n */\r\nMarkerLabel_.prototype.setStyles = function () {\r\n var i, labelStyle;\r\n\r\n // Apply style values from the style sheet defined in the labelClass parameter:\r\n this.labelDiv_.className = this.marker_.get(\"labelClass\");\r\n this.eventDiv_.className = this.labelDiv_.className;\r\n\r\n // Clear existing inline style values:\r\n this.labelDiv_.style.cssText = \"\";\r\n this.eventDiv_.style.cssText = \"\";\r\n // Apply style values defined in the labelStyle parameter:\r\n labelStyle = this.marker_.get(\"labelStyle\");\r\n for (i in labelStyle) {\r\n if (labelStyle.hasOwnProperty(i)) {\r\n this.labelDiv_.style[i] = labelStyle[i];\r\n this.eventDiv_.style[i] = labelStyle[i];\r\n }\r\n }\r\n this.setMandatoryStyles();\r\n};\r\n\r\n/**\r\n * Sets the mandatory styles to the DIV representing the label as well as to the\r\n * associated event DIV. This includes setting the DIV position, z-index, and visibility.\r\n * @private\r\n */\r\nMarkerLabel_.prototype.setMandatoryStyles = function () {\r\n this.labelDiv_.style.position = \"absolute\";\r\n this.labelDiv_.style.overflow = \"hidden\";\r\n // Make sure the opacity setting causes the desired effect on MSIE:\r\n if (typeof this.labelDiv_.style.opacity !== \"undefined\" && this.labelDiv_.style.opacity !== \"\") {\r\n this.labelDiv_.style.MsFilter = \"\\\"progid:DXImageTransform.Microsoft.Alpha(opacity=\" + (this.labelDiv_.style.opacity * 100) + \")\\\"\";\r\n this.labelDiv_.style.filter = \"alpha(opacity=\" + (this.labelDiv_.style.opacity * 100) + \")\";\r\n }\r\n\r\n this.eventDiv_.style.position = this.labelDiv_.style.position;\r\n this.eventDiv_.style.overflow = this.labelDiv_.style.overflow;\r\n this.eventDiv_.style.opacity = 0.01; // Don't use 0; DIV won't be clickable on MSIE\r\n this.eventDiv_.style.MsFilter = \"\\\"progid:DXImageTransform.Microsoft.Alpha(opacity=1)\\\"\";\r\n this.eventDiv_.style.filter = \"alpha(opacity=1)\"; // For MSIE\r\n\r\n this.setAnchor();\r\n this.setPosition(); // This also updates z-index, if necessary.\r\n this.setVisible();\r\n};\r\n\r\n/**\r\n * Sets the anchor point of the label.\r\n * @private\r\n */\r\nMarkerLabel_.prototype.setAnchor = function () {\r\n var anchor = this.marker_.get(\"labelAnchor\");\r\n this.labelDiv_.style.marginLeft = -anchor.x + \"px\";\r\n this.labelDiv_.style.marginTop = -anchor.y + \"px\";\r\n this.eventDiv_.style.marginLeft = -anchor.x + \"px\";\r\n this.eventDiv_.style.marginTop = -anchor.y + \"px\";\r\n};\r\n\r\n/**\r\n * Sets the position of the label. The z-index is also updated, if necessary.\r\n * @private\r\n */\r\nMarkerLabel_.prototype.setPosition = function (yOffset) {\r\n var position = this.getProjection().fromLatLngToDivPixel(this.marker_.getPosition());\r\n if (typeof yOffset === \"undefined\") {\r\n yOffset = 0;\r\n }\r\n this.labelDiv_.style.left = Math.round(position.x) + \"px\";\r\n this.labelDiv_.style.top = Math.round(position.y - yOffset) + \"px\";\r\n this.eventDiv_.style.left = this.labelDiv_.style.left;\r\n this.eventDiv_.style.top = this.labelDiv_.style.top;\r\n\r\n this.setZIndex();\r\n};\r\n\r\n/**\r\n * Sets the z-index of the label. If the marker's z-index property has not been defined, the z-index\r\n * of the label is set to the vertical coordinate of the label. This is in keeping with the default\r\n * stacking order for Google Maps: markers to the south are in front of markers to the north.\r\n * @private\r\n */\r\nMarkerLabel_.prototype.setZIndex = function () {\r\n var zAdjust = (this.marker_.get(\"labelInBackground\") ? -1 : +1);\r\n if (typeof this.marker_.getZIndex() === \"undefined\") {\r\n this.labelDiv_.style.zIndex = parseInt(this.labelDiv_.style.top, 10) + zAdjust;\r\n this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex;\r\n } else {\r\n this.labelDiv_.style.zIndex = this.marker_.getZIndex() + zAdjust;\r\n this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex;\r\n }\r\n};\r\n\r\n/**\r\n * Sets the visibility of the label. The label is visible only if the marker itself is\r\n * visible (i.e., its visible property is true) and the labelVisible property is true.\r\n * @private\r\n */\r\nMarkerLabel_.prototype.setVisible = function () {\r\n if (this.marker_.get(\"labelVisible\")) {\r\n this.labelDiv_.style.display = this.marker_.getVisible() ? \"block\" : \"none\";\r\n } else {\r\n this.labelDiv_.style.display = \"none\";\r\n }\r\n this.eventDiv_.style.display = this.labelDiv_.style.display;\r\n};\r\n\r\n/**\r\n * @name MarkerWithLabelOptions\r\n * @class This class represents the optional parameter passed to the {@link MarkerWithLabel} constructor.\r\n * The properties available are the same as for google.maps.Marker with the addition\r\n * of the properties listed below. To change any of these additional properties after the labeled\r\n * marker has been created, call google.maps.Marker.set(propertyName, propertyValue).\r\n *

    \r\n * When any of these properties changes, a property changed event is fired. The names of these\r\n * events are derived from the name of the property and are of the form propertyname_changed.\r\n * For example, if the content of the label changes, a labelcontent_changed event\r\n * is fired.\r\n *

    \r\n * @property {string|Node} [labelContent] The content of the label (plain text or an HTML DOM node).\r\n * @property {Point} [labelAnchor] By default, a label is drawn with its anchor point at (0,0) so\r\n * that its top left corner is positioned at the anchor point of the associated marker. Use this\r\n * property to change the anchor point of the label. For example, to center a 50px-wide label\r\n * beneath a marker, specify a labelAnchor of google.maps.Point(25, 0).\r\n * (Note: x-values increase to the right and y-values increase to the top.)\r\n * @property {string} [labelClass] The name of the CSS class defining the styles for the label.\r\n * Note that style values for position, overflow, top,\r\n * left, zIndex, display, marginLeft, and\r\n * marginTop are ignored; these styles are for internal use only.\r\n * @property {Object} [labelStyle] An object literal whose properties define specific CSS\r\n * style values to be applied to the label. Style values defined here override those that may\r\n * be defined in the labelClass style sheet. If this property is changed after the\r\n * label has been created, all previously set styles (except those defined in the style sheet)\r\n * are removed from the label before the new style values are applied.\r\n * Note that style values for position, overflow, top,\r\n * left, zIndex, display, marginLeft, and\r\n * marginTop are ignored; these styles are for internal use only.\r\n * @property {boolean} [labelInBackground] A flag indicating whether a label that overlaps its\r\n * associated marker should appear in the background (i.e., in a plane below the marker).\r\n * The default is false, which causes the label to appear in the foreground.\r\n * @property {boolean} [labelVisible] A flag indicating whether the label is to be visible.\r\n * The default is true. Note that even if labelVisible is\r\n * true, the label will not be visible unless the associated marker is also\r\n * visible (i.e., unless the marker's visible property is true).\r\n * @property {boolean} [raiseOnDrag] A flag indicating whether the label and marker are to be\r\n * raised when the marker is dragged. The default is true. If a draggable marker is\r\n * being created and a version of Google Maps API earlier than V3.3 is being used, this property\r\n * must be set to false.\r\n * @property {boolean} [optimized] A flag indicating whether rendering is to be optimized for the\r\n * marker. Important: The optimized rendering technique is not supported by MarkerWithLabel,\r\n * so the value of this parameter is always forced to false.\r\n * @property {string} [crossImage=\"http://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png\"]\r\n * The URL of the cross image to be displayed while dragging a marker.\r\n * @property {string} [handCursor=\"http://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur\"]\r\n * The URL of the cursor to be displayed while dragging a marker.\r\n */\r\n/**\r\n * Creates a MarkerWithLabel with the options specified in {@link MarkerWithLabelOptions}.\r\n * @constructor\r\n * @param {MarkerWithLabelOptions} [opt_options] The optional parameters.\r\n */\r\nfunction MarkerWithLabel(opt_options) {\r\n opt_options = opt_options || {};\r\n opt_options.labelContent = opt_options.labelContent || \"\";\r\n opt_options.labelAnchor = opt_options.labelAnchor || new google.maps.Point(0, 0);\r\n opt_options.labelClass = opt_options.labelClass || \"markerLabels\";\r\n opt_options.labelStyle = opt_options.labelStyle || {};\r\n opt_options.labelInBackground = opt_options.labelInBackground || false;\r\n if (typeof opt_options.labelVisible === \"undefined\") {\r\n opt_options.labelVisible = true;\r\n }\r\n if (typeof opt_options.raiseOnDrag === \"undefined\") {\r\n opt_options.raiseOnDrag = true;\r\n }\r\n if (typeof opt_options.clickable === \"undefined\") {\r\n opt_options.clickable = true;\r\n }\r\n if (typeof opt_options.draggable === \"undefined\") {\r\n opt_options.draggable = false;\r\n }\r\n if (typeof opt_options.optimized === \"undefined\") {\r\n opt_options.optimized = false;\r\n }\r\n opt_options.crossImage = opt_options.crossImage || \"http\" + (document.location.protocol === \"https:\" ? \"s\" : \"\") + \"://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png\";\r\n opt_options.handCursor = opt_options.handCursor || \"http\" + (document.location.protocol === \"https:\" ? \"s\" : \"\") + \"://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur\";\r\n opt_options.optimized = false; // Optimized rendering is not supported\r\n\r\n this.label = new MarkerLabel_(this, opt_options.crossImage, opt_options.handCursor); // Bind the label to the marker\r\n\r\n // Call the parent constructor. It calls Marker.setValues to initialize, so all\r\n // the new parameters are conveniently saved and can be accessed with get/set.\r\n // Marker.set triggers a property changed event (called \"propertyname_changed\")\r\n // that the marker label listens for in order to react to state changes.\r\n google.maps.Marker.apply(this, arguments);\r\n}\r\n\r\ninherits(MarkerWithLabel, google.maps.Marker);\r\n\r\n/**\r\n * Overrides the standard Marker setMap function.\r\n * @param {Map} theMap The map to which the marker is to be added.\r\n * @private\r\n */\r\nMarkerWithLabel.prototype.setMap = function (theMap) {\r\n\r\n // Call the inherited function...\r\n google.maps.Marker.prototype.setMap.apply(this, arguments);\r\n\r\n // ... then deal with the label:\r\n this.label.setMap(theMap);\r\n};\r\n\r\n// ==ClosureCompiler==\r\n// @compilation_level ADVANCED_OPTIMIZATIONS\r\n// @externs_url http://closure-compiler.googlecode.com/svn/trunk/contrib/externs/maps/google_maps_api_v3.js\r\n// @output_wrapper (function() {%output%})();\r\n// ==/ClosureCompiler==\r\n\r\n/**\r\n * @license\r\n * Copyright 2013 Google Inc. All Rights Reserved.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n\r\n/**\r\n * A RichMarker that allows any HTML/DOM to be added to a map and be draggable.\r\n *\r\n * @param {Object.=} opt_options Optional properties to set.\r\n * @extends {google.maps.OverlayView}\r\n * @constructor\r\n */\r\nfunction RichMarker(opt_options) {\r\n var options = opt_options || {};\r\n\r\n /**\r\n * @type {boolean}\r\n * @private\r\n */\r\n this.ready_ = false;\r\n\r\n /**\r\n * @type {boolean}\r\n * @private\r\n */\r\n this.dragging_ = false;\r\n\r\n if (opt_options['visible'] == undefined) {\r\n opt_options['visible'] = true;\r\n }\r\n\r\n if (opt_options['shadow'] == undefined) {\r\n opt_options['shadow'] = '7px -3px 5px rgba(88,88,88,0.7)';\r\n }\r\n\r\n if (opt_options['anchor'] == undefined) {\r\n opt_options['anchor'] = RichMarkerPosition['BOTTOM'];\r\n }\r\n\r\n this.setValues(options);\r\n}\r\nRichMarker.prototype = new google.maps.OverlayView();\r\nwindow['RichMarker'] = RichMarker;\r\n\r\n\r\n/**\r\n * Returns the current visibility state of the marker.\r\n *\r\n * @return {boolean} The visiblity of the marker.\r\n */\r\nRichMarker.prototype.getVisible = function() {\r\n return /** @type {boolean} */ (this.get('visible'));\r\n};\r\nRichMarker.prototype['getVisible'] = RichMarker.prototype.getVisible;\r\n\r\n\r\n/**\r\n * Sets the visiblility state of the marker.\r\n *\r\n * @param {boolean} visible The visiblilty of the marker.\r\n */\r\nRichMarker.prototype.setVisible = function(visible) {\r\n this.set('visible', visible);\r\n};\r\nRichMarker.prototype['setVisible'] = RichMarker.prototype.setVisible;\r\n\r\n\r\n/**\r\n * The visible changed event.\r\n */\r\nRichMarker.prototype.visible_changed = function() {\r\n if (this.ready_) {\r\n this.markerWrapper_.style['display'] = this.getVisible() ? '' : 'none';\r\n this.draw();\r\n }\r\n};\r\nRichMarker.prototype['visible_changed'] = RichMarker.prototype.visible_changed;\r\n\r\n\r\n/**\r\n * Sets the marker to be flat.\r\n *\r\n * @param {boolean} flat If the marker is to be flat or not.\r\n */\r\nRichMarker.prototype.setFlat = function(flat) {\r\n this.set('flat', !!flat);\r\n};\r\nRichMarker.prototype['setFlat'] = RichMarker.prototype.setFlat;\r\n\r\n\r\n/**\r\n * If the makrer is flat or not.\r\n *\r\n * @return {boolean} True the marker is flat.\r\n */\r\nRichMarker.prototype.getFlat = function() {\r\n return /** @type {boolean} */ (this.get('flat'));\r\n};\r\nRichMarker.prototype['getFlat'] = RichMarker.prototype.getFlat;\r\n\r\n\r\n/**\r\n * Get the width of the marker.\r\n *\r\n * @return {Number} The width of the marker.\r\n */\r\nRichMarker.prototype.getWidth = function() {\r\n return /** @type {Number} */ (this.get('width'));\r\n};\r\nRichMarker.prototype['getWidth'] = RichMarker.prototype.getWidth;\r\n\r\n\r\n/**\r\n * Get the height of the marker.\r\n *\r\n * @return {Number} The height of the marker.\r\n */\r\nRichMarker.prototype.getHeight = function() {\r\n return /** @type {Number} */ (this.get('height'));\r\n};\r\nRichMarker.prototype['getHeight'] = RichMarker.prototype.getHeight;\r\n\r\n\r\n/**\r\n * Sets the marker's box shadow.\r\n *\r\n * @param {string} shadow The box shadow to set.\r\n */\r\nRichMarker.prototype.setShadow = function(shadow) {\r\n this.set('shadow', shadow);\r\n this.flat_changed();\r\n};\r\nRichMarker.prototype['setShadow'] = RichMarker.prototype.setShadow;\r\n\r\n\r\n/**\r\n * Gets the marker's box shadow.\r\n *\r\n * @return {string} The box shadow.\r\n */\r\nRichMarker.prototype.getShadow = function() {\r\n return /** @type {string} */ (this.get('shadow'));\r\n};\r\nRichMarker.prototype['getShadow'] = RichMarker.prototype.getShadow;\r\n\r\n\r\n/**\r\n * Flat changed event.\r\n */\r\nRichMarker.prototype.flat_changed = function() {\r\n if (!this.ready_) {\r\n return;\r\n }\r\n\r\n this.markerWrapper_.style['boxShadow'] =\r\n this.markerWrapper_.style['webkitBoxShadow'] =\r\n this.markerWrapper_.style['MozBoxShadow'] =\r\n this.getFlat() ? '' : this.getShadow();\r\n};\r\nRichMarker.prototype['flat_changed'] = RichMarker.prototype.flat_changed;\r\n\r\n\r\n/**\r\n * Sets the zIndex of the marker.\r\n *\r\n * @param {Number} index The index to set.\r\n */\r\nRichMarker.prototype.setZIndex = function(index) {\r\n this.set('zIndex', index);\r\n};\r\nRichMarker.prototype['setZIndex'] = RichMarker.prototype.setZIndex;\r\n\r\n\r\n/**\r\n * Gets the zIndex of the marker.\r\n *\r\n * @return {Number} The zIndex of the marker.\r\n */\r\nRichMarker.prototype.getZIndex = function() {\r\n return /** @type {Number} */ (this.get('zIndex'));\r\n};\r\nRichMarker.prototype['getZIndex'] = RichMarker.prototype.getZIndex;\r\n\r\n\r\n/**\r\n * zIndex changed event.\r\n */\r\nRichMarker.prototype.zIndex_changed = function() {\r\n if (this.getZIndex() && this.ready_) {\r\n this.markerWrapper_.style.zIndex = this.getZIndex();\r\n }\r\n};\r\nRichMarker.prototype['zIndex_changed'] = RichMarker.prototype.zIndex_changed;\r\n\r\n/**\r\n * Whether the marker is draggable or not.\r\n *\r\n * @return {boolean} True if the marker is draggable.\r\n */\r\nRichMarker.prototype.getDraggable = function() {\r\n return /** @type {boolean} */ (this.get('draggable'));\r\n};\r\nRichMarker.prototype['getDraggable'] = RichMarker.prototype.getDraggable;\r\n\r\n\r\n/**\r\n * Sets the marker to be draggable or not.\r\n *\r\n * @param {boolean} draggable If the marker is draggable or not.\r\n */\r\nRichMarker.prototype.setDraggable = function(draggable) {\r\n this.set('draggable', !!draggable);\r\n};\r\nRichMarker.prototype['setDraggable'] = RichMarker.prototype.setDraggable;\r\n\r\n\r\n/**\r\n * Draggable property changed callback.\r\n */\r\nRichMarker.prototype.draggable_changed = function() {\r\n if (this.ready_) {\r\n if (this.getDraggable()) {\r\n this.addDragging_(this.markerWrapper_);\r\n } else {\r\n this.removeDragListeners_();\r\n }\r\n }\r\n};\r\nRichMarker.prototype['draggable_changed'] =\r\n RichMarker.prototype.draggable_changed;\r\n\r\n\r\n/**\r\n * Gets the postiton of the marker.\r\n *\r\n * @return {google.maps.LatLng} The position of the marker.\r\n */\r\nRichMarker.prototype.getPosition = function() {\r\n return /** @type {google.maps.LatLng} */ (this.get('position'));\r\n};\r\nRichMarker.prototype['getPosition'] = RichMarker.prototype.getPosition;\r\n\r\n\r\n/**\r\n * Sets the position of the marker.\r\n *\r\n * @param {google.maps.LatLng} position The position to set.\r\n */\r\nRichMarker.prototype.setPosition = function(position) {\r\n this.set('position', position);\r\n};\r\nRichMarker.prototype['setPosition'] = RichMarker.prototype.setPosition;\r\n\r\n\r\n/**\r\n * Position changed event.\r\n */\r\nRichMarker.prototype.position_changed = function() {\r\n this.draw();\r\n};\r\nRichMarker.prototype['position_changed'] =\r\n RichMarker.prototype.position_changed;\r\n\r\n\r\n/**\r\n * Gets the anchor.\r\n *\r\n * @return {google.maps.Size} The position of the anchor.\r\n */\r\nRichMarker.prototype.getAnchor = function() {\r\n return /** @type {google.maps.Size} */ (this.get('anchor'));\r\n};\r\nRichMarker.prototype['getAnchor'] = RichMarker.prototype.getAnchor;\r\n\r\n\r\n/**\r\n * Sets the anchor.\r\n *\r\n * @param {RichMarkerPosition|google.maps.Size} anchor The anchor to set.\r\n */\r\nRichMarker.prototype.setAnchor = function(anchor) {\r\n this.set('anchor', anchor);\r\n};\r\nRichMarker.prototype['setAnchor'] = RichMarker.prototype.setAnchor;\r\n\r\n\r\n/**\r\n * Anchor changed event.\r\n */\r\nRichMarker.prototype.anchor_changed = function() {\r\n this.draw();\r\n};\r\nRichMarker.prototype['anchor_changed'] = RichMarker.prototype.anchor_changed;\r\n\r\n\r\n/**\r\n * Converts a HTML string to a document fragment.\r\n *\r\n * @param {string} htmlString The HTML string to convert.\r\n * @return {Node} A HTML document fragment.\r\n * @private\r\n */\r\nRichMarker.prototype.htmlToDocumentFragment_ = function(htmlString) {\r\n var tempDiv = document.createElement('DIV');\r\n tempDiv.innerHTML = htmlString;\r\n if (tempDiv.childNodes.length == 1) {\r\n return /** @type {!Node} */ (tempDiv.removeChild(tempDiv.firstChild));\r\n } else {\r\n var fragment = document.createDocumentFragment();\r\n while (tempDiv.firstChild) {\r\n fragment.appendChild(tempDiv.firstChild);\r\n }\r\n return fragment;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Removes all children from the node.\r\n *\r\n * @param {Node} node The node to remove all children from.\r\n * @private\r\n */\r\nRichMarker.prototype.removeChildren_ = function(node) {\r\n if (!node) {\r\n return;\r\n }\r\n\r\n var child;\r\n while (child = node.firstChild) {\r\n node.removeChild(child);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Sets the content of the marker.\r\n *\r\n * @param {string|Node} content The content to set.\r\n */\r\nRichMarker.prototype.setContent = function(content) {\r\n this.set('content', content);\r\n};\r\nRichMarker.prototype['setContent'] = RichMarker.prototype.setContent;\r\n\r\n\r\n/**\r\n * Get the content of the marker.\r\n *\r\n * @return {string|Node} The marker content.\r\n */\r\nRichMarker.prototype.getContent = function() {\r\n return /** @type {Node|string} */ (this.get('content'));\r\n};\r\nRichMarker.prototype['getContent'] = RichMarker.prototype.getContent;\r\n\r\n\r\n/**\r\n * Sets the marker content and adds loading events to images\r\n */\r\nRichMarker.prototype.content_changed = function() {\r\n if (!this.markerContent_) {\r\n // Marker content area doesnt exist.\r\n return;\r\n }\r\n\r\n this.removeChildren_(this.markerContent_);\r\n var content = this.getContent();\r\n if (content) {\r\n if (typeof content == 'string') {\r\n content = content.replace(/^\\s*([\\S\\s]*)\\b\\s*$/, '$1');\r\n content = this.htmlToDocumentFragment_(content);\r\n }\r\n this.markerContent_.appendChild(content);\r\n\r\n var that = this;\r\n var images = this.markerContent_.getElementsByTagName('IMG');\r\n for (var i = 0, image; image = images[i]; i++) {\r\n // By default, a browser lets a image be dragged outside of the browser,\r\n // so by calling preventDefault we stop this behaviour and allow the image\r\n // to be dragged around the map and now out of the browser and onto the\r\n // desktop.\r\n google.maps.event.addDomListener(image, 'mousedown', function(e) {\r\n if (that.getDraggable()) {\r\n if (e.preventDefault) {\r\n e.preventDefault();\r\n }\r\n e.returnValue = false;\r\n }\r\n });\r\n\r\n // Because we don't know the size of an image till it loads, add a\r\n // listener to the image load so the marker can resize and reposition\r\n // itself to be the correct height.\r\n google.maps.event.addDomListener(image, 'load', function() {\r\n that.draw();\r\n });\r\n }\r\n\r\n google.maps.event.trigger(this, 'domready');\r\n }\r\n\r\n if (this.ready_) {\r\n this.draw();\r\n }\r\n};\r\nRichMarker.prototype['content_changed'] = RichMarker.prototype.content_changed;\r\n\r\n/**\r\n * Sets the cursor.\r\n *\r\n * @param {string} whichCursor What cursor to show.\r\n * @private\r\n */\r\nRichMarker.prototype.setCursor_ = function(whichCursor) {\r\n if (!this.ready_) {\r\n return;\r\n }\r\n\r\n var cursor = '';\r\n if (navigator.userAgent.indexOf('Gecko/') !== -1) {\r\n // Moz has some nice cursors :)\r\n if (whichCursor == 'dragging') {\r\n cursor = '-moz-grabbing';\r\n }\r\n\r\n if (whichCursor == 'dragready') {\r\n cursor = '-moz-grab';\r\n }\r\n\r\n if (whichCursor == 'draggable') {\r\n cursor = 'pointer';\r\n }\r\n } else {\r\n if (whichCursor == 'dragging' || whichCursor == 'dragready') {\r\n cursor = 'move';\r\n }\r\n\r\n if (whichCursor == 'draggable') {\r\n cursor = 'pointer';\r\n }\r\n }\r\n\r\n if (this.markerWrapper_.style.cursor != cursor) {\r\n this.markerWrapper_.style.cursor = cursor;\r\n }\r\n};\r\n\r\n/**\r\n * Start dragging.\r\n *\r\n * @param {Event} e The event.\r\n */\r\nRichMarker.prototype.startDrag = function(e) {\r\n if (!this.getDraggable()) {\r\n return;\r\n }\r\n\r\n if (!this.dragging_) {\r\n this.dragging_ = true;\r\n var map = this.getMap();\r\n this.mapDraggable_ = map.get('draggable');\r\n map.set('draggable', false);\r\n\r\n // Store the current mouse position\r\n this.mouseX_ = e.clientX;\r\n this.mouseY_ = e.clientY;\r\n\r\n this.setCursor_('dragready');\r\n\r\n // Stop the text from being selectable while being dragged\r\n this.markerWrapper_.style['MozUserSelect'] = 'none';\r\n this.markerWrapper_.style['KhtmlUserSelect'] = 'none';\r\n this.markerWrapper_.style['WebkitUserSelect'] = 'none';\r\n\r\n this.markerWrapper_['unselectable'] = 'on';\r\n this.markerWrapper_['onselectstart'] = function() {\r\n return false;\r\n };\r\n\r\n this.addDraggingListeners_();\r\n\r\n google.maps.event.trigger(this, 'dragstart');\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Stop dragging.\r\n */\r\nRichMarker.prototype.stopDrag = function() {\r\n if (!this.getDraggable()) {\r\n return;\r\n }\r\n\r\n if (this.dragging_) {\r\n this.dragging_ = false;\r\n this.getMap().set('draggable', this.mapDraggable_);\r\n this.mouseX_ = this.mouseY_ = this.mapDraggable_ = null;\r\n\r\n // Allow the text to be selectable again\r\n this.markerWrapper_.style['MozUserSelect'] = '';\r\n this.markerWrapper_.style['KhtmlUserSelect'] = '';\r\n this.markerWrapper_.style['WebkitUserSelect'] = '';\r\n this.markerWrapper_['unselectable'] = 'off';\r\n this.markerWrapper_['onselectstart'] = function() {};\r\n\r\n this.removeDraggingListeners_();\r\n\r\n this.setCursor_('draggable');\r\n google.maps.event.trigger(this, 'dragend');\r\n\r\n this.draw();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Handles the drag event.\r\n *\r\n * @param {Event} e The event.\r\n */\r\nRichMarker.prototype.drag = function(e) {\r\n if (!this.getDraggable() || !this.dragging_) {\r\n // This object isn't draggable or we have stopped dragging\r\n this.stopDrag();\r\n return;\r\n }\r\n\r\n var dx = this.mouseX_ - e.clientX;\r\n var dy = this.mouseY_ - e.clientY;\r\n\r\n this.mouseX_ = e.clientX;\r\n this.mouseY_ = e.clientY;\r\n\r\n var left = parseInt(this.markerWrapper_.style['left'], 10) - dx;\r\n var top = parseInt(this.markerWrapper_.style['top'], 10) - dy;\r\n\r\n this.markerWrapper_.style['left'] = left + 'px';\r\n this.markerWrapper_.style['top'] = top + 'px';\r\n\r\n var offset = this.getOffset_();\r\n\r\n // Set the position property and adjust for the anchor offset\r\n var point = new google.maps.Point(left - offset.width, top - offset.height);\r\n var projection = this.getProjection();\r\n this.setPosition(projection.fromDivPixelToLatLng(point));\r\n\r\n this.setCursor_('dragging');\r\n google.maps.event.trigger(this, 'drag');\r\n};\r\n\r\n\r\n/**\r\n * Removes the drag listeners associated with the marker.\r\n *\r\n * @private\r\n */\r\nRichMarker.prototype.removeDragListeners_ = function() {\r\n if (this.draggableListener_) {\r\n google.maps.event.removeListener(this.draggableListener_);\r\n delete this.draggableListener_;\r\n }\r\n this.setCursor_('');\r\n};\r\n\r\n\r\n/**\r\n * Add dragability events to the marker.\r\n *\r\n * @param {Node} node The node to apply dragging to.\r\n * @private\r\n */\r\nRichMarker.prototype.addDragging_ = function(node) {\r\n if (!node) {\r\n return;\r\n }\r\n\r\n var that = this;\r\n this.draggableListener_ =\r\n google.maps.event.addDomListener(node, 'mousedown', function(e) {\r\n that.startDrag(e);\r\n });\r\n\r\n this.setCursor_('draggable');\r\n};\r\n\r\n\r\n/**\r\n * Add dragging listeners.\r\n *\r\n * @private\r\n */\r\nRichMarker.prototype.addDraggingListeners_ = function() {\r\n var that = this;\r\n if (this.markerWrapper_.setCapture) {\r\n this.markerWrapper_.setCapture(true);\r\n this.draggingListeners_ = [\r\n google.maps.event.addDomListener(this.markerWrapper_, 'mousemove', function(e) {\r\n that.drag(e);\r\n }, true),\r\n google.maps.event.addDomListener(this.markerWrapper_, 'mouseup', function() {\r\n that.stopDrag();\r\n that.markerWrapper_.releaseCapture();\r\n }, true)\r\n ];\r\n } else {\r\n this.draggingListeners_ = [\r\n google.maps.event.addDomListener(window, 'mousemove', function(e) {\r\n that.drag(e);\r\n }, true),\r\n google.maps.event.addDomListener(window, 'mouseup', function() {\r\n that.stopDrag();\r\n }, true)\r\n ];\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Remove dragging listeners.\r\n *\r\n * @private\r\n */\r\nRichMarker.prototype.removeDraggingListeners_ = function() {\r\n if (this.draggingListeners_) {\r\n for (var i = 0, listener; listener = this.draggingListeners_[i]; i++) {\r\n google.maps.event.removeListener(listener);\r\n }\r\n this.draggingListeners_.length = 0;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Get the anchor offset.\r\n *\r\n * @return {google.maps.Size} The size offset.\r\n * @private\r\n */\r\nRichMarker.prototype.getOffset_ = function() {\r\n var anchor = this.getAnchor();\r\n if (typeof anchor == 'object') {\r\n return /** @type {google.maps.Size} */ (anchor);\r\n }\r\n\r\n var offset = new google.maps.Size(0, 0);\r\n if (!this.markerContent_) {\r\n return offset;\r\n }\r\n\r\n var width = this.markerContent_.offsetWidth;\r\n var height = this.markerContent_.offsetHeight;\r\n\r\n switch (anchor) {\r\n case RichMarkerPosition['TOP_LEFT']:\r\n break;\r\n case RichMarkerPosition['TOP']:\r\n offset.width = -width / 2;\r\n break;\r\n case RichMarkerPosition['TOP_RIGHT']:\r\n offset.width = -width;\r\n break;\r\n case RichMarkerPosition['LEFT']:\r\n offset.height = -height / 2;\r\n break;\r\n case RichMarkerPosition['MIDDLE']:\r\n offset.width = -width / 2;\r\n offset.height = -height / 2;\r\n break;\r\n case RichMarkerPosition['RIGHT']:\r\n offset.width = -width;\r\n offset.height = -height / 2;\r\n break;\r\n case RichMarkerPosition['BOTTOM_LEFT']:\r\n offset.height = -height;\r\n break;\r\n case RichMarkerPosition['BOTTOM']:\r\n offset.width = -width / 2;\r\n offset.height = -height;\r\n break;\r\n case RichMarkerPosition['BOTTOM_RIGHT']:\r\n offset.width = -width;\r\n offset.height = -height;\r\n break;\r\n }\r\n\r\n return offset;\r\n};\r\n\r\n\r\n/**\r\n * Adding the marker to a map.\r\n * Implementing the interface.\r\n */\r\nRichMarker.prototype.onAdd = function() {\r\n if (!this.markerWrapper_) {\r\n this.markerWrapper_ = document.createElement('DIV');\r\n this.markerWrapper_.style['position'] = 'absolute';\r\n }\r\n\r\n if (this.getZIndex()) {\r\n this.markerWrapper_.style['zIndex'] = this.getZIndex();\r\n }\r\n\r\n this.markerWrapper_.style['display'] = this.getVisible() ? '' : 'none';\r\n\r\n if (!this.markerContent_) {\r\n this.markerContent_ = document.createElement('DIV');\r\n this.markerWrapper_.appendChild(this.markerContent_);\r\n\r\n var that = this;\r\n google.maps.event.addDomListener(this.markerContent_, 'click', function(e) {\r\n google.maps.event.trigger(that, 'click');\r\n });\r\n google.maps.event.addDomListener(this.markerContent_, 'mouseover', function(e) {\r\n google.maps.event.trigger(that, 'mouseover');\r\n });\r\n google.maps.event.addDomListener(this.markerContent_, 'mouseout', function(e) {\r\n google.maps.event.trigger(that, 'mouseout');\r\n });\r\n }\r\n\r\n this.ready_ = true;\r\n this.content_changed();\r\n this.flat_changed();\r\n this.draggable_changed();\r\n\r\n var panes = this.getPanes();\r\n if (panes) {\r\n panes.overlayMouseTarget.appendChild(this.markerWrapper_);\r\n }\r\n\r\n google.maps.event.trigger(this, 'ready');\r\n};\r\nRichMarker.prototype['onAdd'] = RichMarker.prototype.onAdd;\r\n\r\n\r\n/**\r\n * Impelementing the interface.\r\n */\r\nRichMarker.prototype.draw = function() {\r\n if (!this.ready_ || this.dragging_) {\r\n return;\r\n }\r\n\r\n var projection = this.getProjection();\r\n\r\n if (!projection) {\r\n // The map projection is not ready yet so do nothing\r\n return;\r\n }\r\n\r\n var latLng = /** @type {google.maps.LatLng} */ (this.get('position'));\r\n var pos = projection.fromLatLngToDivPixel(latLng);\r\n\r\n var offset = this.getOffset_();\r\n this.markerWrapper_.style['top'] = (pos.y + offset.height) + 'px';\r\n this.markerWrapper_.style['left'] = (pos.x + offset.width) + 'px';\r\n\r\n var height = this.markerContent_.offsetHeight;\r\n var width = this.markerContent_.offsetWidth;\r\n\r\n if (width != this.get('width')) {\r\n this.set('width', width);\r\n }\r\n\r\n if (height != this.get('height')) {\r\n this.set('height', height);\r\n }\r\n};\r\nRichMarker.prototype['draw'] = RichMarker.prototype.draw;\r\n\r\n\r\n/**\r\n * Removing a marker from the map.\r\n * Implementing the interface.\r\n */\r\nRichMarker.prototype.onRemove = function() {\r\n if (this.markerWrapper_ && this.markerWrapper_.parentNode) {\r\n this.markerWrapper_.parentNode.removeChild(this.markerWrapper_);\r\n }\r\n this.removeDragListeners_();\r\n};\r\nRichMarker.prototype['onRemove'] = RichMarker.prototype.onRemove;\r\n\r\n\r\n/**\r\n * RichMarker Anchor positions\r\n * @enum {number}\r\n */\r\nvar RichMarkerPosition = {\r\n 'TOP_LEFT': 1,\r\n 'TOP': 2,\r\n 'TOP_RIGHT': 3,\r\n 'LEFT': 4,\r\n 'MIDDLE': 5,\r\n 'RIGHT': 6,\r\n 'BOTTOM_LEFT': 7,\r\n 'BOTTOM': 8,\r\n 'BOTTOM_RIGHT': 9\r\n};\r\nwindow['RichMarkerPosition'] = RichMarkerPosition;\r\n\r\n //END REPLACE\r\n window.InfoBox = InfoBox;\r\n window.Cluster = Cluster;\r\n window.ClusterIcon = ClusterIcon;\r\n window.MarkerClusterer = MarkerClusterer;\r\n window.MarkerLabel_ = MarkerLabel_;\r\n window.MarkerWithLabel = MarkerWithLabel;\r\n window.RichMarker = RichMarker;\r\n })\r\n };\r\n});\r\n;/******/ (function(modules) { // webpackBootstrap\r\n/******/ \t// The module cache\r\n/******/ \tvar installedModules = {};\r\n\r\n/******/ \t// The require function\r\n/******/ \tfunction __webpack_require__(moduleId) {\r\n\r\n/******/ \t\t// Check if module is in cache\r\n/******/ \t\tif(installedModules[moduleId])\r\n/******/ \t\t\treturn installedModules[moduleId].exports;\r\n\r\n/******/ \t\t// Create a new module (and put it into the cache)\r\n/******/ \t\tvar module = installedModules[moduleId] = {\r\n/******/ \t\t\texports: {},\r\n/******/ \t\t\tid: moduleId,\r\n/******/ \t\t\tloaded: false\r\n/******/ \t\t};\r\n\r\n/******/ \t\t// Execute the module function\r\n/******/ \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\r\n\r\n/******/ \t\t// Flag the module as loaded\r\n/******/ \t\tmodule.loaded = true;\r\n\r\n/******/ \t\t// Return the exports of the module\r\n/******/ \t\treturn module.exports;\r\n/******/ \t}\r\n\r\n\r\n/******/ \t// expose the modules object (__webpack_modules__)\r\n/******/ \t__webpack_require__.m = modules;\r\n\r\n/******/ \t// expose the module cache\r\n/******/ \t__webpack_require__.c = installedModules;\r\n\r\n/******/ \t// __webpack_public_path__\r\n/******/ \t__webpack_require__.p = \"\";\r\n\r\n/******/ \t// Load entry module and return exports\r\n/******/ \treturn __webpack_require__(0);\r\n/******/ })\r\n/************************************************************************/\r\n/******/ ([\r\n/* 0 */\r\n/***/ function(module, exports, __webpack_require__) {\r\n\r\n\tangular.module('uiGmapgoogle-maps.wrapped')\r\n\t.service('uiGmapDataStructures', function() {\r\n\treturn {\r\n\t Graph: __webpack_require__(1).Graph,\r\n\t Queue: __webpack_require__(1).Queue\r\n\t};\r\n\t});\r\n\r\n\r\n/***/ },\r\n/* 1 */\r\n/***/ function(module, exports, __webpack_require__) {\r\n\r\n\t(function() {\r\n\t module.exports = {\r\n\t Graph: __webpack_require__(2),\r\n\t Heap: __webpack_require__(3),\r\n\t LinkedList: __webpack_require__(4),\r\n\t Map: __webpack_require__(5),\r\n\t Queue: __webpack_require__(6),\r\n\t RedBlackTree: __webpack_require__(7),\r\n\t Trie: __webpack_require__(8)\r\n\t };\r\n\r\n\t}).call(this);\r\n\r\n\r\n/***/ },\r\n/* 2 */\r\n/***/ function(module, exports) {\r\n\r\n\t/*\r\n\tGraph implemented as a modified incidence list. O(1) for every typical\r\n\toperation except `removeNode()` at O(E) where E is the number of edges.\r\n\r\n\t## Overview example:\r\n\r\n\t```js\r\n\tvar graph = new Graph;\r\n\tgraph.addNode('A'); // => a node object. For more info, log the output or check\r\n\t // the documentation for addNode\r\n\tgraph.addNode('B');\r\n\tgraph.addNode('C');\r\n\tgraph.addEdge('A', 'C'); // => an edge object\r\n\tgraph.addEdge('A', 'B');\r\n\tgraph.getEdge('B', 'A'); // => undefined. Directed edge!\r\n\tgraph.getEdge('A', 'B'); // => the edge object previously added\r\n\tgraph.getEdge('A', 'B').weight = 2 // weight is the only built-in handy property\r\n\t // of an edge object. Feel free to attach\r\n\t // other properties\r\n\tgraph.getInEdgesOf('B'); // => array of edge objects, in this case only one;\r\n\t // connecting A to B\r\n\tgraph.getOutEdgesOf('A'); // => array of edge objects, one to B and one to C\r\n\tgraph.getAllEdgesOf('A'); // => all the in and out edges. Edge directed toward\r\n\t // the node itself are only counted once\r\n\tforEachNode(function(nodeObject) {\r\n\t console.log(node);\r\n\t});\r\n\tforEachEdge(function(edgeObject) {\r\n\t console.log(edgeObject);\r\n\t});\r\n\tgraph.removeNode('C'); // => 'C'. The edge between A and C also removed\r\n\tgraph.removeEdge('A', 'B'); // => the edge object removed\r\n\t```\r\n\r\n\t## Properties:\r\n\r\n\t- nodeSize: total number of nodes.\r\n\t- edgeSize: total number of edges.\r\n\t*/\r\n\r\n\r\n\t(function() {\r\n\t var Graph,\r\n\t __hasProp = {}.hasOwnProperty;\r\n\r\n\t Graph = (function() {\r\n\t function Graph() {\r\n\t this._nodes = {};\r\n\t this.nodeSize = 0;\r\n\t this.edgeSize = 0;\r\n\t }\r\n\r\n\t Graph.prototype.addNode = function(id) {\r\n\t /*\r\n\t The `id` is a unique identifier for the node, and should **not** change\r\n\t after it's added. It will be used for adding, retrieving and deleting\r\n\t related edges too.\r\n\t \r\n\t **Note** that, internally, the ids are kept in an object. JavaScript's\r\n\t object hashes the id `'2'` and `2` to the same key, so please stick to a\r\n\t simple id data type such as number or string.\r\n\t \r\n\t _Returns:_ the node object. Feel free to attach additional custom properties\r\n\t on it for graph algorithms' needs. **Undefined if node id already exists**,\r\n\t as to avoid accidental overrides.\r\n\t */\r\n\r\n\t if (!this._nodes[id]) {\r\n\t this.nodeSize++;\r\n\t return this._nodes[id] = {\r\n\t _outEdges: {},\r\n\t _inEdges: {}\r\n\t };\r\n\t }\r\n\t };\r\n\r\n\t Graph.prototype.getNode = function(id) {\r\n\t /*\r\n\t _Returns:_ the node object. Feel free to attach additional custom properties\r\n\t on it for graph algorithms' needs.\r\n\t */\r\n\r\n\t return this._nodes[id];\r\n\t };\r\n\r\n\t Graph.prototype.removeNode = function(id) {\r\n\t /*\r\n\t _Returns:_ the node object removed, or undefined if it didn't exist in the\r\n\t first place.\r\n\t */\r\n\r\n\t var inEdgeId, nodeToRemove, outEdgeId, _ref, _ref1;\r\n\t nodeToRemove = this._nodes[id];\r\n\t if (!nodeToRemove) {\r\n\t return;\r\n\t } else {\r\n\t _ref = nodeToRemove._outEdges;\r\n\t for (outEdgeId in _ref) {\r\n\t if (!__hasProp.call(_ref, outEdgeId)) continue;\r\n\t this.removeEdge(id, outEdgeId);\r\n\t }\r\n\t _ref1 = nodeToRemove._inEdges;\r\n\t for (inEdgeId in _ref1) {\r\n\t if (!__hasProp.call(_ref1, inEdgeId)) continue;\r\n\t this.removeEdge(inEdgeId, id);\r\n\t }\r\n\t this.nodeSize--;\r\n\t delete this._nodes[id];\r\n\t }\r\n\t return nodeToRemove;\r\n\t };\r\n\r\n\t Graph.prototype.addEdge = function(fromId, toId, weight) {\r\n\t var edgeToAdd, fromNode, toNode;\r\n\t if (weight == null) {\r\n\t weight = 1;\r\n\t }\r\n\t /*\r\n\t `fromId` and `toId` are the node id specified when it was created using\r\n\t `addNode()`. `weight` is optional and defaults to 1. Ignoring it effectively\r\n\t makes this an unweighted graph. Under the hood, `weight` is just a normal\r\n\t property of the edge object.\r\n\t \r\n\t _Returns:_ the edge object created. Feel free to attach additional custom\r\n\t properties on it for graph algorithms' needs. **Or undefined** if the nodes\r\n\t of id `fromId` or `toId` aren't found, or if an edge already exists between\r\n\t the two nodes.\r\n\t */\r\n\r\n\t if (this.getEdge(fromId, toId)) {\r\n\t return;\r\n\t }\r\n\t fromNode = this._nodes[fromId];\r\n\t toNode = this._nodes[toId];\r\n\t if (!fromNode || !toNode) {\r\n\t return;\r\n\t }\r\n\t edgeToAdd = {\r\n\t weight: weight\r\n\t };\r\n\t fromNode._outEdges[toId] = edgeToAdd;\r\n\t toNode._inEdges[fromId] = edgeToAdd;\r\n\t this.edgeSize++;\r\n\t return edgeToAdd;\r\n\t };\r\n\r\n\t Graph.prototype.getEdge = function(fromId, toId) {\r\n\t /*\r\n\t _Returns:_ the edge object, or undefined if the nodes of id `fromId` or\r\n\t `toId` aren't found.\r\n\t */\r\n\r\n\t var fromNode, toNode;\r\n\t fromNode = this._nodes[fromId];\r\n\t toNode = this._nodes[toId];\r\n\t if (!fromNode || !toNode) {\r\n\r\n\t } else {\r\n\t return fromNode._outEdges[toId];\r\n\t }\r\n\t };\r\n\r\n\t Graph.prototype.removeEdge = function(fromId, toId) {\r\n\t /*\r\n\t _Returns:_ the edge object removed, or undefined of edge wasn't found.\r\n\t */\r\n\r\n\t var edgeToDelete, fromNode, toNode;\r\n\t fromNode = this._nodes[fromId];\r\n\t toNode = this._nodes[toId];\r\n\t edgeToDelete = this.getEdge(fromId, toId);\r\n\t if (!edgeToDelete) {\r\n\t return;\r\n\t }\r\n\t delete fromNode._outEdges[toId];\r\n\t delete toNode._inEdges[fromId];\r\n\t this.edgeSize--;\r\n\t return edgeToDelete;\r\n\t };\r\n\r\n\t Graph.prototype.getInEdgesOf = function(nodeId) {\r\n\t /*\r\n\t _Returns:_ an array of edge objects that are directed toward the node, or\r\n\t empty array if no such edge or node exists.\r\n\t */\r\n\r\n\t var fromId, inEdges, toNode, _ref;\r\n\t toNode = this._nodes[nodeId];\r\n\t inEdges = [];\r\n\t _ref = toNode != null ? toNode._inEdges : void 0;\r\n\t for (fromId in _ref) {\r\n\t if (!__hasProp.call(_ref, fromId)) continue;\r\n\t inEdges.push(this.getEdge(fromId, nodeId));\r\n\t }\r\n\t return inEdges;\r\n\t };\r\n\r\n\t Graph.prototype.getOutEdgesOf = function(nodeId) {\r\n\t /*\r\n\t _Returns:_ an array of edge objects that go out of the node, or empty array\r\n\t if no such edge or node exists.\r\n\t */\r\n\r\n\t var fromNode, outEdges, toId, _ref;\r\n\t fromNode = this._nodes[nodeId];\r\n\t outEdges = [];\r\n\t _ref = fromNode != null ? fromNode._outEdges : void 0;\r\n\t for (toId in _ref) {\r\n\t if (!__hasProp.call(_ref, toId)) continue;\r\n\t outEdges.push(this.getEdge(nodeId, toId));\r\n\t }\r\n\t return outEdges;\r\n\t };\r\n\r\n\t Graph.prototype.getAllEdgesOf = function(nodeId) {\r\n\t /*\r\n\t **Note:** not the same as concatenating `getInEdgesOf()` and\r\n\t `getOutEdgesOf()`. Some nodes might have an edge pointing toward itself.\r\n\t This method solves that duplication.\r\n\t \r\n\t _Returns:_ an array of edge objects linked to the node, no matter if they're\r\n\t outgoing or coming. Duplicate edge created by self-pointing nodes are\r\n\t removed. Only one copy stays. Empty array if node has no edge.\r\n\t */\r\n\r\n\t var i, inEdges, outEdges, selfEdge, _i, _ref, _ref1;\r\n\t inEdges = this.getInEdgesOf(nodeId);\r\n\t outEdges = this.getOutEdgesOf(nodeId);\r\n\t if (inEdges.length === 0) {\r\n\t return outEdges;\r\n\t }\r\n\t selfEdge = this.getEdge(nodeId, nodeId);\r\n\t for (i = _i = 0, _ref = inEdges.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {\r\n\t if (inEdges[i] === selfEdge) {\r\n\t _ref1 = [inEdges[inEdges.length - 1], inEdges[i]], inEdges[i] = _ref1[0], inEdges[inEdges.length - 1] = _ref1[1];\r\n\t inEdges.pop();\r\n\t break;\r\n\t }\r\n\t }\r\n\t return inEdges.concat(outEdges);\r\n\t };\r\n\r\n\t Graph.prototype.forEachNode = function(operation) {\r\n\t /*\r\n\t Traverse through the graph in an arbitrary manner, visiting each node once.\r\n\t Pass a function of the form `fn(nodeObject, nodeId)`.\r\n\t \r\n\t _Returns:_ undefined.\r\n\t */\r\n\r\n\t var nodeId, nodeObject, _ref;\r\n\t _ref = this._nodes;\r\n\t for (nodeId in _ref) {\r\n\t if (!__hasProp.call(_ref, nodeId)) continue;\r\n\t nodeObject = _ref[nodeId];\r\n\t operation(nodeObject, nodeId);\r\n\t }\r\n\t };\r\n\r\n\t Graph.prototype.forEachEdge = function(operation) {\r\n\t /*\r\n\t Traverse through the graph in an arbitrary manner, visiting each edge once.\r\n\t Pass a function of the form `fn(edgeObject)`.\r\n\t \r\n\t _Returns:_ undefined.\r\n\t */\r\n\r\n\t var edgeObject, nodeId, nodeObject, toId, _ref, _ref1;\r\n\t _ref = this._nodes;\r\n\t for (nodeId in _ref) {\r\n\t if (!__hasProp.call(_ref, nodeId)) continue;\r\n\t nodeObject = _ref[nodeId];\r\n\t _ref1 = nodeObject._outEdges;\r\n\t for (toId in _ref1) {\r\n\t if (!__hasProp.call(_ref1, toId)) continue;\r\n\t edgeObject = _ref1[toId];\r\n\t operation(edgeObject);\r\n\t }\r\n\t }\r\n\t };\r\n\r\n\t return Graph;\r\n\r\n\t })();\r\n\r\n\t module.exports = Graph;\r\n\r\n\t}).call(this);\r\n\r\n\r\n/***/ },\r\n/* 3 */\r\n/***/ function(module, exports) {\r\n\r\n\t/*\r\n\tMinimum heap, i.e. smallest node at root.\r\n\r\n\t**Note:** does not accept null or undefined. This is by design. Those values\r\n\tcause comparison problems and might report false negative during extraction.\r\n\r\n\t## Overview example:\r\n\r\n\t```js\r\n\tvar heap = new Heap([5, 6, 3, 4]);\r\n\theap.add(10); // => 10\r\n\theap.removeMin(); // => 3\r\n\theap.peekMin(); // => 4\r\n\t```\r\n\r\n\t## Properties:\r\n\r\n\t- size: total number of items.\r\n\t*/\r\n\r\n\r\n\t(function() {\r\n\t var Heap, _leftChild, _parent, _rightChild;\r\n\r\n\t Heap = (function() {\r\n\t function Heap(dataToHeapify) {\r\n\t var i, item, _i, _j, _len, _ref;\r\n\t if (dataToHeapify == null) {\r\n\t dataToHeapify = [];\r\n\t }\r\n\t /*\r\n\t Pass an optional array to be heapified. Takes only O(n) time.\r\n\t */\r\n\r\n\t this._data = [void 0];\r\n\t for (_i = 0, _len = dataToHeapify.length; _i < _len; _i++) {\r\n\t item = dataToHeapify[_i];\r\n\t if (item != null) {\r\n\t this._data.push(item);\r\n\t }\r\n\t }\r\n\t if (this._data.length > 1) {\r\n\t for (i = _j = 2, _ref = this._data.length; 2 <= _ref ? _j < _ref : _j > _ref; i = 2 <= _ref ? ++_j : --_j) {\r\n\t this._upHeap(i);\r\n\t }\r\n\t }\r\n\t this.size = this._data.length - 1;\r\n\t }\r\n\r\n\t Heap.prototype.add = function(value) {\r\n\t /*\r\n\t **Remember:** rejects null and undefined for mentioned reasons.\r\n\t \r\n\t _Returns:_ the value added.\r\n\t */\r\n\r\n\t if (value == null) {\r\n\t return;\r\n\t }\r\n\t this._data.push(value);\r\n\t this._upHeap(this._data.length - 1);\r\n\t this.size++;\r\n\t return value;\r\n\t };\r\n\r\n\t Heap.prototype.removeMin = function() {\r\n\t /*\r\n\t _Returns:_ the smallest item (the root).\r\n\t */\r\n\r\n\t var min;\r\n\t if (this._data.length === 1) {\r\n\t return;\r\n\t }\r\n\t this.size--;\r\n\t if (this._data.length === 2) {\r\n\t return this._data.pop();\r\n\t }\r\n\t min = this._data[1];\r\n\t this._data[1] = this._data.pop();\r\n\t this._downHeap();\r\n\t return min;\r\n\t };\r\n\r\n\t Heap.prototype.peekMin = function() {\r\n\t /*\r\n\t Check the smallest item without removing it.\r\n\t \r\n\t _Returns:_ the smallest item (the root).\r\n\t */\r\n\r\n\t return this._data[1];\r\n\t };\r\n\r\n\t Heap.prototype._upHeap = function(index) {\r\n\t var valueHolder, _ref;\r\n\t valueHolder = this._data[index];\r\n\t while (this._data[index] < this._data[_parent(index)] && index > 1) {\r\n\t _ref = [this._data[_parent(index)], this._data[index]], this._data[index] = _ref[0], this._data[_parent(index)] = _ref[1];\r\n\t index = _parent(index);\r\n\t }\r\n\t };\r\n\r\n\t Heap.prototype._downHeap = function() {\r\n\t var currentIndex, smallerChildIndex, _ref;\r\n\t currentIndex = 1;\r\n\t while (_leftChild(currentIndex < this._data.length)) {\r\n\t smallerChildIndex = _leftChild(currentIndex);\r\n\t if (smallerChildIndex < this._data.length - 1) {\r\n\t if (this._data[_rightChild(currentIndex)] < this._data[smallerChildIndex]) {\r\n\t smallerChildIndex = _rightChild(currentIndex);\r\n\t }\r\n\t }\r\n\t if (this._data[smallerChildIndex] < this._data[currentIndex]) {\r\n\t _ref = [this._data[currentIndex], this._data[smallerChildIndex]], this._data[smallerChildIndex] = _ref[0], this._data[currentIndex] = _ref[1];\r\n\t currentIndex = smallerChildIndex;\r\n\t } else {\r\n\t break;\r\n\t }\r\n\t }\r\n\t };\r\n\r\n\t return Heap;\r\n\r\n\t })();\r\n\r\n\t _parent = function(index) {\r\n\t return index >> 1;\r\n\t };\r\n\r\n\t _leftChild = function(index) {\r\n\t return index << 1;\r\n\t };\r\n\r\n\t _rightChild = function(index) {\r\n\t return (index << 1) + 1;\r\n\t };\r\n\r\n\t module.exports = Heap;\r\n\r\n\t}).call(this);\r\n\r\n\r\n/***/ },\r\n/* 4 */\r\n/***/ function(module, exports) {\r\n\r\n\t/*\r\n\tDoubly Linked.\r\n\r\n\t## Overview example:\r\n\r\n\t```js\r\n\tvar list = new LinkedList([5, 4, 9]);\r\n\tlist.add(12); // => 12\r\n\tlist.head.next.value; // => 4\r\n\tlist.tail.value; // => 12\r\n\tlist.at(-1); // => 12\r\n\tlist.removeAt(2); // => 9\r\n\tlist.remove(4); // => 4\r\n\tlist.indexOf(5); // => 0\r\n\tlist.add(5, 1); // => 5. Second 5 at position 1.\r\n\tlist.indexOf(5, 1); // => 1\r\n\t```\r\n\r\n\t## Properties:\r\n\r\n\t- head: first item.\r\n\t- tail: last item.\r\n\t- size: total number of items.\r\n\t- item.value: value passed to the item when calling `add()`.\r\n\t- item.prev: previous item.\r\n\t- item.next: next item.\r\n\t*/\r\n\r\n\r\n\t(function() {\r\n\t var LinkedList;\r\n\r\n\t LinkedList = (function() {\r\n\t function LinkedList(valuesToAdd) {\r\n\t var value, _i, _len;\r\n\t if (valuesToAdd == null) {\r\n\t valuesToAdd = [];\r\n\t }\r\n\t /*\r\n\t Can pass an array of elements to link together during `new LinkedList()`\r\n\t initiation.\r\n\t */\r\n\r\n\t this.head = {\r\n\t prev: void 0,\r\n\t value: void 0,\r\n\t next: void 0\r\n\t };\r\n\t this.tail = {\r\n\t prev: void 0,\r\n\t value: void 0,\r\n\t next: void 0\r\n\t };\r\n\t this.size = 0;\r\n\t for (_i = 0, _len = valuesToAdd.length; _i < _len; _i++) {\r\n\t value = valuesToAdd[_i];\r\n\t this.add(value);\r\n\t }\r\n\t }\r\n\r\n\t LinkedList.prototype.at = function(position) {\r\n\t /*\r\n\t Get the item at `position` (optional). Accepts negative index:\r\n\t \r\n\t ```js\r\n\t myList.at(-1); // Returns the last element.\r\n\t ```\r\n\t However, passing a negative index that surpasses the boundary will return\r\n\t undefined:\r\n\t \r\n\t ```js\r\n\t myList = new LinkedList([2, 6, 8, 3])\r\n\t myList.at(-5); // Undefined.\r\n\t myList.at(-4); // 2.\r\n\t ```\r\n\t _Returns:_ item gotten, or undefined if not found.\r\n\t */\r\n\r\n\t var currentNode, i, _i, _j, _ref;\r\n\t if (!((-this.size <= position && position < this.size))) {\r\n\t return;\r\n\t }\r\n\t position = this._adjust(position);\r\n\t if (position * 2 < this.size) {\r\n\t currentNode = this.head;\r\n\t for (i = _i = 1; _i <= position; i = _i += 1) {\r\n\t currentNode = currentNode.next;\r\n\t }\r\n\t } else {\r\n\t currentNode = this.tail;\r\n\t for (i = _j = 1, _ref = this.size - position - 1; _j <= _ref; i = _j += 1) {\r\n\t currentNode = currentNode.prev;\r\n\t }\r\n\t }\r\n\t return currentNode;\r\n\t };\r\n\r\n\t LinkedList.prototype.add = function(value, position) {\r\n\t var currentNode, nodeToAdd, _ref, _ref1, _ref2;\r\n\t if (position == null) {\r\n\t position = this.size;\r\n\t }\r\n\t /*\r\n\t Add a new item at `position` (optional). Defaults to adding at the end.\r\n\t `position`, just like in `at()`, can be negative (within the negative\r\n\t boundary). Position specifies the place the value's going to be, and the old\r\n\t node will be pushed higher. `add(-2)` on list of size 7 is the same as\r\n\t `add(5)`.\r\n\t \r\n\t _Returns:_ item added.\r\n\t */\r\n\r\n\t if (!((-this.size <= position && position <= this.size))) {\r\n\t return;\r\n\t }\r\n\t nodeToAdd = {\r\n\t value: value\r\n\t };\r\n\t position = this._adjust(position);\r\n\t if (this.size === 0) {\r\n\t this.head = nodeToAdd;\r\n\t } else {\r\n\t if (position === 0) {\r\n\t _ref = [nodeToAdd, this.head, nodeToAdd], this.head.prev = _ref[0], nodeToAdd.next = _ref[1], this.head = _ref[2];\r\n\t } else {\r\n\t currentNode = this.at(position - 1);\r\n\t _ref1 = [currentNode.next, nodeToAdd, nodeToAdd, currentNode], nodeToAdd.next = _ref1[0], (_ref2 = currentNode.next) != null ? _ref2.prev = _ref1[1] : void 0, currentNode.next = _ref1[2], nodeToAdd.prev = _ref1[3];\r\n\t }\r\n\t }\r\n\t if (position === this.size) {\r\n\t this.tail = nodeToAdd;\r\n\t }\r\n\t this.size++;\r\n\t return value;\r\n\t };\r\n\r\n\t LinkedList.prototype.removeAt = function(position) {\r\n\t var currentNode, valueToReturn, _ref;\r\n\t if (position == null) {\r\n\t position = this.size - 1;\r\n\t }\r\n\t /*\r\n\t Remove an item at index `position` (optional). Defaults to the last item.\r\n\t Index can be negative (within the boundary).\r\n\t \r\n\t _Returns:_ item removed.\r\n\t */\r\n\r\n\t if (!((-this.size <= position && position < this.size))) {\r\n\t return;\r\n\t }\r\n\t if (this.size === 0) {\r\n\t return;\r\n\t }\r\n\t position = this._adjust(position);\r\n\t if (this.size === 1) {\r\n\t valueToReturn = this.head.value;\r\n\t this.head.value = this.tail.value = void 0;\r\n\t } else {\r\n\t if (position === 0) {\r\n\t valueToReturn = this.head.value;\r\n\t this.head = this.head.next;\r\n\t this.head.prev = void 0;\r\n\t } else {\r\n\t currentNode = this.at(position);\r\n\t valueToReturn = currentNode.value;\r\n\t currentNode.prev.next = currentNode.next;\r\n\t if ((_ref = currentNode.next) != null) {\r\n\t _ref.prev = currentNode.prev;\r\n\t }\r\n\t if (position === this.size - 1) {\r\n\t this.tail = currentNode.prev;\r\n\t }\r\n\t }\r\n\t }\r\n\t this.size--;\r\n\t return valueToReturn;\r\n\t };\r\n\r\n\t LinkedList.prototype.remove = function(value) {\r\n\t /*\r\n\t Remove the item using its value instead of position. **Will remove the fist\r\n\t occurrence of `value`.**\r\n\t \r\n\t _Returns:_ the value, or undefined if value's not found.\r\n\t */\r\n\r\n\t var currentNode;\r\n\t if (value == null) {\r\n\t return;\r\n\t }\r\n\t currentNode = this.head;\r\n\t while (currentNode && currentNode.value !== value) {\r\n\t currentNode = currentNode.next;\r\n\t }\r\n\t if (!currentNode) {\r\n\t return;\r\n\t }\r\n\t if (this.size === 1) {\r\n\t this.head.value = this.tail.value = void 0;\r\n\t } else if (currentNode === this.head) {\r\n\t this.head = this.head.next;\r\n\t this.head.prev = void 0;\r\n\t } else if (currentNode === this.tail) {\r\n\t this.tail = this.tail.prev;\r\n\t this.tail.next = void 0;\r\n\t } else {\r\n\t currentNode.prev.next = currentNode.next;\r\n\t currentNode.next.prev = currentNode.prev;\r\n\t }\r\n\t this.size--;\r\n\t return value;\r\n\t };\r\n\r\n\t LinkedList.prototype.indexOf = function(value, startingPosition) {\r\n\t var currentNode, position;\r\n\t if (startingPosition == null) {\r\n\t startingPosition = 0;\r\n\t }\r\n\t /*\r\n\t Find the index of an item, similarly to `array.indexOf()`. Defaults to start\r\n\t searching from the beginning, by can start at another position by passing\r\n\t `startingPosition`. This parameter can also be negative; but unlike the\r\n\t other methods of this class, `startingPosition` (optional) can be as small\r\n\t as desired; a value of -999 for a list of size 5 will start searching\r\n\t normally, at the beginning.\r\n\t \r\n\t **Note:** searches forwardly, **not** backwardly, i.e:\r\n\t \r\n\t ```js\r\n\t var myList = new LinkedList([2, 3, 1, 4, 3, 5])\r\n\t myList.indexOf(3, -3); // Returns 4, not 1\r\n\t ```\r\n\t _Returns:_ index of item found, or -1 if not found.\r\n\t */\r\n\r\n\t if (((this.head.value == null) && !this.head.next) || startingPosition >= this.size) {\r\n\t return -1;\r\n\t }\r\n\t startingPosition = Math.max(0, this._adjust(startingPosition));\r\n\t currentNode = this.at(startingPosition);\r\n\t position = startingPosition;\r\n\t while (currentNode) {\r\n\t if (currentNode.value === value) {\r\n\t break;\r\n\t }\r\n\t currentNode = currentNode.next;\r\n\t position++;\r\n\t }\r\n\t if (position === this.size) {\r\n\t return -1;\r\n\t } else {\r\n\t return position;\r\n\t }\r\n\t };\r\n\r\n\t LinkedList.prototype._adjust = function(position) {\r\n\t if (position < 0) {\r\n\t return this.size + position;\r\n\t } else {\r\n\t return position;\r\n\t }\r\n\t };\r\n\r\n\t return LinkedList;\r\n\r\n\t })();\r\n\r\n\t module.exports = LinkedList;\r\n\r\n\t}).call(this);\r\n\r\n\r\n/***/ },\r\n/* 5 */\r\n/***/ function(module, exports) {\r\n\r\n\t/*\r\n\tKind of a stopgap measure for the upcoming [JavaScript\r\n\tMap](http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets)\r\n\r\n\t**Note:** due to JavaScript's limitations, hashing something other than Boolean,\r\n\tNumber, String, Undefined, Null, RegExp, Function requires a hack that inserts a\r\n\thidden unique property into the object. This means `set`, `get`, `has` and\r\n\t`delete` must employ the same object, and not a mere identical copy as in the\r\n\tcase of, say, a string.\r\n\r\n\t## Overview example:\r\n\r\n\t```js\r\n\tvar map = new Map({'alice': 'wonderland', 20: 'ok'});\r\n\tmap.set('20', 5); // => 5\r\n\tmap.get('20'); // => 5\r\n\tmap.has('alice'); // => true\r\n\tmap.delete(20) // => true\r\n\tvar arr = [1, 2];\r\n\tmap.add(arr, 'goody'); // => 'goody'\r\n\tmap.has(arr); // => true\r\n\tmap.has([1, 2]); // => false. Needs to compare by reference\r\n\tmap.forEach(function(key, value) {\r\n\t console.log(key, value);\r\n\t});\r\n\t```\r\n\r\n\t## Properties:\r\n\r\n\t- size: The total number of `(key, value)` pairs.\r\n\t*/\r\n\r\n\r\n\t(function() {\r\n\t var Map, SPECIAL_TYPE_KEY_PREFIX, _extractDataType, _isSpecialType,\r\n\t __hasProp = {}.hasOwnProperty;\r\n\r\n\t SPECIAL_TYPE_KEY_PREFIX = '_mapId_';\r\n\r\n\t Map = (function() {\r\n\t Map._mapIdTracker = 0;\r\n\r\n\t Map._newMapId = function() {\r\n\t return this._mapIdTracker++;\r\n\t };\r\n\r\n\t function Map(objectToMap) {\r\n\t /*\r\n\t Pass an optional object whose (key, value) pair will be hashed. **Careful**\r\n\t not to pass something like {5: 'hi', '5': 'hello'}, since JavaScript's\r\n\t native object behavior will crush the first 5 property before it gets to\r\n\t constructor.\r\n\t */\r\n\r\n\t var key, value;\r\n\t this._content = {};\r\n\t this._itemId = 0;\r\n\t this._id = Map._newMapId();\r\n\t this.size = 0;\r\n\t for (key in objectToMap) {\r\n\t if (!__hasProp.call(objectToMap, key)) continue;\r\n\t value = objectToMap[key];\r\n\t this.set(key, value);\r\n\t }\r\n\t }\r\n\r\n\t Map.prototype.hash = function(key, makeHash) {\r\n\t var propertyForMap, type;\r\n\t if (makeHash == null) {\r\n\t makeHash = false;\r\n\t }\r\n\t /*\r\n\t The hash function for hashing keys is public. Feel free to replace it with\r\n\t your own. The `makeHash` parameter is optional and accepts a boolean\r\n\t (defaults to `false`) indicating whether or not to produce a new hash (for\r\n\t the first use, naturally).\r\n\t \r\n\t _Returns:_ the hash.\r\n\t */\r\n\r\n\t type = _extractDataType(key);\r\n\t if (_isSpecialType(key)) {\r\n\t propertyForMap = SPECIAL_TYPE_KEY_PREFIX + this._id;\r\n\t if (makeHash && !key[propertyForMap]) {\r\n\t key[propertyForMap] = this._itemId++;\r\n\t }\r\n\t return propertyForMap + '_' + key[propertyForMap];\r\n\t } else {\r\n\t return type + '_' + key;\r\n\t }\r\n\t };\r\n\r\n\t Map.prototype.set = function(key, value) {\r\n\t /*\r\n\t _Returns:_ value.\r\n\t */\r\n\r\n\t if (!this.has(key)) {\r\n\t this.size++;\r\n\t }\r\n\t this._content[this.hash(key, true)] = [value, key];\r\n\t return value;\r\n\t };\r\n\r\n\t Map.prototype.get = function(key) {\r\n\t /*\r\n\t _Returns:_ value corresponding to the key, or undefined if not found.\r\n\t */\r\n\r\n\t var _ref;\r\n\t return (_ref = this._content[this.hash(key)]) != null ? _ref[0] : void 0;\r\n\t };\r\n\r\n\t Map.prototype.has = function(key) {\r\n\t /*\r\n\t Check whether a value exists for the key.\r\n\t \r\n\t _Returns:_ true or false.\r\n\t */\r\n\r\n\t return this.hash(key) in this._content;\r\n\t };\r\n\r\n\t Map.prototype[\"delete\"] = function(key) {\r\n\t /*\r\n\t Remove the (key, value) pair.\r\n\t \r\n\t _Returns:_ **true or false**. Unlike most of this library, this method\r\n\t doesn't return the deleted value. This is so that it conforms to the future\r\n\t JavaScript `map.delete()`'s behavior.\r\n\t */\r\n\r\n\t var hashedKey;\r\n\t hashedKey = this.hash(key);\r\n\t if (hashedKey in this._content) {\r\n\t delete this._content[hashedKey];\r\n\t if (_isSpecialType(key)) {\r\n\t delete key[SPECIAL_TYPE_KEY_PREFIX + this._id];\r\n\t }\r\n\t this.size--;\r\n\t return true;\r\n\t }\r\n\t return false;\r\n\t };\r\n\r\n\t Map.prototype.forEach = function(operation) {\r\n\t /*\r\n\t Traverse through the map. Pass a function of the form `fn(key, value)`.\r\n\t \r\n\t _Returns:_ undefined.\r\n\t */\r\n\r\n\t var key, value, _ref;\r\n\t _ref = this._content;\r\n\t for (key in _ref) {\r\n\t if (!__hasProp.call(_ref, key)) continue;\r\n\t value = _ref[key];\r\n\t operation(value[1], value[0]);\r\n\t }\r\n\t };\r\n\r\n\t return Map;\r\n\r\n\t })();\r\n\r\n\t _isSpecialType = function(key) {\r\n\t var simpleHashableTypes, simpleType, type, _i, _len;\r\n\t simpleHashableTypes = ['Boolean', 'Number', 'String', 'Undefined', 'Null', 'RegExp', 'Function'];\r\n\t type = _extractDataType(key);\r\n\t for (_i = 0, _len = simpleHashableTypes.length; _i < _len; _i++) {\r\n\t simpleType = simpleHashableTypes[_i];\r\n\t if (type === simpleType) {\r\n\t return false;\r\n\t }\r\n\t }\r\n\t return true;\r\n\t };\r\n\r\n\t _extractDataType = function(type) {\r\n\t return Object.prototype.toString.apply(type).match(/\\[object (.+)\\]/)[1];\r\n\t };\r\n\r\n\t module.exports = Map;\r\n\r\n\t}).call(this);\r\n\r\n\r\n/***/ },\r\n/* 6 */\r\n/***/ function(module, exports) {\r\n\r\n\t/*\r\n\tAmortized O(1) dequeue!\r\n\r\n\t## Overview example:\r\n\r\n\t```js\r\n\tvar queue = new Queue([1, 6, 4]);\r\n\tqueue.enqueue(10); // => 10\r\n\tqueue.dequeue(); // => 1\r\n\tqueue.dequeue(); // => 6\r\n\tqueue.dequeue(); // => 4\r\n\tqueue.peek(); // => 10\r\n\tqueue.dequeue(); // => 10\r\n\tqueue.peek(); // => undefined\r\n\t```\r\n\r\n\t## Properties:\r\n\r\n\t- size: The total number of items.\r\n\t*/\r\n\r\n\r\n\t(function() {\r\n\t var Queue;\r\n\r\n\t Queue = (function() {\r\n\t function Queue(initialArray) {\r\n\t if (initialArray == null) {\r\n\t initialArray = [];\r\n\t }\r\n\t /*\r\n\t Pass an optional array to be transformed into a queue. The item at index 0\r\n\t is the first to be dequeued.\r\n\t */\r\n\r\n\t this._content = initialArray;\r\n\t this._dequeueIndex = 0;\r\n\t this.size = this._content.length;\r\n\t }\r\n\r\n\t Queue.prototype.enqueue = function(item) {\r\n\t /*\r\n\t _Returns:_ the item.\r\n\t */\r\n\r\n\t this.size++;\r\n\t this._content.push(item);\r\n\t return item;\r\n\t };\r\n\r\n\t Queue.prototype.dequeue = function() {\r\n\t /*\r\n\t _Returns:_ the dequeued item.\r\n\t */\r\n\r\n\t var itemToDequeue;\r\n\t if (this.size === 0) {\r\n\t return;\r\n\t }\r\n\t this.size--;\r\n\t itemToDequeue = this._content[this._dequeueIndex];\r\n\t this._dequeueIndex++;\r\n\t if (this._dequeueIndex * 2 > this._content.length) {\r\n\t this._content = this._content.slice(this._dequeueIndex);\r\n\t this._dequeueIndex = 0;\r\n\t }\r\n\t return itemToDequeue;\r\n\t };\r\n\r\n\t Queue.prototype.peek = function() {\r\n\t /*\r\n\t Check the next item to be dequeued, without removing it.\r\n\t \r\n\t _Returns:_ the item.\r\n\t */\r\n\r\n\t return this._content[this._dequeueIndex];\r\n\t };\r\n\r\n\t return Queue;\r\n\r\n\t })();\r\n\r\n\t module.exports = Queue;\r\n\r\n\t}).call(this);\r\n\r\n\r\n/***/ },\r\n/* 7 */\r\n/***/ function(module, exports) {\r\n\r\n\t/*\r\n\tCredit to Wikipedia's article on [Red-black\r\n\ttree](http://en.wikipedia.org/wiki/Red–black_tree)\r\n\r\n\t**Note:** doesn't handle duplicate entries, undefined and null. This is by\r\n\tdesign.\r\n\r\n\t## Overview example:\r\n\r\n\t```js\r\n\tvar rbt = new RedBlackTree([7, 5, 1, 8]);\r\n\trbt.add(2); // => 2\r\n\trbt.add(10); // => 10\r\n\trbt.has(5); // => true\r\n\trbt.peekMin(); // => 1\r\n\trbt.peekMax(); // => 10\r\n\trbt.removeMin(); // => 1\r\n\trbt.removeMax(); // => 10\r\n\trbt.remove(8); // => 8\r\n\t```\r\n\r\n\t## Properties:\r\n\r\n\t- size: The total number of items.\r\n\t*/\r\n\r\n\r\n\t(function() {\r\n\t var BLACK, NODE_FOUND, NODE_TOO_BIG, NODE_TOO_SMALL, RED, RedBlackTree, STOP_SEARCHING, _findNode, _grandParentOf, _isLeft, _leftOrRight, _peekMaxNode, _peekMinNode, _siblingOf, _uncleOf;\r\n\r\n\t NODE_FOUND = 0;\r\n\r\n\t NODE_TOO_BIG = 1;\r\n\r\n\t NODE_TOO_SMALL = 2;\r\n\r\n\t STOP_SEARCHING = 3;\r\n\r\n\t RED = 1;\r\n\r\n\t BLACK = 2;\r\n\r\n\t RedBlackTree = (function() {\r\n\t function RedBlackTree(valuesToAdd) {\r\n\t var value, _i, _len;\r\n\t if (valuesToAdd == null) {\r\n\t valuesToAdd = [];\r\n\t }\r\n\t /*\r\n\t Pass an optional array to be turned into binary tree. **Note:** does not\r\n\t accept duplicate, undefined and null.\r\n\t */\r\n\r\n\t this._root;\r\n\t this.size = 0;\r\n\t for (_i = 0, _len = valuesToAdd.length; _i < _len; _i++) {\r\n\t value = valuesToAdd[_i];\r\n\t if (value != null) {\r\n\t this.add(value);\r\n\t }\r\n\t }\r\n\t }\r\n\r\n\t RedBlackTree.prototype.add = function(value) {\r\n\t /*\r\n\t Again, make sure to not pass a value already in the tree, or undefined, or\r\n\t null.\r\n\t \r\n\t _Returns:_ value added.\r\n\t */\r\n\r\n\t var currentNode, foundNode, nodeToInsert, _ref;\r\n\t if (value == null) {\r\n\t return;\r\n\t }\r\n\t this.size++;\r\n\t nodeToInsert = {\r\n\t value: value,\r\n\t _color: RED\r\n\t };\r\n\t if (!this._root) {\r\n\t this._root = nodeToInsert;\r\n\t } else {\r\n\t foundNode = _findNode(this._root, function(node) {\r\n\t if (value === node.value) {\r\n\t return NODE_FOUND;\r\n\t } else {\r\n\t if (value < node.value) {\r\n\t if (node._left) {\r\n\t return NODE_TOO_BIG;\r\n\t } else {\r\n\t nodeToInsert._parent = node;\r\n\t node._left = nodeToInsert;\r\n\t return STOP_SEARCHING;\r\n\t }\r\n\t } else {\r\n\t if (node._right) {\r\n\t return NODE_TOO_SMALL;\r\n\t } else {\r\n\t nodeToInsert._parent = node;\r\n\t node._right = nodeToInsert;\r\n\t return STOP_SEARCHING;\r\n\t }\r\n\t }\r\n\t }\r\n\t });\r\n\t if (foundNode != null) {\r\n\t return;\r\n\t }\r\n\t }\r\n\t currentNode = nodeToInsert;\r\n\t while (true) {\r\n\t if (currentNode === this._root) {\r\n\t currentNode._color = BLACK;\r\n\t break;\r\n\t }\r\n\t if (currentNode._parent._color === BLACK) {\r\n\t break;\r\n\t }\r\n\t if (((_ref = _uncleOf(currentNode)) != null ? _ref._color : void 0) === RED) {\r\n\t currentNode._parent._color = BLACK;\r\n\t _uncleOf(currentNode)._color = BLACK;\r\n\t _grandParentOf(currentNode)._color = RED;\r\n\t currentNode = _grandParentOf(currentNode);\r\n\t continue;\r\n\t }\r\n\t if (!_isLeft(currentNode) && _isLeft(currentNode._parent)) {\r\n\t this._rotateLeft(currentNode._parent);\r\n\t currentNode = currentNode._left;\r\n\t } else if (_isLeft(currentNode) && !_isLeft(currentNode._parent)) {\r\n\t this._rotateRight(currentNode._parent);\r\n\t currentNode = currentNode._right;\r\n\t }\r\n\t currentNode._parent._color = BLACK;\r\n\t _grandParentOf(currentNode)._color = RED;\r\n\t if (_isLeft(currentNode)) {\r\n\t this._rotateRight(_grandParentOf(currentNode));\r\n\t } else {\r\n\t this._rotateLeft(_grandParentOf(currentNode));\r\n\t }\r\n\t break;\r\n\t }\r\n\t return value;\r\n\t };\r\n\r\n\t RedBlackTree.prototype.has = function(value) {\r\n\t /*\r\n\t _Returns:_ true or false.\r\n\t */\r\n\r\n\t var foundNode;\r\n\t foundNode = _findNode(this._root, function(node) {\r\n\t if (value === node.value) {\r\n\t return NODE_FOUND;\r\n\t } else if (value < node.value) {\r\n\t return NODE_TOO_BIG;\r\n\t } else {\r\n\t return NODE_TOO_SMALL;\r\n\t }\r\n\t });\r\n\t if (foundNode) {\r\n\t return true;\r\n\t } else {\r\n\t return false;\r\n\t }\r\n\t };\r\n\r\n\t RedBlackTree.prototype.peekMin = function() {\r\n\t /*\r\n\t Check the minimum value without removing it.\r\n\t \r\n\t _Returns:_ the minimum value.\r\n\t */\r\n\r\n\t var _ref;\r\n\t return (_ref = _peekMinNode(this._root)) != null ? _ref.value : void 0;\r\n\t };\r\n\r\n\t RedBlackTree.prototype.peekMax = function() {\r\n\t /*\r\n\t Check the maximum value without removing it.\r\n\t \r\n\t _Returns:_ the maximum value.\r\n\t */\r\n\r\n\t var _ref;\r\n\t return (_ref = _peekMaxNode(this._root)) != null ? _ref.value : void 0;\r\n\t };\r\n\r\n\t RedBlackTree.prototype.remove = function(value) {\r\n\t /*\r\n\t _Returns:_ the value removed, or undefined if the value's not found.\r\n\t */\r\n\r\n\t var foundNode;\r\n\t foundNode = _findNode(this._root, function(node) {\r\n\t if (value === node.value) {\r\n\t return NODE_FOUND;\r\n\t } else if (value < node.value) {\r\n\t return NODE_TOO_BIG;\r\n\t } else {\r\n\t return NODE_TOO_SMALL;\r\n\t }\r\n\t });\r\n\t if (!foundNode) {\r\n\t return;\r\n\t }\r\n\t this._removeNode(this._root, foundNode);\r\n\t this.size--;\r\n\t return value;\r\n\t };\r\n\r\n\t RedBlackTree.prototype.removeMin = function() {\r\n\t /*\r\n\t _Returns:_ smallest item removed, or undefined if tree's empty.\r\n\t */\r\n\r\n\t var nodeToRemove, valueToReturn;\r\n\t nodeToRemove = _peekMinNode(this._root);\r\n\t if (!nodeToRemove) {\r\n\t return;\r\n\t }\r\n\t valueToReturn = nodeToRemove.value;\r\n\t this._removeNode(this._root, nodeToRemove);\r\n\t return valueToReturn;\r\n\t };\r\n\r\n\t RedBlackTree.prototype.removeMax = function() {\r\n\t /*\r\n\t _Returns:_ biggest item removed, or undefined if tree's empty.\r\n\t */\r\n\r\n\t var nodeToRemove, valueToReturn;\r\n\t nodeToRemove = _peekMaxNode(this._root);\r\n\t if (!nodeToRemove) {\r\n\t return;\r\n\t }\r\n\t valueToReturn = nodeToRemove.value;\r\n\t this._removeNode(this._root, nodeToRemove);\r\n\t return valueToReturn;\r\n\t };\r\n\r\n\t RedBlackTree.prototype._removeNode = function(root, node) {\r\n\t var sibling, successor, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7;\r\n\t if (node._left && node._right) {\r\n\t successor = _peekMinNode(node._right);\r\n\t node.value = successor.value;\r\n\t node = successor;\r\n\t }\r\n\t successor = node._left || node._right;\r\n\t if (!successor) {\r\n\t successor = {\r\n\t color: BLACK,\r\n\t _right: void 0,\r\n\t _left: void 0,\r\n\t isLeaf: true\r\n\t };\r\n\t }\r\n\t successor._parent = node._parent;\r\n\t if ((_ref = node._parent) != null) {\r\n\t _ref[_leftOrRight(node)] = successor;\r\n\t }\r\n\t if (node._color === BLACK) {\r\n\t if (successor._color === RED) {\r\n\t successor._color = BLACK;\r\n\t if (!successor._parent) {\r\n\t this._root = successor;\r\n\t }\r\n\t } else {\r\n\t while (true) {\r\n\t if (!successor._parent) {\r\n\t if (!successor.isLeaf) {\r\n\t this._root = successor;\r\n\t } else {\r\n\t this._root = void 0;\r\n\t }\r\n\t break;\r\n\t }\r\n\t sibling = _siblingOf(successor);\r\n\t if ((sibling != null ? sibling._color : void 0) === RED) {\r\n\t successor._parent._color = RED;\r\n\t sibling._color = BLACK;\r\n\t if (_isLeft(successor)) {\r\n\t this._rotateLeft(successor._parent);\r\n\t } else {\r\n\t this._rotateRight(successor._parent);\r\n\t }\r\n\t }\r\n\t sibling = _siblingOf(successor);\r\n\t if (successor._parent._color === BLACK && (!sibling || (sibling._color === BLACK && (!sibling._left || sibling._left._color === BLACK) && (!sibling._right || sibling._right._color === BLACK)))) {\r\n\t if (sibling != null) {\r\n\t sibling._color = RED;\r\n\t }\r\n\t if (successor.isLeaf) {\r\n\t successor._parent[_leftOrRight(successor)] = void 0;\r\n\t }\r\n\t successor = successor._parent;\r\n\t continue;\r\n\t }\r\n\t if (successor._parent._color === RED && (!sibling || (sibling._color === BLACK && (!sibling._left || ((_ref1 = sibling._left) != null ? _ref1._color : void 0) === BLACK) && (!sibling._right || ((_ref2 = sibling._right) != null ? _ref2._color : void 0) === BLACK)))) {\r\n\t if (sibling != null) {\r\n\t sibling._color = RED;\r\n\t }\r\n\t successor._parent._color = BLACK;\r\n\t break;\r\n\t }\r\n\t if ((sibling != null ? sibling._color : void 0) === BLACK) {\r\n\t if (_isLeft(successor) && (!sibling._right || sibling._right._color === BLACK) && ((_ref3 = sibling._left) != null ? _ref3._color : void 0) === RED) {\r\n\t sibling._color = RED;\r\n\t if ((_ref4 = sibling._left) != null) {\r\n\t _ref4._color = BLACK;\r\n\t }\r\n\t this._rotateRight(sibling);\r\n\t } else if (!_isLeft(successor) && (!sibling._left || sibling._left._color === BLACK) && ((_ref5 = sibling._right) != null ? _ref5._color : void 0) === RED) {\r\n\t sibling._color = RED;\r\n\t if ((_ref6 = sibling._right) != null) {\r\n\t _ref6._color = BLACK;\r\n\t }\r\n\t this._rotateLeft(sibling);\r\n\t }\r\n\t break;\r\n\t }\r\n\t sibling = _siblingOf(successor);\r\n\t sibling._color = successor._parent._color;\r\n\t if (_isLeft(successor)) {\r\n\t sibling._right._color = BLACK;\r\n\t this._rotateRight(successor._parent);\r\n\t } else {\r\n\t sibling._left._color = BLACK;\r\n\t this._rotateLeft(successor._parent);\r\n\t }\r\n\t }\r\n\t }\r\n\t }\r\n\t if (successor.isLeaf) {\r\n\t return (_ref7 = successor._parent) != null ? _ref7[_leftOrRight(successor)] = void 0 : void 0;\r\n\t }\r\n\t };\r\n\r\n\t RedBlackTree.prototype._rotateLeft = function(node) {\r\n\t var _ref, _ref1;\r\n\t if ((_ref = node._parent) != null) {\r\n\t _ref[_leftOrRight(node)] = node._right;\r\n\t }\r\n\t node._right._parent = node._parent;\r\n\t node._parent = node._right;\r\n\t node._right = node._right._left;\r\n\t node._parent._left = node;\r\n\t if ((_ref1 = node._right) != null) {\r\n\t _ref1._parent = node;\r\n\t }\r\n\t if (node._parent._parent == null) {\r\n\t return this._root = node._parent;\r\n\t }\r\n\t };\r\n\r\n\t RedBlackTree.prototype._rotateRight = function(node) {\r\n\t var _ref, _ref1;\r\n\t if ((_ref = node._parent) != null) {\r\n\t _ref[_leftOrRight(node)] = node._left;\r\n\t }\r\n\t node._left._parent = node._parent;\r\n\t node._parent = node._left;\r\n\t node._left = node._left._right;\r\n\t node._parent._right = node;\r\n\t if ((_ref1 = node._left) != null) {\r\n\t _ref1._parent = node;\r\n\t }\r\n\t if (node._parent._parent == null) {\r\n\t return this._root = node._parent;\r\n\t }\r\n\t };\r\n\r\n\t return RedBlackTree;\r\n\r\n\t })();\r\n\r\n\t _isLeft = function(node) {\r\n\t return node === node._parent._left;\r\n\t };\r\n\r\n\t _leftOrRight = function(node) {\r\n\t if (_isLeft(node)) {\r\n\t return '_left';\r\n\t } else {\r\n\t return '_right';\r\n\t }\r\n\t };\r\n\r\n\t _findNode = function(startingNode, comparator) {\r\n\t var comparisonResult, currentNode, foundNode;\r\n\t currentNode = startingNode;\r\n\t foundNode = void 0;\r\n\t while (currentNode) {\r\n\t comparisonResult = comparator(currentNode);\r\n\t if (comparisonResult === NODE_FOUND) {\r\n\t foundNode = currentNode;\r\n\t break;\r\n\t }\r\n\t if (comparisonResult === NODE_TOO_BIG) {\r\n\t currentNode = currentNode._left;\r\n\t } else if (comparisonResult === NODE_TOO_SMALL) {\r\n\t currentNode = currentNode._right;\r\n\t } else if (comparisonResult === STOP_SEARCHING) {\r\n\t break;\r\n\t }\r\n\t }\r\n\t return foundNode;\r\n\t };\r\n\r\n\t _peekMinNode = function(startingNode) {\r\n\t return _findNode(startingNode, function(node) {\r\n\t if (node._left) {\r\n\t return NODE_TOO_BIG;\r\n\t } else {\r\n\t return NODE_FOUND;\r\n\t }\r\n\t });\r\n\t };\r\n\r\n\t _peekMaxNode = function(startingNode) {\r\n\t return _findNode(startingNode, function(node) {\r\n\t if (node._right) {\r\n\t return NODE_TOO_SMALL;\r\n\t } else {\r\n\t return NODE_FOUND;\r\n\t }\r\n\t });\r\n\t };\r\n\r\n\t _grandParentOf = function(node) {\r\n\t var _ref;\r\n\t return (_ref = node._parent) != null ? _ref._parent : void 0;\r\n\t };\r\n\r\n\t _uncleOf = function(node) {\r\n\t if (!_grandParentOf(node)) {\r\n\t return;\r\n\t }\r\n\t if (_isLeft(node._parent)) {\r\n\t return _grandParentOf(node)._right;\r\n\t } else {\r\n\t return _grandParentOf(node)._left;\r\n\t }\r\n\t };\r\n\r\n\t _siblingOf = function(node) {\r\n\t if (_isLeft(node)) {\r\n\t return node._parent._right;\r\n\t } else {\r\n\t return node._parent._left;\r\n\t }\r\n\t };\r\n\r\n\t module.exports = RedBlackTree;\r\n\r\n\t}).call(this);\r\n\r\n\r\n/***/ },\r\n/* 8 */\r\n/***/ function(module, exports, __webpack_require__) {\r\n\r\n\t/*\r\n\tGood for fast insertion/removal/lookup of strings.\r\n\r\n\t## Overview example:\r\n\r\n\t```js\r\n\tvar trie = new Trie(['bear', 'beer']);\r\n\ttrie.add('hello'); // => 'hello'\r\n\ttrie.add('helloha!'); // => 'helloha!'\r\n\ttrie.has('bears'); // => false\r\n\ttrie.longestPrefixOf('beatrice'); // => 'bea'\r\n\ttrie.wordsWithPrefix('hel'); // => ['hello', 'helloha!']\r\n\ttrie.remove('beers'); // => undefined. 'beer' still exists\r\n\ttrie.remove('Beer') // => undefined. Case-sensitive\r\n\ttrie.remove('beer') // => 'beer'. Removed\r\n\t```\r\n\r\n\t## Properties:\r\n\r\n\t- size: The total number of words.\r\n\t*/\r\n\r\n\r\n\t(function() {\r\n\t var Queue, Trie, WORD_END, _hasAtLeastNChildren,\r\n\t __hasProp = {}.hasOwnProperty;\r\n\r\n\t Queue = __webpack_require__(6);\r\n\r\n\t WORD_END = 'end';\r\n\r\n\t Trie = (function() {\r\n\t function Trie(words) {\r\n\t var word, _i, _len;\r\n\t if (words == null) {\r\n\t words = [];\r\n\t }\r\n\t /*\r\n\t Pass an optional array of strings to be inserted initially.\r\n\t */\r\n\r\n\t this._root = {};\r\n\t this.size = 0;\r\n\t for (_i = 0, _len = words.length; _i < _len; _i++) {\r\n\t word = words[_i];\r\n\t this.add(word);\r\n\t }\r\n\t }\r\n\r\n\t Trie.prototype.add = function(word) {\r\n\t /*\r\n\t Add a whole string to the trie.\r\n\t \r\n\t _Returns:_ the word added. Will return undefined (without adding the value)\r\n\t if the word passed is null or undefined.\r\n\t */\r\n\r\n\t var currentNode, letter, _i, _len;\r\n\t if (word == null) {\r\n\t return;\r\n\t }\r\n\t this.size++;\r\n\t currentNode = this._root;\r\n\t for (_i = 0, _len = word.length; _i < _len; _i++) {\r\n\t letter = word[_i];\r\n\t if (currentNode[letter] == null) {\r\n\t currentNode[letter] = {};\r\n\t }\r\n\t currentNode = currentNode[letter];\r\n\t }\r\n\t currentNode[WORD_END] = true;\r\n\t return word;\r\n\t };\r\n\r\n\t Trie.prototype.has = function(word) {\r\n\t /*\r\n\t __Returns:_ true or false.\r\n\t */\r\n\r\n\t var currentNode, letter, _i, _len;\r\n\t if (word == null) {\r\n\t return false;\r\n\t }\r\n\t currentNode = this._root;\r\n\t for (_i = 0, _len = word.length; _i < _len; _i++) {\r\n\t letter = word[_i];\r\n\t if (currentNode[letter] == null) {\r\n\t return false;\r\n\t }\r\n\t currentNode = currentNode[letter];\r\n\t }\r\n\t if (currentNode[WORD_END]) {\r\n\t return true;\r\n\t } else {\r\n\t return false;\r\n\t }\r\n\t };\r\n\r\n\t Trie.prototype.longestPrefixOf = function(word) {\r\n\t /*\r\n\t Find all words containing the prefix. The word itself counts as a prefix.\r\n\t \r\n\t ```js\r\n\t var trie = new Trie;\r\n\t trie.add('hello');\r\n\t trie.longestPrefixOf('he'); // 'he'\r\n\t trie.longestPrefixOf('hello'); // 'hello'\r\n\t trie.longestPrefixOf('helloha!'); // 'hello'\r\n\t ```\r\n\t \r\n\t _Returns:_ the prefix string, or empty string if no prefix found.\r\n\t */\r\n\r\n\t var currentNode, letter, prefix, _i, _len;\r\n\t if (word == null) {\r\n\t return '';\r\n\t }\r\n\t currentNode = this._root;\r\n\t prefix = '';\r\n\t for (_i = 0, _len = word.length; _i < _len; _i++) {\r\n\t letter = word[_i];\r\n\t if (currentNode[letter] == null) {\r\n\t break;\r\n\t }\r\n\t prefix += letter;\r\n\t currentNode = currentNode[letter];\r\n\t }\r\n\t return prefix;\r\n\t };\r\n\r\n\t Trie.prototype.wordsWithPrefix = function(prefix) {\r\n\t /*\r\n\t Find all words containing the prefix. The word itself counts as a prefix.\r\n\t **Watch out for edge cases.**\r\n\t \r\n\t ```js\r\n\t var trie = new Trie;\r\n\t trie.wordsWithPrefix(''); // []. Check later case below.\r\n\t trie.add('');\r\n\t trie.wordsWithPrefix(''); // ['']\r\n\t trie.add('he');\r\n\t trie.add('hello');\r\n\t trie.add('hell');\r\n\t trie.add('bear');\r\n\t trie.add('z');\r\n\t trie.add('zebra');\r\n\t trie.wordsWithPrefix('hel'); // ['hell', 'hello']\r\n\t ```\r\n\t \r\n\t _Returns:_ an array of strings, or empty array if no word found.\r\n\t */\r\n\r\n\t var accumulatedLetters, currentNode, letter, node, queue, subNode, words, _i, _len, _ref;\r\n\t if (prefix == null) {\r\n\t return [];\r\n\t }\r\n\t (prefix != null) || (prefix = '');\r\n\t words = [];\r\n\t currentNode = this._root;\r\n\t for (_i = 0, _len = prefix.length; _i < _len; _i++) {\r\n\t letter = prefix[_i];\r\n\t currentNode = currentNode[letter];\r\n\t if (currentNode == null) {\r\n\t return [];\r\n\t }\r\n\t }\r\n\t queue = new Queue();\r\n\t queue.enqueue([currentNode, '']);\r\n\t while (queue.size !== 0) {\r\n\t _ref = queue.dequeue(), node = _ref[0], accumulatedLetters = _ref[1];\r\n\t if (node[WORD_END]) {\r\n\t words.push(prefix + accumulatedLetters);\r\n\t }\r\n\t for (letter in node) {\r\n\t if (!__hasProp.call(node, letter)) continue;\r\n\t subNode = node[letter];\r\n\t queue.enqueue([subNode, accumulatedLetters + letter]);\r\n\t }\r\n\t }\r\n\t return words;\r\n\t };\r\n\r\n\t Trie.prototype.remove = function(word) {\r\n\t /*\r\n\t _Returns:_ the string removed, or undefined if the word in its whole doesn't\r\n\t exist. **Note:** this means removing `beers` when only `beer` exists will\r\n\t return undefined and conserve `beer`.\r\n\t */\r\n\r\n\t var currentNode, i, letter, prefix, _i, _j, _len, _ref;\r\n\t if (word == null) {\r\n\t return;\r\n\t }\r\n\t currentNode = this._root;\r\n\t prefix = [];\r\n\t for (_i = 0, _len = word.length; _i < _len; _i++) {\r\n\t letter = word[_i];\r\n\t if (currentNode[letter] == null) {\r\n\t return;\r\n\t }\r\n\t currentNode = currentNode[letter];\r\n\t prefix.push([letter, currentNode]);\r\n\t }\r\n\t if (!currentNode[WORD_END]) {\r\n\t return;\r\n\t }\r\n\t this.size--;\r\n\t delete currentNode[WORD_END];\r\n\t if (_hasAtLeastNChildren(currentNode, 1)) {\r\n\t return word;\r\n\t }\r\n\t for (i = _j = _ref = prefix.length - 1; _ref <= 1 ? _j <= 1 : _j >= 1; i = _ref <= 1 ? ++_j : --_j) {\r\n\t if (!_hasAtLeastNChildren(prefix[i][1], 1)) {\r\n\t delete prefix[i - 1][1][prefix[i][0]];\r\n\t } else {\r\n\t break;\r\n\t }\r\n\t }\r\n\t if (!_hasAtLeastNChildren(this._root[prefix[0][0]], 1)) {\r\n\t delete this._root[prefix[0][0]];\r\n\t }\r\n\t return word;\r\n\t };\r\n\r\n\t return Trie;\r\n\r\n\t })();\r\n\r\n\t _hasAtLeastNChildren = function(node, n) {\r\n\t var child, childCount;\r\n\t if (n === 0) {\r\n\t return true;\r\n\t }\r\n\t childCount = 0;\r\n\t for (child in node) {\r\n\t if (!__hasProp.call(node, child)) continue;\r\n\t childCount++;\r\n\t if (childCount >= n) {\r\n\t return true;\r\n\t }\r\n\t }\r\n\t return false;\r\n\t };\r\n\r\n\t module.exports = Trie;\r\n\r\n\t}).call(this);\r\n\r\n\r\n/***/ }\r\n/******/ ]);;angular.module('uiGmapgoogle-maps.wrapped')\r\n.service('uiGmapMarkerSpiderfier', [ 'uiGmapGoogleMapApi', function(GoogleMapApi) {\r\n var self = this;\r\n //BEGIN REPLACE\r\n \r\n/** @preserve OverlappingMarkerSpiderfier\r\nhttps://github.com/jawj/OverlappingMarkerSpiderfier\r\nCopyright (c) 2011 - 2013 George MacKerron\r\nReleased under the MIT licence: http://opensource.org/licenses/mit-license\r\nNote: The Google Maps API v3 must be included *before* this code\r\n */\r\nvar hasProp = {}.hasOwnProperty,\r\n slice = [].slice;\r\n\r\nthis['OverlappingMarkerSpiderfier'] = (function() {\r\n var ge, gm, j, lcH, lcU, len, mt, p, ref, twoPi, x;\r\n\r\n p = _Class.prototype;\r\n\r\n ref = [_Class, p];\r\n for (j = 0, len = ref.length; j < len; j++) {\r\n x = ref[j];\r\n x['VERSION'] = '0.3.3';\r\n }\r\n\r\n gm = void 0;\r\n\r\n ge = void 0;\r\n\r\n mt = void 0;\r\n\r\n twoPi = Math.PI * 2;\r\n\r\n p['keepSpiderfied'] = false;\r\n\r\n p['markersWontHide'] = false;\r\n\r\n p['markersWontMove'] = false;\r\n\r\n p['nearbyDistance'] = 20;\r\n\r\n p['circleSpiralSwitchover'] = 9;\r\n\r\n p['circleFootSeparation'] = 23;\r\n\r\n p['circleStartAngle'] = twoPi / 12;\r\n\r\n p['spiralFootSeparation'] = 26;\r\n\r\n p['spiralLengthStart'] = 11;\r\n\r\n p['spiralLengthFactor'] = 4;\r\n\r\n p['spiderfiedZIndex'] = 1000;\r\n\r\n p['usualLegZIndex'] = 10;\r\n\r\n p['highlightedLegZIndex'] = 20;\r\n\r\n p['event'] = 'click';\r\n\r\n p['minZoomLevel'] = false;\r\n\r\n p['legWeight'] = 1.5;\r\n\r\n p['legColors'] = {\r\n 'usual': {},\r\n 'highlighted': {}\r\n };\r\n\r\n lcU = p['legColors']['usual'];\r\n\r\n lcH = p['legColors']['highlighted'];\r\n\r\n _Class['initializeGoogleMaps'] = function(google) {\r\n gm = google.maps;\r\n ge = gm.event;\r\n mt = gm.MapTypeId;\r\n lcU[mt.HYBRID] = lcU[mt.SATELLITE] = '#fff';\r\n lcH[mt.HYBRID] = lcH[mt.SATELLITE] = '#f00';\r\n lcU[mt.TERRAIN] = lcU[mt.ROADMAP] = '#444';\r\n lcH[mt.TERRAIN] = lcH[mt.ROADMAP] = '#f00';\r\n this.ProjHelper = function(map) {\r\n return this.setMap(map);\r\n };\r\n this.ProjHelper.prototype = new gm.OverlayView();\r\n return this.ProjHelper.prototype['draw'] = function() {};\r\n };\r\n\r\n function _Class(map1, opts) {\r\n var e, k, l, len1, ref1, v;\r\n this.map = map1;\r\n if (opts == null) {\r\n opts = {};\r\n }\r\n for (k in opts) {\r\n if (!hasProp.call(opts, k)) continue;\r\n v = opts[k];\r\n this[k] = v;\r\n }\r\n this.projHelper = new this.constructor.ProjHelper(this.map);\r\n this.initMarkerArrays();\r\n this.listeners = {};\r\n ref1 = ['click', 'zoom_changed', 'maptypeid_changed'];\r\n for (l = 0, len1 = ref1.length; l < len1; l++) {\r\n e = ref1[l];\r\n ge.addListener(this.map, e, (function(_this) {\r\n return function() {\r\n return _this['unspiderfy']();\r\n };\r\n })(this));\r\n }\r\n }\r\n\r\n p.initMarkerArrays = function() {\r\n this.markers = [];\r\n return this.markerListenerRefs = [];\r\n };\r\n\r\n p['addMarker'] = function(marker) {\r\n var listenerRefs;\r\n if (marker['_oms'] != null) {\r\n return this;\r\n }\r\n marker['_oms'] = true;\r\n listenerRefs = [\r\n ge.addListener(marker, this['event'], (function(_this) {\r\n return function(event) {\r\n return _this.spiderListener(marker, event);\r\n };\r\n })(this))\r\n ];\r\n if (!this['markersWontHide']) {\r\n listenerRefs.push(ge.addListener(marker, 'visible_changed', (function(_this) {\r\n return function() {\r\n return _this.markerChangeListener(marker, false);\r\n };\r\n })(this)));\r\n }\r\n if (!this['markersWontMove']) {\r\n listenerRefs.push(ge.addListener(marker, 'position_changed', (function(_this) {\r\n return function() {\r\n return _this.markerChangeListener(marker, true);\r\n };\r\n })(this)));\r\n }\r\n this.markerListenerRefs.push(listenerRefs);\r\n this.markers.push(marker);\r\n return this;\r\n };\r\n\r\n p.markerChangeListener = function(marker, positionChanged) {\r\n if ((marker['_omsData'] != null) && (positionChanged || !marker.getVisible()) && !((this.spiderfying != null) || (this.unspiderfying != null))) {\r\n return this['unspiderfy'](positionChanged ? marker : null);\r\n }\r\n };\r\n\r\n p['getMarkers'] = function() {\r\n return this.markers.slice(0);\r\n };\r\n\r\n p['removeMarker'] = function(marker) {\r\n var i, l, len1, listenerRef, listenerRefs;\r\n if (marker['_omsData'] != null) {\r\n this['unspiderfy']();\r\n }\r\n i = this.arrIndexOf(this.markers, marker);\r\n if (i < 0) {\r\n return this;\r\n }\r\n listenerRefs = this.markerListenerRefs.splice(i, 1)[0];\r\n for (l = 0, len1 = listenerRefs.length; l < len1; l++) {\r\n listenerRef = listenerRefs[l];\r\n ge.removeListener(listenerRef);\r\n }\r\n delete marker['_oms'];\r\n this.markers.splice(i, 1);\r\n return this;\r\n };\r\n\r\n p['clearMarkers'] = function() {\r\n var i, l, len1, len2, listenerRef, listenerRefs, marker, n, ref1;\r\n this['unspiderfy']();\r\n ref1 = this.markers;\r\n for (i = l = 0, len1 = ref1.length; l < len1; i = ++l) {\r\n marker = ref1[i];\r\n listenerRefs = this.markerListenerRefs[i];\r\n for (n = 0, len2 = listenerRefs.length; n < len2; n++) {\r\n listenerRef = listenerRefs[n];\r\n ge.removeListener(listenerRef);\r\n }\r\n delete marker['_oms'];\r\n }\r\n this.initMarkerArrays();\r\n return this;\r\n };\r\n\r\n p['addListener'] = function(event, func) {\r\n var base;\r\n ((base = this.listeners)[event] != null ? base[event] : base[event] = []).push(func);\r\n return this;\r\n };\r\n\r\n p['removeListener'] = function(event, func) {\r\n var i;\r\n i = this.arrIndexOf(this.listeners[event], func);\r\n if (!(i < 0)) {\r\n this.listeners[event].splice(i, 1);\r\n }\r\n return this;\r\n };\r\n\r\n p['clearListeners'] = function(event) {\r\n this.listeners[event] = [];\r\n return this;\r\n };\r\n\r\n p.trigger = function() {\r\n var args, event, func, l, len1, ref1, ref2, results;\r\n event = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];\r\n ref2 = (ref1 = this.listeners[event]) != null ? ref1 : [];\r\n results = [];\r\n for (l = 0, len1 = ref2.length; l < len1; l++) {\r\n func = ref2[l];\r\n results.push(func.apply(null, args));\r\n }\r\n return results;\r\n };\r\n\r\n p.generatePtsCircle = function(count, centerPt) {\r\n var angle, angleStep, circumference, i, l, legLength, ref1, results;\r\n circumference = this['circleFootSeparation'] * (2 + count);\r\n legLength = circumference / twoPi;\r\n angleStep = twoPi / count;\r\n results = [];\r\n for (i = l = 0, ref1 = count; 0 <= ref1 ? l < ref1 : l > ref1; i = 0 <= ref1 ? ++l : --l) {\r\n angle = this['circleStartAngle'] + i * angleStep;\r\n results.push(new gm.Point(centerPt.x + legLength * Math.cos(angle), centerPt.y + legLength * Math.sin(angle)));\r\n }\r\n return results;\r\n };\r\n\r\n p.generatePtsSpiral = function(count, centerPt) {\r\n var angle, i, l, legLength, pt, ref1, results;\r\n legLength = this['spiralLengthStart'];\r\n angle = 0;\r\n results = [];\r\n for (i = l = 0, ref1 = count; 0 <= ref1 ? l < ref1 : l > ref1; i = 0 <= ref1 ? ++l : --l) {\r\n angle += this['spiralFootSeparation'] / legLength + i * 0.0005;\r\n pt = new gm.Point(centerPt.x + legLength * Math.cos(angle), centerPt.y + legLength * Math.sin(angle));\r\n legLength += twoPi * this['spiralLengthFactor'] / angle;\r\n results.push(pt);\r\n }\r\n return results;\r\n };\r\n\r\n p.spiderListener = function(marker, event) {\r\n var $this, clear, l, len1, m, mPt, markerPt, markerSpiderfied, nDist, nearbyMarkerData, nonNearbyMarkers, pxSq, ref1;\r\n markerSpiderfied = marker['_omsData'] != null;\r\n if (!(markerSpiderfied && this['keepSpiderfied'])) {\r\n if (this['event'] === 'mouseover') {\r\n $this = this;\r\n clear = function() {\r\n return $this['unspiderfy']();\r\n };\r\n window.clearTimeout(p.timeout);\r\n p.timeout = setTimeout(clear, 3000);\r\n } else {\r\n this['unspiderfy']();\r\n }\r\n }\r\n if (markerSpiderfied || this.map.getStreetView().getVisible() || this.map.getMapTypeId() === 'GoogleEarthAPI') {\r\n return this.trigger('click', marker, event);\r\n } else {\r\n nearbyMarkerData = [];\r\n nonNearbyMarkers = [];\r\n nDist = this['nearbyDistance'];\r\n pxSq = nDist * nDist;\r\n markerPt = this.llToPt(marker.position);\r\n ref1 = this.markers;\r\n for (l = 0, len1 = ref1.length; l < len1; l++) {\r\n m = ref1[l];\r\n if (!((m.map != null) && m.getVisible())) {\r\n continue;\r\n }\r\n mPt = this.llToPt(m.position);\r\n if (this.ptDistanceSq(mPt, markerPt) < pxSq) {\r\n nearbyMarkerData.push({\r\n marker: m,\r\n markerPt: mPt\r\n });\r\n } else {\r\n nonNearbyMarkers.push(m);\r\n }\r\n }\r\n if (nearbyMarkerData.length === 1) {\r\n return this.trigger('click', marker, event);\r\n } else {\r\n return this.spiderfy(nearbyMarkerData, nonNearbyMarkers);\r\n }\r\n }\r\n };\r\n\r\n p['markersNearMarker'] = function(marker, firstOnly) {\r\n var l, len1, m, mPt, markerPt, markers, nDist, pxSq, ref1, ref2, ref3;\r\n if (firstOnly == null) {\r\n firstOnly = false;\r\n }\r\n if (this.projHelper.getProjection() == null) {\r\n throw \"Must wait for 'idle' event on map before calling markersNearMarker\";\r\n }\r\n nDist = this['nearbyDistance'];\r\n pxSq = nDist * nDist;\r\n markerPt = this.llToPt(marker.position);\r\n markers = [];\r\n ref1 = this.markers;\r\n for (l = 0, len1 = ref1.length; l < len1; l++) {\r\n m = ref1[l];\r\n if (m === marker || (m.map == null) || !m.getVisible()) {\r\n continue;\r\n }\r\n mPt = this.llToPt((ref2 = (ref3 = m['_omsData']) != null ? ref3.usualPosition : void 0) != null ? ref2 : m.position);\r\n if (this.ptDistanceSq(mPt, markerPt) < pxSq) {\r\n markers.push(m);\r\n if (firstOnly) {\r\n break;\r\n }\r\n }\r\n }\r\n return markers;\r\n };\r\n\r\n p['markersNearAnyOtherMarker'] = function() {\r\n var i, i1, i2, l, len1, len2, len3, m, m1, m1Data, m2, m2Data, mData, n, nDist, pxSq, q, ref1, ref2, ref3, results;\r\n if (this.projHelper.getProjection() == null) {\r\n throw \"Must wait for 'idle' event on map before calling markersNearAnyOtherMarker\";\r\n }\r\n nDist = this['nearbyDistance'];\r\n pxSq = nDist * nDist;\r\n mData = (function() {\r\n var l, len1, ref1, ref2, ref3, results;\r\n ref1 = this.markers;\r\n results = [];\r\n for (l = 0, len1 = ref1.length; l < len1; l++) {\r\n m = ref1[l];\r\n results.push({\r\n pt: this.llToPt((ref2 = (ref3 = m['_omsData']) != null ? ref3.usualPosition : void 0) != null ? ref2 : m.position),\r\n willSpiderfy: false\r\n });\r\n }\r\n return results;\r\n }).call(this);\r\n ref1 = this.markers;\r\n for (i1 = l = 0, len1 = ref1.length; l < len1; i1 = ++l) {\r\n m1 = ref1[i1];\r\n if (!((m1.map != null) && m1.getVisible())) {\r\n continue;\r\n }\r\n m1Data = mData[i1];\r\n if (m1Data.willSpiderfy) {\r\n continue;\r\n }\r\n ref2 = this.markers;\r\n for (i2 = n = 0, len2 = ref2.length; n < len2; i2 = ++n) {\r\n m2 = ref2[i2];\r\n if (i2 === i1) {\r\n continue;\r\n }\r\n if (!((m2.map != null) && m2.getVisible())) {\r\n continue;\r\n }\r\n m2Data = mData[i2];\r\n if (i2 < i1 && !m2Data.willSpiderfy) {\r\n continue;\r\n }\r\n if (this.ptDistanceSq(m1Data.pt, m2Data.pt) < pxSq) {\r\n m1Data.willSpiderfy = m2Data.willSpiderfy = true;\r\n break;\r\n }\r\n }\r\n }\r\n ref3 = this.markers;\r\n results = [];\r\n for (i = q = 0, len3 = ref3.length; q < len3; i = ++q) {\r\n m = ref3[i];\r\n if (mData[i].willSpiderfy) {\r\n results.push(m);\r\n }\r\n }\r\n return results;\r\n };\r\n\r\n p.makeHighlightListenerFuncs = function(marker) {\r\n return {\r\n highlight: (function(_this) {\r\n return function() {\r\n return marker['_omsData'].leg.setOptions({\r\n strokeColor: _this['legColors']['highlighted'][_this.map.mapTypeId],\r\n zIndex: _this['highlightedLegZIndex']\r\n });\r\n };\r\n })(this),\r\n unhighlight: (function(_this) {\r\n return function() {\r\n return marker['_omsData'].leg.setOptions({\r\n strokeColor: _this['legColors']['usual'][_this.map.mapTypeId],\r\n zIndex: _this['usualLegZIndex']\r\n });\r\n };\r\n })(this)\r\n };\r\n };\r\n\r\n p.spiderfy = function(markerData, nonNearbyMarkers) {\r\n var bodyPt, footLl, footPt, footPts, highlightListenerFuncs, leg, marker, md, nearestMarkerDatum, numFeet, spiderfiedMarkers;\r\n if (this['minZoomLevel'] && this.map.getZoom() < this['minZoomLevel']) {\r\n return false;\r\n }\r\n this.spiderfying = true;\r\n numFeet = markerData.length;\r\n bodyPt = this.ptAverage((function() {\r\n var l, len1, results;\r\n results = [];\r\n for (l = 0, len1 = markerData.length; l < len1; l++) {\r\n md = markerData[l];\r\n results.push(md.markerPt);\r\n }\r\n return results;\r\n })());\r\n footPts = numFeet >= this['circleSpiralSwitchover'] ? this.generatePtsSpiral(numFeet, bodyPt).reverse() : this.generatePtsCircle(numFeet, bodyPt);\r\n spiderfiedMarkers = (function() {\r\n var l, len1, results;\r\n results = [];\r\n for (l = 0, len1 = footPts.length; l < len1; l++) {\r\n footPt = footPts[l];\r\n footLl = this.ptToLl(footPt);\r\n nearestMarkerDatum = this.minExtract(markerData, (function(_this) {\r\n return function(md) {\r\n return _this.ptDistanceSq(md.markerPt, footPt);\r\n };\r\n })(this));\r\n marker = nearestMarkerDatum.marker;\r\n leg = new gm.Polyline({\r\n map: this.map,\r\n path: [marker.position, footLl],\r\n strokeColor: this['legColors']['usual'][this.map.mapTypeId],\r\n strokeWeight: this['legWeight'],\r\n zIndex: this['usualLegZIndex']\r\n });\r\n marker['_omsData'] = {\r\n usualPosition: marker.position,\r\n leg: leg\r\n };\r\n if (this['legColors']['highlighted'][this.map.mapTypeId] !== this['legColors']['usual'][this.map.mapTypeId]) {\r\n highlightListenerFuncs = this.makeHighlightListenerFuncs(marker);\r\n marker['_omsData'].hightlightListeners = {\r\n highlight: ge.addListener(marker, 'mouseover', highlightListenerFuncs.highlight),\r\n unhighlight: ge.addListener(marker, 'mouseout', highlightListenerFuncs.unhighlight)\r\n };\r\n }\r\n marker.setPosition(footLl);\r\n marker.setZIndex(Math.round(this['spiderfiedZIndex'] + footPt.y));\r\n results.push(marker);\r\n }\r\n return results;\r\n }).call(this);\r\n delete this.spiderfying;\r\n this.spiderfied = true;\r\n return this.trigger('spiderfy', spiderfiedMarkers, nonNearbyMarkers);\r\n };\r\n\r\n p['unspiderfy'] = function(markerNotToMove) {\r\n var l, len1, listeners, marker, nonNearbyMarkers, ref1, unspiderfiedMarkers;\r\n if (markerNotToMove == null) {\r\n markerNotToMove = null;\r\n }\r\n if (this.spiderfied == null) {\r\n return this;\r\n }\r\n this.unspiderfying = true;\r\n unspiderfiedMarkers = [];\r\n nonNearbyMarkers = [];\r\n ref1 = this.markers;\r\n for (l = 0, len1 = ref1.length; l < len1; l++) {\r\n marker = ref1[l];\r\n if (marker['_omsData'] != null) {\r\n marker['_omsData'].leg.setMap(null);\r\n if (marker !== markerNotToMove) {\r\n marker.setPosition(marker['_omsData'].usualPosition);\r\n }\r\n marker.setZIndex(null);\r\n listeners = marker['_omsData'].hightlightListeners;\r\n if (listeners != null) {\r\n ge.removeListener(listeners.highlight);\r\n ge.removeListener(listeners.unhighlight);\r\n }\r\n delete marker['_omsData'];\r\n unspiderfiedMarkers.push(marker);\r\n } else {\r\n nonNearbyMarkers.push(marker);\r\n }\r\n }\r\n delete this.unspiderfying;\r\n delete this.spiderfied;\r\n this.trigger('unspiderfy', unspiderfiedMarkers, nonNearbyMarkers);\r\n return this;\r\n };\r\n\r\n p.ptDistanceSq = function(pt1, pt2) {\r\n var dx, dy;\r\n dx = pt1.x - pt2.x;\r\n dy = pt1.y - pt2.y;\r\n return dx * dx + dy * dy;\r\n };\r\n\r\n p.ptAverage = function(pts) {\r\n var l, len1, numPts, pt, sumX, sumY;\r\n sumX = sumY = 0;\r\n for (l = 0, len1 = pts.length; l < len1; l++) {\r\n pt = pts[l];\r\n sumX += pt.x;\r\n sumY += pt.y;\r\n }\r\n numPts = pts.length;\r\n return new gm.Point(sumX / numPts, sumY / numPts);\r\n };\r\n\r\n p.llToPt = function(ll) {\r\n return this.projHelper.getProjection().fromLatLngToDivPixel(ll);\r\n };\r\n\r\n p.ptToLl = function(pt) {\r\n return this.projHelper.getProjection().fromDivPixelToLatLng(pt);\r\n };\r\n\r\n p.minExtract = function(set, func) {\r\n var bestIndex, bestVal, index, item, l, len1, val;\r\n for (index = l = 0, len1 = set.length; l < len1; index = ++l) {\r\n item = set[index];\r\n val = func(item);\r\n if ((typeof bestIndex === \"undefined\" || bestIndex === null) || val < bestVal) {\r\n bestVal = val;\r\n bestIndex = index;\r\n }\r\n }\r\n return set.splice(bestIndex, 1)[0];\r\n };\r\n\r\n p.arrIndexOf = function(arr, obj) {\r\n var i, l, len1, o;\r\n if (arr.indexOf != null) {\r\n return arr.indexOf(obj);\r\n }\r\n for (i = l = 0, len1 = arr.length; l < len1; i = ++l) {\r\n o = arr[i];\r\n if (o === obj) {\r\n return i;\r\n }\r\n }\r\n return -1;\r\n };\r\n\r\n return _Class;\r\n\r\n})();\r\n\r\n //END REPLACE\r\n GoogleMapApi.then(function(){\r\n self.OverlappingMarkerSpiderfier.initializeGoogleMaps(window.google);\r\n });\r\n return this.OverlappingMarkerSpiderfier;\r\n}]);\r\n;/**\r\n * Performance overrides on MarkerClusterer custom to Angular Google Maps\r\n *\r\n * Created by Petr Bruna ccg1415 and Nick McCready on 7/13/14.\r\n */\r\nangular.module('uiGmapgoogle-maps.extensions')\r\n.service('uiGmapExtendMarkerClusterer',['uiGmapLodash', 'uiGmapPropMap', function (uiGmapLodash, PropMap) {\r\n return {\r\n init: _.once(function () {\r\n (function () {\r\n var __hasProp = {}.hasOwnProperty,\r\n __extends = function (child, parent) {\r\n for (var key in parent) {\r\n if (__hasProp.call(parent, key)) child[key] = parent[key];\r\n }\r\n function ctor() {\r\n this.constructor = child;\r\n }\r\n\r\n ctor.prototype = parent.prototype;\r\n child.prototype = new ctor();\r\n child.__super__ = parent.prototype;\r\n return child;\r\n };\r\n\r\n window.NgMapCluster = (function (_super) {\r\n __extends(NgMapCluster, _super);\r\n\r\n function NgMapCluster(opts) {\r\n NgMapCluster.__super__.constructor.call(this, opts);\r\n this.markers_ = new PropMap();\r\n }\r\n\r\n /**\r\n * Adds a marker to the cluster.\r\n *\r\n * @param {google.maps.Marker} marker The marker to be added.\r\n * @return {boolean} True if the marker was added.\r\n * @ignore\r\n */\r\n NgMapCluster.prototype.addMarker = function (marker) {\r\n var i;\r\n var mCount;\r\n var mz;\r\n\r\n if (this.isMarkerAlreadyAdded_(marker)) {\r\n var oldMarker = this.markers_.get(marker.key);\r\n if (oldMarker.getPosition().lat() == marker.getPosition().lat() && oldMarker.getPosition().lon() == marker.getPosition().lon()) //if nothing has changed\r\n return false;\r\n }\r\n\r\n if (!this.center_) {\r\n this.center_ = marker.getPosition();\r\n this.calculateBounds_();\r\n } else {\r\n if (this.averageCenter_) {\r\n var l = this.markers_.length + 1;\r\n var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l;\r\n var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l;\r\n this.center_ = new google.maps.LatLng(lat, lng);\r\n this.calculateBounds_();\r\n }\r\n }\r\n marker.isAdded = true;\r\n this.markers_.push(marker);\r\n\r\n mCount = this.markers_.length;\r\n mz = this.markerClusterer_.getMaxZoom();\r\n if (mz !== null && this.map_.getZoom() > mz) {\r\n // Zoomed in past max zoom, so show the marker.\r\n if (marker.getMap() !== this.map_) {\r\n marker.setMap(this.map_);\r\n }\r\n } else if (mCount < this.minClusterSize_) {\r\n // Min cluster size not reached so show the marker.\r\n if (marker.getMap() !== this.map_) {\r\n marker.setMap(this.map_);\r\n }\r\n } else if (mCount === this.minClusterSize_) {\r\n // Hide the markers that were showing.\r\n this.markers_.each(function (m) {\r\n m.setMap(null);\r\n });\r\n } else {\r\n marker.setMap(null);\r\n }\r\n\r\n //this.updateIcon_();\r\n return true;\r\n };\r\n\r\n /**\r\n * Determines if a marker has already been added to the cluster.\r\n *\r\n * @param {google.maps.Marker} marker The marker to check.\r\n * @return {boolean} True if the marker has already been added.\r\n */\r\n NgMapCluster.prototype.isMarkerAlreadyAdded_ = function (marker) {\r\n return uiGmapLodash.isNullOrUndefined(this.markers_.get(marker.key));\r\n };\r\n\r\n\r\n /**\r\n * Returns the bounds of the cluster.\r\n *\r\n * @return {google.maps.LatLngBounds} the cluster bounds.\r\n * @ignore\r\n */\r\n NgMapCluster.prototype.getBounds = function () {\r\n var i;\r\n var bounds = new google.maps.LatLngBounds(this.center_, this.center_);\r\n this.getMarkers().each(function(m){\r\n bounds.extend(m.getPosition());\r\n });\r\n return bounds;\r\n };\r\n\r\n\r\n /**\r\n * Removes the cluster from the map.\r\n *\r\n * @ignore\r\n */\r\n NgMapCluster.prototype.remove = function () {\r\n this.clusterIcon_.setMap(null);\r\n this.markers_ = new PropMap();\r\n delete this.markers_;\r\n };\r\n\r\n\r\n return NgMapCluster;\r\n\r\n })(Cluster);\r\n\r\n\r\n window.NgMapMarkerClusterer = (function (_super) {\r\n __extends(NgMapMarkerClusterer, _super);\r\n\r\n function NgMapMarkerClusterer(map, opt_markers, opt_options) {\r\n NgMapMarkerClusterer.__super__.constructor.call(this, map, opt_markers, opt_options);\r\n this.markers_ = new PropMap();\r\n }\r\n\r\n /**\r\n * Removes all clusters and markers from the map and also removes all markers\r\n * managed by the clusterer.\r\n */\r\n NgMapMarkerClusterer.prototype.clearMarkers = function () {\r\n this.resetViewport_(true);\r\n this.markers_ = new PropMap();\r\n };\r\n /**\r\n * Removes a marker and returns true if removed, false if not.\r\n *\r\n * @param {google.maps.Marker} marker The marker to remove\r\n * @return {boolean} Whether the marker was removed or not\r\n */\r\n NgMapMarkerClusterer.prototype.removeMarker_ = function (marker) {\r\n if (!this.markers_.get(marker.key)) {\r\n return false;\r\n }\r\n marker.setMap(null);\r\n this.markers_.remove(marker.key); // Remove the marker from the list of managed markers\r\n return true;\r\n };\r\n\r\n /**\r\n * Creates the clusters. This is done in batches to avoid timeout errors\r\n * in some browsers when there is a huge number of markers.\r\n *\r\n * @param {number} iFirst The index of the first marker in the batch of\r\n * markers to be added to clusters.\r\n */\r\n NgMapMarkerClusterer.prototype.createClusters_ = function (iFirst) {\r\n var i, marker;\r\n var mapBounds;\r\n var cMarkerClusterer = this;\r\n if (!this.ready_) {\r\n return;\r\n }\r\n\r\n // Cancel previous batch processing if we're working on the first batch:\r\n if (iFirst === 0) {\r\n /**\r\n * This event is fired when the MarkerClusterer begins\r\n * clustering markers.\r\n * @name MarkerClusterer#clusteringbegin\r\n * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.\r\n * @event\r\n */\r\n google.maps.event.trigger(this, 'clusteringbegin', this);\r\n\r\n if (typeof this.timerRefStatic !== 'undefined') {\r\n clearTimeout(this.timerRefStatic);\r\n delete this.timerRefStatic;\r\n }\r\n }\r\n\r\n // Get our current map view bounds.\r\n // Create a new bounds object so we don't affect the map.\r\n //\r\n // See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug:\r\n if (this.getMap().getZoom() > 3) {\r\n mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(),\r\n this.getMap().getBounds().getNorthEast());\r\n } else {\r\n mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625));\r\n }\r\n var bounds = this.getExtendedBounds(mapBounds);\r\n\r\n var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length);\r\n\r\n var _ms = this.markers_.values();\r\n for (i = iFirst; i < iLast; i++) {\r\n marker = _ms[i];\r\n if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) {\r\n if (!this.ignoreHidden_ || (this.ignoreHidden_ && marker.getVisible())) {\r\n this.addToClosestCluster_(marker);\r\n }\r\n }\r\n }\r\n\r\n if (iLast < this.markers_.length) {\r\n this.timerRefStatic = setTimeout(function () {\r\n cMarkerClusterer.createClusters_(iLast);\r\n }, 0);\r\n } else {\r\n // custom addition by ui-gmap\r\n // update icon for all clusters\r\n for (i = 0; i < this.clusters_.length; i++) {\r\n this.clusters_[i].updateIcon_();\r\n }\r\n\r\n delete this.timerRefStatic;\r\n\r\n /**\r\n * This event is fired when the MarkerClusterer stops\r\n * clustering markers.\r\n * @name MarkerClusterer#clusteringend\r\n * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.\r\n * @event\r\n */\r\n google.maps.event.trigger(this, 'clusteringend', this);\r\n }\r\n };\r\n\r\n /**\r\n * Adds a marker to a cluster, or creates a new cluster.\r\n *\r\n * @param {google.maps.Marker} marker The marker to add.\r\n */\r\n NgMapMarkerClusterer.prototype.addToClosestCluster_ = function (marker) {\r\n var i, d, cluster, center;\r\n var distance = 40000; // Some large number\r\n var clusterToAddTo = null;\r\n for (i = 0; i < this.clusters_.length; i++) {\r\n cluster = this.clusters_[i];\r\n center = cluster.getCenter();\r\n if (center) {\r\n d = this.distanceBetweenPoints_(center, marker.getPosition());\r\n if (d < distance) {\r\n distance = d;\r\n clusterToAddTo = cluster;\r\n }\r\n }\r\n }\r\n\r\n if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) {\r\n clusterToAddTo.addMarker(marker);\r\n } else {\r\n cluster = new NgMapCluster(this);\r\n cluster.addMarker(marker);\r\n this.clusters_.push(cluster);\r\n }\r\n };\r\n\r\n /**\r\n * Redraws all the clusters.\r\n */\r\n NgMapMarkerClusterer.prototype.redraw_ = function () {\r\n this.createClusters_(0);\r\n };\r\n\r\n\r\n /**\r\n * Removes all clusters from the map. The markers are also removed from the map\r\n * if opt_hide is set to true.\r\n *\r\n * @param {boolean} [opt_hide] Set to true to also remove the markers\r\n * from the map.\r\n */\r\n NgMapMarkerClusterer.prototype.resetViewport_ = function (opt_hide) {\r\n var i, marker;\r\n // Remove all the clusters\r\n for (i = 0; i < this.clusters_.length; i++) {\r\n this.clusters_[i].remove();\r\n }\r\n this.clusters_ = [];\r\n\r\n // Reset the markers to not be added and to be removed from the map.\r\n this.markers_.each(function (marker) {\r\n marker.isAdded = false;\r\n if (opt_hide) {\r\n marker.setMap(null);\r\n }\r\n });\r\n };\r\n\r\n /**\r\n * Extends an object's prototype by another's.\r\n *\r\n * @param {Object} obj1 The object to be extended.\r\n * @param {Object} obj2 The object to extend with.\r\n * @return {Object} The new extended object.\r\n * @ignore\r\n */\r\n NgMapMarkerClusterer.prototype.extend = function (obj1, obj2) {\r\n return (function (object) {\r\n var property;\r\n for (property in object.prototype) {\r\n if (property !== 'constructor')\r\n this.prototype[property] = object.prototype[property];\r\n }\r\n return this;\r\n }).apply(obj1, [obj2]);\r\n };\r\n ////////////////////////////////////////////////////////////////////////////////\r\n /*\r\n Other overrides relevant to MarkerClusterPlus\r\n */\r\n ////////////////////////////////////////////////////////////////////////////////\r\n /**\r\n * Positions and shows the icon.\r\n */\r\n ClusterIcon.prototype.show = function () {\r\n if (this.div_) {\r\n var img = \"\";\r\n // NOTE: values must be specified in px units\r\n var bp = this.backgroundPosition_.split(\" \");\r\n var spriteH = parseInt(bp[0].trim(), 10);\r\n var spriteV = parseInt(bp[1].trim(), 10);\r\n var pos = this.getPosFromLatLng_(this.center_);\r\n this.div_.style.cssText = this.createCss(pos);\r\n img = \"\";\r\n this.div_.innerHTML = img + \"

    \" + this.sums_.text + \"
    \";\r\n if (typeof this.sums_.title === \"undefined\" || this.sums_.title === \"\") {\r\n this.div_.title = this.cluster_.getMarkerClusterer().getTitle();\r\n } else {\r\n this.div_.title = this.sums_.title;\r\n }\r\n this.div_.style.display = \"\";\r\n }\r\n this.visible_ = true;\r\n };\r\n //END OTHER OVERRIDES\r\n ////////////////////////////////////////////////////////////////////////////////\r\n\r\n return NgMapMarkerClusterer;\r\n\r\n })(MarkerClusterer);\r\n }).call(this);\r\n })\r\n };\r\n}]);\r\n}( window,angular));\n},{}],6:[function(require,module,exports){\n/*\r\n * Angular matchMedia Module\r\n * Version 0.2.2\r\n * Uses Bootstrap 3 breakpoint sizes\r\n * Exposes service \"screenSize\" which returns true if breakpoint(s) matches.\r\n * Includes matchMedia polyfill for backward compatibility.\r\n * Copyright © 2013-2014 Jack Tarantino.\r\n**/\r\n\r\nangular.module('matchMedia', [])\r\n\r\n\r\n.run(function initializeNgMatchMedia() {\r\n /*! matchMedia() polyfill - Test a CSS media type/query in JS.\r\n * Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas, David Knight.\r\n * Dual MIT/BSD license\r\n **/\r\n\r\n window.matchMedia || (window.matchMedia = function matchMediaPolyfill() {\r\n 'use strict';\r\n\r\n // For browsers that support matchMedium api such as IE 9 and webkit\r\n var styleMedia = (window.styleMedia || window.media);\r\n\r\n // For those that don't support matchMedium\r\n if (!styleMedia) {\r\n var style = document.createElement('style'),\r\n script = document.getElementsByTagName('script')[0],\r\n info = null;\r\n\r\n style.type = 'text/css';\r\n style.id = 'matchmediajs-test';\r\n\r\n script.parentNode.insertBefore(style, script);\r\n\r\n // 'style.currentStyle' is used by IE <= 8\r\n // 'window.getComputedStyle' for all other browsers\r\n info = ('getComputedStyle' in window)\r\n && window.getComputedStyle(style, null)\r\n || style.currentStyle;\r\n\r\n styleMedia = {\r\n matchMedium: function(media) {\r\n var text = '@media ' + media + '{ #matchmediajs-test { width: 1px; } }';\r\n\r\n // 'style.styleSheet' is used by IE <= 8\r\n // 'style.textContent' for all other browsers\r\n if (style.styleSheet) {\r\n style.styleSheet.cssText = text;\r\n } else {\r\n style.textContent = text;\r\n }\r\n\r\n // Test if media query is true or false\r\n return info.width === '1px';\r\n }\r\n };\r\n }\r\n\r\n return function(media) {\r\n return {\r\n matches: styleMedia.matchMedium(media || 'all'),\r\n media: media || 'all'\r\n };\r\n };\r\n }());\r\n})\r\n\r\n\r\n// takes a comma-separated list of screen sizes to match.\r\n// returns true if any of them match.\r\n.service('screenSize', function screenSize() {\r\n 'use strict';\r\n\r\n var defaultRules = {\r\n lg : '(min-width: 1200px)',\r\n md : '(min-width: 992px) and (max-width: 1199px)',\r\n sm : '(min-width: 768px) and (max-width: 991px)',\r\n xs : '(max-width: 767px)'\r\n };\r\n\r\n this.is = function (list) {\r\n var rules = this.rules || defaultRules;\r\n\r\n // validate that we're getting a string or array.\r\n if (typeof list !== 'string' && typeof list !== 'array') {\r\n throw new Error('screenSize requires array or comma-separated list');\r\n }\r\n\r\n // if it's a string, convert to array.\r\n if (typeof list === 'string') {\r\n list = list.split(/\\s*,\\s*/);\r\n }\r\n\r\n return list.some(function (size, index, arr) {\r\n if ( window.matchMedia(rules[size]).matches ) {\r\n return true;\r\n }\r\n });\r\n };\r\n});\r\n\n},{}],7:[function(require,module,exports){\n/*\r\n AngularJS v1.3.10\r\n (c) 2010-2014 Google, Inc. http://angularjs.org\r\n License: MIT\r\n*/\r\n(function(n,h,p){'use strict';function E(a){var d=[];s(d,h.noop).chars(a);return d.join(\"\")}function g(a){var d={};a=a.split(\",\");var c;for(c=0;c=c;e--)d.end&&d.end(f[e]);f.length=c}}\"string\"!==typeof a&&(a=null===a||\"undefined\"===typeof a?\"\":\"\"+a);var b,k,f=[],m=a,l;for(f.last=function(){return f[f.length-1]};a;){l=\"\";k=!0;if(f.last()&&x[f.last()])a=a.replace(new RegExp(\"(.*)<\\\\s*\\\\/\\\\s*\"+f.last()+\"[^>]*>\",\"i\"),function(a,b){b=b.replace(H,\"$1\").replace(I,\"$1\");d.chars&&d.chars(r(b));return\"\"}),e(\"\",f.last());else{if(0===a.indexOf(\"\\x3c!--\"))b=a.indexOf(\"--\",4),0<=b&&a.lastIndexOf(\"--\\x3e\",b)===b&&(d.comment&&d.comment(a.substring(4,\r\nb)),a=a.substring(b+3),k=!1);else if(y.test(a)){if(b=a.match(y))a=a.replace(b[0],\"\"),k=!1}else if(J.test(a)){if(b=a.match(z))a=a.substring(b[0].length),b[0].replace(z,e),k=!1}else K.test(a)&&((b=a.match(A))?(b[4]&&(a=a.substring(b[0].length),b[0].replace(A,c)),k=!1):(l+=\"<\",a=a.substring(1)));k&&(b=a.indexOf(\"<\"),l+=0>b?a:a.substring(0,b),a=0>b?\"\":a.substring(b),d.chars&&d.chars(r(l)))}if(a==m)throw L(\"badparse\",a);m=a}e()}function r(a){if(!a)return\"\";var d=M.exec(a);a=d[1];var c=d[3];if(d=d[2])q.innerHTML=\r\nd.replace(//g,\">\")}function s(a,d){var c=!1,e=h.bind(a,a.push);return{start:function(a,k,f){a=h.lowercase(a);!c&&x[a]&&(c=a);c||!0!==C[a]||(e(\"<\"),e(a),h.forEach(k,function(c,f){var k=\r\nh.lowercase(f),g=\"img\"===a&&\"src\"===k||\"background\"===k;!0!==P[k]||!0===D[k]&&!d(c,g)||(e(\" \"),e(f),e('=\"'),e(B(c)),e('\"'))}),e(f?\"/>\":\">\"))},end:function(a){a=h.lowercase(a);c||!0!==C[a]||(e(\"\"));a==c&&(c=!1)},chars:function(a){c||e(B(a))}}}var L=h.$$minErr(\"$sanitize\"),A=/^<((?:[a-zA-Z])[\\w:-]*)((?:\\s+[\\w:-]+(?:\\s*=\\s*(?:(?:\"[^\"]*\")|(?:'[^']*')|[^>\\s]+))?)*)\\s*(\\/?)\\s*(>?)/,z=/^<\\/\\s*([\\w:-]+)[^>]*>/,G=/([\\w:-]+)(?:\\s*=\\s*(?:(?:\"((?:[^\"])*)\")|(?:'((?:[^'])*)')|([^>\\s]+)))?/g,K=/^]*?)>/i,I=/\"\\u201d\\u2019]/,c=/^mailto:/;return function(e,b){function k(a){a&&g.push(E(a))}\r\nfunction f(a,c){g.push(\"');k(c);g.push(\"\")}if(!e)return e;for(var m,l=e,g=[],n,p;m=l.match(d);)n=m[0],m[2]||m[4]||(n=(m[3]?\"http://\":\"mailto:\")+n),p=m.index,k(l.substr(0,p)),f(n,m[0].replace(c,\"\")),l=l.substring(p+m[0].length);k(l);return a(g.join(\"\"))}}])})(window,window.angular);\r\n\r\n\n},{}],8:[function(require,module,exports){\n/**\r\n * State-based routing for AngularJS\r\n * @version v0.2.15\r\n * @link http://angular-ui.github.com/\r\n * @license MIT License, http://www.opensource.org/licenses/MIT\r\n */\r\n\r\n/* commonjs package manager support (eg componentjs) */\r\nif (typeof module !== \"undefined\" && typeof exports !== \"undefined\" && module.exports === exports){\r\n module.exports = 'ui.router';\r\n}\r\n\r\n(function (window, angular, undefined) {\r\n/*jshint globalstrict:true*/\r\n/*global angular:false*/\r\n'use strict';\r\n\r\nvar isDefined = angular.isDefined,\r\n isFunction = angular.isFunction,\r\n isString = angular.isString,\r\n isObject = angular.isObject,\r\n isArray = angular.isArray,\r\n forEach = angular.forEach,\r\n extend = angular.extend,\r\n copy = angular.copy;\r\n\r\nfunction inherit(parent, extra) {\r\n return extend(new (extend(function() {}, { prototype: parent }))(), extra);\r\n}\r\n\r\nfunction merge(dst) {\r\n forEach(arguments, function(obj) {\r\n if (obj !== dst) {\r\n forEach(obj, function(value, key) {\r\n if (!dst.hasOwnProperty(key)) dst[key] = value;\r\n });\r\n }\r\n });\r\n return dst;\r\n}\r\n\r\n/**\r\n * Finds the common ancestor path between two states.\r\n *\r\n * @param {Object} first The first state.\r\n * @param {Object} second The second state.\r\n * @return {Array} Returns an array of state names in descending order, not including the root.\r\n */\r\nfunction ancestors(first, second) {\r\n var path = [];\r\n\r\n for (var n in first.path) {\r\n if (first.path[n] !== second.path[n]) break;\r\n path.push(first.path[n]);\r\n }\r\n return path;\r\n}\r\n\r\n/**\r\n * IE8-safe wrapper for `Object.keys()`.\r\n *\r\n * @param {Object} object A JavaScript object.\r\n * @return {Array} Returns the keys of the object as an array.\r\n */\r\nfunction objectKeys(object) {\r\n if (Object.keys) {\r\n return Object.keys(object);\r\n }\r\n var result = [];\r\n\r\n forEach(object, function(val, key) {\r\n result.push(key);\r\n });\r\n return result;\r\n}\r\n\r\n/**\r\n * IE8-safe wrapper for `Array.prototype.indexOf()`.\r\n *\r\n * @param {Array} array A JavaScript array.\r\n * @param {*} value A value to search the array for.\r\n * @return {Number} Returns the array index value of `value`, or `-1` if not present.\r\n */\r\nfunction indexOf(array, value) {\r\n if (Array.prototype.indexOf) {\r\n return array.indexOf(value, Number(arguments[2]) || 0);\r\n }\r\n var len = array.length >>> 0, from = Number(arguments[2]) || 0;\r\n from = (from < 0) ? Math.ceil(from) : Math.floor(from);\r\n\r\n if (from < 0) from += len;\r\n\r\n for (; from < len; from++) {\r\n if (from in array && array[from] === value) return from;\r\n }\r\n return -1;\r\n}\r\n\r\n/**\r\n * Merges a set of parameters with all parameters inherited between the common parents of the\r\n * current state and a given destination state.\r\n *\r\n * @param {Object} currentParams The value of the current state parameters ($stateParams).\r\n * @param {Object} newParams The set of parameters which will be composited with inherited params.\r\n * @param {Object} $current Internal definition of object representing the current state.\r\n * @param {Object} $to Internal definition of object representing state to transition to.\r\n */\r\nfunction inheritParams(currentParams, newParams, $current, $to) {\r\n var parents = ancestors($current, $to), parentParams, inherited = {}, inheritList = [];\r\n\r\n for (var i in parents) {\r\n if (!parents[i].params) continue;\r\n parentParams = objectKeys(parents[i].params);\r\n if (!parentParams.length) continue;\r\n\r\n for (var j in parentParams) {\r\n if (indexOf(inheritList, parentParams[j]) >= 0) continue;\r\n inheritList.push(parentParams[j]);\r\n inherited[parentParams[j]] = currentParams[parentParams[j]];\r\n }\r\n }\r\n return extend({}, inherited, newParams);\r\n}\r\n\r\n/**\r\n * Performs a non-strict comparison of the subset of two objects, defined by a list of keys.\r\n *\r\n * @param {Object} a The first object.\r\n * @param {Object} b The second object.\r\n * @param {Array} keys The list of keys within each object to compare. If the list is empty or not specified,\r\n * it defaults to the list of keys in `a`.\r\n * @return {Boolean} Returns `true` if the keys match, otherwise `false`.\r\n */\r\nfunction equalForKeys(a, b, keys) {\r\n if (!keys) {\r\n keys = [];\r\n for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility\r\n }\r\n\r\n for (var i=0; i\r\n * \r\n * \r\n * \r\n * \r\n * \r\n * \r\n * \r\n * \r\n * \r\n * \r\n * \r\n * \r\n */\r\nangular.module('ui.router', ['ui.router.state']);\r\n\r\nangular.module('ui.router.compat', ['ui.router']);\r\n\r\n/**\r\n * @ngdoc object\r\n * @name ui.router.util.$resolve\r\n *\r\n * @requires $q\r\n * @requires $injector\r\n *\r\n * @description\r\n * Manages resolution of (acyclic) graphs of promises.\r\n */\r\n$Resolve.$inject = ['$q', '$injector'];\r\nfunction $Resolve( $q, $injector) {\r\n \r\n var VISIT_IN_PROGRESS = 1,\r\n VISIT_DONE = 2,\r\n NOTHING = {},\r\n NO_DEPENDENCIES = [],\r\n NO_LOCALS = NOTHING,\r\n NO_PARENT = extend($q.when(NOTHING), { $$promises: NOTHING, $$values: NOTHING });\r\n \r\n\r\n /**\r\n * @ngdoc function\r\n * @name ui.router.util.$resolve#study\r\n * @methodOf ui.router.util.$resolve\r\n *\r\n * @description\r\n * Studies a set of invocables that are likely to be used multiple times.\r\n *
    \r\n   * $resolve.study(invocables)(locals, parent, self)\r\n   * 
    \r\n * is equivalent to\r\n *
    \r\n   * $resolve.resolve(invocables, locals, parent, self)\r\n   * 
    \r\n * but the former is more efficient (in fact `resolve` just calls `study` \r\n * internally).\r\n *\r\n * @param {object} invocables Invocable objects\r\n * @return {function} a function to pass in locals, parent and self\r\n */\r\n this.study = function (invocables) {\r\n if (!isObject(invocables)) throw new Error(\"'invocables' must be an object\");\r\n var invocableKeys = objectKeys(invocables || {});\r\n \r\n // Perform a topological sort of invocables to build an ordered plan\r\n var plan = [], cycle = [], visited = {};\r\n function visit(value, key) {\r\n if (visited[key] === VISIT_DONE) return;\r\n \r\n cycle.push(key);\r\n if (visited[key] === VISIT_IN_PROGRESS) {\r\n cycle.splice(0, indexOf(cycle, key));\r\n throw new Error(\"Cyclic dependency: \" + cycle.join(\" -> \"));\r\n }\r\n visited[key] = VISIT_IN_PROGRESS;\r\n \r\n if (isString(value)) {\r\n plan.push(key, [ function() { return $injector.get(value); }], NO_DEPENDENCIES);\r\n } else {\r\n var params = $injector.annotate(value);\r\n forEach(params, function (param) {\r\n if (param !== key && invocables.hasOwnProperty(param)) visit(invocables[param], param);\r\n });\r\n plan.push(key, value, params);\r\n }\r\n \r\n cycle.pop();\r\n visited[key] = VISIT_DONE;\r\n }\r\n forEach(invocables, visit);\r\n invocables = cycle = visited = null; // plan is all that's required\r\n \r\n function isResolve(value) {\r\n return isObject(value) && value.then && value.$$promises;\r\n }\r\n \r\n return function (locals, parent, self) {\r\n if (isResolve(locals) && self === undefined) {\r\n self = parent; parent = locals; locals = null;\r\n }\r\n if (!locals) locals = NO_LOCALS;\r\n else if (!isObject(locals)) {\r\n throw new Error(\"'locals' must be an object\");\r\n } \r\n if (!parent) parent = NO_PARENT;\r\n else if (!isResolve(parent)) {\r\n throw new Error(\"'parent' must be a promise returned by $resolve.resolve()\");\r\n }\r\n \r\n // To complete the overall resolution, we have to wait for the parent\r\n // promise and for the promise for each invokable in our plan.\r\n var resolution = $q.defer(),\r\n result = resolution.promise,\r\n promises = result.$$promises = {},\r\n values = extend({}, locals),\r\n wait = 1 + plan.length/3,\r\n merged = false;\r\n \r\n function done() {\r\n // Merge parent values we haven't got yet and publish our own $$values\r\n if (!--wait) {\r\n if (!merged) merge(values, parent.$$values); \r\n result.$$values = values;\r\n result.$$promises = result.$$promises || true; // keep for isResolve()\r\n delete result.$$inheritedValues;\r\n resolution.resolve(values);\r\n }\r\n }\r\n \r\n function fail(reason) {\r\n result.$$failure = reason;\r\n resolution.reject(reason);\r\n }\r\n\r\n // Short-circuit if parent has already failed\r\n if (isDefined(parent.$$failure)) {\r\n fail(parent.$$failure);\r\n return result;\r\n }\r\n \r\n if (parent.$$inheritedValues) {\r\n merge(values, omit(parent.$$inheritedValues, invocableKeys));\r\n }\r\n\r\n // Merge parent values if the parent has already resolved, or merge\r\n // parent promises and wait if the parent resolve is still in progress.\r\n extend(promises, parent.$$promises);\r\n if (parent.$$values) {\r\n merged = merge(values, omit(parent.$$values, invocableKeys));\r\n result.$$inheritedValues = omit(parent.$$values, invocableKeys);\r\n done();\r\n } else {\r\n if (parent.$$inheritedValues) {\r\n result.$$inheritedValues = omit(parent.$$inheritedValues, invocableKeys);\r\n } \r\n parent.then(done, fail);\r\n }\r\n \r\n // Process each invocable in the plan, but ignore any where a local of the same name exists.\r\n for (var i=0, ii=plan.length; i} The template html as a string, or a promise \r\n * for that string.\r\n */\r\n this.fromUrl = function (url, params) {\r\n if (isFunction(url)) url = url(params);\r\n if (url == null) return null;\r\n else return $http\r\n .get(url, { cache: $templateCache, headers: { Accept: 'text/html' }})\r\n .then(function(response) { return response.data; });\r\n };\r\n\r\n /**\r\n * @ngdoc function\r\n * @name ui.router.util.$templateFactory#fromProvider\r\n * @methodOf ui.router.util.$templateFactory\r\n *\r\n * @description\r\n * Creates a template by invoking an injectable provider function.\r\n *\r\n * @param {Function} provider Function to invoke via `$injector.invoke`\r\n * @param {Object} params Parameters for the template.\r\n * @param {Object} locals Locals to pass to `invoke`. Defaults to \r\n * `{ params: params }`.\r\n * @return {string|Promise.} The template html as a string, or a promise \r\n * for that string.\r\n */\r\n this.fromProvider = function (provider, params, locals) {\r\n return $injector.invoke(provider, null, locals || { params: params });\r\n };\r\n}\r\n\r\nangular.module('ui.router.util').service('$templateFactory', $TemplateFactory);\r\n\r\nvar $$UMFP; // reference to $UrlMatcherFactoryProvider\r\n\r\n/**\r\n * @ngdoc object\r\n * @name ui.router.util.type:UrlMatcher\r\n *\r\n * @description\r\n * Matches URLs against patterns and extracts named parameters from the path or the search\r\n * part of the URL. A URL pattern consists of a path pattern, optionally followed by '?' and a list\r\n * of search parameters. Multiple search parameter names are separated by '&'. Search parameters\r\n * do not influence whether or not a URL is matched, but their values are passed through into\r\n * the matched parameters returned by {@link ui.router.util.type:UrlMatcher#methods_exec exec}.\r\n *\r\n * Path parameter placeholders can be specified using simple colon/catch-all syntax or curly brace\r\n * syntax, which optionally allows a regular expression for the parameter to be specified:\r\n *\r\n * * `':'` name - colon placeholder\r\n * * `'*'` name - catch-all placeholder\r\n * * `'{' name '}'` - curly placeholder\r\n * * `'{' name ':' regexp|type '}'` - curly placeholder with regexp or type name. Should the\r\n * regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash.\r\n *\r\n * Parameter names may contain only word characters (latin letters, digits, and underscore) and\r\n * must be unique within the pattern (across both path and search parameters). For colon\r\n * placeholders or curly placeholders without an explicit regexp, a path parameter matches any\r\n * number of characters other than '/'. For catch-all placeholders the path parameter matches\r\n * any number of characters.\r\n *\r\n * Examples:\r\n *\r\n * * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for\r\n * trailing slashes, and patterns have to match the entire path, not just a prefix.\r\n * * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or\r\n * '/user/bob/details'. The second path segment will be captured as the parameter 'id'.\r\n * * `'/user/{id}'` - Same as the previous example, but using curly brace syntax.\r\n * * `'/user/{id:[^/]*}'` - Same as the previous example.\r\n * * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id\r\n * parameter consists of 1 to 8 hex digits.\r\n * * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the\r\n * path into the parameter 'path'.\r\n * * `'/files/*path'` - ditto.\r\n * * `'/calendar/{start:date}'` - Matches \"/calendar/2014-11-12\" (because the pattern defined\r\n * in the built-in `date` Type matches `2014-11-12`) and provides a Date object in $stateParams.start\r\n *\r\n * @param {string} pattern The pattern to compile into a matcher.\r\n * @param {Object} config A configuration object hash:\r\n * @param {Object=} parentMatcher Used to concatenate the pattern/config onto\r\n * an existing UrlMatcher\r\n *\r\n * * `caseInsensitive` - `true` if URL matching should be case insensitive, otherwise `false`, the default value (for backward compatibility) is `false`.\r\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`.\r\n *\r\n * @property {string} prefix A static prefix of this pattern. The matcher guarantees that any\r\n * URL matching this matcher (i.e. any string for which {@link ui.router.util.type:UrlMatcher#methods_exec exec()} returns\r\n * non-null) will start with this prefix.\r\n *\r\n * @property {string} source The pattern that was passed into the constructor\r\n *\r\n * @property {string} sourcePath The path portion of the source property\r\n *\r\n * @property {string} sourceSearch The search portion of the source property\r\n *\r\n * @property {string} regex The constructed regex that will be used to match against the url when\r\n * it is time to determine which url will match.\r\n *\r\n * @returns {Object} New `UrlMatcher` object\r\n */\r\nfunction UrlMatcher(pattern, config, parentMatcher) {\r\n config = extend({ params: {} }, isObject(config) ? config : {});\r\n\r\n // Find all placeholders and create a compiled pattern, using either classic or curly syntax:\r\n // '*' name\r\n // ':' name\r\n // '{' name '}'\r\n // '{' name ':' regexp '}'\r\n // The regular expression is somewhat complicated due to the need to allow curly braces\r\n // inside the regular expression. The placeholder regexp breaks down as follows:\r\n // ([:*])([\\w\\[\\]]+) - classic placeholder ($1 / $2) (search version has - for snake-case)\r\n // \\{([\\w\\[\\]]+)(?:\\:( ... ))?\\} - curly brace placeholder ($3) with optional regexp/type ... ($4) (search version has - for snake-case\r\n // (?: ... | ... | ... )+ - the regexp consists of any number of atoms, an atom being either\r\n // [^{}\\\\]+ - anything other than curly braces or backslash\r\n // \\\\. - a backslash escape\r\n // \\{(?:[^{}\\\\]+|\\\\.)*\\} - a matched set of curly braces containing other atoms\r\n var placeholder = /([:*])([\\w\\[\\]]+)|\\{([\\w\\[\\]]+)(?:\\:((?:[^{}\\\\]+|\\\\.|\\{(?:[^{}\\\\]+|\\\\.)*\\})+))?\\}/g,\r\n searchPlaceholder = /([:]?)([\\w\\[\\]-]+)|\\{([\\w\\[\\]-]+)(?:\\:((?:[^{}\\\\]+|\\\\.|\\{(?:[^{}\\\\]+|\\\\.)*\\})+))?\\}/g,\r\n compiled = '^', last = 0, m,\r\n segments = this.segments = [],\r\n parentParams = parentMatcher ? parentMatcher.params : {},\r\n params = this.params = parentMatcher ? parentMatcher.params.$$new() : new $$UMFP.ParamSet(),\r\n paramNames = [];\r\n\r\n function addParameter(id, type, config, location) {\r\n paramNames.push(id);\r\n if (parentParams[id]) return parentParams[id];\r\n if (!/^\\w+(-+\\w+)*(?:\\[\\])?$/.test(id)) throw new Error(\"Invalid parameter name '\" + id + \"' in pattern '\" + pattern + \"'\");\r\n if (params[id]) throw new Error(\"Duplicate parameter name '\" + id + \"' in pattern '\" + pattern + \"'\");\r\n params[id] = new $$UMFP.Param(id, type, config, location);\r\n return params[id];\r\n }\r\n\r\n function quoteRegExp(string, pattern, squash, optional) {\r\n var surroundPattern = ['',''], result = string.replace(/[\\\\\\[\\]\\^$*+?.()|{}]/g, \"\\\\$&\");\r\n if (!pattern) return result;\r\n switch(squash) {\r\n case false: surroundPattern = ['(', ')' + (optional ? \"?\" : \"\")]; break;\r\n case true: surroundPattern = ['?(', ')?']; break;\r\n default: surroundPattern = ['(' + squash + \"|\", ')?']; break;\r\n }\r\n return result + surroundPattern[0] + pattern + surroundPattern[1];\r\n }\r\n\r\n this.source = pattern;\r\n\r\n // Split into static segments separated by path parameter placeholders.\r\n // The number of segments is always 1 more than the number of parameters.\r\n function matchDetails(m, isSearch) {\r\n var id, regexp, segment, type, cfg, arrayMode;\r\n id = m[2] || m[3]; // IE[78] returns '' for unmatched groups instead of null\r\n cfg = config.params[id];\r\n segment = pattern.substring(last, m.index);\r\n regexp = isSearch ? m[4] : m[4] || (m[1] == '*' ? '.*' : null);\r\n type = $$UMFP.type(regexp || \"string\") || inherit($$UMFP.type(\"string\"), { pattern: new RegExp(regexp, config.caseInsensitive ? 'i' : undefined) });\r\n return {\r\n id: id, regexp: regexp, segment: segment, type: type, cfg: cfg\r\n };\r\n }\r\n\r\n var p, param, segment;\r\n while ((m = placeholder.exec(pattern))) {\r\n p = matchDetails(m, false);\r\n if (p.segment.indexOf('?') >= 0) break; // we're into the search part\r\n\r\n param = addParameter(p.id, p.type, p.cfg, \"path\");\r\n compiled += quoteRegExp(p.segment, param.type.pattern.source, param.squash, param.isOptional);\r\n segments.push(p.segment);\r\n last = placeholder.lastIndex;\r\n }\r\n segment = pattern.substring(last);\r\n\r\n // Find any search parameter names and remove them from the last segment\r\n var i = segment.indexOf('?');\r\n\r\n if (i >= 0) {\r\n var search = this.sourceSearch = segment.substring(i);\r\n segment = segment.substring(0, i);\r\n this.sourcePath = pattern.substring(0, last + i);\r\n\r\n if (search.length > 0) {\r\n last = 0;\r\n while ((m = searchPlaceholder.exec(search))) {\r\n p = matchDetails(m, true);\r\n param = addParameter(p.id, p.type, p.cfg, \"search\");\r\n last = placeholder.lastIndex;\r\n // check if ?&\r\n }\r\n }\r\n } else {\r\n this.sourcePath = pattern;\r\n this.sourceSearch = '';\r\n }\r\n\r\n compiled += quoteRegExp(segment) + (config.strict === false ? '\\/?' : '') + '$';\r\n segments.push(segment);\r\n\r\n this.regexp = new RegExp(compiled, config.caseInsensitive ? 'i' : undefined);\r\n this.prefix = segments[0];\r\n this.$$paramNames = paramNames;\r\n}\r\n\r\n/**\r\n * @ngdoc function\r\n * @name ui.router.util.type:UrlMatcher#concat\r\n * @methodOf ui.router.util.type:UrlMatcher\r\n *\r\n * @description\r\n * Returns a new matcher for a pattern constructed by appending the path part and adding the\r\n * search parameters of the specified pattern to this pattern. The current pattern is not\r\n * modified. This can be understood as creating a pattern for URLs that are relative to (or\r\n * suffixes of) the current pattern.\r\n *\r\n * @example\r\n * The following two matchers are equivalent:\r\n *
    \r\n * new UrlMatcher('/user/{id}?q').concat('/details?date');\r\n * new UrlMatcher('/user/{id}/details?q&date');\r\n * 
    \r\n *\r\n * @param {string} pattern The pattern to append.\r\n * @param {Object} config An object hash of the configuration for the matcher.\r\n * @returns {UrlMatcher} A matcher for the concatenated pattern.\r\n */\r\nUrlMatcher.prototype.concat = function (pattern, config) {\r\n // Because order of search parameters is irrelevant, we can add our own search\r\n // parameters to the end of the new pattern. Parse the new pattern by itself\r\n // and then join the bits together, but it's much easier to do this on a string level.\r\n var defaultConfig = {\r\n caseInsensitive: $$UMFP.caseInsensitive(),\r\n strict: $$UMFP.strictMode(),\r\n squash: $$UMFP.defaultSquashPolicy()\r\n };\r\n return new UrlMatcher(this.sourcePath + pattern + this.sourceSearch, extend(defaultConfig, config), this);\r\n};\r\n\r\nUrlMatcher.prototype.toString = function () {\r\n return this.source;\r\n};\r\n\r\n/**\r\n * @ngdoc function\r\n * @name ui.router.util.type:UrlMatcher#exec\r\n * @methodOf ui.router.util.type:UrlMatcher\r\n *\r\n * @description\r\n * Tests the specified path against this matcher, and returns an object containing the captured\r\n * parameter values, or null if the path does not match. The returned object contains the values\r\n * of any search parameters that are mentioned in the pattern, but their value may be null if\r\n * they are not present in `searchParams`. This means that search parameters are always treated\r\n * as optional.\r\n *\r\n * @example\r\n *
    \r\n * new UrlMatcher('/user/{id}?q&r').exec('/user/bob', {\r\n *   x: '1', q: 'hello'\r\n * });\r\n * // returns { id: 'bob', q: 'hello', r: null }\r\n * 
    \r\n *\r\n * @param {string} path The URL path to match, e.g. `$location.path()`.\r\n * @param {Object} searchParams URL search parameters, e.g. `$location.search()`.\r\n * @returns {Object} The captured parameter values.\r\n */\r\nUrlMatcher.prototype.exec = function (path, searchParams) {\r\n var m = this.regexp.exec(path);\r\n if (!m) return null;\r\n searchParams = searchParams || {};\r\n\r\n var paramNames = this.parameters(), nTotal = paramNames.length,\r\n nPath = this.segments.length - 1,\r\n values = {}, i, j, cfg, paramName;\r\n\r\n if (nPath !== m.length - 1) throw new Error(\"Unbalanced capture group in route '\" + this.source + \"'\");\r\n\r\n function decodePathArray(string) {\r\n function reverseString(str) { return str.split(\"\").reverse().join(\"\"); }\r\n function unquoteDashes(str) { return str.replace(/\\\\-/g, \"-\"); }\r\n\r\n var split = reverseString(string).split(/-(?!\\\\)/);\r\n var allReversed = map(split, reverseString);\r\n return map(allReversed, unquoteDashes).reverse();\r\n }\r\n\r\n for (i = 0; i < nPath; i++) {\r\n paramName = paramNames[i];\r\n var param = this.params[paramName];\r\n var paramVal = m[i+1];\r\n // if the param value matches a pre-replace pair, replace the value before decoding.\r\n for (j = 0; j < param.replace; j++) {\r\n if (param.replace[j].from === paramVal) paramVal = param.replace[j].to;\r\n }\r\n if (paramVal && param.array === true) paramVal = decodePathArray(paramVal);\r\n values[paramName] = param.value(paramVal);\r\n }\r\n for (/**/; i < nTotal; i++) {\r\n paramName = paramNames[i];\r\n values[paramName] = this.params[paramName].value(searchParams[paramName]);\r\n }\r\n\r\n return values;\r\n};\r\n\r\n/**\r\n * @ngdoc function\r\n * @name ui.router.util.type:UrlMatcher#parameters\r\n * @methodOf ui.router.util.type:UrlMatcher\r\n *\r\n * @description\r\n * Returns the names of all path and search parameters of this pattern in an unspecified order.\r\n *\r\n * @returns {Array.} An array of parameter names. Must be treated as read-only. If the\r\n * pattern has no parameters, an empty array is returned.\r\n */\r\nUrlMatcher.prototype.parameters = function (param) {\r\n if (!isDefined(param)) return this.$$paramNames;\r\n return this.params[param] || null;\r\n};\r\n\r\n/**\r\n * @ngdoc function\r\n * @name ui.router.util.type:UrlMatcher#validate\r\n * @methodOf ui.router.util.type:UrlMatcher\r\n *\r\n * @description\r\n * Checks an object hash of parameters to validate their correctness according to the parameter\r\n * types of this `UrlMatcher`.\r\n *\r\n * @param {Object} params The object hash of parameters to validate.\r\n * @returns {boolean} Returns `true` if `params` validates, otherwise `false`.\r\n */\r\nUrlMatcher.prototype.validates = function (params) {\r\n return this.params.$$validates(params);\r\n};\r\n\r\n/**\r\n * @ngdoc function\r\n * @name ui.router.util.type:UrlMatcher#format\r\n * @methodOf ui.router.util.type:UrlMatcher\r\n *\r\n * @description\r\n * Creates a URL that matches this pattern by substituting the specified values\r\n * for the path and search parameters. Null values for path parameters are\r\n * treated as empty strings.\r\n *\r\n * @example\r\n *
    \r\n * new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' });\r\n * // returns '/user/bob?q=yes'\r\n * 
    \r\n *\r\n * @param {Object} values the values to substitute for the parameters in this pattern.\r\n * @returns {string} the formatted URL (path and optionally search part).\r\n */\r\nUrlMatcher.prototype.format = function (values) {\r\n values = values || {};\r\n var segments = this.segments, params = this.parameters(), paramset = this.params;\r\n if (!this.validates(values)) return null;\r\n\r\n var i, search = false, nPath = segments.length - 1, nTotal = params.length, result = segments[0];\r\n\r\n function encodeDashes(str) { // Replace dashes with encoded \"\\-\"\r\n return encodeURIComponent(str).replace(/-/g, function(c) { return '%5C%' + c.charCodeAt(0).toString(16).toUpperCase(); });\r\n }\r\n\r\n for (i = 0; i < nTotal; i++) {\r\n var isPathParam = i < nPath;\r\n var name = params[i], param = paramset[name], value = param.value(values[name]);\r\n var isDefaultValue = param.isOptional && param.type.equals(param.value(), value);\r\n var squash = isDefaultValue ? param.squash : false;\r\n var encoded = param.type.encode(value);\r\n\r\n if (isPathParam) {\r\n var nextSegment = segments[i + 1];\r\n if (squash === false) {\r\n if (encoded != null) {\r\n if (isArray(encoded)) {\r\n result += map(encoded, encodeDashes).join(\"-\");\r\n } else {\r\n result += encodeURIComponent(encoded);\r\n }\r\n }\r\n result += nextSegment;\r\n } else if (squash === true) {\r\n var capture = result.match(/\\/$/) ? /\\/?(.*)/ : /(.*)/;\r\n result += nextSegment.match(capture)[1];\r\n } else if (isString(squash)) {\r\n result += squash + nextSegment;\r\n }\r\n } else {\r\n if (encoded == null || (isDefaultValue && squash !== false)) continue;\r\n if (!isArray(encoded)) encoded = [ encoded ];\r\n encoded = map(encoded, encodeURIComponent).join('&' + name + '=');\r\n result += (search ? '&' : '?') + (name + '=' + encoded);\r\n search = true;\r\n }\r\n }\r\n\r\n return result;\r\n};\r\n\r\n/**\r\n * @ngdoc object\r\n * @name ui.router.util.type:Type\r\n *\r\n * @description\r\n * Implements an interface to define custom parameter types that can be decoded from and encoded to\r\n * string parameters matched in a URL. Used by {@link ui.router.util.type:UrlMatcher `UrlMatcher`}\r\n * objects when matching or formatting URLs, or comparing or validating parameter values.\r\n *\r\n * See {@link ui.router.util.$urlMatcherFactory#methods_type `$urlMatcherFactory#type()`} for more\r\n * information on registering custom types.\r\n *\r\n * @param {Object} config A configuration object which contains the custom type definition. The object's\r\n * properties will override the default methods and/or pattern in `Type`'s public interface.\r\n * @example\r\n *
    \r\n * {\r\n *   decode: function(val) { return parseInt(val, 10); },\r\n *   encode: function(val) { return val && val.toString(); },\r\n *   equals: function(a, b) { return this.is(a) && a === b; },\r\n *   is: function(val) { return angular.isNumber(val) isFinite(val) && val % 1 === 0; },\r\n *   pattern: /\\d+/\r\n * }\r\n * 
    \r\n *\r\n * @property {RegExp} pattern The regular expression pattern used to match values of this type when\r\n * coming from a substring of a URL.\r\n *\r\n * @returns {Object} Returns a new `Type` object.\r\n */\r\nfunction Type(config) {\r\n extend(this, config);\r\n}\r\n\r\n/**\r\n * @ngdoc function\r\n * @name ui.router.util.type:Type#is\r\n * @methodOf ui.router.util.type:Type\r\n *\r\n * @description\r\n * Detects whether a value is of a particular type. Accepts a native (decoded) value\r\n * and determines whether it matches the current `Type` object.\r\n *\r\n * @param {*} val The value to check.\r\n * @param {string} key Optional. If the type check is happening in the context of a specific\r\n * {@link ui.router.util.type:UrlMatcher `UrlMatcher`} object, this is the name of the\r\n * parameter in which `val` is stored. Can be used for meta-programming of `Type` objects.\r\n * @returns {Boolean} Returns `true` if the value matches the type, otherwise `false`.\r\n */\r\nType.prototype.is = function(val, key) {\r\n return true;\r\n};\r\n\r\n/**\r\n * @ngdoc function\r\n * @name ui.router.util.type:Type#encode\r\n * @methodOf ui.router.util.type:Type\r\n *\r\n * @description\r\n * Encodes a custom/native type value to a string that can be embedded in a URL. Note that the\r\n * return value does *not* need to be URL-safe (i.e. passed through `encodeURIComponent()`), it\r\n * only needs to be a representation of `val` that has been coerced to a string.\r\n *\r\n * @param {*} val The value to encode.\r\n * @param {string} key The name of the parameter in which `val` is stored. Can be used for\r\n * meta-programming of `Type` objects.\r\n * @returns {string} Returns a string representation of `val` that can be encoded in a URL.\r\n */\r\nType.prototype.encode = function(val, key) {\r\n return val;\r\n};\r\n\r\n/**\r\n * @ngdoc function\r\n * @name ui.router.util.type:Type#decode\r\n * @methodOf ui.router.util.type:Type\r\n *\r\n * @description\r\n * Converts a parameter value (from URL string or transition param) to a custom/native value.\r\n *\r\n * @param {string} val The URL parameter value to decode.\r\n * @param {string} key The name of the parameter in which `val` is stored. Can be used for\r\n * meta-programming of `Type` objects.\r\n * @returns {*} Returns a custom representation of the URL parameter value.\r\n */\r\nType.prototype.decode = function(val, key) {\r\n return val;\r\n};\r\n\r\n/**\r\n * @ngdoc function\r\n * @name ui.router.util.type:Type#equals\r\n * @methodOf ui.router.util.type:Type\r\n *\r\n * @description\r\n * Determines whether two decoded values are equivalent.\r\n *\r\n * @param {*} a A value to compare against.\r\n * @param {*} b A value to compare against.\r\n * @returns {Boolean} Returns `true` if the values are equivalent/equal, otherwise `false`.\r\n */\r\nType.prototype.equals = function(a, b) {\r\n return a == b;\r\n};\r\n\r\nType.prototype.$subPattern = function() {\r\n var sub = this.pattern.toString();\r\n return sub.substr(1, sub.length - 2);\r\n};\r\n\r\nType.prototype.pattern = /.*/;\r\n\r\nType.prototype.toString = function() { return \"{Type:\" + this.name + \"}\"; };\r\n\r\n/** Given an encoded string, or a decoded object, returns a decoded object */\r\nType.prototype.$normalize = function(val) {\r\n return this.is(val) ? val : this.decode(val);\r\n};\r\n\r\n/*\r\n * Wraps an existing custom Type as an array of Type, depending on 'mode'.\r\n * e.g.:\r\n * - urlmatcher pattern \"/path?{queryParam[]:int}\"\r\n * - url: \"/path?queryParam=1&queryParam=2\r\n * - $stateParams.queryParam will be [1, 2]\r\n * if `mode` is \"auto\", then\r\n * - url: \"/path?queryParam=1 will create $stateParams.queryParam: 1\r\n * - url: \"/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2]\r\n */\r\nType.prototype.$asArray = function(mode, isSearch) {\r\n if (!mode) return this;\r\n if (mode === \"auto\" && !isSearch) throw new Error(\"'auto' array mode is for query parameters only\");\r\n\r\n function ArrayType(type, mode) {\r\n function bindTo(type, callbackName) {\r\n return function() {\r\n return type[callbackName].apply(type, arguments);\r\n };\r\n }\r\n\r\n // Wrap non-array value as array\r\n function arrayWrap(val) { return isArray(val) ? val : (isDefined(val) ? [ val ] : []); }\r\n // Unwrap array value for \"auto\" mode. Return undefined for empty array.\r\n function arrayUnwrap(val) {\r\n switch(val.length) {\r\n case 0: return undefined;\r\n case 1: return mode === \"auto\" ? val[0] : val;\r\n default: return val;\r\n }\r\n }\r\n function falsey(val) { return !val; }\r\n\r\n // Wraps type (.is/.encode/.decode) functions to operate on each value of an array\r\n function arrayHandler(callback, allTruthyMode) {\r\n return function handleArray(val) {\r\n val = arrayWrap(val);\r\n var result = map(val, callback);\r\n if (allTruthyMode === true)\r\n return filter(result, falsey).length === 0;\r\n return arrayUnwrap(result);\r\n };\r\n }\r\n\r\n // Wraps type (.equals) functions to operate on each value of an array\r\n function arrayEqualsHandler(callback) {\r\n return function handleArray(val1, val2) {\r\n var left = arrayWrap(val1), right = arrayWrap(val2);\r\n if (left.length !== right.length) return false;\r\n for (var i = 0; i < left.length; i++) {\r\n if (!callback(left[i], right[i])) return false;\r\n }\r\n return true;\r\n };\r\n }\r\n\r\n this.encode = arrayHandler(bindTo(type, 'encode'));\r\n this.decode = arrayHandler(bindTo(type, 'decode'));\r\n this.is = arrayHandler(bindTo(type, 'is'), true);\r\n this.equals = arrayEqualsHandler(bindTo(type, 'equals'));\r\n this.pattern = type.pattern;\r\n this.$normalize = arrayHandler(bindTo(type, '$normalize'));\r\n this.name = type.name;\r\n this.$arrayMode = mode;\r\n }\r\n\r\n return new ArrayType(this, mode);\r\n};\r\n\r\n\r\n\r\n/**\r\n * @ngdoc object\r\n * @name ui.router.util.$urlMatcherFactory\r\n *\r\n * @description\r\n * Factory for {@link ui.router.util.type:UrlMatcher `UrlMatcher`} instances. The factory\r\n * is also available to providers under the name `$urlMatcherFactoryProvider`.\r\n */\r\nfunction $UrlMatcherFactory() {\r\n $$UMFP = this;\r\n\r\n var isCaseInsensitive = false, isStrictMode = true, defaultSquashPolicy = false;\r\n\r\n function valToString(val) { return val != null ? val.toString().replace(/\\//g, \"%2F\") : val; }\r\n function valFromString(val) { return val != null ? val.toString().replace(/%2F/g, \"/\") : val; }\r\n\r\n var $types = {}, enqueue = true, typeQueue = [], injector, defaultTypes = {\r\n string: {\r\n encode: valToString,\r\n decode: valFromString,\r\n // TODO: in 1.0, make string .is() return false if value is undefined/null by default.\r\n // In 0.2.x, string params are optional by default for backwards compat\r\n is: function(val) { return val == null || !isDefined(val) || typeof val === \"string\"; },\r\n pattern: /[^/]*/\r\n },\r\n int: {\r\n encode: valToString,\r\n decode: function(val) { return parseInt(val, 10); },\r\n is: function(val) { return isDefined(val) && this.decode(val.toString()) === val; },\r\n pattern: /\\d+/\r\n },\r\n bool: {\r\n encode: function(val) { return val ? 1 : 0; },\r\n decode: function(val) { return parseInt(val, 10) !== 0; },\r\n is: function(val) { return val === true || val === false; },\r\n pattern: /0|1/\r\n },\r\n date: {\r\n encode: function (val) {\r\n if (!this.is(val))\r\n return undefined;\r\n return [ val.getFullYear(),\r\n ('0' + (val.getMonth() + 1)).slice(-2),\r\n ('0' + val.getDate()).slice(-2)\r\n ].join(\"-\");\r\n },\r\n decode: function (val) {\r\n if (this.is(val)) return val;\r\n var match = this.capture.exec(val);\r\n return match ? new Date(match[1], match[2] - 1, match[3]) : undefined;\r\n },\r\n is: function(val) { return val instanceof Date && !isNaN(val.valueOf()); },\r\n equals: function (a, b) { return this.is(a) && this.is(b) && a.toISOString() === b.toISOString(); },\r\n pattern: /[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/,\r\n capture: /([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/\r\n },\r\n json: {\r\n encode: angular.toJson,\r\n decode: angular.fromJson,\r\n is: angular.isObject,\r\n equals: angular.equals,\r\n pattern: /[^/]*/\r\n },\r\n any: { // does not encode/decode\r\n encode: angular.identity,\r\n decode: angular.identity,\r\n equals: angular.equals,\r\n pattern: /.*/\r\n }\r\n };\r\n\r\n function getDefaultConfig() {\r\n return {\r\n strict: isStrictMode,\r\n caseInsensitive: isCaseInsensitive\r\n };\r\n }\r\n\r\n function isInjectable(value) {\r\n return (isFunction(value) || (isArray(value) && isFunction(value[value.length - 1])));\r\n }\r\n\r\n /**\r\n * [Internal] Get the default value of a parameter, which may be an injectable function.\r\n */\r\n $UrlMatcherFactory.$$getDefaultValue = function(config) {\r\n if (!isInjectable(config.value)) return config.value;\r\n if (!injector) throw new Error(\"Injectable functions cannot be called at configuration time\");\r\n return injector.invoke(config.value);\r\n };\r\n\r\n /**\r\n * @ngdoc function\r\n * @name ui.router.util.$urlMatcherFactory#caseInsensitive\r\n * @methodOf ui.router.util.$urlMatcherFactory\r\n *\r\n * @description\r\n * Defines whether URL matching should be case sensitive (the default behavior), or not.\r\n *\r\n * @param {boolean} value `false` to match URL in a case sensitive manner; otherwise `true`;\r\n * @returns {boolean} the current value of caseInsensitive\r\n */\r\n this.caseInsensitive = function(value) {\r\n if (isDefined(value))\r\n isCaseInsensitive = value;\r\n return isCaseInsensitive;\r\n };\r\n\r\n /**\r\n * @ngdoc function\r\n * @name ui.router.util.$urlMatcherFactory#strictMode\r\n * @methodOf ui.router.util.$urlMatcherFactory\r\n *\r\n * @description\r\n * Defines whether URLs should match trailing slashes, or not (the default behavior).\r\n *\r\n * @param {boolean=} value `false` to match trailing slashes in URLs, otherwise `true`.\r\n * @returns {boolean} the current value of strictMode\r\n */\r\n this.strictMode = function(value) {\r\n if (isDefined(value))\r\n isStrictMode = value;\r\n return isStrictMode;\r\n };\r\n\r\n /**\r\n * @ngdoc function\r\n * @name ui.router.util.$urlMatcherFactory#defaultSquashPolicy\r\n * @methodOf ui.router.util.$urlMatcherFactory\r\n *\r\n * @description\r\n * Sets the default behavior when generating or matching URLs with default parameter values.\r\n *\r\n * @param {string} value A string that defines the default parameter URL squashing behavior.\r\n * `nosquash`: When generating an href with a default parameter value, do not squash the parameter value from the URL\r\n * `slash`: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the\r\n * parameter is surrounded by slashes, squash (remove) one slash from the URL\r\n * any other string, e.g. \"~\": When generating an href with a default parameter value, squash (remove)\r\n * the parameter value from the URL and replace it with this string.\r\n */\r\n this.defaultSquashPolicy = function(value) {\r\n if (!isDefined(value)) return defaultSquashPolicy;\r\n if (value !== true && value !== false && !isString(value))\r\n throw new Error(\"Invalid squash policy: \" + value + \". Valid policies: false, true, arbitrary-string\");\r\n defaultSquashPolicy = value;\r\n return value;\r\n };\r\n\r\n /**\r\n * @ngdoc function\r\n * @name ui.router.util.$urlMatcherFactory#compile\r\n * @methodOf ui.router.util.$urlMatcherFactory\r\n *\r\n * @description\r\n * Creates a {@link ui.router.util.type:UrlMatcher `UrlMatcher`} for the specified pattern.\r\n *\r\n * @param {string} pattern The URL pattern.\r\n * @param {Object} config The config object hash.\r\n * @returns {UrlMatcher} The UrlMatcher.\r\n */\r\n this.compile = function (pattern, config) {\r\n return new UrlMatcher(pattern, extend(getDefaultConfig(), config));\r\n };\r\n\r\n /**\r\n * @ngdoc function\r\n * @name ui.router.util.$urlMatcherFactory#isMatcher\r\n * @methodOf ui.router.util.$urlMatcherFactory\r\n *\r\n * @description\r\n * Returns true if the specified object is a `UrlMatcher`, or false otherwise.\r\n *\r\n * @param {Object} object The object to perform the type check against.\r\n * @returns {Boolean} Returns `true` if the object matches the `UrlMatcher` interface, by\r\n * implementing all the same methods.\r\n */\r\n this.isMatcher = function (o) {\r\n if (!isObject(o)) return false;\r\n var result = true;\r\n\r\n forEach(UrlMatcher.prototype, function(val, name) {\r\n if (isFunction(val)) {\r\n result = result && (isDefined(o[name]) && isFunction(o[name]));\r\n }\r\n });\r\n return result;\r\n };\r\n\r\n /**\r\n * @ngdoc function\r\n * @name ui.router.util.$urlMatcherFactory#type\r\n * @methodOf ui.router.util.$urlMatcherFactory\r\n *\r\n * @description\r\n * Registers a custom {@link ui.router.util.type:Type `Type`} object that can be used to\r\n * generate URLs with typed parameters.\r\n *\r\n * @param {string} name The type name.\r\n * @param {Object|Function} definition The type definition. See\r\n * {@link ui.router.util.type:Type `Type`} for information on the values accepted.\r\n * @param {Object|Function} definitionFn (optional) A function that is injected before the app\r\n * runtime starts. The result of this function is merged into the existing `definition`.\r\n * See {@link ui.router.util.type:Type `Type`} for information on the values accepted.\r\n *\r\n * @returns {Object} Returns `$urlMatcherFactoryProvider`.\r\n *\r\n * @example\r\n * This is a simple example of a custom type that encodes and decodes items from an\r\n * array, using the array index as the URL-encoded value:\r\n *\r\n *
    \r\n   * var list = ['John', 'Paul', 'George', 'Ringo'];\r\n   *\r\n   * $urlMatcherFactoryProvider.type('listItem', {\r\n   *   encode: function(item) {\r\n   *     // Represent the list item in the URL using its corresponding index\r\n   *     return list.indexOf(item);\r\n   *   },\r\n   *   decode: function(item) {\r\n   *     // Look up the list item by index\r\n   *     return list[parseInt(item, 10)];\r\n   *   },\r\n   *   is: function(item) {\r\n   *     // Ensure the item is valid by checking to see that it appears\r\n   *     // in the list\r\n   *     return list.indexOf(item) > -1;\r\n   *   }\r\n   * });\r\n   *\r\n   * $stateProvider.state('list', {\r\n   *   url: \"/list/{item:listItem}\",\r\n   *   controller: function($scope, $stateParams) {\r\n   *     console.log($stateParams.item);\r\n   *   }\r\n   * });\r\n   *\r\n   * // ...\r\n   *\r\n   * // Changes URL to '/list/3', logs \"Ringo\" to the console\r\n   * $state.go('list', { item: \"Ringo\" });\r\n   * 
    \r\n *\r\n * This is a more complex example of a type that relies on dependency injection to\r\n * interact with services, and uses the parameter name from the URL to infer how to\r\n * handle encoding and decoding parameter values:\r\n *\r\n *
    \r\n   * // Defines a custom type that gets a value from a service,\r\n   * // where each service gets different types of values from\r\n   * // a backend API:\r\n   * $urlMatcherFactoryProvider.type('dbObject', {}, function(Users, Posts) {\r\n   *\r\n   *   // Matches up services to URL parameter names\r\n   *   var services = {\r\n   *     user: Users,\r\n   *     post: Posts\r\n   *   };\r\n   *\r\n   *   return {\r\n   *     encode: function(object) {\r\n   *       // Represent the object in the URL using its unique ID\r\n   *       return object.id;\r\n   *     },\r\n   *     decode: function(value, key) {\r\n   *       // Look up the object by ID, using the parameter\r\n   *       // name (key) to call the correct service\r\n   *       return services[key].findById(value);\r\n   *     },\r\n   *     is: function(object, key) {\r\n   *       // Check that object is a valid dbObject\r\n   *       return angular.isObject(object) && object.id && services[key];\r\n   *     }\r\n   *     equals: function(a, b) {\r\n   *       // Check the equality of decoded objects by comparing\r\n   *       // their unique IDs\r\n   *       return a.id === b.id;\r\n   *     }\r\n   *   };\r\n   * });\r\n   *\r\n   * // In a config() block, you can then attach URLs with\r\n   * // type-annotated parameters:\r\n   * $stateProvider.state('users', {\r\n   *   url: \"/users\",\r\n   *   // ...\r\n   * }).state('users.item', {\r\n   *   url: \"/{user:dbObject}\",\r\n   *   controller: function($scope, $stateParams) {\r\n   *     // $stateParams.user will now be an object returned from\r\n   *     // the Users service\r\n   *   },\r\n   *   // ...\r\n   * });\r\n   * 
    \r\n */\r\n this.type = function (name, definition, definitionFn) {\r\n if (!isDefined(definition)) return $types[name];\r\n if ($types.hasOwnProperty(name)) throw new Error(\"A type named '\" + name + \"' has already been defined.\");\r\n\r\n $types[name] = new Type(extend({ name: name }, definition));\r\n if (definitionFn) {\r\n typeQueue.push({ name: name, def: definitionFn });\r\n if (!enqueue) flushTypeQueue();\r\n }\r\n return this;\r\n };\r\n\r\n // `flushTypeQueue()` waits until `$urlMatcherFactory` is injected before invoking the queued `definitionFn`s\r\n function flushTypeQueue() {\r\n while(typeQueue.length) {\r\n var type = typeQueue.shift();\r\n if (type.pattern) throw new Error(\"You cannot override a type's .pattern at runtime.\");\r\n angular.extend($types[type.name], injector.invoke(type.def));\r\n }\r\n }\r\n\r\n // Register default types. Store them in the prototype of $types.\r\n forEach(defaultTypes, function(type, name) { $types[name] = new Type(extend({name: name}, type)); });\r\n $types = inherit($types, {});\r\n\r\n /* No need to document $get, since it returns this */\r\n this.$get = ['$injector', function ($injector) {\r\n injector = $injector;\r\n enqueue = false;\r\n flushTypeQueue();\r\n\r\n forEach(defaultTypes, function(type, name) {\r\n if (!$types[name]) $types[name] = new Type(type);\r\n });\r\n return this;\r\n }];\r\n\r\n this.Param = function Param(id, type, config, location) {\r\n var self = this;\r\n config = unwrapShorthand(config);\r\n type = getType(config, type, location);\r\n var arrayMode = getArrayMode();\r\n type = arrayMode ? type.$asArray(arrayMode, location === \"search\") : type;\r\n if (type.name === \"string\" && !arrayMode && location === \"path\" && config.value === undefined)\r\n config.value = \"\"; // for 0.2.x; in 0.3.0+ do not automatically default to \"\"\r\n var isOptional = config.value !== undefined;\r\n var squash = getSquashPolicy(config, isOptional);\r\n var replace = getReplace(config, arrayMode, isOptional, squash);\r\n\r\n function unwrapShorthand(config) {\r\n var keys = isObject(config) ? objectKeys(config) : [];\r\n var isShorthand = indexOf(keys, \"value\") === -1 && indexOf(keys, \"type\") === -1 &&\r\n indexOf(keys, \"squash\") === -1 && indexOf(keys, \"array\") === -1;\r\n if (isShorthand) config = { value: config };\r\n config.$$fn = isInjectable(config.value) ? config.value : function () { return config.value; };\r\n return config;\r\n }\r\n\r\n function getType(config, urlType, location) {\r\n if (config.type && urlType) throw new Error(\"Param '\"+id+\"' has two type configurations.\");\r\n if (urlType) return urlType;\r\n if (!config.type) return (location === \"config\" ? $types.any : $types.string);\r\n return config.type instanceof Type ? config.type : new Type(config.type);\r\n }\r\n\r\n // array config: param name (param[]) overrides default settings. explicit config overrides param name.\r\n function getArrayMode() {\r\n var arrayDefaults = { array: (location === \"search\" ? \"auto\" : false) };\r\n var arrayParamNomenclature = id.match(/\\[\\]$/) ? { array: true } : {};\r\n return extend(arrayDefaults, arrayParamNomenclature, config).array;\r\n }\r\n\r\n /**\r\n * returns false, true, or the squash value to indicate the \"default parameter url squash policy\".\r\n */\r\n function getSquashPolicy(config, isOptional) {\r\n var squash = config.squash;\r\n if (!isOptional || squash === false) return false;\r\n if (!isDefined(squash) || squash == null) return defaultSquashPolicy;\r\n if (squash === true || isString(squash)) return squash;\r\n throw new Error(\"Invalid squash policy: '\" + squash + \"'. Valid policies: false, true, or arbitrary string\");\r\n }\r\n\r\n function getReplace(config, arrayMode, isOptional, squash) {\r\n var replace, configuredKeys, defaultPolicy = [\r\n { from: \"\", to: (isOptional || arrayMode ? undefined : \"\") },\r\n { from: null, to: (isOptional || arrayMode ? undefined : \"\") }\r\n ];\r\n replace = isArray(config.replace) ? config.replace : [];\r\n if (isString(squash))\r\n replace.push({ from: squash, to: undefined });\r\n configuredKeys = map(replace, function(item) { return item.from; } );\r\n return filter(defaultPolicy, function(item) { return indexOf(configuredKeys, item.from) === -1; }).concat(replace);\r\n }\r\n\r\n /**\r\n * [Internal] Get the default value of a parameter, which may be an injectable function.\r\n */\r\n function $$getDefaultValue() {\r\n if (!injector) throw new Error(\"Injectable functions cannot be called at configuration time\");\r\n var defaultValue = injector.invoke(config.$$fn);\r\n if (defaultValue !== null && defaultValue !== undefined && !self.type.is(defaultValue))\r\n throw new Error(\"Default value (\" + defaultValue + \") for parameter '\" + self.id + \"' is not an instance of Type (\" + self.type.name + \")\");\r\n return defaultValue;\r\n }\r\n\r\n /**\r\n * [Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the\r\n * default value, which may be the result of an injectable function.\r\n */\r\n function $value(value) {\r\n function hasReplaceVal(val) { return function(obj) { return obj.from === val; }; }\r\n function $replace(value) {\r\n var replacement = map(filter(self.replace, hasReplaceVal(value)), function(obj) { return obj.to; });\r\n return replacement.length ? replacement[0] : value;\r\n }\r\n value = $replace(value);\r\n return !isDefined(value) ? $$getDefaultValue() : self.type.$normalize(value);\r\n }\r\n\r\n function toString() { return \"{Param:\" + id + \" \" + type + \" squash: '\" + squash + \"' optional: \" + isOptional + \"}\"; }\r\n\r\n extend(this, {\r\n id: id,\r\n type: type,\r\n location: location,\r\n array: arrayMode,\r\n squash: squash,\r\n replace: replace,\r\n isOptional: isOptional,\r\n value: $value,\r\n dynamic: undefined,\r\n config: config,\r\n toString: toString\r\n });\r\n };\r\n\r\n function ParamSet(params) {\r\n extend(this, params || {});\r\n }\r\n\r\n ParamSet.prototype = {\r\n $$new: function() {\r\n return inherit(this, extend(new ParamSet(), { $$parent: this}));\r\n },\r\n $$keys: function () {\r\n var keys = [], chain = [], parent = this,\r\n ignore = objectKeys(ParamSet.prototype);\r\n while (parent) { chain.push(parent); parent = parent.$$parent; }\r\n chain.reverse();\r\n forEach(chain, function(paramset) {\r\n forEach(objectKeys(paramset), function(key) {\r\n if (indexOf(keys, key) === -1 && indexOf(ignore, key) === -1) keys.push(key);\r\n });\r\n });\r\n return keys;\r\n },\r\n $$values: function(paramValues) {\r\n var values = {}, self = this;\r\n forEach(self.$$keys(), function(key) {\r\n values[key] = self[key].value(paramValues && paramValues[key]);\r\n });\r\n return values;\r\n },\r\n $$equals: function(paramValues1, paramValues2) {\r\n var equal = true, self = this;\r\n forEach(self.$$keys(), function(key) {\r\n var left = paramValues1 && paramValues1[key], right = paramValues2 && paramValues2[key];\r\n if (!self[key].type.equals(left, right)) equal = false;\r\n });\r\n return equal;\r\n },\r\n $$validates: function $$validate(paramValues) {\r\n var keys = this.$$keys(), i, param, rawVal, normalized, encoded;\r\n for (i = 0; i < keys.length; i++) {\r\n param = this[keys[i]];\r\n rawVal = paramValues[keys[i]];\r\n if ((rawVal === undefined || rawVal === null) && param.isOptional)\r\n break; // There was no parameter value, but the param is optional\r\n normalized = param.type.$normalize(rawVal);\r\n if (!param.type.is(normalized))\r\n return false; // The value was not of the correct Type, and could not be decoded to the correct Type\r\n encoded = param.type.encode(normalized);\r\n if (angular.isString(encoded) && !param.type.pattern.exec(encoded))\r\n return false; // The value was of the correct type, but when encoded, did not match the Type's regexp\r\n }\r\n return true;\r\n },\r\n $$parent: undefined\r\n };\r\n\r\n this.ParamSet = ParamSet;\r\n}\r\n\r\n// Register as a provider so it's available to other providers\r\nangular.module('ui.router.util').provider('$urlMatcherFactory', $UrlMatcherFactory);\r\nangular.module('ui.router.util').run(['$urlMatcherFactory', function($urlMatcherFactory) { }]);\r\n\r\n/**\r\n * @ngdoc object\r\n * @name ui.router.router.$urlRouterProvider\r\n *\r\n * @requires ui.router.util.$urlMatcherFactoryProvider\r\n * @requires $locationProvider\r\n *\r\n * @description\r\n * `$urlRouterProvider` has the responsibility of watching `$location`. \r\n * When `$location` changes it runs through a list of rules one by one until a \r\n * match is found. `$urlRouterProvider` is used behind the scenes anytime you specify \r\n * a url in a state configuration. All urls are compiled into a UrlMatcher object.\r\n *\r\n * There are several methods on `$urlRouterProvider` that make it useful to use directly\r\n * in your module config.\r\n */\r\n$UrlRouterProvider.$inject = ['$locationProvider', '$urlMatcherFactoryProvider'];\r\nfunction $UrlRouterProvider( $locationProvider, $urlMatcherFactory) {\r\n var rules = [], otherwise = null, interceptDeferred = false, listener;\r\n\r\n // Returns a string that is a prefix of all strings matching the RegExp\r\n function regExpPrefix(re) {\r\n var prefix = /^\\^((?:\\\\[^a-zA-Z0-9]|[^\\\\\\[\\]\\^$*+?.()|{}]+)*)/.exec(re.source);\r\n return (prefix != null) ? prefix[1].replace(/\\\\(.)/g, \"$1\") : '';\r\n }\r\n\r\n // Interpolates matched values into a String.replace()-style pattern\r\n function interpolate(pattern, match) {\r\n return pattern.replace(/\\$(\\$|\\d{1,2})/, function (m, what) {\r\n return match[what === '$' ? 0 : Number(what)];\r\n });\r\n }\r\n\r\n /**\r\n * @ngdoc function\r\n * @name ui.router.router.$urlRouterProvider#rule\r\n * @methodOf ui.router.router.$urlRouterProvider\r\n *\r\n * @description\r\n * Defines rules that are used by `$urlRouterProvider` to find matches for\r\n * specific URLs.\r\n *\r\n * @example\r\n *
    \r\n   * var app = angular.module('app', ['ui.router.router']);\r\n   *\r\n   * app.config(function ($urlRouterProvider) {\r\n   *   // Here's an example of how you might allow case insensitive urls\r\n   *   $urlRouterProvider.rule(function ($injector, $location) {\r\n   *     var path = $location.path(),\r\n   *         normalized = path.toLowerCase();\r\n   *\r\n   *     if (path !== normalized) {\r\n   *       return normalized;\r\n   *     }\r\n   *   });\r\n   * });\r\n   * 
    \r\n *\r\n * @param {object} rule Handler function that takes `$injector` and `$location`\r\n * services as arguments. You can use them to return a valid path as a string.\r\n *\r\n * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance\r\n */\r\n this.rule = function (rule) {\r\n if (!isFunction(rule)) throw new Error(\"'rule' must be a function\");\r\n rules.push(rule);\r\n return this;\r\n };\r\n\r\n /**\r\n * @ngdoc object\r\n * @name ui.router.router.$urlRouterProvider#otherwise\r\n * @methodOf ui.router.router.$urlRouterProvider\r\n *\r\n * @description\r\n * Defines a path that is used when an invalid route is requested.\r\n *\r\n * @example\r\n *
    \r\n   * var app = angular.module('app', ['ui.router.router']);\r\n   *\r\n   * app.config(function ($urlRouterProvider) {\r\n   *   // if the path doesn't match any of the urls you configured\r\n   *   // otherwise will take care of routing the user to the\r\n   *   // specified url\r\n   *   $urlRouterProvider.otherwise('/index');\r\n   *\r\n   *   // Example of using function rule as param\r\n   *   $urlRouterProvider.otherwise(function ($injector, $location) {\r\n   *     return '/a/valid/url';\r\n   *   });\r\n   * });\r\n   * 
    \r\n *\r\n * @param {string|object} rule The url path you want to redirect to or a function \r\n * rule that returns the url path. The function version is passed two params: \r\n * `$injector` and `$location` services, and must return a url string.\r\n *\r\n * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance\r\n */\r\n this.otherwise = function (rule) {\r\n if (isString(rule)) {\r\n var redirect = rule;\r\n rule = function () { return redirect; };\r\n }\r\n else if (!isFunction(rule)) throw new Error(\"'rule' must be a function\");\r\n otherwise = rule;\r\n return this;\r\n };\r\n\r\n\r\n function handleIfMatch($injector, handler, match) {\r\n if (!match) return false;\r\n var result = $injector.invoke(handler, handler, { $match: match });\r\n return isDefined(result) ? result : true;\r\n }\r\n\r\n /**\r\n * @ngdoc function\r\n * @name ui.router.router.$urlRouterProvider#when\r\n * @methodOf ui.router.router.$urlRouterProvider\r\n *\r\n * @description\r\n * Registers a handler for a given url matching. if handle is a string, it is\r\n * treated as a redirect, and is interpolated according to the syntax of match\r\n * (i.e. like `String.replace()` for `RegExp`, or like a `UrlMatcher` pattern otherwise).\r\n *\r\n * If the handler is a function, it is injectable. It gets invoked if `$location`\r\n * matches. You have the option of inject the match object as `$match`.\r\n *\r\n * The handler can return\r\n *\r\n * - **falsy** to indicate that the rule didn't match after all, then `$urlRouter`\r\n * will continue trying to find another one that matches.\r\n * - **string** which is treated as a redirect and passed to `$location.url()`\r\n * - **void** or any **truthy** value tells `$urlRouter` that the url was handled.\r\n *\r\n * @example\r\n *
    \r\n   * var app = angular.module('app', ['ui.router.router']);\r\n   *\r\n   * app.config(function ($urlRouterProvider) {\r\n   *   $urlRouterProvider.when($state.url, function ($match, $stateParams) {\r\n   *     if ($state.$current.navigable !== state ||\r\n   *         !equalForKeys($match, $stateParams) {\r\n   *      $state.transitionTo(state, $match, false);\r\n   *     }\r\n   *   });\r\n   * });\r\n   * 
    \r\n *\r\n * @param {string|object} what The incoming path that you want to redirect.\r\n * @param {string|object} handler The path you want to redirect your user to.\r\n */\r\n this.when = function (what, handler) {\r\n var redirect, handlerIsString = isString(handler);\r\n if (isString(what)) what = $urlMatcherFactory.compile(what);\r\n\r\n if (!handlerIsString && !isFunction(handler) && !isArray(handler))\r\n throw new Error(\"invalid 'handler' in when()\");\r\n\r\n var strategies = {\r\n matcher: function (what, handler) {\r\n if (handlerIsString) {\r\n redirect = $urlMatcherFactory.compile(handler);\r\n handler = ['$match', function ($match) { return redirect.format($match); }];\r\n }\r\n return extend(function ($injector, $location) {\r\n return handleIfMatch($injector, handler, what.exec($location.path(), $location.search()));\r\n }, {\r\n prefix: isString(what.prefix) ? what.prefix : ''\r\n });\r\n },\r\n regex: function (what, handler) {\r\n if (what.global || what.sticky) throw new Error(\"when() RegExp must not be global or sticky\");\r\n\r\n if (handlerIsString) {\r\n redirect = handler;\r\n handler = ['$match', function ($match) { return interpolate(redirect, $match); }];\r\n }\r\n return extend(function ($injector, $location) {\r\n return handleIfMatch($injector, handler, what.exec($location.path()));\r\n }, {\r\n prefix: regExpPrefix(what)\r\n });\r\n }\r\n };\r\n\r\n var check = { matcher: $urlMatcherFactory.isMatcher(what), regex: what instanceof RegExp };\r\n\r\n for (var n in check) {\r\n if (check[n]) return this.rule(strategies[n](what, handler));\r\n }\r\n\r\n throw new Error(\"invalid 'what' in when()\");\r\n };\r\n\r\n /**\r\n * @ngdoc function\r\n * @name ui.router.router.$urlRouterProvider#deferIntercept\r\n * @methodOf ui.router.router.$urlRouterProvider\r\n *\r\n * @description\r\n * Disables (or enables) deferring location change interception.\r\n *\r\n * If you wish to customize the behavior of syncing the URL (for example, if you wish to\r\n * defer a transition but maintain the current URL), call this method at configuration time.\r\n * Then, at run time, call `$urlRouter.listen()` after you have configured your own\r\n * `$locationChangeSuccess` event handler.\r\n *\r\n * @example\r\n *
    \r\n   * var app = angular.module('app', ['ui.router.router']);\r\n   *\r\n   * app.config(function ($urlRouterProvider) {\r\n   *\r\n   *   // Prevent $urlRouter from automatically intercepting URL changes;\r\n   *   // this allows you to configure custom behavior in between\r\n   *   // location changes and route synchronization:\r\n   *   $urlRouterProvider.deferIntercept();\r\n   *\r\n   * }).run(function ($rootScope, $urlRouter, UserService) {\r\n   *\r\n   *   $rootScope.$on('$locationChangeSuccess', function(e) {\r\n   *     // UserService is an example service for managing user state\r\n   *     if (UserService.isLoggedIn()) return;\r\n   *\r\n   *     // Prevent $urlRouter's default handler from firing\r\n   *     e.preventDefault();\r\n   *\r\n   *     UserService.handleLogin().then(function() {\r\n   *       // Once the user has logged in, sync the current URL\r\n   *       // to the router:\r\n   *       $urlRouter.sync();\r\n   *     });\r\n   *   });\r\n   *\r\n   *   // Configures $urlRouter's listener *after* your custom listener\r\n   *   $urlRouter.listen();\r\n   * });\r\n   * 
    \r\n *\r\n * @param {boolean} defer Indicates whether to defer location change interception. Passing\r\n no parameter is equivalent to `true`.\r\n */\r\n this.deferIntercept = function (defer) {\r\n if (defer === undefined) defer = true;\r\n interceptDeferred = defer;\r\n };\r\n\r\n /**\r\n * @ngdoc object\r\n * @name ui.router.router.$urlRouter\r\n *\r\n * @requires $location\r\n * @requires $rootScope\r\n * @requires $injector\r\n * @requires $browser\r\n *\r\n * @description\r\n *\r\n */\r\n this.$get = $get;\r\n $get.$inject = ['$location', '$rootScope', '$injector', '$browser'];\r\n function $get( $location, $rootScope, $injector, $browser) {\r\n\r\n var baseHref = $browser.baseHref(), location = $location.url(), lastPushedUrl;\r\n\r\n function appendBasePath(url, isHtml5, absolute) {\r\n if (baseHref === '/') return url;\r\n if (isHtml5) return baseHref.slice(0, -1) + url;\r\n if (absolute) return baseHref.slice(1) + url;\r\n return url;\r\n }\r\n\r\n // TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree\r\n function update(evt) {\r\n if (evt && evt.defaultPrevented) return;\r\n var ignoreUpdate = lastPushedUrl && $location.url() === lastPushedUrl;\r\n lastPushedUrl = undefined;\r\n // TODO: Re-implement this in 1.0 for https://github.com/angular-ui/ui-router/issues/1573\r\n //if (ignoreUpdate) return true;\r\n\r\n function check(rule) {\r\n var handled = rule($injector, $location);\r\n\r\n if (!handled) return false;\r\n if (isString(handled)) $location.replace().url(handled);\r\n return true;\r\n }\r\n var n = rules.length, i;\r\n\r\n for (i = 0; i < n; i++) {\r\n if (check(rules[i])) return;\r\n }\r\n // always check otherwise last to allow dynamic updates to the set of rules\r\n if (otherwise) check(otherwise);\r\n }\r\n\r\n function listen() {\r\n listener = listener || $rootScope.$on('$locationChangeSuccess', update);\r\n return listener;\r\n }\r\n\r\n if (!interceptDeferred) listen();\r\n\r\n return {\r\n /**\r\n * @ngdoc function\r\n * @name ui.router.router.$urlRouter#sync\r\n * @methodOf ui.router.router.$urlRouter\r\n *\r\n * @description\r\n * Triggers an update; the same update that happens when the address bar url changes, aka `$locationChangeSuccess`.\r\n * This method is useful when you need to use `preventDefault()` on the `$locationChangeSuccess` event,\r\n * perform some custom logic (route protection, auth, config, redirection, etc) and then finally proceed\r\n * with the transition by calling `$urlRouter.sync()`.\r\n *\r\n * @example\r\n *
    \r\n       * angular.module('app', ['ui.router'])\r\n       *   .run(function($rootScope, $urlRouter) {\r\n       *     $rootScope.$on('$locationChangeSuccess', function(evt) {\r\n       *       // Halt state change from even starting\r\n       *       evt.preventDefault();\r\n       *       // Perform custom logic\r\n       *       var meetsRequirement = ...\r\n       *       // Continue with the update and state transition if logic allows\r\n       *       if (meetsRequirement) $urlRouter.sync();\r\n       *     });\r\n       * });\r\n       * 
    \r\n */\r\n sync: function() {\r\n update();\r\n },\r\n\r\n listen: function() {\r\n return listen();\r\n },\r\n\r\n update: function(read) {\r\n if (read) {\r\n location = $location.url();\r\n return;\r\n }\r\n if ($location.url() === location) return;\r\n\r\n $location.url(location);\r\n $location.replace();\r\n },\r\n\r\n push: function(urlMatcher, params, options) {\r\n var url = urlMatcher.format(params || {});\r\n\r\n // Handle the special hash param, if needed\r\n if (url !== null && params && params['#']) {\r\n url += '#' + params['#'];\r\n }\r\n\r\n $location.url(url);\r\n lastPushedUrl = options && options.$$avoidResync ? $location.url() : undefined;\r\n if (options && options.replace) $location.replace();\r\n },\r\n\r\n /**\r\n * @ngdoc function\r\n * @name ui.router.router.$urlRouter#href\r\n * @methodOf ui.router.router.$urlRouter\r\n *\r\n * @description\r\n * A URL generation method that returns the compiled URL for a given\r\n * {@link ui.router.util.type:UrlMatcher `UrlMatcher`}, populated with the provided parameters.\r\n *\r\n * @example\r\n *
    \r\n       * $bob = $urlRouter.href(new UrlMatcher(\"/about/:person\"), {\r\n       *   person: \"bob\"\r\n       * });\r\n       * // $bob == \"/about/bob\";\r\n       * 
    \r\n *\r\n * @param {UrlMatcher} urlMatcher The `UrlMatcher` object which is used as the template of the URL to generate.\r\n * @param {object=} params An object of parameter values to fill the matcher's required parameters.\r\n * @param {object=} options Options object. The options are:\r\n *\r\n * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. \"http://www.example.com/fullurl\".\r\n *\r\n * @returns {string} Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher`\r\n */\r\n href: function(urlMatcher, params, options) {\r\n if (!urlMatcher.validates(params)) return null;\r\n\r\n var isHtml5 = $locationProvider.html5Mode();\r\n if (angular.isObject(isHtml5)) {\r\n isHtml5 = isHtml5.enabled;\r\n }\r\n \r\n var url = urlMatcher.format(params);\r\n options = options || {};\r\n\r\n if (!isHtml5 && url !== null) {\r\n url = \"#\" + $locationProvider.hashPrefix() + url;\r\n }\r\n\r\n // Handle special hash param, if needed\r\n if (url !== null && params && params['#']) {\r\n url += '#' + params['#'];\r\n }\r\n\r\n url = appendBasePath(url, isHtml5, options.absolute);\r\n\r\n if (!options.absolute || !url) {\r\n return url;\r\n }\r\n\r\n var slash = (!isHtml5 && url ? '/' : ''), port = $location.port();\r\n port = (port === 80 || port === 443 ? '' : ':' + port);\r\n\r\n return [$location.protocol(), '://', $location.host(), port, slash, url].join('');\r\n }\r\n };\r\n }\r\n}\r\n\r\nangular.module('ui.router.router').provider('$urlRouter', $UrlRouterProvider);\r\n\r\n/**\r\n * @ngdoc object\r\n * @name ui.router.state.$stateProvider\r\n *\r\n * @requires ui.router.router.$urlRouterProvider\r\n * @requires ui.router.util.$urlMatcherFactoryProvider\r\n *\r\n * @description\r\n * The new `$stateProvider` works similar to Angular's v1 router, but it focuses purely\r\n * on state.\r\n *\r\n * A state corresponds to a \"place\" in the application in terms of the overall UI and\r\n * navigation. A state describes (via the controller / template / view properties) what\r\n * the UI looks like and does at that place.\r\n *\r\n * States often have things in common, and the primary way of factoring out these\r\n * commonalities in this model is via the state hierarchy, i.e. parent/child states aka\r\n * nested states.\r\n *\r\n * The `$stateProvider` provides interfaces to declare these states for your app.\r\n */\r\n$StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider'];\r\nfunction $StateProvider( $urlRouterProvider, $urlMatcherFactory) {\r\n\r\n var root, states = {}, $state, queue = {}, abstractKey = 'abstract';\r\n\r\n // Builds state properties from definition passed to registerState()\r\n var stateBuilder = {\r\n\r\n // Derive parent state from a hierarchical name only if 'parent' is not explicitly defined.\r\n // state.children = [];\r\n // if (parent) parent.children.push(state);\r\n parent: function(state) {\r\n if (isDefined(state.parent) && state.parent) return findState(state.parent);\r\n // regex matches any valid composite state name\r\n // would match \"contact.list\" but not \"contacts\"\r\n var compositeName = /^(.+)\\.[^.]+$/.exec(state.name);\r\n return compositeName ? findState(compositeName[1]) : root;\r\n },\r\n\r\n // inherit 'data' from parent and override by own values (if any)\r\n data: function(state) {\r\n if (state.parent && state.parent.data) {\r\n state.data = state.self.data = extend({}, state.parent.data, state.data);\r\n }\r\n return state.data;\r\n },\r\n\r\n // Build a URLMatcher if necessary, either via a relative or absolute URL\r\n url: function(state) {\r\n var url = state.url, config = { params: state.params || {} };\r\n\r\n if (isString(url)) {\r\n if (url.charAt(0) == '^') return $urlMatcherFactory.compile(url.substring(1), config);\r\n return (state.parent.navigable || root).url.concat(url, config);\r\n }\r\n\r\n if (!url || $urlMatcherFactory.isMatcher(url)) return url;\r\n throw new Error(\"Invalid url '\" + url + \"' in state '\" + state + \"'\");\r\n },\r\n\r\n // Keep track of the closest ancestor state that has a URL (i.e. is navigable)\r\n navigable: function(state) {\r\n return state.url ? state : (state.parent ? state.parent.navigable : null);\r\n },\r\n\r\n // Own parameters for this state. state.url.params is already built at this point. Create and add non-url params\r\n ownParams: function(state) {\r\n var params = state.url && state.url.params || new $$UMFP.ParamSet();\r\n forEach(state.params || {}, function(config, id) {\r\n if (!params[id]) params[id] = new $$UMFP.Param(id, null, config, \"config\");\r\n });\r\n return params;\r\n },\r\n\r\n // Derive parameters for this state and ensure they're a super-set of parent's parameters\r\n params: function(state) {\r\n return state.parent && state.parent.params ? extend(state.parent.params.$$new(), state.ownParams) : new $$UMFP.ParamSet();\r\n },\r\n\r\n // If there is no explicit multi-view configuration, make one up so we don't have\r\n // to handle both cases in the view directive later. Note that having an explicit\r\n // 'views' property will mean the default unnamed view properties are ignored. This\r\n // is also a good time to resolve view names to absolute names, so everything is a\r\n // straight lookup at link time.\r\n views: function(state) {\r\n var views = {};\r\n\r\n forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) {\r\n if (name.indexOf('@') < 0) name += '@' + state.parent.name;\r\n views[name] = view;\r\n });\r\n return views;\r\n },\r\n\r\n // Keep a full path from the root down to this state as this is needed for state activation.\r\n path: function(state) {\r\n return state.parent ? state.parent.path.concat(state) : []; // exclude root from path\r\n },\r\n\r\n // Speed up $state.contains() as it's used a lot\r\n includes: function(state) {\r\n var includes = state.parent ? extend({}, state.parent.includes) : {};\r\n includes[state.name] = true;\r\n return includes;\r\n },\r\n\r\n $delegates: {}\r\n };\r\n\r\n function isRelative(stateName) {\r\n return stateName.indexOf(\".\") === 0 || stateName.indexOf(\"^\") === 0;\r\n }\r\n\r\n function findState(stateOrName, base) {\r\n if (!stateOrName) return undefined;\r\n\r\n var isStr = isString(stateOrName),\r\n name = isStr ? stateOrName : stateOrName.name,\r\n path = isRelative(name);\r\n\r\n if (path) {\r\n if (!base) throw new Error(\"No reference point given for path '\" + name + \"'\");\r\n base = findState(base);\r\n \r\n var rel = name.split(\".\"), i = 0, pathLength = rel.length, current = base;\r\n\r\n for (; i < pathLength; i++) {\r\n if (rel[i] === \"\" && i === 0) {\r\n current = base;\r\n continue;\r\n }\r\n if (rel[i] === \"^\") {\r\n if (!current.parent) throw new Error(\"Path '\" + name + \"' not valid for state '\" + base.name + \"'\");\r\n current = current.parent;\r\n continue;\r\n }\r\n break;\r\n }\r\n rel = rel.slice(i).join(\".\");\r\n name = current.name + (current.name && rel ? \".\" : \"\") + rel;\r\n }\r\n var state = states[name];\r\n\r\n if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) {\r\n return state;\r\n }\r\n return undefined;\r\n }\r\n\r\n function queueState(parentName, state) {\r\n if (!queue[parentName]) {\r\n queue[parentName] = [];\r\n }\r\n queue[parentName].push(state);\r\n }\r\n\r\n function flushQueuedChildren(parentName) {\r\n var queued = queue[parentName] || [];\r\n while(queued.length) {\r\n registerState(queued.shift());\r\n }\r\n }\r\n\r\n function registerState(state) {\r\n // Wrap a new object around the state so we can store our private details easily.\r\n state = inherit(state, {\r\n self: state,\r\n resolve: state.resolve || {},\r\n toString: function() { return this.name; }\r\n });\r\n\r\n var name = state.name;\r\n if (!isString(name) || name.indexOf('@') >= 0) throw new Error(\"State must have a valid name\");\r\n if (states.hasOwnProperty(name)) throw new Error(\"State '\" + name + \"'' is already defined\");\r\n\r\n // Get parent name\r\n var parentName = (name.indexOf('.') !== -1) ? name.substring(0, name.lastIndexOf('.'))\r\n : (isString(state.parent)) ? state.parent\r\n : (isObject(state.parent) && isString(state.parent.name)) ? state.parent.name\r\n : '';\r\n\r\n // If parent is not registered yet, add state to queue and register later\r\n if (parentName && !states[parentName]) {\r\n return queueState(parentName, state.self);\r\n }\r\n\r\n for (var key in stateBuilder) {\r\n if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]);\r\n }\r\n states[name] = state;\r\n\r\n // Register the state in the global state list and with $urlRouter if necessary.\r\n if (!state[abstractKey] && state.url) {\r\n $urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) {\r\n if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) {\r\n $state.transitionTo(state, $match, { inherit: true, location: false });\r\n }\r\n }]);\r\n }\r\n\r\n // Register any queued children\r\n flushQueuedChildren(name);\r\n\r\n return state;\r\n }\r\n\r\n // Checks text to see if it looks like a glob.\r\n function isGlob (text) {\r\n return text.indexOf('*') > -1;\r\n }\r\n\r\n // Returns true if glob matches current $state name.\r\n function doesStateMatchGlob (glob) {\r\n var globSegments = glob.split('.'),\r\n segments = $state.$current.name.split('.');\r\n\r\n //match single stars\r\n for (var i = 0, l = globSegments.length; i < l; i++) {\r\n if (globSegments[i] === '*') {\r\n segments[i] = '*';\r\n }\r\n }\r\n\r\n //match greedy starts\r\n if (globSegments[0] === '**') {\r\n segments = segments.slice(indexOf(segments, globSegments[1]));\r\n segments.unshift('**');\r\n }\r\n //match greedy ends\r\n if (globSegments[globSegments.length - 1] === '**') {\r\n segments.splice(indexOf(segments, globSegments[globSegments.length - 2]) + 1, Number.MAX_VALUE);\r\n segments.push('**');\r\n }\r\n\r\n if (globSegments.length != segments.length) {\r\n return false;\r\n }\r\n\r\n return segments.join('') === globSegments.join('');\r\n }\r\n\r\n\r\n // Implicit root state that is always active\r\n root = registerState({\r\n name: '',\r\n url: '^',\r\n views: null,\r\n 'abstract': true\r\n });\r\n root.navigable = null;\r\n\r\n\r\n /**\r\n * @ngdoc function\r\n * @name ui.router.state.$stateProvider#decorator\r\n * @methodOf ui.router.state.$stateProvider\r\n *\r\n * @description\r\n * Allows you to extend (carefully) or override (at your own peril) the \r\n * `stateBuilder` object used internally by `$stateProvider`. This can be used \r\n * to add custom functionality to ui-router, for example inferring templateUrl \r\n * based on the state name.\r\n *\r\n * When passing only a name, it returns the current (original or decorated) builder\r\n * function that matches `name`.\r\n *\r\n * The builder functions that can be decorated are listed below. Though not all\r\n * necessarily have a good use case for decoration, that is up to you to decide.\r\n *\r\n * In addition, users can attach custom decorators, which will generate new \r\n * properties within the state's internal definition. There is currently no clear \r\n * use-case for this beyond accessing internal states (i.e. $state.$current), \r\n * however, expect this to become increasingly relevant as we introduce additional \r\n * meta-programming features.\r\n *\r\n * **Warning**: Decorators should not be interdependent because the order of \r\n * execution of the builder functions in non-deterministic. Builder functions \r\n * should only be dependent on the state definition object and super function.\r\n *\r\n *\r\n * Existing builder functions and current return values:\r\n *\r\n * - **parent** `{object}` - returns the parent state object.\r\n * - **data** `{object}` - returns state data, including any inherited data that is not\r\n * overridden by own values (if any).\r\n * - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}\r\n * or `null`.\r\n * - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is \r\n * navigable).\r\n * - **params** `{object}` - returns an array of state params that are ensured to \r\n * be a super-set of parent's params.\r\n * - **views** `{object}` - returns a views object where each key is an absolute view \r\n * name (i.e. \"viewName@stateName\") and each value is the config object \r\n * (template, controller) for the view. Even when you don't use the views object \r\n * explicitly on a state config, one is still created for you internally.\r\n * So by decorating this builder function you have access to decorating template \r\n * and controller properties.\r\n * - **ownParams** `{object}` - returns an array of params that belong to the state, \r\n * not including any params defined by ancestor states.\r\n * - **path** `{string}` - returns the full path from the root down to this state. \r\n * Needed for state activation.\r\n * - **includes** `{object}` - returns an object that includes every state that \r\n * would pass a `$state.includes()` test.\r\n *\r\n * @example\r\n *
    \r\n   * // Override the internal 'views' builder with a function that takes the state\r\n   * // definition, and a reference to the internal function being overridden:\r\n   * $stateProvider.decorator('views', function (state, parent) {\r\n   *   var result = {},\r\n   *       views = parent(state);\r\n   *\r\n   *   angular.forEach(views, function (config, name) {\r\n   *     var autoName = (state.name + '.' + name).replace('.', '/');\r\n   *     config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';\r\n   *     result[name] = config;\r\n   *   });\r\n   *   return result;\r\n   * });\r\n   *\r\n   * $stateProvider.state('home', {\r\n   *   views: {\r\n   *     'contact.list': { controller: 'ListController' },\r\n   *     'contact.item': { controller: 'ItemController' }\r\n   *   }\r\n   * });\r\n   *\r\n   * // ...\r\n   *\r\n   * $state.go('home');\r\n   * // Auto-populates list and item views with /partials/home/contact/list.html,\r\n   * // and /partials/home/contact/item.html, respectively.\r\n   * 
    \r\n *\r\n * @param {string} name The name of the builder function to decorate. \r\n * @param {object} func A function that is responsible for decorating the original \r\n * builder function. The function receives two parameters:\r\n *\r\n * - `{object}` - state - The state config object.\r\n * - `{object}` - super - The original builder function.\r\n *\r\n * @return {object} $stateProvider - $stateProvider instance\r\n */\r\n this.decorator = decorator;\r\n function decorator(name, func) {\r\n /*jshint validthis: true */\r\n if (isString(name) && !isDefined(func)) {\r\n return stateBuilder[name];\r\n }\r\n if (!isFunction(func) || !isString(name)) {\r\n return this;\r\n }\r\n if (stateBuilder[name] && !stateBuilder.$delegates[name]) {\r\n stateBuilder.$delegates[name] = stateBuilder[name];\r\n }\r\n stateBuilder[name] = func;\r\n return this;\r\n }\r\n\r\n /**\r\n * @ngdoc function\r\n * @name ui.router.state.$stateProvider#state\r\n * @methodOf ui.router.state.$stateProvider\r\n *\r\n * @description\r\n * Registers a state configuration under a given state name. The stateConfig object\r\n * has the following acceptable properties.\r\n *\r\n * @param {string} name A unique state name, e.g. \"home\", \"about\", \"contacts\".\r\n * To create a parent/child state use a dot, e.g. \"about.sales\", \"home.newest\".\r\n * @param {object} stateConfig State configuration object.\r\n * @param {string|function=} stateConfig.template\r\n * \r\n * html template as a string or a function that returns\r\n * an html template as a string which should be used by the uiView directives. This property \r\n * takes precedence over templateUrl.\r\n * \r\n * If `template` is a function, it will be called with the following parameters:\r\n *\r\n * - {array.<object>} - state parameters extracted from the current $location.path() by\r\n * applying the current state\r\n *\r\n *
    template:\r\n   *   \"

    inline template definition

    \" +\r\n * \"
    \"
    \r\n *
    template: function(params) {\r\n   *       return \"

    generated template

    \"; }
    \r\n * \r\n *\r\n * @param {string|function=} stateConfig.templateUrl\r\n * \r\n *\r\n * path or function that returns a path to an html\r\n * template that should be used by uiView.\r\n * \r\n * If `templateUrl` is a function, it will be called with the following parameters:\r\n *\r\n * - {array.<object>} - state parameters extracted from the current $location.path() by \r\n * applying the current state\r\n *\r\n *
    templateUrl: \"home.html\"
    \r\n *
    templateUrl: function(params) {\r\n   *     return myTemplates[params.pageId]; }
    \r\n *\r\n * @param {function=} stateConfig.templateProvider\r\n * \r\n * Provider function that returns HTML content string.\r\n *
     templateProvider:\r\n   *       function(MyTemplateService, params) {\r\n   *         return MyTemplateService.getTemplate(params.pageId);\r\n   *       }
    \r\n *\r\n * @param {string|function=} stateConfig.controller\r\n * \r\n *\r\n * Controller fn that should be associated with newly\r\n * related scope or the name of a registered controller if passed as a string.\r\n * Optionally, the ControllerAs may be declared here.\r\n *
    controller: \"MyRegisteredController\"
    \r\n *
    controller:\r\n   *     \"MyRegisteredController as fooCtrl\"}
    \r\n *
    controller: function($scope, MyService) {\r\n   *     $scope.data = MyService.getData(); }
    \r\n *\r\n * @param {function=} stateConfig.controllerProvider\r\n * \r\n *\r\n * Injectable provider function that returns the actual controller or string.\r\n *
    controllerProvider:\r\n   *   function(MyResolveData) {\r\n   *     if (MyResolveData.foo)\r\n   *       return \"FooCtrl\"\r\n   *     else if (MyResolveData.bar)\r\n   *       return \"BarCtrl\";\r\n   *     else return function($scope) {\r\n   *       $scope.baz = \"Qux\";\r\n   *     }\r\n   *   }
    \r\n *\r\n * @param {string=} stateConfig.controllerAs\r\n * \r\n * \r\n * A controller alias name. If present the controller will be\r\n * published to scope under the controllerAs name.\r\n *
    controllerAs: \"myCtrl\"
    \r\n *\r\n * @param {string|object=} stateConfig.parent\r\n * \r\n * Optionally specifies the parent state of this state.\r\n *\r\n *
    parent: 'parentState'
    \r\n *
    parent: parentState // JS variable
    \r\n *\r\n * @param {object=} stateConfig.resolve\r\n * \r\n *\r\n * An optional map<string, function> of dependencies which\r\n * should be injected into the controller. If any of these dependencies are promises, \r\n * the router will wait for them all to be resolved before the controller is instantiated.\r\n * If all the promises are resolved successfully, the $stateChangeSuccess event is fired\r\n * and the values of the resolved promises are injected into any controllers that reference them.\r\n * If any of the promises are rejected the $stateChangeError event is fired.\r\n *\r\n * The map object is:\r\n * \r\n * - key - {string}: name of dependency to be injected into controller\r\n * - factory - {string|function}: If string then it is alias for service. Otherwise if function, \r\n * it is injected and return value it treated as dependency. If result is a promise, it is \r\n * resolved before its value is injected into controller.\r\n *\r\n *
    resolve: {\r\n   *     myResolve1:\r\n   *       function($http, $stateParams) {\r\n   *         return $http.get(\"/api/foos/\"+stateParams.fooID);\r\n   *       }\r\n   *     }
    \r\n *\r\n * @param {string=} stateConfig.url\r\n * \r\n *\r\n * A url fragment with optional parameters. When a state is navigated or\r\n * transitioned to, the `$stateParams` service will be populated with any \r\n * parameters that were passed.\r\n *\r\n * (See {@link ui.router.util.type:UrlMatcher UrlMatcher} `UrlMatcher`} for\r\n * more details on acceptable patterns )\r\n *\r\n * examples:\r\n *
    url: \"/home\"\r\n   * url: \"/users/:userid\"\r\n   * url: \"/books/{bookid:[a-zA-Z_-]}\"\r\n   * url: \"/books/{categoryid:int}\"\r\n   * url: \"/books/{publishername:string}/{categoryid:int}\"\r\n   * url: \"/messages?before&after\"\r\n   * url: \"/messages?{before:date}&{after:date}\"\r\n   * url: \"/messages/:mailboxid?{before:date}&{after:date}\"\r\n   * 
    \r\n *\r\n * @param {object=} stateConfig.views\r\n * \r\n * an optional map<string, object> which defined multiple views, or targets views\r\n * manually/explicitly.\r\n *\r\n * Examples:\r\n *\r\n * Targets three named `ui-view`s in the parent state's template\r\n *
    views: {\r\n   *     header: {\r\n   *       controller: \"headerCtrl\",\r\n   *       templateUrl: \"header.html\"\r\n   *     }, body: {\r\n   *       controller: \"bodyCtrl\",\r\n   *       templateUrl: \"body.html\"\r\n   *     }, footer: {\r\n   *       controller: \"footCtrl\",\r\n   *       templateUrl: \"footer.html\"\r\n   *     }\r\n   *   }
    \r\n *\r\n * Targets named `ui-view=\"header\"` from grandparent state 'top''s template, and named `ui-view=\"body\" from parent state's template.\r\n *
    views: {\r\n   *     'header@top': {\r\n   *       controller: \"msgHeaderCtrl\",\r\n   *       templateUrl: \"msgHeader.html\"\r\n   *     }, 'body': {\r\n   *       controller: \"messagesCtrl\",\r\n   *       templateUrl: \"messages.html\"\r\n   *     }\r\n   *   }
    \r\n *\r\n * @param {boolean=} [stateConfig.abstract=false]\r\n * \r\n * An abstract state will never be directly activated,\r\n * but can provide inherited properties to its common children states.\r\n *
    abstract: true
    \r\n *\r\n * @param {function=} stateConfig.onEnter\r\n * \r\n *\r\n * Callback function for when a state is entered. Good way\r\n * to trigger an action or dispatch an event, such as opening a dialog.\r\n * If minifying your scripts, make sure to explictly annotate this function,\r\n * because it won't be automatically annotated by your build tools.\r\n *\r\n *
    onEnter: function(MyService, $stateParams) {\r\n   *     MyService.foo($stateParams.myParam);\r\n   * }
    \r\n *\r\n * @param {function=} stateConfig.onExit\r\n * \r\n *\r\n * Callback function for when a state is exited. Good way to\r\n * trigger an action or dispatch an event, such as opening a dialog.\r\n * If minifying your scripts, make sure to explictly annotate this function,\r\n * because it won't be automatically annotated by your build tools.\r\n *\r\n *
    onExit: function(MyService, $stateParams) {\r\n   *     MyService.cleanup($stateParams.myParam);\r\n   * }
    \r\n *\r\n * @param {boolean=} [stateConfig.reloadOnSearch=true]\r\n * \r\n *\r\n * If `false`, will not retrigger the same state\r\n * just because a search/query parameter has changed (via $location.search() or $location.hash()). \r\n * Useful for when you'd like to modify $location.search() without triggering a reload.\r\n *
    reloadOnSearch: false
    \r\n *\r\n * @param {object=} stateConfig.data\r\n * \r\n *\r\n * Arbitrary data object, useful for custom configuration. The parent state's `data` is\r\n * prototypally inherited. In other words, adding a data property to a state adds it to\r\n * the entire subtree via prototypal inheritance.\r\n *\r\n *
    data: {\r\n   *     requiredRole: 'foo'\r\n   * } 
    \r\n *\r\n * @param {object=} stateConfig.params\r\n * \r\n *\r\n * A map which optionally configures parameters declared in the `url`, or\r\n * defines additional non-url parameters. For each parameter being\r\n * configured, add a configuration object keyed to the name of the parameter.\r\n *\r\n * Each parameter configuration object may contain the following properties:\r\n *\r\n * - ** value ** - {object|function=}: specifies the default value for this\r\n * parameter. This implicitly sets this parameter as optional.\r\n *\r\n * When UI-Router routes to a state and no value is\r\n * specified for this parameter in the URL or transition, the\r\n * default value will be used instead. If `value` is a function,\r\n * it will be injected and invoked, and the return value used.\r\n *\r\n * *Note*: `undefined` is treated as \"no default value\" while `null`\r\n * is treated as \"the default value is `null`\".\r\n *\r\n * *Shorthand*: If you only need to configure the default value of the\r\n * parameter, you may use a shorthand syntax. In the **`params`**\r\n * map, instead mapping the param name to a full parameter configuration\r\n * object, simply set map it to the default parameter value, e.g.:\r\n *\r\n *
    // define a parameter's default value\r\n   * params: {\r\n   *     param1: { value: \"defaultValue\" }\r\n   * }\r\n   * // shorthand default values\r\n   * params: {\r\n   *     param1: \"defaultValue\",\r\n   *     param2: \"param2Default\"\r\n   * }
    \r\n *\r\n * - ** array ** - {boolean=}: *(default: false)* If true, the param value will be\r\n * treated as an array of values. If you specified a Type, the value will be\r\n * treated as an array of the specified Type. Note: query parameter values\r\n * default to a special `\"auto\"` mode.\r\n *\r\n * For query parameters in `\"auto\"` mode, if multiple values for a single parameter\r\n * are present in the URL (e.g.: `/foo?bar=1&bar=2&bar=3`) then the values\r\n * are mapped to an array (e.g.: `{ foo: [ '1', '2', '3' ] }`). However, if\r\n * only one value is present (e.g.: `/foo?bar=1`) then the value is treated as single\r\n * value (e.g.: `{ foo: '1' }`).\r\n *\r\n *
    params: {\r\n   *     param1: { array: true }\r\n   * }
    \r\n *\r\n * - ** squash ** - {bool|string=}: `squash` configures how a default parameter value is represented in the URL when\r\n * the current parameter value is the same as the default value. If `squash` is not set, it uses the\r\n * configured default squash policy.\r\n * (See {@link ui.router.util.$urlMatcherFactory#methods_defaultSquashPolicy `defaultSquashPolicy()`})\r\n *\r\n * There are three squash settings:\r\n *\r\n * - false: The parameter's default value is not squashed. It is encoded and included in the URL\r\n * - true: The parameter's default value is omitted from the URL. If the parameter is preceeded and followed\r\n * by slashes in the state's `url` declaration, then one of those slashes are omitted.\r\n * This can allow for cleaner looking URLs.\r\n * - `\"\"`: The parameter's default value is replaced with an arbitrary placeholder of your choice.\r\n *\r\n *
    params: {\r\n   *     param1: {\r\n   *       value: \"defaultId\",\r\n   *       squash: true\r\n   * } }\r\n   * // squash \"defaultValue\" to \"~\"\r\n   * params: {\r\n   *     param1: {\r\n   *       value: \"defaultValue\",\r\n   *       squash: \"~\"\r\n   * } }\r\n   * 
    \r\n *\r\n *\r\n * @example\r\n *
    \r\n   * // Some state name examples\r\n   *\r\n   * // stateName can be a single top-level name (must be unique).\r\n   * $stateProvider.state(\"home\", {});\r\n   *\r\n   * // Or it can be a nested state name. This state is a child of the\r\n   * // above \"home\" state.\r\n   * $stateProvider.state(\"home.newest\", {});\r\n   *\r\n   * // Nest states as deeply as needed.\r\n   * $stateProvider.state(\"home.newest.abc.xyz.inception\", {});\r\n   *\r\n   * // state() returns $stateProvider, so you can chain state declarations.\r\n   * $stateProvider\r\n   *   .state(\"home\", {})\r\n   *   .state(\"about\", {})\r\n   *   .state(\"contacts\", {});\r\n   * 
    \r\n *\r\n */\r\n this.state = state;\r\n function state(name, definition) {\r\n /*jshint validthis: true */\r\n if (isObject(name)) definition = name;\r\n else definition.name = name;\r\n registerState(definition);\r\n return this;\r\n }\r\n\r\n /**\r\n * @ngdoc object\r\n * @name ui.router.state.$state\r\n *\r\n * @requires $rootScope\r\n * @requires $q\r\n * @requires ui.router.state.$view\r\n * @requires $injector\r\n * @requires ui.router.util.$resolve\r\n * @requires ui.router.state.$stateParams\r\n * @requires ui.router.router.$urlRouter\r\n *\r\n * @property {object} params A param object, e.g. {sectionId: section.id)}, that \r\n * you'd like to test against the current active state.\r\n * @property {object} current A reference to the state's config object. However \r\n * you passed it in. Useful for accessing custom data.\r\n * @property {object} transition Currently pending transition. A promise that'll \r\n * resolve or reject.\r\n *\r\n * @description\r\n * `$state` service is responsible for representing states as well as transitioning\r\n * between them. It also provides interfaces to ask for current state or even states\r\n * you're coming from.\r\n */\r\n this.$get = $get;\r\n $get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$urlRouter', '$location', '$urlMatcherFactory'];\r\n function $get( $rootScope, $q, $view, $injector, $resolve, $stateParams, $urlRouter, $location, $urlMatcherFactory) {\r\n\r\n var TransitionSuperseded = $q.reject(new Error('transition superseded'));\r\n var TransitionPrevented = $q.reject(new Error('transition prevented'));\r\n var TransitionAborted = $q.reject(new Error('transition aborted'));\r\n var TransitionFailed = $q.reject(new Error('transition failed'));\r\n\r\n // Handles the case where a state which is the target of a transition is not found, and the user\r\n // can optionally retry or defer the transition\r\n function handleRedirect(redirect, state, params, options) {\r\n /**\r\n * @ngdoc event\r\n * @name ui.router.state.$state#$stateNotFound\r\n * @eventOf ui.router.state.$state\r\n * @eventType broadcast on root scope\r\n * @description\r\n * Fired when a requested state **cannot be found** using the provided state name during transition.\r\n * The event is broadcast allowing any handlers a single chance to deal with the error (usually by\r\n * lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler,\r\n * you can see its three properties in the example. You can use `event.preventDefault()` to abort the\r\n * transition and the promise returned from `go` will be rejected with a `'transition aborted'` value.\r\n *\r\n * @param {Object} event Event object.\r\n * @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties.\r\n * @param {State} fromState Current state object.\r\n * @param {Object} fromParams Current state params.\r\n *\r\n * @example\r\n *\r\n *
    \r\n       * // somewhere, assume lazy.state has not been defined\r\n       * $state.go(\"lazy.state\", {a:1, b:2}, {inherit:false});\r\n       *\r\n       * // somewhere else\r\n       * $scope.$on('$stateNotFound',\r\n       * function(event, unfoundState, fromState, fromParams){\r\n       *     console.log(unfoundState.to); // \"lazy.state\"\r\n       *     console.log(unfoundState.toParams); // {a:1, b:2}\r\n       *     console.log(unfoundState.options); // {inherit:false} + default options\r\n       * })\r\n       * 
    \r\n */\r\n var evt = $rootScope.$broadcast('$stateNotFound', redirect, state, params);\r\n\r\n if (evt.defaultPrevented) {\r\n $urlRouter.update();\r\n return TransitionAborted;\r\n }\r\n\r\n if (!evt.retry) {\r\n return null;\r\n }\r\n\r\n // Allow the handler to return a promise to defer state lookup retry\r\n if (options.$retry) {\r\n $urlRouter.update();\r\n return TransitionFailed;\r\n }\r\n var retryTransition = $state.transition = $q.when(evt.retry);\r\n\r\n retryTransition.then(function() {\r\n if (retryTransition !== $state.transition) return TransitionSuperseded;\r\n redirect.options.$retry = true;\r\n return $state.transitionTo(redirect.to, redirect.toParams, redirect.options);\r\n }, function() {\r\n return TransitionAborted;\r\n });\r\n $urlRouter.update();\r\n\r\n return retryTransition;\r\n }\r\n\r\n root.locals = { resolve: null, globals: { $stateParams: {} } };\r\n\r\n $state = {\r\n params: {},\r\n current: root.self,\r\n $current: root,\r\n transition: null\r\n };\r\n\r\n /**\r\n * @ngdoc function\r\n * @name ui.router.state.$state#reload\r\n * @methodOf ui.router.state.$state\r\n *\r\n * @description\r\n * A method that force reloads the current state. All resolves are re-resolved,\r\n * controllers reinstantiated, and events re-fired.\r\n *\r\n * @example\r\n *
    \r\n     * var app angular.module('app', ['ui.router']);\r\n     *\r\n     * app.controller('ctrl', function ($scope, $state) {\r\n     *   $scope.reload = function(){\r\n     *     $state.reload();\r\n     *   }\r\n     * });\r\n     * 
    \r\n *\r\n * `reload()` is just an alias for:\r\n *
    \r\n     * $state.transitionTo($state.current, $stateParams, { \r\n     *   reload: true, inherit: false, notify: true\r\n     * });\r\n     * 
    \r\n *\r\n * @param {string=|object=} state - A state name or a state object, which is the root of the resolves to be re-resolved.\r\n * @example\r\n *
    \r\n     * //assuming app application consists of 3 states: 'contacts', 'contacts.detail', 'contacts.detail.item' \r\n     * //and current state is 'contacts.detail.item'\r\n     * var app angular.module('app', ['ui.router']);\r\n     *\r\n     * app.controller('ctrl', function ($scope, $state) {\r\n     *   $scope.reload = function(){\r\n     *     //will reload 'contact.detail' and 'contact.detail.item' states\r\n     *     $state.reload('contact.detail');\r\n     *   }\r\n     * });\r\n     * 
    \r\n *\r\n * `reload()` is just an alias for:\r\n *
    \r\n     * $state.transitionTo($state.current, $stateParams, { \r\n     *   reload: true, inherit: false, notify: true\r\n     * });\r\n     * 
    \r\n\r\n * @returns {promise} A promise representing the state of the new transition. See\r\n * {@link ui.router.state.$state#methods_go $state.go}.\r\n */\r\n $state.reload = function reload(state) {\r\n return $state.transitionTo($state.current, $stateParams, { reload: state || true, inherit: false, notify: true});\r\n };\r\n\r\n /**\r\n * @ngdoc function\r\n * @name ui.router.state.$state#go\r\n * @methodOf ui.router.state.$state\r\n *\r\n * @description\r\n * Convenience method for transitioning to a new state. `$state.go` calls \r\n * `$state.transitionTo` internally but automatically sets options to \r\n * `{ location: true, inherit: true, relative: $state.$current, notify: true }`. \r\n * This allows you to easily use an absolute or relative to path and specify \r\n * only the parameters you'd like to update (while letting unspecified parameters \r\n * inherit from the currently active ancestor states).\r\n *\r\n * @example\r\n *
    \r\n     * var app = angular.module('app', ['ui.router']);\r\n     *\r\n     * app.controller('ctrl', function ($scope, $state) {\r\n     *   $scope.changeState = function () {\r\n     *     $state.go('contact.detail');\r\n     *   };\r\n     * });\r\n     * 
    \r\n * \r\n *\r\n * @param {string} to Absolute state name or relative state path. Some examples:\r\n *\r\n * - `$state.go('contact.detail')` - will go to the `contact.detail` state\r\n * - `$state.go('^')` - will go to a parent state\r\n * - `$state.go('^.sibling')` - will go to a sibling state\r\n * - `$state.go('.child.grandchild')` - will go to grandchild state\r\n *\r\n * @param {object=} params A map of the parameters that will be sent to the state, \r\n * will populate $stateParams. Any parameters that are not specified will be inherited from currently \r\n * defined parameters. This allows, for example, going to a sibling state that shares parameters\r\n * specified in a parent state. Parameter inheritance only works between common ancestor states, I.e.\r\n * transitioning to a sibling will get you the parameters for all parents, transitioning to a child\r\n * will get you all current parameters, etc.\r\n * @param {object=} options Options object. The options are:\r\n *\r\n * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`\r\n * will not. If string, must be `\"replace\"`, which will update url and also replace last history record.\r\n * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.\r\n * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'), \r\n * defines which state to be relative from.\r\n * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.\r\n * - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params \r\n * have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd\r\n * use this when you want to force a reload when *everything* is the same, including search params.\r\n *\r\n * @returns {promise} A promise representing the state of the new transition.\r\n *\r\n * Possible success values:\r\n *\r\n * - $state.current\r\n *\r\n *
    Possible rejection values:\r\n *\r\n * - 'transition superseded' - when a newer transition has been started after this one\r\n * - 'transition prevented' - when `event.preventDefault()` has been called in a `$stateChangeStart` listener\r\n * - 'transition aborted' - when `event.preventDefault()` has been called in a `$stateNotFound` listener or\r\n * when a `$stateNotFound` `event.retry` promise errors.\r\n * - 'transition failed' - when a state has been unsuccessfully found after 2 tries.\r\n * - *resolve error* - when an error has occurred with a `resolve`\r\n *\r\n */\r\n $state.go = function go(to, params, options) {\r\n return $state.transitionTo(to, params, extend({ inherit: true, relative: $state.$current }, options));\r\n };\r\n\r\n /**\r\n * @ngdoc function\r\n * @name ui.router.state.$state#transitionTo\r\n * @methodOf ui.router.state.$state\r\n *\r\n * @description\r\n * Low-level method for transitioning to a new state. {@link ui.router.state.$state#methods_go $state.go}\r\n * uses `transitionTo` internally. `$state.go` is recommended in most situations.\r\n *\r\n * @example\r\n *
    \r\n     * var app = angular.module('app', ['ui.router']);\r\n     *\r\n     * app.controller('ctrl', function ($scope, $state) {\r\n     *   $scope.changeState = function () {\r\n     *     $state.transitionTo('contact.detail');\r\n     *   };\r\n     * });\r\n     * 
    \r\n *\r\n * @param {string} to State name.\r\n * @param {object=} toParams A map of the parameters that will be sent to the state,\r\n * will populate $stateParams.\r\n * @param {object=} options Options object. The options are:\r\n *\r\n * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`\r\n * will not. If string, must be `\"replace\"`, which will update url and also replace last history record.\r\n * - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url.\r\n * - **`relative`** - {object=}, When transitioning with relative path (e.g '^'), \r\n * defines which state to be relative from.\r\n * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.\r\n * - **`reload`** (v0.2.5) - {boolean=false|string=|object=}, If `true` will force transition even if the state or params \r\n * have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd\r\n * use this when you want to force a reload when *everything* is the same, including search params.\r\n * if String, then will reload the state with the name given in reload, and any children.\r\n * if Object, then a stateObj is expected, will reload the state found in stateObj, and any children.\r\n *\r\n * @returns {promise} A promise representing the state of the new transition. See\r\n * {@link ui.router.state.$state#methods_go $state.go}.\r\n */\r\n $state.transitionTo = function transitionTo(to, toParams, options) {\r\n toParams = toParams || {};\r\n options = extend({\r\n location: true, inherit: false, relative: null, notify: true, reload: false, $retry: false\r\n }, options || {});\r\n\r\n var from = $state.$current, fromParams = $state.params, fromPath = from.path;\r\n var evt, toState = findState(to, options.relative);\r\n\r\n // Store the hash param for later (since it will be stripped out by various methods)\r\n var hash = toParams['#'];\r\n\r\n if (!isDefined(toState)) {\r\n var redirect = { to: to, toParams: toParams, options: options };\r\n var redirectResult = handleRedirect(redirect, from.self, fromParams, options);\r\n\r\n if (redirectResult) {\r\n return redirectResult;\r\n }\r\n\r\n // Always retry once if the $stateNotFound was not prevented\r\n // (handles either redirect changed or state lazy-definition)\r\n to = redirect.to;\r\n toParams = redirect.toParams;\r\n options = redirect.options;\r\n toState = findState(to, options.relative);\r\n\r\n if (!isDefined(toState)) {\r\n if (!options.relative) throw new Error(\"No such state '\" + to + \"'\");\r\n throw new Error(\"Could not resolve '\" + to + \"' from state '\" + options.relative + \"'\");\r\n }\r\n }\r\n if (toState[abstractKey]) throw new Error(\"Cannot transition to abstract state '\" + to + \"'\");\r\n if (options.inherit) toParams = inheritParams($stateParams, toParams || {}, $state.$current, toState);\r\n if (!toState.params.$$validates(toParams)) return TransitionFailed;\r\n\r\n toParams = toState.params.$$values(toParams);\r\n to = toState;\r\n\r\n var toPath = to.path;\r\n\r\n // Starting from the root of the path, keep all levels that haven't changed\r\n var keep = 0, state = toPath[keep], locals = root.locals, toLocals = [];\r\n\r\n if (!options.reload) {\r\n while (state && state === fromPath[keep] && state.ownParams.$$equals(toParams, fromParams)) {\r\n locals = toLocals[keep] = state.locals;\r\n keep++;\r\n state = toPath[keep];\r\n }\r\n } else if (isString(options.reload) || isObject(options.reload)) {\r\n if (isObject(options.reload) && !options.reload.name) {\r\n throw new Error('Invalid reload state object');\r\n }\r\n \r\n var reloadState = options.reload === true ? fromPath[0] : findState(options.reload);\r\n if (options.reload && !reloadState) {\r\n throw new Error(\"No such reload state '\" + (isString(options.reload) ? options.reload : options.reload.name) + \"'\");\r\n }\r\n\r\n while (state && state === fromPath[keep] && state !== reloadState) {\r\n locals = toLocals[keep] = state.locals;\r\n keep++;\r\n state = toPath[keep];\r\n }\r\n }\r\n\r\n // If we're going to the same state and all locals are kept, we've got nothing to do.\r\n // But clear 'transition', as we still want to cancel any other pending transitions.\r\n // TODO: We may not want to bump 'transition' if we're called from a location change\r\n // that we've initiated ourselves, because we might accidentally abort a legitimate\r\n // transition initiated from code?\r\n if (shouldSkipReload(to, toParams, from, fromParams, locals, options)) {\r\n if (hash) toParams['#'] = hash;\r\n $state.params = toParams;\r\n copy($state.params, $stateParams);\r\n if (options.location && to.navigable && to.navigable.url) {\r\n $urlRouter.push(to.navigable.url, toParams, {\r\n $$avoidResync: true, replace: options.location === 'replace'\r\n });\r\n $urlRouter.update(true);\r\n }\r\n $state.transition = null;\r\n return $q.when($state.current);\r\n }\r\n\r\n // Filter parameters before we pass them to event handlers etc.\r\n toParams = filterByKeys(to.params.$$keys(), toParams || {});\r\n\r\n // Broadcast start event and cancel the transition if requested\r\n if (options.notify) {\r\n /**\r\n * @ngdoc event\r\n * @name ui.router.state.$state#$stateChangeStart\r\n * @eventOf ui.router.state.$state\r\n * @eventType broadcast on root scope\r\n * @description\r\n * Fired when the state transition **begins**. You can use `event.preventDefault()`\r\n * to prevent the transition from happening and then the transition promise will be\r\n * rejected with a `'transition prevented'` value.\r\n *\r\n * @param {Object} event Event object.\r\n * @param {State} toState The state being transitioned to.\r\n * @param {Object} toParams The params supplied to the `toState`.\r\n * @param {State} fromState The current state, pre-transition.\r\n * @param {Object} fromParams The params supplied to the `fromState`.\r\n *\r\n * @example\r\n *\r\n *
    \r\n         * $rootScope.$on('$stateChangeStart',\r\n         * function(event, toState, toParams, fromState, fromParams){\r\n         *     event.preventDefault();\r\n         *     // transitionTo() promise will be rejected with\r\n         *     // a 'transition prevented' error\r\n         * })\r\n         * 
    \r\n */\r\n if ($rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams).defaultPrevented) {\r\n $rootScope.$broadcast('$stateChangeCancel', to.self, toParams, from.self, fromParams);\r\n $urlRouter.update();\r\n return TransitionPrevented;\r\n }\r\n }\r\n\r\n // Resolve locals for the remaining states, but don't update any global state just\r\n // yet -- if anything fails to resolve the current state needs to remain untouched.\r\n // We also set up an inheritance chain for the locals here. This allows the view directive\r\n // to quickly look up the correct definition for each view in the current state. Even\r\n // though we create the locals object itself outside resolveState(), it is initially\r\n // empty and gets filled asynchronously. We need to keep track of the promise for the\r\n // (fully resolved) current locals, and pass this down the chain.\r\n var resolved = $q.when(locals);\r\n\r\n for (var l = keep; l < toPath.length; l++, state = toPath[l]) {\r\n locals = toLocals[l] = inherit(locals);\r\n resolved = resolveState(state, toParams, state === to, resolved, locals, options);\r\n }\r\n\r\n // Once everything is resolved, we are ready to perform the actual transition\r\n // and return a promise for the new state. We also keep track of what the\r\n // current promise is, so that we can detect overlapping transitions and\r\n // keep only the outcome of the last transition.\r\n var transition = $state.transition = resolved.then(function () {\r\n var l, entering, exiting;\r\n\r\n if ($state.transition !== transition) return TransitionSuperseded;\r\n\r\n // Exit 'from' states not kept\r\n for (l = fromPath.length - 1; l >= keep; l--) {\r\n exiting = fromPath[l];\r\n if (exiting.self.onExit) {\r\n $injector.invoke(exiting.self.onExit, exiting.self, exiting.locals.globals);\r\n }\r\n exiting.locals = null;\r\n }\r\n\r\n // Enter 'to' states not kept\r\n for (l = keep; l < toPath.length; l++) {\r\n entering = toPath[l];\r\n entering.locals = toLocals[l];\r\n if (entering.self.onEnter) {\r\n $injector.invoke(entering.self.onEnter, entering.self, entering.locals.globals);\r\n }\r\n }\r\n\r\n // Re-add the saved hash before we start returning things\r\n if (hash) toParams['#'] = hash;\r\n\r\n // Run it again, to catch any transitions in callbacks\r\n if ($state.transition !== transition) return TransitionSuperseded;\r\n\r\n // Update globals in $state\r\n $state.$current = to;\r\n $state.current = to.self;\r\n $state.params = toParams;\r\n copy($state.params, $stateParams);\r\n $state.transition = null;\r\n\r\n if (options.location && to.navigable) {\r\n $urlRouter.push(to.navigable.url, to.navigable.locals.globals.$stateParams, {\r\n $$avoidResync: true, replace: options.location === 'replace'\r\n });\r\n }\r\n\r\n if (options.notify) {\r\n /**\r\n * @ngdoc event\r\n * @name ui.router.state.$state#$stateChangeSuccess\r\n * @eventOf ui.router.state.$state\r\n * @eventType broadcast on root scope\r\n * @description\r\n * Fired once the state transition is **complete**.\r\n *\r\n * @param {Object} event Event object.\r\n * @param {State} toState The state being transitioned to.\r\n * @param {Object} toParams The params supplied to the `toState`.\r\n * @param {State} fromState The current state, pre-transition.\r\n * @param {Object} fromParams The params supplied to the `fromState`.\r\n */\r\n $rootScope.$broadcast('$stateChangeSuccess', to.self, toParams, from.self, fromParams);\r\n }\r\n $urlRouter.update(true);\r\n\r\n return $state.current;\r\n }, function (error) {\r\n if ($state.transition !== transition) return TransitionSuperseded;\r\n\r\n $state.transition = null;\r\n /**\r\n * @ngdoc event\r\n * @name ui.router.state.$state#$stateChangeError\r\n * @eventOf ui.router.state.$state\r\n * @eventType broadcast on root scope\r\n * @description\r\n * Fired when an **error occurs** during transition. It's important to note that if you\r\n * have any errors in your resolve functions (javascript errors, non-existent services, etc)\r\n * they will not throw traditionally. You must listen for this $stateChangeError event to\r\n * catch **ALL** errors.\r\n *\r\n * @param {Object} event Event object.\r\n * @param {State} toState The state being transitioned to.\r\n * @param {Object} toParams The params supplied to the `toState`.\r\n * @param {State} fromState The current state, pre-transition.\r\n * @param {Object} fromParams The params supplied to the `fromState`.\r\n * @param {Error} error The resolve error object.\r\n */\r\n evt = $rootScope.$broadcast('$stateChangeError', to.self, toParams, from.self, fromParams, error);\r\n\r\n if (!evt.defaultPrevented) {\r\n $urlRouter.update();\r\n }\r\n\r\n return $q.reject(error);\r\n });\r\n\r\n return transition;\r\n };\r\n\r\n /**\r\n * @ngdoc function\r\n * @name ui.router.state.$state#is\r\n * @methodOf ui.router.state.$state\r\n *\r\n * @description\r\n * Similar to {@link ui.router.state.$state#methods_includes $state.includes},\r\n * but only checks for the full state name. If params is supplied then it will be\r\n * tested for strict equality against the current active params object, so all params\r\n * must match with none missing and no extras.\r\n *\r\n * @example\r\n *
    \r\n     * $state.$current.name = 'contacts.details.item';\r\n     *\r\n     * // absolute name\r\n     * $state.is('contact.details.item'); // returns true\r\n     * $state.is(contactDetailItemStateObject); // returns true\r\n     *\r\n     * // relative name (. and ^), typically from a template\r\n     * // E.g. from the 'contacts.details' template\r\n     * 
    Item
    \r\n *
    \r\n *\r\n * @param {string|object} stateOrName The state name (absolute or relative) or state object you'd like to check.\r\n * @param {object=} params A param object, e.g. `{sectionId: section.id}`, that you'd like\r\n * to test against the current active state.\r\n * @param {object=} options An options object. The options are:\r\n *\r\n * - **`relative`** - {string|object} - If `stateOrName` is a relative state name and `options.relative` is set, .is will\r\n * test relative to `options.relative` state (or name).\r\n *\r\n * @returns {boolean} Returns true if it is the state.\r\n */\r\n $state.is = function is(stateOrName, params, options) {\r\n options = extend({ relative: $state.$current }, options || {});\r\n var state = findState(stateOrName, options.relative);\r\n\r\n if (!isDefined(state)) { return undefined; }\r\n if ($state.$current !== state) { return false; }\r\n return params ? equalForKeys(state.params.$$values(params), $stateParams) : true;\r\n };\r\n\r\n /**\r\n * @ngdoc function\r\n * @name ui.router.state.$state#includes\r\n * @methodOf ui.router.state.$state\r\n *\r\n * @description\r\n * A method to determine if the current active state is equal to or is the child of the\r\n * state stateName. If any params are passed then they will be tested for a match as well.\r\n * Not all the parameters need to be passed, just the ones you'd like to test for equality.\r\n *\r\n * @example\r\n * Partial and relative names\r\n *
    \r\n     * $state.$current.name = 'contacts.details.item';\r\n     *\r\n     * // Using partial names\r\n     * $state.includes(\"contacts\"); // returns true\r\n     * $state.includes(\"contacts.details\"); // returns true\r\n     * $state.includes(\"contacts.details.item\"); // returns true\r\n     * $state.includes(\"contacts.list\"); // returns false\r\n     * $state.includes(\"about\"); // returns false\r\n     *\r\n     * // Using relative names (. and ^), typically from a template\r\n     * // E.g. from the 'contacts.details' template\r\n     * 
    Item
    \r\n *
    \r\n *\r\n * Basic globbing patterns\r\n *
    \r\n     * $state.$current.name = 'contacts.details.item.url';\r\n     *\r\n     * $state.includes(\"*.details.*.*\"); // returns true\r\n     * $state.includes(\"*.details.**\"); // returns true\r\n     * $state.includes(\"**.item.**\"); // returns true\r\n     * $state.includes(\"*.details.item.url\"); // returns true\r\n     * $state.includes(\"*.details.*.url\"); // returns true\r\n     * $state.includes(\"*.details.*\"); // returns false\r\n     * $state.includes(\"item.**\"); // returns false\r\n     * 
    \r\n *\r\n * @param {string} stateOrName A partial name, relative name, or glob pattern\r\n * to be searched for within the current state name.\r\n * @param {object=} params A param object, e.g. `{sectionId: section.id}`,\r\n * that you'd like to test against the current active state.\r\n * @param {object=} options An options object. The options are:\r\n *\r\n * - **`relative`** - {string|object=} - If `stateOrName` is a relative state reference and `options.relative` is set,\r\n * .includes will test relative to `options.relative` state (or name).\r\n *\r\n * @returns {boolean} Returns true if it does include the state\r\n */\r\n $state.includes = function includes(stateOrName, params, options) {\r\n options = extend({ relative: $state.$current }, options || {});\r\n if (isString(stateOrName) && isGlob(stateOrName)) {\r\n if (!doesStateMatchGlob(stateOrName)) {\r\n return false;\r\n }\r\n stateOrName = $state.$current.name;\r\n }\r\n\r\n var state = findState(stateOrName, options.relative);\r\n if (!isDefined(state)) { return undefined; }\r\n if (!isDefined($state.$current.includes[state.name])) { return false; }\r\n return params ? equalForKeys(state.params.$$values(params), $stateParams, objectKeys(params)) : true;\r\n };\r\n\r\n\r\n /**\r\n * @ngdoc function\r\n * @name ui.router.state.$state#href\r\n * @methodOf ui.router.state.$state\r\n *\r\n * @description\r\n * A url generation method that returns the compiled url for the given state populated with the given params.\r\n *\r\n * @example\r\n *
    \r\n     * expect($state.href(\"about.person\", { person: \"bob\" })).toEqual(\"/about/bob\");\r\n     * 
    \r\n *\r\n * @param {string|object} stateOrName The state name or state object you'd like to generate a url from.\r\n * @param {object=} params An object of parameter values to fill the state's required parameters.\r\n * @param {object=} options Options object. The options are:\r\n *\r\n * - **`lossy`** - {boolean=true} - If true, and if there is no url associated with the state provided in the\r\n * first parameter, then the constructed href url will be built from the first navigable ancestor (aka\r\n * ancestor with a valid url).\r\n * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.\r\n * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'), \r\n * defines which state to be relative from.\r\n * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. \"http://www.example.com/fullurl\".\r\n * \r\n * @returns {string} compiled state url\r\n */\r\n $state.href = function href(stateOrName, params, options) {\r\n options = extend({\r\n lossy: true,\r\n inherit: true,\r\n absolute: false,\r\n relative: $state.$current\r\n }, options || {});\r\n\r\n var state = findState(stateOrName, options.relative);\r\n\r\n if (!isDefined(state)) return null;\r\n if (options.inherit) params = inheritParams($stateParams, params || {}, $state.$current, state);\r\n \r\n var nav = (state && options.lossy) ? state.navigable : state;\r\n\r\n if (!nav || nav.url === undefined || nav.url === null) {\r\n return null;\r\n }\r\n return $urlRouter.href(nav.url, filterByKeys(state.params.$$keys().concat('#'), params || {}), {\r\n absolute: options.absolute\r\n });\r\n };\r\n\r\n /**\r\n * @ngdoc function\r\n * @name ui.router.state.$state#get\r\n * @methodOf ui.router.state.$state\r\n *\r\n * @description\r\n * Returns the state configuration object for any specific state or all states.\r\n *\r\n * @param {string|object=} stateOrName (absolute or relative) If provided, will only get the config for\r\n * the requested state. If not provided, returns an array of ALL state configs.\r\n * @param {string|object=} context When stateOrName is a relative state reference, the state will be retrieved relative to context.\r\n * @returns {Object|Array} State configuration object or array of all objects.\r\n */\r\n $state.get = function (stateOrName, context) {\r\n if (arguments.length === 0) return map(objectKeys(states), function(name) { return states[name].self; });\r\n var state = findState(stateOrName, context || $state.$current);\r\n return (state && state.self) ? state.self : null;\r\n };\r\n\r\n function resolveState(state, params, paramsAreFiltered, inherited, dst, options) {\r\n // Make a restricted $stateParams with only the parameters that apply to this state if\r\n // necessary. In addition to being available to the controller and onEnter/onExit callbacks,\r\n // we also need $stateParams to be available for any $injector calls we make during the\r\n // dependency resolution process.\r\n var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params.$$keys(), params);\r\n var locals = { $stateParams: $stateParams };\r\n\r\n // Resolve 'global' dependencies for the state, i.e. those not specific to a view.\r\n // We're also including $stateParams in this; that way the parameters are restricted\r\n // to the set that should be visible to the state, and are independent of when we update\r\n // the global $state and $stateParams values.\r\n dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state);\r\n var promises = [dst.resolve.then(function (globals) {\r\n dst.globals = globals;\r\n })];\r\n if (inherited) promises.push(inherited);\r\n\r\n function resolveViews() {\r\n var viewsPromises = [];\r\n\r\n // Resolve template and dependencies for all views.\r\n forEach(state.views, function (view, name) {\r\n var injectables = (view.resolve && view.resolve !== state.resolve ? view.resolve : {});\r\n injectables.$template = [ function () {\r\n return $view.load(name, { view: view, locals: dst.globals, params: $stateParams, notify: options.notify }) || '';\r\n }];\r\n\r\n viewsPromises.push($resolve.resolve(injectables, dst.globals, dst.resolve, state).then(function (result) {\r\n // References to the controller (only instantiated at link time)\r\n if (isFunction(view.controllerProvider) || isArray(view.controllerProvider)) {\r\n var injectLocals = angular.extend({}, injectables, dst.globals);\r\n result.$$controller = $injector.invoke(view.controllerProvider, null, injectLocals);\r\n } else {\r\n result.$$controller = view.controller;\r\n }\r\n // Provide access to the state itself for internal use\r\n result.$$state = state;\r\n result.$$controllerAs = view.controllerAs;\r\n dst[name] = result;\r\n }));\r\n });\r\n\r\n return $q.all(viewsPromises).then(function(){\r\n return dst.globals;\r\n });\r\n }\r\n\r\n // Wait for all the promises and then return the activation object\r\n return $q.all(promises).then(resolveViews).then(function (values) {\r\n return dst;\r\n });\r\n }\r\n\r\n return $state;\r\n }\r\n\r\n function shouldSkipReload(to, toParams, from, fromParams, locals, options) {\r\n // Return true if there are no differences in non-search (path/object) params, false if there are differences\r\n function nonSearchParamsEqual(fromAndToState, fromParams, toParams) {\r\n // Identify whether all the parameters that differ between `fromParams` and `toParams` were search params.\r\n function notSearchParam(key) {\r\n return fromAndToState.params[key].location != \"search\";\r\n }\r\n var nonQueryParamKeys = fromAndToState.params.$$keys().filter(notSearchParam);\r\n var nonQueryParams = pick.apply({}, [fromAndToState.params].concat(nonQueryParamKeys));\r\n var nonQueryParamSet = new $$UMFP.ParamSet(nonQueryParams);\r\n return nonQueryParamSet.$$equals(fromParams, toParams);\r\n }\r\n\r\n // If reload was not explicitly requested\r\n // and we're transitioning to the same state we're already in\r\n // and the locals didn't change\r\n // or they changed in a way that doesn't merit reloading\r\n // (reloadOnParams:false, or reloadOnSearch.false and only search params changed)\r\n // Then return true.\r\n if (!options.reload && to === from &&\r\n (locals === from.locals || (to.self.reloadOnSearch === false && nonSearchParamsEqual(from, fromParams, toParams)))) {\r\n return true;\r\n }\r\n }\r\n}\r\n\r\nangular.module('ui.router.state')\r\n .value('$stateParams', {})\r\n .provider('$state', $StateProvider);\r\n\r\n\r\n$ViewProvider.$inject = [];\r\nfunction $ViewProvider() {\r\n\r\n this.$get = $get;\r\n /**\r\n * @ngdoc object\r\n * @name ui.router.state.$view\r\n *\r\n * @requires ui.router.util.$templateFactory\r\n * @requires $rootScope\r\n *\r\n * @description\r\n *\r\n */\r\n $get.$inject = ['$rootScope', '$templateFactory'];\r\n function $get( $rootScope, $templateFactory) {\r\n return {\r\n // $view.load('full.viewName', { template: ..., controller: ..., resolve: ..., async: false, params: ... })\r\n /**\r\n * @ngdoc function\r\n * @name ui.router.state.$view#load\r\n * @methodOf ui.router.state.$view\r\n *\r\n * @description\r\n *\r\n * @param {string} name name\r\n * @param {object} options option object.\r\n */\r\n load: function load(name, options) {\r\n var result, defaults = {\r\n template: null, controller: null, view: null, locals: null, notify: true, async: true, params: {}\r\n };\r\n options = extend(defaults, options);\r\n\r\n if (options.view) {\r\n result = $templateFactory.fromConfig(options.view, options.params, options.locals);\r\n }\r\n if (result && options.notify) {\r\n /**\r\n * @ngdoc event\r\n * @name ui.router.state.$state#$viewContentLoading\r\n * @eventOf ui.router.state.$view\r\n * @eventType broadcast on root scope\r\n * @description\r\n *\r\n * Fired once the view **begins loading**, *before* the DOM is rendered.\r\n *\r\n * @param {Object} event Event object.\r\n * @param {Object} viewConfig The view config properties (template, controller, etc).\r\n *\r\n * @example\r\n *\r\n *
    \r\n         * $scope.$on('$viewContentLoading',\r\n         * function(event, viewConfig){\r\n         *     // Access to all the view config properties.\r\n         *     // and one special property 'targetView'\r\n         *     // viewConfig.targetView\r\n         * });\r\n         * 
    \r\n */\r\n $rootScope.$broadcast('$viewContentLoading', options);\r\n }\r\n return result;\r\n }\r\n };\r\n }\r\n}\r\n\r\nangular.module('ui.router.state').provider('$view', $ViewProvider);\r\n\r\n/**\r\n * @ngdoc object\r\n * @name ui.router.state.$uiViewScrollProvider\r\n *\r\n * @description\r\n * Provider that returns the {@link ui.router.state.$uiViewScroll} service function.\r\n */\r\nfunction $ViewScrollProvider() {\r\n\r\n var useAnchorScroll = false;\r\n\r\n /**\r\n * @ngdoc function\r\n * @name ui.router.state.$uiViewScrollProvider#useAnchorScroll\r\n * @methodOf ui.router.state.$uiViewScrollProvider\r\n *\r\n * @description\r\n * Reverts back to using the core [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll) service for\r\n * scrolling based on the url anchor.\r\n */\r\n this.useAnchorScroll = function () {\r\n useAnchorScroll = true;\r\n };\r\n\r\n /**\r\n * @ngdoc object\r\n * @name ui.router.state.$uiViewScroll\r\n *\r\n * @requires $anchorScroll\r\n * @requires $timeout\r\n *\r\n * @description\r\n * When called with a jqLite element, it scrolls the element into view (after a\r\n * `$timeout` so the DOM has time to refresh).\r\n *\r\n * If you prefer to rely on `$anchorScroll` to scroll the view to the anchor,\r\n * this can be enabled by calling {@link ui.router.state.$uiViewScrollProvider#methods_useAnchorScroll `$uiViewScrollProvider.useAnchorScroll()`}.\r\n */\r\n this.$get = ['$anchorScroll', '$timeout', function ($anchorScroll, $timeout) {\r\n if (useAnchorScroll) {\r\n return $anchorScroll;\r\n }\r\n\r\n return function ($element) {\r\n return $timeout(function () {\r\n $element[0].scrollIntoView();\r\n }, 0, false);\r\n };\r\n }];\r\n}\r\n\r\nangular.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider);\r\n\r\n/**\r\n * @ngdoc directive\r\n * @name ui.router.state.directive:ui-view\r\n *\r\n * @requires ui.router.state.$state\r\n * @requires $compile\r\n * @requires $controller\r\n * @requires $injector\r\n * @requires ui.router.state.$uiViewScroll\r\n * @requires $document\r\n *\r\n * @restrict ECA\r\n *\r\n * @description\r\n * The ui-view directive tells $state where to place your templates.\r\n *\r\n * @param {string=} name A view name. The name should be unique amongst the other views in the\r\n * same state. You can have views of the same name that live in different states.\r\n *\r\n * @param {string=} autoscroll It allows you to set the scroll behavior of the browser window\r\n * when a view is populated. By default, $anchorScroll is overridden by ui-router's custom scroll\r\n * service, {@link ui.router.state.$uiViewScroll}. This custom service let's you\r\n * scroll ui-view elements into view when they are populated during a state activation.\r\n *\r\n * *Note: To revert back to old [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll)\r\n * functionality, call `$uiViewScrollProvider.useAnchorScroll()`.*\r\n *\r\n * @param {string=} onload Expression to evaluate whenever the view updates.\r\n * \r\n * @example\r\n * A view can be unnamed or named. \r\n *
    \r\n * \r\n * 
    \r\n * \r\n * \r\n *
    \r\n *
    \r\n *\r\n * You can only have one unnamed view within any template (or root html). If you are only using a \r\n * single view and it is unnamed then you can populate it like so:\r\n *
    \r\n * 
    \r\n * $stateProvider.state(\"home\", {\r\n * template: \"

    HELLO!

    \"\r\n * })\r\n *
    \r\n * \r\n * The above is a convenient shortcut equivalent to specifying your view explicitly with the {@link ui.router.state.$stateProvider#views `views`}\r\n * config property, by name, in this case an empty name:\r\n *
    \r\n * $stateProvider.state(\"home\", {\r\n *   views: {\r\n *     \"\": {\r\n *       template: \"

    HELLO!

    \"\r\n * }\r\n * } \r\n * })\r\n *
    \r\n * \r\n * But typically you'll only use the views property if you name your view or have more than one view \r\n * in the same template. There's not really a compelling reason to name a view if its the only one, \r\n * but you could if you wanted, like so:\r\n *
    \r\n * 
    \r\n *
    \r\n *
    \r\n * $stateProvider.state(\"home\", {\r\n *   views: {\r\n *     \"main\": {\r\n *       template: \"

    HELLO!

    \"\r\n * }\r\n * } \r\n * })\r\n *
    \r\n * \r\n * Really though, you'll use views to set up multiple views:\r\n *
    \r\n * 
    \r\n *
    \r\n *
    \r\n *
    \r\n * \r\n *
    \r\n * $stateProvider.state(\"home\", {\r\n *   views: {\r\n *     \"\": {\r\n *       template: \"

    HELLO!

    \"\r\n * },\r\n * \"chart\": {\r\n * template: \"\"\r\n * },\r\n * \"data\": {\r\n * template: \"\"\r\n * }\r\n * } \r\n * })\r\n *
    \r\n *\r\n * Examples for `autoscroll`:\r\n *\r\n *
    \r\n * \r\n * \r\n *\r\n * \r\n * \r\n * \r\n * \r\n * 
    \r\n */\r\n$ViewDirective.$inject = ['$state', '$injector', '$uiViewScroll', '$interpolate'];\r\nfunction $ViewDirective( $state, $injector, $uiViewScroll, $interpolate) {\r\n\r\n function getService() {\r\n return ($injector.has) ? function(service) {\r\n return $injector.has(service) ? $injector.get(service) : null;\r\n } : function(service) {\r\n try {\r\n return $injector.get(service);\r\n } catch (e) {\r\n return null;\r\n }\r\n };\r\n }\r\n\r\n var service = getService(),\r\n $animator = service('$animator'),\r\n $animate = service('$animate');\r\n\r\n // Returns a set of DOM manipulation functions based on which Angular version\r\n // it should use\r\n function getRenderer(attrs, scope) {\r\n var statics = function() {\r\n return {\r\n enter: function (element, target, cb) { target.after(element); cb(); },\r\n leave: function (element, cb) { element.remove(); cb(); }\r\n };\r\n };\r\n\r\n if ($animate) {\r\n return {\r\n enter: function(element, target, cb) {\r\n var promise = $animate.enter(element, null, target, cb);\r\n if (promise && promise.then) promise.then(cb);\r\n },\r\n leave: function(element, cb) {\r\n var promise = $animate.leave(element, cb);\r\n if (promise && promise.then) promise.then(cb);\r\n }\r\n };\r\n }\r\n\r\n if ($animator) {\r\n var animate = $animator && $animator(scope, attrs);\r\n\r\n return {\r\n enter: function(element, target, cb) {animate.enter(element, null, target); cb(); },\r\n leave: function(element, cb) { animate.leave(element); cb(); }\r\n };\r\n }\r\n\r\n return statics();\r\n }\r\n\r\n var directive = {\r\n restrict: 'ECA',\r\n terminal: true,\r\n priority: 400,\r\n transclude: 'element',\r\n compile: function (tElement, tAttrs, $transclude) {\r\n return function (scope, $element, attrs) {\r\n var previousEl, currentEl, currentScope, latestLocals,\r\n onloadExp = attrs.onload || '',\r\n autoScrollExp = attrs.autoscroll,\r\n renderer = getRenderer(attrs, scope);\r\n\r\n scope.$on('$stateChangeSuccess', function() {\r\n updateView(false);\r\n });\r\n scope.$on('$viewContentLoading', function() {\r\n updateView(false);\r\n });\r\n\r\n updateView(true);\r\n\r\n function cleanupLastView() {\r\n if (previousEl) {\r\n previousEl.remove();\r\n previousEl = null;\r\n }\r\n\r\n if (currentScope) {\r\n currentScope.$destroy();\r\n currentScope = null;\r\n }\r\n\r\n if (currentEl) {\r\n renderer.leave(currentEl, function() {\r\n previousEl = null;\r\n });\r\n\r\n previousEl = currentEl;\r\n currentEl = null;\r\n }\r\n }\r\n\r\n function updateView(firstTime) {\r\n var newScope,\r\n name = getUiViewName(scope, attrs, $element, $interpolate),\r\n previousLocals = name && $state.$current && $state.$current.locals[name];\r\n\r\n if (!firstTime && previousLocals === latestLocals) return; // nothing to do\r\n newScope = scope.$new();\r\n latestLocals = $state.$current.locals[name];\r\n\r\n var clone = $transclude(newScope, function(clone) {\r\n renderer.enter(clone, $element, function onUiViewEnter() {\r\n if(currentScope) {\r\n currentScope.$emit('$viewContentAnimationEnded');\r\n }\r\n\r\n if (angular.isDefined(autoScrollExp) && !autoScrollExp || scope.$eval(autoScrollExp)) {\r\n $uiViewScroll(clone);\r\n }\r\n });\r\n cleanupLastView();\r\n });\r\n\r\n currentEl = clone;\r\n currentScope = newScope;\r\n /**\r\n * @ngdoc event\r\n * @name ui.router.state.directive:ui-view#$viewContentLoaded\r\n * @eventOf ui.router.state.directive:ui-view\r\n * @eventType emits on ui-view directive scope\r\n * @description *\r\n * Fired once the view is **loaded**, *after* the DOM is rendered.\r\n *\r\n * @param {Object} event Event object.\r\n */\r\n currentScope.$emit('$viewContentLoaded');\r\n currentScope.$eval(onloadExp);\r\n }\r\n };\r\n }\r\n };\r\n\r\n return directive;\r\n}\r\n\r\n$ViewDirectiveFill.$inject = ['$compile', '$controller', '$state', '$interpolate'];\r\nfunction $ViewDirectiveFill ( $compile, $controller, $state, $interpolate) {\r\n return {\r\n restrict: 'ECA',\r\n priority: -400,\r\n compile: function (tElement) {\r\n var initial = tElement.html();\r\n return function (scope, $element, attrs) {\r\n var current = $state.$current,\r\n name = getUiViewName(scope, attrs, $element, $interpolate),\r\n locals = current && current.locals[name];\r\n\r\n if (! locals) {\r\n return;\r\n }\r\n\r\n $element.data('$uiView', { name: name, state: locals.$$state });\r\n $element.html(locals.$template ? locals.$template : initial);\r\n\r\n var link = $compile($element.contents());\r\n\r\n if (locals.$$controller) {\r\n locals.$scope = scope;\r\n locals.$element = $element;\r\n var controller = $controller(locals.$$controller, locals);\r\n if (locals.$$controllerAs) {\r\n scope[locals.$$controllerAs] = controller;\r\n }\r\n $element.data('$ngControllerController', controller);\r\n $element.children().data('$ngControllerController', controller);\r\n }\r\n\r\n link(scope);\r\n };\r\n }\r\n };\r\n}\r\n\r\n/**\r\n * Shared ui-view code for both directives:\r\n * Given scope, element, and its attributes, return the view's name\r\n */\r\nfunction getUiViewName(scope, attrs, element, $interpolate) {\r\n var name = $interpolate(attrs.uiView || attrs.name || '')(scope);\r\n var inherited = element.inheritedData('$uiView');\r\n return name.indexOf('@') >= 0 ? name : (name + '@' + (inherited ? inherited.state.name : ''));\r\n}\r\n\r\nangular.module('ui.router.state').directive('uiView', $ViewDirective);\r\nangular.module('ui.router.state').directive('uiView', $ViewDirectiveFill);\r\n\r\nfunction parseStateRef(ref, current) {\r\n var preparsed = ref.match(/^\\s*({[^}]*})\\s*$/), parsed;\r\n if (preparsed) ref = current + '(' + preparsed[1] + ')';\r\n parsed = ref.replace(/\\n/g, \" \").match(/^([^(]+?)\\s*(\\((.*)\\))?$/);\r\n if (!parsed || parsed.length !== 4) throw new Error(\"Invalid state ref '\" + ref + \"'\");\r\n return { state: parsed[1], paramExpr: parsed[3] || null };\r\n}\r\n\r\nfunction stateContext(el) {\r\n var stateData = el.parent().inheritedData('$uiView');\r\n\r\n if (stateData && stateData.state && stateData.state.name) {\r\n return stateData.state;\r\n }\r\n}\r\n\r\n/**\r\n * @ngdoc directive\r\n * @name ui.router.state.directive:ui-sref\r\n *\r\n * @requires ui.router.state.$state\r\n * @requires $timeout\r\n *\r\n * @restrict A\r\n *\r\n * @description\r\n * A directive that binds a link (`` tag) to a state. If the state has an associated \r\n * URL, the directive will automatically generate & update the `href` attribute via \r\n * the {@link ui.router.state.$state#methods_href $state.href()} method. Clicking \r\n * the link will trigger a state transition with optional parameters. \r\n *\r\n * Also middle-clicking, right-clicking, and ctrl-clicking on the link will be \r\n * handled natively by the browser.\r\n *\r\n * You can also use relative state paths within ui-sref, just like the relative \r\n * paths passed to `$state.go()`. You just need to be aware that the path is relative\r\n * to the state that the link lives in, in other words the state that loaded the \r\n * template containing the link.\r\n *\r\n * You can specify options to pass to {@link ui.router.state.$state#go $state.go()}\r\n * using the `ui-sref-opts` attribute. Options are restricted to `location`, `inherit`,\r\n * and `reload`.\r\n *\r\n * @example\r\n * Here's an example of how you'd use ui-sref and how it would compile. If you have the \r\n * following template:\r\n *
    \r\n * Home | About | Next page\r\n * \r\n * \r\n * 
    \r\n * \r\n * Then the compiled html would be (assuming Html5Mode is off and current state is contacts):\r\n *
    \r\n * Home | About | Next page\r\n * \r\n * 
      \r\n *
    • \r\n * Joe\r\n *
    • \r\n *
    • \r\n * Alice\r\n *
    • \r\n *
    • \r\n * Bob\r\n *
    • \r\n *
    \r\n *\r\n * Home\r\n *
    \r\n *\r\n * @param {string} ui-sref 'stateName' can be any valid absolute or relative state\r\n * @param {Object} ui-sref-opts options to pass to {@link ui.router.state.$state#go $state.go()}\r\n */\r\n$StateRefDirective.$inject = ['$state', '$timeout'];\r\nfunction $StateRefDirective($state, $timeout) {\r\n var allowedOptions = ['location', 'inherit', 'reload', 'absolute'];\r\n\r\n return {\r\n restrict: 'A',\r\n require: ['?^uiSrefActive', '?^uiSrefActiveEq'],\r\n link: function(scope, element, attrs, uiSrefActive) {\r\n var ref = parseStateRef(attrs.uiSref, $state.current.name);\r\n var params = null, url = null, base = stateContext(element) || $state.$current;\r\n // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.\r\n var hrefKind = Object.prototype.toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?\r\n 'xlink:href' : 'href';\r\n var newHref = null, isAnchor = element.prop(\"tagName\").toUpperCase() === \"A\";\r\n var isForm = element[0].nodeName === \"FORM\";\r\n var attr = isForm ? \"action\" : hrefKind, nav = true;\r\n\r\n var options = { relative: base, inherit: true };\r\n var optionsOverride = scope.$eval(attrs.uiSrefOpts) || {};\r\n\r\n angular.forEach(allowedOptions, function(option) {\r\n if (option in optionsOverride) {\r\n options[option] = optionsOverride[option];\r\n }\r\n });\r\n\r\n var update = function(newVal) {\r\n if (newVal) params = angular.copy(newVal);\r\n if (!nav) return;\r\n\r\n newHref = $state.href(ref.state, params, options);\r\n\r\n var activeDirective = uiSrefActive[1] || uiSrefActive[0];\r\n if (activeDirective) {\r\n activeDirective.$$addStateInfo(ref.state, params);\r\n }\r\n if (newHref === null) {\r\n nav = false;\r\n return false;\r\n }\r\n attrs.$set(attr, newHref);\r\n };\r\n\r\n if (ref.paramExpr) {\r\n scope.$watch(ref.paramExpr, function(newVal, oldVal) {\r\n if (newVal !== params) update(newVal);\r\n }, true);\r\n params = angular.copy(scope.$eval(ref.paramExpr));\r\n }\r\n update();\r\n\r\n if (isForm) return;\r\n\r\n element.bind(\"click\", function(e) {\r\n var button = e.which || e.button;\r\n if ( !(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || element.attr('target')) ) {\r\n // HACK: This is to allow ng-clicks to be processed before the transition is initiated:\r\n var transition = $timeout(function() {\r\n $state.go(ref.state, params, options);\r\n });\r\n e.preventDefault();\r\n\r\n // if the state has no URL, ignore one preventDefault from the directive.\r\n var ignorePreventDefaultCount = isAnchor && !newHref ? 1: 0;\r\n e.preventDefault = function() {\r\n if (ignorePreventDefaultCount-- <= 0)\r\n $timeout.cancel(transition);\r\n };\r\n }\r\n });\r\n }\r\n };\r\n}\r\n\r\n/**\r\n * @ngdoc directive\r\n * @name ui.router.state.directive:ui-sref-active\r\n *\r\n * @requires ui.router.state.$state\r\n * @requires ui.router.state.$stateParams\r\n * @requires $interpolate\r\n *\r\n * @restrict A\r\n *\r\n * @description\r\n * A directive working alongside ui-sref to add classes to an element when the\r\n * related ui-sref directive's state is active, and removing them when it is inactive.\r\n * The primary use-case is to simplify the special appearance of navigation menus\r\n * relying on `ui-sref`, by having the \"active\" state's menu button appear different,\r\n * distinguishing it from the inactive menu items.\r\n *\r\n * ui-sref-active can live on the same element as ui-sref or on a parent element. The first\r\n * ui-sref-active found at the same level or above the ui-sref will be used.\r\n *\r\n * Will activate when the ui-sref's target state or any child state is active. If you\r\n * need to activate only when the ui-sref target state is active and *not* any of\r\n * it's children, then you will use\r\n * {@link ui.router.state.directive:ui-sref-active-eq ui-sref-active-eq}\r\n *\r\n * @example\r\n * Given the following template:\r\n *
    \r\n * \r\n * 
    \r\n *\r\n *\r\n * When the app state is \"app.user\" (or any children states), and contains the state parameter \"user\" with value \"bilbobaggins\",\r\n * the resulting HTML will appear as (note the 'active' class):\r\n *
    \r\n * \r\n * 
    \r\n *\r\n * The class name is interpolated **once** during the directives link time (any further changes to the\r\n * interpolated value are ignored).\r\n *\r\n * Multiple classes may be specified in a space-separated format:\r\n *
    \r\n * 
      \r\n *
    • \r\n * link\r\n *
    • \r\n *
    \r\n *
    \r\n */\r\n\r\n/**\r\n * @ngdoc directive\r\n * @name ui.router.state.directive:ui-sref-active-eq\r\n *\r\n * @requires ui.router.state.$state\r\n * @requires ui.router.state.$stateParams\r\n * @requires $interpolate\r\n *\r\n * @restrict A\r\n *\r\n * @description\r\n * The same as {@link ui.router.state.directive:ui-sref-active ui-sref-active} but will only activate\r\n * when the exact target state used in the `ui-sref` is active; no child states.\r\n *\r\n */\r\n$StateRefActiveDirective.$inject = ['$state', '$stateParams', '$interpolate'];\r\nfunction $StateRefActiveDirective($state, $stateParams, $interpolate) {\r\n return {\r\n restrict: \"A\",\r\n controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {\r\n var states = [], activeClass;\r\n\r\n // There probably isn't much point in $observing this\r\n // uiSrefActive and uiSrefActiveEq share the same directive object with some\r\n // slight difference in logic routing\r\n activeClass = $interpolate($attrs.uiSrefActiveEq || $attrs.uiSrefActive || '', false)($scope);\r\n\r\n // Allow uiSref to communicate with uiSrefActive[Equals]\r\n this.$$addStateInfo = function (newState, newParams) {\r\n var state = $state.get(newState, stateContext($element));\r\n\r\n states.push({\r\n state: state || { name: newState },\r\n params: newParams\r\n });\r\n\r\n update();\r\n };\r\n\r\n $scope.$on('$stateChangeSuccess', update);\r\n\r\n // Update route state\r\n function update() {\r\n if (anyMatch()) {\r\n $element.addClass(activeClass);\r\n } else {\r\n $element.removeClass(activeClass);\r\n }\r\n }\r\n\r\n function anyMatch() {\r\n for (var i = 0; i < states.length; i++) {\r\n if (isMatch(states[i].state, states[i].params)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n function isMatch(state, params) {\r\n if (typeof $attrs.uiSrefActiveEq !== 'undefined') {\r\n return $state.is(state.name, params);\r\n } else {\r\n return $state.includes(state.name, params);\r\n }\r\n }\r\n }]\r\n };\r\n}\r\n\r\nangular.module('ui.router.state')\r\n .directive('uiSref', $StateRefDirective)\r\n .directive('uiSrefActive', $StateRefActiveDirective)\r\n .directive('uiSrefActiveEq', $StateRefActiveDirective);\r\n\r\n/**\r\n * @ngdoc filter\r\n * @name ui.router.state.filter:isState\r\n *\r\n * @requires ui.router.state.$state\r\n *\r\n * @description\r\n * Translates to {@link ui.router.state.$state#methods_is $state.is(\"stateName\")}.\r\n */\r\n$IsStateFilter.$inject = ['$state'];\r\nfunction $IsStateFilter($state) {\r\n var isFilter = function (state) {\r\n return $state.is(state);\r\n };\r\n isFilter.$stateful = true;\r\n return isFilter;\r\n}\r\n\r\n/**\r\n * @ngdoc filter\r\n * @name ui.router.state.filter:includedByState\r\n *\r\n * @requires ui.router.state.$state\r\n *\r\n * @description\r\n * Translates to {@link ui.router.state.$state#methods_includes $state.includes('fullOrPartialStateName')}.\r\n */\r\n$IncludedByStateFilter.$inject = ['$state'];\r\nfunction $IncludedByStateFilter($state) {\r\n var includesFilter = function (state) {\r\n return $state.includes(state);\r\n };\r\n includesFilter.$stateful = true;\r\n return includesFilter;\r\n}\r\n\r\nangular.module('ui.router.state')\r\n .filter('isState', $IsStateFilter)\r\n .filter('includedByState', $IncludedByStateFilter);\r\n})(window, window.angular);\n},{}],9:[function(require,module,exports){\n(function (global){\n; var __browserify_shim_require__=require;(function browserifyShim(module, exports, require, define, browserify_shim__define__module__export__) {\n/**\r\n * @license AngularJS v1.3.18\r\n * (c) 2010-2014 Google, Inc. http://angularjs.org\r\n * License: MIT\r\n */\r\n(function(window, document, undefined) {'use strict';\r\n\r\n/**\r\n * @description\r\n *\r\n * This object provides a utility for producing rich Error messages within\r\n * Angular. It can be called as follows:\r\n *\r\n * var exampleMinErr = minErr('example');\r\n * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);\r\n *\r\n * The above creates an instance of minErr in the example namespace. The\r\n * resulting error will have a namespaced error code of example.one. The\r\n * resulting error will replace {0} with the value of foo, and {1} with the\r\n * value of bar. The object is not restricted in the number of arguments it can\r\n * take.\r\n *\r\n * If fewer arguments are specified than necessary for interpolation, the extra\r\n * interpolation markers will be preserved in the final string.\r\n *\r\n * Since data will be parsed statically during a build step, some restrictions\r\n * are applied with respect to how minErr instances are created and called.\r\n * Instances should have names of the form namespaceMinErr for a minErr created\r\n * using minErr('namespace') . Error codes, namespaces and template strings\r\n * should all be static strings, not variables or general expressions.\r\n *\r\n * @param {string} module The namespace to use for the new minErr instance.\r\n * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning\r\n * error from returned function, for cases when a particular type of error is useful.\r\n * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance\r\n */\r\n\r\nfunction minErr(module, ErrorConstructor) {\r\n ErrorConstructor = ErrorConstructor || Error;\r\n return function() {\r\n var code = arguments[0],\r\n prefix = '[' + (module ? module + ':' : '') + code + '] ',\r\n template = arguments[1],\r\n templateArgs = arguments,\r\n\r\n message, i;\r\n\r\n message = prefix + template.replace(/\\{\\d+\\}/g, function(match) {\r\n var index = +match.slice(1, -1), arg;\r\n\r\n if (index + 2 < templateArgs.length) {\r\n return toDebugString(templateArgs[index + 2]);\r\n }\r\n return match;\r\n });\r\n\r\n message = message + '\\nhttp://errors.angularjs.org/1.3.18/' +\r\n (module ? module + '/' : '') + code;\r\n for (i = 2; i < arguments.length; i++) {\r\n message = message + (i == 2 ? '?' : '&') + 'p' + (i - 2) + '=' +\r\n encodeURIComponent(toDebugString(arguments[i]));\r\n }\r\n return new ErrorConstructor(message);\r\n };\r\n}\r\n\r\n/* We need to tell jshint what variables are being exported */\r\n/* global angular: true,\r\n msie: true,\r\n jqLite: true,\r\n jQuery: true,\r\n slice: true,\r\n splice: true,\r\n push: true,\r\n toString: true,\r\n ngMinErr: true,\r\n angularModule: true,\r\n uid: true,\r\n REGEX_STRING_REGEXP: true,\r\n VALIDITY_STATE_PROPERTY: true,\r\n\r\n lowercase: true,\r\n uppercase: true,\r\n manualLowercase: true,\r\n manualUppercase: true,\r\n nodeName_: true,\r\n isArrayLike: true,\r\n forEach: true,\r\n sortedKeys: true,\r\n forEachSorted: true,\r\n reverseParams: true,\r\n nextUid: true,\r\n setHashKey: true,\r\n extend: true,\r\n int: true,\r\n inherit: true,\r\n noop: true,\r\n identity: true,\r\n valueFn: true,\r\n isUndefined: true,\r\n isDefined: true,\r\n isObject: true,\r\n isString: true,\r\n isNumber: true,\r\n isDate: true,\r\n isArray: true,\r\n isFunction: true,\r\n isRegExp: true,\r\n isWindow: true,\r\n isScope: true,\r\n isFile: true,\r\n isFormData: true,\r\n isBlob: true,\r\n isBoolean: true,\r\n isPromiseLike: true,\r\n trim: true,\r\n escapeForRegexp: true,\r\n isElement: true,\r\n makeMap: true,\r\n includes: true,\r\n arrayRemove: true,\r\n copy: true,\r\n shallowCopy: true,\r\n equals: true,\r\n csp: true,\r\n concat: true,\r\n sliceArgs: true,\r\n bind: true,\r\n toJsonReplacer: true,\r\n toJson: true,\r\n fromJson: true,\r\n startingTag: true,\r\n tryDecodeURIComponent: true,\r\n parseKeyValue: true,\r\n toKeyValue: true,\r\n encodeUriSegment: true,\r\n encodeUriQuery: true,\r\n angularInit: true,\r\n bootstrap: true,\r\n getTestability: true,\r\n snake_case: true,\r\n bindJQuery: true,\r\n assertArg: true,\r\n assertArgFn: true,\r\n assertNotHasOwnProperty: true,\r\n getter: true,\r\n getBlockNodes: true,\r\n hasOwnProperty: true,\r\n createMap: true,\r\n\r\n NODE_TYPE_ELEMENT: true,\r\n NODE_TYPE_ATTRIBUTE: true,\r\n NODE_TYPE_TEXT: true,\r\n NODE_TYPE_COMMENT: true,\r\n NODE_TYPE_DOCUMENT: true,\r\n NODE_TYPE_DOCUMENT_FRAGMENT: true,\r\n*/\r\n\r\n////////////////////////////////////\r\n\r\n/**\r\n * @ngdoc module\r\n * @name ng\r\n * @module ng\r\n * @description\r\n *\r\n * # ng (core module)\r\n * The ng module is loaded by default when an AngularJS application is started. The module itself\r\n * contains the essential components for an AngularJS application to function. The table below\r\n * lists a high level breakdown of each of the services/factories, filters, directives and testing\r\n * components available within this core module.\r\n *\r\n *
    \r\n */\r\n\r\nvar REGEX_STRING_REGEXP = /^\\/(.+)\\/([a-z]*)$/;\r\n\r\n// The name of a form control's ValidityState property.\r\n// This is used so that it's possible for internal tests to create mock ValidityStates.\r\nvar VALIDITY_STATE_PROPERTY = 'validity';\r\n\r\n/**\r\n * @ngdoc function\r\n * @name angular.lowercase\r\n * @module ng\r\n * @kind function\r\n *\r\n * @description Converts the specified string to lowercase.\r\n * @param {string} string String to be converted to lowercase.\r\n * @returns {string} Lowercased string.\r\n */\r\nvar lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};\r\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\r\n\r\n/**\r\n * @ngdoc function\r\n * @name angular.uppercase\r\n * @module ng\r\n * @kind function\r\n *\r\n * @description Converts the specified string to uppercase.\r\n * @param {string} string String to be converted to uppercase.\r\n * @returns {string} Uppercased string.\r\n */\r\nvar uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};\r\n\r\n\r\nvar manualLowercase = function(s) {\r\n /* jshint bitwise: false */\r\n return isString(s)\r\n ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})\r\n : s;\r\n};\r\nvar manualUppercase = function(s) {\r\n /* jshint bitwise: false */\r\n return isString(s)\r\n ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})\r\n : s;\r\n};\r\n\r\n\r\n// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish\r\n// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods\r\n// with correct but slower alternatives.\r\nif ('i' !== 'I'.toLowerCase()) {\r\n lowercase = manualLowercase;\r\n uppercase = manualUppercase;\r\n}\r\n\r\n\r\nvar\r\n msie, // holds major version number for IE, or NaN if UA is not IE.\r\n jqLite, // delay binding since jQuery could be loaded after us.\r\n jQuery, // delay binding\r\n slice = [].slice,\r\n splice = [].splice,\r\n push = [].push,\r\n toString = Object.prototype.toString,\r\n ngMinErr = minErr('ng'),\r\n\r\n /** @name angular */\r\n angular = window.angular || (window.angular = {}),\r\n angularModule,\r\n uid = 0;\r\n\r\n/**\r\n * documentMode is an IE-only property\r\n * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx\r\n */\r\nmsie = document.documentMode;\r\n\r\n\r\n/**\r\n * @private\r\n * @param {*} obj\r\n * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,\r\n * String ...)\r\n */\r\nfunction isArrayLike(obj) {\r\n if (obj == null || isWindow(obj)) {\r\n return false;\r\n }\r\n\r\n // Support: iOS 8.2 (not reproducible in simulator)\r\n // \"length\" in obj used to prevent JIT error (gh-11508)\r\n var length = \"length\" in Object(obj) && obj.length;\r\n\r\n if (obj.nodeType === NODE_TYPE_ELEMENT && length) {\r\n return true;\r\n }\r\n\r\n return isString(obj) || isArray(obj) || length === 0 ||\r\n typeof length === 'number' && length > 0 && (length - 1) in obj;\r\n}\r\n\r\n/**\r\n * @ngdoc function\r\n * @name angular.forEach\r\n * @module ng\r\n * @kind function\r\n *\r\n * @description\r\n * Invokes the `iterator` function once for each item in `obj` collection, which can be either an\r\n * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`\r\n * is the value of an object property or an array element, `key` is the object property key or\r\n * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.\r\n *\r\n * It is worth noting that `.forEach` does not iterate over inherited properties because it filters\r\n * using the `hasOwnProperty` method.\r\n *\r\n * Unlike ES262's\r\n * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),\r\n * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just\r\n * return the value provided.\r\n *\r\n ```js\r\n var values = {name: 'misko', gender: 'male'};\r\n var log = [];\r\n angular.forEach(values, function(value, key) {\r\n this.push(key + ': ' + value);\r\n }, log);\r\n expect(log).toEqual(['name: misko', 'gender: male']);\r\n ```\r\n *\r\n * @param {Object|Array} obj Object to iterate over.\r\n * @param {Function} iterator Iterator function.\r\n * @param {Object=} context Object to become context (`this`) for the iterator function.\r\n * @returns {Object|Array} Reference to `obj`.\r\n */\r\n\r\nfunction forEach(obj, iterator, context) {\r\n var key, length;\r\n if (obj) {\r\n if (isFunction(obj)) {\r\n for (key in obj) {\r\n // Need to check if hasOwnProperty exists,\r\n // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function\r\n if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {\r\n iterator.call(context, obj[key], key, obj);\r\n }\r\n }\r\n } else if (isArray(obj) || isArrayLike(obj)) {\r\n var isPrimitive = typeof obj !== 'object';\r\n for (key = 0, length = obj.length; key < length; key++) {\r\n if (isPrimitive || key in obj) {\r\n iterator.call(context, obj[key], key, obj);\r\n }\r\n }\r\n } else if (obj.forEach && obj.forEach !== forEach) {\r\n obj.forEach(iterator, context, obj);\r\n } else {\r\n for (key in obj) {\r\n if (obj.hasOwnProperty(key)) {\r\n iterator.call(context, obj[key], key, obj);\r\n }\r\n }\r\n }\r\n }\r\n return obj;\r\n}\r\n\r\nfunction sortedKeys(obj) {\r\n return Object.keys(obj).sort();\r\n}\r\n\r\nfunction forEachSorted(obj, iterator, context) {\r\n var keys = sortedKeys(obj);\r\n for (var i = 0; i < keys.length; i++) {\r\n iterator.call(context, obj[keys[i]], keys[i]);\r\n }\r\n return keys;\r\n}\r\n\r\n\r\n/**\r\n * when using forEach the params are value, key, but it is often useful to have key, value.\r\n * @param {function(string, *)} iteratorFn\r\n * @returns {function(*, string)}\r\n */\r\nfunction reverseParams(iteratorFn) {\r\n return function(value, key) { iteratorFn(key, value); };\r\n}\r\n\r\n/**\r\n * A consistent way of creating unique IDs in angular.\r\n *\r\n * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before\r\n * we hit number precision issues in JavaScript.\r\n *\r\n * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M\r\n *\r\n * @returns {number} an unique alpha-numeric string\r\n */\r\nfunction nextUid() {\r\n return ++uid;\r\n}\r\n\r\n\r\n/**\r\n * Set or clear the hashkey for an object.\r\n * @param obj object\r\n * @param h the hashkey (!truthy to delete the hashkey)\r\n */\r\nfunction setHashKey(obj, h) {\r\n if (h) {\r\n obj.$$hashKey = h;\r\n } else {\r\n delete obj.$$hashKey;\r\n }\r\n}\r\n\r\n/**\r\n * @ngdoc function\r\n * @name angular.extend\r\n * @module ng\r\n * @kind function\r\n *\r\n * @description\r\n * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)\r\n * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so\r\n * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.\r\n * Note: Keep in mind that `angular.extend` does not support recursive merge (deep copy).\r\n *\r\n * @param {Object} dst Destination object.\r\n * @param {...Object} src Source object(s).\r\n * @returns {Object} Reference to `dst`.\r\n */\r\nfunction extend(dst) {\r\n var h = dst.$$hashKey;\r\n\r\n for (var i = 1, ii = arguments.length; i < ii; i++) {\r\n var obj = arguments[i];\r\n if (obj) {\r\n var keys = Object.keys(obj);\r\n for (var j = 0, jj = keys.length; j < jj; j++) {\r\n var key = keys[j];\r\n dst[key] = obj[key];\r\n }\r\n }\r\n }\r\n\r\n setHashKey(dst, h);\r\n return dst;\r\n}\r\n\r\nfunction int(str) {\r\n return parseInt(str, 10);\r\n}\r\n\r\n\r\nfunction inherit(parent, extra) {\r\n return extend(Object.create(parent), extra);\r\n}\r\n\r\n/**\r\n * @ngdoc function\r\n * @name angular.noop\r\n * @module ng\r\n * @kind function\r\n *\r\n * @description\r\n * A function that performs no operations. This function can be useful when writing code in the\r\n * functional style.\r\n ```js\r\n function foo(callback) {\r\n var result = calculateResult();\r\n (callback || angular.noop)(result);\r\n }\r\n ```\r\n */\r\nfunction noop() {}\r\nnoop.$inject = [];\r\n\r\n\r\n/**\r\n * @ngdoc function\r\n * @name angular.identity\r\n * @module ng\r\n * @kind function\r\n *\r\n * @description\r\n * A function that returns its first argument. This function is useful when writing code in the\r\n * functional style.\r\n *\r\n ```js\r\n function transformer(transformationFn, value) {\r\n return (transformationFn || angular.identity)(value);\r\n };\r\n ```\r\n * @param {*} value to be returned.\r\n * @returns {*} the value passed in.\r\n */\r\nfunction identity($) {return $;}\r\nidentity.$inject = [];\r\n\r\n\r\nfunction valueFn(value) {return function() {return value;};}\r\n\r\n/**\r\n * @ngdoc function\r\n * @name angular.isUndefined\r\n * @module ng\r\n * @kind function\r\n *\r\n * @description\r\n * Determines if a reference is undefined.\r\n *\r\n * @param {*} value Reference to check.\r\n * @returns {boolean} True if `value` is undefined.\r\n */\r\nfunction isUndefined(value) {return typeof value === 'undefined';}\r\n\r\n\r\n/**\r\n * @ngdoc function\r\n * @name angular.isDefined\r\n * @module ng\r\n * @kind function\r\n *\r\n * @description\r\n * Determines if a reference is defined.\r\n *\r\n * @param {*} value Reference to check.\r\n * @returns {boolean} True if `value` is defined.\r\n */\r\nfunction isDefined(value) {return typeof value !== 'undefined';}\r\n\r\n\r\n/**\r\n * @ngdoc function\r\n * @name angular.isObject\r\n * @module ng\r\n * @kind function\r\n *\r\n * @description\r\n * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not\r\n * considered to be objects. Note that JavaScript arrays are objects.\r\n *\r\n * @param {*} value Reference to check.\r\n * @returns {boolean} True if `value` is an `Object` but not `null`.\r\n */\r\nfunction isObject(value) {\r\n // http://jsperf.com/isobject4\r\n return value !== null && typeof value === 'object';\r\n}\r\n\r\n\r\n/**\r\n * @ngdoc function\r\n * @name angular.isString\r\n * @module ng\r\n * @kind function\r\n *\r\n * @description\r\n * Determines if a reference is a `String`.\r\n *\r\n * @param {*} value Reference to check.\r\n * @returns {boolean} True if `value` is a `String`.\r\n */\r\nfunction isString(value) {return typeof value === 'string';}\r\n\r\n\r\n/**\r\n * @ngdoc function\r\n * @name angular.isNumber\r\n * @module ng\r\n * @kind function\r\n *\r\n * @description\r\n * Determines if a reference is a `Number`.\r\n *\r\n * This includes the \"special\" numbers `NaN`, `+Infinity` and `-Infinity`.\r\n *\r\n * If you wish to exclude these then you can use the native\r\n * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)\r\n * method.\r\n *\r\n * @param {*} value Reference to check.\r\n * @returns {boolean} True if `value` is a `Number`.\r\n */\r\nfunction isNumber(value) {return typeof value === 'number';}\r\n\r\n\r\n/**\r\n * @ngdoc function\r\n * @name angular.isDate\r\n * @module ng\r\n * @kind function\r\n *\r\n * @description\r\n * Determines if a value is a date.\r\n *\r\n * @param {*} value Reference to check.\r\n * @returns {boolean} True if `value` is a `Date`.\r\n */\r\nfunction isDate(value) {\r\n return toString.call(value) === '[object Date]';\r\n}\r\n\r\n\r\n/**\r\n * @ngdoc function\r\n * @name angular.isArray\r\n * @module ng\r\n * @kind function\r\n *\r\n * @description\r\n * Determines if a reference is an `Array`.\r\n *\r\n * @param {*} value Reference to check.\r\n * @returns {boolean} True if `value` is an `Array`.\r\n */\r\nvar isArray = Array.isArray;\r\n\r\n/**\r\n * @ngdoc function\r\n * @name angular.isFunction\r\n * @module ng\r\n * @kind function\r\n *\r\n * @description\r\n * Determines if a reference is a `Function`.\r\n *\r\n * @param {*} value Reference to check.\r\n * @returns {boolean} True if `value` is a `Function`.\r\n */\r\nfunction isFunction(value) {return typeof value === 'function';}\r\n\r\n\r\n/**\r\n * Determines if a value is a regular expression object.\r\n *\r\n * @private\r\n * @param {*} value Reference to check.\r\n * @returns {boolean} True if `value` is a `RegExp`.\r\n */\r\nfunction isRegExp(value) {\r\n return toString.call(value) === '[object RegExp]';\r\n}\r\n\r\n\r\n/**\r\n * Checks if `obj` is a window object.\r\n *\r\n * @private\r\n * @param {*} obj Object to check\r\n * @returns {boolean} True if `obj` is a window obj.\r\n */\r\nfunction isWindow(obj) {\r\n return obj && obj.window === obj;\r\n}\r\n\r\n\r\nfunction isScope(obj) {\r\n return obj && obj.$evalAsync && obj.$watch;\r\n}\r\n\r\n\r\nfunction isFile(obj) {\r\n return toString.call(obj) === '[object File]';\r\n}\r\n\r\n\r\nfunction isFormData(obj) {\r\n return toString.call(obj) === '[object FormData]';\r\n}\r\n\r\n\r\nfunction isBlob(obj) {\r\n return toString.call(obj) === '[object Blob]';\r\n}\r\n\r\n\r\nfunction isBoolean(value) {\r\n return typeof value === 'boolean';\r\n}\r\n\r\n\r\nfunction isPromiseLike(obj) {\r\n return obj && isFunction(obj.then);\r\n}\r\n\r\n\r\nvar trim = function(value) {\r\n return isString(value) ? value.trim() : value;\r\n};\r\n\r\n// Copied from:\r\n// http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021\r\n// Prereq: s is a string.\r\nvar escapeForRegexp = function(s) {\r\n return s.replace(/([-()\\[\\]{}+?*.$\\^|,:#= 0)\r\n array.splice(index, 1);\r\n return value;\r\n}\r\n\r\n/**\r\n * @ngdoc function\r\n * @name angular.copy\r\n * @module ng\r\n * @kind function\r\n *\r\n * @description\r\n * Creates a deep copy of `source`, which should be an object or an array.\r\n *\r\n * * If no destination is supplied, a copy of the object or array is created.\r\n * * If a destination is provided, all of its elements (for arrays) or properties (for objects)\r\n * are deleted and then all elements/properties from the source are copied to it.\r\n * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.\r\n * * If `source` is identical to 'destination' an exception will be thrown.\r\n *\r\n * @param {*} source The source that will be used to make a copy.\r\n * Can be any type, including primitives, `null`, and `undefined`.\r\n * @param {(Object|Array)=} destination Destination into which the source is copied. If\r\n * provided, must be of the same type as `source`.\r\n * @returns {*} The copy or updated `destination`, if `destination` was specified.\r\n *\r\n * @example\r\n \r\n \r\n
    \r\n
    \r\n Name:
    \r\n E-mail:
    \r\n Gender: male\r\n female
    \r\n \r\n \r\n
    \r\n
    form = {{user | json}}
    \r\n
    master = {{master | json}}
    \r\n
    \r\n\r\n \r\n
    \r\n
    \r\n */\r\nfunction copy(source, destination, stackSource, stackDest) {\r\n if (isWindow(source) || isScope(source)) {\r\n throw ngMinErr('cpws',\r\n \"Can't copy! Making copies of Window or Scope instances is not supported.\");\r\n }\r\n\r\n if (!destination) {\r\n destination = source;\r\n if (source) {\r\n if (isArray(source)) {\r\n destination = copy(source, [], stackSource, stackDest);\r\n } else if (isDate(source)) {\r\n destination = new Date(source.getTime());\r\n } else if (isRegExp(source)) {\r\n destination = new RegExp(source.source, source.toString().match(/[^\\/]*$/)[0]);\r\n destination.lastIndex = source.lastIndex;\r\n } else if (isObject(source)) {\r\n var emptyObject = Object.create(Object.getPrototypeOf(source));\r\n destination = copy(source, emptyObject, stackSource, stackDest);\r\n }\r\n }\r\n } else {\r\n if (source === destination) throw ngMinErr('cpi',\r\n \"Can't copy! Source and destination are identical.\");\r\n\r\n stackSource = stackSource || [];\r\n stackDest = stackDest || [];\r\n\r\n if (isObject(source)) {\r\n var index = stackSource.indexOf(source);\r\n if (index !== -1) return stackDest[index];\r\n\r\n stackSource.push(source);\r\n stackDest.push(destination);\r\n }\r\n\r\n var result;\r\n if (isArray(source)) {\r\n destination.length = 0;\r\n for (var i = 0; i < source.length; i++) {\r\n result = copy(source[i], null, stackSource, stackDest);\r\n if (isObject(source[i])) {\r\n stackSource.push(source[i]);\r\n stackDest.push(result);\r\n }\r\n destination.push(result);\r\n }\r\n } else {\r\n var h = destination.$$hashKey;\r\n if (isArray(destination)) {\r\n destination.length = 0;\r\n } else {\r\n forEach(destination, function(value, key) {\r\n delete destination[key];\r\n });\r\n }\r\n for (var key in source) {\r\n if (source.hasOwnProperty(key)) {\r\n result = copy(source[key], null, stackSource, stackDest);\r\n if (isObject(source[key])) {\r\n stackSource.push(source[key]);\r\n stackDest.push(result);\r\n }\r\n destination[key] = result;\r\n }\r\n }\r\n setHashKey(destination,h);\r\n }\r\n\r\n }\r\n return destination;\r\n}\r\n\r\n/**\r\n * Creates a shallow copy of an object, an array or a primitive.\r\n *\r\n * Assumes that there are no proto properties for objects.\r\n */\r\nfunction shallowCopy(src, dst) {\r\n if (isArray(src)) {\r\n dst = dst || [];\r\n\r\n for (var i = 0, ii = src.length; i < ii; i++) {\r\n dst[i] = src[i];\r\n }\r\n } else if (isObject(src)) {\r\n dst = dst || {};\r\n\r\n for (var key in src) {\r\n if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {\r\n dst[key] = src[key];\r\n }\r\n }\r\n }\r\n\r\n return dst || src;\r\n}\r\n\r\n\r\n/**\r\n * @ngdoc function\r\n * @name angular.equals\r\n * @module ng\r\n * @kind function\r\n *\r\n * @description\r\n * Determines if two objects or two values are equivalent. Supports value types, regular\r\n * expressions, arrays and objects.\r\n *\r\n * Two objects or values are considered equivalent if at least one of the following is true:\r\n *\r\n * * Both objects or values pass `===` comparison.\r\n * * Both objects or values are of the same type and all of their properties are equal by\r\n * comparing them with `angular.equals`.\r\n * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)\r\n * * Both values represent the same regular expression (In JavaScript,\r\n * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual\r\n * representation matches).\r\n *\r\n * During a property comparison, properties of `function` type and properties with names\r\n * that begin with `$` are ignored.\r\n *\r\n * Scope and DOMWindow objects are being compared only by identify (`===`).\r\n *\r\n * @param {*} o1 Object or value to compare.\r\n * @param {*} o2 Object or value to compare.\r\n * @returns {boolean} True if arguments are equal.\r\n */\r\nfunction equals(o1, o2) {\r\n if (o1 === o2) return true;\r\n if (o1 === null || o2 === null) return false;\r\n if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN\r\n var t1 = typeof o1, t2 = typeof o2, length, key, keySet;\r\n if (t1 == t2) {\r\n if (t1 == 'object') {\r\n if (isArray(o1)) {\r\n if (!isArray(o2)) return false;\r\n if ((length = o1.length) == o2.length) {\r\n for (key = 0; key < length; key++) {\r\n if (!equals(o1[key], o2[key])) return false;\r\n }\r\n return true;\r\n }\r\n } else if (isDate(o1)) {\r\n if (!isDate(o2)) return false;\r\n return equals(o1.getTime(), o2.getTime());\r\n } else if (isRegExp(o1)) {\r\n return isRegExp(o2) ? o1.toString() == o2.toString() : false;\r\n } else {\r\n if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||\r\n isArray(o2) || isDate(o2) || isRegExp(o2)) return false;\r\n keySet = {};\r\n for (key in o1) {\r\n if (key.charAt(0) === '$' || isFunction(o1[key])) continue;\r\n if (!equals(o1[key], o2[key])) return false;\r\n keySet[key] = true;\r\n }\r\n for (key in o2) {\r\n if (!keySet.hasOwnProperty(key) &&\r\n key.charAt(0) !== '$' &&\r\n o2[key] !== undefined &&\r\n !isFunction(o2[key])) return false;\r\n }\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n}\r\n\r\nvar csp = function() {\r\n if (isDefined(csp.isActive_)) return csp.isActive_;\r\n\r\n var active = !!(document.querySelector('[ng-csp]') ||\r\n document.querySelector('[data-ng-csp]'));\r\n\r\n if (!active) {\r\n try {\r\n /* jshint -W031, -W054 */\r\n new Function('');\r\n /* jshint +W031, +W054 */\r\n } catch (e) {\r\n active = true;\r\n }\r\n }\r\n\r\n return (csp.isActive_ = active);\r\n};\r\n\r\n\r\n\r\nfunction concat(array1, array2, index) {\r\n return array1.concat(slice.call(array2, index));\r\n}\r\n\r\nfunction sliceArgs(args, startIndex) {\r\n return slice.call(args, startIndex || 0);\r\n}\r\n\r\n\r\n/* jshint -W101 */\r\n/**\r\n * @ngdoc function\r\n * @name angular.bind\r\n * @module ng\r\n * @kind function\r\n *\r\n * @description\r\n * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for\r\n * `fn`). You can supply optional `args` that are prebound to the function. This feature is also\r\n * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as\r\n * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).\r\n *\r\n * @param {Object} self Context which `fn` should be evaluated in.\r\n * @param {function()} fn Function to be bound.\r\n * @param {...*} args Optional arguments to be prebound to the `fn` function call.\r\n * @returns {function()} Function that wraps the `fn` with all the specified bindings.\r\n */\r\n/* jshint +W101 */\r\nfunction bind(self, fn) {\r\n var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];\r\n if (isFunction(fn) && !(fn instanceof RegExp)) {\r\n return curryArgs.length\r\n ? function() {\r\n return arguments.length\r\n ? fn.apply(self, concat(curryArgs, arguments, 0))\r\n : fn.apply(self, curryArgs);\r\n }\r\n : function() {\r\n return arguments.length\r\n ? fn.apply(self, arguments)\r\n : fn.call(self);\r\n };\r\n } else {\r\n // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)\r\n return fn;\r\n }\r\n}\r\n\r\n\r\nfunction toJsonReplacer(key, value) {\r\n var val = value;\r\n\r\n if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {\r\n val = undefined;\r\n } else if (isWindow(value)) {\r\n val = '$WINDOW';\r\n } else if (value && document === value) {\r\n val = '$DOCUMENT';\r\n } else if (isScope(value)) {\r\n val = '$SCOPE';\r\n }\r\n\r\n return val;\r\n}\r\n\r\n\r\n/**\r\n * @ngdoc function\r\n * @name angular.toJson\r\n * @module ng\r\n * @kind function\r\n *\r\n * @description\r\n * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be\r\n * stripped since angular uses this notation internally.\r\n *\r\n * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.\r\n * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.\r\n * If set to an integer, the JSON output will contain that many spaces per indentation.\r\n * @returns {string|undefined} JSON-ified string representing `obj`.\r\n */\r\nfunction toJson(obj, pretty) {\r\n if (typeof obj === 'undefined') return undefined;\r\n if (!isNumber(pretty)) {\r\n pretty = pretty ? 2 : null;\r\n }\r\n return JSON.stringify(obj, toJsonReplacer, pretty);\r\n}\r\n\r\n\r\n/**\r\n * @ngdoc function\r\n * @name angular.fromJson\r\n * @module ng\r\n * @kind function\r\n *\r\n * @description\r\n * Deserializes a JSON string.\r\n *\r\n * @param {string} json JSON string to deserialize.\r\n * @returns {Object|Array|string|number} Deserialized JSON string.\r\n */\r\nfunction fromJson(json) {\r\n return isString(json)\r\n ? JSON.parse(json)\r\n : json;\r\n}\r\n\r\n\r\n/**\r\n * @returns {string} Returns the string representation of the element.\r\n */\r\nfunction startingTag(element) {\r\n element = jqLite(element).clone();\r\n try {\r\n // turns out IE does not let you set .html() on elements which\r\n // are not allowed to have children. So we just ignore it.\r\n element.empty();\r\n } catch (e) {}\r\n var elemHtml = jqLite('
    ').append(element).html();\r\n try {\r\n return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :\r\n elemHtml.\r\n match(/^(<[^>]+>)/)[1].\r\n replace(/^<([\\w\\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });\r\n } catch (e) {\r\n return lowercase(elemHtml);\r\n }\r\n\r\n}\r\n\r\n\r\n/////////////////////////////////////////////////\r\n\r\n/**\r\n * Tries to decode the URI component without throwing an exception.\r\n *\r\n * @private\r\n * @param str value potential URI component to check.\r\n * @returns {boolean} True if `value` can be decoded\r\n * with the decodeURIComponent function.\r\n */\r\nfunction tryDecodeURIComponent(value) {\r\n try {\r\n return decodeURIComponent(value);\r\n } catch (e) {\r\n // Ignore any invalid uri component\r\n }\r\n}\r\n\r\n\r\n/**\r\n * Parses an escaped url query string into key-value pairs.\r\n * @returns {Object.}\r\n */\r\nfunction parseKeyValue(/**string*/keyValue) {\r\n var obj = {}, key_value, key;\r\n forEach((keyValue || \"\").split('&'), function(keyValue) {\r\n if (keyValue) {\r\n key_value = keyValue.replace(/\\+/g,'%20').split('=');\r\n key = tryDecodeURIComponent(key_value[0]);\r\n if (isDefined(key)) {\r\n var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;\r\n if (!hasOwnProperty.call(obj, key)) {\r\n obj[key] = val;\r\n } else if (isArray(obj[key])) {\r\n obj[key].push(val);\r\n } else {\r\n obj[key] = [obj[key],val];\r\n }\r\n }\r\n }\r\n });\r\n return obj;\r\n}\r\n\r\nfunction toKeyValue(obj) {\r\n var parts = [];\r\n forEach(obj, function(value, key) {\r\n if (isArray(value)) {\r\n forEach(value, function(arrayValue) {\r\n parts.push(encodeUriQuery(key, true) +\r\n (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));\r\n });\r\n } else {\r\n parts.push(encodeUriQuery(key, true) +\r\n (value === true ? '' : '=' + encodeUriQuery(value, true)));\r\n }\r\n });\r\n return parts.length ? parts.join('&') : '';\r\n}\r\n\r\n\r\n/**\r\n * We need our custom method because encodeURIComponent is too aggressive and doesn't follow\r\n * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path\r\n * segments:\r\n * segment = *pchar\r\n * pchar = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\r\n * pct-encoded = \"%\" HEXDIG HEXDIG\r\n * unreserved = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\r\n * sub-delims = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\"\r\n * / \"*\" / \"+\" / \",\" / \";\" / \"=\"\r\n */\r\nfunction encodeUriSegment(val) {\r\n return encodeUriQuery(val, true).\r\n replace(/%26/gi, '&').\r\n replace(/%3D/gi, '=').\r\n replace(/%2B/gi, '+');\r\n}\r\n\r\n\r\n/**\r\n * This method is intended for encoding *key* or *value* parts of query component. We need a custom\r\n * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be\r\n * encoded per http://tools.ietf.org/html/rfc3986:\r\n * query = *( pchar / \"/\" / \"?\" )\r\n * pchar = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\r\n * unreserved = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\r\n * pct-encoded = \"%\" HEXDIG HEXDIG\r\n * sub-delims = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\"\r\n * / \"*\" / \"+\" / \",\" / \";\" / \"=\"\r\n */\r\nfunction encodeUriQuery(val, pctEncodeSpaces) {\r\n return encodeURIComponent(val).\r\n replace(/%40/gi, '@').\r\n replace(/%3A/gi, ':').\r\n replace(/%24/g, '$').\r\n replace(/%2C/gi, ',').\r\n replace(/%3B/gi, ';').\r\n replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));\r\n}\r\n\r\nvar ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];\r\n\r\nfunction getNgAttribute(element, ngAttr) {\r\n var attr, i, ii = ngAttrPrefixes.length;\r\n element = jqLite(element);\r\n for (i = 0; i < ii; ++i) {\r\n attr = ngAttrPrefixes[i] + ngAttr;\r\n if (isString(attr = element.attr(attr))) {\r\n return attr;\r\n }\r\n }\r\n return null;\r\n}\r\n\r\n/**\r\n * @ngdoc directive\r\n * @name ngApp\r\n * @module ng\r\n *\r\n * @element ANY\r\n * @param {angular.Module} ngApp an optional application\r\n * {@link angular.module module} name to load.\r\n * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be\r\n * created in \"strict-di\" mode. This means that the application will fail to invoke functions which\r\n * do not use explicit function annotation (and are thus unsuitable for minification), as described\r\n * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in\r\n * tracking down the root of these bugs.\r\n *\r\n * @description\r\n *\r\n * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive\r\n * designates the **root element** of the application and is typically placed near the root element\r\n * of the page - e.g. on the `` or `` tags.\r\n *\r\n * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`\r\n * found in the document will be used to define the root element to auto-bootstrap as an\r\n * application. To run multiple applications in an HTML document you must manually bootstrap them using\r\n * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.\r\n *\r\n * You can specify an **AngularJS module** to be used as the root module for the application. This\r\n * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It\r\n * should contain the application code needed or have dependencies on other modules that will\r\n * contain the code. See {@link angular.module} for more information.\r\n *\r\n * In the example below if the `ngApp` directive were not placed on the `html` element then the\r\n * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`\r\n * would not be resolved to `3`.\r\n *\r\n * `ngApp` is the easiest, and most common way to bootstrap an application.\r\n *\r\n \r\n \r\n
    \r\n I can add: {{a}} + {{b}} = {{ a+b }}\r\n
    \r\n
    \r\n \r\n angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {\r\n $scope.a = 1;\r\n $scope.b = 2;\r\n });\r\n \r\n
    \r\n *\r\n * Using `ngStrictDi`, you would see something like this:\r\n *\r\n \r\n \r\n
    \r\n
    \r\n I can add: {{a}} + {{b}} = {{ a+b }}\r\n\r\n

    This renders because the controller does not fail to\r\n instantiate, by using explicit annotation style (see\r\n script.js for details)\r\n

    \r\n
    \r\n\r\n
    \r\n Name:
    \r\n Hello, {{name}}!\r\n\r\n

    This renders because the controller does not fail to\r\n instantiate, by using explicit annotation style\r\n (see script.js for details)\r\n

    \r\n
    \r\n\r\n
    \r\n I can add: {{a}} + {{b}} = {{ a+b }}\r\n\r\n

    The controller could not be instantiated, due to relying\r\n on automatic function annotations (which are disabled in\r\n strict mode). As such, the content of this section is not\r\n interpolated, and there should be an error in your web console.\r\n

    \r\n
    \r\n
    \r\n
    \r\n \r\n angular.module('ngAppStrictDemo', [])\r\n // BadController will fail to instantiate, due to relying on automatic function annotation,\r\n // rather than an explicit annotation\r\n .controller('BadController', function($scope) {\r\n $scope.a = 1;\r\n $scope.b = 2;\r\n })\r\n // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,\r\n // due to using explicit annotations using the array style and $inject property, respectively.\r\n .controller('GoodController1', ['$scope', function($scope) {\r\n $scope.a = 1;\r\n $scope.b = 2;\r\n }])\r\n .controller('GoodController2', GoodController2);\r\n function GoodController2($scope) {\r\n $scope.name = \"World\";\r\n }\r\n GoodController2.$inject = ['$scope'];\r\n \r\n \r\n div[ng-controller] {\r\n margin-bottom: 1em;\r\n -webkit-border-radius: 4px;\r\n border-radius: 4px;\r\n border: 1px solid;\r\n padding: .5em;\r\n }\r\n div[ng-controller^=Good] {\r\n border-color: #d6e9c6;\r\n background-color: #dff0d8;\r\n color: #3c763d;\r\n }\r\n div[ng-controller^=Bad] {\r\n border-color: #ebccd1;\r\n background-color: #f2dede;\r\n color: #a94442;\r\n margin-bottom: 0;\r\n }\r\n \r\n
    \r\n */\r\nfunction angularInit(element, bootstrap) {\r\n var appElement,\r\n module,\r\n config = {};\r\n\r\n // The element `element` has priority over any other element\r\n forEach(ngAttrPrefixes, function(prefix) {\r\n var name = prefix + 'app';\r\n\r\n if (!appElement && element.hasAttribute && element.hasAttribute(name)) {\r\n appElement = element;\r\n module = element.getAttribute(name);\r\n }\r\n });\r\n forEach(ngAttrPrefixes, function(prefix) {\r\n var name = prefix + 'app';\r\n var candidate;\r\n\r\n if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\\\:') + ']'))) {\r\n appElement = candidate;\r\n module = candidate.getAttribute(name);\r\n }\r\n });\r\n if (appElement) {\r\n config.strictDi = getNgAttribute(appElement, \"strict-di\") !== null;\r\n bootstrap(appElement, module ? [module] : [], config);\r\n }\r\n}\r\n\r\n/**\r\n * @ngdoc function\r\n * @name angular.bootstrap\r\n * @module ng\r\n * @description\r\n * Use this function to manually start up angular application.\r\n *\r\n * See: {@link guide/bootstrap Bootstrap}\r\n *\r\n * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.\r\n * They must use {@link ng.directive:ngApp ngApp}.\r\n *\r\n * Angular will detect if it has been loaded into the browser more than once and only allow the\r\n * first loaded script to be bootstrapped and will report a warning to the browser console for\r\n * each of the subsequent scripts. This prevents strange results in applications, where otherwise\r\n * multiple instances of Angular try to work on the DOM.\r\n *\r\n * ```html\r\n * \r\n * \r\n * \r\n *
    \r\n * {{greeting}}\r\n *
    \r\n *\r\n * \r\n * \r\n * \r\n * \r\n * ```\r\n *\r\n * @param {DOMElement} element DOM element which is the root of angular application.\r\n * @param {Array=} modules an array of modules to load into the application.\r\n * Each item in the array should be the name of a predefined module or a (DI annotated)\r\n * function that will be invoked by the injector as a `config` block.\r\n * See: {@link angular.module modules}\r\n * @param {Object=} config an object for defining configuration options for the application. The\r\n * following keys are supported:\r\n *\r\n * * `strictDi` - disable automatic function annotation for the application. This is meant to\r\n * assist in finding bugs which break minified code. Defaults to `false`.\r\n *\r\n * @returns {auto.$injector} Returns the newly created injector for this app.\r\n */\r\nfunction bootstrap(element, modules, config) {\r\n if (!isObject(config)) config = {};\r\n var defaultConfig = {\r\n strictDi: false\r\n };\r\n config = extend(defaultConfig, config);\r\n var doBootstrap = function() {\r\n element = jqLite(element);\r\n\r\n if (element.injector()) {\r\n var tag = (element[0] === document) ? 'document' : startingTag(element);\r\n //Encode angle brackets to prevent input from being sanitized to empty string #8683\r\n throw ngMinErr(\r\n 'btstrpd',\r\n \"App Already Bootstrapped with this Element '{0}'\",\r\n tag.replace(//,'>'));\r\n }\r\n\r\n modules = modules || [];\r\n modules.unshift(['$provide', function($provide) {\r\n $provide.value('$rootElement', element);\r\n }]);\r\n\r\n if (config.debugInfoEnabled) {\r\n // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.\r\n modules.push(['$compileProvider', function($compileProvider) {\r\n $compileProvider.debugInfoEnabled(true);\r\n }]);\r\n }\r\n\r\n modules.unshift('ng');\r\n var injector = createInjector(modules, config.strictDi);\r\n injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',\r\n function bootstrapApply(scope, element, compile, injector) {\r\n scope.$apply(function() {\r\n element.data('$injector', injector);\r\n compile(element)(scope);\r\n });\r\n }]\r\n );\r\n return injector;\r\n };\r\n\r\n var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;\r\n var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;\r\n\r\n if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {\r\n config.debugInfoEnabled = true;\r\n window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');\r\n }\r\n\r\n if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {\r\n return doBootstrap();\r\n }\r\n\r\n window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');\r\n angular.resumeBootstrap = function(extraModules) {\r\n forEach(extraModules, function(module) {\r\n modules.push(module);\r\n });\r\n return doBootstrap();\r\n };\r\n\r\n if (isFunction(angular.resumeDeferredBootstrap)) {\r\n angular.resumeDeferredBootstrap();\r\n }\r\n}\r\n\r\n/**\r\n * @ngdoc function\r\n * @name angular.reloadWithDebugInfo\r\n * @module ng\r\n * @description\r\n * Use this function to reload the current application with debug information turned on.\r\n * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.\r\n *\r\n * See {@link ng.$compileProvider#debugInfoEnabled} for more.\r\n */\r\nfunction reloadWithDebugInfo() {\r\n window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;\r\n window.location.reload();\r\n}\r\n\r\n/**\r\n * @name angular.getTestability\r\n * @module ng\r\n * @description\r\n * Get the testability service for the instance of Angular on the given\r\n * element.\r\n * @param {DOMElement} element DOM element which is the root of angular application.\r\n */\r\nfunction getTestability(rootElement) {\r\n var injector = angular.element(rootElement).injector();\r\n if (!injector) {\r\n throw ngMinErr('test',\r\n 'no injector found for element argument to getTestability');\r\n }\r\n return injector.get('$$testability');\r\n}\r\n\r\nvar SNAKE_CASE_REGEXP = /[A-Z]/g;\r\nfunction snake_case(name, separator) {\r\n separator = separator || '_';\r\n return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {\r\n return (pos ? separator : '') + letter.toLowerCase();\r\n });\r\n}\r\n\r\nvar bindJQueryFired = false;\r\nvar skipDestroyOnNextJQueryCleanData;\r\nfunction bindJQuery() {\r\n var originalCleanData;\r\n\r\n if (bindJQueryFired) {\r\n return;\r\n }\r\n\r\n // bind to jQuery if present;\r\n jQuery = window.jQuery;\r\n // Use jQuery if it exists with proper functionality, otherwise default to us.\r\n // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.\r\n // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older\r\n // versions. It will not work for sure with jQuery <1.7, though.\r\n if (jQuery && jQuery.fn.on) {\r\n jqLite = jQuery;\r\n extend(jQuery.fn, {\r\n scope: JQLitePrototype.scope,\r\n isolateScope: JQLitePrototype.isolateScope,\r\n controller: JQLitePrototype.controller,\r\n injector: JQLitePrototype.injector,\r\n inheritedData: JQLitePrototype.inheritedData\r\n });\r\n\r\n // All nodes removed from the DOM via various jQuery APIs like .remove()\r\n // are passed through jQuery.cleanData. Monkey-patch this method to fire\r\n // the $destroy event on all removed nodes.\r\n originalCleanData = jQuery.cleanData;\r\n jQuery.cleanData = function(elems) {\r\n var events;\r\n if (!skipDestroyOnNextJQueryCleanData) {\r\n for (var i = 0, elem; (elem = elems[i]) != null; i++) {\r\n events = jQuery._data(elem, \"events\");\r\n if (events && events.$destroy) {\r\n jQuery(elem).triggerHandler('$destroy');\r\n }\r\n }\r\n } else {\r\n skipDestroyOnNextJQueryCleanData = false;\r\n }\r\n originalCleanData(elems);\r\n };\r\n } else {\r\n jqLite = JQLite;\r\n }\r\n\r\n angular.element = jqLite;\r\n\r\n // Prevent double-proxying.\r\n bindJQueryFired = true;\r\n}\r\n\r\n/**\r\n * throw error if the argument is falsy.\r\n */\r\nfunction assertArg(arg, name, reason) {\r\n if (!arg) {\r\n throw ngMinErr('areq', \"Argument '{0}' is {1}\", (name || '?'), (reason || \"required\"));\r\n }\r\n return arg;\r\n}\r\n\r\nfunction assertArgFn(arg, name, acceptArrayAnnotation) {\r\n if (acceptArrayAnnotation && isArray(arg)) {\r\n arg = arg[arg.length - 1];\r\n }\r\n\r\n assertArg(isFunction(arg), name, 'not a function, got ' +\r\n (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));\r\n return arg;\r\n}\r\n\r\n/**\r\n * throw error if the name given is hasOwnProperty\r\n * @param {String} name the name to test\r\n * @param {String} context the context in which the name is used, such as module or directive\r\n */\r\nfunction assertNotHasOwnProperty(name, context) {\r\n if (name === 'hasOwnProperty') {\r\n throw ngMinErr('badname', \"hasOwnProperty is not a valid {0} name\", context);\r\n }\r\n}\r\n\r\n/**\r\n * Return the value accessible from the object by path. Any undefined traversals are ignored\r\n * @param {Object} obj starting object\r\n * @param {String} path path to traverse\r\n * @param {boolean} [bindFnToScope=true]\r\n * @returns {Object} value as accessible by path\r\n */\r\n//TODO(misko): this function needs to be removed\r\nfunction getter(obj, path, bindFnToScope) {\r\n if (!path) return obj;\r\n var keys = path.split('.');\r\n var key;\r\n var lastInstance = obj;\r\n var len = keys.length;\r\n\r\n for (var i = 0; i < len; i++) {\r\n key = keys[i];\r\n if (obj) {\r\n obj = (lastInstance = obj)[key];\r\n }\r\n }\r\n if (!bindFnToScope && isFunction(obj)) {\r\n return bind(lastInstance, obj);\r\n }\r\n return obj;\r\n}\r\n\r\n/**\r\n * Return the DOM siblings between the first and last node in the given array.\r\n * @param {Array} array like object\r\n * @returns {jqLite} jqLite collection containing the nodes\r\n */\r\nfunction getBlockNodes(nodes) {\r\n // TODO(perf): just check if all items in `nodes` are siblings and if they are return the original\r\n // collection, otherwise update the original collection.\r\n var node = nodes[0];\r\n var endNode = nodes[nodes.length - 1];\r\n var blockNodes = [node];\r\n\r\n do {\r\n node = node.nextSibling;\r\n if (!node) break;\r\n blockNodes.push(node);\r\n } while (node !== endNode);\r\n\r\n return jqLite(blockNodes);\r\n}\r\n\r\n\r\n/**\r\n * Creates a new object without a prototype. This object is useful for lookup without having to\r\n * guard against prototypically inherited properties via hasOwnProperty.\r\n *\r\n * Related micro-benchmarks:\r\n * - http://jsperf.com/object-create2\r\n * - http://jsperf.com/proto-map-lookup/2\r\n * - http://jsperf.com/for-in-vs-object-keys2\r\n *\r\n * @returns {Object}\r\n */\r\nfunction createMap() {\r\n return Object.create(null);\r\n}\r\n\r\nvar NODE_TYPE_ELEMENT = 1;\r\nvar NODE_TYPE_ATTRIBUTE = 2;\r\nvar NODE_TYPE_TEXT = 3;\r\nvar NODE_TYPE_COMMENT = 8;\r\nvar NODE_TYPE_DOCUMENT = 9;\r\nvar NODE_TYPE_DOCUMENT_FRAGMENT = 11;\r\n\r\n/**\r\n * @ngdoc type\r\n * @name angular.Module\r\n * @module ng\r\n * @description\r\n *\r\n * Interface for configuring angular {@link angular.module modules}.\r\n */\r\n\r\nfunction setupModuleLoader(window) {\r\n\r\n var $injectorMinErr = minErr('$injector');\r\n var ngMinErr = minErr('ng');\r\n\r\n function ensure(obj, name, factory) {\r\n return obj[name] || (obj[name] = factory());\r\n }\r\n\r\n var angular = ensure(window, 'angular', Object);\r\n\r\n // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap\r\n angular.$$minErr = angular.$$minErr || minErr;\r\n\r\n return ensure(angular, 'module', function() {\r\n /** @type {Object.} */\r\n var modules = {};\r\n\r\n /**\r\n * @ngdoc function\r\n * @name angular.module\r\n * @module ng\r\n * @description\r\n *\r\n * The `angular.module` is a global place for creating, registering and retrieving Angular\r\n * modules.\r\n * All modules (angular core or 3rd party) that should be available to an application must be\r\n * registered using this mechanism.\r\n *\r\n * When passed two or more arguments, a new module is created. If passed only one argument, an\r\n * existing module (the name passed as the first argument to `module`) is retrieved.\r\n *\r\n *\r\n * # Module\r\n *\r\n * A module is a collection of services, directives, controllers, filters, and configuration information.\r\n * `angular.module` is used to configure the {@link auto.$injector $injector}.\r\n *\r\n * ```js\r\n * // Create a new module\r\n * var myModule = angular.module('myModule', []);\r\n *\r\n * // register a new service\r\n * myModule.value('appName', 'MyCoolApp');\r\n *\r\n * // configure existing services inside initialization blocks.\r\n * myModule.config(['$locationProvider', function($locationProvider) {\r\n * // Configure existing providers\r\n * $locationProvider.hashPrefix('!');\r\n * }]);\r\n * ```\r\n *\r\n * Then you can create an injector and load your modules like this:\r\n *\r\n * ```js\r\n * var injector = angular.injector(['ng', 'myModule'])\r\n * ```\r\n *\r\n * However it's more likely that you'll just use\r\n * {@link ng.directive:ngApp ngApp} or\r\n * {@link angular.bootstrap} to simplify this process for you.\r\n *\r\n * @param {!string} name The name of the module to create or retrieve.\r\n * @param {!Array.=} requires If specified then new module is being created. If\r\n * unspecified then the module is being retrieved for further configuration.\r\n * @param {Function=} configFn Optional configuration function for the module. Same as\r\n * {@link angular.Module#config Module#config()}.\r\n * @returns {module} new module with the {@link angular.Module} api.\r\n */\r\n return function module(name, requires, configFn) {\r\n var assertNotHasOwnProperty = function(name, context) {\r\n if (name === 'hasOwnProperty') {\r\n throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);\r\n }\r\n };\r\n\r\n assertNotHasOwnProperty(name, 'module');\r\n if (requires && modules.hasOwnProperty(name)) {\r\n modules[name] = null;\r\n }\r\n return ensure(modules, name, function() {\r\n if (!requires) {\r\n throw $injectorMinErr('nomod', \"Module '{0}' is not available! You either misspelled \" +\r\n \"the module name or forgot to load it. If registering a module ensure that you \" +\r\n \"specify the dependencies as the second argument.\", name);\r\n }\r\n\r\n /** @type {!Array.>} */\r\n var invokeQueue = [];\r\n\r\n /** @type {!Array.} */\r\n var configBlocks = [];\r\n\r\n /** @type {!Array.} */\r\n var runBlocks = [];\r\n\r\n var config = invokeLater('$injector', 'invoke', 'push', configBlocks);\r\n\r\n /** @type {angular.Module} */\r\n var moduleInstance = {\r\n // Private state\r\n _invokeQueue: invokeQueue,\r\n _configBlocks: configBlocks,\r\n _runBlocks: runBlocks,\r\n\r\n /**\r\n * @ngdoc property\r\n * @name angular.Module#requires\r\n * @module ng\r\n *\r\n * @description\r\n * Holds the list of modules which the injector will load before the current module is\r\n * loaded.\r\n */\r\n requires: requires,\r\n\r\n /**\r\n * @ngdoc property\r\n * @name angular.Module#name\r\n * @module ng\r\n *\r\n * @description\r\n * Name of the module.\r\n */\r\n name: name,\r\n\r\n\r\n /**\r\n * @ngdoc method\r\n * @name angular.Module#provider\r\n * @module ng\r\n * @param {string} name service name\r\n * @param {Function} providerType Construction function for creating new instance of the\r\n * service.\r\n * @description\r\n * See {@link auto.$provide#provider $provide.provider()}.\r\n */\r\n provider: invokeLater('$provide', 'provider'),\r\n\r\n /**\r\n * @ngdoc method\r\n * @name angular.Module#factory\r\n * @module ng\r\n * @param {string} name service name\r\n * @param {Function} providerFunction Function for creating new instance of the service.\r\n * @description\r\n * See {@link auto.$provide#factory $provide.factory()}.\r\n */\r\n factory: invokeLater('$provide', 'factory'),\r\n\r\n /**\r\n * @ngdoc method\r\n * @name angular.Module#service\r\n * @module ng\r\n * @param {string} name service name\r\n * @param {Function} constructor A constructor function that will be instantiated.\r\n * @description\r\n * See {@link auto.$provide#service $provide.service()}.\r\n */\r\n service: invokeLater('$provide', 'service'),\r\n\r\n /**\r\n * @ngdoc method\r\n * @name angular.Module#value\r\n * @module ng\r\n * @param {string} name service name\r\n * @param {*} object Service instance object.\r\n * @description\r\n * See {@link auto.$provide#value $provide.value()}.\r\n */\r\n value: invokeLater('$provide', 'value'),\r\n\r\n /**\r\n * @ngdoc method\r\n * @name angular.Module#constant\r\n * @module ng\r\n * @param {string} name constant name\r\n * @param {*} object Constant value.\r\n * @description\r\n * Because the constant are fixed, they get applied before other provide methods.\r\n * See {@link auto.$provide#constant $provide.constant()}.\r\n */\r\n constant: invokeLater('$provide', 'constant', 'unshift'),\r\n\r\n /**\r\n * @ngdoc method\r\n * @name angular.Module#animation\r\n * @module ng\r\n * @param {string} name animation name\r\n * @param {Function} animationFactory Factory function for creating new instance of an\r\n * animation.\r\n * @description\r\n *\r\n * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.\r\n *\r\n *\r\n * Defines an animation hook that can be later used with\r\n * {@link ngAnimate.$animate $animate} service and directives that use this service.\r\n *\r\n * ```js\r\n * module.animation('.animation-name', function($inject1, $inject2) {\r\n * return {\r\n * eventName : function(element, done) {\r\n * //code to run the animation\r\n * //once complete, then run done()\r\n * return function cancellationFunction(element) {\r\n * //code to cancel the animation\r\n * }\r\n * }\r\n * }\r\n * })\r\n * ```\r\n *\r\n * See {@link ng.$animateProvider#register $animateProvider.register()} and\r\n * {@link ngAnimate ngAnimate module} for more information.\r\n */\r\n animation: invokeLater('$animateProvider', 'register'),\r\n\r\n /**\r\n * @ngdoc method\r\n * @name angular.Module#filter\r\n * @module ng\r\n * @param {string} name Filter name - this must be a valid angular expression identifier\r\n * @param {Function} filterFactory Factory function for creating new instance of filter.\r\n * @description\r\n * See {@link ng.$filterProvider#register $filterProvider.register()}.\r\n *\r\n *
    \r\n * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.\r\n * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace\r\n * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores\r\n * (`myapp_subsection_filterx`).\r\n *
    \r\n */\r\n filter: invokeLater('$filterProvider', 'register'),\r\n\r\n /**\r\n * @ngdoc method\r\n * @name angular.Module#controller\r\n * @module ng\r\n * @param {string|Object} name Controller name, or an object map of controllers where the\r\n * keys are the names and the values are the constructors.\r\n * @param {Function} constructor Controller constructor function.\r\n * @description\r\n * See {@link ng.$controllerProvider#register $controllerProvider.register()}.\r\n */\r\n controller: invokeLater('$controllerProvider', 'register'),\r\n\r\n /**\r\n * @ngdoc method\r\n * @name angular.Module#directive\r\n * @module ng\r\n * @param {string|Object} name Directive name, or an object map of directives where the\r\n * keys are the names and the values are the factories.\r\n * @param {Function} directiveFactory Factory function for creating new instance of\r\n * directives.\r\n * @description\r\n * See {@link ng.$compileProvider#directive $compileProvider.directive()}.\r\n */\r\n directive: invokeLater('$compileProvider', 'directive'),\r\n\r\n /**\r\n * @ngdoc method\r\n * @name angular.Module#config\r\n * @module ng\r\n * @param {Function} configFn Execute this function on module load. Useful for service\r\n * configuration.\r\n * @description\r\n * Use this method to register work which needs to be performed on module loading.\r\n * For more about how to configure services, see\r\n * {@link providers#provider-recipe Provider Recipe}.\r\n */\r\n config: config,\r\n\r\n /**\r\n * @ngdoc method\r\n * @name angular.Module#run\r\n * @module ng\r\n * @param {Function} initializationFn Execute this function after injector creation.\r\n * Useful for application initialization.\r\n * @description\r\n * Use this method to register work which should be performed when the injector is done\r\n * loading all modules.\r\n */\r\n run: function(block) {\r\n runBlocks.push(block);\r\n return this;\r\n }\r\n };\r\n\r\n if (configFn) {\r\n config(configFn);\r\n }\r\n\r\n return moduleInstance;\r\n\r\n /**\r\n * @param {string} provider\r\n * @param {string} method\r\n * @param {String=} insertMethod\r\n * @returns {angular.Module}\r\n */\r\n function invokeLater(provider, method, insertMethod, queue) {\r\n if (!queue) queue = invokeQueue;\r\n return function() {\r\n queue[insertMethod || 'push']([provider, method, arguments]);\r\n return moduleInstance;\r\n };\r\n }\r\n });\r\n };\r\n });\r\n\r\n}\r\n\r\n/* global: toDebugString: true */\r\n\r\nfunction serializeObject(obj) {\r\n var seen = [];\r\n\r\n return JSON.stringify(obj, function(key, val) {\r\n val = toJsonReplacer(key, val);\r\n if (isObject(val)) {\r\n\r\n if (seen.indexOf(val) >= 0) return '<>';\r\n\r\n seen.push(val);\r\n }\r\n return val;\r\n });\r\n}\r\n\r\nfunction toDebugString(obj) {\r\n if (typeof obj === 'function') {\r\n return obj.toString().replace(/ \\{[\\s\\S]*$/, '');\r\n } else if (typeof obj === 'undefined') {\r\n return 'undefined';\r\n } else if (typeof obj !== 'string') {\r\n return serializeObject(obj);\r\n }\r\n return obj;\r\n}\r\n\r\n/* global angularModule: true,\r\n version: true,\r\n\r\n $LocaleProvider,\r\n $CompileProvider,\r\n\r\n htmlAnchorDirective,\r\n inputDirective,\r\n inputDirective,\r\n formDirective,\r\n scriptDirective,\r\n selectDirective,\r\n styleDirective,\r\n optionDirective,\r\n ngBindDirective,\r\n ngBindHtmlDirective,\r\n ngBindTemplateDirective,\r\n ngClassDirective,\r\n ngClassEvenDirective,\r\n ngClassOddDirective,\r\n ngCspDirective,\r\n ngCloakDirective,\r\n ngControllerDirective,\r\n ngFormDirective,\r\n ngHideDirective,\r\n ngIfDirective,\r\n ngIncludeDirective,\r\n ngIncludeFillContentDirective,\r\n ngInitDirective,\r\n ngNonBindableDirective,\r\n ngPluralizeDirective,\r\n ngRepeatDirective,\r\n ngShowDirective,\r\n ngStyleDirective,\r\n ngSwitchDirective,\r\n ngSwitchWhenDirective,\r\n ngSwitchDefaultDirective,\r\n ngOptionsDirective,\r\n ngTranscludeDirective,\r\n ngModelDirective,\r\n ngListDirective,\r\n ngChangeDirective,\r\n patternDirective,\r\n patternDirective,\r\n requiredDirective,\r\n requiredDirective,\r\n minlengthDirective,\r\n minlengthDirective,\r\n maxlengthDirective,\r\n maxlengthDirective,\r\n ngValueDirective,\r\n ngModelOptionsDirective,\r\n ngAttributeAliasDirectives,\r\n ngEventDirectives,\r\n\r\n $AnchorScrollProvider,\r\n $AnimateProvider,\r\n $BrowserProvider,\r\n $CacheFactoryProvider,\r\n $ControllerProvider,\r\n $DocumentProvider,\r\n $ExceptionHandlerProvider,\r\n $FilterProvider,\r\n $InterpolateProvider,\r\n $IntervalProvider,\r\n $HttpProvider,\r\n $HttpBackendProvider,\r\n $LocationProvider,\r\n $LogProvider,\r\n $ParseProvider,\r\n $RootScopeProvider,\r\n $QProvider,\r\n $$QProvider,\r\n $$SanitizeUriProvider,\r\n $SceProvider,\r\n $SceDelegateProvider,\r\n $SnifferProvider,\r\n $TemplateCacheProvider,\r\n $TemplateRequestProvider,\r\n $$TestabilityProvider,\r\n $TimeoutProvider,\r\n $$RAFProvider,\r\n $$AsyncCallbackProvider,\r\n $WindowProvider,\r\n $$jqLiteProvider\r\n*/\r\n\r\n\r\n/**\r\n * @ngdoc object\r\n * @name angular.version\r\n * @module ng\r\n * @description\r\n * An object that contains information about the current AngularJS version. This object has the\r\n * following properties:\r\n *\r\n * - `full` – `{string}` – Full version string, such as \"0.9.18\".\r\n * - `major` – `{number}` – Major version number, such as \"0\".\r\n * - `minor` – `{number}` – Minor version number, such as \"9\".\r\n * - `dot` – `{number}` – Dot version number, such as \"18\".\r\n * - `codeName` – `{string}` – Code name of the release, such as \"jiggling-armfat\".\r\n */\r\nvar version = {\r\n full: '1.3.18', // all of these placeholder strings will be replaced by grunt's\r\n major: 1, // package task\r\n minor: 3,\r\n dot: 18,\r\n codeName: 'collective-penmanship'\r\n};\r\n\r\n\r\nfunction publishExternalAPI(angular) {\r\n extend(angular, {\r\n 'bootstrap': bootstrap,\r\n 'copy': copy,\r\n 'extend': extend,\r\n 'equals': equals,\r\n 'element': jqLite,\r\n 'forEach': forEach,\r\n 'injector': createInjector,\r\n 'noop': noop,\r\n 'bind': bind,\r\n 'toJson': toJson,\r\n 'fromJson': fromJson,\r\n 'identity': identity,\r\n 'isUndefined': isUndefined,\r\n 'isDefined': isDefined,\r\n 'isString': isString,\r\n 'isFunction': isFunction,\r\n 'isObject': isObject,\r\n 'isNumber': isNumber,\r\n 'isElement': isElement,\r\n 'isArray': isArray,\r\n 'version': version,\r\n 'isDate': isDate,\r\n 'lowercase': lowercase,\r\n 'uppercase': uppercase,\r\n 'callbacks': {counter: 0},\r\n 'getTestability': getTestability,\r\n '$$minErr': minErr,\r\n '$$csp': csp,\r\n 'reloadWithDebugInfo': reloadWithDebugInfo\r\n });\r\n\r\n angularModule = setupModuleLoader(window);\r\n try {\r\n angularModule('ngLocale');\r\n } catch (e) {\r\n angularModule('ngLocale', []).provider('$locale', $LocaleProvider);\r\n }\r\n\r\n angularModule('ng', ['ngLocale'], ['$provide',\r\n function ngModule($provide) {\r\n // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.\r\n $provide.provider({\r\n $$sanitizeUri: $$SanitizeUriProvider\r\n });\r\n $provide.provider('$compile', $CompileProvider).\r\n directive({\r\n a: htmlAnchorDirective,\r\n input: inputDirective,\r\n textarea: inputDirective,\r\n form: formDirective,\r\n script: scriptDirective,\r\n select: selectDirective,\r\n style: styleDirective,\r\n option: optionDirective,\r\n ngBind: ngBindDirective,\r\n ngBindHtml: ngBindHtmlDirective,\r\n ngBindTemplate: ngBindTemplateDirective,\r\n ngClass: ngClassDirective,\r\n ngClassEven: ngClassEvenDirective,\r\n ngClassOdd: ngClassOddDirective,\r\n ngCloak: ngCloakDirective,\r\n ngController: ngControllerDirective,\r\n ngForm: ngFormDirective,\r\n ngHide: ngHideDirective,\r\n ngIf: ngIfDirective,\r\n ngInclude: ngIncludeDirective,\r\n ngInit: ngInitDirective,\r\n ngNonBindable: ngNonBindableDirective,\r\n ngPluralize: ngPluralizeDirective,\r\n ngRepeat: ngRepeatDirective,\r\n ngShow: ngShowDirective,\r\n ngStyle: ngStyleDirective,\r\n ngSwitch: ngSwitchDirective,\r\n ngSwitchWhen: ngSwitchWhenDirective,\r\n ngSwitchDefault: ngSwitchDefaultDirective,\r\n ngOptions: ngOptionsDirective,\r\n ngTransclude: ngTranscludeDirective,\r\n ngModel: ngModelDirective,\r\n ngList: ngListDirective,\r\n ngChange: ngChangeDirective,\r\n pattern: patternDirective,\r\n ngPattern: patternDirective,\r\n required: requiredDirective,\r\n ngRequired: requiredDirective,\r\n minlength: minlengthDirective,\r\n ngMinlength: minlengthDirective,\r\n maxlength: maxlengthDirective,\r\n ngMaxlength: maxlengthDirective,\r\n ngValue: ngValueDirective,\r\n ngModelOptions: ngModelOptionsDirective\r\n }).\r\n directive({\r\n ngInclude: ngIncludeFillContentDirective\r\n }).\r\n directive(ngAttributeAliasDirectives).\r\n directive(ngEventDirectives);\r\n $provide.provider({\r\n $anchorScroll: $AnchorScrollProvider,\r\n $animate: $AnimateProvider,\r\n $browser: $BrowserProvider,\r\n $cacheFactory: $CacheFactoryProvider,\r\n $controller: $ControllerProvider,\r\n $document: $DocumentProvider,\r\n $exceptionHandler: $ExceptionHandlerProvider,\r\n $filter: $FilterProvider,\r\n $interpolate: $InterpolateProvider,\r\n $interval: $IntervalProvider,\r\n $http: $HttpProvider,\r\n $httpBackend: $HttpBackendProvider,\r\n $location: $LocationProvider,\r\n $log: $LogProvider,\r\n $parse: $ParseProvider,\r\n $rootScope: $RootScopeProvider,\r\n $q: $QProvider,\r\n $$q: $$QProvider,\r\n $sce: $SceProvider,\r\n $sceDelegate: $SceDelegateProvider,\r\n $sniffer: $SnifferProvider,\r\n $templateCache: $TemplateCacheProvider,\r\n $templateRequest: $TemplateRequestProvider,\r\n $$testability: $$TestabilityProvider,\r\n $timeout: $TimeoutProvider,\r\n $window: $WindowProvider,\r\n $$rAF: $$RAFProvider,\r\n $$asyncCallback: $$AsyncCallbackProvider,\r\n $$jqLite: $$jqLiteProvider\r\n });\r\n }\r\n ]);\r\n}\r\n\r\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\r\n * Any commits to this file should be reviewed with security in mind. *\r\n * Changes to this file can potentially create security vulnerabilities. *\r\n * An approval from 2 Core members with history of modifying *\r\n * this file is required. *\r\n * *\r\n * Does the change somehow allow for arbitrary javascript to be executed? *\r\n * Or allows for someone to change the prototype of built-in objects? *\r\n * Or gives undesired access to variables likes document or window? *\r\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\r\n\r\n/* global JQLitePrototype: true,\r\n addEventListenerFn: true,\r\n removeEventListenerFn: true,\r\n BOOLEAN_ATTR: true,\r\n ALIASED_ATTR: true,\r\n*/\r\n\r\n//////////////////////////////////\r\n//JQLite\r\n//////////////////////////////////\r\n\r\n/**\r\n * @ngdoc function\r\n * @name angular.element\r\n * @module ng\r\n * @kind function\r\n *\r\n * @description\r\n * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.\r\n *\r\n * If jQuery is available, `angular.element` is an alias for the\r\n * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`\r\n * delegates to Angular's built-in subset of jQuery, called \"jQuery lite\" or \"jqLite.\"\r\n *\r\n *
    jqLite is a tiny, API-compatible subset of jQuery that allows\r\n * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most\r\n * commonly needed functionality with the goal of having a very small footprint.
    \r\n *\r\n * To use `jQuery`, simply ensure it is loaded before the `angular.js` file.\r\n *\r\n *
    **Note:** all element references in Angular are always wrapped with jQuery or\r\n * jqLite; they are never raw DOM references.
    \r\n *\r\n * ## Angular's jqLite\r\n * jqLite provides only the following jQuery methods:\r\n *\r\n * - [`addClass()`](http://api.jquery.com/addClass/)\r\n * - [`after()`](http://api.jquery.com/after/)\r\n * - [`append()`](http://api.jquery.com/append/)\r\n * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters\r\n * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData\r\n * - [`children()`](http://api.jquery.com/children/) - Does not support selectors\r\n * - [`clone()`](http://api.jquery.com/clone/)\r\n * - [`contents()`](http://api.jquery.com/contents/)\r\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'.\r\n * - [`data()`](http://api.jquery.com/data/)\r\n * - [`detach()`](http://api.jquery.com/detach/)\r\n * - [`empty()`](http://api.jquery.com/empty/)\r\n * - [`eq()`](http://api.jquery.com/eq/)\r\n * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name\r\n * - [`hasClass()`](http://api.jquery.com/hasClass/)\r\n * - [`html()`](http://api.jquery.com/html/)\r\n * - [`next()`](http://api.jquery.com/next/) - Does not support selectors\r\n * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData\r\n * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors\r\n * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors\r\n * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors\r\n * - [`prepend()`](http://api.jquery.com/prepend/)\r\n * - [`prop()`](http://api.jquery.com/prop/)\r\n * - [`ready()`](http://api.jquery.com/ready/)\r\n * - [`remove()`](http://api.jquery.com/remove/)\r\n * - [`removeAttr()`](http://api.jquery.com/removeAttr/)\r\n * - [`removeClass()`](http://api.jquery.com/removeClass/)\r\n * - [`removeData()`](http://api.jquery.com/removeData/)\r\n * - [`replaceWith()`](http://api.jquery.com/replaceWith/)\r\n * - [`text()`](http://api.jquery.com/text/)\r\n * - [`toggleClass()`](http://api.jquery.com/toggleClass/)\r\n * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.\r\n * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces\r\n * - [`val()`](http://api.jquery.com/val/)\r\n * - [`wrap()`](http://api.jquery.com/wrap/)\r\n *\r\n * ## jQuery/jqLite Extras\r\n * Angular also provides the following additional methods and events to both jQuery and jqLite:\r\n *\r\n * ### Events\r\n * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event\r\n * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM\r\n * element before it is removed.\r\n *\r\n * ### Methods\r\n * - `controller(name)` - retrieves the controller of the current element or its parent. By default\r\n * retrieves controller associated with the `ngController` directive. If `name` is provided as\r\n * camelCase directive name, then the controller for this directive will be retrieved (e.g.\r\n * `'ngModel'`).\r\n * - `injector()` - retrieves the injector of the current element or its parent.\r\n * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current\r\n * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to\r\n * be enabled.\r\n * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the\r\n * current element. This getter should be used only on elements that contain a directive which starts a new isolate\r\n * scope. Calling `scope()` on this element always returns the original non-isolate scope.\r\n * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.\r\n * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top\r\n * parent element is reached.\r\n *\r\n * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.\r\n * @returns {Object} jQuery object.\r\n */\r\n\r\nJQLite.expando = 'ng339';\r\n\r\nvar jqCache = JQLite.cache = {},\r\n jqId = 1,\r\n addEventListenerFn = function(element, type, fn) {\r\n element.addEventListener(type, fn, false);\r\n },\r\n removeEventListenerFn = function(element, type, fn) {\r\n element.removeEventListener(type, fn, false);\r\n };\r\n\r\n/*\r\n * !!! This is an undocumented \"private\" function !!!\r\n */\r\nJQLite._data = function(node) {\r\n //jQuery always returns an object on cache miss\r\n return this.cache[node[this.expando]] || {};\r\n};\r\n\r\nfunction jqNextId() { return ++jqId; }\r\n\r\n\r\nvar SPECIAL_CHARS_REGEXP = /([\\:\\-\\_]+(.))/g;\r\nvar MOZ_HACK_REGEXP = /^moz([A-Z])/;\r\nvar MOUSE_EVENT_MAP= { mouseleave: \"mouseout\", mouseenter: \"mouseover\"};\r\nvar jqLiteMinErr = minErr('jqLite');\r\n\r\n/**\r\n * Converts snake_case to camelCase.\r\n * Also there is special case for Moz prefix starting with upper case letter.\r\n * @param name Name to normalize\r\n */\r\nfunction camelCase(name) {\r\n return name.\r\n replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {\r\n return offset ? letter.toUpperCase() : letter;\r\n }).\r\n replace(MOZ_HACK_REGEXP, 'Moz$1');\r\n}\r\n\r\nvar SINGLE_TAG_REGEXP = /^<(\\w+)\\s*\\/?>(?:<\\/\\1>|)$/;\r\nvar HTML_REGEXP = /<|&#?\\w+;/;\r\nvar TAG_NAME_REGEXP = /<([\\w:]+)/;\r\nvar XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\\w:]+)[^>]*)\\/>/gi;\r\n\r\nvar wrapMap = {\r\n 'option': [1, ''],\r\n\r\n 'thead': [1, '', '
    '],\r\n 'col': [2, '', '
    '],\r\n 'tr': [2, '', '
    '],\r\n 'td': [3, '', '
    '],\r\n '_default': [0, \"\", \"\"]\r\n};\r\n\r\nwrapMap.optgroup = wrapMap.option;\r\nwrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;\r\nwrapMap.th = wrapMap.td;\r\n\r\n\r\nfunction jqLiteIsTextNode(html) {\r\n return !HTML_REGEXP.test(html);\r\n}\r\n\r\nfunction jqLiteAcceptsData(node) {\r\n // The window object can accept data but has no nodeType\r\n // Otherwise we are only interested in elements (1) and documents (9)\r\n var nodeType = node.nodeType;\r\n return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;\r\n}\r\n\r\nfunction jqLiteBuildFragment(html, context) {\r\n var tmp, tag, wrap,\r\n fragment = context.createDocumentFragment(),\r\n nodes = [], i;\r\n\r\n if (jqLiteIsTextNode(html)) {\r\n // Convert non-html into a text node\r\n nodes.push(context.createTextNode(html));\r\n } else {\r\n // Convert html into DOM nodes\r\n tmp = tmp || fragment.appendChild(context.createElement(\"div\"));\r\n tag = (TAG_NAME_REGEXP.exec(html) || [\"\", \"\"])[1].toLowerCase();\r\n wrap = wrapMap[tag] || wrapMap._default;\r\n tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, \"<$1>\") + wrap[2];\r\n\r\n // Descend through wrappers to the right content\r\n i = wrap[0];\r\n while (i--) {\r\n tmp = tmp.lastChild;\r\n }\r\n\r\n nodes = concat(nodes, tmp.childNodes);\r\n\r\n tmp = fragment.firstChild;\r\n tmp.textContent = \"\";\r\n }\r\n\r\n // Remove wrapper from fragment\r\n fragment.textContent = \"\";\r\n fragment.innerHTML = \"\"; // Clear inner HTML\r\n forEach(nodes, function(node) {\r\n fragment.appendChild(node);\r\n });\r\n\r\n return fragment;\r\n}\r\n\r\nfunction jqLiteParseHTML(html, context) {\r\n context = context || document;\r\n var parsed;\r\n\r\n if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {\r\n return [context.createElement(parsed[1])];\r\n }\r\n\r\n if ((parsed = jqLiteBuildFragment(html, context))) {\r\n return parsed.childNodes;\r\n }\r\n\r\n return [];\r\n}\r\n\r\n/////////////////////////////////////////////\r\nfunction JQLite(element) {\r\n if (element instanceof JQLite) {\r\n return element;\r\n }\r\n\r\n var argIsString;\r\n\r\n if (isString(element)) {\r\n element = trim(element);\r\n argIsString = true;\r\n }\r\n if (!(this instanceof JQLite)) {\r\n if (argIsString && element.charAt(0) != '<') {\r\n throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');\r\n }\r\n return new JQLite(element);\r\n }\r\n\r\n if (argIsString) {\r\n jqLiteAddNodes(this, jqLiteParseHTML(element));\r\n } else {\r\n jqLiteAddNodes(this, element);\r\n }\r\n}\r\n\r\nfunction jqLiteClone(element) {\r\n return element.cloneNode(true);\r\n}\r\n\r\nfunction jqLiteDealoc(element, onlyDescendants) {\r\n if (!onlyDescendants) jqLiteRemoveData(element);\r\n\r\n if (element.querySelectorAll) {\r\n var descendants = element.querySelectorAll('*');\r\n for (var i = 0, l = descendants.length; i < l; i++) {\r\n jqLiteRemoveData(descendants[i]);\r\n }\r\n }\r\n}\r\n\r\nfunction jqLiteOff(element, type, fn, unsupported) {\r\n if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');\r\n\r\n var expandoStore = jqLiteExpandoStore(element);\r\n var events = expandoStore && expandoStore.events;\r\n var handle = expandoStore && expandoStore.handle;\r\n\r\n if (!handle) return; //no listeners registered\r\n\r\n if (!type) {\r\n for (type in events) {\r\n if (type !== '$destroy') {\r\n removeEventListenerFn(element, type, handle);\r\n }\r\n delete events[type];\r\n }\r\n } else {\r\n forEach(type.split(' '), function(type) {\r\n if (isDefined(fn)) {\r\n var listenerFns = events[type];\r\n arrayRemove(listenerFns || [], fn);\r\n if (listenerFns && listenerFns.length > 0) {\r\n return;\r\n }\r\n }\r\n\r\n removeEventListenerFn(element, type, handle);\r\n delete events[type];\r\n });\r\n }\r\n}\r\n\r\nfunction jqLiteRemoveData(element, name) {\r\n var expandoId = element.ng339;\r\n var expandoStore = expandoId && jqCache[expandoId];\r\n\r\n if (expandoStore) {\r\n if (name) {\r\n delete expandoStore.data[name];\r\n return;\r\n }\r\n\r\n if (expandoStore.handle) {\r\n if (expandoStore.events.$destroy) {\r\n expandoStore.handle({}, '$destroy');\r\n }\r\n jqLiteOff(element);\r\n }\r\n delete jqCache[expandoId];\r\n element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it\r\n }\r\n}\r\n\r\n\r\nfunction jqLiteExpandoStore(element, createIfNecessary) {\r\n var expandoId = element.ng339,\r\n expandoStore = expandoId && jqCache[expandoId];\r\n\r\n if (createIfNecessary && !expandoStore) {\r\n element.ng339 = expandoId = jqNextId();\r\n expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};\r\n }\r\n\r\n return expandoStore;\r\n}\r\n\r\n\r\nfunction jqLiteData(element, key, value) {\r\n if (jqLiteAcceptsData(element)) {\r\n\r\n var isSimpleSetter = isDefined(value);\r\n var isSimpleGetter = !isSimpleSetter && key && !isObject(key);\r\n var massGetter = !key;\r\n var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);\r\n var data = expandoStore && expandoStore.data;\r\n\r\n if (isSimpleSetter) { // data('key', value)\r\n data[key] = value;\r\n } else {\r\n if (massGetter) { // data()\r\n return data;\r\n } else {\r\n if (isSimpleGetter) { // data('key')\r\n // don't force creation of expandoStore if it doesn't exist yet\r\n return data && data[key];\r\n } else { // mass-setter: data({key1: val1, key2: val2})\r\n extend(data, key);\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\nfunction jqLiteHasClass(element, selector) {\r\n if (!element.getAttribute) return false;\r\n return ((\" \" + (element.getAttribute('class') || '') + \" \").replace(/[\\n\\t]/g, \" \").\r\n indexOf(\" \" + selector + \" \") > -1);\r\n}\r\n\r\nfunction jqLiteRemoveClass(element, cssClasses) {\r\n if (cssClasses && element.setAttribute) {\r\n forEach(cssClasses.split(' '), function(cssClass) {\r\n element.setAttribute('class', trim(\r\n (\" \" + (element.getAttribute('class') || '') + \" \")\r\n .replace(/[\\n\\t]/g, \" \")\r\n .replace(\" \" + trim(cssClass) + \" \", \" \"))\r\n );\r\n });\r\n }\r\n}\r\n\r\nfunction jqLiteAddClass(element, cssClasses) {\r\n if (cssClasses && element.setAttribute) {\r\n var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')\r\n .replace(/[\\n\\t]/g, \" \");\r\n\r\n forEach(cssClasses.split(' '), function(cssClass) {\r\n cssClass = trim(cssClass);\r\n if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {\r\n existingClasses += cssClass + ' ';\r\n }\r\n });\r\n\r\n element.setAttribute('class', trim(existingClasses));\r\n }\r\n}\r\n\r\n\r\nfunction jqLiteAddNodes(root, elements) {\r\n // THIS CODE IS VERY HOT. Don't make changes without benchmarking.\r\n\r\n if (elements) {\r\n\r\n // if a Node (the most common case)\r\n if (elements.nodeType) {\r\n root[root.length++] = elements;\r\n } else {\r\n var length = elements.length;\r\n\r\n // if an Array or NodeList and not a Window\r\n if (typeof length === 'number' && elements.window !== elements) {\r\n if (length) {\r\n for (var i = 0; i < length; i++) {\r\n root[root.length++] = elements[i];\r\n }\r\n }\r\n } else {\r\n root[root.length++] = elements;\r\n }\r\n }\r\n }\r\n}\r\n\r\n\r\nfunction jqLiteController(element, name) {\r\n return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');\r\n}\r\n\r\nfunction jqLiteInheritedData(element, name, value) {\r\n // if element is the document object work with the html element instead\r\n // this makes $(document).scope() possible\r\n if (element.nodeType == NODE_TYPE_DOCUMENT) {\r\n element = element.documentElement;\r\n }\r\n var names = isArray(name) ? name : [name];\r\n\r\n while (element) {\r\n for (var i = 0, ii = names.length; i < ii; i++) {\r\n if ((value = jqLite.data(element, names[i])) !== undefined) return value;\r\n }\r\n\r\n // If dealing with a document fragment node with a host element, and no parent, use the host\r\n // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM\r\n // to lookup parent controllers.\r\n element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);\r\n }\r\n}\r\n\r\nfunction jqLiteEmpty(element) {\r\n jqLiteDealoc(element, true);\r\n while (element.firstChild) {\r\n element.removeChild(element.firstChild);\r\n }\r\n}\r\n\r\nfunction jqLiteRemove(element, keepData) {\r\n if (!keepData) jqLiteDealoc(element);\r\n var parent = element.parentNode;\r\n if (parent) parent.removeChild(element);\r\n}\r\n\r\n\r\nfunction jqLiteDocumentLoaded(action, win) {\r\n win = win || window;\r\n if (win.document.readyState === 'complete') {\r\n // Force the action to be run async for consistent behaviour\r\n // from the action's point of view\r\n // i.e. it will definitely not be in a $apply\r\n win.setTimeout(action);\r\n } else {\r\n // No need to unbind this handler as load is only ever called once\r\n jqLite(win).on('load', action);\r\n }\r\n}\r\n\r\n//////////////////////////////////////////\r\n// Functions which are declared directly.\r\n//////////////////////////////////////////\r\nvar JQLitePrototype = JQLite.prototype = {\r\n ready: function(fn) {\r\n var fired = false;\r\n\r\n function trigger() {\r\n if (fired) return;\r\n fired = true;\r\n fn();\r\n }\r\n\r\n // check if document is already loaded\r\n if (document.readyState === 'complete') {\r\n setTimeout(trigger);\r\n } else {\r\n this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9\r\n // we can not use jqLite since we are not done loading and jQuery could be loaded later.\r\n // jshint -W064\r\n JQLite(window).on('load', trigger); // fallback to window.onload for others\r\n // jshint +W064\r\n }\r\n },\r\n toString: function() {\r\n var value = [];\r\n forEach(this, function(e) { value.push('' + e);});\r\n return '[' + value.join(', ') + ']';\r\n },\r\n\r\n eq: function(index) {\r\n return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);\r\n },\r\n\r\n length: 0,\r\n push: push,\r\n sort: [].sort,\r\n splice: [].splice\r\n};\r\n\r\n//////////////////////////////////////////\r\n// Functions iterating getter/setters.\r\n// these functions return self on setter and\r\n// value on get.\r\n//////////////////////////////////////////\r\nvar BOOLEAN_ATTR = {};\r\nforEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {\r\n BOOLEAN_ATTR[lowercase(value)] = value;\r\n});\r\nvar BOOLEAN_ELEMENTS = {};\r\nforEach('input,select,option,textarea,button,form,details'.split(','), function(value) {\r\n BOOLEAN_ELEMENTS[value] = true;\r\n});\r\nvar ALIASED_ATTR = {\r\n 'ngMinlength': 'minlength',\r\n 'ngMaxlength': 'maxlength',\r\n 'ngMin': 'min',\r\n 'ngMax': 'max',\r\n 'ngPattern': 'pattern'\r\n};\r\n\r\nfunction getBooleanAttrName(element, name) {\r\n // check dom last since we will most likely fail on name\r\n var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];\r\n\r\n // booleanAttr is here twice to minimize DOM access\r\n return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;\r\n}\r\n\r\nfunction getAliasedAttrName(element, name) {\r\n var nodeName = element.nodeName;\r\n return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name];\r\n}\r\n\r\nforEach({\r\n data: jqLiteData,\r\n removeData: jqLiteRemoveData\r\n}, function(fn, name) {\r\n JQLite[name] = fn;\r\n});\r\n\r\nforEach({\r\n data: jqLiteData,\r\n inheritedData: jqLiteInheritedData,\r\n\r\n scope: function(element) {\r\n // Can't use jqLiteData here directly so we stay compatible with jQuery!\r\n return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);\r\n },\r\n\r\n isolateScope: function(element) {\r\n // Can't use jqLiteData here directly so we stay compatible with jQuery!\r\n return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');\r\n },\r\n\r\n controller: jqLiteController,\r\n\r\n injector: function(element) {\r\n return jqLiteInheritedData(element, '$injector');\r\n },\r\n\r\n removeAttr: function(element, name) {\r\n element.removeAttribute(name);\r\n },\r\n\r\n hasClass: jqLiteHasClass,\r\n\r\n css: function(element, name, value) {\r\n name = camelCase(name);\r\n\r\n if (isDefined(value)) {\r\n element.style[name] = value;\r\n } else {\r\n return element.style[name];\r\n }\r\n },\r\n\r\n attr: function(element, name, value) {\r\n var nodeType = element.nodeType;\r\n if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {\r\n return;\r\n }\r\n var lowercasedName = lowercase(name);\r\n if (BOOLEAN_ATTR[lowercasedName]) {\r\n if (isDefined(value)) {\r\n if (!!value) {\r\n element[name] = true;\r\n element.setAttribute(name, lowercasedName);\r\n } else {\r\n element[name] = false;\r\n element.removeAttribute(lowercasedName);\r\n }\r\n } else {\r\n return (element[name] ||\r\n (element.attributes.getNamedItem(name) || noop).specified)\r\n ? lowercasedName\r\n : undefined;\r\n }\r\n } else if (isDefined(value)) {\r\n element.setAttribute(name, value);\r\n } else if (element.getAttribute) {\r\n // the extra argument \"2\" is to get the right thing for a.href in IE, see jQuery code\r\n // some elements (e.g. Document) don't have get attribute, so return undefined\r\n var ret = element.getAttribute(name, 2);\r\n // normalize non-existing attributes to undefined (as jQuery)\r\n return ret === null ? undefined : ret;\r\n }\r\n },\r\n\r\n prop: function(element, name, value) {\r\n if (isDefined(value)) {\r\n element[name] = value;\r\n } else {\r\n return element[name];\r\n }\r\n },\r\n\r\n text: (function() {\r\n getText.$dv = '';\r\n return getText;\r\n\r\n function getText(element, value) {\r\n if (isUndefined(value)) {\r\n var nodeType = element.nodeType;\r\n return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';\r\n }\r\n element.textContent = value;\r\n }\r\n })(),\r\n\r\n val: function(element, value) {\r\n if (isUndefined(value)) {\r\n if (element.multiple && nodeName_(element) === 'select') {\r\n var result = [];\r\n forEach(element.options, function(option) {\r\n if (option.selected) {\r\n result.push(option.value || option.text);\r\n }\r\n });\r\n return result.length === 0 ? null : result;\r\n }\r\n return element.value;\r\n }\r\n element.value = value;\r\n },\r\n\r\n html: function(element, value) {\r\n if (isUndefined(value)) {\r\n return element.innerHTML;\r\n }\r\n jqLiteDealoc(element, true);\r\n element.innerHTML = value;\r\n },\r\n\r\n empty: jqLiteEmpty\r\n}, function(fn, name) {\r\n /**\r\n * Properties: writes return selection, reads return first value\r\n */\r\n JQLite.prototype[name] = function(arg1, arg2) {\r\n var i, key;\r\n var nodeCount = this.length;\r\n\r\n // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it\r\n // in a way that survives minification.\r\n // jqLiteEmpty takes no arguments but is a setter.\r\n if (fn !== jqLiteEmpty &&\r\n (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {\r\n if (isObject(arg1)) {\r\n\r\n // we are a write, but the object properties are the key/values\r\n for (i = 0; i < nodeCount; i++) {\r\n if (fn === jqLiteData) {\r\n // data() takes the whole object in jQuery\r\n fn(this[i], arg1);\r\n } else {\r\n for (key in arg1) {\r\n fn(this[i], key, arg1[key]);\r\n }\r\n }\r\n }\r\n // return self for chaining\r\n return this;\r\n } else {\r\n // we are a read, so read the first child.\r\n // TODO: do we still need this?\r\n var value = fn.$dv;\r\n // Only if we have $dv do we iterate over all, otherwise it is just the first element.\r\n var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;\r\n for (var j = 0; j < jj; j++) {\r\n var nodeValue = fn(this[j], arg1, arg2);\r\n value = value ? value + nodeValue : nodeValue;\r\n }\r\n return value;\r\n }\r\n } else {\r\n // we are a write, so apply to all children\r\n for (i = 0; i < nodeCount; i++) {\r\n fn(this[i], arg1, arg2);\r\n }\r\n // return self for chaining\r\n return this;\r\n }\r\n };\r\n});\r\n\r\nfunction createEventHandler(element, events) {\r\n var eventHandler = function(event, type) {\r\n // jQuery specific api\r\n event.isDefaultPrevented = function() {\r\n return event.defaultPrevented;\r\n };\r\n\r\n var eventFns = events[type || event.type];\r\n var eventFnsLength = eventFns ? eventFns.length : 0;\r\n\r\n if (!eventFnsLength) return;\r\n\r\n if (isUndefined(event.immediatePropagationStopped)) {\r\n var originalStopImmediatePropagation = event.stopImmediatePropagation;\r\n event.stopImmediatePropagation = function() {\r\n event.immediatePropagationStopped = true;\r\n\r\n if (event.stopPropagation) {\r\n event.stopPropagation();\r\n }\r\n\r\n if (originalStopImmediatePropagation) {\r\n originalStopImmediatePropagation.call(event);\r\n }\r\n };\r\n }\r\n\r\n event.isImmediatePropagationStopped = function() {\r\n return event.immediatePropagationStopped === true;\r\n };\r\n\r\n // Copy event handlers in case event handlers array is modified during execution.\r\n if ((eventFnsLength > 1)) {\r\n eventFns = shallowCopy(eventFns);\r\n }\r\n\r\n for (var i = 0; i < eventFnsLength; i++) {\r\n if (!event.isImmediatePropagationStopped()) {\r\n eventFns[i].call(element, event);\r\n }\r\n }\r\n };\r\n\r\n // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all\r\n // events on `element`\r\n eventHandler.elem = element;\r\n return eventHandler;\r\n}\r\n\r\n//////////////////////////////////////////\r\n// Functions iterating traversal.\r\n// These functions chain results into a single\r\n// selector.\r\n//////////////////////////////////////////\r\nforEach({\r\n removeData: jqLiteRemoveData,\r\n\r\n on: function jqLiteOn(element, type, fn, unsupported) {\r\n if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');\r\n\r\n // Do not add event handlers to non-elements because they will not be cleaned up.\r\n if (!jqLiteAcceptsData(element)) {\r\n return;\r\n }\r\n\r\n var expandoStore = jqLiteExpandoStore(element, true);\r\n var events = expandoStore.events;\r\n var handle = expandoStore.handle;\r\n\r\n if (!handle) {\r\n handle = expandoStore.handle = createEventHandler(element, events);\r\n }\r\n\r\n // http://jsperf.com/string-indexof-vs-split\r\n var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];\r\n var i = types.length;\r\n\r\n while (i--) {\r\n type = types[i];\r\n var eventFns = events[type];\r\n\r\n if (!eventFns) {\r\n events[type] = [];\r\n\r\n if (type === 'mouseenter' || type === 'mouseleave') {\r\n // Refer to jQuery's implementation of mouseenter & mouseleave\r\n // Read about mouseenter and mouseleave:\r\n // http://www.quirksmode.org/js/events_mouse.html#link8\r\n\r\n jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) {\r\n var target = this, related = event.relatedTarget;\r\n // For mousenter/leave call the handler if related is outside the target.\r\n // NB: No relatedTarget if the mouse left/entered the browser window\r\n if (!related || (related !== target && !target.contains(related))) {\r\n handle(event, type);\r\n }\r\n });\r\n\r\n } else {\r\n if (type !== '$destroy') {\r\n addEventListenerFn(element, type, handle);\r\n }\r\n }\r\n eventFns = events[type];\r\n }\r\n eventFns.push(fn);\r\n }\r\n },\r\n\r\n off: jqLiteOff,\r\n\r\n one: function(element, type, fn) {\r\n element = jqLite(element);\r\n\r\n //add the listener twice so that when it is called\r\n //you can remove the original function and still be\r\n //able to call element.off(ev, fn) normally\r\n element.on(type, function onFn() {\r\n element.off(type, fn);\r\n element.off(type, onFn);\r\n });\r\n element.on(type, fn);\r\n },\r\n\r\n replaceWith: function(element, replaceNode) {\r\n var index, parent = element.parentNode;\r\n jqLiteDealoc(element);\r\n forEach(new JQLite(replaceNode), function(node) {\r\n if (index) {\r\n parent.insertBefore(node, index.nextSibling);\r\n } else {\r\n parent.replaceChild(node, element);\r\n }\r\n index = node;\r\n });\r\n },\r\n\r\n children: function(element) {\r\n var children = [];\r\n forEach(element.childNodes, function(element) {\r\n if (element.nodeType === NODE_TYPE_ELEMENT)\r\n children.push(element);\r\n });\r\n return children;\r\n },\r\n\r\n contents: function(element) {\r\n return element.contentDocument || element.childNodes || [];\r\n },\r\n\r\n append: function(element, node) {\r\n var nodeType = element.nodeType;\r\n if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;\r\n\r\n node = new JQLite(node);\r\n\r\n for (var i = 0, ii = node.length; i < ii; i++) {\r\n var child = node[i];\r\n element.appendChild(child);\r\n }\r\n },\r\n\r\n prepend: function(element, node) {\r\n if (element.nodeType === NODE_TYPE_ELEMENT) {\r\n var index = element.firstChild;\r\n forEach(new JQLite(node), function(child) {\r\n element.insertBefore(child, index);\r\n });\r\n }\r\n },\r\n\r\n wrap: function(element, wrapNode) {\r\n wrapNode = jqLite(wrapNode).eq(0).clone()[0];\r\n var parent = element.parentNode;\r\n if (parent) {\r\n parent.replaceChild(wrapNode, element);\r\n }\r\n wrapNode.appendChild(element);\r\n },\r\n\r\n remove: jqLiteRemove,\r\n\r\n detach: function(element) {\r\n jqLiteRemove(element, true);\r\n },\r\n\r\n after: function(element, newElement) {\r\n var index = element, parent = element.parentNode;\r\n newElement = new JQLite(newElement);\r\n\r\n for (var i = 0, ii = newElement.length; i < ii; i++) {\r\n var node = newElement[i];\r\n parent.insertBefore(node, index.nextSibling);\r\n index = node;\r\n }\r\n },\r\n\r\n addClass: jqLiteAddClass,\r\n removeClass: jqLiteRemoveClass,\r\n\r\n toggleClass: function(element, selector, condition) {\r\n if (selector) {\r\n forEach(selector.split(' '), function(className) {\r\n var classCondition = condition;\r\n if (isUndefined(classCondition)) {\r\n classCondition = !jqLiteHasClass(element, className);\r\n }\r\n (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);\r\n });\r\n }\r\n },\r\n\r\n parent: function(element) {\r\n var parent = element.parentNode;\r\n return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;\r\n },\r\n\r\n next: function(element) {\r\n return element.nextElementSibling;\r\n },\r\n\r\n find: function(element, selector) {\r\n if (element.getElementsByTagName) {\r\n return element.getElementsByTagName(selector);\r\n } else {\r\n return [];\r\n }\r\n },\r\n\r\n clone: jqLiteClone,\r\n\r\n triggerHandler: function(element, event, extraParameters) {\r\n\r\n var dummyEvent, eventFnsCopy, handlerArgs;\r\n var eventName = event.type || event;\r\n var expandoStore = jqLiteExpandoStore(element);\r\n var events = expandoStore && expandoStore.events;\r\n var eventFns = events && events[eventName];\r\n\r\n if (eventFns) {\r\n // Create a dummy event to pass to the handlers\r\n dummyEvent = {\r\n preventDefault: function() { this.defaultPrevented = true; },\r\n isDefaultPrevented: function() { return this.defaultPrevented === true; },\r\n stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },\r\n isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },\r\n stopPropagation: noop,\r\n type: eventName,\r\n target: element\r\n };\r\n\r\n // If a custom event was provided then extend our dummy event with it\r\n if (event.type) {\r\n dummyEvent = extend(dummyEvent, event);\r\n }\r\n\r\n // Copy event handlers in case event handlers array is modified during execution.\r\n eventFnsCopy = shallowCopy(eventFns);\r\n handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];\r\n\r\n forEach(eventFnsCopy, function(fn) {\r\n if (!dummyEvent.isImmediatePropagationStopped()) {\r\n fn.apply(element, handlerArgs);\r\n }\r\n });\r\n }\r\n }\r\n}, function(fn, name) {\r\n /**\r\n * chaining functions\r\n */\r\n JQLite.prototype[name] = function(arg1, arg2, arg3) {\r\n var value;\r\n\r\n for (var i = 0, ii = this.length; i < ii; i++) {\r\n if (isUndefined(value)) {\r\n value = fn(this[i], arg1, arg2, arg3);\r\n if (isDefined(value)) {\r\n // any function which returns a value needs to be wrapped\r\n value = jqLite(value);\r\n }\r\n } else {\r\n jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));\r\n }\r\n }\r\n return isDefined(value) ? value : this;\r\n };\r\n\r\n // bind legacy bind/unbind to on/off\r\n JQLite.prototype.bind = JQLite.prototype.on;\r\n JQLite.prototype.unbind = JQLite.prototype.off;\r\n});\r\n\r\n\r\n// Provider for private $$jqLite service\r\nfunction $$jqLiteProvider() {\r\n this.$get = function $$jqLite() {\r\n return extend(JQLite, {\r\n hasClass: function(node, classes) {\r\n if (node.attr) node = node[0];\r\n return jqLiteHasClass(node, classes);\r\n },\r\n addClass: function(node, classes) {\r\n if (node.attr) node = node[0];\r\n return jqLiteAddClass(node, classes);\r\n },\r\n removeClass: function(node, classes) {\r\n if (node.attr) node = node[0];\r\n return jqLiteRemoveClass(node, classes);\r\n }\r\n });\r\n };\r\n}\r\n\r\n/**\r\n * Computes a hash of an 'obj'.\r\n * Hash of a:\r\n * string is string\r\n * number is number as string\r\n * object is either result of calling $$hashKey function on the object or uniquely generated id,\r\n * that is also assigned to the $$hashKey property of the object.\r\n *\r\n * @param obj\r\n * @returns {string} hash string such that the same input will have the same hash string.\r\n * The resulting string key is in 'type:hashKey' format.\r\n */\r\nfunction hashKey(obj, nextUidFn) {\r\n var key = obj && obj.$$hashKey;\r\n\r\n if (key) {\r\n if (typeof key === 'function') {\r\n key = obj.$$hashKey();\r\n }\r\n return key;\r\n }\r\n\r\n var objType = typeof obj;\r\n if (objType == 'function' || (objType == 'object' && obj !== null)) {\r\n key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();\r\n } else {\r\n key = objType + ':' + obj;\r\n }\r\n\r\n return key;\r\n}\r\n\r\n/**\r\n * HashMap which can use objects as keys\r\n */\r\nfunction HashMap(array, isolatedUid) {\r\n if (isolatedUid) {\r\n var uid = 0;\r\n this.nextUid = function() {\r\n return ++uid;\r\n };\r\n }\r\n forEach(array, this.put, this);\r\n}\r\nHashMap.prototype = {\r\n /**\r\n * Store key value pair\r\n * @param key key to store can be any type\r\n * @param value value to store can be any type\r\n */\r\n put: function(key, value) {\r\n this[hashKey(key, this.nextUid)] = value;\r\n },\r\n\r\n /**\r\n * @param key\r\n * @returns {Object} the value for the key\r\n */\r\n get: function(key) {\r\n return this[hashKey(key, this.nextUid)];\r\n },\r\n\r\n /**\r\n * Remove the key/value pair\r\n * @param key\r\n */\r\n remove: function(key) {\r\n var value = this[key = hashKey(key, this.nextUid)];\r\n delete this[key];\r\n return value;\r\n }\r\n};\r\n\r\n/**\r\n * @ngdoc function\r\n * @module ng\r\n * @name angular.injector\r\n * @kind function\r\n *\r\n * @description\r\n * Creates an injector object that can be used for retrieving services as well as for\r\n * dependency injection (see {@link guide/di dependency injection}).\r\n *\r\n * @param {Array.} modules A list of module functions or their aliases. See\r\n * {@link angular.module}. The `ng` module must be explicitly added.\r\n * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which\r\n * disallows argument name annotation inference.\r\n * @returns {injector} Injector object. See {@link auto.$injector $injector}.\r\n *\r\n * @example\r\n * Typical usage\r\n * ```js\r\n * // create an injector\r\n * var $injector = angular.injector(['ng']);\r\n *\r\n * // use the injector to kick off your application\r\n * // use the type inference to auto inject arguments, or use implicit injection\r\n * $injector.invoke(function($rootScope, $compile, $document) {\r\n * $compile($document)($rootScope);\r\n * $rootScope.$digest();\r\n * });\r\n * ```\r\n *\r\n * Sometimes you want to get access to the injector of a currently running Angular app\r\n * from outside Angular. Perhaps, you want to inject and compile some markup after the\r\n * application has been bootstrapped. You can do this using the extra `injector()` added\r\n * to JQuery/jqLite elements. See {@link angular.element}.\r\n *\r\n * *This is fairly rare but could be the case if a third party library is injecting the\r\n * markup.*\r\n *\r\n * In the following example a new block of HTML containing a `ng-controller`\r\n * directive is added to the end of the document body by JQuery. We then compile and link\r\n * it into the current AngularJS scope.\r\n *\r\n * ```js\r\n * var $div = $('
    {{content.label}}
    ');\r\n * $(document.body).append($div);\r\n *\r\n * angular.element(document).injector().invoke(function($compile) {\r\n * var scope = angular.element($div).scope();\r\n * $compile($div)(scope);\r\n * });\r\n * ```\r\n */\r\n\r\n\r\n/**\r\n * @ngdoc module\r\n * @name auto\r\n * @description\r\n *\r\n * Implicit module which gets automatically added to each {@link auto.$injector $injector}.\r\n */\r\n\r\nvar FN_ARGS = /^function\\s*[^\\(]*\\(\\s*([^\\)]*)\\)/m;\r\nvar FN_ARG_SPLIT = /,/;\r\nvar FN_ARG = /^\\s*(_?)(\\S+?)\\1\\s*$/;\r\nvar STRIP_COMMENTS = /((\\/\\/.*$)|(\\/\\*[\\s\\S]*?\\*\\/))/mg;\r\nvar $injectorMinErr = minErr('$injector');\r\n\r\nfunction anonFn(fn) {\r\n // For anonymous functions, showing at the very least the function signature can help in\r\n // debugging.\r\n var fnText = fn.toString().replace(STRIP_COMMENTS, ''),\r\n args = fnText.match(FN_ARGS);\r\n if (args) {\r\n return 'function(' + (args[1] || '').replace(/[\\s\\r\\n]+/, ' ') + ')';\r\n }\r\n return 'fn';\r\n}\r\n\r\nfunction annotate(fn, strictDi, name) {\r\n var $inject,\r\n fnText,\r\n argDecl,\r\n last;\r\n\r\n if (typeof fn === 'function') {\r\n if (!($inject = fn.$inject)) {\r\n $inject = [];\r\n if (fn.length) {\r\n if (strictDi) {\r\n if (!isString(name) || !name) {\r\n name = fn.name || anonFn(fn);\r\n }\r\n throw $injectorMinErr('strictdi',\r\n '{0} is not using explicit annotation and cannot be invoked in strict mode', name);\r\n }\r\n fnText = fn.toString().replace(STRIP_COMMENTS, '');\r\n argDecl = fnText.match(FN_ARGS);\r\n forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {\r\n arg.replace(FN_ARG, function(all, underscore, name) {\r\n $inject.push(name);\r\n });\r\n });\r\n }\r\n fn.$inject = $inject;\r\n }\r\n } else if (isArray(fn)) {\r\n last = fn.length - 1;\r\n assertArgFn(fn[last], 'fn');\r\n $inject = fn.slice(0, last);\r\n } else {\r\n assertArgFn(fn, 'fn', true);\r\n }\r\n return $inject;\r\n}\r\n\r\n///////////////////////////////////////\r\n\r\n/**\r\n * @ngdoc service\r\n * @name $injector\r\n *\r\n * @description\r\n *\r\n * `$injector` is used to retrieve object instances as defined by\r\n * {@link auto.$provide provider}, instantiate types, invoke methods,\r\n * and load modules.\r\n *\r\n * The following always holds true:\r\n *\r\n * ```js\r\n * var $injector = angular.injector();\r\n * expect($injector.get('$injector')).toBe($injector);\r\n * expect($injector.invoke(function($injector) {\r\n * return $injector;\r\n * })).toBe($injector);\r\n * ```\r\n *\r\n * # Injection Function Annotation\r\n *\r\n * JavaScript does not have annotations, and annotations are needed for dependency injection. The\r\n * following are all valid ways of annotating function with injection arguments and are equivalent.\r\n *\r\n * ```js\r\n * // inferred (only works if code not minified/obfuscated)\r\n * $injector.invoke(function(serviceA){});\r\n *\r\n * // annotated\r\n * function explicit(serviceA) {};\r\n * explicit.$inject = ['serviceA'];\r\n * $injector.invoke(explicit);\r\n *\r\n * // inline\r\n * $injector.invoke(['serviceA', function(serviceA){}]);\r\n * ```\r\n *\r\n * ## Inference\r\n *\r\n * In JavaScript calling `toString()` on a function returns the function definition. The definition\r\n * can then be parsed and the function arguments can be extracted. This method of discovering\r\n * annotations is disallowed when the injector is in strict mode.\r\n * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the\r\n * argument names.\r\n *\r\n * ## `$inject` Annotation\r\n * By adding an `$inject` property onto a function the injection parameters can be specified.\r\n *\r\n * ## Inline\r\n * As an array of injection names, where the last item in the array is the function to call.\r\n */\r\n\r\n/**\r\n * @ngdoc method\r\n * @name $injector#get\r\n *\r\n * @description\r\n * Return an instance of the service.\r\n *\r\n * @param {string} name The name of the instance to retrieve.\r\n * @param {string=} caller An optional string to provide the origin of the function call for error messages.\r\n * @return {*} The instance.\r\n */\r\n\r\n/**\r\n * @ngdoc method\r\n * @name $injector#invoke\r\n *\r\n * @description\r\n * Invoke the method and supply the method arguments from the `$injector`.\r\n *\r\n * @param {Function|Array.} fn The injectable function to invoke. Function parameters are\r\n * injected according to the {@link guide/di $inject Annotation} rules.\r\n * @param {Object=} self The `this` for the invoked method.\r\n * @param {Object=} locals Optional object. If preset then any argument names are read from this\r\n * object first, before the `$injector` is consulted.\r\n * @returns {*} the value returned by the invoked `fn` function.\r\n */\r\n\r\n/**\r\n * @ngdoc method\r\n * @name $injector#has\r\n *\r\n * @description\r\n * Allows the user to query if the particular service exists.\r\n *\r\n * @param {string} name Name of the service to query.\r\n * @returns {boolean} `true` if injector has given service.\r\n */\r\n\r\n/**\r\n * @ngdoc method\r\n * @name $injector#instantiate\r\n * @description\r\n * Create a new instance of JS type. The method takes a constructor function, invokes the new\r\n * operator, and supplies all of the arguments to the constructor function as specified by the\r\n * constructor annotation.\r\n *\r\n * @param {Function} Type Annotated constructor function.\r\n * @param {Object=} locals Optional object. If preset then any argument names are read from this\r\n * object first, before the `$injector` is consulted.\r\n * @returns {Object} new instance of `Type`.\r\n */\r\n\r\n/**\r\n * @ngdoc method\r\n * @name $injector#annotate\r\n *\r\n * @description\r\n * Returns an array of service names which the function is requesting for injection. This API is\r\n * used by the injector to determine which services need to be injected into the function when the\r\n * function is invoked. There are three ways in which the function can be annotated with the needed\r\n * dependencies.\r\n *\r\n * # Argument names\r\n *\r\n * The simplest form is to extract the dependencies from the arguments of the function. This is done\r\n * by converting the function into a string using `toString()` method and extracting the argument\r\n * names.\r\n * ```js\r\n * // Given\r\n * function MyController($scope, $route) {\r\n * // ...\r\n * }\r\n *\r\n * // Then\r\n * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);\r\n * ```\r\n *\r\n * You can disallow this method by using strict injection mode.\r\n *\r\n * This method does not work with code minification / obfuscation. For this reason the following\r\n * annotation strategies are supported.\r\n *\r\n * # The `$inject` property\r\n *\r\n * If a function has an `$inject` property and its value is an array of strings, then the strings\r\n * represent names of services to be injected into the function.\r\n * ```js\r\n * // Given\r\n * var MyController = function(obfuscatedScope, obfuscatedRoute) {\r\n * // ...\r\n * }\r\n * // Define function dependencies\r\n * MyController['$inject'] = ['$scope', '$route'];\r\n *\r\n * // Then\r\n * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);\r\n * ```\r\n *\r\n * # The array notation\r\n *\r\n * It is often desirable to inline Injected functions and that's when setting the `$inject` property\r\n * is very inconvenient. In these situations using the array notation to specify the dependencies in\r\n * a way that survives minification is a better choice:\r\n *\r\n * ```js\r\n * // We wish to write this (not minification / obfuscation safe)\r\n * injector.invoke(function($compile, $rootScope) {\r\n * // ...\r\n * });\r\n *\r\n * // We are forced to write break inlining\r\n * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {\r\n * // ...\r\n * };\r\n * tmpFn.$inject = ['$compile', '$rootScope'];\r\n * injector.invoke(tmpFn);\r\n *\r\n * // To better support inline function the inline annotation is supported\r\n * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {\r\n * // ...\r\n * }]);\r\n *\r\n * // Therefore\r\n * expect(injector.annotate(\r\n * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])\r\n * ).toEqual(['$compile', '$rootScope']);\r\n * ```\r\n *\r\n * @param {Function|Array.} fn Function for which dependent service names need to\r\n * be retrieved as described above.\r\n *\r\n * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.\r\n *\r\n * @returns {Array.} The names of the services which the function requires.\r\n */\r\n\r\n\r\n\r\n\r\n/**\r\n * @ngdoc service\r\n * @name $provide\r\n *\r\n * @description\r\n *\r\n * The {@link auto.$provide $provide} service has a number of methods for registering components\r\n * with the {@link auto.$injector $injector}. Many of these functions are also exposed on\r\n * {@link angular.Module}.\r\n *\r\n * An Angular **service** is a singleton object created by a **service factory**. These **service\r\n * factories** are functions which, in turn, are created by a **service provider**.\r\n * The **service providers** are constructor functions. When instantiated they must contain a\r\n * property called `$get`, which holds the **service factory** function.\r\n *\r\n * When you request a service, the {@link auto.$injector $injector} is responsible for finding the\r\n * correct **service provider**, instantiating it and then calling its `$get` **service factory**\r\n * function to get the instance of the **service**.\r\n *\r\n * Often services have no configuration options and there is no need to add methods to the service\r\n * provider. The provider will be no more than a constructor function with a `$get` property. For\r\n * these cases the {@link auto.$provide $provide} service has additional helper methods to register\r\n * services without specifying a provider.\r\n *\r\n * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the\r\n * {@link auto.$injector $injector}\r\n * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by\r\n * providers and services.\r\n * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by\r\n * services, not providers.\r\n * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,\r\n * that will be wrapped in a **service provider** object, whose `$get` property will contain the\r\n * given factory function.\r\n * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`\r\n * that will be wrapped in a **service provider** object, whose `$get` property will instantiate\r\n * a new object using the given constructor function.\r\n *\r\n * See the individual methods for more information and examples.\r\n */\r\n\r\n/**\r\n * @ngdoc method\r\n * @name $provide#provider\r\n * @description\r\n *\r\n * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions\r\n * are constructor functions, whose instances are responsible for \"providing\" a factory for a\r\n * service.\r\n *\r\n * Service provider names start with the name of the service they provide followed by `Provider`.\r\n * For example, the {@link ng.$log $log} service has a provider called\r\n * {@link ng.$logProvider $logProvider}.\r\n *\r\n * Service provider objects can have additional methods which allow configuration of the provider\r\n * and its service. Importantly, you can configure what kind of service is created by the `$get`\r\n * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a\r\n * method {@link ng.$logProvider#debugEnabled debugEnabled}\r\n * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the\r\n * console or not.\r\n *\r\n * @param {string} name The name of the instance. NOTE: the provider will be available under `name +\r\n 'Provider'` key.\r\n * @param {(Object|function())} provider If the provider is:\r\n *\r\n * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using\r\n * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.\r\n * - `Constructor`: a new instance of the provider will be created using\r\n * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.\r\n *\r\n * @returns {Object} registered provider instance\r\n\r\n * @example\r\n *\r\n * The following example shows how to create a simple event tracking service and register it using\r\n * {@link auto.$provide#provider $provide.provider()}.\r\n *\r\n * ```js\r\n * // Define the eventTracker provider\r\n * function EventTrackerProvider() {\r\n * var trackingUrl = '/track';\r\n *\r\n * // A provider method for configuring where the tracked events should been saved\r\n * this.setTrackingUrl = function(url) {\r\n * trackingUrl = url;\r\n * };\r\n *\r\n * // The service factory function\r\n * this.$get = ['$http', function($http) {\r\n * var trackedEvents = {};\r\n * return {\r\n * // Call this to track an event\r\n * event: function(event) {\r\n * var count = trackedEvents[event] || 0;\r\n * count += 1;\r\n * trackedEvents[event] = count;\r\n * return count;\r\n * },\r\n * // Call this to save the tracked events to the trackingUrl\r\n * save: function() {\r\n * $http.post(trackingUrl, trackedEvents);\r\n * }\r\n * };\r\n * }];\r\n * }\r\n *\r\n * describe('eventTracker', function() {\r\n * var postSpy;\r\n *\r\n * beforeEach(module(function($provide) {\r\n * // Register the eventTracker provider\r\n * $provide.provider('eventTracker', EventTrackerProvider);\r\n * }));\r\n *\r\n * beforeEach(module(function(eventTrackerProvider) {\r\n * // Configure eventTracker provider\r\n * eventTrackerProvider.setTrackingUrl('/custom-track');\r\n * }));\r\n *\r\n * it('tracks events', inject(function(eventTracker) {\r\n * expect(eventTracker.event('login')).toEqual(1);\r\n * expect(eventTracker.event('login')).toEqual(2);\r\n * }));\r\n *\r\n * it('saves to the tracking url', inject(function(eventTracker, $http) {\r\n * postSpy = spyOn($http, 'post');\r\n * eventTracker.event('login');\r\n * eventTracker.save();\r\n * expect(postSpy).toHaveBeenCalled();\r\n * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');\r\n * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');\r\n * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });\r\n * }));\r\n * });\r\n * ```\r\n */\r\n\r\n/**\r\n * @ngdoc method\r\n * @name $provide#factory\r\n * @description\r\n *\r\n * Register a **service factory**, which will be called to return the service instance.\r\n * This is short for registering a service where its provider consists of only a `$get` property,\r\n * which is the given service factory function.\r\n * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to\r\n * configure your service in a provider.\r\n *\r\n * @param {string} name The name of the instance.\r\n * @param {Function|Array.} $getFn The injectable $getFn for the instance creation.\r\n * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.\r\n * @returns {Object} registered provider instance\r\n *\r\n * @example\r\n * Here is an example of registering a service\r\n * ```js\r\n * $provide.factory('ping', ['$http', function($http) {\r\n * return function ping() {\r\n * return $http.send('/ping');\r\n * };\r\n * }]);\r\n * ```\r\n * You would then inject and use this service like this:\r\n * ```js\r\n * someModule.controller('Ctrl', ['ping', function(ping) {\r\n * ping();\r\n * }]);\r\n * ```\r\n */\r\n\r\n\r\n/**\r\n * @ngdoc method\r\n * @name $provide#service\r\n * @description\r\n *\r\n * Register a **service constructor**, which will be invoked with `new` to create the service\r\n * instance.\r\n * This is short for registering a service where its provider's `$get` property is the service\r\n * constructor function that will be used to instantiate the service instance.\r\n *\r\n * You should use {@link auto.$provide#service $provide.service(class)} if you define your service\r\n * as a type/class.\r\n *\r\n * @param {string} name The name of the instance.\r\n * @param {Function|Array.} constructor An injectable class (constructor function)\r\n * that will be instantiated.\r\n * @returns {Object} registered provider instance\r\n *\r\n * @example\r\n * Here is an example of registering a service using\r\n * {@link auto.$provide#service $provide.service(class)}.\r\n * ```js\r\n * var Ping = function($http) {\r\n * this.$http = $http;\r\n * };\r\n *\r\n * Ping.$inject = ['$http'];\r\n *\r\n * Ping.prototype.send = function() {\r\n * return this.$http.get('/ping');\r\n * };\r\n * $provide.service('ping', Ping);\r\n * ```\r\n * You would then inject and use this service like this:\r\n * ```js\r\n * someModule.controller('Ctrl', ['ping', function(ping) {\r\n * ping.send();\r\n * }]);\r\n * ```\r\n */\r\n\r\n\r\n/**\r\n * @ngdoc method\r\n * @name $provide#value\r\n * @description\r\n *\r\n * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a\r\n * number, an array, an object or a function. This is short for registering a service where its\r\n * provider's `$get` property is a factory function that takes no arguments and returns the **value\r\n * service**.\r\n *\r\n * Value services are similar to constant services, except that they cannot be injected into a\r\n * module configuration function (see {@link angular.Module#config}) but they can be overridden by\r\n * an Angular\r\n * {@link auto.$provide#decorator decorator}.\r\n *\r\n * @param {string} name The name of the instance.\r\n * @param {*} value The value.\r\n * @returns {Object} registered provider instance\r\n *\r\n * @example\r\n * Here are some examples of creating value services.\r\n * ```js\r\n * $provide.value('ADMIN_USER', 'admin');\r\n *\r\n * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });\r\n *\r\n * $provide.value('halfOf', function(value) {\r\n * return value / 2;\r\n * });\r\n * ```\r\n */\r\n\r\n\r\n/**\r\n * @ngdoc method\r\n * @name $provide#constant\r\n * @description\r\n *\r\n * Register a **constant service**, such as a string, a number, an array, an object or a function,\r\n * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be\r\n * injected into a module configuration function (see {@link angular.Module#config}) and it cannot\r\n * be overridden by an Angular {@link auto.$provide#decorator decorator}.\r\n *\r\n * @param {string} name The name of the constant.\r\n * @param {*} value The constant value.\r\n * @returns {Object} registered instance\r\n *\r\n * @example\r\n * Here a some examples of creating constants:\r\n * ```js\r\n * $provide.constant('SHARD_HEIGHT', 306);\r\n *\r\n * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);\r\n *\r\n * $provide.constant('double', function(value) {\r\n * return value * 2;\r\n * });\r\n * ```\r\n */\r\n\r\n\r\n/**\r\n * @ngdoc method\r\n * @name $provide#decorator\r\n * @description\r\n *\r\n * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator\r\n * intercepts the creation of a service, allowing it to override or modify the behaviour of the\r\n * service. The object returned by the decorator may be the original service, or a new service\r\n * object which replaces or wraps and delegates to the original service.\r\n *\r\n * @param {string} name The name of the service to decorate.\r\n * @param {Function|Array.} decorator This function will be invoked when the service needs to be\r\n * instantiated and should return the decorated service instance. The function is called using\r\n * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.\r\n * Local injection arguments:\r\n *\r\n * * `$delegate` - The original service instance, which can be monkey patched, configured,\r\n * decorated or delegated to.\r\n *\r\n * @example\r\n * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting\r\n * calls to {@link ng.$log#error $log.warn()}.\r\n * ```js\r\n * $provide.decorator('$log', ['$delegate', function($delegate) {\r\n * $delegate.warn = $delegate.error;\r\n * return $delegate;\r\n * }]);\r\n * ```\r\n */\r\n\r\n\r\nfunction createInjector(modulesToLoad, strictDi) {\r\n strictDi = (strictDi === true);\r\n var INSTANTIATING = {},\r\n providerSuffix = 'Provider',\r\n path = [],\r\n loadedModules = new HashMap([], true),\r\n providerCache = {\r\n $provide: {\r\n provider: supportObject(provider),\r\n factory: supportObject(factory),\r\n service: supportObject(service),\r\n value: supportObject(value),\r\n constant: supportObject(constant),\r\n decorator: decorator\r\n }\r\n },\r\n providerInjector = (providerCache.$injector =\r\n createInternalInjector(providerCache, function(serviceName, caller) {\r\n if (angular.isString(caller)) {\r\n path.push(caller);\r\n }\r\n throw $injectorMinErr('unpr', \"Unknown provider: {0}\", path.join(' <- '));\r\n })),\r\n instanceCache = {},\r\n instanceInjector = (instanceCache.$injector =\r\n createInternalInjector(instanceCache, function(serviceName, caller) {\r\n var provider = providerInjector.get(serviceName + providerSuffix, caller);\r\n return instanceInjector.invoke(provider.$get, provider, undefined, serviceName);\r\n }));\r\n\r\n\r\n forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });\r\n\r\n return instanceInjector;\r\n\r\n ////////////////////////////////////\r\n // $provider\r\n ////////////////////////////////////\r\n\r\n function supportObject(delegate) {\r\n return function(key, value) {\r\n if (isObject(key)) {\r\n forEach(key, reverseParams(delegate));\r\n } else {\r\n return delegate(key, value);\r\n }\r\n };\r\n }\r\n\r\n function provider(name, provider_) {\r\n assertNotHasOwnProperty(name, 'service');\r\n if (isFunction(provider_) || isArray(provider_)) {\r\n provider_ = providerInjector.instantiate(provider_);\r\n }\r\n if (!provider_.$get) {\r\n throw $injectorMinErr('pget', \"Provider '{0}' must define $get factory method.\", name);\r\n }\r\n return providerCache[name + providerSuffix] = provider_;\r\n }\r\n\r\n function enforceReturnValue(name, factory) {\r\n return function enforcedReturnValue() {\r\n var result = instanceInjector.invoke(factory, this);\r\n if (isUndefined(result)) {\r\n throw $injectorMinErr('undef', \"Provider '{0}' must return a value from $get factory method.\", name);\r\n }\r\n return result;\r\n };\r\n }\r\n\r\n function factory(name, factoryFn, enforce) {\r\n return provider(name, {\r\n $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn\r\n });\r\n }\r\n\r\n function service(name, constructor) {\r\n return factory(name, ['$injector', function($injector) {\r\n return $injector.instantiate(constructor);\r\n }]);\r\n }\r\n\r\n function value(name, val) { return factory(name, valueFn(val), false); }\r\n\r\n function constant(name, value) {\r\n assertNotHasOwnProperty(name, 'constant');\r\n providerCache[name] = value;\r\n instanceCache[name] = value;\r\n }\r\n\r\n function decorator(serviceName, decorFn) {\r\n var origProvider = providerInjector.get(serviceName + providerSuffix),\r\n orig$get = origProvider.$get;\r\n\r\n origProvider.$get = function() {\r\n var origInstance = instanceInjector.invoke(orig$get, origProvider);\r\n return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});\r\n };\r\n }\r\n\r\n ////////////////////////////////////\r\n // Module Loading\r\n ////////////////////////////////////\r\n function loadModules(modulesToLoad) {\r\n var runBlocks = [], moduleFn;\r\n forEach(modulesToLoad, function(module) {\r\n if (loadedModules.get(module)) return;\r\n loadedModules.put(module, true);\r\n\r\n function runInvokeQueue(queue) {\r\n var i, ii;\r\n for (i = 0, ii = queue.length; i < ii; i++) {\r\n var invokeArgs = queue[i],\r\n provider = providerInjector.get(invokeArgs[0]);\r\n\r\n provider[invokeArgs[1]].apply(provider, invokeArgs[2]);\r\n }\r\n }\r\n\r\n try {\r\n if (isString(module)) {\r\n moduleFn = angularModule(module);\r\n runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);\r\n runInvokeQueue(moduleFn._invokeQueue);\r\n runInvokeQueue(moduleFn._configBlocks);\r\n } else if (isFunction(module)) {\r\n runBlocks.push(providerInjector.invoke(module));\r\n } else if (isArray(module)) {\r\n runBlocks.push(providerInjector.invoke(module));\r\n } else {\r\n assertArgFn(module, 'module');\r\n }\r\n } catch (e) {\r\n if (isArray(module)) {\r\n module = module[module.length - 1];\r\n }\r\n if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {\r\n // Safari & FF's stack traces don't contain error.message content\r\n // unlike those of Chrome and IE\r\n // So if stack doesn't contain message, we create a new string that contains both.\r\n // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.\r\n /* jshint -W022 */\r\n e = e.message + '\\n' + e.stack;\r\n }\r\n throw $injectorMinErr('modulerr', \"Failed to instantiate module {0} due to:\\n{1}\",\r\n module, e.stack || e.message || e);\r\n }\r\n });\r\n return runBlocks;\r\n }\r\n\r\n ////////////////////////////////////\r\n // internal Injector\r\n ////////////////////////////////////\r\n\r\n function createInternalInjector(cache, factory) {\r\n\r\n function getService(serviceName, caller) {\r\n if (cache.hasOwnProperty(serviceName)) {\r\n if (cache[serviceName] === INSTANTIATING) {\r\n throw $injectorMinErr('cdep', 'Circular dependency found: {0}',\r\n serviceName + ' <- ' + path.join(' <- '));\r\n }\r\n return cache[serviceName];\r\n } else {\r\n try {\r\n path.unshift(serviceName);\r\n cache[serviceName] = INSTANTIATING;\r\n return cache[serviceName] = factory(serviceName, caller);\r\n } catch (err) {\r\n if (cache[serviceName] === INSTANTIATING) {\r\n delete cache[serviceName];\r\n }\r\n throw err;\r\n } finally {\r\n path.shift();\r\n }\r\n }\r\n }\r\n\r\n function invoke(fn, self, locals, serviceName) {\r\n if (typeof locals === 'string') {\r\n serviceName = locals;\r\n locals = null;\r\n }\r\n\r\n var args = [],\r\n $inject = createInjector.$$annotate(fn, strictDi, serviceName),\r\n length, i,\r\n key;\r\n\r\n for (i = 0, length = $inject.length; i < length; i++) {\r\n key = $inject[i];\r\n if (typeof key !== 'string') {\r\n throw $injectorMinErr('itkn',\r\n 'Incorrect injection token! Expected service name as string, got {0}', key);\r\n }\r\n args.push(\r\n locals && locals.hasOwnProperty(key)\r\n ? locals[key]\r\n : getService(key, serviceName)\r\n );\r\n }\r\n if (isArray(fn)) {\r\n fn = fn[length];\r\n }\r\n\r\n // http://jsperf.com/angularjs-invoke-apply-vs-switch\r\n // #5388\r\n return fn.apply(self, args);\r\n }\r\n\r\n function instantiate(Type, locals, serviceName) {\r\n // Check if Type is annotated and use just the given function at n-1 as parameter\r\n // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);\r\n // Object creation: http://jsperf.com/create-constructor/2\r\n var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype || null);\r\n var returnedValue = invoke(Type, instance, locals, serviceName);\r\n\r\n return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;\r\n }\r\n\r\n return {\r\n invoke: invoke,\r\n instantiate: instantiate,\r\n get: getService,\r\n annotate: createInjector.$$annotate,\r\n has: function(name) {\r\n return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);\r\n }\r\n };\r\n }\r\n}\r\n\r\ncreateInjector.$$annotate = annotate;\r\n\r\n/**\r\n * @ngdoc provider\r\n * @name $anchorScrollProvider\r\n *\r\n * @description\r\n * Use `$anchorScrollProvider` to disable automatic scrolling whenever\r\n * {@link ng.$location#hash $location.hash()} changes.\r\n */\r\nfunction $AnchorScrollProvider() {\r\n\r\n var autoScrollingEnabled = true;\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $anchorScrollProvider#disableAutoScrolling\r\n *\r\n * @description\r\n * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to\r\n * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.
    \r\n * Use this method to disable automatic scrolling.\r\n *\r\n * If automatic scrolling is disabled, one must explicitly call\r\n * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the\r\n * current hash.\r\n */\r\n this.disableAutoScrolling = function() {\r\n autoScrollingEnabled = false;\r\n };\r\n\r\n /**\r\n * @ngdoc service\r\n * @name $anchorScroll\r\n * @kind function\r\n * @requires $window\r\n * @requires $location\r\n * @requires $rootScope\r\n *\r\n * @description\r\n * When called, it checks the current value of {@link ng.$location#hash $location.hash()} and\r\n * scrolls to the related element, according to the rules specified in the\r\n * [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).\r\n *\r\n * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to\r\n * match any anchor whenever it changes. This can be disabled by calling\r\n * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.\r\n *\r\n * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a\r\n * vertical scroll-offset (either fixed or dynamic).\r\n *\r\n * @property {(number|function|jqLite)} yOffset\r\n * If set, specifies a vertical scroll-offset. This is often useful when there are fixed\r\n * positioned elements at the top of the page, such as navbars, headers etc.\r\n *\r\n * `yOffset` can be specified in various ways:\r\n * - **number**: A fixed number of pixels to be used as offset.

    \r\n * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return\r\n * a number representing the offset (in pixels).

    \r\n * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from\r\n * the top of the page to the element's bottom will be used as offset.
    \r\n * **Note**: The element will be taken into account only as long as its `position` is set to\r\n * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust\r\n * their height and/or positioning according to the viewport's size.\r\n *\r\n *
    \r\n *
    \r\n * In order for `yOffset` to work properly, scrolling should take place on the document's root and\r\n * not some child element.\r\n *
    \r\n *\r\n * @example\r\n \r\n \r\n
    \r\n Go to bottom\r\n You're at the bottom!\r\n
    \r\n
    \r\n \r\n angular.module('anchorScrollExample', [])\r\n .controller('ScrollController', ['$scope', '$location', '$anchorScroll',\r\n function ($scope, $location, $anchorScroll) {\r\n $scope.gotoBottom = function() {\r\n // set the location.hash to the id of\r\n // the element you wish to scroll to.\r\n $location.hash('bottom');\r\n\r\n // call $anchorScroll()\r\n $anchorScroll();\r\n };\r\n }]);\r\n \r\n \r\n #scrollArea {\r\n height: 280px;\r\n overflow: auto;\r\n }\r\n\r\n #bottom {\r\n display: block;\r\n margin-top: 2000px;\r\n }\r\n \r\n
    \r\n *\r\n *
    \r\n * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).\r\n * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.\r\n *\r\n * @example\r\n \r\n \r\n \r\n
    \r\n Anchor {{x}} of 5\r\n
    \r\n
    \r\n \r\n angular.module('anchorScrollOffsetExample', [])\r\n .run(['$anchorScroll', function($anchorScroll) {\r\n $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels\r\n }])\r\n .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',\r\n function ($anchorScroll, $location, $scope) {\r\n $scope.gotoAnchor = function(x) {\r\n var newHash = 'anchor' + x;\r\n if ($location.hash() !== newHash) {\r\n // set the $location.hash to `newHash` and\r\n // $anchorScroll will automatically scroll to it\r\n $location.hash('anchor' + x);\r\n } else {\r\n // call $anchorScroll() explicitly,\r\n // since $location.hash hasn't changed\r\n $anchorScroll();\r\n }\r\n };\r\n }\r\n ]);\r\n \r\n \r\n body {\r\n padding-top: 50px;\r\n }\r\n\r\n .anchor {\r\n border: 2px dashed DarkOrchid;\r\n padding: 10px 10px 200px 10px;\r\n }\r\n\r\n .fixed-header {\r\n background-color: rgba(0, 0, 0, 0.2);\r\n height: 50px;\r\n position: fixed;\r\n top: 0; left: 0; right: 0;\r\n }\r\n\r\n .fixed-header > a {\r\n display: inline-block;\r\n margin: 5px 15px;\r\n }\r\n \r\n
    \r\n */\r\n this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {\r\n var document = $window.document;\r\n\r\n // Helper function to get first anchor from a NodeList\r\n // (using `Array#some()` instead of `angular#forEach()` since it's more performant\r\n // and working in all supported browsers.)\r\n function getFirstAnchor(list) {\r\n var result = null;\r\n Array.prototype.some.call(list, function(element) {\r\n if (nodeName_(element) === 'a') {\r\n result = element;\r\n return true;\r\n }\r\n });\r\n return result;\r\n }\r\n\r\n function getYOffset() {\r\n\r\n var offset = scroll.yOffset;\r\n\r\n if (isFunction(offset)) {\r\n offset = offset();\r\n } else if (isElement(offset)) {\r\n var elem = offset[0];\r\n var style = $window.getComputedStyle(elem);\r\n if (style.position !== 'fixed') {\r\n offset = 0;\r\n } else {\r\n offset = elem.getBoundingClientRect().bottom;\r\n }\r\n } else if (!isNumber(offset)) {\r\n offset = 0;\r\n }\r\n\r\n return offset;\r\n }\r\n\r\n function scrollTo(elem) {\r\n if (elem) {\r\n elem.scrollIntoView();\r\n\r\n var offset = getYOffset();\r\n\r\n if (offset) {\r\n // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.\r\n // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the\r\n // top of the viewport.\r\n //\r\n // IF the number of pixels from the top of `elem` to the end of the page's content is less\r\n // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some\r\n // way down the page.\r\n //\r\n // This is often the case for elements near the bottom of the page.\r\n //\r\n // In such cases we do not need to scroll the whole `offset` up, just the difference between\r\n // the top of the element and the offset, which is enough to align the top of `elem` at the\r\n // desired position.\r\n var elemTop = elem.getBoundingClientRect().top;\r\n $window.scrollBy(0, elemTop - offset);\r\n }\r\n } else {\r\n $window.scrollTo(0, 0);\r\n }\r\n }\r\n\r\n function scroll() {\r\n var hash = $location.hash(), elm;\r\n\r\n // empty hash, scroll to the top of the page\r\n if (!hash) scrollTo(null);\r\n\r\n // element with given id\r\n else if ((elm = document.getElementById(hash))) scrollTo(elm);\r\n\r\n // first anchor with given name :-D\r\n else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);\r\n\r\n // no element and hash == 'top', scroll to the top of the page\r\n else if (hash === 'top') scrollTo(null);\r\n }\r\n\r\n // does not scroll when user clicks on anchor link that is currently on\r\n // (no url change, no $location.hash() change), browser native does scroll\r\n if (autoScrollingEnabled) {\r\n $rootScope.$watch(function autoScrollWatch() {return $location.hash();},\r\n function autoScrollWatchAction(newVal, oldVal) {\r\n // skip the initial scroll if $location.hash is empty\r\n if (newVal === oldVal && newVal === '') return;\r\n\r\n jqLiteDocumentLoaded(function() {\r\n $rootScope.$evalAsync(scroll);\r\n });\r\n });\r\n }\r\n\r\n return scroll;\r\n }];\r\n}\r\n\r\nvar $animateMinErr = minErr('$animate');\r\n\r\n/**\r\n * @ngdoc provider\r\n * @name $animateProvider\r\n *\r\n * @description\r\n * Default implementation of $animate that doesn't perform any animations, instead just\r\n * synchronously performs DOM\r\n * updates and calls done() callbacks.\r\n *\r\n * In order to enable animations the ngAnimate module has to be loaded.\r\n *\r\n * To see the functional implementation check out src/ngAnimate/animate.js\r\n */\r\nvar $AnimateProvider = ['$provide', function($provide) {\r\n\r\n\r\n this.$$selectors = {};\r\n\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $animateProvider#register\r\n *\r\n * @description\r\n * Registers a new injectable animation factory function. The factory function produces the\r\n * animation object which contains callback functions for each event that is expected to be\r\n * animated.\r\n *\r\n * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction`\r\n * must be called once the element animation is complete. If a function is returned then the\r\n * animation service will use this function to cancel the animation whenever a cancel event is\r\n * triggered.\r\n *\r\n *\r\n * ```js\r\n * return {\r\n * eventFn : function(element, done) {\r\n * //code to run the animation\r\n * //once complete, then run done()\r\n * return function cancellationFunction() {\r\n * //code to cancel the animation\r\n * }\r\n * }\r\n * }\r\n * ```\r\n *\r\n * @param {string} name The name of the animation.\r\n * @param {Function} factory The factory function that will be executed to return the animation\r\n * object.\r\n */\r\n this.register = function(name, factory) {\r\n var key = name + '-animation';\r\n if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel',\r\n \"Expecting class selector starting with '.' got '{0}'.\", name);\r\n this.$$selectors[name.substr(1)] = key;\r\n $provide.factory(key, factory);\r\n };\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $animateProvider#classNameFilter\r\n *\r\n * @description\r\n * Sets and/or returns the CSS class regular expression that is checked when performing\r\n * an animation. Upon bootstrap the classNameFilter value is not set at all and will\r\n * therefore enable $animate to attempt to perform an animation on any element.\r\n * When setting the classNameFilter value, animations will only be performed on elements\r\n * that successfully match the filter expression. This in turn can boost performance\r\n * for low-powered devices as well as applications containing a lot of structural operations.\r\n * @param {RegExp=} expression The className expression which will be checked against all animations\r\n * @return {RegExp} The current CSS className expression value. If null then there is no expression value\r\n */\r\n this.classNameFilter = function(expression) {\r\n if (arguments.length === 1) {\r\n this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;\r\n }\r\n return this.$$classNameFilter;\r\n };\r\n\r\n this.$get = ['$$q', '$$asyncCallback', '$rootScope', function($$q, $$asyncCallback, $rootScope) {\r\n\r\n var currentDefer;\r\n\r\n function runAnimationPostDigest(fn) {\r\n var cancelFn, defer = $$q.defer();\r\n defer.promise.$$cancelFn = function ngAnimateMaybeCancel() {\r\n cancelFn && cancelFn();\r\n };\r\n\r\n $rootScope.$$postDigest(function ngAnimatePostDigest() {\r\n cancelFn = fn(function ngAnimateNotifyComplete() {\r\n defer.resolve();\r\n });\r\n });\r\n\r\n return defer.promise;\r\n }\r\n\r\n function resolveElementClasses(element, classes) {\r\n var toAdd = [], toRemove = [];\r\n\r\n var hasClasses = createMap();\r\n forEach((element.attr('class') || '').split(/\\s+/), function(className) {\r\n hasClasses[className] = true;\r\n });\r\n\r\n forEach(classes, function(status, className) {\r\n var hasClass = hasClasses[className];\r\n\r\n // If the most recent class manipulation (via $animate) was to remove the class, and the\r\n // element currently has the class, the class is scheduled for removal. Otherwise, if\r\n // the most recent class manipulation (via $animate) was to add the class, and the\r\n // element does not currently have the class, the class is scheduled to be added.\r\n if (status === false && hasClass) {\r\n toRemove.push(className);\r\n } else if (status === true && !hasClass) {\r\n toAdd.push(className);\r\n }\r\n });\r\n\r\n return (toAdd.length + toRemove.length) > 0 &&\r\n [toAdd.length ? toAdd : null, toRemove.length ? toRemove : null];\r\n }\r\n\r\n function cachedClassManipulation(cache, classes, op) {\r\n for (var i=0, ii = classes.length; i < ii; ++i) {\r\n var className = classes[i];\r\n cache[className] = op;\r\n }\r\n }\r\n\r\n function asyncPromise() {\r\n // only serve one instance of a promise in order to save CPU cycles\r\n if (!currentDefer) {\r\n currentDefer = $$q.defer();\r\n $$asyncCallback(function() {\r\n currentDefer.resolve();\r\n currentDefer = null;\r\n });\r\n }\r\n return currentDefer.promise;\r\n }\r\n\r\n function applyStyles(element, options) {\r\n if (angular.isObject(options)) {\r\n var styles = extend(options.from || {}, options.to || {});\r\n element.css(styles);\r\n }\r\n }\r\n\r\n /**\r\n *\r\n * @ngdoc service\r\n * @name $animate\r\n * @description The $animate service provides rudimentary DOM manipulation functions to\r\n * insert, remove and move elements within the DOM, as well as adding and removing classes.\r\n * This service is the core service used by the ngAnimate $animator service which provides\r\n * high-level animation hooks for CSS and JavaScript.\r\n *\r\n * $animate is available in the AngularJS core, however, the ngAnimate module must be included\r\n * to enable full out animation support. Otherwise, $animate will only perform simple DOM\r\n * manipulation operations.\r\n *\r\n * To learn more about enabling animation support, click here to visit the {@link ngAnimate\r\n * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service\r\n * page}.\r\n */\r\n return {\r\n animate: function(element, from, to) {\r\n applyStyles(element, { from: from, to: to });\r\n return asyncPromise();\r\n },\r\n\r\n /**\r\n *\r\n * @ngdoc method\r\n * @name $animate#enter\r\n * @kind function\r\n * @description Inserts the element into the DOM either after the `after` element or\r\n * as the first child within the `parent` element. When the function is called a promise\r\n * is returned that will be resolved at a later time.\r\n * @param {DOMElement} element the element which will be inserted into the DOM\r\n * @param {DOMElement} parent the parent element which will append the element as\r\n * a child (if the after element is not present)\r\n * @param {DOMElement} after the sibling element which will append the element\r\n * after itself\r\n * @param {object=} options an optional collection of styles that will be applied to the element.\r\n * @return {Promise} the animation callback promise\r\n */\r\n enter: function(element, parent, after, options) {\r\n applyStyles(element, options);\r\n after ? after.after(element)\r\n : parent.prepend(element);\r\n return asyncPromise();\r\n },\r\n\r\n /**\r\n *\r\n * @ngdoc method\r\n * @name $animate#leave\r\n * @kind function\r\n * @description Removes the element from the DOM. When the function is called a promise\r\n * is returned that will be resolved at a later time.\r\n * @param {DOMElement} element the element which will be removed from the DOM\r\n * @param {object=} options an optional collection of options that will be applied to the element.\r\n * @return {Promise} the animation callback promise\r\n */\r\n leave: function(element, options) {\r\n applyStyles(element, options);\r\n element.remove();\r\n return asyncPromise();\r\n },\r\n\r\n /**\r\n *\r\n * @ngdoc method\r\n * @name $animate#move\r\n * @kind function\r\n * @description Moves the position of the provided element within the DOM to be placed\r\n * either after the `after` element or inside of the `parent` element. When the function\r\n * is called a promise is returned that will be resolved at a later time.\r\n *\r\n * @param {DOMElement} element the element which will be moved around within the\r\n * DOM\r\n * @param {DOMElement} parent the parent element where the element will be\r\n * inserted into (if the after element is not present)\r\n * @param {DOMElement} after the sibling element where the element will be\r\n * positioned next to\r\n * @param {object=} options an optional collection of options that will be applied to the element.\r\n * @return {Promise} the animation callback promise\r\n */\r\n move: function(element, parent, after, options) {\r\n // Do not remove element before insert. Removing will cause data associated with the\r\n // element to be dropped. Insert will implicitly do the remove.\r\n return this.enter(element, parent, after, options);\r\n },\r\n\r\n /**\r\n *\r\n * @ngdoc method\r\n * @name $animate#addClass\r\n * @kind function\r\n * @description Adds the provided className CSS class value to the provided element.\r\n * When the function is called a promise is returned that will be resolved at a later time.\r\n * @param {DOMElement} element the element which will have the className value\r\n * added to it\r\n * @param {string} className the CSS class which will be added to the element\r\n * @param {object=} options an optional collection of options that will be applied to the element.\r\n * @return {Promise} the animation callback promise\r\n */\r\n addClass: function(element, className, options) {\r\n return this.setClass(element, className, [], options);\r\n },\r\n\r\n $$addClassImmediately: function(element, className, options) {\r\n element = jqLite(element);\r\n className = !isString(className)\r\n ? (isArray(className) ? className.join(' ') : '')\r\n : className;\r\n forEach(element, function(element) {\r\n jqLiteAddClass(element, className);\r\n });\r\n applyStyles(element, options);\r\n return asyncPromise();\r\n },\r\n\r\n /**\r\n *\r\n * @ngdoc method\r\n * @name $animate#removeClass\r\n * @kind function\r\n * @description Removes the provided className CSS class value from the provided element.\r\n * When the function is called a promise is returned that will be resolved at a later time.\r\n * @param {DOMElement} element the element which will have the className value\r\n * removed from it\r\n * @param {string} className the CSS class which will be removed from the element\r\n * @param {object=} options an optional collection of options that will be applied to the element.\r\n * @return {Promise} the animation callback promise\r\n */\r\n removeClass: function(element, className, options) {\r\n return this.setClass(element, [], className, options);\r\n },\r\n\r\n $$removeClassImmediately: function(element, className, options) {\r\n element = jqLite(element);\r\n className = !isString(className)\r\n ? (isArray(className) ? className.join(' ') : '')\r\n : className;\r\n forEach(element, function(element) {\r\n jqLiteRemoveClass(element, className);\r\n });\r\n applyStyles(element, options);\r\n return asyncPromise();\r\n },\r\n\r\n /**\r\n *\r\n * @ngdoc method\r\n * @name $animate#setClass\r\n * @kind function\r\n * @description Adds and/or removes the given CSS classes to and from the element.\r\n * When the function is called a promise is returned that will be resolved at a later time.\r\n * @param {DOMElement} element the element which will have its CSS classes changed\r\n * removed from it\r\n * @param {string} add the CSS classes which will be added to the element\r\n * @param {string} remove the CSS class which will be removed from the element\r\n * @param {object=} options an optional collection of options that will be applied to the element.\r\n * @return {Promise} the animation callback promise\r\n */\r\n setClass: function(element, add, remove, options) {\r\n var self = this;\r\n var STORAGE_KEY = '$$animateClasses';\r\n var createdCache = false;\r\n element = jqLite(element);\r\n\r\n var cache = element.data(STORAGE_KEY);\r\n if (!cache) {\r\n cache = {\r\n classes: {},\r\n options: options\r\n };\r\n createdCache = true;\r\n } else if (options && cache.options) {\r\n cache.options = angular.extend(cache.options || {}, options);\r\n }\r\n\r\n var classes = cache.classes;\r\n\r\n add = isArray(add) ? add : add.split(' ');\r\n remove = isArray(remove) ? remove : remove.split(' ');\r\n cachedClassManipulation(classes, add, true);\r\n cachedClassManipulation(classes, remove, false);\r\n\r\n if (createdCache) {\r\n cache.promise = runAnimationPostDigest(function(done) {\r\n var cache = element.data(STORAGE_KEY);\r\n element.removeData(STORAGE_KEY);\r\n\r\n // in the event that the element is removed before postDigest\r\n // is run then the cache will be undefined and there will be\r\n // no need anymore to add or remove and of the element classes\r\n if (cache) {\r\n var classes = resolveElementClasses(element, cache.classes);\r\n if (classes) {\r\n self.$$setClassImmediately(element, classes[0], classes[1], cache.options);\r\n }\r\n }\r\n\r\n done();\r\n });\r\n element.data(STORAGE_KEY, cache);\r\n }\r\n\r\n return cache.promise;\r\n },\r\n\r\n $$setClassImmediately: function(element, add, remove, options) {\r\n add && this.$$addClassImmediately(element, add);\r\n remove && this.$$removeClassImmediately(element, remove);\r\n applyStyles(element, options);\r\n return asyncPromise();\r\n },\r\n\r\n enabled: noop,\r\n cancel: noop\r\n };\r\n }];\r\n}];\r\n\r\nfunction $$AsyncCallbackProvider() {\r\n this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) {\r\n return $$rAF.supported\r\n ? function(fn) { return $$rAF(fn); }\r\n : function(fn) {\r\n return $timeout(fn, 0, false);\r\n };\r\n }];\r\n}\r\n\r\n/* global stripHash: true */\r\n\r\n/**\r\n * ! This is a private undocumented service !\r\n *\r\n * @name $browser\r\n * @requires $log\r\n * @description\r\n * This object has two goals:\r\n *\r\n * - hide all the global state in the browser caused by the window object\r\n * - abstract away all the browser specific features and inconsistencies\r\n *\r\n * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`\r\n * service, which can be used for convenient testing of the application without the interaction with\r\n * the real browser apis.\r\n */\r\n/**\r\n * @param {object} window The global window object.\r\n * @param {object} document jQuery wrapped document.\r\n * @param {object} $log window.console or an object with the same interface.\r\n * @param {object} $sniffer $sniffer service\r\n */\r\nfunction Browser(window, document, $log, $sniffer) {\r\n var self = this,\r\n rawDocument = document[0],\r\n location = window.location,\r\n history = window.history,\r\n setTimeout = window.setTimeout,\r\n clearTimeout = window.clearTimeout,\r\n pendingDeferIds = {};\r\n\r\n self.isMock = false;\r\n\r\n var outstandingRequestCount = 0;\r\n var outstandingRequestCallbacks = [];\r\n\r\n // TODO(vojta): remove this temporary api\r\n self.$$completeOutstandingRequest = completeOutstandingRequest;\r\n self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };\r\n\r\n /**\r\n * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`\r\n * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.\r\n */\r\n function completeOutstandingRequest(fn) {\r\n try {\r\n fn.apply(null, sliceArgs(arguments, 1));\r\n } finally {\r\n outstandingRequestCount--;\r\n if (outstandingRequestCount === 0) {\r\n while (outstandingRequestCallbacks.length) {\r\n try {\r\n outstandingRequestCallbacks.pop()();\r\n } catch (e) {\r\n $log.error(e);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n function getHash(url) {\r\n var index = url.indexOf('#');\r\n return index === -1 ? '' : url.substr(index);\r\n }\r\n\r\n /**\r\n * @private\r\n * Note: this method is used only by scenario runner\r\n * TODO(vojta): prefix this method with $$ ?\r\n * @param {function()} callback Function that will be called when no outstanding request\r\n */\r\n self.notifyWhenNoOutstandingRequests = function(callback) {\r\n // force browser to execute all pollFns - this is needed so that cookies and other pollers fire\r\n // at some deterministic time in respect to the test runner's actions. Leaving things up to the\r\n // regular poller would result in flaky tests.\r\n forEach(pollFns, function(pollFn) { pollFn(); });\r\n\r\n if (outstandingRequestCount === 0) {\r\n callback();\r\n } else {\r\n outstandingRequestCallbacks.push(callback);\r\n }\r\n };\r\n\r\n //////////////////////////////////////////////////////////////\r\n // Poll Watcher API\r\n //////////////////////////////////////////////////////////////\r\n var pollFns = [],\r\n pollTimeout;\r\n\r\n /**\r\n * @name $browser#addPollFn\r\n *\r\n * @param {function()} fn Poll function to add\r\n *\r\n * @description\r\n * Adds a function to the list of functions that poller periodically executes,\r\n * and starts polling if not started yet.\r\n *\r\n * @returns {function()} the added function\r\n */\r\n self.addPollFn = function(fn) {\r\n if (isUndefined(pollTimeout)) startPoller(100, setTimeout);\r\n pollFns.push(fn);\r\n return fn;\r\n };\r\n\r\n /**\r\n * @param {number} interval How often should browser call poll functions (ms)\r\n * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.\r\n *\r\n * @description\r\n * Configures the poller to run in the specified intervals, using the specified\r\n * setTimeout fn and kicks it off.\r\n */\r\n function startPoller(interval, setTimeout) {\r\n (function check() {\r\n forEach(pollFns, function(pollFn) { pollFn(); });\r\n pollTimeout = setTimeout(check, interval);\r\n })();\r\n }\r\n\r\n //////////////////////////////////////////////////////////////\r\n // URL API\r\n //////////////////////////////////////////////////////////////\r\n\r\n var cachedState, lastHistoryState,\r\n lastBrowserUrl = location.href,\r\n baseElement = document.find('base'),\r\n reloadLocation = null;\r\n\r\n cacheState();\r\n lastHistoryState = cachedState;\r\n\r\n /**\r\n * @name $browser#url\r\n *\r\n * @description\r\n * GETTER:\r\n * Without any argument, this method just returns current value of location.href.\r\n *\r\n * SETTER:\r\n * With at least one argument, this method sets url to new value.\r\n * If html5 history api supported, pushState/replaceState is used, otherwise\r\n * location.href/location.replace is used.\r\n * Returns its own instance to allow chaining\r\n *\r\n * NOTE: this api is intended for use only by the $location service. Please use the\r\n * {@link ng.$location $location service} to change url.\r\n *\r\n * @param {string} url New url (when used as setter)\r\n * @param {boolean=} replace Should new url replace current history record?\r\n * @param {object=} state object to use with pushState/replaceState\r\n */\r\n self.url = function(url, replace, state) {\r\n // In modern browsers `history.state` is `null` by default; treating it separately\r\n // from `undefined` would cause `$browser.url('/foo')` to change `history.state`\r\n // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.\r\n if (isUndefined(state)) {\r\n state = null;\r\n }\r\n\r\n // Android Browser BFCache causes location, history reference to become stale.\r\n if (location !== window.location) location = window.location;\r\n if (history !== window.history) history = window.history;\r\n\r\n // setter\r\n if (url) {\r\n var sameState = lastHistoryState === state;\r\n\r\n // Don't change anything if previous and current URLs and states match. This also prevents\r\n // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.\r\n // See https://github.com/angular/angular.js/commit/ffb2701\r\n if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {\r\n return self;\r\n }\r\n var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);\r\n lastBrowserUrl = url;\r\n lastHistoryState = state;\r\n // Don't use history API if only the hash changed\r\n // due to a bug in IE10/IE11 which leads\r\n // to not firing a `hashchange` nor `popstate` event\r\n // in some cases (see #9143).\r\n if ($sniffer.history && (!sameBase || !sameState)) {\r\n history[replace ? 'replaceState' : 'pushState'](state, '', url);\r\n cacheState();\r\n // Do the assignment again so that those two variables are referentially identical.\r\n lastHistoryState = cachedState;\r\n } else {\r\n if (!sameBase || reloadLocation) {\r\n reloadLocation = url;\r\n }\r\n if (replace) {\r\n location.replace(url);\r\n } else if (!sameBase) {\r\n location.href = url;\r\n } else {\r\n location.hash = getHash(url);\r\n }\r\n }\r\n return self;\r\n // getter\r\n } else {\r\n // - reloadLocation is needed as browsers don't allow to read out\r\n // the new location.href if a reload happened.\r\n // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172\r\n return reloadLocation || location.href.replace(/%27/g,\"'\");\r\n }\r\n };\r\n\r\n /**\r\n * @name $browser#state\r\n *\r\n * @description\r\n * This method is a getter.\r\n *\r\n * Return history.state or null if history.state is undefined.\r\n *\r\n * @returns {object} state\r\n */\r\n self.state = function() {\r\n return cachedState;\r\n };\r\n\r\n var urlChangeListeners = [],\r\n urlChangeInit = false;\r\n\r\n function cacheStateAndFireUrlChange() {\r\n cacheState();\r\n fireUrlChange();\r\n }\r\n\r\n function getCurrentState() {\r\n try {\r\n return history.state;\r\n } catch (e) {\r\n // MSIE can reportedly throw when there is no state (UNCONFIRMED).\r\n }\r\n }\r\n\r\n // This variable should be used *only* inside the cacheState function.\r\n var lastCachedState = null;\r\n function cacheState() {\r\n // This should be the only place in $browser where `history.state` is read.\r\n cachedState = getCurrentState();\r\n cachedState = isUndefined(cachedState) ? null : cachedState;\r\n\r\n // Prevent callbacks fo fire twice if both hashchange & popstate were fired.\r\n if (equals(cachedState, lastCachedState)) {\r\n cachedState = lastCachedState;\r\n }\r\n lastCachedState = cachedState;\r\n }\r\n\r\n function fireUrlChange() {\r\n if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {\r\n return;\r\n }\r\n\r\n lastBrowserUrl = self.url();\r\n lastHistoryState = cachedState;\r\n forEach(urlChangeListeners, function(listener) {\r\n listener(self.url(), cachedState);\r\n });\r\n }\r\n\r\n /**\r\n * @name $browser#onUrlChange\r\n *\r\n * @description\r\n * Register callback function that will be called, when url changes.\r\n *\r\n * It's only called when the url is changed from outside of angular:\r\n * - user types different url into address bar\r\n * - user clicks on history (forward/back) button\r\n * - user clicks on a link\r\n *\r\n * It's not called when url is changed by $browser.url() method\r\n *\r\n * The listener gets called with new url as parameter.\r\n *\r\n * NOTE: this api is intended for use only by the $location service. Please use the\r\n * {@link ng.$location $location service} to monitor url changes in angular apps.\r\n *\r\n * @param {function(string)} listener Listener function to be called when url changes.\r\n * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.\r\n */\r\n self.onUrlChange = function(callback) {\r\n // TODO(vojta): refactor to use node's syntax for events\r\n if (!urlChangeInit) {\r\n // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)\r\n // don't fire popstate when user change the address bar and don't fire hashchange when url\r\n // changed by push/replaceState\r\n\r\n // html5 history api - popstate event\r\n if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);\r\n // hashchange event\r\n jqLite(window).on('hashchange', cacheStateAndFireUrlChange);\r\n\r\n urlChangeInit = true;\r\n }\r\n\r\n urlChangeListeners.push(callback);\r\n return callback;\r\n };\r\n\r\n /**\r\n * Checks whether the url has changed outside of Angular.\r\n * Needs to be exported to be able to check for changes that have been done in sync,\r\n * as hashchange/popstate events fire in async.\r\n */\r\n self.$$checkUrlChange = fireUrlChange;\r\n\r\n //////////////////////////////////////////////////////////////\r\n // Misc API\r\n //////////////////////////////////////////////////////////////\r\n\r\n /**\r\n * @name $browser#baseHref\r\n *\r\n * @description\r\n * Returns current \r\n * (always relative - without domain)\r\n *\r\n * @returns {string} The current base href\r\n */\r\n self.baseHref = function() {\r\n var href = baseElement.attr('href');\r\n return href ? href.replace(/^(https?\\:)?\\/\\/[^\\/]*/, '') : '';\r\n };\r\n\r\n //////////////////////////////////////////////////////////////\r\n // Cookies API\r\n //////////////////////////////////////////////////////////////\r\n var lastCookies = {};\r\n var lastCookieString = '';\r\n var cookiePath = self.baseHref();\r\n\r\n function safeDecodeURIComponent(str) {\r\n try {\r\n return decodeURIComponent(str);\r\n } catch (e) {\r\n return str;\r\n }\r\n }\r\n\r\n /**\r\n * @name $browser#cookies\r\n *\r\n * @param {string=} name Cookie name\r\n * @param {string=} value Cookie value\r\n *\r\n * @description\r\n * The cookies method provides a 'private' low level access to browser cookies.\r\n * It is not meant to be used directly, use the $cookie service instead.\r\n *\r\n * The return values vary depending on the arguments that the method was called with as follows:\r\n *\r\n * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify\r\n * it\r\n * - cookies(name, value) -> set name to value, if value is undefined delete the cookie\r\n * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that\r\n * way)\r\n *\r\n * @returns {Object} Hash of all cookies (if called without any parameter)\r\n */\r\n self.cookies = function(name, value) {\r\n var cookieLength, cookieArray, cookie, i, index;\r\n\r\n if (name) {\r\n if (value === undefined) {\r\n rawDocument.cookie = encodeURIComponent(name) + \"=;path=\" + cookiePath +\r\n \";expires=Thu, 01 Jan 1970 00:00:00 GMT\";\r\n } else {\r\n if (isString(value)) {\r\n cookieLength = (rawDocument.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) +\r\n ';path=' + cookiePath).length + 1;\r\n\r\n // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:\r\n // - 300 cookies\r\n // - 20 cookies per unique domain\r\n // - 4096 bytes per cookie\r\n if (cookieLength > 4096) {\r\n $log.warn(\"Cookie '\" + name +\r\n \"' possibly not set or overflowed because it was too large (\" +\r\n cookieLength + \" > 4096 bytes)!\");\r\n }\r\n }\r\n }\r\n } else {\r\n if (rawDocument.cookie !== lastCookieString) {\r\n lastCookieString = rawDocument.cookie;\r\n cookieArray = lastCookieString.split(\"; \");\r\n lastCookies = {};\r\n\r\n for (i = 0; i < cookieArray.length; i++) {\r\n cookie = cookieArray[i];\r\n index = cookie.indexOf('=');\r\n if (index > 0) { //ignore nameless cookies\r\n name = safeDecodeURIComponent(cookie.substring(0, index));\r\n // the first value that is seen for a cookie is the most\r\n // specific one. values for the same cookie name that\r\n // follow are for less specific paths.\r\n if (lastCookies[name] === undefined) {\r\n lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));\r\n }\r\n }\r\n }\r\n }\r\n return lastCookies;\r\n }\r\n };\r\n\r\n\r\n /**\r\n * @name $browser#defer\r\n * @param {function()} fn A function, who's execution should be deferred.\r\n * @param {number=} [delay=0] of milliseconds to defer the function execution.\r\n * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.\r\n *\r\n * @description\r\n * Executes a fn asynchronously via `setTimeout(fn, delay)`.\r\n *\r\n * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using\r\n * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed\r\n * via `$browser.defer.flush()`.\r\n *\r\n */\r\n self.defer = function(fn, delay) {\r\n var timeoutId;\r\n outstandingRequestCount++;\r\n timeoutId = setTimeout(function() {\r\n delete pendingDeferIds[timeoutId];\r\n completeOutstandingRequest(fn);\r\n }, delay || 0);\r\n pendingDeferIds[timeoutId] = true;\r\n return timeoutId;\r\n };\r\n\r\n\r\n /**\r\n * @name $browser#defer.cancel\r\n *\r\n * @description\r\n * Cancels a deferred task identified with `deferId`.\r\n *\r\n * @param {*} deferId Token returned by the `$browser.defer` function.\r\n * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully\r\n * canceled.\r\n */\r\n self.defer.cancel = function(deferId) {\r\n if (pendingDeferIds[deferId]) {\r\n delete pendingDeferIds[deferId];\r\n clearTimeout(deferId);\r\n completeOutstandingRequest(noop);\r\n return true;\r\n }\r\n return false;\r\n };\r\n\r\n}\r\n\r\nfunction $BrowserProvider() {\r\n this.$get = ['$window', '$log', '$sniffer', '$document',\r\n function($window, $log, $sniffer, $document) {\r\n return new Browser($window, $document, $log, $sniffer);\r\n }];\r\n}\r\n\r\n/**\r\n * @ngdoc service\r\n * @name $cacheFactory\r\n *\r\n * @description\r\n * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to\r\n * them.\r\n *\r\n * ```js\r\n *\r\n * var cache = $cacheFactory('cacheId');\r\n * expect($cacheFactory.get('cacheId')).toBe(cache);\r\n * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();\r\n *\r\n * cache.put(\"key\", \"value\");\r\n * cache.put(\"another key\", \"another value\");\r\n *\r\n * // We've specified no options on creation\r\n * expect(cache.info()).toEqual({id: 'cacheId', size: 2});\r\n *\r\n * ```\r\n *\r\n *\r\n * @param {string} cacheId Name or id of the newly created cache.\r\n * @param {object=} options Options object that specifies the cache behavior. Properties:\r\n *\r\n * - `{number=}` `capacity` — turns the cache into LRU cache.\r\n *\r\n * @returns {object} Newly created cache object with the following set of methods:\r\n *\r\n * - `{object}` `info()` — Returns id, size, and options of cache.\r\n * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns\r\n * it.\r\n * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.\r\n * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.\r\n * - `{void}` `removeAll()` — Removes all cached values.\r\n * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.\r\n *\r\n * @example\r\n \r\n \r\n
    \r\n \r\n \r\n \r\n\r\n

    Cached Values

    \r\n
    \r\n \r\n : \r\n \r\n
    \r\n\r\n

    Cache Info

    \r\n
    \r\n \r\n : \r\n \r\n
    \r\n
    \r\n
    \r\n \r\n angular.module('cacheExampleApp', []).\r\n controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {\r\n $scope.keys = [];\r\n $scope.cache = $cacheFactory('cacheId');\r\n $scope.put = function(key, value) {\r\n if ($scope.cache.get(key) === undefined) {\r\n $scope.keys.push(key);\r\n }\r\n $scope.cache.put(key, value === undefined ? null : value);\r\n };\r\n }]);\r\n \r\n \r\n p {\r\n margin: 10px 0 3px;\r\n }\r\n \r\n
    \r\n */\r\nfunction $CacheFactoryProvider() {\r\n\r\n this.$get = function() {\r\n var caches = {};\r\n\r\n function cacheFactory(cacheId, options) {\r\n if (cacheId in caches) {\r\n throw minErr('$cacheFactory')('iid', \"CacheId '{0}' is already taken!\", cacheId);\r\n }\r\n\r\n var size = 0,\r\n stats = extend({}, options, {id: cacheId}),\r\n data = {},\r\n capacity = (options && options.capacity) || Number.MAX_VALUE,\r\n lruHash = {},\r\n freshEnd = null,\r\n staleEnd = null;\r\n\r\n /**\r\n * @ngdoc type\r\n * @name $cacheFactory.Cache\r\n *\r\n * @description\r\n * A cache object used to store and retrieve data, primarily used by\r\n * {@link $http $http} and the {@link ng.directive:script script} directive to cache\r\n * templates and other data.\r\n *\r\n * ```js\r\n * angular.module('superCache')\r\n * .factory('superCache', ['$cacheFactory', function($cacheFactory) {\r\n * return $cacheFactory('super-cache');\r\n * }]);\r\n * ```\r\n *\r\n * Example test:\r\n *\r\n * ```js\r\n * it('should behave like a cache', inject(function(superCache) {\r\n * superCache.put('key', 'value');\r\n * superCache.put('another key', 'another value');\r\n *\r\n * expect(superCache.info()).toEqual({\r\n * id: 'super-cache',\r\n * size: 2\r\n * });\r\n *\r\n * superCache.remove('another key');\r\n * expect(superCache.get('another key')).toBeUndefined();\r\n *\r\n * superCache.removeAll();\r\n * expect(superCache.info()).toEqual({\r\n * id: 'super-cache',\r\n * size: 0\r\n * });\r\n * }));\r\n * ```\r\n */\r\n return caches[cacheId] = {\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $cacheFactory.Cache#put\r\n * @kind function\r\n *\r\n * @description\r\n * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be\r\n * retrieved later, and incrementing the size of the cache if the key was not already\r\n * present in the cache. If behaving like an LRU cache, it will also remove stale\r\n * entries from the set.\r\n *\r\n * It will not insert undefined values into the cache.\r\n *\r\n * @param {string} key the key under which the cached data is stored.\r\n * @param {*} value the value to store alongside the key. If it is undefined, the key\r\n * will not be stored.\r\n * @returns {*} the value stored.\r\n */\r\n put: function(key, value) {\r\n if (capacity < Number.MAX_VALUE) {\r\n var lruEntry = lruHash[key] || (lruHash[key] = {key: key});\r\n\r\n refresh(lruEntry);\r\n }\r\n\r\n if (isUndefined(value)) return;\r\n if (!(key in data)) size++;\r\n data[key] = value;\r\n\r\n if (size > capacity) {\r\n this.remove(staleEnd.key);\r\n }\r\n\r\n return value;\r\n },\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $cacheFactory.Cache#get\r\n * @kind function\r\n *\r\n * @description\r\n * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.\r\n *\r\n * @param {string} key the key of the data to be retrieved\r\n * @returns {*} the value stored.\r\n */\r\n get: function(key) {\r\n if (capacity < Number.MAX_VALUE) {\r\n var lruEntry = lruHash[key];\r\n\r\n if (!lruEntry) return;\r\n\r\n refresh(lruEntry);\r\n }\r\n\r\n return data[key];\r\n },\r\n\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $cacheFactory.Cache#remove\r\n * @kind function\r\n *\r\n * @description\r\n * Removes an entry from the {@link $cacheFactory.Cache Cache} object.\r\n *\r\n * @param {string} key the key of the entry to be removed\r\n */\r\n remove: function(key) {\r\n if (capacity < Number.MAX_VALUE) {\r\n var lruEntry = lruHash[key];\r\n\r\n if (!lruEntry) return;\r\n\r\n if (lruEntry == freshEnd) freshEnd = lruEntry.p;\r\n if (lruEntry == staleEnd) staleEnd = lruEntry.n;\r\n link(lruEntry.n,lruEntry.p);\r\n\r\n delete lruHash[key];\r\n }\r\n\r\n delete data[key];\r\n size--;\r\n },\r\n\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $cacheFactory.Cache#removeAll\r\n * @kind function\r\n *\r\n * @description\r\n * Clears the cache object of any entries.\r\n */\r\n removeAll: function() {\r\n data = {};\r\n size = 0;\r\n lruHash = {};\r\n freshEnd = staleEnd = null;\r\n },\r\n\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $cacheFactory.Cache#destroy\r\n * @kind function\r\n *\r\n * @description\r\n * Destroys the {@link $cacheFactory.Cache Cache} object entirely,\r\n * removing it from the {@link $cacheFactory $cacheFactory} set.\r\n */\r\n destroy: function() {\r\n data = null;\r\n stats = null;\r\n lruHash = null;\r\n delete caches[cacheId];\r\n },\r\n\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $cacheFactory.Cache#info\r\n * @kind function\r\n *\r\n * @description\r\n * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.\r\n *\r\n * @returns {object} an object with the following properties:\r\n *
      \r\n *
    • **id**: the id of the cache instance
    • \r\n *
    • **size**: the number of entries kept in the cache instance
    • \r\n *
    • **...**: any additional properties from the options object when creating the\r\n * cache.
    • \r\n *
    \r\n */\r\n info: function() {\r\n return extend({}, stats, {size: size});\r\n }\r\n };\r\n\r\n\r\n /**\r\n * makes the `entry` the freshEnd of the LRU linked list\r\n */\r\n function refresh(entry) {\r\n if (entry != freshEnd) {\r\n if (!staleEnd) {\r\n staleEnd = entry;\r\n } else if (staleEnd == entry) {\r\n staleEnd = entry.n;\r\n }\r\n\r\n link(entry.n, entry.p);\r\n link(entry, freshEnd);\r\n freshEnd = entry;\r\n freshEnd.n = null;\r\n }\r\n }\r\n\r\n\r\n /**\r\n * bidirectionally links two entries of the LRU linked list\r\n */\r\n function link(nextEntry, prevEntry) {\r\n if (nextEntry != prevEntry) {\r\n if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify\r\n if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify\r\n }\r\n }\r\n }\r\n\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $cacheFactory#info\r\n *\r\n * @description\r\n * Get information about all the caches that have been created\r\n *\r\n * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`\r\n */\r\n cacheFactory.info = function() {\r\n var info = {};\r\n forEach(caches, function(cache, cacheId) {\r\n info[cacheId] = cache.info();\r\n });\r\n return info;\r\n };\r\n\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $cacheFactory#get\r\n *\r\n * @description\r\n * Get access to a cache object by the `cacheId` used when it was created.\r\n *\r\n * @param {string} cacheId Name or id of a cache to access.\r\n * @returns {object} Cache object identified by the cacheId or undefined if no such cache.\r\n */\r\n cacheFactory.get = function(cacheId) {\r\n return caches[cacheId];\r\n };\r\n\r\n\r\n return cacheFactory;\r\n };\r\n}\r\n\r\n/**\r\n * @ngdoc service\r\n * @name $templateCache\r\n *\r\n * @description\r\n * The first time a template is used, it is loaded in the template cache for quick retrieval. You\r\n * can load templates directly into the cache in a `script` tag, or by consuming the\r\n * `$templateCache` service directly.\r\n *\r\n * Adding via the `script` tag:\r\n *\r\n * ```html\r\n * \r\n * ```\r\n *\r\n * **Note:** the `script` tag containing the template does not need to be included in the `head` of\r\n * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,\r\n * element with ng-app attribute), otherwise the template will be ignored.\r\n *\r\n * Adding via the `$templateCache` service:\r\n *\r\n * ```js\r\n * var myApp = angular.module('myApp', []);\r\n * myApp.run(function($templateCache) {\r\n * $templateCache.put('templateId.html', 'This is the content of the template');\r\n * });\r\n * ```\r\n *\r\n * To retrieve the template later, simply use it in your HTML:\r\n * ```html\r\n *
    \r\n * ```\r\n *\r\n * or get it via Javascript:\r\n * ```js\r\n * $templateCache.get('templateId.html')\r\n * ```\r\n *\r\n * See {@link ng.$cacheFactory $cacheFactory}.\r\n *\r\n */\r\nfunction $TemplateCacheProvider() {\r\n this.$get = ['$cacheFactory', function($cacheFactory) {\r\n return $cacheFactory('templates');\r\n }];\r\n}\r\n\r\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\r\n * Any commits to this file should be reviewed with security in mind. *\r\n * Changes to this file can potentially create security vulnerabilities. *\r\n * An approval from 2 Core members with history of modifying *\r\n * this file is required. *\r\n * *\r\n * Does the change somehow allow for arbitrary javascript to be executed? *\r\n * Or allows for someone to change the prototype of built-in objects? *\r\n * Or gives undesired access to variables likes document or window? *\r\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\r\n\r\n/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!\r\n *\r\n * DOM-related variables:\r\n *\r\n * - \"node\" - DOM Node\r\n * - \"element\" - DOM Element or Node\r\n * - \"$node\" or \"$element\" - jqLite-wrapped node or element\r\n *\r\n *\r\n * Compiler related stuff:\r\n *\r\n * - \"linkFn\" - linking fn of a single directive\r\n * - \"nodeLinkFn\" - function that aggregates all linking fns for a particular node\r\n * - \"childLinkFn\" - function that aggregates all linking fns for child nodes of a particular node\r\n * - \"compositeLinkFn\" - function that aggregates all linking fns for a compilation root (nodeList)\r\n */\r\n\r\n\r\n/**\r\n * @ngdoc service\r\n * @name $compile\r\n * @kind function\r\n *\r\n * @description\r\n * Compiles an HTML string or DOM into a template and produces a template function, which\r\n * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.\r\n *\r\n * The compilation is a process of walking the DOM tree and matching DOM elements to\r\n * {@link ng.$compileProvider#directive directives}.\r\n *\r\n *
    \r\n * **Note:** This document is an in-depth reference of all directive options.\r\n * For a gentle introduction to directives with examples of common use cases,\r\n * see the {@link guide/directive directive guide}.\r\n *
    \r\n *\r\n * ## Comprehensive Directive API\r\n *\r\n * There are many different options for a directive.\r\n *\r\n * The difference resides in the return value of the factory function.\r\n * You can either return a \"Directive Definition Object\" (see below) that defines the directive properties,\r\n * or just the `postLink` function (all other properties will have the default values).\r\n *\r\n *
    \r\n * **Best Practice:** It's recommended to use the \"directive definition object\" form.\r\n *
    \r\n *\r\n * Here's an example directive declared with a Directive Definition Object:\r\n *\r\n * ```js\r\n * var myModule = angular.module(...);\r\n *\r\n * myModule.directive('directiveName', function factory(injectables) {\r\n * var directiveDefinitionObject = {\r\n * priority: 0,\r\n * template: '
    ', // or // function(tElement, tAttrs) { ... },\r\n * // or\r\n * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },\r\n * transclude: false,\r\n * restrict: 'A',\r\n * templateNamespace: 'html',\r\n * scope: false,\r\n * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },\r\n * controllerAs: 'stringIdentifier',\r\n * bindToController: false,\r\n * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],\r\n * compile: function compile(tElement, tAttrs, transclude) {\r\n * return {\r\n * pre: function preLink(scope, iElement, iAttrs, controller) { ... },\r\n * post: function postLink(scope, iElement, iAttrs, controller) { ... }\r\n * }\r\n * // or\r\n * // return function postLink( ... ) { ... }\r\n * },\r\n * // or\r\n * // link: {\r\n * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },\r\n * // post: function postLink(scope, iElement, iAttrs, controller) { ... }\r\n * // }\r\n * // or\r\n * // link: function postLink( ... ) { ... }\r\n * };\r\n * return directiveDefinitionObject;\r\n * });\r\n * ```\r\n *\r\n *
    \r\n * **Note:** Any unspecified options will use the default value. You can see the default values below.\r\n *
    \r\n *\r\n * Therefore the above can be simplified as:\r\n *\r\n * ```js\r\n * var myModule = angular.module(...);\r\n *\r\n * myModule.directive('directiveName', function factory(injectables) {\r\n * var directiveDefinitionObject = {\r\n * link: function postLink(scope, iElement, iAttrs) { ... }\r\n * };\r\n * return directiveDefinitionObject;\r\n * // or\r\n * // return function postLink(scope, iElement, iAttrs) { ... }\r\n * });\r\n * ```\r\n *\r\n *\r\n *\r\n * ### Directive Definition Object\r\n *\r\n * The directive definition object provides instructions to the {@link ng.$compile\r\n * compiler}. The attributes are:\r\n *\r\n * #### `multiElement`\r\n * When this property is set to true, the HTML compiler will collect DOM nodes between\r\n * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them\r\n * together as the directive elements. It is recommended that this feature be used on directives\r\n * which are not strictly behavioural (such as {@link ngClick}), and which\r\n * do not manipulate or replace child nodes (such as {@link ngInclude}).\r\n *\r\n * #### `priority`\r\n * When there are multiple directives defined on a single DOM element, sometimes it\r\n * is necessary to specify the order in which the directives are applied. The `priority` is used\r\n * to sort the directives before their `compile` functions get called. Priority is defined as a\r\n * number. Directives with greater numerical `priority` are compiled first. Pre-link functions\r\n * are also run in priority order, but post-link functions are run in reverse order. The order\r\n * of directives with the same priority is undefined. The default priority is `0`.\r\n *\r\n * #### `terminal`\r\n * If set to true then the current `priority` will be the last set of directives\r\n * which will execute (any directives at the current priority will still execute\r\n * as the order of execution on same `priority` is undefined). Note that expressions\r\n * and other directives used in the directive's template will also be excluded from execution.\r\n *\r\n * #### `scope`\r\n * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the\r\n * same element request a new scope, only one new scope is created. The new scope rule does not\r\n * apply for the root of the template since the root of the template always gets a new scope.\r\n *\r\n * **If set to `{}` (object hash),** then a new \"isolate\" scope is created. The 'isolate' scope differs from\r\n * normal scope in that it does not prototypically inherit from the parent scope. This is useful\r\n * when creating reusable components, which should not accidentally read or modify data in the\r\n * parent scope.\r\n *\r\n * The 'isolate' scope takes an object hash which defines a set of local scope properties\r\n * derived from the parent scope. These local properties are useful for aliasing values for\r\n * templates. Locals definition is a hash of local scope property to its source:\r\n *\r\n * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is\r\n * always a string since DOM attributes are strings. If no `attr` name is specified then the\r\n * attribute name is assumed to be the same as the local name.\r\n * Given `` and widget definition\r\n * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect\r\n * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the\r\n * `localName` property on the widget scope. The `name` is read from the parent scope (not\r\n * component scope).\r\n *\r\n * * `=` or `=attr` - set up bi-directional binding between a local scope property and the\r\n * parent scope property of name defined via the value of the `attr` attribute. If no `attr`\r\n * name is specified then the attribute name is assumed to be the same as the local name.\r\n * Given `` and widget definition of\r\n * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the\r\n * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected\r\n * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent\r\n * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You\r\n * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If\r\n * you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use\r\n * `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).\r\n *\r\n * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.\r\n * If no `attr` name is specified then the attribute name is assumed to be the same as the\r\n * local name. Given `` and widget definition of\r\n * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to\r\n * a function wrapper for the `count = count + value` expression. Often it's desirable to\r\n * pass data from the isolated scope via an expression to the parent scope, this can be\r\n * done by passing a map of local variable names and values into the expression wrapper fn.\r\n * For example, if the expression is `increment(amount)` then we can specify the amount value\r\n * by calling the `localFn` as `localFn({amount: 22})`.\r\n *\r\n *\r\n * #### `bindToController`\r\n * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will\r\n * allow a component to have its properties bound to the controller, rather than to scope. When the controller\r\n * is instantiated, the initial values of the isolate scope bindings are already available.\r\n *\r\n * #### `controller`\r\n * Controller constructor function. The controller is instantiated before the\r\n * pre-linking phase and it is shared with other directives (see\r\n * `require` attribute). This allows the directives to communicate with each other and augment\r\n * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:\r\n *\r\n * * `$scope` - Current scope associated with the element\r\n * * `$element` - Current element\r\n * * `$attrs` - Current attributes object for the element\r\n * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:\r\n * `function([scope], cloneLinkingFn, futureParentElement)`.\r\n * * `scope`: optional argument to override the scope.\r\n * * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.\r\n * * `futureParentElement`:\r\n * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.\r\n * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.\r\n * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)\r\n * and when the `cloneLinkinFn` is passed,\r\n * as those elements need to created and cloned in a special way when they are defined outside their\r\n * usual containers (e.g. like ``).\r\n * * See also the `directive.templateNamespace` property.\r\n *\r\n *\r\n * #### `require`\r\n * Require another directive and inject its controller as the fourth argument to the linking function. The\r\n * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the\r\n * injected argument will be an array in corresponding order. If no such directive can be\r\n * found, or if the directive does not have a controller, then an error is raised (unless no link function\r\n * is specified, in which case error checking is skipped). The name can be prefixed with:\r\n *\r\n * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.\r\n * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.\r\n * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.\r\n * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.\r\n * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass\r\n * `null` to the `link` fn if not found.\r\n * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass\r\n * `null` to the `link` fn if not found.\r\n *\r\n *\r\n * #### `controllerAs`\r\n * Controller alias at the directive scope. An alias for the controller so it\r\n * can be referenced at the directive template. The directive needs to define a scope for this\r\n * configuration to be used. Useful in the case when directive is used as component.\r\n *\r\n *\r\n * #### `restrict`\r\n * String of subset of `EACM` which restricts the directive to a specific directive\r\n * declaration style. If omitted, the defaults (elements and attributes) are used.\r\n *\r\n * * `E` - Element name (default): ``\r\n * * `A` - Attribute (default): `
    `\r\n * * `C` - Class: `
    `\r\n * * `M` - Comment: ``\r\n *\r\n *\r\n * #### `templateNamespace`\r\n * String representing the document type used by the markup in the template.\r\n * AngularJS needs this information as those elements need to be created and cloned\r\n * in a special way when they are defined outside their usual containers like `` and ``.\r\n *\r\n * * `html` - All root nodes in the template are HTML. Root nodes may also be\r\n * top-level elements such as `` or ``.\r\n * * `svg` - The root nodes in the template are SVG elements (excluding ``).\r\n * * `math` - The root nodes in the template are MathML elements (excluding ``).\r\n *\r\n * If no `templateNamespace` is specified, then the namespace is considered to be `html`.\r\n *\r\n * #### `template`\r\n * HTML markup that may:\r\n * * Replace the contents of the directive's element (default).\r\n * * Replace the directive's element itself (if `replace` is true - DEPRECATED).\r\n * * Wrap the contents of the directive's element (if `transclude` is true).\r\n *\r\n * Value may be:\r\n *\r\n * * A string. For example `
    {{delete_str}}
    `.\r\n * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`\r\n * function api below) and returns a string value.\r\n *\r\n *\r\n * #### `templateUrl`\r\n * This is similar to `template` but the template is loaded from the specified URL, asynchronously.\r\n *\r\n * Because template loading is asynchronous the compiler will suspend compilation of directives on that element\r\n * for later when the template has been resolved. In the meantime it will continue to compile and link\r\n * sibling and parent elements as though this element had not contained any directives.\r\n *\r\n * The compiler does not suspend the entire compilation to wait for templates to be loaded because this\r\n * would result in the whole app \"stalling\" until all templates are loaded asynchronously - even in the\r\n * case when only one deeply nested directive has `templateUrl`.\r\n *\r\n * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}\r\n *\r\n * You can specify `templateUrl` as a string representing the URL or as a function which takes two\r\n * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns\r\n * a string value representing the url. In either case, the template URL is passed through {@link\r\n * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.\r\n *\r\n *\r\n * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)\r\n * specify what the template should replace. Defaults to `false`.\r\n *\r\n * * `true` - the template will replace the directive's element.\r\n * * `false` - the template will replace the contents of the directive's element.\r\n *\r\n * The replacement process migrates all of the attributes / classes from the old element to the new\r\n * one. See the {@link guide/directive#template-expanding-directive\r\n * Directives Guide} for an example.\r\n *\r\n * There are very few scenarios where element replacement is required for the application function,\r\n * the main one being reusable custom components that are used within SVG contexts\r\n * (because SVG doesn't work with custom elements in the DOM tree).\r\n *\r\n * #### `transclude`\r\n * Extract the contents of the element where the directive appears and make it available to the directive.\r\n * The contents are compiled and provided to the directive as a **transclusion function**. See the\r\n * {@link $compile#transclusion Transclusion} section below.\r\n *\r\n * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the\r\n * directive's element or the entire element:\r\n *\r\n * * `true` - transclude the content (i.e. the child nodes) of the directive's element.\r\n * * `'element'` - transclude the whole of the directive's element including any directives on this\r\n * element that defined at a lower priority than this directive. When used, the `template`\r\n * property is ignored.\r\n *\r\n *\r\n * #### `compile`\r\n *\r\n * ```js\r\n * function compile(tElement, tAttrs, transclude) { ... }\r\n * ```\r\n *\r\n * The compile function deals with transforming the template DOM. Since most directives do not do\r\n * template transformation, it is not used often. The compile function takes the following arguments:\r\n *\r\n * * `tElement` - template element - The element where the directive has been declared. It is\r\n * safe to do template transformation on the element and child elements only.\r\n *\r\n * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared\r\n * between all directive compile functions.\r\n *\r\n * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`\r\n *\r\n *
    \r\n * **Note:** The template instance and the link instance may be different objects if the template has\r\n * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that\r\n * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration\r\n * should be done in a linking function rather than in a compile function.\r\n *
    \r\n\r\n *
    \r\n * **Note:** The compile function cannot handle directives that recursively use themselves in their\r\n * own templates or compile functions. Compiling these directives results in an infinite loop and a\r\n * stack overflow errors.\r\n *\r\n * This can be avoided by manually using $compile in the postLink function to imperatively compile\r\n * a directive's template instead of relying on automatic template compilation via `template` or\r\n * `templateUrl` declaration or manual compilation inside the compile function.\r\n *
    \r\n *\r\n *
    \r\n * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it\r\n * e.g. does not know about the right outer scope. Please use the transclude function that is passed\r\n * to the link function instead.\r\n *
    \r\n\r\n * A compile function can have a return value which can be either a function or an object.\r\n *\r\n * * returning a (post-link) function - is equivalent to registering the linking function via the\r\n * `link` property of the config object when the compile function is empty.\r\n *\r\n * * returning an object with function(s) registered via `pre` and `post` properties - allows you to\r\n * control when a linking function should be called during the linking phase. See info about\r\n * pre-linking and post-linking functions below.\r\n *\r\n *\r\n * #### `link`\r\n * This property is used only if the `compile` property is not defined.\r\n *\r\n * ```js\r\n * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }\r\n * ```\r\n *\r\n * The link function is responsible for registering DOM listeners as well as updating the DOM. It is\r\n * executed after the template has been cloned. This is where most of the directive logic will be\r\n * put.\r\n *\r\n * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the\r\n * directive for registering {@link ng.$rootScope.Scope#$watch watches}.\r\n *\r\n * * `iElement` - instance element - The element where the directive is to be used. It is safe to\r\n * manipulate the children of the element only in `postLink` function since the children have\r\n * already been linked.\r\n *\r\n * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared\r\n * between all directive linking functions.\r\n *\r\n * * `controller` - the directive's required controller instance(s) - Instances are shared\r\n * among all directives, which allows the directives to use the controllers as a communication\r\n * channel. The exact value depends on the directive's `require` property:\r\n * * `string`: the controller instance\r\n * * `array`: array of controller instances\r\n * * no controller(s) required: `undefined`\r\n *\r\n * If a required controller cannot be found, and it is optional, the instance is `null`,\r\n * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.\r\n *\r\n * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.\r\n * This is the same as the `$transclude`\r\n * parameter of directive controllers, see there for details.\r\n * `function([scope], cloneLinkingFn, futureParentElement)`.\r\n *\r\n * #### Pre-linking function\r\n *\r\n * Executed before the child elements are linked. Not safe to do DOM transformation since the\r\n * compiler linking function will fail to locate the correct elements for linking.\r\n *\r\n * #### Post-linking function\r\n *\r\n * Executed after the child elements are linked.\r\n *\r\n * Note that child elements that contain `templateUrl` directives will not have been compiled\r\n * and linked since they are waiting for their template to load asynchronously and their own\r\n * compilation and linking has been suspended until that occurs.\r\n *\r\n * It is safe to do DOM transformation in the post-linking function on elements that are not waiting\r\n * for their async templates to be resolved.\r\n *\r\n *\r\n * ### Transclusion\r\n *\r\n * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and\r\n * copying them to another part of the DOM, while maintaining their connection to the original AngularJS\r\n * scope from where they were taken.\r\n *\r\n * Transclusion is used (often with {@link ngTransclude}) to insert the\r\n * original contents of a directive's element into a specified place in the template of the directive.\r\n * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded\r\n * content has access to the properties on the scope from which it was taken, even if the directive\r\n * has isolated scope.\r\n * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.\r\n *\r\n * This makes it possible for the widget to have private state for its template, while the transcluded\r\n * content has access to its originating scope.\r\n *\r\n *
    \r\n * **Note:** When testing an element transclude directive you must not place the directive at the root of the\r\n * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives\r\n * Testing Transclusion Directives}.\r\n *
    \r\n *\r\n * #### Transclusion Functions\r\n *\r\n * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion\r\n * function** to the directive's `link` function and `controller`. This transclusion function is a special\r\n * **linking function** that will return the compiled contents linked to a new transclusion scope.\r\n *\r\n *
    \r\n * If you are just using {@link ngTransclude} then you don't need to worry about this function, since\r\n * ngTransclude will deal with it for us.\r\n *
    \r\n *\r\n * If you want to manually control the insertion and removal of the transcluded content in your directive\r\n * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery\r\n * object that contains the compiled DOM, which is linked to the correct transclusion scope.\r\n *\r\n * When you call a transclusion function you can pass in a **clone attach function**. This function accepts\r\n * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded\r\n * content and the `scope` is the newly created transclusion scope, to which the clone is bound.\r\n *\r\n *
    \r\n * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function\r\n * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.\r\n *
    \r\n *\r\n * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone\r\n * attach function**:\r\n *\r\n * ```js\r\n * var transcludedContent, transclusionScope;\r\n *\r\n * $transclude(function(clone, scope) {\r\n * element.append(clone);\r\n * transcludedContent = clone;\r\n * transclusionScope = scope;\r\n * });\r\n * ```\r\n *\r\n * Later, if you want to remove the transcluded content from your DOM then you should also destroy the\r\n * associated transclusion scope:\r\n *\r\n * ```js\r\n * transcludedContent.remove();\r\n * transclusionScope.$destroy();\r\n * ```\r\n *\r\n *
    \r\n * **Best Practice**: if you intend to add and remove transcluded content manually in your directive\r\n * (by calling the transclude function to get the DOM and and calling `element.remove()` to remove it),\r\n * then you are also responsible for calling `$destroy` on the transclusion scope.\r\n *
    \r\n *\r\n * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}\r\n * automatically destroy their transluded clones as necessary so you do not need to worry about this if\r\n * you are simply using {@link ngTransclude} to inject the transclusion into your directive.\r\n *\r\n *\r\n * #### Transclusion Scopes\r\n *\r\n * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion\r\n * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed\r\n * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it\r\n * was taken.\r\n *\r\n * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look\r\n * like this:\r\n *\r\n * ```html\r\n *
    \r\n *
    \r\n *
    \r\n *
    \r\n *
    \r\n *
    \r\n * ```\r\n *\r\n * The `$parent` scope hierarchy will look like this:\r\n *\r\n * ```\r\n * - $rootScope\r\n * - isolate\r\n * - transclusion\r\n * ```\r\n *\r\n * but the scopes will inherit prototypically from different scopes to their `$parent`.\r\n *\r\n * ```\r\n * - $rootScope\r\n * - transclusion\r\n * - isolate\r\n * ```\r\n *\r\n *\r\n * ### Attributes\r\n *\r\n * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the\r\n * `link()` or `compile()` functions. It has a variety of uses.\r\n *\r\n * accessing *Normalized attribute names:*\r\n * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.\r\n * the attributes object allows for normalized access to\r\n * the attributes.\r\n *\r\n * * *Directive inter-communication:* All directives share the same instance of the attributes\r\n * object which allows the directives to use the attributes object as inter directive\r\n * communication.\r\n *\r\n * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object\r\n * allowing other directives to read the interpolated value.\r\n *\r\n * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes\r\n * that contain interpolation (e.g. `src=\"{{bar}}\"`). Not only is this very efficient but it's also\r\n * the only way to easily get the actual value because during the linking phase the interpolation\r\n * hasn't been evaluated yet and so the value is at this time set to `undefined`.\r\n *\r\n * ```js\r\n * function linkingFn(scope, elm, attrs, ctrl) {\r\n * // get the attribute value\r\n * console.log(attrs.ngModel);\r\n *\r\n * // change the attribute\r\n * attrs.$set('ngModel', 'new value');\r\n *\r\n * // observe changes to interpolated attribute\r\n * attrs.$observe('ngModel', function(value) {\r\n * console.log('ngModel has changed value to ' + value);\r\n * });\r\n * }\r\n * ```\r\n *\r\n * ## Example\r\n *\r\n *
    \r\n * **Note**: Typically directives are registered with `module.directive`. The example below is\r\n * to illustrate how `$compile` works.\r\n *
    \r\n *\r\n \r\n \r\n \r\n
    \r\n
    \r\n
    \r\n
    \r\n
    \r\n
    \r\n \r\n it('should auto compile', function() {\r\n var textarea = $('textarea');\r\n var output = $('div[compile]');\r\n // The initial state reads 'Hello Angular'.\r\n expect(output.getText()).toBe('Hello Angular');\r\n textarea.clear();\r\n textarea.sendKeys('{{name}}!');\r\n expect(output.getText()).toBe('Angular!');\r\n });\r\n \r\n
    \r\n\r\n *\r\n *\r\n * @param {string|DOMElement} element Element or HTML string to compile into a template function.\r\n * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.\r\n *\r\n *
    \r\n * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it\r\n * e.g. will not use the right outer scope. Please pass the transclude function as a\r\n * `parentBoundTranscludeFn` to the link function instead.\r\n *
    \r\n *\r\n * @param {number} maxPriority only apply directives lower than given priority (Only effects the\r\n * root element(s), not their children)\r\n * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template\r\n * (a DOM element/tree) to a scope. Where:\r\n *\r\n * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.\r\n * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the\r\n * `template` and call the `cloneAttachFn` function allowing the caller to attach the\r\n * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is\r\n * called as:
    `cloneAttachFn(clonedElement, scope)` where:\r\n *\r\n * * `clonedElement` - is a clone of the original `element` passed into the compiler.\r\n * * `scope` - is the current scope with which the linking function is working with.\r\n *\r\n * * `options` - An optional object hash with linking options. If `options` is provided, then the following\r\n * keys may be used to control linking behavior:\r\n *\r\n * * `parentBoundTranscludeFn` - the transclude function made available to\r\n * directives; if given, it will be passed through to the link functions of\r\n * directives found in `element` during compilation.\r\n * * `transcludeControllers` - an object hash with keys that map controller names\r\n * to controller instances; if given, it will make the controllers\r\n * available to directives.\r\n * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add\r\n * the cloned elements; only needed for transcludes that are allowed to contain non html\r\n * elements (e.g. SVG elements). See also the directive.controller property.\r\n *\r\n * Calling the linking function returns the element of the template. It is either the original\r\n * element passed in, or the clone of the element if the `cloneAttachFn` is provided.\r\n *\r\n * After linking the view is not updated until after a call to $digest which typically is done by\r\n * Angular automatically.\r\n *\r\n * If you need access to the bound view, there are two ways to do it:\r\n *\r\n * - If you are not asking the linking function to clone the template, create the DOM element(s)\r\n * before you send them to the compiler and keep this reference around.\r\n * ```js\r\n * var element = $compile('

    {{total}}

    ')(scope);\r\n * ```\r\n *\r\n * - if on the other hand, you need the element to be cloned, the view reference from the original\r\n * example would not point to the clone, but rather to the original template that was cloned. In\r\n * this case, you can access the clone via the cloneAttachFn:\r\n * ```js\r\n * var templateElement = angular.element('

    {{total}}

    '),\r\n * scope = ....;\r\n *\r\n * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {\r\n * //attach the clone to DOM document at the right place\r\n * });\r\n *\r\n * //now we have reference to the cloned DOM via `clonedElement`\r\n * ```\r\n *\r\n *\r\n * For information on how the compiler works, see the\r\n * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.\r\n */\r\n\r\nvar $compileMinErr = minErr('$compile');\r\n\r\n/**\r\n * @ngdoc provider\r\n * @name $compileProvider\r\n *\r\n * @description\r\n */\r\n$CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];\r\nfunction $CompileProvider($provide, $$sanitizeUriProvider) {\r\n var hasDirectives = {},\r\n Suffix = 'Directive',\r\n COMMENT_DIRECTIVE_REGEXP = /^\\s*directive\\:\\s*([\\w\\-]+)\\s+(.*)$/,\r\n CLASS_DIRECTIVE_REGEXP = /(([\\w\\-]+)(?:\\:([^;]+))?;?)/,\r\n ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),\r\n REQUIRE_PREFIX_REGEXP = /^(?:(\\^\\^?)?(\\?)?(\\^\\^?)?)?/;\r\n\r\n // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes\r\n // The assumption is that future DOM event attribute names will begin with\r\n // 'on' and be composed of only English letters.\r\n var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;\r\n\r\n function parseIsolateBindings(scope, directiveName) {\r\n var LOCAL_REGEXP = /^\\s*([@&]|=(\\*?))(\\??)\\s*(\\w*)\\s*$/;\r\n\r\n var bindings = {};\r\n\r\n forEach(scope, function(definition, scopeName) {\r\n var match = definition.match(LOCAL_REGEXP);\r\n\r\n if (!match) {\r\n throw $compileMinErr('iscp',\r\n \"Invalid isolate scope definition for directive '{0}'.\" +\r\n \" Definition: {... {1}: '{2}' ...}\",\r\n directiveName, scopeName, definition);\r\n }\r\n\r\n bindings[scopeName] = {\r\n mode: match[1][0],\r\n collection: match[2] === '*',\r\n optional: match[3] === '?',\r\n attrName: match[4] || scopeName\r\n };\r\n });\r\n\r\n return bindings;\r\n }\r\n\r\n function assertValidDirectiveName(name) {\r\n var letter = name.charAt(0);\r\n if (!letter || letter !== lowercase(letter)) {\r\n throw $compileMinErr('baddir', \"Directive name '{0}' is invalid. The first character must be a lowercase letter\", name);\r\n }\r\n return name;\r\n }\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $compileProvider#directive\r\n * @kind function\r\n *\r\n * @description\r\n * Register a new directive with the compiler.\r\n *\r\n * @param {string|Object} name Name of the directive in camel-case (i.e. ngBind which\r\n * will match as ng-bind), or an object map of directives where the keys are the\r\n * names and the values are the factories.\r\n * @param {Function|Array} directiveFactory An injectable directive factory function. See\r\n * {@link guide/directive} for more info.\r\n * @returns {ng.$compileProvider} Self for chaining.\r\n */\r\n this.directive = function registerDirective(name, directiveFactory) {\r\n assertNotHasOwnProperty(name, 'directive');\r\n if (isString(name)) {\r\n assertValidDirectiveName(name);\r\n assertArg(directiveFactory, 'directiveFactory');\r\n if (!hasDirectives.hasOwnProperty(name)) {\r\n hasDirectives[name] = [];\r\n $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',\r\n function($injector, $exceptionHandler) {\r\n var directives = [];\r\n forEach(hasDirectives[name], function(directiveFactory, index) {\r\n try {\r\n var directive = $injector.invoke(directiveFactory);\r\n if (isFunction(directive)) {\r\n directive = { compile: valueFn(directive) };\r\n } else if (!directive.compile && directive.link) {\r\n directive.compile = valueFn(directive.link);\r\n }\r\n directive.priority = directive.priority || 0;\r\n directive.index = index;\r\n directive.name = directive.name || name;\r\n directive.require = directive.require || (directive.controller && directive.name);\r\n directive.restrict = directive.restrict || 'EA';\r\n if (isObject(directive.scope)) {\r\n directive.$$isolateBindings = parseIsolateBindings(directive.scope, directive.name);\r\n }\r\n directives.push(directive);\r\n } catch (e) {\r\n $exceptionHandler(e);\r\n }\r\n });\r\n return directives;\r\n }]);\r\n }\r\n hasDirectives[name].push(directiveFactory);\r\n } else {\r\n forEach(name, reverseParams(registerDirective));\r\n }\r\n return this;\r\n };\r\n\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $compileProvider#aHrefSanitizationWhitelist\r\n * @kind function\r\n *\r\n * @description\r\n * Retrieves or overrides the default regular expression that is used for whitelisting of safe\r\n * urls during a[href] sanitization.\r\n *\r\n * The sanitization is a security measure aimed at preventing XSS attacks via html links.\r\n *\r\n * Any url about to be assigned to a[href] via data-binding is first normalized and turned into\r\n * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`\r\n * regular expression. If a match is found, the original url is written into the dom. Otherwise,\r\n * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\r\n *\r\n * @param {RegExp=} regexp New regexp to whitelist urls with.\r\n * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\r\n * chaining otherwise.\r\n */\r\n this.aHrefSanitizationWhitelist = function(regexp) {\r\n if (isDefined(regexp)) {\r\n $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);\r\n return this;\r\n } else {\r\n return $$sanitizeUriProvider.aHrefSanitizationWhitelist();\r\n }\r\n };\r\n\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $compileProvider#imgSrcSanitizationWhitelist\r\n * @kind function\r\n *\r\n * @description\r\n * Retrieves or overrides the default regular expression that is used for whitelisting of safe\r\n * urls during img[src] sanitization.\r\n *\r\n * The sanitization is a security measure aimed at prevent XSS attacks via html links.\r\n *\r\n * Any url about to be assigned to img[src] via data-binding is first normalized and turned into\r\n * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`\r\n * regular expression. If a match is found, the original url is written into the dom. Otherwise,\r\n * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\r\n *\r\n * @param {RegExp=} regexp New regexp to whitelist urls with.\r\n * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\r\n * chaining otherwise.\r\n */\r\n this.imgSrcSanitizationWhitelist = function(regexp) {\r\n if (isDefined(regexp)) {\r\n $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);\r\n return this;\r\n } else {\r\n return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();\r\n }\r\n };\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $compileProvider#debugInfoEnabled\r\n *\r\n * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the\r\n * current debugInfoEnabled state\r\n * @returns {*} current value if used as getter or itself (chaining) if used as setter\r\n *\r\n * @kind function\r\n *\r\n * @description\r\n * Call this method to enable/disable various debug runtime information in the compiler such as adding\r\n * binding information and a reference to the current scope on to DOM elements.\r\n * If enabled, the compiler will add the following to DOM elements that have been bound to the scope\r\n * * `ng-binding` CSS class\r\n * * `$binding` data property containing an array of the binding expressions\r\n *\r\n * You may want to disable this in production for a significant performance boost. See\r\n * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.\r\n *\r\n * The default value is true.\r\n */\r\n var debugInfoEnabled = true;\r\n this.debugInfoEnabled = function(enabled) {\r\n if (isDefined(enabled)) {\r\n debugInfoEnabled = enabled;\r\n return this;\r\n }\r\n return debugInfoEnabled;\r\n };\r\n\r\n this.$get = [\r\n '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',\r\n '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',\r\n function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,\r\n $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {\r\n\r\n var Attributes = function(element, attributesToCopy) {\r\n if (attributesToCopy) {\r\n var keys = Object.keys(attributesToCopy);\r\n var i, l, key;\r\n\r\n for (i = 0, l = keys.length; i < l; i++) {\r\n key = keys[i];\r\n this[key] = attributesToCopy[key];\r\n }\r\n } else {\r\n this.$attr = {};\r\n }\r\n\r\n this.$$element = element;\r\n };\r\n\r\n Attributes.prototype = {\r\n /**\r\n * @ngdoc method\r\n * @name $compile.directive.Attributes#$normalize\r\n * @kind function\r\n *\r\n * @description\r\n * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or\r\n * `data-`) to its normalized, camelCase form.\r\n *\r\n * Also there is special case for Moz prefix starting with upper case letter.\r\n *\r\n * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}\r\n *\r\n * @param {string} name Name to normalize\r\n */\r\n $normalize: directiveNormalize,\r\n\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $compile.directive.Attributes#$addClass\r\n * @kind function\r\n *\r\n * @description\r\n * Adds the CSS class value specified by the classVal parameter to the element. If animations\r\n * are enabled then an animation will be triggered for the class addition.\r\n *\r\n * @param {string} classVal The className value that will be added to the element\r\n */\r\n $addClass: function(classVal) {\r\n if (classVal && classVal.length > 0) {\r\n $animate.addClass(this.$$element, classVal);\r\n }\r\n },\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $compile.directive.Attributes#$removeClass\r\n * @kind function\r\n *\r\n * @description\r\n * Removes the CSS class value specified by the classVal parameter from the element. If\r\n * animations are enabled then an animation will be triggered for the class removal.\r\n *\r\n * @param {string} classVal The className value that will be removed from the element\r\n */\r\n $removeClass: function(classVal) {\r\n if (classVal && classVal.length > 0) {\r\n $animate.removeClass(this.$$element, classVal);\r\n }\r\n },\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $compile.directive.Attributes#$updateClass\r\n * @kind function\r\n *\r\n * @description\r\n * Adds and removes the appropriate CSS class values to the element based on the difference\r\n * between the new and old CSS class values (specified as newClasses and oldClasses).\r\n *\r\n * @param {string} newClasses The current CSS className value\r\n * @param {string} oldClasses The former CSS className value\r\n */\r\n $updateClass: function(newClasses, oldClasses) {\r\n var toAdd = tokenDifference(newClasses, oldClasses);\r\n if (toAdd && toAdd.length) {\r\n $animate.addClass(this.$$element, toAdd);\r\n }\r\n\r\n var toRemove = tokenDifference(oldClasses, newClasses);\r\n if (toRemove && toRemove.length) {\r\n $animate.removeClass(this.$$element, toRemove);\r\n }\r\n },\r\n\r\n /**\r\n * Set a normalized attribute on the element in a way such that all directives\r\n * can share the attribute. This function properly handles boolean attributes.\r\n * @param {string} key Normalized key. (ie ngAttribute)\r\n * @param {string|boolean} value The value to set. If `null` attribute will be deleted.\r\n * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.\r\n * Defaults to true.\r\n * @param {string=} attrName Optional none normalized name. Defaults to key.\r\n */\r\n $set: function(key, value, writeAttr, attrName) {\r\n // TODO: decide whether or not to throw an error if \"class\"\r\n //is set through this function since it may cause $updateClass to\r\n //become unstable.\r\n\r\n var node = this.$$element[0],\r\n booleanKey = getBooleanAttrName(node, key),\r\n aliasedKey = getAliasedAttrName(node, key),\r\n observer = key,\r\n nodeName;\r\n\r\n if (booleanKey) {\r\n this.$$element.prop(key, value);\r\n attrName = booleanKey;\r\n } else if (aliasedKey) {\r\n this[aliasedKey] = value;\r\n observer = aliasedKey;\r\n }\r\n\r\n this[key] = value;\r\n\r\n // translate normalized key to actual key\r\n if (attrName) {\r\n this.$attr[key] = attrName;\r\n } else {\r\n attrName = this.$attr[key];\r\n if (!attrName) {\r\n this.$attr[key] = attrName = snake_case(key, '-');\r\n }\r\n }\r\n\r\n nodeName = nodeName_(this.$$element);\r\n\r\n if ((nodeName === 'a' && key === 'href') ||\r\n (nodeName === 'img' && key === 'src')) {\r\n // sanitize a[href] and img[src] values\r\n this[key] = value = $$sanitizeUri(value, key === 'src');\r\n } else if (nodeName === 'img' && key === 'srcset') {\r\n // sanitize img[srcset] values\r\n var result = \"\";\r\n\r\n // first check if there are spaces because it's not the same pattern\r\n var trimmedSrcset = trim(value);\r\n // ( 999x ,| 999w ,| ,|, )\r\n var srcPattern = /(\\s+\\d+x\\s*,|\\s+\\d+w\\s*,|\\s+,|,\\s+)/;\r\n var pattern = /\\s/.test(trimmedSrcset) ? srcPattern : /(,)/;\r\n\r\n // split srcset into tuple of uri and descriptor except for the last item\r\n var rawUris = trimmedSrcset.split(pattern);\r\n\r\n // for each tuples\r\n var nbrUrisWith2parts = Math.floor(rawUris.length / 2);\r\n for (var i = 0; i < nbrUrisWith2parts; i++) {\r\n var innerIdx = i * 2;\r\n // sanitize the uri\r\n result += $$sanitizeUri(trim(rawUris[innerIdx]), true);\r\n // add the descriptor\r\n result += (\" \" + trim(rawUris[innerIdx + 1]));\r\n }\r\n\r\n // split the last item into uri and descriptor\r\n var lastTuple = trim(rawUris[i * 2]).split(/\\s/);\r\n\r\n // sanitize the last uri\r\n result += $$sanitizeUri(trim(lastTuple[0]), true);\r\n\r\n // and add the last descriptor if any\r\n if (lastTuple.length === 2) {\r\n result += (\" \" + trim(lastTuple[1]));\r\n }\r\n this[key] = value = result;\r\n }\r\n\r\n if (writeAttr !== false) {\r\n if (value === null || value === undefined) {\r\n this.$$element.removeAttr(attrName);\r\n } else {\r\n this.$$element.attr(attrName, value);\r\n }\r\n }\r\n\r\n // fire observers\r\n var $$observers = this.$$observers;\r\n $$observers && forEach($$observers[observer], function(fn) {\r\n try {\r\n fn(value);\r\n } catch (e) {\r\n $exceptionHandler(e);\r\n }\r\n });\r\n },\r\n\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $compile.directive.Attributes#$observe\r\n * @kind function\r\n *\r\n * @description\r\n * Observes an interpolated attribute.\r\n *\r\n * The observer function will be invoked once during the next `$digest` following\r\n * compilation. The observer is then invoked whenever the interpolated value\r\n * changes.\r\n *\r\n * @param {string} key Normalized key. (ie ngAttribute) .\r\n * @param {function(interpolatedValue)} fn Function that will be called whenever\r\n the interpolated value of the attribute changes.\r\n * See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.\r\n * @returns {function()} Returns a deregistration function for this observer.\r\n */\r\n $observe: function(key, fn) {\r\n var attrs = this,\r\n $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),\r\n listeners = ($$observers[key] || ($$observers[key] = []));\r\n\r\n listeners.push(fn);\r\n $rootScope.$evalAsync(function() {\r\n if (!listeners.$$inter && attrs.hasOwnProperty(key)) {\r\n // no one registered attribute interpolation function, so lets call it manually\r\n fn(attrs[key]);\r\n }\r\n });\r\n\r\n return function() {\r\n arrayRemove(listeners, fn);\r\n };\r\n }\r\n };\r\n\r\n\r\n function safeAddClass($element, className) {\r\n try {\r\n $element.addClass(className);\r\n } catch (e) {\r\n // ignore, since it means that we are trying to set class on\r\n // SVG element, where class name is read-only.\r\n }\r\n }\r\n\r\n\r\n var startSymbol = $interpolate.startSymbol(),\r\n endSymbol = $interpolate.endSymbol(),\r\n denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')\r\n ? identity\r\n : function denormalizeTemplate(template) {\r\n return template.replace(/\\{\\{/g, startSymbol).replace(/}}/g, endSymbol);\r\n },\r\n NG_ATTR_BINDING = /^ngAttr[A-Z]/;\r\n\r\n compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {\r\n var bindings = $element.data('$binding') || [];\r\n\r\n if (isArray(binding)) {\r\n bindings = bindings.concat(binding);\r\n } else {\r\n bindings.push(binding);\r\n }\r\n\r\n $element.data('$binding', bindings);\r\n } : noop;\r\n\r\n compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {\r\n safeAddClass($element, 'ng-binding');\r\n } : noop;\r\n\r\n compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {\r\n var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';\r\n $element.data(dataName, scope);\r\n } : noop;\r\n\r\n compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {\r\n safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');\r\n } : noop;\r\n\r\n return compile;\r\n\r\n //================================\r\n\r\n function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,\r\n previousCompileContext) {\r\n if (!($compileNodes instanceof jqLite)) {\r\n // jquery always rewraps, whereas we need to preserve the original selector so that we can\r\n // modify it.\r\n $compileNodes = jqLite($compileNodes);\r\n }\r\n // We can not compile top level text elements since text nodes can be merged and we will\r\n // not be able to attach scope data to them, so we will wrap them in \r\n forEach($compileNodes, function(node, index) {\r\n if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\\S+/) /* non-empty */ ) {\r\n $compileNodes[index] = jqLite(node).wrap('').parent()[0];\r\n }\r\n });\r\n var compositeLinkFn =\r\n compileNodes($compileNodes, transcludeFn, $compileNodes,\r\n maxPriority, ignoreDirective, previousCompileContext);\r\n compile.$$addScopeClass($compileNodes);\r\n var namespace = null;\r\n return function publicLinkFn(scope, cloneConnectFn, options) {\r\n assertArg(scope, 'scope');\r\n\r\n options = options || {};\r\n var parentBoundTranscludeFn = options.parentBoundTranscludeFn,\r\n transcludeControllers = options.transcludeControllers,\r\n futureParentElement = options.futureParentElement;\r\n\r\n // When `parentBoundTranscludeFn` is passed, it is a\r\n // `controllersBoundTransclude` function (it was previously passed\r\n // as `transclude` to directive.link) so we must unwrap it to get\r\n // its `boundTranscludeFn`\r\n if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {\r\n parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;\r\n }\r\n\r\n if (!namespace) {\r\n namespace = detectNamespaceForChildElements(futureParentElement);\r\n }\r\n var $linkNode;\r\n if (namespace !== 'html') {\r\n // When using a directive with replace:true and templateUrl the $compileNodes\r\n // (or a child element inside of them)\r\n // might change, so we need to recreate the namespace adapted compileNodes\r\n // for call to the link function.\r\n // Note: This will already clone the nodes...\r\n $linkNode = jqLite(\r\n wrapTemplate(namespace, jqLite('
    ').append($compileNodes).html())\r\n );\r\n } else if (cloneConnectFn) {\r\n // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart\r\n // and sometimes changes the structure of the DOM.\r\n $linkNode = JQLitePrototype.clone.call($compileNodes);\r\n } else {\r\n $linkNode = $compileNodes;\r\n }\r\n\r\n if (transcludeControllers) {\r\n for (var controllerName in transcludeControllers) {\r\n $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);\r\n }\r\n }\r\n\r\n compile.$$addScopeInfo($linkNode, scope);\r\n\r\n if (cloneConnectFn) cloneConnectFn($linkNode, scope);\r\n if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);\r\n return $linkNode;\r\n };\r\n }\r\n\r\n function detectNamespaceForChildElements(parentElement) {\r\n // TODO: Make this detect MathML as well...\r\n var node = parentElement && parentElement[0];\r\n if (!node) {\r\n return 'html';\r\n } else {\r\n return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html';\r\n }\r\n }\r\n\r\n /**\r\n * Compile function matches each node in nodeList against the directives. Once all directives\r\n * for a particular node are collected their compile functions are executed. The compile\r\n * functions return values - the linking functions - are combined into a composite linking\r\n * function, which is the a linking function for the node.\r\n *\r\n * @param {NodeList} nodeList an array of nodes or NodeList to compile\r\n * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the\r\n * scope argument is auto-generated to the new child of the transcluded parent scope.\r\n * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then\r\n * the rootElement must be set the jqLite collection of the compile root. This is\r\n * needed so that the jqLite collection items can be replaced with widgets.\r\n * @param {number=} maxPriority Max directive priority.\r\n * @returns {Function} A composite linking function of all of the matched directives or null.\r\n */\r\n function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,\r\n previousCompileContext) {\r\n var linkFns = [],\r\n attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;\r\n\r\n for (var i = 0; i < nodeList.length; i++) {\r\n attrs = new Attributes();\r\n\r\n // we must always refer to nodeList[i] since the nodes can be replaced underneath us.\r\n directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,\r\n ignoreDirective);\r\n\r\n nodeLinkFn = (directives.length)\r\n ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,\r\n null, [], [], previousCompileContext)\r\n : null;\r\n\r\n if (nodeLinkFn && nodeLinkFn.scope) {\r\n compile.$$addScopeClass(attrs.$$element);\r\n }\r\n\r\n childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||\r\n !(childNodes = nodeList[i].childNodes) ||\r\n !childNodes.length)\r\n ? null\r\n : compileNodes(childNodes,\r\n nodeLinkFn ? (\r\n (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)\r\n && nodeLinkFn.transclude) : transcludeFn);\r\n\r\n if (nodeLinkFn || childLinkFn) {\r\n linkFns.push(i, nodeLinkFn, childLinkFn);\r\n linkFnFound = true;\r\n nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;\r\n }\r\n\r\n //use the previous context only for the first element in the virtual group\r\n previousCompileContext = null;\r\n }\r\n\r\n // return a linking function if we have found anything, null otherwise\r\n return linkFnFound ? compositeLinkFn : null;\r\n\r\n function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {\r\n var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;\r\n var stableNodeList;\r\n\r\n\r\n if (nodeLinkFnFound) {\r\n // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our\r\n // offsets don't get screwed up\r\n var nodeListLength = nodeList.length;\r\n stableNodeList = new Array(nodeListLength);\r\n\r\n // create a sparse array by only copying the elements which have a linkFn\r\n for (i = 0; i < linkFns.length; i+=3) {\r\n idx = linkFns[i];\r\n stableNodeList[idx] = nodeList[idx];\r\n }\r\n } else {\r\n stableNodeList = nodeList;\r\n }\r\n\r\n for (i = 0, ii = linkFns.length; i < ii;) {\r\n node = stableNodeList[linkFns[i++]];\r\n nodeLinkFn = linkFns[i++];\r\n childLinkFn = linkFns[i++];\r\n\r\n if (nodeLinkFn) {\r\n if (nodeLinkFn.scope) {\r\n childScope = scope.$new();\r\n compile.$$addScopeInfo(jqLite(node), childScope);\r\n } else {\r\n childScope = scope;\r\n }\r\n\r\n if (nodeLinkFn.transcludeOnThisElement) {\r\n childBoundTranscludeFn = createBoundTranscludeFn(\r\n scope, nodeLinkFn.transclude, parentBoundTranscludeFn,\r\n nodeLinkFn.elementTranscludeOnThisElement);\r\n\r\n } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {\r\n childBoundTranscludeFn = parentBoundTranscludeFn;\r\n\r\n } else if (!parentBoundTranscludeFn && transcludeFn) {\r\n childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);\r\n\r\n } else {\r\n childBoundTranscludeFn = null;\r\n }\r\n\r\n nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);\r\n\r\n } else if (childLinkFn) {\r\n childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);\r\n }\r\n }\r\n }\r\n }\r\n\r\n function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn, elementTransclusion) {\r\n\r\n var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {\r\n\r\n if (!transcludedScope) {\r\n transcludedScope = scope.$new(false, containingScope);\r\n transcludedScope.$$transcluded = true;\r\n }\r\n\r\n return transcludeFn(transcludedScope, cloneFn, {\r\n parentBoundTranscludeFn: previousBoundTranscludeFn,\r\n transcludeControllers: controllers,\r\n futureParentElement: futureParentElement\r\n });\r\n };\r\n\r\n return boundTranscludeFn;\r\n }\r\n\r\n /**\r\n * Looks for directives on the given node and adds them to the directive collection which is\r\n * sorted.\r\n *\r\n * @param node Node to search.\r\n * @param directives An array to which the directives are added to. This array is sorted before\r\n * the function returns.\r\n * @param attrs The shared attrs object which is used to populate the normalized attributes.\r\n * @param {number=} maxPriority Max directive priority.\r\n */\r\n function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {\r\n var nodeType = node.nodeType,\r\n attrsMap = attrs.$attr,\r\n match,\r\n className;\r\n\r\n switch (nodeType) {\r\n case NODE_TYPE_ELEMENT: /* Element */\r\n // use the node name: \r\n addDirective(directives,\r\n directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);\r\n\r\n // iterate over the attributes\r\n for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,\r\n j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {\r\n var attrStartName = false;\r\n var attrEndName = false;\r\n\r\n attr = nAttrs[j];\r\n name = attr.name;\r\n value = trim(attr.value);\r\n\r\n // support ngAttr attribute binding\r\n ngAttrName = directiveNormalize(name);\r\n if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {\r\n name = name.replace(PREFIX_REGEXP, '')\r\n .substr(8).replace(/_(.)/g, function(match, letter) {\r\n return letter.toUpperCase();\r\n });\r\n }\r\n\r\n var directiveNName = ngAttrName.replace(/(Start|End)$/, '');\r\n if (directiveIsMultiElement(directiveNName)) {\r\n if (ngAttrName === directiveNName + 'Start') {\r\n attrStartName = name;\r\n attrEndName = name.substr(0, name.length - 5) + 'end';\r\n name = name.substr(0, name.length - 6);\r\n }\r\n }\r\n\r\n nName = directiveNormalize(name.toLowerCase());\r\n attrsMap[nName] = name;\r\n if (isNgAttr || !attrs.hasOwnProperty(nName)) {\r\n attrs[nName] = value;\r\n if (getBooleanAttrName(node, nName)) {\r\n attrs[nName] = true; // presence means true\r\n }\r\n }\r\n addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);\r\n addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,\r\n attrEndName);\r\n }\r\n\r\n // use class as directive\r\n className = node.className;\r\n if (isObject(className)) {\r\n // Maybe SVGAnimatedString\r\n className = className.animVal;\r\n }\r\n if (isString(className) && className !== '') {\r\n while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {\r\n nName = directiveNormalize(match[2]);\r\n if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {\r\n attrs[nName] = trim(match[3]);\r\n }\r\n className = className.substr(match.index + match[0].length);\r\n }\r\n }\r\n break;\r\n case NODE_TYPE_TEXT: /* Text Node */\r\n addTextInterpolateDirective(directives, node.nodeValue);\r\n break;\r\n case NODE_TYPE_COMMENT: /* Comment */\r\n try {\r\n match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);\r\n if (match) {\r\n nName = directiveNormalize(match[1]);\r\n if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {\r\n attrs[nName] = trim(match[2]);\r\n }\r\n }\r\n } catch (e) {\r\n // turns out that under some circumstances IE9 throws errors when one attempts to read\r\n // comment's node value.\r\n // Just ignore it and continue. (Can't seem to reproduce in test case.)\r\n }\r\n break;\r\n }\r\n\r\n directives.sort(byPriority);\r\n return directives;\r\n }\r\n\r\n /**\r\n * Given a node with an directive-start it collects all of the siblings until it finds\r\n * directive-end.\r\n * @param node\r\n * @param attrStart\r\n * @param attrEnd\r\n * @returns {*}\r\n */\r\n function groupScan(node, attrStart, attrEnd) {\r\n var nodes = [];\r\n var depth = 0;\r\n if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {\r\n do {\r\n if (!node) {\r\n throw $compileMinErr('uterdir',\r\n \"Unterminated attribute, found '{0}' but no matching '{1}' found.\",\r\n attrStart, attrEnd);\r\n }\r\n if (node.nodeType == NODE_TYPE_ELEMENT) {\r\n if (node.hasAttribute(attrStart)) depth++;\r\n if (node.hasAttribute(attrEnd)) depth--;\r\n }\r\n nodes.push(node);\r\n node = node.nextSibling;\r\n } while (depth > 0);\r\n } else {\r\n nodes.push(node);\r\n }\r\n\r\n return jqLite(nodes);\r\n }\r\n\r\n /**\r\n * Wrapper for linking function which converts normal linking function into a grouped\r\n * linking function.\r\n * @param linkFn\r\n * @param attrStart\r\n * @param attrEnd\r\n * @returns {Function}\r\n */\r\n function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {\r\n return function(scope, element, attrs, controllers, transcludeFn) {\r\n element = groupScan(element[0], attrStart, attrEnd);\r\n return linkFn(scope, element, attrs, controllers, transcludeFn);\r\n };\r\n }\r\n\r\n /**\r\n * Once the directives have been collected, their compile functions are executed. This method\r\n * is responsible for inlining directive templates as well as terminating the application\r\n * of the directives if the terminal directive has been reached.\r\n *\r\n * @param {Array} directives Array of collected directives to execute their compile function.\r\n * this needs to be pre-sorted by priority order.\r\n * @param {Node} compileNode The raw DOM node to apply the compile functions to\r\n * @param {Object} templateAttrs The shared attribute function\r\n * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the\r\n * scope argument is auto-generated to the new\r\n * child of the transcluded parent scope.\r\n * @param {JQLite} jqCollection If we are working on the root of the compile tree then this\r\n * argument has the root jqLite array so that we can replace nodes\r\n * on it.\r\n * @param {Object=} originalReplaceDirective An optional directive that will be ignored when\r\n * compiling the transclusion.\r\n * @param {Array.} preLinkFns\r\n * @param {Array.} postLinkFns\r\n * @param {Object} previousCompileContext Context used for previous compilation of the current\r\n * node\r\n * @returns {Function} linkFn\r\n */\r\n function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,\r\n jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,\r\n previousCompileContext) {\r\n previousCompileContext = previousCompileContext || {};\r\n\r\n var terminalPriority = -Number.MAX_VALUE,\r\n newScopeDirective,\r\n controllerDirectives = previousCompileContext.controllerDirectives,\r\n controllers,\r\n newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,\r\n templateDirective = previousCompileContext.templateDirective,\r\n nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,\r\n hasTranscludeDirective = false,\r\n hasTemplate = false,\r\n hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,\r\n $compileNode = templateAttrs.$$element = jqLite(compileNode),\r\n directive,\r\n directiveName,\r\n $template,\r\n replaceDirective = originalReplaceDirective,\r\n childTranscludeFn = transcludeFn,\r\n linkFn,\r\n directiveValue;\r\n\r\n // executes all directives on the current element\r\n for (var i = 0, ii = directives.length; i < ii; i++) {\r\n directive = directives[i];\r\n var attrStart = directive.$$start;\r\n var attrEnd = directive.$$end;\r\n\r\n // collect multiblock sections\r\n if (attrStart) {\r\n $compileNode = groupScan(compileNode, attrStart, attrEnd);\r\n }\r\n $template = undefined;\r\n\r\n if (terminalPriority > directive.priority) {\r\n break; // prevent further processing of directives\r\n }\r\n\r\n if (directiveValue = directive.scope) {\r\n\r\n // skip the check for directives with async templates, we'll check the derived sync\r\n // directive when the template arrives\r\n if (!directive.templateUrl) {\r\n if (isObject(directiveValue)) {\r\n // This directive is trying to add an isolated scope.\r\n // Check that there is no scope of any kind already\r\n assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,\r\n directive, $compileNode);\r\n newIsolateScopeDirective = directive;\r\n } else {\r\n // This directive is trying to add a child scope.\r\n // Check that there is no isolated scope already\r\n assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,\r\n $compileNode);\r\n }\r\n }\r\n\r\n newScopeDirective = newScopeDirective || directive;\r\n }\r\n\r\n directiveName = directive.name;\r\n\r\n if (!directive.templateUrl && directive.controller) {\r\n directiveValue = directive.controller;\r\n controllerDirectives = controllerDirectives || {};\r\n assertNoDuplicate(\"'\" + directiveName + \"' controller\",\r\n controllerDirectives[directiveName], directive, $compileNode);\r\n controllerDirectives[directiveName] = directive;\r\n }\r\n\r\n if (directiveValue = directive.transclude) {\r\n hasTranscludeDirective = true;\r\n\r\n // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.\r\n // This option should only be used by directives that know how to safely handle element transclusion,\r\n // where the transcluded nodes are added or replaced after linking.\r\n if (!directive.$$tlb) {\r\n assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);\r\n nonTlbTranscludeDirective = directive;\r\n }\r\n\r\n if (directiveValue == 'element') {\r\n hasElementTranscludeDirective = true;\r\n terminalPriority = directive.priority;\r\n $template = $compileNode;\r\n $compileNode = templateAttrs.$$element =\r\n jqLite(document.createComment(' ' + directiveName + ': ' +\r\n templateAttrs[directiveName] + ' '));\r\n compileNode = $compileNode[0];\r\n replaceWith(jqCollection, sliceArgs($template), compileNode);\r\n\r\n childTranscludeFn = compile($template, transcludeFn, terminalPriority,\r\n replaceDirective && replaceDirective.name, {\r\n // Don't pass in:\r\n // - controllerDirectives - otherwise we'll create duplicates controllers\r\n // - newIsolateScopeDirective or templateDirective - combining templates with\r\n // element transclusion doesn't make sense.\r\n //\r\n // We need only nonTlbTranscludeDirective so that we prevent putting transclusion\r\n // on the same element more than once.\r\n nonTlbTranscludeDirective: nonTlbTranscludeDirective\r\n });\r\n } else {\r\n $template = jqLite(jqLiteClone(compileNode)).contents();\r\n $compileNode.empty(); // clear contents\r\n childTranscludeFn = compile($template, transcludeFn);\r\n }\r\n }\r\n\r\n if (directive.template) {\r\n hasTemplate = true;\r\n assertNoDuplicate('template', templateDirective, directive, $compileNode);\r\n templateDirective = directive;\r\n\r\n directiveValue = (isFunction(directive.template))\r\n ? directive.template($compileNode, templateAttrs)\r\n : directive.template;\r\n\r\n directiveValue = denormalizeTemplate(directiveValue);\r\n\r\n if (directive.replace) {\r\n replaceDirective = directive;\r\n if (jqLiteIsTextNode(directiveValue)) {\r\n $template = [];\r\n } else {\r\n $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));\r\n }\r\n compileNode = $template[0];\r\n\r\n if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {\r\n throw $compileMinErr('tplrt',\r\n \"Template for directive '{0}' must have exactly one root element. {1}\",\r\n directiveName, '');\r\n }\r\n\r\n replaceWith(jqCollection, $compileNode, compileNode);\r\n\r\n var newTemplateAttrs = {$attr: {}};\r\n\r\n // combine directives from the original node and from the template:\r\n // - take the array of directives for this element\r\n // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)\r\n // - collect directives from the template and sort them by priority\r\n // - combine directives as: processed + template + unprocessed\r\n var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);\r\n var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));\r\n\r\n if (newIsolateScopeDirective) {\r\n markDirectivesAsIsolate(templateDirectives);\r\n }\r\n directives = directives.concat(templateDirectives).concat(unprocessedDirectives);\r\n mergeTemplateAttributes(templateAttrs, newTemplateAttrs);\r\n\r\n ii = directives.length;\r\n } else {\r\n $compileNode.html(directiveValue);\r\n }\r\n }\r\n\r\n if (directive.templateUrl) {\r\n hasTemplate = true;\r\n assertNoDuplicate('template', templateDirective, directive, $compileNode);\r\n templateDirective = directive;\r\n\r\n if (directive.replace) {\r\n replaceDirective = directive;\r\n }\r\n\r\n nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,\r\n templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {\r\n controllerDirectives: controllerDirectives,\r\n newIsolateScopeDirective: newIsolateScopeDirective,\r\n templateDirective: templateDirective,\r\n nonTlbTranscludeDirective: nonTlbTranscludeDirective\r\n });\r\n ii = directives.length;\r\n } else if (directive.compile) {\r\n try {\r\n linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);\r\n if (isFunction(linkFn)) {\r\n addLinkFns(null, linkFn, attrStart, attrEnd);\r\n } else if (linkFn) {\r\n addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);\r\n }\r\n } catch (e) {\r\n $exceptionHandler(e, startingTag($compileNode));\r\n }\r\n }\r\n\r\n if (directive.terminal) {\r\n nodeLinkFn.terminal = true;\r\n terminalPriority = Math.max(terminalPriority, directive.priority);\r\n }\r\n\r\n }\r\n\r\n nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;\r\n nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;\r\n nodeLinkFn.elementTranscludeOnThisElement = hasElementTranscludeDirective;\r\n nodeLinkFn.templateOnThisElement = hasTemplate;\r\n nodeLinkFn.transclude = childTranscludeFn;\r\n\r\n previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;\r\n\r\n // might be normal or delayed nodeLinkFn depending on if templateUrl is present\r\n return nodeLinkFn;\r\n\r\n ////////////////////\r\n\r\n function addLinkFns(pre, post, attrStart, attrEnd) {\r\n if (pre) {\r\n if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);\r\n pre.require = directive.require;\r\n pre.directiveName = directiveName;\r\n if (newIsolateScopeDirective === directive || directive.$$isolateScope) {\r\n pre = cloneAndAnnotateFn(pre, {isolateScope: true});\r\n }\r\n preLinkFns.push(pre);\r\n }\r\n if (post) {\r\n if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);\r\n post.require = directive.require;\r\n post.directiveName = directiveName;\r\n if (newIsolateScopeDirective === directive || directive.$$isolateScope) {\r\n post = cloneAndAnnotateFn(post, {isolateScope: true});\r\n }\r\n postLinkFns.push(post);\r\n }\r\n }\r\n\r\n\r\n function getControllers(directiveName, require, $element, elementControllers) {\r\n var value, retrievalMethod = 'data', optional = false;\r\n var $searchElement = $element;\r\n var match;\r\n if (isString(require)) {\r\n match = require.match(REQUIRE_PREFIX_REGEXP);\r\n require = require.substring(match[0].length);\r\n\r\n if (match[3]) {\r\n if (match[1]) match[3] = null;\r\n else match[1] = match[3];\r\n }\r\n if (match[1] === '^') {\r\n retrievalMethod = 'inheritedData';\r\n } else if (match[1] === '^^') {\r\n retrievalMethod = 'inheritedData';\r\n $searchElement = $element.parent();\r\n }\r\n if (match[2] === '?') {\r\n optional = true;\r\n }\r\n\r\n value = null;\r\n\r\n if (elementControllers && retrievalMethod === 'data') {\r\n if (value = elementControllers[require]) {\r\n value = value.instance;\r\n }\r\n }\r\n value = value || $searchElement[retrievalMethod]('$' + require + 'Controller');\r\n\r\n if (!value && !optional) {\r\n throw $compileMinErr('ctreq',\r\n \"Controller '{0}', required by directive '{1}', can't be found!\",\r\n require, directiveName);\r\n }\r\n return value || null;\r\n } else if (isArray(require)) {\r\n value = [];\r\n forEach(require, function(require) {\r\n value.push(getControllers(directiveName, require, $element, elementControllers));\r\n });\r\n }\r\n return value;\r\n }\r\n\r\n\r\n function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {\r\n var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element,\r\n attrs;\r\n\r\n if (compileNode === linkNode) {\r\n attrs = templateAttrs;\r\n $element = templateAttrs.$$element;\r\n } else {\r\n $element = jqLite(linkNode);\r\n attrs = new Attributes($element, templateAttrs);\r\n }\r\n\r\n if (newIsolateScopeDirective) {\r\n isolateScope = scope.$new(true);\r\n }\r\n\r\n if (boundTranscludeFn) {\r\n // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`\r\n // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`\r\n transcludeFn = controllersBoundTransclude;\r\n transcludeFn.$$boundTransclude = boundTranscludeFn;\r\n }\r\n\r\n if (controllerDirectives) {\r\n // TODO: merge `controllers` and `elementControllers` into single object.\r\n controllers = {};\r\n elementControllers = {};\r\n forEach(controllerDirectives, function(directive) {\r\n var locals = {\r\n $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,\r\n $element: $element,\r\n $attrs: attrs,\r\n $transclude: transcludeFn\r\n }, controllerInstance;\r\n\r\n controller = directive.controller;\r\n if (controller == '@') {\r\n controller = attrs[directive.name];\r\n }\r\n\r\n controllerInstance = $controller(controller, locals, true, directive.controllerAs);\r\n\r\n // For directives with element transclusion the element is a comment,\r\n // but jQuery .data doesn't support attaching data to comment nodes as it's hard to\r\n // clean up (http://bugs.jquery.com/ticket/8335).\r\n // Instead, we save the controllers for the element in a local hash and attach to .data\r\n // later, once we have the actual element.\r\n elementControllers[directive.name] = controllerInstance;\r\n if (!hasElementTranscludeDirective) {\r\n $element.data('$' + directive.name + 'Controller', controllerInstance.instance);\r\n }\r\n\r\n controllers[directive.name] = controllerInstance;\r\n });\r\n }\r\n\r\n if (newIsolateScopeDirective) {\r\n compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||\r\n templateDirective === newIsolateScopeDirective.$$originalDirective)));\r\n compile.$$addScopeClass($element, true);\r\n\r\n var isolateScopeController = controllers && controllers[newIsolateScopeDirective.name];\r\n var isolateBindingContext = isolateScope;\r\n if (isolateScopeController && isolateScopeController.identifier &&\r\n newIsolateScopeDirective.bindToController === true) {\r\n isolateBindingContext = isolateScopeController.instance;\r\n }\r\n\r\n forEach(isolateScope.$$isolateBindings = newIsolateScopeDirective.$$isolateBindings, function(definition, scopeName) {\r\n var attrName = definition.attrName,\r\n optional = definition.optional,\r\n mode = definition.mode, // @, =, or &\r\n lastValue,\r\n parentGet, parentSet, compare;\r\n\r\n switch (mode) {\r\n\r\n case '@':\r\n attrs.$observe(attrName, function(value) {\r\n isolateBindingContext[scopeName] = value;\r\n });\r\n attrs.$$observers[attrName].$$scope = scope;\r\n if (attrs[attrName]) {\r\n // If the attribute has been provided then we trigger an interpolation to ensure\r\n // the value is there for use in the link fn\r\n isolateBindingContext[scopeName] = $interpolate(attrs[attrName])(scope);\r\n }\r\n break;\r\n\r\n case '=':\r\n if (optional && !attrs[attrName]) {\r\n return;\r\n }\r\n parentGet = $parse(attrs[attrName]);\r\n if (parentGet.literal) {\r\n compare = equals;\r\n } else {\r\n compare = function(a, b) { return a === b || (a !== a && b !== b); };\r\n }\r\n parentSet = parentGet.assign || function() {\r\n // reset the change, or we will throw this exception on every $digest\r\n lastValue = isolateBindingContext[scopeName] = parentGet(scope);\r\n throw $compileMinErr('nonassign',\r\n \"Expression '{0}' used with directive '{1}' is non-assignable!\",\r\n attrs[attrName], newIsolateScopeDirective.name);\r\n };\r\n lastValue = isolateBindingContext[scopeName] = parentGet(scope);\r\n var parentValueWatch = function parentValueWatch(parentValue) {\r\n if (!compare(parentValue, isolateBindingContext[scopeName])) {\r\n // we are out of sync and need to copy\r\n if (!compare(parentValue, lastValue)) {\r\n // parent changed and it has precedence\r\n isolateBindingContext[scopeName] = parentValue;\r\n } else {\r\n // if the parent can be assigned then do so\r\n parentSet(scope, parentValue = isolateBindingContext[scopeName]);\r\n }\r\n }\r\n return lastValue = parentValue;\r\n };\r\n parentValueWatch.$stateful = true;\r\n var unwatch;\r\n if (definition.collection) {\r\n unwatch = scope.$watchCollection(attrs[attrName], parentValueWatch);\r\n } else {\r\n unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);\r\n }\r\n isolateScope.$on('$destroy', unwatch);\r\n break;\r\n\r\n case '&':\r\n parentGet = $parse(attrs[attrName]);\r\n isolateBindingContext[scopeName] = function(locals) {\r\n return parentGet(scope, locals);\r\n };\r\n break;\r\n }\r\n });\r\n }\r\n if (controllers) {\r\n forEach(controllers, function(controller) {\r\n controller();\r\n });\r\n controllers = null;\r\n }\r\n\r\n // PRELINKING\r\n for (i = 0, ii = preLinkFns.length; i < ii; i++) {\r\n linkFn = preLinkFns[i];\r\n invokeLinkFn(linkFn,\r\n linkFn.isolateScope ? isolateScope : scope,\r\n $element,\r\n attrs,\r\n linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),\r\n transcludeFn\r\n );\r\n }\r\n\r\n // RECURSION\r\n // We only pass the isolate scope, if the isolate directive has a template,\r\n // otherwise the child elements do not belong to the isolate directive.\r\n var scopeToChild = scope;\r\n if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {\r\n scopeToChild = isolateScope;\r\n }\r\n childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);\r\n\r\n // POSTLINKING\r\n for (i = postLinkFns.length - 1; i >= 0; i--) {\r\n linkFn = postLinkFns[i];\r\n invokeLinkFn(linkFn,\r\n linkFn.isolateScope ? isolateScope : scope,\r\n $element,\r\n attrs,\r\n linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),\r\n transcludeFn\r\n );\r\n }\r\n\r\n // This is the function that is injected as `$transclude`.\r\n // Note: all arguments are optional!\r\n function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) {\r\n var transcludeControllers;\r\n\r\n // No scope passed in:\r\n if (!isScope(scope)) {\r\n futureParentElement = cloneAttachFn;\r\n cloneAttachFn = scope;\r\n scope = undefined;\r\n }\r\n\r\n if (hasElementTranscludeDirective) {\r\n transcludeControllers = elementControllers;\r\n }\r\n if (!futureParentElement) {\r\n futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;\r\n }\r\n return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);\r\n }\r\n }\r\n }\r\n\r\n function markDirectivesAsIsolate(directives) {\r\n // mark all directives as needing isolate scope.\r\n for (var j = 0, jj = directives.length; j < jj; j++) {\r\n directives[j] = inherit(directives[j], {$$isolateScope: true});\r\n }\r\n }\r\n\r\n /**\r\n * looks up the directive and decorates it with exception handling and proper parameters. We\r\n * call this the boundDirective.\r\n *\r\n * @param {string} name name of the directive to look up.\r\n * @param {string} location The directive must be found in specific format.\r\n * String containing any of theses characters:\r\n *\r\n * * `E`: element name\r\n * * `A': attribute\r\n * * `C`: class\r\n * * `M`: comment\r\n * @returns {boolean} true if directive was added.\r\n */\r\n function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,\r\n endAttrName) {\r\n if (name === ignoreDirective) return null;\r\n var match = null;\r\n if (hasDirectives.hasOwnProperty(name)) {\r\n for (var directive, directives = $injector.get(name + Suffix),\r\n i = 0, ii = directives.length; i < ii; i++) {\r\n try {\r\n directive = directives[i];\r\n if ((maxPriority === undefined || maxPriority > directive.priority) &&\r\n directive.restrict.indexOf(location) != -1) {\r\n if (startAttrName) {\r\n directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});\r\n }\r\n tDirectives.push(directive);\r\n match = directive;\r\n }\r\n } catch (e) { $exceptionHandler(e); }\r\n }\r\n }\r\n return match;\r\n }\r\n\r\n\r\n /**\r\n * looks up the directive and returns true if it is a multi-element directive,\r\n * and therefore requires DOM nodes between -start and -end markers to be grouped\r\n * together.\r\n *\r\n * @param {string} name name of the directive to look up.\r\n * @returns true if directive was registered as multi-element.\r\n */\r\n function directiveIsMultiElement(name) {\r\n if (hasDirectives.hasOwnProperty(name)) {\r\n for (var directive, directives = $injector.get(name + Suffix),\r\n i = 0, ii = directives.length; i < ii; i++) {\r\n directive = directives[i];\r\n if (directive.multiElement) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * When the element is replaced with HTML template then the new attributes\r\n * on the template need to be merged with the existing attributes in the DOM.\r\n * The desired effect is to have both of the attributes present.\r\n *\r\n * @param {object} dst destination attributes (original DOM)\r\n * @param {object} src source attributes (from the directive template)\r\n */\r\n function mergeTemplateAttributes(dst, src) {\r\n var srcAttr = src.$attr,\r\n dstAttr = dst.$attr,\r\n $element = dst.$$element;\r\n\r\n // reapply the old attributes to the new element\r\n forEach(dst, function(value, key) {\r\n if (key.charAt(0) != '$') {\r\n if (src[key] && src[key] !== value) {\r\n value += (key === 'style' ? ';' : ' ') + src[key];\r\n }\r\n dst.$set(key, value, true, srcAttr[key]);\r\n }\r\n });\r\n\r\n // copy the new attributes on the old attrs object\r\n forEach(src, function(value, key) {\r\n if (key == 'class') {\r\n safeAddClass($element, value);\r\n dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;\r\n } else if (key == 'style') {\r\n $element.attr('style', $element.attr('style') + ';' + value);\r\n dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;\r\n // `dst` will never contain hasOwnProperty as DOM parser won't let it.\r\n // You will get an \"InvalidCharacterError: DOM Exception 5\" error if you\r\n // have an attribute like \"has-own-property\" or \"data-has-own-property\", etc.\r\n } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {\r\n dst[key] = value;\r\n dstAttr[key] = srcAttr[key];\r\n }\r\n });\r\n }\r\n\r\n\r\n function compileTemplateUrl(directives, $compileNode, tAttrs,\r\n $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {\r\n var linkQueue = [],\r\n afterTemplateNodeLinkFn,\r\n afterTemplateChildLinkFn,\r\n beforeTemplateCompileNode = $compileNode[0],\r\n origAsyncDirective = directives.shift(),\r\n derivedSyncDirective = inherit(origAsyncDirective, {\r\n templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective\r\n }),\r\n templateUrl = (isFunction(origAsyncDirective.templateUrl))\r\n ? origAsyncDirective.templateUrl($compileNode, tAttrs)\r\n : origAsyncDirective.templateUrl,\r\n templateNamespace = origAsyncDirective.templateNamespace;\r\n\r\n $compileNode.empty();\r\n\r\n $templateRequest(templateUrl)\r\n .then(function(content) {\r\n var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;\r\n\r\n content = denormalizeTemplate(content);\r\n\r\n if (origAsyncDirective.replace) {\r\n if (jqLiteIsTextNode(content)) {\r\n $template = [];\r\n } else {\r\n $template = removeComments(wrapTemplate(templateNamespace, trim(content)));\r\n }\r\n compileNode = $template[0];\r\n\r\n if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {\r\n throw $compileMinErr('tplrt',\r\n \"Template for directive '{0}' must have exactly one root element. {1}\",\r\n origAsyncDirective.name, templateUrl);\r\n }\r\n\r\n tempTemplateAttrs = {$attr: {}};\r\n replaceWith($rootElement, $compileNode, compileNode);\r\n var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);\r\n\r\n if (isObject(origAsyncDirective.scope)) {\r\n markDirectivesAsIsolate(templateDirectives);\r\n }\r\n directives = templateDirectives.concat(directives);\r\n mergeTemplateAttributes(tAttrs, tempTemplateAttrs);\r\n } else {\r\n compileNode = beforeTemplateCompileNode;\r\n $compileNode.html(content);\r\n }\r\n\r\n directives.unshift(derivedSyncDirective);\r\n\r\n afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,\r\n childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,\r\n previousCompileContext);\r\n forEach($rootElement, function(node, i) {\r\n if (node == compileNode) {\r\n $rootElement[i] = $compileNode[0];\r\n }\r\n });\r\n afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);\r\n\r\n while (linkQueue.length) {\r\n var scope = linkQueue.shift(),\r\n beforeTemplateLinkNode = linkQueue.shift(),\r\n linkRootElement = linkQueue.shift(),\r\n boundTranscludeFn = linkQueue.shift(),\r\n linkNode = $compileNode[0];\r\n\r\n if (scope.$$destroyed) continue;\r\n\r\n if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {\r\n var oldClasses = beforeTemplateLinkNode.className;\r\n\r\n if (!(previousCompileContext.hasElementTranscludeDirective &&\r\n origAsyncDirective.replace)) {\r\n // it was cloned therefore we have to clone as well.\r\n linkNode = jqLiteClone(compileNode);\r\n }\r\n replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);\r\n\r\n // Copy in CSS classes from original node\r\n safeAddClass(jqLite(linkNode), oldClasses);\r\n }\r\n if (afterTemplateNodeLinkFn.transcludeOnThisElement) {\r\n childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);\r\n } else {\r\n childBoundTranscludeFn = boundTranscludeFn;\r\n }\r\n afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,\r\n childBoundTranscludeFn);\r\n }\r\n linkQueue = null;\r\n });\r\n\r\n return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {\r\n var childBoundTranscludeFn = boundTranscludeFn;\r\n if (scope.$$destroyed) return;\r\n if (linkQueue) {\r\n linkQueue.push(scope,\r\n node,\r\n rootElement,\r\n childBoundTranscludeFn);\r\n } else {\r\n if (afterTemplateNodeLinkFn.transcludeOnThisElement) {\r\n childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);\r\n }\r\n afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);\r\n }\r\n };\r\n }\r\n\r\n\r\n /**\r\n * Sorting function for bound directives.\r\n */\r\n function byPriority(a, b) {\r\n var diff = b.priority - a.priority;\r\n if (diff !== 0) return diff;\r\n if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;\r\n return a.index - b.index;\r\n }\r\n\r\n\r\n function assertNoDuplicate(what, previousDirective, directive, element) {\r\n if (previousDirective) {\r\n throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',\r\n previousDirective.name, directive.name, what, startingTag(element));\r\n }\r\n }\r\n\r\n\r\n function addTextInterpolateDirective(directives, text) {\r\n var interpolateFn = $interpolate(text, true);\r\n if (interpolateFn) {\r\n directives.push({\r\n priority: 0,\r\n compile: function textInterpolateCompileFn(templateNode) {\r\n var templateNodeParent = templateNode.parent(),\r\n hasCompileParent = !!templateNodeParent.length;\r\n\r\n // When transcluding a template that has bindings in the root\r\n // we don't have a parent and thus need to add the class during linking fn.\r\n if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);\r\n\r\n return function textInterpolateLinkFn(scope, node) {\r\n var parent = node.parent();\r\n if (!hasCompileParent) compile.$$addBindingClass(parent);\r\n compile.$$addBindingInfo(parent, interpolateFn.expressions);\r\n scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {\r\n node[0].nodeValue = value;\r\n });\r\n };\r\n }\r\n });\r\n }\r\n }\r\n\r\n\r\n function wrapTemplate(type, template) {\r\n type = lowercase(type || 'html');\r\n switch (type) {\r\n case 'svg':\r\n case 'math':\r\n var wrapper = document.createElement('div');\r\n wrapper.innerHTML = '<' + type + '>' + template + '';\r\n return wrapper.childNodes[0].childNodes;\r\n default:\r\n return template;\r\n }\r\n }\r\n\r\n\r\n function getTrustedContext(node, attrNormalizedName) {\r\n if (attrNormalizedName == \"srcdoc\") {\r\n return $sce.HTML;\r\n }\r\n var tag = nodeName_(node);\r\n // maction[xlink:href] can source SVG. It's not limited to .\r\n if (attrNormalizedName == \"xlinkHref\" ||\r\n (tag == \"form\" && attrNormalizedName == \"action\") ||\r\n (tag != \"img\" && (attrNormalizedName == \"src\" ||\r\n attrNormalizedName == \"ngSrc\"))) {\r\n return $sce.RESOURCE_URL;\r\n }\r\n }\r\n\r\n\r\n function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {\r\n var trustedContext = getTrustedContext(node, name);\r\n allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;\r\n\r\n var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);\r\n\r\n // no interpolation found -> ignore\r\n if (!interpolateFn) return;\r\n\r\n\r\n if (name === \"multiple\" && nodeName_(node) === \"select\") {\r\n throw $compileMinErr(\"selmulti\",\r\n \"Binding to the 'multiple' attribute is not supported. Element: {0}\",\r\n startingTag(node));\r\n }\r\n\r\n directives.push({\r\n priority: 100,\r\n compile: function() {\r\n return {\r\n pre: function attrInterpolatePreLinkFn(scope, element, attr) {\r\n var $$observers = (attr.$$observers || (attr.$$observers = {}));\r\n\r\n if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {\r\n throw $compileMinErr('nodomevents',\r\n \"Interpolations for HTML DOM event attributes are disallowed. Please use the \" +\r\n \"ng- versions (such as ng-click instead of onclick) instead.\");\r\n }\r\n\r\n // If the attribute has changed since last $interpolate()ed\r\n var newValue = attr[name];\r\n if (newValue !== value) {\r\n // we need to interpolate again since the attribute value has been updated\r\n // (e.g. by another directive's compile function)\r\n // ensure unset/empty values make interpolateFn falsy\r\n interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);\r\n value = newValue;\r\n }\r\n\r\n // if attribute was updated so that there is no interpolation going on we don't want to\r\n // register any observers\r\n if (!interpolateFn) return;\r\n\r\n // initialize attr object so that it's ready in case we need the value for isolate\r\n // scope initialization, otherwise the value would not be available from isolate\r\n // directive's linking fn during linking phase\r\n attr[name] = interpolateFn(scope);\r\n\r\n ($$observers[name] || ($$observers[name] = [])).$$inter = true;\r\n (attr.$$observers && attr.$$observers[name].$$scope || scope).\r\n $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {\r\n //special case for class attribute addition + removal\r\n //so that class changes can tap into the animation\r\n //hooks provided by the $animate service. Be sure to\r\n //skip animations when the first digest occurs (when\r\n //both the new and the old values are the same) since\r\n //the CSS classes are the non-interpolated values\r\n if (name === 'class' && newValue != oldValue) {\r\n attr.$updateClass(newValue, oldValue);\r\n } else {\r\n attr.$set(name, newValue);\r\n }\r\n });\r\n }\r\n };\r\n }\r\n });\r\n }\r\n\r\n\r\n /**\r\n * This is a special jqLite.replaceWith, which can replace items which\r\n * have no parents, provided that the containing jqLite collection is provided.\r\n *\r\n * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes\r\n * in the root of the tree.\r\n * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep\r\n * the shell, but replace its DOM node reference.\r\n * @param {Node} newNode The new DOM node.\r\n */\r\n function replaceWith($rootElement, elementsToRemove, newNode) {\r\n var firstElementToRemove = elementsToRemove[0],\r\n removeCount = elementsToRemove.length,\r\n parent = firstElementToRemove.parentNode,\r\n i, ii;\r\n\r\n if ($rootElement) {\r\n for (i = 0, ii = $rootElement.length; i < ii; i++) {\r\n if ($rootElement[i] == firstElementToRemove) {\r\n $rootElement[i++] = newNode;\r\n for (var j = i, j2 = j + removeCount - 1,\r\n jj = $rootElement.length;\r\n j < jj; j++, j2++) {\r\n if (j2 < jj) {\r\n $rootElement[j] = $rootElement[j2];\r\n } else {\r\n delete $rootElement[j];\r\n }\r\n }\r\n $rootElement.length -= removeCount - 1;\r\n\r\n // If the replaced element is also the jQuery .context then replace it\r\n // .context is a deprecated jQuery api, so we should set it only when jQuery set it\r\n // http://api.jquery.com/context/\r\n if ($rootElement.context === firstElementToRemove) {\r\n $rootElement.context = newNode;\r\n }\r\n break;\r\n }\r\n }\r\n }\r\n\r\n if (parent) {\r\n parent.replaceChild(newNode, firstElementToRemove);\r\n }\r\n\r\n // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it?\r\n var fragment = document.createDocumentFragment();\r\n fragment.appendChild(firstElementToRemove);\r\n\r\n // Copy over user data (that includes Angular's $scope etc.). Don't copy private\r\n // data here because there's no public interface in jQuery to do that and copying over\r\n // event listeners (which is the main use of private data) wouldn't work anyway.\r\n jqLite(newNode).data(jqLite(firstElementToRemove).data());\r\n\r\n // Remove data of the replaced element. We cannot just call .remove()\r\n // on the element it since that would deallocate scope that is needed\r\n // for the new node. Instead, remove the data \"manually\".\r\n if (!jQuery) {\r\n delete jqLite.cache[firstElementToRemove[jqLite.expando]];\r\n } else {\r\n // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after\r\n // the replaced element. The cleanData version monkey-patched by Angular would cause\r\n // the scope to be trashed and we do need the very same scope to work with the new\r\n // element. However, we cannot just cache the non-patched version and use it here as\r\n // that would break if another library patches the method after Angular does (one\r\n // example is jQuery UI). Instead, set a flag indicating scope destroying should be\r\n // skipped this one time.\r\n skipDestroyOnNextJQueryCleanData = true;\r\n jQuery.cleanData([firstElementToRemove]);\r\n }\r\n\r\n for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {\r\n var element = elementsToRemove[k];\r\n jqLite(element).remove(); // must do this way to clean up expando\r\n fragment.appendChild(element);\r\n delete elementsToRemove[k];\r\n }\r\n\r\n elementsToRemove[0] = newNode;\r\n elementsToRemove.length = 1;\r\n }\r\n\r\n\r\n function cloneAndAnnotateFn(fn, annotation) {\r\n return extend(function() { return fn.apply(null, arguments); }, fn, annotation);\r\n }\r\n\r\n\r\n function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {\r\n try {\r\n linkFn(scope, $element, attrs, controllers, transcludeFn);\r\n } catch (e) {\r\n $exceptionHandler(e, startingTag($element));\r\n }\r\n }\r\n }];\r\n}\r\n\r\nvar PREFIX_REGEXP = /^((?:x|data)[\\:\\-_])/i;\r\n/**\r\n * Converts all accepted directives format into proper directive name.\r\n * @param name Name to normalize\r\n */\r\nfunction directiveNormalize(name) {\r\n return camelCase(name.replace(PREFIX_REGEXP, ''));\r\n}\r\n\r\n/**\r\n * @ngdoc type\r\n * @name $compile.directive.Attributes\r\n *\r\n * @description\r\n * A shared object between directive compile / linking functions which contains normalized DOM\r\n * element attributes. The values reflect current binding state `{{ }}`. The normalization is\r\n * needed since all of these are treated as equivalent in Angular:\r\n *\r\n * ```\r\n * \r\n * ```\r\n */\r\n\r\n/**\r\n * @ngdoc property\r\n * @name $compile.directive.Attributes#$attr\r\n *\r\n * @description\r\n * A map of DOM element attribute names to the normalized name. This is\r\n * needed to do reverse lookup from normalized name back to actual name.\r\n */\r\n\r\n\r\n/**\r\n * @ngdoc method\r\n * @name $compile.directive.Attributes#$set\r\n * @kind function\r\n *\r\n * @description\r\n * Set DOM element attribute value.\r\n *\r\n *\r\n * @param {string} name Normalized element attribute name of the property to modify. The name is\r\n * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}\r\n * property to the original name.\r\n * @param {string} value Value to set the attribute to. The value can be an interpolated string.\r\n */\r\n\r\n\r\n\r\n/**\r\n * Closure compiler type information\r\n */\r\n\r\nfunction nodesetLinkingFn(\r\n /* angular.Scope */ scope,\r\n /* NodeList */ nodeList,\r\n /* Element */ rootElement,\r\n /* function(Function) */ boundTranscludeFn\r\n) {}\r\n\r\nfunction directiveLinkingFn(\r\n /* nodesetLinkingFn */ nodesetLinkingFn,\r\n /* angular.Scope */ scope,\r\n /* Node */ node,\r\n /* Element */ rootElement,\r\n /* function(Function) */ boundTranscludeFn\r\n) {}\r\n\r\nfunction tokenDifference(str1, str2) {\r\n var values = '',\r\n tokens1 = str1.split(/\\s+/),\r\n tokens2 = str2.split(/\\s+/);\r\n\r\n outer:\r\n for (var i = 0; i < tokens1.length; i++) {\r\n var token = tokens1[i];\r\n for (var j = 0; j < tokens2.length; j++) {\r\n if (token == tokens2[j]) continue outer;\r\n }\r\n values += (values.length > 0 ? ' ' : '') + token;\r\n }\r\n return values;\r\n}\r\n\r\nfunction removeComments(jqNodes) {\r\n jqNodes = jqLite(jqNodes);\r\n var i = jqNodes.length;\r\n\r\n if (i <= 1) {\r\n return jqNodes;\r\n }\r\n\r\n while (i--) {\r\n var node = jqNodes[i];\r\n if (node.nodeType === NODE_TYPE_COMMENT) {\r\n splice.call(jqNodes, i, 1);\r\n }\r\n }\r\n return jqNodes;\r\n}\r\n\r\nvar $controllerMinErr = minErr('$controller');\r\n\r\n/**\r\n * @ngdoc provider\r\n * @name $controllerProvider\r\n * @description\r\n * The {@link ng.$controller $controller service} is used by Angular to create new\r\n * controllers.\r\n *\r\n * This provider allows controller registration via the\r\n * {@link ng.$controllerProvider#register register} method.\r\n */\r\nfunction $ControllerProvider() {\r\n var controllers = {},\r\n globals = false,\r\n CNTRL_REG = /^(\\S+)(\\s+as\\s+(\\w+))?$/;\r\n\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $controllerProvider#register\r\n * @param {string|Object} name Controller name, or an object map of controllers where the keys are\r\n * the names and the values are the constructors.\r\n * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI\r\n * annotations in the array notation).\r\n */\r\n this.register = function(name, constructor) {\r\n assertNotHasOwnProperty(name, 'controller');\r\n if (isObject(name)) {\r\n extend(controllers, name);\r\n } else {\r\n controllers[name] = constructor;\r\n }\r\n };\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $controllerProvider#allowGlobals\r\n * @description If called, allows `$controller` to find controller constructors on `window`\r\n */\r\n this.allowGlobals = function() {\r\n globals = true;\r\n };\r\n\r\n\r\n this.$get = ['$injector', '$window', function($injector, $window) {\r\n\r\n /**\r\n * @ngdoc service\r\n * @name $controller\r\n * @requires $injector\r\n *\r\n * @param {Function|string} constructor If called with a function then it's considered to be the\r\n * controller constructor function. Otherwise it's considered to be a string which is used\r\n * to retrieve the controller constructor using the following steps:\r\n *\r\n * * check if a controller with given name is registered via `$controllerProvider`\r\n * * check if evaluating the string on the current scope returns a constructor\r\n * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global\r\n * `window` object (not recommended)\r\n *\r\n * The string can use the `controller as property` syntax, where the controller instance is published\r\n * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this\r\n * to work correctly.\r\n *\r\n * @param {Object} locals Injection locals for Controller.\r\n * @return {Object} Instance of given controller.\r\n *\r\n * @description\r\n * `$controller` service is responsible for instantiating controllers.\r\n *\r\n * It's just a simple call to {@link auto.$injector $injector}, but extracted into\r\n * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).\r\n */\r\n return function(expression, locals, later, ident) {\r\n // PRIVATE API:\r\n // param `later` --- indicates that the controller's constructor is invoked at a later time.\r\n // If true, $controller will allocate the object with the correct\r\n // prototype chain, but will not invoke the controller until a returned\r\n // callback is invoked.\r\n // param `ident` --- An optional label which overrides the label parsed from the controller\r\n // expression, if any.\r\n var instance, match, constructor, identifier;\r\n later = later === true;\r\n if (ident && isString(ident)) {\r\n identifier = ident;\r\n }\r\n\r\n if (isString(expression)) {\r\n match = expression.match(CNTRL_REG);\r\n if (!match) {\r\n throw $controllerMinErr('ctrlfmt',\r\n \"Badly formed controller string '{0}'. \" +\r\n \"Must match `__name__ as __id__` or `__name__`.\", expression);\r\n }\r\n constructor = match[1],\r\n identifier = identifier || match[3];\r\n expression = controllers.hasOwnProperty(constructor)\r\n ? controllers[constructor]\r\n : getter(locals.$scope, constructor, true) ||\r\n (globals ? getter($window, constructor, true) : undefined);\r\n\r\n assertArgFn(expression, constructor, true);\r\n }\r\n\r\n if (later) {\r\n // Instantiate controller later:\r\n // This machinery is used to create an instance of the object before calling the\r\n // controller's constructor itself.\r\n //\r\n // This allows properties to be added to the controller before the constructor is\r\n // invoked. Primarily, this is used for isolate scope bindings in $compile.\r\n //\r\n // This feature is not intended for use by applications, and is thus not documented\r\n // publicly.\r\n // Object creation: http://jsperf.com/create-constructor/2\r\n var controllerPrototype = (isArray(expression) ?\r\n expression[expression.length - 1] : expression).prototype;\r\n instance = Object.create(controllerPrototype || null);\r\n\r\n if (identifier) {\r\n addIdentifier(locals, identifier, instance, constructor || expression.name);\r\n }\r\n\r\n return extend(function() {\r\n $injector.invoke(expression, instance, locals, constructor);\r\n return instance;\r\n }, {\r\n instance: instance,\r\n identifier: identifier\r\n });\r\n }\r\n\r\n instance = $injector.instantiate(expression, locals, constructor);\r\n\r\n if (identifier) {\r\n addIdentifier(locals, identifier, instance, constructor || expression.name);\r\n }\r\n\r\n return instance;\r\n };\r\n\r\n function addIdentifier(locals, identifier, instance, name) {\r\n if (!(locals && isObject(locals.$scope))) {\r\n throw minErr('$controller')('noscp',\r\n \"Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.\",\r\n name, identifier);\r\n }\r\n\r\n locals.$scope[identifier] = instance;\r\n }\r\n }];\r\n}\r\n\r\n/**\r\n * @ngdoc service\r\n * @name $document\r\n * @requires $window\r\n *\r\n * @description\r\n * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.\r\n *\r\n * @example\r\n \r\n \r\n
    \r\n

    $document title:

    \r\n

    window.document title:

    \r\n
    \r\n
    \r\n \r\n angular.module('documentExample', [])\r\n .controller('ExampleController', ['$scope', '$document', function($scope, $document) {\r\n $scope.title = $document[0].title;\r\n $scope.windowTitle = angular.element(window.document)[0].title;\r\n }]);\r\n \r\n
    \r\n */\r\nfunction $DocumentProvider() {\r\n this.$get = ['$window', function(window) {\r\n return jqLite(window.document);\r\n }];\r\n}\r\n\r\n/**\r\n * @ngdoc service\r\n * @name $exceptionHandler\r\n * @requires ng.$log\r\n *\r\n * @description\r\n * Any uncaught exception in angular expressions is delegated to this service.\r\n * The default implementation simply delegates to `$log.error` which logs it into\r\n * the browser console.\r\n *\r\n * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by\r\n * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.\r\n *\r\n * ## Example:\r\n *\r\n * ```js\r\n * angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {\r\n * return function(exception, cause) {\r\n * exception.message += ' (caused by \"' + cause + '\")';\r\n * throw exception;\r\n * };\r\n * });\r\n * ```\r\n *\r\n * This example will override the normal action of `$exceptionHandler`, to make angular\r\n * exceptions fail hard when they happen, instead of just logging to the console.\r\n *\r\n *
    \r\n * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`\r\n * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}\r\n * (unless executed during a digest).\r\n *\r\n * If you wish, you can manually delegate exceptions, e.g.\r\n * `try { ... } catch(e) { $exceptionHandler(e); }`\r\n *\r\n * @param {Error} exception Exception associated with the error.\r\n * @param {string=} cause optional information about the context in which\r\n * the error was thrown.\r\n *\r\n */\r\nfunction $ExceptionHandlerProvider() {\r\n this.$get = ['$log', function($log) {\r\n return function(exception, cause) {\r\n $log.error.apply($log, arguments);\r\n };\r\n }];\r\n}\r\n\r\nvar APPLICATION_JSON = 'application/json';\r\nvar CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};\r\nvar JSON_START = /^\\[|^\\{(?!\\{)/;\r\nvar JSON_ENDS = {\r\n '[': /]$/,\r\n '{': /}$/\r\n};\r\nvar JSON_PROTECTION_PREFIX = /^\\)\\]\\}',?\\n/;\r\n\r\nfunction defaultHttpResponseTransform(data, headers) {\r\n if (isString(data)) {\r\n // Strip json vulnerability protection prefix and trim whitespace\r\n var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();\r\n\r\n if (tempData) {\r\n var contentType = headers('Content-Type');\r\n if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {\r\n data = fromJson(tempData);\r\n }\r\n }\r\n }\r\n\r\n return data;\r\n}\r\n\r\nfunction isJsonLike(str) {\r\n var jsonStart = str.match(JSON_START);\r\n return jsonStart && JSON_ENDS[jsonStart[0]].test(str);\r\n}\r\n\r\n/**\r\n * Parse headers into key value object\r\n *\r\n * @param {string} headers Raw headers as a string\r\n * @returns {Object} Parsed headers as key value object\r\n */\r\nfunction parseHeaders(headers) {\r\n var parsed = createMap(), key, val, i;\r\n\r\n if (!headers) return parsed;\r\n\r\n forEach(headers.split('\\n'), function(line) {\r\n i = line.indexOf(':');\r\n key = lowercase(trim(line.substr(0, i)));\r\n val = trim(line.substr(i + 1));\r\n\r\n if (key) {\r\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\r\n }\r\n });\r\n\r\n return parsed;\r\n}\r\n\r\n\r\n/**\r\n * Returns a function that provides access to parsed headers.\r\n *\r\n * Headers are lazy parsed when first requested.\r\n * @see parseHeaders\r\n *\r\n * @param {(string|Object)} headers Headers to provide access to.\r\n * @returns {function(string=)} Returns a getter function which if called with:\r\n *\r\n * - if called with single an argument returns a single header value or null\r\n * - if called with no arguments returns an object containing all headers.\r\n */\r\nfunction headersGetter(headers) {\r\n var headersObj = isObject(headers) ? headers : undefined;\r\n\r\n return function(name) {\r\n if (!headersObj) headersObj = parseHeaders(headers);\r\n\r\n if (name) {\r\n var value = headersObj[lowercase(name)];\r\n if (value === void 0) {\r\n value = null;\r\n }\r\n return value;\r\n }\r\n\r\n return headersObj;\r\n };\r\n}\r\n\r\n\r\n/**\r\n * Chain all given functions\r\n *\r\n * This function is used for both request and response transforming\r\n *\r\n * @param {*} data Data to transform.\r\n * @param {function(string=)} headers HTTP headers getter fn.\r\n * @param {number} status HTTP status code of the response.\r\n * @param {(Function|Array.)} fns Function or an array of functions.\r\n * @returns {*} Transformed data.\r\n */\r\nfunction transformData(data, headers, status, fns) {\r\n if (isFunction(fns))\r\n return fns(data, headers, status);\r\n\r\n forEach(fns, function(fn) {\r\n data = fn(data, headers, status);\r\n });\r\n\r\n return data;\r\n}\r\n\r\n\r\nfunction isSuccess(status) {\r\n return 200 <= status && status < 300;\r\n}\r\n\r\n\r\n/**\r\n * @ngdoc provider\r\n * @name $httpProvider\r\n * @description\r\n * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.\r\n * */\r\nfunction $HttpProvider() {\r\n /**\r\n * @ngdoc property\r\n * @name $httpProvider#defaults\r\n * @description\r\n *\r\n * Object containing default values for all {@link ng.$http $http} requests.\r\n *\r\n * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}\r\n * that will provide the cache for all requests who set their `cache` property to `true`.\r\n * If you set the `default.cache = false` then only requests that specify their own custom\r\n * cache object will be cached. See {@link $http#caching $http Caching} for more information.\r\n *\r\n * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.\r\n * Defaults value is `'XSRF-TOKEN'`.\r\n *\r\n * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the\r\n * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.\r\n *\r\n * - **`defaults.headers`** - {Object} - Default headers for all $http requests.\r\n * Refer to {@link ng.$http#setting-http-headers $http} for documentation on\r\n * setting default headers.\r\n * - **`defaults.headers.common`**\r\n * - **`defaults.headers.post`**\r\n * - **`defaults.headers.put`**\r\n * - **`defaults.headers.patch`**\r\n *\r\n **/\r\n var defaults = this.defaults = {\r\n // transform incoming response data\r\n transformResponse: [defaultHttpResponseTransform],\r\n\r\n // transform outgoing request data\r\n transformRequest: [function(d) {\r\n return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;\r\n }],\r\n\r\n // default headers\r\n headers: {\r\n common: {\r\n 'Accept': 'application/json, text/plain, */*'\r\n },\r\n post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),\r\n put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),\r\n patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)\r\n },\r\n\r\n xsrfCookieName: 'XSRF-TOKEN',\r\n xsrfHeaderName: 'X-XSRF-TOKEN'\r\n };\r\n\r\n var useApplyAsync = false;\r\n /**\r\n * @ngdoc method\r\n * @name $httpProvider#useApplyAsync\r\n * @description\r\n *\r\n * Configure $http service to combine processing of multiple http responses received at around\r\n * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in\r\n * significant performance improvement for bigger applications that make many HTTP requests\r\n * concurrently (common during application bootstrap).\r\n *\r\n * Defaults to false. If no value is specifed, returns the current configured value.\r\n *\r\n * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred\r\n * \"apply\" on the next tick, giving time for subsequent requests in a roughly ~10ms window\r\n * to load and share the same digest cycle.\r\n *\r\n * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.\r\n * otherwise, returns the current configured value.\r\n **/\r\n this.useApplyAsync = function(value) {\r\n if (isDefined(value)) {\r\n useApplyAsync = !!value;\r\n return this;\r\n }\r\n return useApplyAsync;\r\n };\r\n\r\n /**\r\n * @ngdoc property\r\n * @name $httpProvider#interceptors\r\n * @description\r\n *\r\n * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}\r\n * pre-processing of request or postprocessing of responses.\r\n *\r\n * These service factories are ordered by request, i.e. they are applied in the same order as the\r\n * array, on request, but reverse order, on response.\r\n *\r\n * {@link ng.$http#interceptors Interceptors detailed info}\r\n **/\r\n var interceptorFactories = this.interceptors = [];\r\n\r\n this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',\r\n function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {\r\n\r\n var defaultCache = $cacheFactory('$http');\r\n\r\n /**\r\n * Interceptors stored in reverse order. Inner interceptors before outer interceptors.\r\n * The reversal is needed so that we can build up the interception chain around the\r\n * server request.\r\n */\r\n var reversedInterceptors = [];\r\n\r\n forEach(interceptorFactories, function(interceptorFactory) {\r\n reversedInterceptors.unshift(isString(interceptorFactory)\r\n ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));\r\n });\r\n\r\n /**\r\n * @ngdoc service\r\n * @kind function\r\n * @name $http\r\n * @requires ng.$httpBackend\r\n * @requires $cacheFactory\r\n * @requires $rootScope\r\n * @requires $q\r\n * @requires $injector\r\n *\r\n * @description\r\n * The `$http` service is a core Angular service that facilitates communication with the remote\r\n * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)\r\n * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).\r\n *\r\n * For unit testing applications that use `$http` service, see\r\n * {@link ngMock.$httpBackend $httpBackend mock}.\r\n *\r\n * For a higher level of abstraction, please check out the {@link ngResource.$resource\r\n * $resource} service.\r\n *\r\n * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by\r\n * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage\r\n * it is important to familiarize yourself with these APIs and the guarantees they provide.\r\n *\r\n *\r\n * ## General usage\r\n * The `$http` service is a function which takes a single argument — a configuration object —\r\n * that is used to generate an HTTP request and returns a {@link ng.$q promise}\r\n * with two $http specific methods: `success` and `error`.\r\n *\r\n * ```js\r\n * // Simple GET request example :\r\n * $http.get('/someUrl').\r\n * success(function(data, status, headers, config) {\r\n * // this callback will be called asynchronously\r\n * // when the response is available\r\n * }).\r\n * error(function(data, status, headers, config) {\r\n * // called asynchronously if an error occurs\r\n * // or server returns response with an error status.\r\n * });\r\n * ```\r\n *\r\n * ```js\r\n * // Simple POST request example (passing data) :\r\n * $http.post('/someUrl', {msg:'hello word!'}).\r\n * success(function(data, status, headers, config) {\r\n * // this callback will be called asynchronously\r\n * // when the response is available\r\n * }).\r\n * error(function(data, status, headers, config) {\r\n * // called asynchronously if an error occurs\r\n * // or server returns response with an error status.\r\n * });\r\n * ```\r\n *\r\n *\r\n * Since the returned value of calling the $http function is a `promise`, you can also use\r\n * the `then` method to register callbacks, and these callbacks will receive a single argument –\r\n * an object representing the response. See the API signature and type info below for more\r\n * details.\r\n *\r\n * A response status code between 200 and 299 is considered a success status and\r\n * will result in the success callback being called. Note that if the response is a redirect,\r\n * XMLHttpRequest will transparently follow it, meaning that the error callback will not be\r\n * called for such responses.\r\n *\r\n * ## Writing Unit Tests that use $http\r\n * When unit testing (using {@link ngMock ngMock}), it is necessary to call\r\n * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending\r\n * request using trained responses.\r\n *\r\n * ```\r\n * $httpBackend.expectGET(...);\r\n * $http.get(...);\r\n * $httpBackend.flush();\r\n * ```\r\n *\r\n * ## Shortcut methods\r\n *\r\n * Shortcut methods are also available. All shortcut methods require passing in the URL, and\r\n * request data must be passed in for POST/PUT requests.\r\n *\r\n * ```js\r\n * $http.get('/someUrl').success(successCallback);\r\n * $http.post('/someUrl', data).success(successCallback);\r\n * ```\r\n *\r\n * Complete list of shortcut methods:\r\n *\r\n * - {@link ng.$http#get $http.get}\r\n * - {@link ng.$http#head $http.head}\r\n * - {@link ng.$http#post $http.post}\r\n * - {@link ng.$http#put $http.put}\r\n * - {@link ng.$http#delete $http.delete}\r\n * - {@link ng.$http#jsonp $http.jsonp}\r\n * - {@link ng.$http#patch $http.patch}\r\n *\r\n *\r\n * ## Setting HTTP Headers\r\n *\r\n * The $http service will automatically add certain HTTP headers to all requests. These defaults\r\n * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration\r\n * object, which currently contains this default configuration:\r\n *\r\n * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):\r\n * - `Accept: application/json, text/plain, * / *`\r\n * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)\r\n * - `Content-Type: application/json`\r\n * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)\r\n * - `Content-Type: application/json`\r\n *\r\n * To add or overwrite these defaults, simply add or remove a property from these configuration\r\n * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object\r\n * with the lowercased HTTP method name as the key, e.g.\r\n * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.\r\n *\r\n * The defaults can also be set at runtime via the `$http.defaults` object in the same\r\n * fashion. For example:\r\n *\r\n * ```\r\n * module.run(function($http) {\r\n * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'\r\n * });\r\n * ```\r\n *\r\n * In addition, you can supply a `headers` property in the config object passed when\r\n * calling `$http(config)`, which overrides the defaults without changing them globally.\r\n *\r\n * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,\r\n * Use the `headers` property, setting the desired header to `undefined`. For example:\r\n *\r\n * ```js\r\n * var req = {\r\n * method: 'POST',\r\n * url: 'http://example.com',\r\n * headers: {\r\n * 'Content-Type': undefined\r\n * },\r\n * data: { test: 'test' }\r\n * }\r\n *\r\n * $http(req).success(function(){...}).error(function(){...});\r\n * ```\r\n *\r\n * ## Transforming Requests and Responses\r\n *\r\n * Both requests and responses can be transformed using transformation functions: `transformRequest`\r\n * and `transformResponse`. These properties can be a single function that returns\r\n * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,\r\n * which allows you to `push` or `unshift` a new transformation function into the transformation chain.\r\n *\r\n * ### Default Transformations\r\n *\r\n * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and\r\n * `defaults.transformResponse` properties. If a request does not provide its own transformations\r\n * then these will be applied.\r\n *\r\n * You can augment or replace the default transformations by modifying these properties by adding to or\r\n * replacing the array.\r\n *\r\n * Angular provides the following default transformations:\r\n *\r\n * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):\r\n *\r\n * - If the `data` property of the request configuration object contains an object, serialize it\r\n * into JSON format.\r\n *\r\n * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):\r\n *\r\n * - If XSRF prefix is detected, strip it (see Security Considerations section below).\r\n * - If JSON response is detected, deserialize it using a JSON parser.\r\n *\r\n *\r\n * ### Overriding the Default Transformations Per Request\r\n *\r\n * If you wish override the request/response transformations only for a single request then provide\r\n * `transformRequest` and/or `transformResponse` properties on the configuration object passed\r\n * into `$http`.\r\n *\r\n * Note that if you provide these properties on the config object the default transformations will be\r\n * overwritten. If you wish to augment the default transformations then you must include them in your\r\n * local transformation array.\r\n *\r\n * The following code demonstrates adding a new response transformation to be run after the default response\r\n * transformations have been run.\r\n *\r\n * ```js\r\n * function appendTransform(defaults, transform) {\r\n *\r\n * // We can't guarantee that the default transformation is an array\r\n * defaults = angular.isArray(defaults) ? defaults : [defaults];\r\n *\r\n * // Append the new transformation to the defaults\r\n * return defaults.concat(transform);\r\n * }\r\n *\r\n * $http({\r\n * url: '...',\r\n * method: 'GET',\r\n * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {\r\n * return doTransform(value);\r\n * })\r\n * });\r\n * ```\r\n *\r\n *\r\n * ## Caching\r\n *\r\n * To enable caching, set the request configuration `cache` property to `true` (to use default\r\n * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).\r\n * When the cache is enabled, `$http` stores the response from the server in the specified\r\n * cache. The next time the same request is made, the response is served from the cache without\r\n * sending a request to the server.\r\n *\r\n * Note that even if the response is served from cache, delivery of the data is asynchronous in\r\n * the same way that real requests are.\r\n *\r\n * If there are multiple GET requests for the same URL that should be cached using the same\r\n * cache, but the cache is not populated yet, only one request to the server will be made and\r\n * the remaining requests will be fulfilled using the response from the first request.\r\n *\r\n * You can change the default cache to a new object (built with\r\n * {@link ng.$cacheFactory `$cacheFactory`}) by updating the\r\n * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set\r\n * their `cache` property to `true` will now use this cache object.\r\n *\r\n * If you set the default cache to `false` then only requests that specify their own custom\r\n * cache object will be cached.\r\n *\r\n * ## Interceptors\r\n *\r\n * Before you start creating interceptors, be sure to understand the\r\n * {@link ng.$q $q and deferred/promise APIs}.\r\n *\r\n * For purposes of global error handling, authentication, or any kind of synchronous or\r\n * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be\r\n * able to intercept requests before they are handed to the server and\r\n * responses before they are handed over to the application code that\r\n * initiated these requests. The interceptors leverage the {@link ng.$q\r\n * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.\r\n *\r\n * The interceptors are service factories that are registered with the `$httpProvider` by\r\n * adding them to the `$httpProvider.interceptors` array. The factory is called and\r\n * injected with dependencies (if specified) and returns the interceptor.\r\n *\r\n * There are two kinds of interceptors (and two kinds of rejection interceptors):\r\n *\r\n * * `request`: interceptors get called with a http `config` object. The function is free to\r\n * modify the `config` object or create a new one. The function needs to return the `config`\r\n * object directly, or a promise containing the `config` or a new `config` object.\r\n * * `requestError`: interceptor gets called when a previous interceptor threw an error or\r\n * resolved with a rejection.\r\n * * `response`: interceptors get called with http `response` object. The function is free to\r\n * modify the `response` object or create a new one. The function needs to return the `response`\r\n * object directly, or as a promise containing the `response` or a new `response` object.\r\n * * `responseError`: interceptor gets called when a previous interceptor threw an error or\r\n * resolved with a rejection.\r\n *\r\n *\r\n * ```js\r\n * // register the interceptor as a service\r\n * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {\r\n * return {\r\n * // optional method\r\n * 'request': function(config) {\r\n * // do something on success\r\n * return config;\r\n * },\r\n *\r\n * // optional method\r\n * 'requestError': function(rejection) {\r\n * // do something on error\r\n * if (canRecover(rejection)) {\r\n * return responseOrNewPromise\r\n * }\r\n * return $q.reject(rejection);\r\n * },\r\n *\r\n *\r\n *\r\n * // optional method\r\n * 'response': function(response) {\r\n * // do something on success\r\n * return response;\r\n * },\r\n *\r\n * // optional method\r\n * 'responseError': function(rejection) {\r\n * // do something on error\r\n * if (canRecover(rejection)) {\r\n * return responseOrNewPromise\r\n * }\r\n * return $q.reject(rejection);\r\n * }\r\n * };\r\n * });\r\n *\r\n * $httpProvider.interceptors.push('myHttpInterceptor');\r\n *\r\n *\r\n * // alternatively, register the interceptor via an anonymous factory\r\n * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {\r\n * return {\r\n * 'request': function(config) {\r\n * // same as above\r\n * },\r\n *\r\n * 'response': function(response) {\r\n * // same as above\r\n * }\r\n * };\r\n * });\r\n * ```\r\n *\r\n * ## Security Considerations\r\n *\r\n * When designing web applications, consider security threats from:\r\n *\r\n * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)\r\n * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)\r\n *\r\n * Both server and the client must cooperate in order to eliminate these threats. Angular comes\r\n * pre-configured with strategies that address these issues, but for this to work backend server\r\n * cooperation is required.\r\n *\r\n * ### JSON Vulnerability Protection\r\n *\r\n * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)\r\n * allows third party website to turn your JSON resource URL into\r\n * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To\r\n * counter this your server can prefix all JSON requests with following string `\")]}',\\n\"`.\r\n * Angular will automatically strip the prefix before processing it as JSON.\r\n *\r\n * For example if your server needs to return:\r\n * ```js\r\n * ['one','two']\r\n * ```\r\n *\r\n * which is vulnerable to attack, your server can return:\r\n * ```js\r\n * )]}',\r\n * ['one','two']\r\n * ```\r\n *\r\n * Angular will strip the prefix, before processing the JSON.\r\n *\r\n *\r\n * ### Cross Site Request Forgery (XSRF) Protection\r\n *\r\n * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which\r\n * an unauthorized site can gain your user's private data. Angular provides a mechanism\r\n * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie\r\n * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only\r\n * JavaScript that runs on your domain could read the cookie, your server can be assured that\r\n * the XHR came from JavaScript running on your domain. The header will not be set for\r\n * cross-domain requests.\r\n *\r\n * To take advantage of this, your server needs to set a token in a JavaScript readable session\r\n * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the\r\n * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure\r\n * that only JavaScript running on your domain could have sent the request. The token must be\r\n * unique for each user and must be verifiable by the server (to prevent the JavaScript from\r\n * making up its own tokens). We recommend that the token is a digest of your site's\r\n * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography))\r\n * for added security.\r\n *\r\n * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName\r\n * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,\r\n * or the per-request config object.\r\n *\r\n *\r\n * @param {object} config Object describing the request to be made and how it should be\r\n * processed. The object has following properties:\r\n *\r\n * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)\r\n * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.\r\n * - **params** – `{Object.}` – Map of strings or objects which will be turned\r\n * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be\r\n * JSONified.\r\n * - **data** – `{string|Object}` – Data to be sent as the request message data.\r\n * - **headers** – `{Object}` – Map of strings or functions which return strings representing\r\n * HTTP headers to send to the server. If the return value of a function is null, the\r\n * header will not be sent.\r\n * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.\r\n * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.\r\n * - **transformRequest** –\r\n * `{function(data, headersGetter)|Array.}` –\r\n * transform function or an array of such functions. The transform function takes the http\r\n * request body and headers and returns its transformed (typically serialized) version.\r\n * See {@link ng.$http#overriding-the-default-transformations-per-request\r\n * Overriding the Default Transformations}\r\n * - **transformResponse** –\r\n * `{function(data, headersGetter, status)|Array.}` –\r\n * transform function or an array of such functions. The transform function takes the http\r\n * response body, headers and status and returns its transformed (typically deserialized) version.\r\n * See {@link ng.$http#overriding-the-default-transformations-per-request\r\n * Overriding the Default Transformations}\r\n * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the\r\n * GET request, otherwise if a cache instance built with\r\n * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for\r\n * caching.\r\n * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}\r\n * that should abort the request when resolved.\r\n * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the\r\n * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)\r\n * for more information.\r\n * - **responseType** - `{string}` - see\r\n * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).\r\n *\r\n * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the\r\n * standard `then` method and two http specific methods: `success` and `error`. The `then`\r\n * method takes two arguments a success and an error callback which will be called with a\r\n * response object. The `success` and `error` methods take a single argument - a function that\r\n * will be called when the request succeeds or fails respectively. The arguments passed into\r\n * these functions are destructured representation of the response object passed into the\r\n * `then` method. The response object has these properties:\r\n *\r\n * - **data** – `{string|Object}` – The response body transformed with the transform\r\n * functions.\r\n * - **status** – `{number}` – HTTP status code of the response.\r\n * - **headers** – `{function([headerName])}` – Header getter function.\r\n * - **config** – `{Object}` – The configuration object that was used to generate the request.\r\n * - **statusText** – `{string}` – HTTP status text of the response.\r\n *\r\n * @property {Array.} pendingRequests Array of config objects for currently pending\r\n * requests. This is primarily meant to be used for debugging purposes.\r\n *\r\n *\r\n * @example\r\n\r\n\r\n
    \r\n \r\n \r\n
    \r\n \r\n \r\n \r\n
    http status code: {{status}}
    \r\n
    http response data: {{data}}
    \r\n
    \r\n
    \r\n\r\n angular.module('httpExample', [])\r\n .controller('FetchController', ['$scope', '$http', '$templateCache',\r\n function($scope, $http, $templateCache) {\r\n $scope.method = 'GET';\r\n $scope.url = 'http-hello.html';\r\n\r\n $scope.fetch = function() {\r\n $scope.code = null;\r\n $scope.response = null;\r\n\r\n $http({method: $scope.method, url: $scope.url, cache: $templateCache}).\r\n success(function(data, status) {\r\n $scope.status = status;\r\n $scope.data = data;\r\n }).\r\n error(function(data, status) {\r\n $scope.data = data || \"Request failed\";\r\n $scope.status = status;\r\n });\r\n };\r\n\r\n $scope.updateModel = function(method, url) {\r\n $scope.method = method;\r\n $scope.url = url;\r\n };\r\n }]);\r\n\r\n\r\n Hello, $http!\r\n\r\n\r\n var status = element(by.binding('status'));\r\n var data = element(by.binding('data'));\r\n var fetchBtn = element(by.id('fetchbtn'));\r\n var sampleGetBtn = element(by.id('samplegetbtn'));\r\n var sampleJsonpBtn = element(by.id('samplejsonpbtn'));\r\n var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));\r\n\r\n it('should make an xhr GET request', function() {\r\n sampleGetBtn.click();\r\n fetchBtn.click();\r\n expect(status.getText()).toMatch('200');\r\n expect(data.getText()).toMatch(/Hello, \\$http!/);\r\n });\r\n\r\n// Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185\r\n// it('should make a JSONP request to angularjs.org', function() {\r\n// sampleJsonpBtn.click();\r\n// fetchBtn.click();\r\n// expect(status.getText()).toMatch('200');\r\n// expect(data.getText()).toMatch(/Super Hero!/);\r\n// });\r\n\r\n it('should make JSONP request to invalid URL and invoke the error handler',\r\n function() {\r\n invalidJsonpBtn.click();\r\n fetchBtn.click();\r\n expect(status.getText()).toMatch('0');\r\n expect(data.getText()).toMatch('Request failed');\r\n });\r\n\r\n
    \r\n */\r\n function $http(requestConfig) {\r\n\r\n if (!angular.isObject(requestConfig)) {\r\n throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);\r\n }\r\n\r\n var config = extend({\r\n method: 'get',\r\n transformRequest: defaults.transformRequest,\r\n transformResponse: defaults.transformResponse\r\n }, requestConfig);\r\n\r\n config.headers = mergeHeaders(requestConfig);\r\n config.method = uppercase(config.method);\r\n\r\n var serverRequest = function(config) {\r\n var headers = config.headers;\r\n var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);\r\n\r\n // strip content-type if data is undefined\r\n if (isUndefined(reqData)) {\r\n forEach(headers, function(value, header) {\r\n if (lowercase(header) === 'content-type') {\r\n delete headers[header];\r\n }\r\n });\r\n }\r\n\r\n if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {\r\n config.withCredentials = defaults.withCredentials;\r\n }\r\n\r\n // send request\r\n return sendReq(config, reqData).then(transformResponse, transformResponse);\r\n };\r\n\r\n var chain = [serverRequest, undefined];\r\n var promise = $q.when(config);\r\n\r\n // apply interceptors\r\n forEach(reversedInterceptors, function(interceptor) {\r\n if (interceptor.request || interceptor.requestError) {\r\n chain.unshift(interceptor.request, interceptor.requestError);\r\n }\r\n if (interceptor.response || interceptor.responseError) {\r\n chain.push(interceptor.response, interceptor.responseError);\r\n }\r\n });\r\n\r\n while (chain.length) {\r\n var thenFn = chain.shift();\r\n var rejectFn = chain.shift();\r\n\r\n promise = promise.then(thenFn, rejectFn);\r\n }\r\n\r\n promise.success = function(fn) {\r\n assertArgFn(fn, 'fn');\r\n\r\n promise.then(function(response) {\r\n fn(response.data, response.status, response.headers, config);\r\n });\r\n return promise;\r\n };\r\n\r\n promise.error = function(fn) {\r\n assertArgFn(fn, 'fn');\r\n\r\n promise.then(null, function(response) {\r\n fn(response.data, response.status, response.headers, config);\r\n });\r\n return promise;\r\n };\r\n\r\n return promise;\r\n\r\n function transformResponse(response) {\r\n // make a copy since the response must be cacheable\r\n var resp = extend({}, response);\r\n if (!response.data) {\r\n resp.data = response.data;\r\n } else {\r\n resp.data = transformData(response.data, response.headers, response.status, config.transformResponse);\r\n }\r\n return (isSuccess(response.status))\r\n ? resp\r\n : $q.reject(resp);\r\n }\r\n\r\n function executeHeaderFns(headers) {\r\n var headerContent, processedHeaders = {};\r\n\r\n forEach(headers, function(headerFn, header) {\r\n if (isFunction(headerFn)) {\r\n headerContent = headerFn();\r\n if (headerContent != null) {\r\n processedHeaders[header] = headerContent;\r\n }\r\n } else {\r\n processedHeaders[header] = headerFn;\r\n }\r\n });\r\n\r\n return processedHeaders;\r\n }\r\n\r\n function mergeHeaders(config) {\r\n var defHeaders = defaults.headers,\r\n reqHeaders = extend({}, config.headers),\r\n defHeaderName, lowercaseDefHeaderName, reqHeaderName;\r\n\r\n defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);\r\n\r\n // using for-in instead of forEach to avoid unecessary iteration after header has been found\r\n defaultHeadersIteration:\r\n for (defHeaderName in defHeaders) {\r\n lowercaseDefHeaderName = lowercase(defHeaderName);\r\n\r\n for (reqHeaderName in reqHeaders) {\r\n if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {\r\n continue defaultHeadersIteration;\r\n }\r\n }\r\n\r\n reqHeaders[defHeaderName] = defHeaders[defHeaderName];\r\n }\r\n\r\n // execute if header value is a function for merged headers\r\n return executeHeaderFns(reqHeaders);\r\n }\r\n }\r\n\r\n $http.pendingRequests = [];\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $http#get\r\n *\r\n * @description\r\n * Shortcut method to perform `GET` request.\r\n *\r\n * @param {string} url Relative or absolute URL specifying the destination of the request\r\n * @param {Object=} config Optional configuration object\r\n * @returns {HttpPromise} Future object\r\n */\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $http#delete\r\n *\r\n * @description\r\n * Shortcut method to perform `DELETE` request.\r\n *\r\n * @param {string} url Relative or absolute URL specifying the destination of the request\r\n * @param {Object=} config Optional configuration object\r\n * @returns {HttpPromise} Future object\r\n */\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $http#head\r\n *\r\n * @description\r\n * Shortcut method to perform `HEAD` request.\r\n *\r\n * @param {string} url Relative or absolute URL specifying the destination of the request\r\n * @param {Object=} config Optional configuration object\r\n * @returns {HttpPromise} Future object\r\n */\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $http#jsonp\r\n *\r\n * @description\r\n * Shortcut method to perform `JSONP` request.\r\n *\r\n * @param {string} url Relative or absolute URL specifying the destination of the request.\r\n * The name of the callback should be the string `JSON_CALLBACK`.\r\n * @param {Object=} config Optional configuration object\r\n * @returns {HttpPromise} Future object\r\n */\r\n createShortMethods('get', 'delete', 'head', 'jsonp');\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $http#post\r\n *\r\n * @description\r\n * Shortcut method to perform `POST` request.\r\n *\r\n * @param {string} url Relative or absolute URL specifying the destination of the request\r\n * @param {*} data Request content\r\n * @param {Object=} config Optional configuration object\r\n * @returns {HttpPromise} Future object\r\n */\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $http#put\r\n *\r\n * @description\r\n * Shortcut method to perform `PUT` request.\r\n *\r\n * @param {string} url Relative or absolute URL specifying the destination of the request\r\n * @param {*} data Request content\r\n * @param {Object=} config Optional configuration object\r\n * @returns {HttpPromise} Future object\r\n */\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $http#patch\r\n *\r\n * @description\r\n * Shortcut method to perform `PATCH` request.\r\n *\r\n * @param {string} url Relative or absolute URL specifying the destination of the request\r\n * @param {*} data Request content\r\n * @param {Object=} config Optional configuration object\r\n * @returns {HttpPromise} Future object\r\n */\r\n createShortMethodsWithData('post', 'put', 'patch');\r\n\r\n /**\r\n * @ngdoc property\r\n * @name $http#defaults\r\n *\r\n * @description\r\n * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of\r\n * default headers, withCredentials as well as request and response transformations.\r\n *\r\n * See \"Setting HTTP Headers\" and \"Transforming Requests and Responses\" sections above.\r\n */\r\n $http.defaults = defaults;\r\n\r\n\r\n return $http;\r\n\r\n\r\n function createShortMethods(names) {\r\n forEach(arguments, function(name) {\r\n $http[name] = function(url, config) {\r\n return $http(extend(config || {}, {\r\n method: name,\r\n url: url\r\n }));\r\n };\r\n });\r\n }\r\n\r\n\r\n function createShortMethodsWithData(name) {\r\n forEach(arguments, function(name) {\r\n $http[name] = function(url, data, config) {\r\n return $http(extend(config || {}, {\r\n method: name,\r\n url: url,\r\n data: data\r\n }));\r\n };\r\n });\r\n }\r\n\r\n\r\n /**\r\n * Makes the request.\r\n *\r\n * !!! ACCESSES CLOSURE VARS:\r\n * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests\r\n */\r\n function sendReq(config, reqData) {\r\n var deferred = $q.defer(),\r\n promise = deferred.promise,\r\n cache,\r\n cachedResp,\r\n reqHeaders = config.headers,\r\n url = buildUrl(config.url, config.params);\r\n\r\n $http.pendingRequests.push(config);\r\n promise.then(removePendingReq, removePendingReq);\r\n\r\n\r\n if ((config.cache || defaults.cache) && config.cache !== false &&\r\n (config.method === 'GET' || config.method === 'JSONP')) {\r\n cache = isObject(config.cache) ? config.cache\r\n : isObject(defaults.cache) ? defaults.cache\r\n : defaultCache;\r\n }\r\n\r\n if (cache) {\r\n cachedResp = cache.get(url);\r\n if (isDefined(cachedResp)) {\r\n if (isPromiseLike(cachedResp)) {\r\n // cached request has already been sent, but there is no response yet\r\n cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);\r\n } else {\r\n // serving from cache\r\n if (isArray(cachedResp)) {\r\n resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);\r\n } else {\r\n resolvePromise(cachedResp, 200, {}, 'OK');\r\n }\r\n }\r\n } else {\r\n // put the promise for the non-transformed response into cache as a placeholder\r\n cache.put(url, promise);\r\n }\r\n }\r\n\r\n\r\n // if we won't have the response in cache, set the xsrf headers and\r\n // send the request to the backend\r\n if (isUndefined(cachedResp)) {\r\n var xsrfValue = urlIsSameOrigin(config.url)\r\n ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName]\r\n : undefined;\r\n if (xsrfValue) {\r\n reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;\r\n }\r\n\r\n $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,\r\n config.withCredentials, config.responseType);\r\n }\r\n\r\n return promise;\r\n\r\n\r\n /**\r\n * Callback registered to $httpBackend():\r\n * - caches the response if desired\r\n * - resolves the raw $http promise\r\n * - calls $apply\r\n */\r\n function done(status, response, headersString, statusText) {\r\n if (cache) {\r\n if (isSuccess(status)) {\r\n cache.put(url, [status, response, parseHeaders(headersString), statusText]);\r\n } else {\r\n // remove promise from the cache\r\n cache.remove(url);\r\n }\r\n }\r\n\r\n function resolveHttpPromise() {\r\n resolvePromise(response, status, headersString, statusText);\r\n }\r\n\r\n if (useApplyAsync) {\r\n $rootScope.$applyAsync(resolveHttpPromise);\r\n } else {\r\n resolveHttpPromise();\r\n if (!$rootScope.$$phase) $rootScope.$apply();\r\n }\r\n }\r\n\r\n\r\n /**\r\n * Resolves the raw $http promise.\r\n */\r\n function resolvePromise(response, status, headers, statusText) {\r\n // normalize internal statuses to 0\r\n status = Math.max(status, 0);\r\n\r\n (isSuccess(status) ? deferred.resolve : deferred.reject)({\r\n data: response,\r\n status: status,\r\n headers: headersGetter(headers),\r\n config: config,\r\n statusText: statusText\r\n });\r\n }\r\n\r\n function resolvePromiseWithResult(result) {\r\n resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);\r\n }\r\n\r\n function removePendingReq() {\r\n var idx = $http.pendingRequests.indexOf(config);\r\n if (idx !== -1) $http.pendingRequests.splice(idx, 1);\r\n }\r\n }\r\n\r\n\r\n function buildUrl(url, params) {\r\n if (!params) return url;\r\n var parts = [];\r\n forEachSorted(params, function(value, key) {\r\n if (value === null || isUndefined(value)) return;\r\n if (!isArray(value)) value = [value];\r\n\r\n forEach(value, function(v) {\r\n if (isObject(v)) {\r\n if (isDate(v)) {\r\n v = v.toISOString();\r\n } else {\r\n v = toJson(v);\r\n }\r\n }\r\n parts.push(encodeUriQuery(key) + '=' +\r\n encodeUriQuery(v));\r\n });\r\n });\r\n if (parts.length > 0) {\r\n url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');\r\n }\r\n return url;\r\n }\r\n }];\r\n}\r\n\r\nfunction createXhr() {\r\n return new window.XMLHttpRequest();\r\n}\r\n\r\n/**\r\n * @ngdoc service\r\n * @name $httpBackend\r\n * @requires $window\r\n * @requires $document\r\n *\r\n * @description\r\n * HTTP backend used by the {@link ng.$http service} that delegates to\r\n * XMLHttpRequest object or JSONP and deals with browser incompatibilities.\r\n *\r\n * You should never need to use this service directly, instead use the higher-level abstractions:\r\n * {@link ng.$http $http} or {@link ngResource.$resource $resource}.\r\n *\r\n * During testing this implementation is swapped with {@link ngMock.$httpBackend mock\r\n * $httpBackend} which can be trained with responses.\r\n */\r\nfunction $HttpBackendProvider() {\r\n this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {\r\n return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);\r\n }];\r\n}\r\n\r\nfunction createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {\r\n // TODO(vojta): fix the signature\r\n return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {\r\n $browser.$$incOutstandingRequestCount();\r\n url = url || $browser.url();\r\n\r\n if (lowercase(method) == 'jsonp') {\r\n var callbackId = '_' + (callbacks.counter++).toString(36);\r\n callbacks[callbackId] = function(data) {\r\n callbacks[callbackId].data = data;\r\n callbacks[callbackId].called = true;\r\n };\r\n\r\n var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),\r\n callbackId, function(status, text) {\r\n completeRequest(callback, status, callbacks[callbackId].data, \"\", text);\r\n callbacks[callbackId] = noop;\r\n });\r\n } else {\r\n\r\n var xhr = createXhr();\r\n\r\n xhr.open(method, url, true);\r\n forEach(headers, function(value, key) {\r\n if (isDefined(value)) {\r\n xhr.setRequestHeader(key, value);\r\n }\r\n });\r\n\r\n xhr.onload = function requestLoaded() {\r\n var statusText = xhr.statusText || '';\r\n\r\n // responseText is the old-school way of retrieving response (supported by IE9)\r\n // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)\r\n var response = ('response' in xhr) ? xhr.response : xhr.responseText;\r\n\r\n // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)\r\n var status = xhr.status === 1223 ? 204 : xhr.status;\r\n\r\n // fix status code when it is 0 (0 status is undocumented).\r\n // Occurs when accessing file resources or on Android 4.1 stock browser\r\n // while retrieving files from application cache.\r\n if (status === 0) {\r\n status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;\r\n }\r\n\r\n completeRequest(callback,\r\n status,\r\n response,\r\n xhr.getAllResponseHeaders(),\r\n statusText);\r\n };\r\n\r\n var requestError = function() {\r\n // The response is always empty\r\n // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error\r\n completeRequest(callback, -1, null, null, '');\r\n };\r\n\r\n xhr.onerror = requestError;\r\n xhr.onabort = requestError;\r\n\r\n if (withCredentials) {\r\n xhr.withCredentials = true;\r\n }\r\n\r\n if (responseType) {\r\n try {\r\n xhr.responseType = responseType;\r\n } catch (e) {\r\n // WebKit added support for the json responseType value on 09/03/2013\r\n // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are\r\n // known to throw when setting the value \"json\" as the response type. Other older\r\n // browsers implementing the responseType\r\n //\r\n // The json response type can be ignored if not supported, because JSON payloads are\r\n // parsed on the client-side regardless.\r\n if (responseType !== 'json') {\r\n throw e;\r\n }\r\n }\r\n }\r\n\r\n xhr.send(post || null);\r\n }\r\n\r\n if (timeout > 0) {\r\n var timeoutId = $browserDefer(timeoutRequest, timeout);\r\n } else if (isPromiseLike(timeout)) {\r\n timeout.then(timeoutRequest);\r\n }\r\n\r\n\r\n function timeoutRequest() {\r\n jsonpDone && jsonpDone();\r\n xhr && xhr.abort();\r\n }\r\n\r\n function completeRequest(callback, status, response, headersString, statusText) {\r\n // cancel timeout and subsequent timeout promise resolution\r\n if (timeoutId !== undefined) {\r\n $browserDefer.cancel(timeoutId);\r\n }\r\n jsonpDone = xhr = null;\r\n\r\n callback(status, response, headersString, statusText);\r\n $browser.$$completeOutstandingRequest(noop);\r\n }\r\n };\r\n\r\n function jsonpReq(url, callbackId, done) {\r\n // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:\r\n // - fetches local scripts via XHR and evals them\r\n // - adds and immediately removes script elements from the document\r\n var script = rawDocument.createElement('script'), callback = null;\r\n script.type = \"text/javascript\";\r\n script.src = url;\r\n script.async = true;\r\n\r\n callback = function(event) {\r\n removeEventListenerFn(script, \"load\", callback);\r\n removeEventListenerFn(script, \"error\", callback);\r\n rawDocument.body.removeChild(script);\r\n script = null;\r\n var status = -1;\r\n var text = \"unknown\";\r\n\r\n if (event) {\r\n if (event.type === \"load\" && !callbacks[callbackId].called) {\r\n event = { type: \"error\" };\r\n }\r\n text = event.type;\r\n status = event.type === \"error\" ? 404 : 200;\r\n }\r\n\r\n if (done) {\r\n done(status, text);\r\n }\r\n };\r\n\r\n addEventListenerFn(script, \"load\", callback);\r\n addEventListenerFn(script, \"error\", callback);\r\n rawDocument.body.appendChild(script);\r\n return callback;\r\n }\r\n}\r\n\r\nvar $interpolateMinErr = minErr('$interpolate');\r\n\r\n/**\r\n * @ngdoc provider\r\n * @name $interpolateProvider\r\n *\r\n * @description\r\n *\r\n * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.\r\n *\r\n * @example\r\n\r\n\r\n\r\n
    \r\n //demo.label//\r\n
    \r\n
    \r\n\r\n it('should interpolate binding with custom symbols', function() {\r\n expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');\r\n });\r\n\r\n
    \r\n */\r\nfunction $InterpolateProvider() {\r\n var startSymbol = '{{';\r\n var endSymbol = '}}';\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $interpolateProvider#startSymbol\r\n * @description\r\n * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.\r\n *\r\n * @param {string=} value new value to set the starting symbol to.\r\n * @returns {string|self} Returns the symbol when used as getter and self if used as setter.\r\n */\r\n this.startSymbol = function(value) {\r\n if (value) {\r\n startSymbol = value;\r\n return this;\r\n } else {\r\n return startSymbol;\r\n }\r\n };\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $interpolateProvider#endSymbol\r\n * @description\r\n * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.\r\n *\r\n * @param {string=} value new value to set the ending symbol to.\r\n * @returns {string|self} Returns the symbol when used as getter and self if used as setter.\r\n */\r\n this.endSymbol = function(value) {\r\n if (value) {\r\n endSymbol = value;\r\n return this;\r\n } else {\r\n return endSymbol;\r\n }\r\n };\r\n\r\n\r\n this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {\r\n var startSymbolLength = startSymbol.length,\r\n endSymbolLength = endSymbol.length,\r\n escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),\r\n escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');\r\n\r\n function escape(ch) {\r\n return '\\\\\\\\\\\\' + ch;\r\n }\r\n\r\n /**\r\n * @ngdoc service\r\n * @name $interpolate\r\n * @kind function\r\n *\r\n * @requires $parse\r\n * @requires $sce\r\n *\r\n * @description\r\n *\r\n * Compiles a string with markup into an interpolation function. This service is used by the\r\n * HTML {@link ng.$compile $compile} service for data binding. See\r\n * {@link ng.$interpolateProvider $interpolateProvider} for configuring the\r\n * interpolation markup.\r\n *\r\n *\r\n * ```js\r\n * var $interpolate = ...; // injected\r\n * var exp = $interpolate('Hello {{name | uppercase}}!');\r\n * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');\r\n * ```\r\n *\r\n * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is\r\n * `true`, the interpolation function will return `undefined` unless all embedded expressions\r\n * evaluate to a value other than `undefined`.\r\n *\r\n * ```js\r\n * var $interpolate = ...; // injected\r\n * var context = {greeting: 'Hello', name: undefined };\r\n *\r\n * // default \"forgiving\" mode\r\n * var exp = $interpolate('{{greeting}} {{name}}!');\r\n * expect(exp(context)).toEqual('Hello !');\r\n *\r\n * // \"allOrNothing\" mode\r\n * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);\r\n * expect(exp(context)).toBeUndefined();\r\n * context.name = 'Angular';\r\n * expect(exp(context)).toEqual('Hello Angular!');\r\n * ```\r\n *\r\n * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.\r\n *\r\n * ####Escaped Interpolation\r\n * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers\r\n * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).\r\n * It will be rendered as a regular start/end marker, and will not be interpreted as an expression\r\n * or binding.\r\n *\r\n * This enables web-servers to prevent script injection attacks and defacing attacks, to some\r\n * degree, while also enabling code examples to work without relying on the\r\n * {@link ng.directive:ngNonBindable ngNonBindable} directive.\r\n *\r\n * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,\r\n * replacing angle brackets (<, >) with &lt; and &gt; respectively, and replacing all\r\n * interpolation start/end markers with their escaped counterparts.**\r\n *\r\n * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered\r\n * output when the $interpolate service processes the text. So, for HTML elements interpolated\r\n * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter\r\n * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,\r\n * this is typically useful only when user-data is used in rendering a template from the server, or\r\n * when otherwise untrusted data is used by a directive.\r\n *\r\n * \r\n * \r\n *
    \r\n *

    {{apptitle}}: \\{\\{ username = \"defaced value\"; \\}\\}\r\n *

    \r\n *

    {{username}} attempts to inject code which will deface the\r\n * application, but fails to accomplish their task, because the server has correctly\r\n * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)\r\n * characters.

    \r\n *

    Instead, the result of the attempted script injection is visible, and can be removed\r\n * from the database by an administrator.

    \r\n *
    \r\n *
    \r\n *
    \r\n *\r\n * @param {string} text The text with markup to interpolate.\r\n * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have\r\n * embedded expression in order to return an interpolation function. Strings with no\r\n * embedded expression will return null for the interpolation function.\r\n * @param {string=} trustedContext when provided, the returned function passes the interpolated\r\n * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,\r\n * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that\r\n * provides Strict Contextual Escaping for details.\r\n * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined\r\n * unless all embedded expressions evaluate to a value other than `undefined`.\r\n * @returns {function(context)} an interpolation function which is used to compute the\r\n * interpolated string. The function has these parameters:\r\n *\r\n * - `context`: evaluation context for all expressions embedded in the interpolated text\r\n */\r\n function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {\r\n allOrNothing = !!allOrNothing;\r\n var startIndex,\r\n endIndex,\r\n index = 0,\r\n expressions = [],\r\n parseFns = [],\r\n textLength = text.length,\r\n exp,\r\n concat = [],\r\n expressionPositions = [];\r\n\r\n while (index < textLength) {\r\n if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&\r\n ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {\r\n if (index !== startIndex) {\r\n concat.push(unescapeText(text.substring(index, startIndex)));\r\n }\r\n exp = text.substring(startIndex + startSymbolLength, endIndex);\r\n expressions.push(exp);\r\n parseFns.push($parse(exp, parseStringifyInterceptor));\r\n index = endIndex + endSymbolLength;\r\n expressionPositions.push(concat.length);\r\n concat.push('');\r\n } else {\r\n // we did not find an interpolation, so we have to add the remainder to the separators array\r\n if (index !== textLength) {\r\n concat.push(unescapeText(text.substring(index)));\r\n }\r\n break;\r\n }\r\n }\r\n\r\n // Concatenating expressions makes it hard to reason about whether some combination of\r\n // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a\r\n // single expression be used for iframe[src], object[src], etc., we ensure that the value\r\n // that's used is assigned or constructed by some JS code somewhere that is more testable or\r\n // make it obvious that you bound the value to some user controlled value. This helps reduce\r\n // the load when auditing for XSS issues.\r\n if (trustedContext && concat.length > 1) {\r\n throw $interpolateMinErr('noconcat',\r\n \"Error while interpolating: {0}\\nStrict Contextual Escaping disallows \" +\r\n \"interpolations that concatenate multiple expressions when a trusted value is \" +\r\n \"required. See http://docs.angularjs.org/api/ng.$sce\", text);\r\n }\r\n\r\n if (!mustHaveExpression || expressions.length) {\r\n var compute = function(values) {\r\n for (var i = 0, ii = expressions.length; i < ii; i++) {\r\n if (allOrNothing && isUndefined(values[i])) return;\r\n concat[expressionPositions[i]] = values[i];\r\n }\r\n return concat.join('');\r\n };\r\n\r\n var getValue = function(value) {\r\n return trustedContext ?\r\n $sce.getTrusted(trustedContext, value) :\r\n $sce.valueOf(value);\r\n };\r\n\r\n var stringify = function(value) {\r\n if (value == null) { // null || undefined\r\n return '';\r\n }\r\n switch (typeof value) {\r\n case 'string':\r\n break;\r\n case 'number':\r\n value = '' + value;\r\n break;\r\n default:\r\n value = toJson(value);\r\n }\r\n\r\n return value;\r\n };\r\n\r\n return extend(function interpolationFn(context) {\r\n var i = 0;\r\n var ii = expressions.length;\r\n var values = new Array(ii);\r\n\r\n try {\r\n for (; i < ii; i++) {\r\n values[i] = parseFns[i](context);\r\n }\r\n\r\n return compute(values);\r\n } catch (err) {\r\n var newErr = $interpolateMinErr('interr', \"Can't interpolate: {0}\\n{1}\", text,\r\n err.toString());\r\n $exceptionHandler(newErr);\r\n }\r\n\r\n }, {\r\n // all of these properties are undocumented for now\r\n exp: text, //just for compatibility with regular watchers created via $watch\r\n expressions: expressions,\r\n $$watchDelegate: function(scope, listener, objectEquality) {\r\n var lastValue;\r\n return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {\r\n var currValue = compute(values);\r\n if (isFunction(listener)) {\r\n listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);\r\n }\r\n lastValue = currValue;\r\n }, objectEquality);\r\n }\r\n });\r\n }\r\n\r\n function unescapeText(text) {\r\n return text.replace(escapedStartRegexp, startSymbol).\r\n replace(escapedEndRegexp, endSymbol);\r\n }\r\n\r\n function parseStringifyInterceptor(value) {\r\n try {\r\n value = getValue(value);\r\n return allOrNothing && !isDefined(value) ? value : stringify(value);\r\n } catch (err) {\r\n var newErr = $interpolateMinErr('interr', \"Can't interpolate: {0}\\n{1}\", text,\r\n err.toString());\r\n $exceptionHandler(newErr);\r\n }\r\n }\r\n }\r\n\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $interpolate#startSymbol\r\n * @description\r\n * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.\r\n *\r\n * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change\r\n * the symbol.\r\n *\r\n * @returns {string} start symbol.\r\n */\r\n $interpolate.startSymbol = function() {\r\n return startSymbol;\r\n };\r\n\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $interpolate#endSymbol\r\n * @description\r\n * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.\r\n *\r\n * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change\r\n * the symbol.\r\n *\r\n * @returns {string} end symbol.\r\n */\r\n $interpolate.endSymbol = function() {\r\n return endSymbol;\r\n };\r\n\r\n return $interpolate;\r\n }];\r\n}\r\n\r\nfunction $IntervalProvider() {\r\n this.$get = ['$rootScope', '$window', '$q', '$$q',\r\n function($rootScope, $window, $q, $$q) {\r\n var intervals = {};\r\n\r\n\r\n /**\r\n * @ngdoc service\r\n * @name $interval\r\n *\r\n * @description\r\n * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`\r\n * milliseconds.\r\n *\r\n * The return value of registering an interval function is a promise. This promise will be\r\n * notified upon each tick of the interval, and will be resolved after `count` iterations, or\r\n * run indefinitely if `count` is not defined. The value of the notification will be the\r\n * number of iterations that have run.\r\n * To cancel an interval, call `$interval.cancel(promise)`.\r\n *\r\n * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to\r\n * move forward by `millis` milliseconds and trigger any functions scheduled to run in that\r\n * time.\r\n *\r\n *
    \r\n * **Note**: Intervals created by this service must be explicitly destroyed when you are finished\r\n * with them. In particular they are not automatically destroyed when a controller's scope or a\r\n * directive's element are destroyed.\r\n * You should take this into consideration and make sure to always cancel the interval at the\r\n * appropriate moment. See the example below for more details on how and when to do this.\r\n *
    \r\n *\r\n * @param {function()} fn A function that should be called repeatedly.\r\n * @param {number} delay Number of milliseconds between each function call.\r\n * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat\r\n * indefinitely.\r\n * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise\r\n * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.\r\n * @returns {promise} A promise which will be notified on each iteration.\r\n *\r\n * @example\r\n * \r\n * \r\n * \r\n *\r\n *
    \r\n *
    \r\n * Date format:
    \r\n * Current time is: \r\n *
    \r\n * Blood 1 : {{blood_1}}\r\n * Blood 2 : {{blood_2}}\r\n * \r\n * \r\n * \r\n *
    \r\n *
    \r\n *\r\n *
    \r\n *
    \r\n */\r\n function interval(fn, delay, count, invokeApply) {\r\n var setInterval = $window.setInterval,\r\n clearInterval = $window.clearInterval,\r\n iteration = 0,\r\n skipApply = (isDefined(invokeApply) && !invokeApply),\r\n deferred = (skipApply ? $$q : $q).defer(),\r\n promise = deferred.promise;\r\n\r\n count = isDefined(count) ? count : 0;\r\n\r\n promise.then(null, null, fn);\r\n\r\n promise.$$intervalId = setInterval(function tick() {\r\n deferred.notify(iteration++);\r\n\r\n if (count > 0 && iteration >= count) {\r\n deferred.resolve(iteration);\r\n clearInterval(promise.$$intervalId);\r\n delete intervals[promise.$$intervalId];\r\n }\r\n\r\n if (!skipApply) $rootScope.$apply();\r\n\r\n }, delay);\r\n\r\n intervals[promise.$$intervalId] = deferred;\r\n\r\n return promise;\r\n }\r\n\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $interval#cancel\r\n *\r\n * @description\r\n * Cancels a task associated with the `promise`.\r\n *\r\n * @param {promise} promise returned by the `$interval` function.\r\n * @returns {boolean} Returns `true` if the task was successfully canceled.\r\n */\r\n interval.cancel = function(promise) {\r\n if (promise && promise.$$intervalId in intervals) {\r\n intervals[promise.$$intervalId].reject('canceled');\r\n $window.clearInterval(promise.$$intervalId);\r\n delete intervals[promise.$$intervalId];\r\n return true;\r\n }\r\n return false;\r\n };\r\n\r\n return interval;\r\n }];\r\n}\r\n\r\n/**\r\n * @ngdoc service\r\n * @name $locale\r\n *\r\n * @description\r\n * $locale service provides localization rules for various Angular components. As of right now the\r\n * only public api is:\r\n *\r\n * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)\r\n */\r\nfunction $LocaleProvider() {\r\n this.$get = function() {\r\n return {\r\n id: 'en-us',\r\n\r\n NUMBER_FORMATS: {\r\n DECIMAL_SEP: '.',\r\n GROUP_SEP: ',',\r\n PATTERNS: [\r\n { // Decimal Pattern\r\n minInt: 1,\r\n minFrac: 0,\r\n maxFrac: 3,\r\n posPre: '',\r\n posSuf: '',\r\n negPre: '-',\r\n negSuf: '',\r\n gSize: 3,\r\n lgSize: 3\r\n },{ //Currency Pattern\r\n minInt: 1,\r\n minFrac: 2,\r\n maxFrac: 2,\r\n posPre: '\\u00A4',\r\n posSuf: '',\r\n negPre: '(\\u00A4',\r\n negSuf: ')',\r\n gSize: 3,\r\n lgSize: 3\r\n }\r\n ],\r\n CURRENCY_SYM: '$'\r\n },\r\n\r\n DATETIME_FORMATS: {\r\n MONTH:\r\n 'January,February,March,April,May,June,July,August,September,October,November,December'\r\n .split(','),\r\n SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),\r\n DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),\r\n SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),\r\n AMPMS: ['AM','PM'],\r\n medium: 'MMM d, y h:mm:ss a',\r\n 'short': 'M/d/yy h:mm a',\r\n fullDate: 'EEEE, MMMM d, y',\r\n longDate: 'MMMM d, y',\r\n mediumDate: 'MMM d, y',\r\n shortDate: 'M/d/yy',\r\n mediumTime: 'h:mm:ss a',\r\n shortTime: 'h:mm a',\r\n ERANAMES: [\r\n \"Before Christ\",\r\n \"Anno Domini\"\r\n ],\r\n ERAS: [\r\n \"BC\",\r\n \"AD\"\r\n ]\r\n },\r\n\r\n pluralCat: function(num) {\r\n if (num === 1) {\r\n return 'one';\r\n }\r\n return 'other';\r\n }\r\n };\r\n };\r\n}\r\n\r\nvar PATH_MATCH = /^([^\\?#]*)(\\?([^#]*))?(#(.*))?$/,\r\n DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};\r\nvar $locationMinErr = minErr('$location');\r\n\r\n\r\n/**\r\n * Encode path using encodeUriSegment, ignoring forward slashes\r\n *\r\n * @param {string} path Path to encode\r\n * @returns {string}\r\n */\r\nfunction encodePath(path) {\r\n var segments = path.split('/'),\r\n i = segments.length;\r\n\r\n while (i--) {\r\n segments[i] = encodeUriSegment(segments[i]);\r\n }\r\n\r\n return segments.join('/');\r\n}\r\n\r\nfunction parseAbsoluteUrl(absoluteUrl, locationObj) {\r\n var parsedUrl = urlResolve(absoluteUrl);\r\n\r\n locationObj.$$protocol = parsedUrl.protocol;\r\n locationObj.$$host = parsedUrl.hostname;\r\n locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;\r\n}\r\n\r\n\r\nfunction parseAppUrl(relativeUrl, locationObj) {\r\n var prefixed = (relativeUrl.charAt(0) !== '/');\r\n if (prefixed) {\r\n relativeUrl = '/' + relativeUrl;\r\n }\r\n var match = urlResolve(relativeUrl);\r\n locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?\r\n match.pathname.substring(1) : match.pathname);\r\n locationObj.$$search = parseKeyValue(match.search);\r\n locationObj.$$hash = decodeURIComponent(match.hash);\r\n\r\n // make sure path starts with '/';\r\n if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {\r\n locationObj.$$path = '/' + locationObj.$$path;\r\n }\r\n}\r\n\r\n\r\n/**\r\n *\r\n * @param {string} begin\r\n * @param {string} whole\r\n * @returns {string} returns text from whole after begin or undefined if it does not begin with\r\n * expected string.\r\n */\r\nfunction beginsWith(begin, whole) {\r\n if (whole.indexOf(begin) === 0) {\r\n return whole.substr(begin.length);\r\n }\r\n}\r\n\r\n\r\nfunction stripHash(url) {\r\n var index = url.indexOf('#');\r\n return index == -1 ? url : url.substr(0, index);\r\n}\r\n\r\nfunction trimEmptyHash(url) {\r\n return url.replace(/(#.+)|#$/, '$1');\r\n}\r\n\r\n\r\nfunction stripFile(url) {\r\n return url.substr(0, stripHash(url).lastIndexOf('/') + 1);\r\n}\r\n\r\n/* return the server only (scheme://host:port) */\r\nfunction serverBase(url) {\r\n return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));\r\n}\r\n\r\n\r\n/**\r\n * LocationHtml5Url represents an url\r\n * This object is exposed as $location service when HTML5 mode is enabled and supported\r\n *\r\n * @constructor\r\n * @param {string} appBase application base URL\r\n * @param {string} basePrefix url path prefix\r\n */\r\nfunction LocationHtml5Url(appBase, basePrefix) {\r\n this.$$html5 = true;\r\n basePrefix = basePrefix || '';\r\n var appBaseNoFile = stripFile(appBase);\r\n parseAbsoluteUrl(appBase, this);\r\n\r\n\r\n /**\r\n * Parse given html5 (regular) url string into properties\r\n * @param {string} url HTML5 url\r\n * @private\r\n */\r\n this.$$parse = function(url) {\r\n var pathUrl = beginsWith(appBaseNoFile, url);\r\n if (!isString(pathUrl)) {\r\n throw $locationMinErr('ipthprfx', 'Invalid url \"{0}\", missing path prefix \"{1}\".', url,\r\n appBaseNoFile);\r\n }\r\n\r\n parseAppUrl(pathUrl, this);\r\n\r\n if (!this.$$path) {\r\n this.$$path = '/';\r\n }\r\n\r\n this.$$compose();\r\n };\r\n\r\n /**\r\n * Compose url and update `absUrl` property\r\n * @private\r\n */\r\n this.$$compose = function() {\r\n var search = toKeyValue(this.$$search),\r\n hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';\r\n\r\n this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;\r\n this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'\r\n };\r\n\r\n this.$$parseLinkUrl = function(url, relHref) {\r\n if (relHref && relHref[0] === '#') {\r\n // special case for links to hash fragments:\r\n // keep the old url and only replace the hash fragment\r\n this.hash(relHref.slice(1));\r\n return true;\r\n }\r\n var appUrl, prevAppUrl;\r\n var rewrittenUrl;\r\n\r\n if ((appUrl = beginsWith(appBase, url)) !== undefined) {\r\n prevAppUrl = appUrl;\r\n if ((appUrl = beginsWith(basePrefix, appUrl)) !== undefined) {\r\n rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);\r\n } else {\r\n rewrittenUrl = appBase + prevAppUrl;\r\n }\r\n } else if ((appUrl = beginsWith(appBaseNoFile, url)) !== undefined) {\r\n rewrittenUrl = appBaseNoFile + appUrl;\r\n } else if (appBaseNoFile == url + '/') {\r\n rewrittenUrl = appBaseNoFile;\r\n }\r\n if (rewrittenUrl) {\r\n this.$$parse(rewrittenUrl);\r\n }\r\n return !!rewrittenUrl;\r\n };\r\n}\r\n\r\n\r\n/**\r\n * LocationHashbangUrl represents url\r\n * This object is exposed as $location service when developer doesn't opt into html5 mode.\r\n * It also serves as the base class for html5 mode fallback on legacy browsers.\r\n *\r\n * @constructor\r\n * @param {string} appBase application base URL\r\n * @param {string} hashPrefix hashbang prefix\r\n */\r\nfunction LocationHashbangUrl(appBase, hashPrefix) {\r\n var appBaseNoFile = stripFile(appBase);\r\n\r\n parseAbsoluteUrl(appBase, this);\r\n\r\n\r\n /**\r\n * Parse given hashbang url into properties\r\n * @param {string} url Hashbang url\r\n * @private\r\n */\r\n this.$$parse = function(url) {\r\n var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);\r\n var withoutHashUrl;\r\n\r\n if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {\r\n\r\n // The rest of the url starts with a hash so we have\r\n // got either a hashbang path or a plain hash fragment\r\n withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);\r\n if (isUndefined(withoutHashUrl)) {\r\n // There was no hashbang prefix so we just have a hash fragment\r\n withoutHashUrl = withoutBaseUrl;\r\n }\r\n\r\n } else {\r\n // There was no hashbang path nor hash fragment:\r\n // If we are in HTML5 mode we use what is left as the path;\r\n // Otherwise we ignore what is left\r\n if (this.$$html5) {\r\n withoutHashUrl = withoutBaseUrl;\r\n } else {\r\n withoutHashUrl = '';\r\n if (isUndefined(withoutBaseUrl)) {\r\n appBase = url;\r\n this.replace();\r\n }\r\n }\r\n }\r\n\r\n parseAppUrl(withoutHashUrl, this);\r\n\r\n this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);\r\n\r\n this.$$compose();\r\n\r\n /*\r\n * In Windows, on an anchor node on documents loaded from\r\n * the filesystem, the browser will return a pathname\r\n * prefixed with the drive name ('/C:/path') when a\r\n * pathname without a drive is set:\r\n * * a.setAttribute('href', '/foo')\r\n * * a.pathname === '/C:/foo' //true\r\n *\r\n * Inside of Angular, we're always using pathnames that\r\n * do not include drive names for routing.\r\n */\r\n function removeWindowsDriveName(path, url, base) {\r\n /*\r\n Matches paths for file protocol on windows,\r\n such as /C:/foo/bar, and captures only /foo/bar.\r\n */\r\n var windowsFilePathExp = /^\\/[A-Z]:(\\/.*)/;\r\n\r\n var firstPathSegmentMatch;\r\n\r\n //Get the relative path from the input URL.\r\n if (url.indexOf(base) === 0) {\r\n url = url.replace(base, '');\r\n }\r\n\r\n // The input URL intentionally contains a first path segment that ends with a colon.\r\n if (windowsFilePathExp.exec(url)) {\r\n return path;\r\n }\r\n\r\n firstPathSegmentMatch = windowsFilePathExp.exec(path);\r\n return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;\r\n }\r\n };\r\n\r\n /**\r\n * Compose hashbang url and update `absUrl` property\r\n * @private\r\n */\r\n this.$$compose = function() {\r\n var search = toKeyValue(this.$$search),\r\n hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';\r\n\r\n this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;\r\n this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');\r\n };\r\n\r\n this.$$parseLinkUrl = function(url, relHref) {\r\n if (stripHash(appBase) == stripHash(url)) {\r\n this.$$parse(url);\r\n return true;\r\n }\r\n return false;\r\n };\r\n}\r\n\r\n\r\n/**\r\n * LocationHashbangUrl represents url\r\n * This object is exposed as $location service when html5 history api is enabled but the browser\r\n * does not support it.\r\n *\r\n * @constructor\r\n * @param {string} appBase application base URL\r\n * @param {string} hashPrefix hashbang prefix\r\n */\r\nfunction LocationHashbangInHtml5Url(appBase, hashPrefix) {\r\n this.$$html5 = true;\r\n LocationHashbangUrl.apply(this, arguments);\r\n\r\n var appBaseNoFile = stripFile(appBase);\r\n\r\n this.$$parseLinkUrl = function(url, relHref) {\r\n if (relHref && relHref[0] === '#') {\r\n // special case for links to hash fragments:\r\n // keep the old url and only replace the hash fragment\r\n this.hash(relHref.slice(1));\r\n return true;\r\n }\r\n\r\n var rewrittenUrl;\r\n var appUrl;\r\n\r\n if (appBase == stripHash(url)) {\r\n rewrittenUrl = url;\r\n } else if ((appUrl = beginsWith(appBaseNoFile, url))) {\r\n rewrittenUrl = appBase + hashPrefix + appUrl;\r\n } else if (appBaseNoFile === url + '/') {\r\n rewrittenUrl = appBaseNoFile;\r\n }\r\n if (rewrittenUrl) {\r\n this.$$parse(rewrittenUrl);\r\n }\r\n return !!rewrittenUrl;\r\n };\r\n\r\n this.$$compose = function() {\r\n var search = toKeyValue(this.$$search),\r\n hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';\r\n\r\n this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;\r\n // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'\r\n this.$$absUrl = appBase + hashPrefix + this.$$url;\r\n };\r\n\r\n}\r\n\r\n\r\nvar locationPrototype = {\r\n\r\n /**\r\n * Are we in html5 mode?\r\n * @private\r\n */\r\n $$html5: false,\r\n\r\n /**\r\n * Has any change been replacing?\r\n * @private\r\n */\r\n $$replace: false,\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $location#absUrl\r\n *\r\n * @description\r\n * This method is getter only.\r\n *\r\n * Return full url representation with all segments encoded according to rules specified in\r\n * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).\r\n *\r\n *\r\n * ```js\r\n * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\r\n * var absUrl = $location.absUrl();\r\n * // => \"http://example.com/#/some/path?foo=bar&baz=xoxo\"\r\n * ```\r\n *\r\n * @return {string} full url\r\n */\r\n absUrl: locationGetter('$$absUrl'),\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $location#url\r\n *\r\n * @description\r\n * This method is getter / setter.\r\n *\r\n * Return url (e.g. `/path?a=b#hash`) when called without any parameter.\r\n *\r\n * Change path, search and hash, when called with parameter and return `$location`.\r\n *\r\n *\r\n * ```js\r\n * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\r\n * var url = $location.url();\r\n * // => \"/some/path?foo=bar&baz=xoxo\"\r\n * ```\r\n *\r\n * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)\r\n * @return {string} url\r\n */\r\n url: function(url) {\r\n if (isUndefined(url))\r\n return this.$$url;\r\n\r\n var match = PATH_MATCH.exec(url);\r\n if (match[1] || url === '') this.path(decodeURIComponent(match[1]));\r\n if (match[2] || match[1] || url === '') this.search(match[3] || '');\r\n this.hash(match[5] || '');\r\n\r\n return this;\r\n },\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $location#protocol\r\n *\r\n * @description\r\n * This method is getter only.\r\n *\r\n * Return protocol of current url.\r\n *\r\n *\r\n * ```js\r\n * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\r\n * var protocol = $location.protocol();\r\n * // => \"http\"\r\n * ```\r\n *\r\n * @return {string} protocol of current url\r\n */\r\n protocol: locationGetter('$$protocol'),\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $location#host\r\n *\r\n * @description\r\n * This method is getter only.\r\n *\r\n * Return host of current url.\r\n *\r\n * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.\r\n *\r\n *\r\n * ```js\r\n * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\r\n * var host = $location.host();\r\n * // => \"example.com\"\r\n *\r\n * // given url http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo\r\n * host = $location.host();\r\n * // => \"example.com\"\r\n * host = location.host;\r\n * // => \"example.com:8080\"\r\n * ```\r\n *\r\n * @return {string} host of current url.\r\n */\r\n host: locationGetter('$$host'),\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $location#port\r\n *\r\n * @description\r\n * This method is getter only.\r\n *\r\n * Return port of current url.\r\n *\r\n *\r\n * ```js\r\n * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\r\n * var port = $location.port();\r\n * // => 80\r\n * ```\r\n *\r\n * @return {Number} port\r\n */\r\n port: locationGetter('$$port'),\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $location#path\r\n *\r\n * @description\r\n * This method is getter / setter.\r\n *\r\n * Return path of current url when called without any parameter.\r\n *\r\n * Change path when called with parameter and return `$location`.\r\n *\r\n * Note: Path should always begin with forward slash (/), this method will add the forward slash\r\n * if it is missing.\r\n *\r\n *\r\n * ```js\r\n * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\r\n * var path = $location.path();\r\n * // => \"/some/path\"\r\n * ```\r\n *\r\n * @param {(string|number)=} path New path\r\n * @return {string} path\r\n */\r\n path: locationGetterSetter('$$path', function(path) {\r\n path = path !== null ? path.toString() : '';\r\n return path.charAt(0) == '/' ? path : '/' + path;\r\n }),\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $location#search\r\n *\r\n * @description\r\n * This method is getter / setter.\r\n *\r\n * Return search part (as object) of current url when called without any parameter.\r\n *\r\n * Change search part when called with parameter and return `$location`.\r\n *\r\n *\r\n * ```js\r\n * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\r\n * var searchObject = $location.search();\r\n * // => {foo: 'bar', baz: 'xoxo'}\r\n *\r\n * // set foo to 'yipee'\r\n * $location.search('foo', 'yipee');\r\n * // $location.search() => {foo: 'yipee', baz: 'xoxo'}\r\n * ```\r\n *\r\n * @param {string|Object.|Object.>} search New search params - string or\r\n * hash object.\r\n *\r\n * When called with a single argument the method acts as a setter, setting the `search` component\r\n * of `$location` to the specified value.\r\n *\r\n * If the argument is a hash object containing an array of values, these values will be encoded\r\n * as duplicate search parameters in the url.\r\n *\r\n * @param {(string|Number|Array|boolean)=} paramValue If `search` is a string or number, then `paramValue`\r\n * will override only a single search property.\r\n *\r\n * If `paramValue` is an array, it will override the property of the `search` component of\r\n * `$location` specified via the first argument.\r\n *\r\n * If `paramValue` is `null`, the property specified via the first argument will be deleted.\r\n *\r\n * If `paramValue` is `true`, the property specified via the first argument will be added with no\r\n * value nor trailing equal sign.\r\n *\r\n * @return {Object} If called with no arguments returns the parsed `search` object. If called with\r\n * one or more arguments returns `$location` object itself.\r\n */\r\n search: function(search, paramValue) {\r\n switch (arguments.length) {\r\n case 0:\r\n return this.$$search;\r\n case 1:\r\n if (isString(search) || isNumber(search)) {\r\n search = search.toString();\r\n this.$$search = parseKeyValue(search);\r\n } else if (isObject(search)) {\r\n search = copy(search, {});\r\n // remove object undefined or null properties\r\n forEach(search, function(value, key) {\r\n if (value == null) delete search[key];\r\n });\r\n\r\n this.$$search = search;\r\n } else {\r\n throw $locationMinErr('isrcharg',\r\n 'The first argument of the `$location#search()` call must be a string or an object.');\r\n }\r\n break;\r\n default:\r\n if (isUndefined(paramValue) || paramValue === null) {\r\n delete this.$$search[search];\r\n } else {\r\n this.$$search[search] = paramValue;\r\n }\r\n }\r\n\r\n this.$$compose();\r\n return this;\r\n },\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $location#hash\r\n *\r\n * @description\r\n * This method is getter / setter.\r\n *\r\n * Return hash fragment when called without any parameter.\r\n *\r\n * Change hash fragment when called with parameter and return `$location`.\r\n *\r\n *\r\n * ```js\r\n * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue\r\n * var hash = $location.hash();\r\n * // => \"hashValue\"\r\n * ```\r\n *\r\n * @param {(string|number)=} hash New hash fragment\r\n * @return {string} hash\r\n */\r\n hash: locationGetterSetter('$$hash', function(hash) {\r\n return hash !== null ? hash.toString() : '';\r\n }),\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $location#replace\r\n *\r\n * @description\r\n * If called, all changes to $location during current `$digest` will be replacing current history\r\n * record, instead of adding new one.\r\n */\r\n replace: function() {\r\n this.$$replace = true;\r\n return this;\r\n }\r\n};\r\n\r\nforEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {\r\n Location.prototype = Object.create(locationPrototype);\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $location#state\r\n *\r\n * @description\r\n * This method is getter / setter.\r\n *\r\n * Return the history state object when called without any parameter.\r\n *\r\n * Change the history state object when called with one parameter and return `$location`.\r\n * The state object is later passed to `pushState` or `replaceState`.\r\n *\r\n * NOTE: This method is supported only in HTML5 mode and only in browsers supporting\r\n * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support\r\n * older browsers (like IE9 or Android < 4.0), don't use this method.\r\n *\r\n * @param {object=} state State object for pushState or replaceState\r\n * @return {object} state\r\n */\r\n Location.prototype.state = function(state) {\r\n if (!arguments.length)\r\n return this.$$state;\r\n\r\n if (Location !== LocationHtml5Url || !this.$$html5) {\r\n throw $locationMinErr('nostate', 'History API state support is available only ' +\r\n 'in HTML5 mode and only in browsers supporting HTML5 History API');\r\n }\r\n // The user might modify `stateObject` after invoking `$location.state(stateObject)`\r\n // but we're changing the $$state reference to $browser.state() during the $digest\r\n // so the modification window is narrow.\r\n this.$$state = isUndefined(state) ? null : state;\r\n\r\n return this;\r\n };\r\n});\r\n\r\n\r\nfunction locationGetter(property) {\r\n return function() {\r\n return this[property];\r\n };\r\n}\r\n\r\n\r\nfunction locationGetterSetter(property, preprocess) {\r\n return function(value) {\r\n if (isUndefined(value))\r\n return this[property];\r\n\r\n this[property] = preprocess(value);\r\n this.$$compose();\r\n\r\n return this;\r\n };\r\n}\r\n\r\n\r\n/**\r\n * @ngdoc service\r\n * @name $location\r\n *\r\n * @requires $rootElement\r\n *\r\n * @description\r\n * The $location service parses the URL in the browser address bar (based on the\r\n * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL\r\n * available to your application. Changes to the URL in the address bar are reflected into\r\n * $location service and changes to $location are reflected into the browser address bar.\r\n *\r\n * **The $location service:**\r\n *\r\n * - Exposes the current URL in the browser address bar, so you can\r\n * - Watch and observe the URL.\r\n * - Change the URL.\r\n * - Synchronizes the URL with the browser when the user\r\n * - Changes the address bar.\r\n * - Clicks the back or forward button (or clicks a History link).\r\n * - Clicks on a link.\r\n * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).\r\n *\r\n * For more information see {@link guide/$location Developer Guide: Using $location}\r\n */\r\n\r\n/**\r\n * @ngdoc provider\r\n * @name $locationProvider\r\n * @description\r\n * Use the `$locationProvider` to configure how the application deep linking paths are stored.\r\n */\r\nfunction $LocationProvider() {\r\n var hashPrefix = '',\r\n html5Mode = {\r\n enabled: false,\r\n requireBase: true,\r\n rewriteLinks: true\r\n };\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $locationProvider#hashPrefix\r\n * @description\r\n * @param {string=} prefix Prefix for hash part (containing path and search)\r\n * @returns {*} current value if used as getter or itself (chaining) if used as setter\r\n */\r\n this.hashPrefix = function(prefix) {\r\n if (isDefined(prefix)) {\r\n hashPrefix = prefix;\r\n return this;\r\n } else {\r\n return hashPrefix;\r\n }\r\n };\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $locationProvider#html5Mode\r\n * @description\r\n * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.\r\n * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported\r\n * properties:\r\n * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to\r\n * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not\r\n * support `pushState`.\r\n * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies\r\n * whether or not a tag is required to be present. If `enabled` and `requireBase` are\r\n * true, and a base tag is not present, an error will be thrown when `$location` is injected.\r\n * See the {@link guide/$location $location guide for more information}\r\n * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,\r\n * enables/disables url rewriting for relative links.\r\n *\r\n * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter\r\n */\r\n this.html5Mode = function(mode) {\r\n if (isBoolean(mode)) {\r\n html5Mode.enabled = mode;\r\n return this;\r\n } else if (isObject(mode)) {\r\n\r\n if (isBoolean(mode.enabled)) {\r\n html5Mode.enabled = mode.enabled;\r\n }\r\n\r\n if (isBoolean(mode.requireBase)) {\r\n html5Mode.requireBase = mode.requireBase;\r\n }\r\n\r\n if (isBoolean(mode.rewriteLinks)) {\r\n html5Mode.rewriteLinks = mode.rewriteLinks;\r\n }\r\n\r\n return this;\r\n } else {\r\n return html5Mode;\r\n }\r\n };\r\n\r\n /**\r\n * @ngdoc event\r\n * @name $location#$locationChangeStart\r\n * @eventType broadcast on root scope\r\n * @description\r\n * Broadcasted before a URL will change.\r\n *\r\n * This change can be prevented by calling\r\n * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more\r\n * details about event object. Upon successful change\r\n * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.\r\n *\r\n * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when\r\n * the browser supports the HTML5 History API.\r\n *\r\n * @param {Object} angularEvent Synthetic event object.\r\n * @param {string} newUrl New URL\r\n * @param {string=} oldUrl URL that was before it was changed.\r\n * @param {string=} newState New history state object\r\n * @param {string=} oldState History state object that was before it was changed.\r\n */\r\n\r\n /**\r\n * @ngdoc event\r\n * @name $location#$locationChangeSuccess\r\n * @eventType broadcast on root scope\r\n * @description\r\n * Broadcasted after a URL was changed.\r\n *\r\n * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when\r\n * the browser supports the HTML5 History API.\r\n *\r\n * @param {Object} angularEvent Synthetic event object.\r\n * @param {string} newUrl New URL\r\n * @param {string=} oldUrl URL that was before it was changed.\r\n * @param {string=} newState New history state object\r\n * @param {string=} oldState History state object that was before it was changed.\r\n */\r\n\r\n this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',\r\n function($rootScope, $browser, $sniffer, $rootElement, $window) {\r\n var $location,\r\n LocationMode,\r\n baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''\r\n initialUrl = $browser.url(),\r\n appBase;\r\n\r\n if (html5Mode.enabled) {\r\n if (!baseHref && html5Mode.requireBase) {\r\n throw $locationMinErr('nobase',\r\n \"$location in HTML5 mode requires a tag to be present!\");\r\n }\r\n appBase = serverBase(initialUrl) + (baseHref || '/');\r\n LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;\r\n } else {\r\n appBase = stripHash(initialUrl);\r\n LocationMode = LocationHashbangUrl;\r\n }\r\n $location = new LocationMode(appBase, '#' + hashPrefix);\r\n $location.$$parseLinkUrl(initialUrl, initialUrl);\r\n\r\n $location.$$state = $browser.state();\r\n\r\n var IGNORE_URI_REGEXP = /^\\s*(javascript|mailto):/i;\r\n\r\n function setBrowserUrlWithFallback(url, replace, state) {\r\n var oldUrl = $location.url();\r\n var oldState = $location.$$state;\r\n try {\r\n $browser.url(url, replace, state);\r\n\r\n // Make sure $location.state() returns referentially identical (not just deeply equal)\r\n // state object; this makes possible quick checking if the state changed in the digest\r\n // loop. Checking deep equality would be too expensive.\r\n $location.$$state = $browser.state();\r\n } catch (e) {\r\n // Restore old values if pushState fails\r\n $location.url(oldUrl);\r\n $location.$$state = oldState;\r\n\r\n throw e;\r\n }\r\n }\r\n\r\n $rootElement.on('click', function(event) {\r\n // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)\r\n // currently we open nice url link and redirect then\r\n\r\n if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;\r\n\r\n var elm = jqLite(event.target);\r\n\r\n // traverse the DOM up to find first A tag\r\n while (nodeName_(elm[0]) !== 'a') {\r\n // ignore rewriting if no A tag (reached root element, or no parent - removed from document)\r\n if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;\r\n }\r\n\r\n var absHref = elm.prop('href');\r\n // get the actual href attribute - see\r\n // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx\r\n var relHref = elm.attr('href') || elm.attr('xlink:href');\r\n\r\n if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {\r\n // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during\r\n // an animation.\r\n absHref = urlResolve(absHref.animVal).href;\r\n }\r\n\r\n // Ignore when url is started with javascript: or mailto:\r\n if (IGNORE_URI_REGEXP.test(absHref)) return;\r\n\r\n if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {\r\n if ($location.$$parseLinkUrl(absHref, relHref)) {\r\n // We do a preventDefault for all urls that are part of the angular application,\r\n // in html5mode and also without, so that we are able to abort navigation without\r\n // getting double entries in the location history.\r\n event.preventDefault();\r\n // update location manually\r\n if ($location.absUrl() != $browser.url()) {\r\n $rootScope.$apply();\r\n // hack to work around FF6 bug 684208 when scenario runner clicks on links\r\n $window.angular['ff-684208-preventDefault'] = true;\r\n }\r\n }\r\n }\r\n });\r\n\r\n\r\n // rewrite hashbang url <> html5 url\r\n if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {\r\n $browser.url($location.absUrl(), true);\r\n }\r\n\r\n var initializing = true;\r\n\r\n // update $location when $browser url changes\r\n $browser.onUrlChange(function(newUrl, newState) {\r\n $rootScope.$evalAsync(function() {\r\n var oldUrl = $location.absUrl();\r\n var oldState = $location.$$state;\r\n var defaultPrevented;\r\n\r\n $location.$$parse(newUrl);\r\n $location.$$state = newState;\r\n\r\n defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,\r\n newState, oldState).defaultPrevented;\r\n\r\n // if the location was changed by a `$locationChangeStart` handler then stop\r\n // processing this location change\r\n if ($location.absUrl() !== newUrl) return;\r\n\r\n if (defaultPrevented) {\r\n $location.$$parse(oldUrl);\r\n $location.$$state = oldState;\r\n setBrowserUrlWithFallback(oldUrl, false, oldState);\r\n } else {\r\n initializing = false;\r\n afterLocationChange(oldUrl, oldState);\r\n }\r\n });\r\n if (!$rootScope.$$phase) $rootScope.$digest();\r\n });\r\n\r\n // update browser\r\n $rootScope.$watch(function $locationWatch() {\r\n var oldUrl = trimEmptyHash($browser.url());\r\n var newUrl = trimEmptyHash($location.absUrl());\r\n var oldState = $browser.state();\r\n var currentReplace = $location.$$replace;\r\n var urlOrStateChanged = oldUrl !== newUrl ||\r\n ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);\r\n\r\n if (initializing || urlOrStateChanged) {\r\n initializing = false;\r\n\r\n $rootScope.$evalAsync(function() {\r\n var newUrl = $location.absUrl();\r\n var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,\r\n $location.$$state, oldState).defaultPrevented;\r\n\r\n // if the location was changed by a `$locationChangeStart` handler then stop\r\n // processing this location change\r\n if ($location.absUrl() !== newUrl) return;\r\n\r\n if (defaultPrevented) {\r\n $location.$$parse(oldUrl);\r\n $location.$$state = oldState;\r\n } else {\r\n if (urlOrStateChanged) {\r\n setBrowserUrlWithFallback(newUrl, currentReplace,\r\n oldState === $location.$$state ? null : $location.$$state);\r\n }\r\n afterLocationChange(oldUrl, oldState);\r\n }\r\n });\r\n }\r\n\r\n $location.$$replace = false;\r\n\r\n // we don't need to return anything because $evalAsync will make the digest loop dirty when\r\n // there is a change\r\n });\r\n\r\n return $location;\r\n\r\n function afterLocationChange(oldUrl, oldState) {\r\n $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,\r\n $location.$$state, oldState);\r\n }\r\n}];\r\n}\r\n\r\n/**\r\n * @ngdoc service\r\n * @name $log\r\n * @requires $window\r\n *\r\n * @description\r\n * Simple service for logging. Default implementation safely writes the message\r\n * into the browser's console (if present).\r\n *\r\n * The main purpose of this service is to simplify debugging and troubleshooting.\r\n *\r\n * The default is to log `debug` messages. You can use\r\n * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.\r\n *\r\n * @example\r\n \r\n \r\n angular.module('logExample', [])\r\n .controller('LogController', ['$scope', '$log', function($scope, $log) {\r\n $scope.$log = $log;\r\n $scope.message = 'Hello World!';\r\n }]);\r\n \r\n \r\n
    \r\n

    Reload this page with open console, enter text and hit the log button...

    \r\n Message:\r\n \r\n \r\n \r\n \r\n \r\n \r\n
    \r\n
    \r\n
    \r\n */\r\n\r\n/**\r\n * @ngdoc provider\r\n * @name $logProvider\r\n * @description\r\n * Use the `$logProvider` to configure how the application logs messages\r\n */\r\nfunction $LogProvider() {\r\n var debug = true,\r\n self = this;\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $logProvider#debugEnabled\r\n * @description\r\n * @param {boolean=} flag enable or disable debug level messages\r\n * @returns {*} current value if used as getter or itself (chaining) if used as setter\r\n */\r\n this.debugEnabled = function(flag) {\r\n if (isDefined(flag)) {\r\n debug = flag;\r\n return this;\r\n } else {\r\n return debug;\r\n }\r\n };\r\n\r\n this.$get = ['$window', function($window) {\r\n return {\r\n /**\r\n * @ngdoc method\r\n * @name $log#log\r\n *\r\n * @description\r\n * Write a log message\r\n */\r\n log: consoleLog('log'),\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $log#info\r\n *\r\n * @description\r\n * Write an information message\r\n */\r\n info: consoleLog('info'),\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $log#warn\r\n *\r\n * @description\r\n * Write a warning message\r\n */\r\n warn: consoleLog('warn'),\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $log#error\r\n *\r\n * @description\r\n * Write an error message\r\n */\r\n error: consoleLog('error'),\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $log#debug\r\n *\r\n * @description\r\n * Write a debug message\r\n */\r\n debug: (function() {\r\n var fn = consoleLog('debug');\r\n\r\n return function() {\r\n if (debug) {\r\n fn.apply(self, arguments);\r\n }\r\n };\r\n }())\r\n };\r\n\r\n function formatError(arg) {\r\n if (arg instanceof Error) {\r\n if (arg.stack) {\r\n arg = (arg.message && arg.stack.indexOf(arg.message) === -1)\r\n ? 'Error: ' + arg.message + '\\n' + arg.stack\r\n : arg.stack;\r\n } else if (arg.sourceURL) {\r\n arg = arg.message + '\\n' + arg.sourceURL + ':' + arg.line;\r\n }\r\n }\r\n return arg;\r\n }\r\n\r\n function consoleLog(type) {\r\n var console = $window.console || {},\r\n logFn = console[type] || console.log || noop,\r\n hasApply = false;\r\n\r\n // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.\r\n // The reason behind this is that console.log has type \"object\" in IE8...\r\n try {\r\n hasApply = !!logFn.apply;\r\n } catch (e) {}\r\n\r\n if (hasApply) {\r\n return function() {\r\n var args = [];\r\n forEach(arguments, function(arg) {\r\n args.push(formatError(arg));\r\n });\r\n return logFn.apply(console, args);\r\n };\r\n }\r\n\r\n // we are IE which either doesn't have window.console => this is noop and we do nothing,\r\n // or we are IE where console.log doesn't have apply so we log at least first 2 args\r\n return function(arg1, arg2) {\r\n logFn(arg1, arg2 == null ? '' : arg2);\r\n };\r\n }\r\n }];\r\n}\r\n\r\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\r\n * Any commits to this file should be reviewed with security in mind. *\r\n * Changes to this file can potentially create security vulnerabilities. *\r\n * An approval from 2 Core members with history of modifying *\r\n * this file is required. *\r\n * *\r\n * Does the change somehow allow for arbitrary javascript to be executed? *\r\n * Or allows for someone to change the prototype of built-in objects? *\r\n * Or gives undesired access to variables likes document or window? *\r\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\r\n\r\nvar $parseMinErr = minErr('$parse');\r\n\r\n// Sandboxing Angular Expressions\r\n// ------------------------------\r\n// Angular expressions are generally considered safe because these expressions only have direct\r\n// access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by\r\n// obtaining a reference to native JS functions such as the Function constructor.\r\n//\r\n// As an example, consider the following Angular expression:\r\n//\r\n// {}.toString.constructor('alert(\"evil JS code\")')\r\n//\r\n// This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits\r\n// against the expression language, but not to prevent exploits that were enabled by exposing\r\n// sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good\r\n// practice and therefore we are not even trying to protect against interaction with an object\r\n// explicitly exposed in this way.\r\n//\r\n// In general, it is not possible to access a Window object from an angular expression unless a\r\n// window or some DOM object that has a reference to window is published onto a Scope.\r\n// Similarly we prevent invocations of function known to be dangerous, as well as assignments to\r\n// native objects.\r\n//\r\n// See https://docs.angularjs.org/guide/security\r\n\r\n\r\nfunction ensureSafeMemberName(name, fullExpression) {\r\n if (name === \"__defineGetter__\" || name === \"__defineSetter__\"\r\n || name === \"__lookupGetter__\" || name === \"__lookupSetter__\"\r\n || name === \"__proto__\") {\r\n throw $parseMinErr('isecfld',\r\n 'Attempting to access a disallowed field in Angular expressions! '\r\n + 'Expression: {0}', fullExpression);\r\n }\r\n return name;\r\n}\r\n\r\nfunction ensureSafeObject(obj, fullExpression) {\r\n // nifty check if obj is Function that is fast and works across iframes and other contexts\r\n if (obj) {\r\n if (obj.constructor === obj) {\r\n throw $parseMinErr('isecfn',\r\n 'Referencing Function in Angular expressions is disallowed! Expression: {0}',\r\n fullExpression);\r\n } else if (// isWindow(obj)\r\n obj.window === obj) {\r\n throw $parseMinErr('isecwindow',\r\n 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',\r\n fullExpression);\r\n } else if (// isElement(obj)\r\n obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {\r\n throw $parseMinErr('isecdom',\r\n 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',\r\n fullExpression);\r\n } else if (// block Object so that we can't get hold of dangerous Object.* methods\r\n obj === Object) {\r\n throw $parseMinErr('isecobj',\r\n 'Referencing Object in Angular expressions is disallowed! Expression: {0}',\r\n fullExpression);\r\n }\r\n }\r\n return obj;\r\n}\r\n\r\nvar CALL = Function.prototype.call;\r\nvar APPLY = Function.prototype.apply;\r\nvar BIND = Function.prototype.bind;\r\n\r\nfunction ensureSafeFunction(obj, fullExpression) {\r\n if (obj) {\r\n if (obj.constructor === obj) {\r\n throw $parseMinErr('isecfn',\r\n 'Referencing Function in Angular expressions is disallowed! Expression: {0}',\r\n fullExpression);\r\n } else if (obj === CALL || obj === APPLY || obj === BIND) {\r\n throw $parseMinErr('isecff',\r\n 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',\r\n fullExpression);\r\n }\r\n }\r\n}\r\n\r\n//Keyword constants\r\nvar CONSTANTS = createMap();\r\nforEach({\r\n 'null': function() { return null; },\r\n 'true': function() { return true; },\r\n 'false': function() { return false; },\r\n 'undefined': function() {}\r\n}, function(constantGetter, name) {\r\n constantGetter.constant = constantGetter.literal = constantGetter.sharedGetter = true;\r\n CONSTANTS[name] = constantGetter;\r\n});\r\n\r\n//Not quite a constant, but can be lex/parsed the same\r\nCONSTANTS['this'] = function(self) { return self; };\r\nCONSTANTS['this'].sharedGetter = true;\r\n\r\n\r\n//Operators - will be wrapped by binaryFn/unaryFn/assignment/filter\r\nvar OPERATORS = extend(createMap(), {\r\n '+':function(self, locals, a, b) {\r\n a=a(self, locals); b=b(self, locals);\r\n if (isDefined(a)) {\r\n if (isDefined(b)) {\r\n return a + b;\r\n }\r\n return a;\r\n }\r\n return isDefined(b) ? b : undefined;},\r\n '-':function(self, locals, a, b) {\r\n a=a(self, locals); b=b(self, locals);\r\n return (isDefined(a) ? a : 0) - (isDefined(b) ? b : 0);\r\n },\r\n '*':function(self, locals, a, b) {return a(self, locals) * b(self, locals);},\r\n '/':function(self, locals, a, b) {return a(self, locals) / b(self, locals);},\r\n '%':function(self, locals, a, b) {return a(self, locals) % b(self, locals);},\r\n '===':function(self, locals, a, b) {return a(self, locals) === b(self, locals);},\r\n '!==':function(self, locals, a, b) {return a(self, locals) !== b(self, locals);},\r\n '==':function(self, locals, a, b) {return a(self, locals) == b(self, locals);},\r\n '!=':function(self, locals, a, b) {return a(self, locals) != b(self, locals);},\r\n '<':function(self, locals, a, b) {return a(self, locals) < b(self, locals);},\r\n '>':function(self, locals, a, b) {return a(self, locals) > b(self, locals);},\r\n '<=':function(self, locals, a, b) {return a(self, locals) <= b(self, locals);},\r\n '>=':function(self, locals, a, b) {return a(self, locals) >= b(self, locals);},\r\n '&&':function(self, locals, a, b) {return a(self, locals) && b(self, locals);},\r\n '||':function(self, locals, a, b) {return a(self, locals) || b(self, locals);},\r\n '!':function(self, locals, a) {return !a(self, locals);},\r\n\r\n //Tokenized as operators but parsed as assignment/filters\r\n '=':true,\r\n '|':true\r\n});\r\nvar ESCAPE = {\"n\":\"\\n\", \"f\":\"\\f\", \"r\":\"\\r\", \"t\":\"\\t\", \"v\":\"\\v\", \"'\":\"'\", '\"':'\"'};\r\n\r\n\r\n/////////////////////////////////////////\r\n\r\n\r\n/**\r\n * @constructor\r\n */\r\nvar Lexer = function(options) {\r\n this.options = options;\r\n};\r\n\r\nLexer.prototype = {\r\n constructor: Lexer,\r\n\r\n lex: function(text) {\r\n this.text = text;\r\n this.index = 0;\r\n this.tokens = [];\r\n\r\n while (this.index < this.text.length) {\r\n var ch = this.text.charAt(this.index);\r\n if (ch === '\"' || ch === \"'\") {\r\n this.readString(ch);\r\n } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {\r\n this.readNumber();\r\n } else if (this.isIdent(ch)) {\r\n this.readIdent();\r\n } else if (this.is(ch, '(){}[].,;:?')) {\r\n this.tokens.push({index: this.index, text: ch});\r\n this.index++;\r\n } else if (this.isWhitespace(ch)) {\r\n this.index++;\r\n } else {\r\n var ch2 = ch + this.peek();\r\n var ch3 = ch2 + this.peek(2);\r\n var op1 = OPERATORS[ch];\r\n var op2 = OPERATORS[ch2];\r\n var op3 = OPERATORS[ch3];\r\n if (op1 || op2 || op3) {\r\n var token = op3 ? ch3 : (op2 ? ch2 : ch);\r\n this.tokens.push({index: this.index, text: token, operator: true});\r\n this.index += token.length;\r\n } else {\r\n this.throwError('Unexpected next character ', this.index, this.index + 1);\r\n }\r\n }\r\n }\r\n return this.tokens;\r\n },\r\n\r\n is: function(ch, chars) {\r\n return chars.indexOf(ch) !== -1;\r\n },\r\n\r\n peek: function(i) {\r\n var num = i || 1;\r\n return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;\r\n },\r\n\r\n isNumber: function(ch) {\r\n return ('0' <= ch && ch <= '9') && typeof ch === \"string\";\r\n },\r\n\r\n isWhitespace: function(ch) {\r\n // IE treats non-breaking space as \\u00A0\r\n return (ch === ' ' || ch === '\\r' || ch === '\\t' ||\r\n ch === '\\n' || ch === '\\v' || ch === '\\u00A0');\r\n },\r\n\r\n isIdent: function(ch) {\r\n return ('a' <= ch && ch <= 'z' ||\r\n 'A' <= ch && ch <= 'Z' ||\r\n '_' === ch || ch === '$');\r\n },\r\n\r\n isExpOperator: function(ch) {\r\n return (ch === '-' || ch === '+' || this.isNumber(ch));\r\n },\r\n\r\n throwError: function(error, start, end) {\r\n end = end || this.index;\r\n var colStr = (isDefined(start)\r\n ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'\r\n : ' ' + end);\r\n throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',\r\n error, colStr, this.text);\r\n },\r\n\r\n readNumber: function() {\r\n var number = '';\r\n var start = this.index;\r\n while (this.index < this.text.length) {\r\n var ch = lowercase(this.text.charAt(this.index));\r\n if (ch == '.' || this.isNumber(ch)) {\r\n number += ch;\r\n } else {\r\n var peekCh = this.peek();\r\n if (ch == 'e' && this.isExpOperator(peekCh)) {\r\n number += ch;\r\n } else if (this.isExpOperator(ch) &&\r\n peekCh && this.isNumber(peekCh) &&\r\n number.charAt(number.length - 1) == 'e') {\r\n number += ch;\r\n } else if (this.isExpOperator(ch) &&\r\n (!peekCh || !this.isNumber(peekCh)) &&\r\n number.charAt(number.length - 1) == 'e') {\r\n this.throwError('Invalid exponent');\r\n } else {\r\n break;\r\n }\r\n }\r\n this.index++;\r\n }\r\n this.tokens.push({\r\n index: start,\r\n text: number,\r\n constant: true,\r\n value: Number(number)\r\n });\r\n },\r\n\r\n readIdent: function() {\r\n var start = this.index;\r\n while (this.index < this.text.length) {\r\n var ch = this.text.charAt(this.index);\r\n if (!(this.isIdent(ch) || this.isNumber(ch))) {\r\n break;\r\n }\r\n this.index++;\r\n }\r\n this.tokens.push({\r\n index: start,\r\n text: this.text.slice(start, this.index),\r\n identifier: true\r\n });\r\n },\r\n\r\n readString: function(quote) {\r\n var start = this.index;\r\n this.index++;\r\n var string = '';\r\n var rawString = quote;\r\n var escape = false;\r\n while (this.index < this.text.length) {\r\n var ch = this.text.charAt(this.index);\r\n rawString += ch;\r\n if (escape) {\r\n if (ch === 'u') {\r\n var hex = this.text.substring(this.index + 1, this.index + 5);\r\n if (!hex.match(/[\\da-f]{4}/i))\r\n this.throwError('Invalid unicode escape [\\\\u' + hex + ']');\r\n this.index += 4;\r\n string += String.fromCharCode(parseInt(hex, 16));\r\n } else {\r\n var rep = ESCAPE[ch];\r\n string = string + (rep || ch);\r\n }\r\n escape = false;\r\n } else if (ch === '\\\\') {\r\n escape = true;\r\n } else if (ch === quote) {\r\n this.index++;\r\n this.tokens.push({\r\n index: start,\r\n text: rawString,\r\n constant: true,\r\n value: string\r\n });\r\n return;\r\n } else {\r\n string += ch;\r\n }\r\n this.index++;\r\n }\r\n this.throwError('Unterminated quote', start);\r\n }\r\n};\r\n\r\n\r\nfunction isConstant(exp) {\r\n return exp.constant;\r\n}\r\n\r\n/**\r\n * @constructor\r\n */\r\nvar Parser = function(lexer, $filter, options) {\r\n this.lexer = lexer;\r\n this.$filter = $filter;\r\n this.options = options;\r\n};\r\n\r\nParser.ZERO = extend(function() {\r\n return 0;\r\n}, {\r\n sharedGetter: true,\r\n constant: true\r\n});\r\n\r\nParser.prototype = {\r\n constructor: Parser,\r\n\r\n parse: function(text) {\r\n this.text = text;\r\n this.tokens = this.lexer.lex(text);\r\n\r\n var value = this.statements();\r\n\r\n if (this.tokens.length !== 0) {\r\n this.throwError('is an unexpected token', this.tokens[0]);\r\n }\r\n\r\n value.literal = !!value.literal;\r\n value.constant = !!value.constant;\r\n\r\n return value;\r\n },\r\n\r\n primary: function() {\r\n var primary;\r\n if (this.expect('(')) {\r\n primary = this.filterChain();\r\n this.consume(')');\r\n } else if (this.expect('[')) {\r\n primary = this.arrayDeclaration();\r\n } else if (this.expect('{')) {\r\n primary = this.object();\r\n } else if (this.peek().identifier && this.peek().text in CONSTANTS) {\r\n primary = CONSTANTS[this.consume().text];\r\n } else if (this.peek().identifier) {\r\n primary = this.identifier();\r\n } else if (this.peek().constant) {\r\n primary = this.constant();\r\n } else {\r\n this.throwError('not a primary expression', this.peek());\r\n }\r\n\r\n var next, context;\r\n while ((next = this.expect('(', '[', '.'))) {\r\n if (next.text === '(') {\r\n primary = this.functionCall(primary, context);\r\n context = null;\r\n } else if (next.text === '[') {\r\n context = primary;\r\n primary = this.objectIndex(primary);\r\n } else if (next.text === '.') {\r\n context = primary;\r\n primary = this.fieldAccess(primary);\r\n } else {\r\n this.throwError('IMPOSSIBLE');\r\n }\r\n }\r\n return primary;\r\n },\r\n\r\n throwError: function(msg, token) {\r\n throw $parseMinErr('syntax',\r\n 'Syntax Error: Token \\'{0}\\' {1} at column {2} of the expression [{3}] starting at [{4}].',\r\n token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));\r\n },\r\n\r\n peekToken: function() {\r\n if (this.tokens.length === 0)\r\n throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);\r\n return this.tokens[0];\r\n },\r\n\r\n peek: function(e1, e2, e3, e4) {\r\n return this.peekAhead(0, e1, e2, e3, e4);\r\n },\r\n peekAhead: function(i, e1, e2, e3, e4) {\r\n if (this.tokens.length > i) {\r\n var token = this.tokens[i];\r\n var t = token.text;\r\n if (t === e1 || t === e2 || t === e3 || t === e4 ||\r\n (!e1 && !e2 && !e3 && !e4)) {\r\n return token;\r\n }\r\n }\r\n return false;\r\n },\r\n\r\n expect: function(e1, e2, e3, e4) {\r\n var token = this.peek(e1, e2, e3, e4);\r\n if (token) {\r\n this.tokens.shift();\r\n return token;\r\n }\r\n return false;\r\n },\r\n\r\n consume: function(e1) {\r\n if (this.tokens.length === 0) {\r\n throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);\r\n }\r\n\r\n var token = this.expect(e1);\r\n if (!token) {\r\n this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());\r\n }\r\n return token;\r\n },\r\n\r\n unaryFn: function(op, right) {\r\n var fn = OPERATORS[op];\r\n return extend(function $parseUnaryFn(self, locals) {\r\n return fn(self, locals, right);\r\n }, {\r\n constant:right.constant,\r\n inputs: [right]\r\n });\r\n },\r\n\r\n binaryFn: function(left, op, right, isBranching) {\r\n var fn = OPERATORS[op];\r\n return extend(function $parseBinaryFn(self, locals) {\r\n return fn(self, locals, left, right);\r\n }, {\r\n constant: left.constant && right.constant,\r\n inputs: !isBranching && [left, right]\r\n });\r\n },\r\n\r\n identifier: function() {\r\n var id = this.consume().text;\r\n\r\n //Continue reading each `.identifier` unless it is a method invocation\r\n while (this.peek('.') && this.peekAhead(1).identifier && !this.peekAhead(2, '(')) {\r\n id += this.consume().text + this.consume().text;\r\n }\r\n\r\n return getterFn(id, this.options, this.text);\r\n },\r\n\r\n constant: function() {\r\n var value = this.consume().value;\r\n\r\n return extend(function $parseConstant() {\r\n return value;\r\n }, {\r\n constant: true,\r\n literal: true\r\n });\r\n },\r\n\r\n statements: function() {\r\n var statements = [];\r\n while (true) {\r\n if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))\r\n statements.push(this.filterChain());\r\n if (!this.expect(';')) {\r\n // optimize for the common case where there is only one statement.\r\n // TODO(size): maybe we should not support multiple statements?\r\n return (statements.length === 1)\r\n ? statements[0]\r\n : function $parseStatements(self, locals) {\r\n var value;\r\n for (var i = 0, ii = statements.length; i < ii; i++) {\r\n value = statements[i](self, locals);\r\n }\r\n return value;\r\n };\r\n }\r\n }\r\n },\r\n\r\n filterChain: function() {\r\n var left = this.expression();\r\n var token;\r\n while ((token = this.expect('|'))) {\r\n left = this.filter(left);\r\n }\r\n return left;\r\n },\r\n\r\n filter: function(inputFn) {\r\n var fn = this.$filter(this.consume().text);\r\n var argsFn;\r\n var args;\r\n\r\n if (this.peek(':')) {\r\n argsFn = [];\r\n args = []; // we can safely reuse the array\r\n while (this.expect(':')) {\r\n argsFn.push(this.expression());\r\n }\r\n }\r\n\r\n var inputs = [inputFn].concat(argsFn || []);\r\n\r\n return extend(function $parseFilter(self, locals) {\r\n var input = inputFn(self, locals);\r\n if (args) {\r\n args[0] = input;\r\n\r\n var i = argsFn.length;\r\n while (i--) {\r\n args[i + 1] = argsFn[i](self, locals);\r\n }\r\n\r\n return fn.apply(undefined, args);\r\n }\r\n\r\n return fn(input);\r\n }, {\r\n constant: !fn.$stateful && inputs.every(isConstant),\r\n inputs: !fn.$stateful && inputs\r\n });\r\n },\r\n\r\n expression: function() {\r\n return this.assignment();\r\n },\r\n\r\n assignment: function() {\r\n var left = this.ternary();\r\n var right;\r\n var token;\r\n if ((token = this.expect('='))) {\r\n if (!left.assign) {\r\n this.throwError('implies assignment but [' +\r\n this.text.substring(0, token.index) + '] can not be assigned to', token);\r\n }\r\n right = this.ternary();\r\n return extend(function $parseAssignment(scope, locals) {\r\n return left.assign(scope, right(scope, locals), locals);\r\n }, {\r\n inputs: [left, right]\r\n });\r\n }\r\n return left;\r\n },\r\n\r\n ternary: function() {\r\n var left = this.logicalOR();\r\n var middle;\r\n var token;\r\n if ((token = this.expect('?'))) {\r\n middle = this.assignment();\r\n if (this.consume(':')) {\r\n var right = this.assignment();\r\n\r\n return extend(function $parseTernary(self, locals) {\r\n return left(self, locals) ? middle(self, locals) : right(self, locals);\r\n }, {\r\n constant: left.constant && middle.constant && right.constant\r\n });\r\n }\r\n }\r\n\r\n return left;\r\n },\r\n\r\n logicalOR: function() {\r\n var left = this.logicalAND();\r\n var token;\r\n while ((token = this.expect('||'))) {\r\n left = this.binaryFn(left, token.text, this.logicalAND(), true);\r\n }\r\n return left;\r\n },\r\n\r\n logicalAND: function() {\r\n var left = this.equality();\r\n var token;\r\n while ((token = this.expect('&&'))) {\r\n left = this.binaryFn(left, token.text, this.equality(), true);\r\n }\r\n return left;\r\n },\r\n\r\n equality: function() {\r\n var left = this.relational();\r\n var token;\r\n while ((token = this.expect('==','!=','===','!=='))) {\r\n left = this.binaryFn(left, token.text, this.relational());\r\n }\r\n return left;\r\n },\r\n\r\n relational: function() {\r\n var left = this.additive();\r\n var token;\r\n while ((token = this.expect('<', '>', '<=', '>='))) {\r\n left = this.binaryFn(left, token.text, this.additive());\r\n }\r\n return left;\r\n },\r\n\r\n additive: function() {\r\n var left = this.multiplicative();\r\n var token;\r\n while ((token = this.expect('+','-'))) {\r\n left = this.binaryFn(left, token.text, this.multiplicative());\r\n }\r\n return left;\r\n },\r\n\r\n multiplicative: function() {\r\n var left = this.unary();\r\n var token;\r\n while ((token = this.expect('*','/','%'))) {\r\n left = this.binaryFn(left, token.text, this.unary());\r\n }\r\n return left;\r\n },\r\n\r\n unary: function() {\r\n var token;\r\n if (this.expect('+')) {\r\n return this.primary();\r\n } else if ((token = this.expect('-'))) {\r\n return this.binaryFn(Parser.ZERO, token.text, this.unary());\r\n } else if ((token = this.expect('!'))) {\r\n return this.unaryFn(token.text, this.unary());\r\n } else {\r\n return this.primary();\r\n }\r\n },\r\n\r\n fieldAccess: function(object) {\r\n var getter = this.identifier();\r\n\r\n return extend(function $parseFieldAccess(scope, locals, self) {\r\n var o = self || object(scope, locals);\r\n return (o == null) ? undefined : getter(o);\r\n }, {\r\n assign: function(scope, value, locals) {\r\n var o = object(scope, locals);\r\n if (!o) object.assign(scope, o = {}, locals);\r\n return getter.assign(o, value);\r\n }\r\n });\r\n },\r\n\r\n objectIndex: function(obj) {\r\n var expression = this.text;\r\n\r\n var indexFn = this.expression();\r\n this.consume(']');\r\n\r\n return extend(function $parseObjectIndex(self, locals) {\r\n var o = obj(self, locals),\r\n i = indexFn(self, locals),\r\n v;\r\n\r\n ensureSafeMemberName(i, expression);\r\n if (!o) return undefined;\r\n v = ensureSafeObject(o[i], expression);\r\n return v;\r\n }, {\r\n assign: function(self, value, locals) {\r\n var key = ensureSafeMemberName(indexFn(self, locals), expression);\r\n // prevent overwriting of Function.constructor which would break ensureSafeObject check\r\n var o = ensureSafeObject(obj(self, locals), expression);\r\n if (!o) obj.assign(self, o = {}, locals);\r\n return o[key] = value;\r\n }\r\n });\r\n },\r\n\r\n functionCall: function(fnGetter, contextGetter) {\r\n var argsFn = [];\r\n if (this.peekToken().text !== ')') {\r\n do {\r\n argsFn.push(this.expression());\r\n } while (this.expect(','));\r\n }\r\n this.consume(')');\r\n\r\n var expressionText = this.text;\r\n // we can safely reuse the array across invocations\r\n var args = argsFn.length ? [] : null;\r\n\r\n return function $parseFunctionCall(scope, locals) {\r\n var context = contextGetter ? contextGetter(scope, locals) : isDefined(contextGetter) ? undefined : scope;\r\n var fn = fnGetter(scope, locals, context) || noop;\r\n\r\n if (args) {\r\n var i = argsFn.length;\r\n while (i--) {\r\n args[i] = ensureSafeObject(argsFn[i](scope, locals), expressionText);\r\n }\r\n }\r\n\r\n ensureSafeObject(context, expressionText);\r\n ensureSafeFunction(fn, expressionText);\r\n\r\n // IE doesn't have apply for some native functions\r\n var v = fn.apply\r\n ? fn.apply(context, args)\r\n : fn(args[0], args[1], args[2], args[3], args[4]);\r\n\r\n if (args) {\r\n // Free-up the memory (arguments of the last function call).\r\n args.length = 0;\r\n }\r\n\r\n return ensureSafeObject(v, expressionText);\r\n };\r\n },\r\n\r\n // This is used with json array declaration\r\n arrayDeclaration: function() {\r\n var elementFns = [];\r\n if (this.peekToken().text !== ']') {\r\n do {\r\n if (this.peek(']')) {\r\n // Support trailing commas per ES5.1.\r\n break;\r\n }\r\n elementFns.push(this.expression());\r\n } while (this.expect(','));\r\n }\r\n this.consume(']');\r\n\r\n return extend(function $parseArrayLiteral(self, locals) {\r\n var array = [];\r\n for (var i = 0, ii = elementFns.length; i < ii; i++) {\r\n array.push(elementFns[i](self, locals));\r\n }\r\n return array;\r\n }, {\r\n literal: true,\r\n constant: elementFns.every(isConstant),\r\n inputs: elementFns\r\n });\r\n },\r\n\r\n object: function() {\r\n var keys = [], valueFns = [];\r\n if (this.peekToken().text !== '}') {\r\n do {\r\n if (this.peek('}')) {\r\n // Support trailing commas per ES5.1.\r\n break;\r\n }\r\n var token = this.consume();\r\n if (token.constant) {\r\n keys.push(token.value);\r\n } else if (token.identifier) {\r\n keys.push(token.text);\r\n } else {\r\n this.throwError(\"invalid key\", token);\r\n }\r\n this.consume(':');\r\n valueFns.push(this.expression());\r\n } while (this.expect(','));\r\n }\r\n this.consume('}');\r\n\r\n return extend(function $parseObjectLiteral(self, locals) {\r\n var object = {};\r\n for (var i = 0, ii = valueFns.length; i < ii; i++) {\r\n object[keys[i]] = valueFns[i](self, locals);\r\n }\r\n return object;\r\n }, {\r\n literal: true,\r\n constant: valueFns.every(isConstant),\r\n inputs: valueFns\r\n });\r\n }\r\n};\r\n\r\n\r\n//////////////////////////////////////////////////\r\n// Parser helper functions\r\n//////////////////////////////////////////////////\r\n\r\nfunction setter(obj, locals, path, setValue, fullExp) {\r\n ensureSafeObject(obj, fullExp);\r\n ensureSafeObject(locals, fullExp);\r\n\r\n var element = path.split('.'), key;\r\n for (var i = 0; element.length > 1; i++) {\r\n key = ensureSafeMemberName(element.shift(), fullExp);\r\n var propertyObj = (i === 0 && locals && locals[key]) || obj[key];\r\n if (!propertyObj) {\r\n propertyObj = {};\r\n obj[key] = propertyObj;\r\n }\r\n obj = ensureSafeObject(propertyObj, fullExp);\r\n }\r\n key = ensureSafeMemberName(element.shift(), fullExp);\r\n ensureSafeObject(obj[key], fullExp);\r\n obj[key] = setValue;\r\n return setValue;\r\n}\r\n\r\nvar getterFnCacheDefault = createMap();\r\nvar getterFnCacheExpensive = createMap();\r\n\r\nfunction isPossiblyDangerousMemberName(name) {\r\n return name == 'constructor';\r\n}\r\n\r\n/**\r\n * Implementation of the \"Black Hole\" variant from:\r\n * - http://jsperf.com/angularjs-parse-getter/4\r\n * - http://jsperf.com/path-evaluation-simplified/7\r\n */\r\nfunction cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, expensiveChecks) {\r\n ensureSafeMemberName(key0, fullExp);\r\n ensureSafeMemberName(key1, fullExp);\r\n ensureSafeMemberName(key2, fullExp);\r\n ensureSafeMemberName(key3, fullExp);\r\n ensureSafeMemberName(key4, fullExp);\r\n var eso = function(o) {\r\n return ensureSafeObject(o, fullExp);\r\n };\r\n var eso0 = (expensiveChecks || isPossiblyDangerousMemberName(key0)) ? eso : identity;\r\n var eso1 = (expensiveChecks || isPossiblyDangerousMemberName(key1)) ? eso : identity;\r\n var eso2 = (expensiveChecks || isPossiblyDangerousMemberName(key2)) ? eso : identity;\r\n var eso3 = (expensiveChecks || isPossiblyDangerousMemberName(key3)) ? eso : identity;\r\n var eso4 = (expensiveChecks || isPossiblyDangerousMemberName(key4)) ? eso : identity;\r\n\r\n return function cspSafeGetter(scope, locals) {\r\n var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope;\r\n\r\n if (pathVal == null) return pathVal;\r\n pathVal = eso0(pathVal[key0]);\r\n\r\n if (!key1) return pathVal;\r\n if (pathVal == null) return undefined;\r\n pathVal = eso1(pathVal[key1]);\r\n\r\n if (!key2) return pathVal;\r\n if (pathVal == null) return undefined;\r\n pathVal = eso2(pathVal[key2]);\r\n\r\n if (!key3) return pathVal;\r\n if (pathVal == null) return undefined;\r\n pathVal = eso3(pathVal[key3]);\r\n\r\n if (!key4) return pathVal;\r\n if (pathVal == null) return undefined;\r\n pathVal = eso4(pathVal[key4]);\r\n\r\n return pathVal;\r\n };\r\n}\r\n\r\nfunction getterFnWithEnsureSafeObject(fn, fullExpression) {\r\n return function(s, l) {\r\n return fn(s, l, ensureSafeObject, fullExpression);\r\n };\r\n}\r\n\r\nfunction getterFn(path, options, fullExp) {\r\n var expensiveChecks = options.expensiveChecks;\r\n var getterFnCache = (expensiveChecks ? getterFnCacheExpensive : getterFnCacheDefault);\r\n var fn = getterFnCache[path];\r\n if (fn) return fn;\r\n\r\n\r\n var pathKeys = path.split('.'),\r\n pathKeysLength = pathKeys.length;\r\n\r\n // http://jsperf.com/angularjs-parse-getter/6\r\n if (options.csp) {\r\n if (pathKeysLength < 6) {\r\n fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp, expensiveChecks);\r\n } else {\r\n fn = function cspSafeGetter(scope, locals) {\r\n var i = 0, val;\r\n do {\r\n val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++],\r\n pathKeys[i++], fullExp, expensiveChecks)(scope, locals);\r\n\r\n locals = undefined; // clear after first iteration\r\n scope = val;\r\n } while (i < pathKeysLength);\r\n return val;\r\n };\r\n }\r\n } else {\r\n var code = '';\r\n if (expensiveChecks) {\r\n code += 's = eso(s, fe);\\nl = eso(l, fe);\\n';\r\n }\r\n var needsEnsureSafeObject = expensiveChecks;\r\n forEach(pathKeys, function(key, index) {\r\n ensureSafeMemberName(key, fullExp);\r\n var lookupJs = (index\r\n // we simply dereference 's' on any .dot notation\r\n ? 's'\r\n // but if we are first then we check locals first, and if so read it first\r\n : '((l&&l.hasOwnProperty(\"' + key + '\"))?l:s)') + '.' + key;\r\n if (expensiveChecks || isPossiblyDangerousMemberName(key)) {\r\n lookupJs = 'eso(' + lookupJs + ', fe)';\r\n needsEnsureSafeObject = true;\r\n }\r\n code += 'if(s == null) return undefined;\\n' +\r\n 's=' + lookupJs + ';\\n';\r\n });\r\n code += 'return s;';\r\n\r\n /* jshint -W054 */\r\n var evaledFnGetter = new Function('s', 'l', 'eso', 'fe', code); // s=scope, l=locals, eso=ensureSafeObject\r\n /* jshint +W054 */\r\n evaledFnGetter.toString = valueFn(code);\r\n if (needsEnsureSafeObject) {\r\n evaledFnGetter = getterFnWithEnsureSafeObject(evaledFnGetter, fullExp);\r\n }\r\n fn = evaledFnGetter;\r\n }\r\n\r\n fn.sharedGetter = true;\r\n fn.assign = function(self, value, locals) {\r\n return setter(self, locals, path, value, path);\r\n };\r\n getterFnCache[path] = fn;\r\n return fn;\r\n}\r\n\r\nvar objectValueOf = Object.prototype.valueOf;\r\n\r\nfunction getValueOf(value) {\r\n return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);\r\n}\r\n\r\n///////////////////////////////////\r\n\r\n/**\r\n * @ngdoc service\r\n * @name $parse\r\n * @kind function\r\n *\r\n * @description\r\n *\r\n * Converts Angular {@link guide/expression expression} into a function.\r\n *\r\n * ```js\r\n * var getter = $parse('user.name');\r\n * var setter = getter.assign;\r\n * var context = {user:{name:'angular'}};\r\n * var locals = {user:{name:'local'}};\r\n *\r\n * expect(getter(context)).toEqual('angular');\r\n * setter(context, 'newValue');\r\n * expect(context.user.name).toEqual('newValue');\r\n * expect(getter(context, locals)).toEqual('local');\r\n * ```\r\n *\r\n *\r\n * @param {string} expression String expression to compile.\r\n * @returns {function(context, locals)} a function which represents the compiled expression:\r\n *\r\n * * `context` – `{object}` – an object against which any expressions embedded in the strings\r\n * are evaluated against (typically a scope object).\r\n * * `locals` – `{object=}` – local variables context object, useful for overriding values in\r\n * `context`.\r\n *\r\n * The returned function also has the following properties:\r\n * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript\r\n * literal.\r\n * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript\r\n * constant literals.\r\n * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be\r\n * set to a function to change its value on the given context.\r\n *\r\n */\r\n\r\n\r\n/**\r\n * @ngdoc provider\r\n * @name $parseProvider\r\n *\r\n * @description\r\n * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}\r\n * service.\r\n */\r\nfunction $ParseProvider() {\r\n var cacheDefault = createMap();\r\n var cacheExpensive = createMap();\r\n\r\n\r\n\r\n this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {\r\n var $parseOptions = {\r\n csp: $sniffer.csp,\r\n expensiveChecks: false\r\n },\r\n $parseOptionsExpensive = {\r\n csp: $sniffer.csp,\r\n expensiveChecks: true\r\n };\r\n\r\n function wrapSharedExpression(exp) {\r\n var wrapped = exp;\r\n\r\n if (exp.sharedGetter) {\r\n wrapped = function $parseWrapper(self, locals) {\r\n return exp(self, locals);\r\n };\r\n wrapped.literal = exp.literal;\r\n wrapped.constant = exp.constant;\r\n wrapped.assign = exp.assign;\r\n }\r\n\r\n return wrapped;\r\n }\r\n\r\n return function $parse(exp, interceptorFn, expensiveChecks) {\r\n var parsedExpression, oneTime, cacheKey;\r\n\r\n switch (typeof exp) {\r\n case 'string':\r\n cacheKey = exp = exp.trim();\r\n\r\n var cache = (expensiveChecks ? cacheExpensive : cacheDefault);\r\n parsedExpression = cache[cacheKey];\r\n\r\n if (!parsedExpression) {\r\n if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {\r\n oneTime = true;\r\n exp = exp.substring(2);\r\n }\r\n\r\n var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;\r\n var lexer = new Lexer(parseOptions);\r\n var parser = new Parser(lexer, $filter, parseOptions);\r\n parsedExpression = parser.parse(exp);\r\n\r\n if (parsedExpression.constant) {\r\n parsedExpression.$$watchDelegate = constantWatchDelegate;\r\n } else if (oneTime) {\r\n //oneTime is not part of the exp passed to the Parser so we may have to\r\n //wrap the parsedExpression before adding a $$watchDelegate\r\n parsedExpression = wrapSharedExpression(parsedExpression);\r\n parsedExpression.$$watchDelegate = parsedExpression.literal ?\r\n oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;\r\n } else if (parsedExpression.inputs) {\r\n parsedExpression.$$watchDelegate = inputsWatchDelegate;\r\n }\r\n\r\n cache[cacheKey] = parsedExpression;\r\n }\r\n return addInterceptor(parsedExpression, interceptorFn);\r\n\r\n case 'function':\r\n return addInterceptor(exp, interceptorFn);\r\n\r\n default:\r\n return addInterceptor(noop, interceptorFn);\r\n }\r\n };\r\n\r\n function collectExpressionInputs(inputs, list) {\r\n for (var i = 0, ii = inputs.length; i < ii; i++) {\r\n var input = inputs[i];\r\n if (!input.constant) {\r\n if (input.inputs) {\r\n collectExpressionInputs(input.inputs, list);\r\n } else if (list.indexOf(input) === -1) { // TODO(perf) can we do better?\r\n list.push(input);\r\n }\r\n }\r\n }\r\n\r\n return list;\r\n }\r\n\r\n function expressionInputDirtyCheck(newValue, oldValueOfValue) {\r\n\r\n if (newValue == null || oldValueOfValue == null) { // null/undefined\r\n return newValue === oldValueOfValue;\r\n }\r\n\r\n if (typeof newValue === 'object') {\r\n\r\n // attempt to convert the value to a primitive type\r\n // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can\r\n // be cheaply dirty-checked\r\n newValue = getValueOf(newValue);\r\n\r\n if (typeof newValue === 'object') {\r\n // objects/arrays are not supported - deep-watching them would be too expensive\r\n return false;\r\n }\r\n\r\n // fall-through to the primitive equality check\r\n }\r\n\r\n //Primitive or NaN\r\n return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);\r\n }\r\n\r\n function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression) {\r\n var inputExpressions = parsedExpression.$$inputs ||\r\n (parsedExpression.$$inputs = collectExpressionInputs(parsedExpression.inputs, []));\r\n\r\n var lastResult;\r\n\r\n if (inputExpressions.length === 1) {\r\n var oldInputValue = expressionInputDirtyCheck; // init to something unique so that equals check fails\r\n inputExpressions = inputExpressions[0];\r\n return scope.$watch(function expressionInputWatch(scope) {\r\n var newInputValue = inputExpressions(scope);\r\n if (!expressionInputDirtyCheck(newInputValue, oldInputValue)) {\r\n lastResult = parsedExpression(scope);\r\n oldInputValue = newInputValue && getValueOf(newInputValue);\r\n }\r\n return lastResult;\r\n }, listener, objectEquality);\r\n }\r\n\r\n var oldInputValueOfValues = [];\r\n for (var i = 0, ii = inputExpressions.length; i < ii; i++) {\r\n oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails\r\n }\r\n\r\n return scope.$watch(function expressionInputsWatch(scope) {\r\n var changed = false;\r\n\r\n for (var i = 0, ii = inputExpressions.length; i < ii; i++) {\r\n var newInputValue = inputExpressions[i](scope);\r\n if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {\r\n oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);\r\n }\r\n }\r\n\r\n if (changed) {\r\n lastResult = parsedExpression(scope);\r\n }\r\n\r\n return lastResult;\r\n }, listener, objectEquality);\r\n }\r\n\r\n function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {\r\n var unwatch, lastValue;\r\n return unwatch = scope.$watch(function oneTimeWatch(scope) {\r\n return parsedExpression(scope);\r\n }, function oneTimeListener(value, old, scope) {\r\n lastValue = value;\r\n if (isFunction(listener)) {\r\n listener.apply(this, arguments);\r\n }\r\n if (isDefined(value)) {\r\n scope.$$postDigest(function() {\r\n if (isDefined(lastValue)) {\r\n unwatch();\r\n }\r\n });\r\n }\r\n }, objectEquality);\r\n }\r\n\r\n function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {\r\n var unwatch, lastValue;\r\n return unwatch = scope.$watch(function oneTimeWatch(scope) {\r\n return parsedExpression(scope);\r\n }, function oneTimeListener(value, old, scope) {\r\n lastValue = value;\r\n if (isFunction(listener)) {\r\n listener.call(this, value, old, scope);\r\n }\r\n if (isAllDefined(value)) {\r\n scope.$$postDigest(function() {\r\n if (isAllDefined(lastValue)) unwatch();\r\n });\r\n }\r\n }, objectEquality);\r\n\r\n function isAllDefined(value) {\r\n var allDefined = true;\r\n forEach(value, function(val) {\r\n if (!isDefined(val)) allDefined = false;\r\n });\r\n return allDefined;\r\n }\r\n }\r\n\r\n function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {\r\n var unwatch;\r\n return unwatch = scope.$watch(function constantWatch(scope) {\r\n return parsedExpression(scope);\r\n }, function constantListener(value, old, scope) {\r\n if (isFunction(listener)) {\r\n listener.apply(this, arguments);\r\n }\r\n unwatch();\r\n }, objectEquality);\r\n }\r\n\r\n function addInterceptor(parsedExpression, interceptorFn) {\r\n if (!interceptorFn) return parsedExpression;\r\n var watchDelegate = parsedExpression.$$watchDelegate;\r\n\r\n var regularWatch =\r\n watchDelegate !== oneTimeLiteralWatchDelegate &&\r\n watchDelegate !== oneTimeWatchDelegate;\r\n\r\n var fn = regularWatch ? function regularInterceptedExpression(scope, locals) {\r\n var value = parsedExpression(scope, locals);\r\n return interceptorFn(value, scope, locals);\r\n } : function oneTimeInterceptedExpression(scope, locals) {\r\n var value = parsedExpression(scope, locals);\r\n var result = interceptorFn(value, scope, locals);\r\n // we only return the interceptor's result if the\r\n // initial value is defined (for bind-once)\r\n return isDefined(value) ? result : value;\r\n };\r\n\r\n // Propagate $$watchDelegates other then inputsWatchDelegate\r\n if (parsedExpression.$$watchDelegate &&\r\n parsedExpression.$$watchDelegate !== inputsWatchDelegate) {\r\n fn.$$watchDelegate = parsedExpression.$$watchDelegate;\r\n } else if (!interceptorFn.$stateful) {\r\n // If there is an interceptor, but no watchDelegate then treat the interceptor like\r\n // we treat filters - it is assumed to be a pure function unless flagged with $stateful\r\n fn.$$watchDelegate = inputsWatchDelegate;\r\n fn.inputs = [parsedExpression];\r\n }\r\n\r\n return fn;\r\n }\r\n }];\r\n}\r\n\r\n/**\r\n * @ngdoc service\r\n * @name $q\r\n * @requires $rootScope\r\n *\r\n * @description\r\n * A service that helps you run functions asynchronously, and use their return values (or exceptions)\r\n * when they are done processing.\r\n *\r\n * This is an implementation of promises/deferred objects inspired by\r\n * [Kris Kowal's Q](https://github.com/kriskowal/q).\r\n *\r\n * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred\r\n * implementations, and the other which resembles ES6 promises to some degree.\r\n *\r\n * # $q constructor\r\n *\r\n * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`\r\n * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,\r\n * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).\r\n *\r\n * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are\r\n * available yet.\r\n *\r\n * It can be used like so:\r\n *\r\n * ```js\r\n * // for the purpose of this example let's assume that variables `$q` and `okToGreet`\r\n * // are available in the current lexical scope (they could have been injected or passed in).\r\n *\r\n * function asyncGreet(name) {\r\n * // perform some asynchronous operation, resolve or reject the promise when appropriate.\r\n * return $q(function(resolve, reject) {\r\n * setTimeout(function() {\r\n * if (okToGreet(name)) {\r\n * resolve('Hello, ' + name + '!');\r\n * } else {\r\n * reject('Greeting ' + name + ' is not allowed.');\r\n * }\r\n * }, 1000);\r\n * });\r\n * }\r\n *\r\n * var promise = asyncGreet('Robin Hood');\r\n * promise.then(function(greeting) {\r\n * alert('Success: ' + greeting);\r\n * }, function(reason) {\r\n * alert('Failed: ' + reason);\r\n * });\r\n * ```\r\n *\r\n * Note: progress/notify callbacks are not currently supported via the ES6-style interface.\r\n *\r\n * However, the more traditional CommonJS-style usage is still available, and documented below.\r\n *\r\n * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an\r\n * interface for interacting with an object that represents the result of an action that is\r\n * performed asynchronously, and may or may not be finished at any given point in time.\r\n *\r\n * From the perspective of dealing with error handling, deferred and promise APIs are to\r\n * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.\r\n *\r\n * ```js\r\n * // for the purpose of this example let's assume that variables `$q` and `okToGreet`\r\n * // are available in the current lexical scope (they could have been injected or passed in).\r\n *\r\n * function asyncGreet(name) {\r\n * var deferred = $q.defer();\r\n *\r\n * setTimeout(function() {\r\n * deferred.notify('About to greet ' + name + '.');\r\n *\r\n * if (okToGreet(name)) {\r\n * deferred.resolve('Hello, ' + name + '!');\r\n * } else {\r\n * deferred.reject('Greeting ' + name + ' is not allowed.');\r\n * }\r\n * }, 1000);\r\n *\r\n * return deferred.promise;\r\n * }\r\n *\r\n * var promise = asyncGreet('Robin Hood');\r\n * promise.then(function(greeting) {\r\n * alert('Success: ' + greeting);\r\n * }, function(reason) {\r\n * alert('Failed: ' + reason);\r\n * }, function(update) {\r\n * alert('Got notification: ' + update);\r\n * });\r\n * ```\r\n *\r\n * At first it might not be obvious why this extra complexity is worth the trouble. The payoff\r\n * comes in the way of guarantees that promise and deferred APIs make, see\r\n * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.\r\n *\r\n * Additionally the promise api allows for composition that is very hard to do with the\r\n * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.\r\n * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the\r\n * section on serial or parallel joining of promises.\r\n *\r\n * # The Deferred API\r\n *\r\n * A new instance of deferred is constructed by calling `$q.defer()`.\r\n *\r\n * The purpose of the deferred object is to expose the associated Promise instance as well as APIs\r\n * that can be used for signaling the successful or unsuccessful completion, as well as the status\r\n * of the task.\r\n *\r\n * **Methods**\r\n *\r\n * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection\r\n * constructed via `$q.reject`, the promise will be rejected instead.\r\n * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to\r\n * resolving it with a rejection constructed via `$q.reject`.\r\n * - `notify(value)` - provides updates on the status of the promise's execution. This may be called\r\n * multiple times before the promise is either resolved or rejected.\r\n *\r\n * **Properties**\r\n *\r\n * - promise – `{Promise}` – promise object associated with this deferred.\r\n *\r\n *\r\n * # The Promise API\r\n *\r\n * A new promise instance is created when a deferred instance is created and can be retrieved by\r\n * calling `deferred.promise`.\r\n *\r\n * The purpose of the promise object is to allow for interested parties to get access to the result\r\n * of the deferred task when it completes.\r\n *\r\n * **Methods**\r\n *\r\n * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or\r\n * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously\r\n * as soon as the result is available. The callbacks are called with a single argument: the result\r\n * or rejection reason. Additionally, the notify callback may be called zero or more times to\r\n * provide a progress indication, before the promise is resolved or rejected.\r\n *\r\n * This method *returns a new promise* which is resolved or rejected via the return value of the\r\n * `successCallback`, `errorCallback`. It also notifies via the return value of the\r\n * `notifyCallback` method. The promise cannot be resolved or rejected from the notifyCallback\r\n * method.\r\n *\r\n * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`\r\n *\r\n * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,\r\n * but to do so without modifying the final value. This is useful to release resources or do some\r\n * clean-up that needs to be done whether the promise was rejected or resolved. See the [full\r\n * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for\r\n * more information.\r\n *\r\n * # Chaining promises\r\n *\r\n * Because calling the `then` method of a promise returns a new derived promise, it is easily\r\n * possible to create a chain of promises:\r\n *\r\n * ```js\r\n * promiseB = promiseA.then(function(result) {\r\n * return result + 1;\r\n * });\r\n *\r\n * // promiseB will be resolved immediately after promiseA is resolved and its value\r\n * // will be the result of promiseA incremented by 1\r\n * ```\r\n *\r\n * It is possible to create chains of any length and since a promise can be resolved with another\r\n * promise (which will defer its resolution further), it is possible to pause/defer resolution of\r\n * the promises at any point in the chain. This makes it possible to implement powerful APIs like\r\n * $http's response interceptors.\r\n *\r\n *\r\n * # Differences between Kris Kowal's Q and $q\r\n *\r\n * There are two main differences:\r\n *\r\n * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation\r\n * mechanism in angular, which means faster propagation of resolution or rejection into your\r\n * models and avoiding unnecessary browser repaints, which would result in flickering UI.\r\n * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains\r\n * all the important functionality needed for common async tasks.\r\n *\r\n * # Testing\r\n *\r\n * ```js\r\n * it('should simulate promise', inject(function($q, $rootScope) {\r\n * var deferred = $q.defer();\r\n * var promise = deferred.promise;\r\n * var resolvedValue;\r\n *\r\n * promise.then(function(value) { resolvedValue = value; });\r\n * expect(resolvedValue).toBeUndefined();\r\n *\r\n * // Simulate resolving of promise\r\n * deferred.resolve(123);\r\n * // Note that the 'then' function does not get called synchronously.\r\n * // This is because we want the promise API to always be async, whether or not\r\n * // it got called synchronously or asynchronously.\r\n * expect(resolvedValue).toBeUndefined();\r\n *\r\n * // Propagate promise resolution to 'then' functions using $apply().\r\n * $rootScope.$apply();\r\n * expect(resolvedValue).toEqual(123);\r\n * }));\r\n * ```\r\n *\r\n * @param {function(function, function)} resolver Function which is responsible for resolving or\r\n * rejecting the newly created promise. The first parameter is a function which resolves the\r\n * promise, the second parameter is a function which rejects the promise.\r\n *\r\n * @returns {Promise} The newly created promise.\r\n */\r\nfunction $QProvider() {\r\n\r\n this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {\r\n return qFactory(function(callback) {\r\n $rootScope.$evalAsync(callback);\r\n }, $exceptionHandler);\r\n }];\r\n}\r\n\r\nfunction $$QProvider() {\r\n this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {\r\n return qFactory(function(callback) {\r\n $browser.defer(callback);\r\n }, $exceptionHandler);\r\n }];\r\n}\r\n\r\n/**\r\n * Constructs a promise manager.\r\n *\r\n * @param {function(function)} nextTick Function for executing functions in the next turn.\r\n * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for\r\n * debugging purposes.\r\n * @returns {object} Promise manager.\r\n */\r\nfunction qFactory(nextTick, exceptionHandler) {\r\n var $qMinErr = minErr('$q', TypeError);\r\n function callOnce(self, resolveFn, rejectFn) {\r\n var called = false;\r\n function wrap(fn) {\r\n return function(value) {\r\n if (called) return;\r\n called = true;\r\n fn.call(self, value);\r\n };\r\n }\r\n\r\n return [wrap(resolveFn), wrap(rejectFn)];\r\n }\r\n\r\n /**\r\n * @ngdoc method\r\n * @name ng.$q#defer\r\n * @kind function\r\n *\r\n * @description\r\n * Creates a `Deferred` object which represents a task which will finish in the future.\r\n *\r\n * @returns {Deferred} Returns a new instance of deferred.\r\n */\r\n var defer = function() {\r\n return new Deferred();\r\n };\r\n\r\n function Promise() {\r\n this.$$state = { status: 0 };\r\n }\r\n\r\n Promise.prototype = {\r\n then: function(onFulfilled, onRejected, progressBack) {\r\n var result = new Deferred();\r\n\r\n this.$$state.pending = this.$$state.pending || [];\r\n this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);\r\n if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);\r\n\r\n return result.promise;\r\n },\r\n\r\n \"catch\": function(callback) {\r\n return this.then(null, callback);\r\n },\r\n\r\n \"finally\": function(callback, progressBack) {\r\n return this.then(function(value) {\r\n return handleCallback(value, true, callback);\r\n }, function(error) {\r\n return handleCallback(error, false, callback);\r\n }, progressBack);\r\n }\r\n };\r\n\r\n //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native\r\n function simpleBind(context, fn) {\r\n return function(value) {\r\n fn.call(context, value);\r\n };\r\n }\r\n\r\n function processQueue(state) {\r\n var fn, promise, pending;\r\n\r\n pending = state.pending;\r\n state.processScheduled = false;\r\n state.pending = undefined;\r\n for (var i = 0, ii = pending.length; i < ii; ++i) {\r\n promise = pending[i][0];\r\n fn = pending[i][state.status];\r\n try {\r\n if (isFunction(fn)) {\r\n promise.resolve(fn(state.value));\r\n } else if (state.status === 1) {\r\n promise.resolve(state.value);\r\n } else {\r\n promise.reject(state.value);\r\n }\r\n } catch (e) {\r\n promise.reject(e);\r\n exceptionHandler(e);\r\n }\r\n }\r\n }\r\n\r\n function scheduleProcessQueue(state) {\r\n if (state.processScheduled || !state.pending) return;\r\n state.processScheduled = true;\r\n nextTick(function() { processQueue(state); });\r\n }\r\n\r\n function Deferred() {\r\n this.promise = new Promise();\r\n //Necessary to support unbound execution :/\r\n this.resolve = simpleBind(this, this.resolve);\r\n this.reject = simpleBind(this, this.reject);\r\n this.notify = simpleBind(this, this.notify);\r\n }\r\n\r\n Deferred.prototype = {\r\n resolve: function(val) {\r\n if (this.promise.$$state.status) return;\r\n if (val === this.promise) {\r\n this.$$reject($qMinErr(\r\n 'qcycle',\r\n \"Expected promise to be resolved with value other than itself '{0}'\",\r\n val));\r\n } else {\r\n this.$$resolve(val);\r\n }\r\n\r\n },\r\n\r\n $$resolve: function(val) {\r\n var then, fns;\r\n\r\n fns = callOnce(this, this.$$resolve, this.$$reject);\r\n try {\r\n if ((isObject(val) || isFunction(val))) then = val && val.then;\r\n if (isFunction(then)) {\r\n this.promise.$$state.status = -1;\r\n then.call(val, fns[0], fns[1], this.notify);\r\n } else {\r\n this.promise.$$state.value = val;\r\n this.promise.$$state.status = 1;\r\n scheduleProcessQueue(this.promise.$$state);\r\n }\r\n } catch (e) {\r\n fns[1](e);\r\n exceptionHandler(e);\r\n }\r\n },\r\n\r\n reject: function(reason) {\r\n if (this.promise.$$state.status) return;\r\n this.$$reject(reason);\r\n },\r\n\r\n $$reject: function(reason) {\r\n this.promise.$$state.value = reason;\r\n this.promise.$$state.status = 2;\r\n scheduleProcessQueue(this.promise.$$state);\r\n },\r\n\r\n notify: function(progress) {\r\n var callbacks = this.promise.$$state.pending;\r\n\r\n if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {\r\n nextTick(function() {\r\n var callback, result;\r\n for (var i = 0, ii = callbacks.length; i < ii; i++) {\r\n result = callbacks[i][0];\r\n callback = callbacks[i][3];\r\n try {\r\n result.notify(isFunction(callback) ? callback(progress) : progress);\r\n } catch (e) {\r\n exceptionHandler(e);\r\n }\r\n }\r\n });\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $q#reject\r\n * @kind function\r\n *\r\n * @description\r\n * Creates a promise that is resolved as rejected with the specified `reason`. This api should be\r\n * used to forward rejection in a chain of promises. If you are dealing with the last promise in\r\n * a promise chain, you don't need to worry about it.\r\n *\r\n * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of\r\n * `reject` as the `throw` keyword in JavaScript. This also means that if you \"catch\" an error via\r\n * a promise error callback and you want to forward the error to the promise derived from the\r\n * current promise, you have to \"rethrow\" the error by returning a rejection constructed via\r\n * `reject`.\r\n *\r\n * ```js\r\n * promiseB = promiseA.then(function(result) {\r\n * // success: do something and resolve promiseB\r\n * // with the old or a new result\r\n * return result;\r\n * }, function(reason) {\r\n * // error: handle the error if possible and\r\n * // resolve promiseB with newPromiseOrValue,\r\n * // otherwise forward the rejection to promiseB\r\n * if (canHandle(reason)) {\r\n * // handle the error and recover\r\n * return newPromiseOrValue;\r\n * }\r\n * return $q.reject(reason);\r\n * });\r\n * ```\r\n *\r\n * @param {*} reason Constant, message, exception or an object representing the rejection reason.\r\n * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.\r\n */\r\n var reject = function(reason) {\r\n var result = new Deferred();\r\n result.reject(reason);\r\n return result.promise;\r\n };\r\n\r\n var makePromise = function makePromise(value, resolved) {\r\n var result = new Deferred();\r\n if (resolved) {\r\n result.resolve(value);\r\n } else {\r\n result.reject(value);\r\n }\r\n return result.promise;\r\n };\r\n\r\n var handleCallback = function handleCallback(value, isResolved, callback) {\r\n var callbackOutput = null;\r\n try {\r\n if (isFunction(callback)) callbackOutput = callback();\r\n } catch (e) {\r\n return makePromise(e, false);\r\n }\r\n if (isPromiseLike(callbackOutput)) {\r\n return callbackOutput.then(function() {\r\n return makePromise(value, isResolved);\r\n }, function(error) {\r\n return makePromise(error, false);\r\n });\r\n } else {\r\n return makePromise(value, isResolved);\r\n }\r\n };\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $q#when\r\n * @kind function\r\n *\r\n * @description\r\n * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.\r\n * This is useful when you are dealing with an object that might or might not be a promise, or if\r\n * the promise comes from a source that can't be trusted.\r\n *\r\n * @param {*} value Value or a promise\r\n * @returns {Promise} Returns a promise of the passed value or promise\r\n */\r\n\r\n\r\n var when = function(value, callback, errback, progressBack) {\r\n var result = new Deferred();\r\n result.resolve(value);\r\n return result.promise.then(callback, errback, progressBack);\r\n };\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $q#all\r\n * @kind function\r\n *\r\n * @description\r\n * Combines multiple promises into a single promise that is resolved when all of the input\r\n * promises are resolved.\r\n *\r\n * @param {Array.|Object.} promises An array or hash of promises.\r\n * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,\r\n * each value corresponding to the promise at the same index/key in the `promises` array/hash.\r\n * If any of the promises is resolved with a rejection, this resulting promise will be rejected\r\n * with the same rejection value.\r\n */\r\n\r\n function all(promises) {\r\n var deferred = new Deferred(),\r\n counter = 0,\r\n results = isArray(promises) ? [] : {};\r\n\r\n forEach(promises, function(promise, key) {\r\n counter++;\r\n when(promise).then(function(value) {\r\n if (results.hasOwnProperty(key)) return;\r\n results[key] = value;\r\n if (!(--counter)) deferred.resolve(results);\r\n }, function(reason) {\r\n if (results.hasOwnProperty(key)) return;\r\n deferred.reject(reason);\r\n });\r\n });\r\n\r\n if (counter === 0) {\r\n deferred.resolve(results);\r\n }\r\n\r\n return deferred.promise;\r\n }\r\n\r\n var $Q = function Q(resolver) {\r\n if (!isFunction(resolver)) {\r\n throw $qMinErr('norslvr', \"Expected resolverFn, got '{0}'\", resolver);\r\n }\r\n\r\n if (!(this instanceof Q)) {\r\n // More useful when $Q is the Promise itself.\r\n return new Q(resolver);\r\n }\r\n\r\n var deferred = new Deferred();\r\n\r\n function resolveFn(value) {\r\n deferred.resolve(value);\r\n }\r\n\r\n function rejectFn(reason) {\r\n deferred.reject(reason);\r\n }\r\n\r\n resolver(resolveFn, rejectFn);\r\n\r\n return deferred.promise;\r\n };\r\n\r\n $Q.defer = defer;\r\n $Q.reject = reject;\r\n $Q.when = when;\r\n $Q.all = all;\r\n\r\n return $Q;\r\n}\r\n\r\nfunction $$RAFProvider() { //rAF\r\n this.$get = ['$window', '$timeout', function($window, $timeout) {\r\n var requestAnimationFrame = $window.requestAnimationFrame ||\r\n $window.webkitRequestAnimationFrame;\r\n\r\n var cancelAnimationFrame = $window.cancelAnimationFrame ||\r\n $window.webkitCancelAnimationFrame ||\r\n $window.webkitCancelRequestAnimationFrame;\r\n\r\n var rafSupported = !!requestAnimationFrame;\r\n var rafFn = rafSupported\r\n ? function(fn) {\r\n var id = requestAnimationFrame(fn);\r\n return function() {\r\n cancelAnimationFrame(id);\r\n };\r\n }\r\n : function(fn) {\r\n var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666\r\n return function() {\r\n $timeout.cancel(timer);\r\n };\r\n };\r\n\r\n queueFn.supported = rafSupported;\r\n\r\n var cancelLastRAF;\r\n var taskCount = 0;\r\n var taskQueue = [];\r\n return queueFn;\r\n\r\n function flush() {\r\n for (var i = 0; i < taskQueue.length; i++) {\r\n var task = taskQueue[i];\r\n if (task) {\r\n taskQueue[i] = null;\r\n task();\r\n }\r\n }\r\n taskCount = taskQueue.length = 0;\r\n }\r\n\r\n function queueFn(asyncFn) {\r\n var index = taskQueue.length;\r\n\r\n taskCount++;\r\n taskQueue.push(asyncFn);\r\n\r\n if (index === 0) {\r\n cancelLastRAF = rafFn(flush);\r\n }\r\n\r\n return function cancelQueueFn() {\r\n if (index >= 0) {\r\n taskQueue[index] = null;\r\n index = null;\r\n\r\n if (--taskCount === 0 && cancelLastRAF) {\r\n cancelLastRAF();\r\n cancelLastRAF = null;\r\n taskQueue.length = 0;\r\n }\r\n }\r\n };\r\n }\r\n }];\r\n}\r\n\r\n/**\r\n * DESIGN NOTES\r\n *\r\n * The design decisions behind the scope are heavily favored for speed and memory consumption.\r\n *\r\n * The typical use of scope is to watch the expressions, which most of the time return the same\r\n * value as last time so we optimize the operation.\r\n *\r\n * Closures construction is expensive in terms of speed as well as memory:\r\n * - No closures, instead use prototypical inheritance for API\r\n * - Internal state needs to be stored on scope directly, which means that private state is\r\n * exposed as $$____ properties\r\n *\r\n * Loop operations are optimized by using while(count--) { ... }\r\n * - this means that in order to keep the same order of execution as addition we have to add\r\n * items to the array at the beginning (unshift) instead of at the end (push)\r\n *\r\n * Child scopes are created and removed often\r\n * - Using an array would be slow since inserts in middle are expensive so we use linked list\r\n *\r\n * There are few watches then a lot of observers. This is why you don't want the observer to be\r\n * implemented in the same way as watch. Watch requires return of initialization function which\r\n * are expensive to construct.\r\n */\r\n\r\n\r\n/**\r\n * @ngdoc provider\r\n * @name $rootScopeProvider\r\n * @description\r\n *\r\n * Provider for the $rootScope service.\r\n */\r\n\r\n/**\r\n * @ngdoc method\r\n * @name $rootScopeProvider#digestTtl\r\n * @description\r\n *\r\n * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and\r\n * assuming that the model is unstable.\r\n *\r\n * The current default is 10 iterations.\r\n *\r\n * In complex applications it's possible that the dependencies between `$watch`s will result in\r\n * several digest iterations. However if an application needs more than the default 10 digest\r\n * iterations for its model to stabilize then you should investigate what is causing the model to\r\n * continuously change during the digest.\r\n *\r\n * Increasing the TTL could have performance implications, so you should not change it without\r\n * proper justification.\r\n *\r\n * @param {number} limit The number of digest iterations.\r\n */\r\n\r\n\r\n/**\r\n * @ngdoc service\r\n * @name $rootScope\r\n * @description\r\n *\r\n * Every application has a single root {@link ng.$rootScope.Scope scope}.\r\n * All other scopes are descendant scopes of the root scope. Scopes provide separation\r\n * between the model and the view, via a mechanism for watching the model for changes.\r\n * They also provide an event emission/broadcast and subscription facility. See the\r\n * {@link guide/scope developer guide on scopes}.\r\n */\r\nfunction $RootScopeProvider() {\r\n var TTL = 10;\r\n var $rootScopeMinErr = minErr('$rootScope');\r\n var lastDirtyWatch = null;\r\n var applyAsyncId = null;\r\n\r\n this.digestTtl = function(value) {\r\n if (arguments.length) {\r\n TTL = value;\r\n }\r\n return TTL;\r\n };\r\n\r\n function createChildScopeClass(parent) {\r\n function ChildScope() {\r\n this.$$watchers = this.$$nextSibling =\r\n this.$$childHead = this.$$childTail = null;\r\n this.$$listeners = {};\r\n this.$$listenerCount = {};\r\n this.$id = nextUid();\r\n this.$$ChildScope = null;\r\n }\r\n ChildScope.prototype = parent;\r\n return ChildScope;\r\n }\r\n\r\n this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',\r\n function($injector, $exceptionHandler, $parse, $browser) {\r\n\r\n function destroyChildScope($event) {\r\n $event.currentScope.$$destroyed = true;\r\n }\r\n\r\n /**\r\n * @ngdoc type\r\n * @name $rootScope.Scope\r\n *\r\n * @description\r\n * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the\r\n * {@link auto.$injector $injector}. Child scopes are created using the\r\n * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when\r\n * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for\r\n * an in-depth introduction and usage examples.\r\n *\r\n *\r\n * # Inheritance\r\n * A scope can inherit from a parent scope, as in this example:\r\n * ```js\r\n var parent = $rootScope;\r\n var child = parent.$new();\r\n\r\n parent.salutation = \"Hello\";\r\n expect(child.salutation).toEqual('Hello');\r\n\r\n child.salutation = \"Welcome\";\r\n expect(child.salutation).toEqual('Welcome');\r\n expect(parent.salutation).toEqual('Hello');\r\n * ```\r\n *\r\n * When interacting with `Scope` in tests, additional helper methods are available on the\r\n * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional\r\n * details.\r\n *\r\n *\r\n * @param {Object.=} providers Map of service factory which need to be\r\n * provided for the current scope. Defaults to {@link ng}.\r\n * @param {Object.=} instanceCache Provides pre-instantiated services which should\r\n * append/override services provided by `providers`. This is handy\r\n * when unit-testing and having the need to override a default\r\n * service.\r\n * @returns {Object} Newly created scope.\r\n *\r\n */\r\n function Scope() {\r\n this.$id = nextUid();\r\n this.$$phase = this.$parent = this.$$watchers =\r\n this.$$nextSibling = this.$$prevSibling =\r\n this.$$childHead = this.$$childTail = null;\r\n this.$root = this;\r\n this.$$destroyed = false;\r\n this.$$listeners = {};\r\n this.$$listenerCount = {};\r\n this.$$isolateBindings = null;\r\n }\r\n\r\n /**\r\n * @ngdoc property\r\n * @name $rootScope.Scope#$id\r\n *\r\n * @description\r\n * Unique scope ID (monotonically increasing) useful for debugging.\r\n */\r\n\r\n /**\r\n * @ngdoc property\r\n * @name $rootScope.Scope#$parent\r\n *\r\n * @description\r\n * Reference to the parent scope.\r\n */\r\n\r\n /**\r\n * @ngdoc property\r\n * @name $rootScope.Scope#$root\r\n *\r\n * @description\r\n * Reference to the root scope.\r\n */\r\n\r\n Scope.prototype = {\r\n constructor: Scope,\r\n /**\r\n * @ngdoc method\r\n * @name $rootScope.Scope#$new\r\n * @kind function\r\n *\r\n * @description\r\n * Creates a new child {@link ng.$rootScope.Scope scope}.\r\n *\r\n * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.\r\n * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.\r\n *\r\n * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is\r\n * desired for the scope and its child scopes to be permanently detached from the parent and\r\n * thus stop participating in model change detection and listener notification by invoking.\r\n *\r\n * @param {boolean} isolate If true, then the scope does not prototypically inherit from the\r\n * parent scope. The scope is isolated, as it can not see parent scope properties.\r\n * When creating widgets, it is useful for the widget to not accidentally read parent\r\n * state.\r\n *\r\n * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`\r\n * of the newly created scope. Defaults to `this` scope if not provided.\r\n * This is used when creating a transclude scope to correctly place it\r\n * in the scope hierarchy while maintaining the correct prototypical\r\n * inheritance.\r\n *\r\n * @returns {Object} The newly created child scope.\r\n *\r\n */\r\n $new: function(isolate, parent) {\r\n var child;\r\n\r\n parent = parent || this;\r\n\r\n if (isolate) {\r\n child = new Scope();\r\n child.$root = this.$root;\r\n } else {\r\n // Only create a child scope class if somebody asks for one,\r\n // but cache it to allow the VM to optimize lookups.\r\n if (!this.$$ChildScope) {\r\n this.$$ChildScope = createChildScopeClass(this);\r\n }\r\n child = new this.$$ChildScope();\r\n }\r\n child.$parent = parent;\r\n child.$$prevSibling = parent.$$childTail;\r\n if (parent.$$childHead) {\r\n parent.$$childTail.$$nextSibling = child;\r\n parent.$$childTail = child;\r\n } else {\r\n parent.$$childHead = parent.$$childTail = child;\r\n }\r\n\r\n // When the new scope is not isolated or we inherit from `this`, and\r\n // the parent scope is destroyed, the property `$$destroyed` is inherited\r\n // prototypically. In all other cases, this property needs to be set\r\n // when the parent scope is destroyed.\r\n // The listener needs to be added after the parent is set\r\n if (isolate || parent != this) child.$on('$destroy', destroyChildScope);\r\n\r\n return child;\r\n },\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $rootScope.Scope#$watch\r\n * @kind function\r\n *\r\n * @description\r\n * Registers a `listener` callback to be executed whenever the `watchExpression` changes.\r\n *\r\n * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest\r\n * $digest()} and should return the value that will be watched. (Since\r\n * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the\r\n * `watchExpression` can execute multiple times per\r\n * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)\r\n * - The `listener` is called only when the value from the current `watchExpression` and the\r\n * previous call to `watchExpression` are not equal (with the exception of the initial run,\r\n * see below). Inequality is determined according to reference inequality,\r\n * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)\r\n * via the `!==` Javascript operator, unless `objectEquality == true`\r\n * (see next point)\r\n * - When `objectEquality == true`, inequality of the `watchExpression` is determined\r\n * according to the {@link angular.equals} function. To save the value of the object for\r\n * later comparison, the {@link angular.copy} function is used. This therefore means that\r\n * watching complex objects will have adverse memory and performance implications.\r\n * - The watch `listener` may change the model, which may trigger other `listener`s to fire.\r\n * This is achieved by rerunning the watchers until no changes are detected. The rerun\r\n * iteration limit is 10 to prevent an infinite loop deadlock.\r\n *\r\n *\r\n * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,\r\n * you can register a `watchExpression` function with no `listener`. (Be prepared for\r\n * multiple calls to your `watchExpression` because it will execute multiple times in a\r\n * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)\r\n *\r\n * After a watcher is registered with the scope, the `listener` fn is called asynchronously\r\n * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the\r\n * watcher. In rare cases, this is undesirable because the listener is called when the result\r\n * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you\r\n * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the\r\n * listener was called due to initialization.\r\n *\r\n *\r\n *\r\n * # Example\r\n * ```js\r\n // let's assume that scope was dependency injected as the $rootScope\r\n var scope = $rootScope;\r\n scope.name = 'misko';\r\n scope.counter = 0;\r\n\r\n expect(scope.counter).toEqual(0);\r\n scope.$watch('name', function(newValue, oldValue) {\r\n scope.counter = scope.counter + 1;\r\n });\r\n expect(scope.counter).toEqual(0);\r\n\r\n scope.$digest();\r\n // the listener is always called during the first $digest loop after it was registered\r\n expect(scope.counter).toEqual(1);\r\n\r\n scope.$digest();\r\n // but now it will not be called unless the value changes\r\n expect(scope.counter).toEqual(1);\r\n\r\n scope.name = 'adam';\r\n scope.$digest();\r\n expect(scope.counter).toEqual(2);\r\n\r\n\r\n\r\n // Using a function as a watchExpression\r\n var food;\r\n scope.foodCounter = 0;\r\n expect(scope.foodCounter).toEqual(0);\r\n scope.$watch(\r\n // This function returns the value being watched. It is called for each turn of the $digest loop\r\n function() { return food; },\r\n // This is the change listener, called when the value returned from the above function changes\r\n function(newValue, oldValue) {\r\n if ( newValue !== oldValue ) {\r\n // Only increment the counter if the value changed\r\n scope.foodCounter = scope.foodCounter + 1;\r\n }\r\n }\r\n );\r\n // No digest has been run so the counter will be zero\r\n expect(scope.foodCounter).toEqual(0);\r\n\r\n // Run the digest but since food has not changed count will still be zero\r\n scope.$digest();\r\n expect(scope.foodCounter).toEqual(0);\r\n\r\n // Update food and run digest. Now the counter will increment\r\n food = 'cheeseburger';\r\n scope.$digest();\r\n expect(scope.foodCounter).toEqual(1);\r\n\r\n * ```\r\n *\r\n *\r\n *\r\n * @param {(function()|string)} watchExpression Expression that is evaluated on each\r\n * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers\r\n * a call to the `listener`.\r\n *\r\n * - `string`: Evaluated as {@link guide/expression expression}\r\n * - `function(scope)`: called with current `scope` as a parameter.\r\n * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value\r\n * of `watchExpression` changes.\r\n *\r\n * - `newVal` contains the current value of the `watchExpression`\r\n * - `oldVal` contains the previous value of the `watchExpression`\r\n * - `scope` refers to the current scope\r\n * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of\r\n * comparing for reference equality.\r\n * @returns {function()} Returns a deregistration function for this listener.\r\n */\r\n $watch: function(watchExp, listener, objectEquality) {\r\n var get = $parse(watchExp);\r\n\r\n if (get.$$watchDelegate) {\r\n return get.$$watchDelegate(this, listener, objectEquality, get);\r\n }\r\n var scope = this,\r\n array = scope.$$watchers,\r\n watcher = {\r\n fn: listener,\r\n last: initWatchVal,\r\n get: get,\r\n exp: watchExp,\r\n eq: !!objectEquality\r\n };\r\n\r\n lastDirtyWatch = null;\r\n\r\n if (!isFunction(listener)) {\r\n watcher.fn = noop;\r\n }\r\n\r\n if (!array) {\r\n array = scope.$$watchers = [];\r\n }\r\n // we use unshift since we use a while loop in $digest for speed.\r\n // the while loop reads in reverse order.\r\n array.unshift(watcher);\r\n\r\n return function deregisterWatch() {\r\n arrayRemove(array, watcher);\r\n lastDirtyWatch = null;\r\n };\r\n },\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $rootScope.Scope#$watchGroup\r\n * @kind function\r\n *\r\n * @description\r\n * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.\r\n * If any one expression in the collection changes the `listener` is executed.\r\n *\r\n * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every\r\n * call to $digest() to see if any items changes.\r\n * - The `listener` is called whenever any expression in the `watchExpressions` array changes.\r\n *\r\n * @param {Array.} watchExpressions Array of expressions that will be individually\r\n * watched using {@link ng.$rootScope.Scope#$watch $watch()}\r\n *\r\n * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any\r\n * expression in `watchExpressions` changes\r\n * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching\r\n * those of `watchExpression`\r\n * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching\r\n * those of `watchExpression`\r\n * The `scope` refers to the current scope.\r\n * @returns {function()} Returns a de-registration function for all listeners.\r\n */\r\n $watchGroup: function(watchExpressions, listener) {\r\n var oldValues = new Array(watchExpressions.length);\r\n var newValues = new Array(watchExpressions.length);\r\n var deregisterFns = [];\r\n var self = this;\r\n var changeReactionScheduled = false;\r\n var firstRun = true;\r\n\r\n if (!watchExpressions.length) {\r\n // No expressions means we call the listener ASAP\r\n var shouldCall = true;\r\n self.$evalAsync(function() {\r\n if (shouldCall) listener(newValues, newValues, self);\r\n });\r\n return function deregisterWatchGroup() {\r\n shouldCall = false;\r\n };\r\n }\r\n\r\n if (watchExpressions.length === 1) {\r\n // Special case size of one\r\n return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {\r\n newValues[0] = value;\r\n oldValues[0] = oldValue;\r\n listener(newValues, (value === oldValue) ? newValues : oldValues, scope);\r\n });\r\n }\r\n\r\n forEach(watchExpressions, function(expr, i) {\r\n var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {\r\n newValues[i] = value;\r\n oldValues[i] = oldValue;\r\n if (!changeReactionScheduled) {\r\n changeReactionScheduled = true;\r\n self.$evalAsync(watchGroupAction);\r\n }\r\n });\r\n deregisterFns.push(unwatchFn);\r\n });\r\n\r\n function watchGroupAction() {\r\n changeReactionScheduled = false;\r\n\r\n if (firstRun) {\r\n firstRun = false;\r\n listener(newValues, newValues, self);\r\n } else {\r\n listener(newValues, oldValues, self);\r\n }\r\n }\r\n\r\n return function deregisterWatchGroup() {\r\n while (deregisterFns.length) {\r\n deregisterFns.shift()();\r\n }\r\n };\r\n },\r\n\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $rootScope.Scope#$watchCollection\r\n * @kind function\r\n *\r\n * @description\r\n * Shallow watches the properties of an object and fires whenever any of the properties change\r\n * (for arrays, this implies watching the array items; for object maps, this implies watching\r\n * the properties). If a change is detected, the `listener` callback is fired.\r\n *\r\n * - The `obj` collection is observed via standard $watch operation and is examined on every\r\n * call to $digest() to see if any items have been added, removed, or moved.\r\n * - The `listener` is called whenever anything within the `obj` has changed. Examples include\r\n * adding, removing, and moving items belonging to an object or array.\r\n *\r\n *\r\n * # Example\r\n * ```js\r\n $scope.names = ['igor', 'matias', 'misko', 'james'];\r\n $scope.dataCount = 4;\r\n\r\n $scope.$watchCollection('names', function(newNames, oldNames) {\r\n $scope.dataCount = newNames.length;\r\n });\r\n\r\n expect($scope.dataCount).toEqual(4);\r\n $scope.$digest();\r\n\r\n //still at 4 ... no changes\r\n expect($scope.dataCount).toEqual(4);\r\n\r\n $scope.names.pop();\r\n $scope.$digest();\r\n\r\n //now there's been a change\r\n expect($scope.dataCount).toEqual(3);\r\n * ```\r\n *\r\n *\r\n * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The\r\n * expression value should evaluate to an object or an array which is observed on each\r\n * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the\r\n * collection will trigger a call to the `listener`.\r\n *\r\n * @param {function(newCollection, oldCollection, scope)} listener a callback function called\r\n * when a change is detected.\r\n * - The `newCollection` object is the newly modified data obtained from the `obj` expression\r\n * - The `oldCollection` object is a copy of the former collection data.\r\n * Due to performance considerations, the`oldCollection` value is computed only if the\r\n * `listener` function declares two or more arguments.\r\n * - The `scope` argument refers to the current scope.\r\n *\r\n * @returns {function()} Returns a de-registration function for this listener. When the\r\n * de-registration function is executed, the internal watch operation is terminated.\r\n */\r\n $watchCollection: function(obj, listener) {\r\n $watchCollectionInterceptor.$stateful = true;\r\n\r\n var self = this;\r\n // the current value, updated on each dirty-check run\r\n var newValue;\r\n // a shallow copy of the newValue from the last dirty-check run,\r\n // updated to match newValue during dirty-check run\r\n var oldValue;\r\n // a shallow copy of the newValue from when the last change happened\r\n var veryOldValue;\r\n // only track veryOldValue if the listener is asking for it\r\n var trackVeryOldValue = (listener.length > 1);\r\n var changeDetected = 0;\r\n var changeDetector = $parse(obj, $watchCollectionInterceptor);\r\n var internalArray = [];\r\n var internalObject = {};\r\n var initRun = true;\r\n var oldLength = 0;\r\n\r\n function $watchCollectionInterceptor(_value) {\r\n newValue = _value;\r\n var newLength, key, bothNaN, newItem, oldItem;\r\n\r\n // If the new value is undefined, then return undefined as the watch may be a one-time watch\r\n if (isUndefined(newValue)) return;\r\n\r\n if (!isObject(newValue)) { // if primitive\r\n if (oldValue !== newValue) {\r\n oldValue = newValue;\r\n changeDetected++;\r\n }\r\n } else if (isArrayLike(newValue)) {\r\n if (oldValue !== internalArray) {\r\n // we are transitioning from something which was not an array into array.\r\n oldValue = internalArray;\r\n oldLength = oldValue.length = 0;\r\n changeDetected++;\r\n }\r\n\r\n newLength = newValue.length;\r\n\r\n if (oldLength !== newLength) {\r\n // if lengths do not match we need to trigger change notification\r\n changeDetected++;\r\n oldValue.length = oldLength = newLength;\r\n }\r\n // copy the items to oldValue and look for changes.\r\n for (var i = 0; i < newLength; i++) {\r\n oldItem = oldValue[i];\r\n newItem = newValue[i];\r\n\r\n bothNaN = (oldItem !== oldItem) && (newItem !== newItem);\r\n if (!bothNaN && (oldItem !== newItem)) {\r\n changeDetected++;\r\n oldValue[i] = newItem;\r\n }\r\n }\r\n } else {\r\n if (oldValue !== internalObject) {\r\n // we are transitioning from something which was not an object into object.\r\n oldValue = internalObject = {};\r\n oldLength = 0;\r\n changeDetected++;\r\n }\r\n // copy the items to oldValue and look for changes.\r\n newLength = 0;\r\n for (key in newValue) {\r\n if (newValue.hasOwnProperty(key)) {\r\n newLength++;\r\n newItem = newValue[key];\r\n oldItem = oldValue[key];\r\n\r\n if (key in oldValue) {\r\n bothNaN = (oldItem !== oldItem) && (newItem !== newItem);\r\n if (!bothNaN && (oldItem !== newItem)) {\r\n changeDetected++;\r\n oldValue[key] = newItem;\r\n }\r\n } else {\r\n oldLength++;\r\n oldValue[key] = newItem;\r\n changeDetected++;\r\n }\r\n }\r\n }\r\n if (oldLength > newLength) {\r\n // we used to have more keys, need to find them and destroy them.\r\n changeDetected++;\r\n for (key in oldValue) {\r\n if (!newValue.hasOwnProperty(key)) {\r\n oldLength--;\r\n delete oldValue[key];\r\n }\r\n }\r\n }\r\n }\r\n return changeDetected;\r\n }\r\n\r\n function $watchCollectionAction() {\r\n if (initRun) {\r\n initRun = false;\r\n listener(newValue, newValue, self);\r\n } else {\r\n listener(newValue, veryOldValue, self);\r\n }\r\n\r\n // make a copy for the next time a collection is changed\r\n if (trackVeryOldValue) {\r\n if (!isObject(newValue)) {\r\n //primitive\r\n veryOldValue = newValue;\r\n } else if (isArrayLike(newValue)) {\r\n veryOldValue = new Array(newValue.length);\r\n for (var i = 0; i < newValue.length; i++) {\r\n veryOldValue[i] = newValue[i];\r\n }\r\n } else { // if object\r\n veryOldValue = {};\r\n for (var key in newValue) {\r\n if (hasOwnProperty.call(newValue, key)) {\r\n veryOldValue[key] = newValue[key];\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n return this.$watch(changeDetector, $watchCollectionAction);\r\n },\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $rootScope.Scope#$digest\r\n * @kind function\r\n *\r\n * @description\r\n * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and\r\n * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change\r\n * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}\r\n * until no more listeners are firing. This means that it is possible to get into an infinite\r\n * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of\r\n * iterations exceeds 10.\r\n *\r\n * Usually, you don't call `$digest()` directly in\r\n * {@link ng.directive:ngController controllers} or in\r\n * {@link ng.$compileProvider#directive directives}.\r\n * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within\r\n * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.\r\n *\r\n * If you want to be notified whenever `$digest()` is called,\r\n * you can register a `watchExpression` function with\r\n * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.\r\n *\r\n * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.\r\n *\r\n * # Example\r\n * ```js\r\n var scope = ...;\r\n scope.name = 'misko';\r\n scope.counter = 0;\r\n\r\n expect(scope.counter).toEqual(0);\r\n scope.$watch('name', function(newValue, oldValue) {\r\n scope.counter = scope.counter + 1;\r\n });\r\n expect(scope.counter).toEqual(0);\r\n\r\n scope.$digest();\r\n // the listener is always called during the first $digest loop after it was registered\r\n expect(scope.counter).toEqual(1);\r\n\r\n scope.$digest();\r\n // but now it will not be called unless the value changes\r\n expect(scope.counter).toEqual(1);\r\n\r\n scope.name = 'adam';\r\n scope.$digest();\r\n expect(scope.counter).toEqual(2);\r\n * ```\r\n *\r\n */\r\n $digest: function() {\r\n var watch, value, last,\r\n watchers,\r\n length,\r\n dirty, ttl = TTL,\r\n next, current, target = this,\r\n watchLog = [],\r\n logIdx, logMsg, asyncTask;\r\n\r\n beginPhase('$digest');\r\n // Check for changes to browser url that happened in sync before the call to $digest\r\n $browser.$$checkUrlChange();\r\n\r\n if (this === $rootScope && applyAsyncId !== null) {\r\n // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then\r\n // cancel the scheduled $apply and flush the queue of expressions to be evaluated.\r\n $browser.defer.cancel(applyAsyncId);\r\n flushApplyAsync();\r\n }\r\n\r\n lastDirtyWatch = null;\r\n\r\n do { // \"while dirty\" loop\r\n dirty = false;\r\n current = target;\r\n\r\n while (asyncQueue.length) {\r\n try {\r\n asyncTask = asyncQueue.shift();\r\n asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);\r\n } catch (e) {\r\n $exceptionHandler(e);\r\n }\r\n lastDirtyWatch = null;\r\n }\r\n\r\n traverseScopesLoop:\r\n do { // \"traverse the scopes\" loop\r\n if ((watchers = current.$$watchers)) {\r\n // process our watches\r\n length = watchers.length;\r\n while (length--) {\r\n try {\r\n watch = watchers[length];\r\n // Most common watches are on primitives, in which case we can short\r\n // circuit it with === operator, only when === fails do we use .equals\r\n if (watch) {\r\n if ((value = watch.get(current)) !== (last = watch.last) &&\r\n !(watch.eq\r\n ? equals(value, last)\r\n : (typeof value === 'number' && typeof last === 'number'\r\n && isNaN(value) && isNaN(last)))) {\r\n dirty = true;\r\n lastDirtyWatch = watch;\r\n watch.last = watch.eq ? copy(value, null) : value;\r\n watch.fn(value, ((last === initWatchVal) ? value : last), current);\r\n if (ttl < 5) {\r\n logIdx = 4 - ttl;\r\n if (!watchLog[logIdx]) watchLog[logIdx] = [];\r\n watchLog[logIdx].push({\r\n msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,\r\n newVal: value,\r\n oldVal: last\r\n });\r\n }\r\n } else if (watch === lastDirtyWatch) {\r\n // If the most recently dirty watcher is now clean, short circuit since the remaining watchers\r\n // have already been tested.\r\n dirty = false;\r\n break traverseScopesLoop;\r\n }\r\n }\r\n } catch (e) {\r\n $exceptionHandler(e);\r\n }\r\n }\r\n }\r\n\r\n // Insanity Warning: scope depth-first traversal\r\n // yes, this code is a bit crazy, but it works and we have tests to prove it!\r\n // this piece should be kept in sync with the traversal in $broadcast\r\n if (!(next = (current.$$childHead ||\r\n (current !== target && current.$$nextSibling)))) {\r\n while (current !== target && !(next = current.$$nextSibling)) {\r\n current = current.$parent;\r\n }\r\n }\r\n } while ((current = next));\r\n\r\n // `break traverseScopesLoop;` takes us to here\r\n\r\n if ((dirty || asyncQueue.length) && !(ttl--)) {\r\n clearPhase();\r\n throw $rootScopeMinErr('infdig',\r\n '{0} $digest() iterations reached. Aborting!\\n' +\r\n 'Watchers fired in the last 5 iterations: {1}',\r\n TTL, watchLog);\r\n }\r\n\r\n } while (dirty || asyncQueue.length);\r\n\r\n clearPhase();\r\n\r\n while (postDigestQueue.length) {\r\n try {\r\n postDigestQueue.shift()();\r\n } catch (e) {\r\n $exceptionHandler(e);\r\n }\r\n }\r\n },\r\n\r\n\r\n /**\r\n * @ngdoc event\r\n * @name $rootScope.Scope#$destroy\r\n * @eventType broadcast on scope being destroyed\r\n *\r\n * @description\r\n * Broadcasted when a scope and its children are being destroyed.\r\n *\r\n * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to\r\n * clean up DOM bindings before an element is removed from the DOM.\r\n */\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $rootScope.Scope#$destroy\r\n * @kind function\r\n *\r\n * @description\r\n * Removes the current scope (and all of its children) from the parent scope. Removal implies\r\n * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer\r\n * propagate to the current scope and its children. Removal also implies that the current\r\n * scope is eligible for garbage collection.\r\n *\r\n * The `$destroy()` is usually used by directives such as\r\n * {@link ng.directive:ngRepeat ngRepeat} for managing the\r\n * unrolling of the loop.\r\n *\r\n * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.\r\n * Application code can register a `$destroy` event handler that will give it a chance to\r\n * perform any necessary cleanup.\r\n *\r\n * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to\r\n * clean up DOM bindings before an element is removed from the DOM.\r\n */\r\n $destroy: function() {\r\n // we can't destroy the root scope or a scope that has been already destroyed\r\n if (this.$$destroyed) return;\r\n var parent = this.$parent;\r\n\r\n this.$broadcast('$destroy');\r\n this.$$destroyed = true;\r\n if (this === $rootScope) return;\r\n\r\n for (var eventName in this.$$listenerCount) {\r\n decrementListenerCount(this, this.$$listenerCount[eventName], eventName);\r\n }\r\n\r\n // sever all the references to parent scopes (after this cleanup, the current scope should\r\n // not be retained by any of our references and should be eligible for garbage collection)\r\n if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;\r\n if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;\r\n if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;\r\n if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;\r\n\r\n // Disable listeners, watchers and apply/digest methods\r\n this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;\r\n this.$on = this.$watch = this.$watchGroup = function() { return noop; };\r\n this.$$listeners = {};\r\n\r\n // All of the code below is bogus code that works around V8's memory leak via optimized code\r\n // and inline caches.\r\n //\r\n // see:\r\n // - https://code.google.com/p/v8/issues/detail?id=2073#c26\r\n // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909\r\n // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451\r\n\r\n this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =\r\n this.$$childTail = this.$root = this.$$watchers = null;\r\n },\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $rootScope.Scope#$eval\r\n * @kind function\r\n *\r\n * @description\r\n * Executes the `expression` on the current scope and returns the result. Any exceptions in\r\n * the expression are propagated (uncaught). This is useful when evaluating Angular\r\n * expressions.\r\n *\r\n * # Example\r\n * ```js\r\n var scope = ng.$rootScope.Scope();\r\n scope.a = 1;\r\n scope.b = 2;\r\n\r\n expect(scope.$eval('a+b')).toEqual(3);\r\n expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);\r\n * ```\r\n *\r\n * @param {(string|function())=} expression An angular expression to be executed.\r\n *\r\n * - `string`: execute using the rules as defined in {@link guide/expression expression}.\r\n * - `function(scope)`: execute the function with the current `scope` parameter.\r\n *\r\n * @param {(object)=} locals Local variables object, useful for overriding values in scope.\r\n * @returns {*} The result of evaluating the expression.\r\n */\r\n $eval: function(expr, locals) {\r\n return $parse(expr)(this, locals);\r\n },\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $rootScope.Scope#$evalAsync\r\n * @kind function\r\n *\r\n * @description\r\n * Executes the expression on the current scope at a later point in time.\r\n *\r\n * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only\r\n * that:\r\n *\r\n * - it will execute after the function that scheduled the evaluation (preferably before DOM\r\n * rendering).\r\n * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after\r\n * `expression` execution.\r\n *\r\n * Any exceptions from the execution of the expression are forwarded to the\r\n * {@link ng.$exceptionHandler $exceptionHandler} service.\r\n *\r\n * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle\r\n * will be scheduled. However, it is encouraged to always call code that changes the model\r\n * from within an `$apply` call. That includes code evaluated via `$evalAsync`.\r\n *\r\n * @param {(string|function())=} expression An angular expression to be executed.\r\n *\r\n * - `string`: execute using the rules as defined in {@link guide/expression expression}.\r\n * - `function(scope)`: execute the function with the current `scope` parameter.\r\n *\r\n * @param {(object)=} locals Local variables object, useful for overriding values in scope.\r\n */\r\n $evalAsync: function(expr, locals) {\r\n // if we are outside of an $digest loop and this is the first time we are scheduling async\r\n // task also schedule async auto-flush\r\n if (!$rootScope.$$phase && !asyncQueue.length) {\r\n $browser.defer(function() {\r\n if (asyncQueue.length) {\r\n $rootScope.$digest();\r\n }\r\n });\r\n }\r\n\r\n asyncQueue.push({scope: this, expression: expr, locals: locals});\r\n },\r\n\r\n $$postDigest: function(fn) {\r\n postDigestQueue.push(fn);\r\n },\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $rootScope.Scope#$apply\r\n * @kind function\r\n *\r\n * @description\r\n * `$apply()` is used to execute an expression in angular from outside of the angular\r\n * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).\r\n * Because we are calling into the angular framework we need to perform proper scope life\r\n * cycle of {@link ng.$exceptionHandler exception handling},\r\n * {@link ng.$rootScope.Scope#$digest executing watches}.\r\n *\r\n * ## Life cycle\r\n *\r\n * # Pseudo-Code of `$apply()`\r\n * ```js\r\n function $apply(expr) {\r\n try {\r\n return $eval(expr);\r\n } catch (e) {\r\n $exceptionHandler(e);\r\n } finally {\r\n $root.$digest();\r\n }\r\n }\r\n * ```\r\n *\r\n *\r\n * Scope's `$apply()` method transitions through the following stages:\r\n *\r\n * 1. The {@link guide/expression expression} is executed using the\r\n * {@link ng.$rootScope.Scope#$eval $eval()} method.\r\n * 2. Any exceptions from the execution of the expression are forwarded to the\r\n * {@link ng.$exceptionHandler $exceptionHandler} service.\r\n * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the\r\n * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.\r\n *\r\n *\r\n * @param {(string|function())=} exp An angular expression to be executed.\r\n *\r\n * - `string`: execute using the rules as defined in {@link guide/expression expression}.\r\n * - `function(scope)`: execute the function with current `scope` parameter.\r\n *\r\n * @returns {*} The result of evaluating the expression.\r\n */\r\n $apply: function(expr) {\r\n try {\r\n beginPhase('$apply');\r\n return this.$eval(expr);\r\n } catch (e) {\r\n $exceptionHandler(e);\r\n } finally {\r\n clearPhase();\r\n try {\r\n $rootScope.$digest();\r\n } catch (e) {\r\n $exceptionHandler(e);\r\n throw e;\r\n }\r\n }\r\n },\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $rootScope.Scope#$applyAsync\r\n * @kind function\r\n *\r\n * @description\r\n * Schedule the invocation of $apply to occur at a later time. The actual time difference\r\n * varies across browsers, but is typically around ~10 milliseconds.\r\n *\r\n * This can be used to queue up multiple expressions which need to be evaluated in the same\r\n * digest.\r\n *\r\n * @param {(string|function())=} exp An angular expression to be executed.\r\n *\r\n * - `string`: execute using the rules as defined in {@link guide/expression expression}.\r\n * - `function(scope)`: execute the function with current `scope` parameter.\r\n */\r\n $applyAsync: function(expr) {\r\n var scope = this;\r\n expr && applyAsyncQueue.push($applyAsyncExpression);\r\n scheduleApplyAsync();\r\n\r\n function $applyAsyncExpression() {\r\n scope.$eval(expr);\r\n }\r\n },\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $rootScope.Scope#$on\r\n * @kind function\r\n *\r\n * @description\r\n * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for\r\n * discussion of event life cycle.\r\n *\r\n * The event listener function format is: `function(event, args...)`. The `event` object\r\n * passed into the listener has the following attributes:\r\n *\r\n * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or\r\n * `$broadcast`-ed.\r\n * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the\r\n * event propagates through the scope hierarchy, this property is set to null.\r\n * - `name` - `{string}`: name of the event.\r\n * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel\r\n * further event propagation (available only for events that were `$emit`-ed).\r\n * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag\r\n * to true.\r\n * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.\r\n *\r\n * @param {string} name Event name to listen on.\r\n * @param {function(event, ...args)} listener Function to call when the event is emitted.\r\n * @returns {function()} Returns a deregistration function for this listener.\r\n */\r\n $on: function(name, listener) {\r\n var namedListeners = this.$$listeners[name];\r\n if (!namedListeners) {\r\n this.$$listeners[name] = namedListeners = [];\r\n }\r\n namedListeners.push(listener);\r\n\r\n var current = this;\r\n do {\r\n if (!current.$$listenerCount[name]) {\r\n current.$$listenerCount[name] = 0;\r\n }\r\n current.$$listenerCount[name]++;\r\n } while ((current = current.$parent));\r\n\r\n var self = this;\r\n return function() {\r\n var indexOfListener = namedListeners.indexOf(listener);\r\n if (indexOfListener !== -1) {\r\n namedListeners[indexOfListener] = null;\r\n decrementListenerCount(self, 1, name);\r\n }\r\n };\r\n },\r\n\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $rootScope.Scope#$emit\r\n * @kind function\r\n *\r\n * @description\r\n * Dispatches an event `name` upwards through the scope hierarchy notifying the\r\n * registered {@link ng.$rootScope.Scope#$on} listeners.\r\n *\r\n * The event life cycle starts at the scope on which `$emit` was called. All\r\n * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get\r\n * notified. Afterwards, the event traverses upwards toward the root scope and calls all\r\n * registered listeners along the way. The event will stop propagating if one of the listeners\r\n * cancels it.\r\n *\r\n * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed\r\n * onto the {@link ng.$exceptionHandler $exceptionHandler} service.\r\n *\r\n * @param {string} name Event name to emit.\r\n * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.\r\n * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).\r\n */\r\n $emit: function(name, args) {\r\n var empty = [],\r\n namedListeners,\r\n scope = this,\r\n stopPropagation = false,\r\n event = {\r\n name: name,\r\n targetScope: scope,\r\n stopPropagation: function() {stopPropagation = true;},\r\n preventDefault: function() {\r\n event.defaultPrevented = true;\r\n },\r\n defaultPrevented: false\r\n },\r\n listenerArgs = concat([event], arguments, 1),\r\n i, length;\r\n\r\n do {\r\n namedListeners = scope.$$listeners[name] || empty;\r\n event.currentScope = scope;\r\n for (i = 0, length = namedListeners.length; i < length; i++) {\r\n\r\n // if listeners were deregistered, defragment the array\r\n if (!namedListeners[i]) {\r\n namedListeners.splice(i, 1);\r\n i--;\r\n length--;\r\n continue;\r\n }\r\n try {\r\n //allow all listeners attached to the current scope to run\r\n namedListeners[i].apply(null, listenerArgs);\r\n } catch (e) {\r\n $exceptionHandler(e);\r\n }\r\n }\r\n //if any listener on the current scope stops propagation, prevent bubbling\r\n if (stopPropagation) {\r\n event.currentScope = null;\r\n return event;\r\n }\r\n //traverse upwards\r\n scope = scope.$parent;\r\n } while (scope);\r\n\r\n event.currentScope = null;\r\n\r\n return event;\r\n },\r\n\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $rootScope.Scope#$broadcast\r\n * @kind function\r\n *\r\n * @description\r\n * Dispatches an event `name` downwards to all child scopes (and their children) notifying the\r\n * registered {@link ng.$rootScope.Scope#$on} listeners.\r\n *\r\n * The event life cycle starts at the scope on which `$broadcast` was called. All\r\n * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get\r\n * notified. Afterwards, the event propagates to all direct and indirect scopes of the current\r\n * scope and calls all registered listeners along the way. The event cannot be canceled.\r\n *\r\n * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed\r\n * onto the {@link ng.$exceptionHandler $exceptionHandler} service.\r\n *\r\n * @param {string} name Event name to broadcast.\r\n * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.\r\n * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}\r\n */\r\n $broadcast: function(name, args) {\r\n var target = this,\r\n current = target,\r\n next = target,\r\n event = {\r\n name: name,\r\n targetScope: target,\r\n preventDefault: function() {\r\n event.defaultPrevented = true;\r\n },\r\n defaultPrevented: false\r\n };\r\n\r\n if (!target.$$listenerCount[name]) return event;\r\n\r\n var listenerArgs = concat([event], arguments, 1),\r\n listeners, i, length;\r\n\r\n //down while you can, then up and next sibling or up and next sibling until back at root\r\n while ((current = next)) {\r\n event.currentScope = current;\r\n listeners = current.$$listeners[name] || [];\r\n for (i = 0, length = listeners.length; i < length; i++) {\r\n // if listeners were deregistered, defragment the array\r\n if (!listeners[i]) {\r\n listeners.splice(i, 1);\r\n i--;\r\n length--;\r\n continue;\r\n }\r\n\r\n try {\r\n listeners[i].apply(null, listenerArgs);\r\n } catch (e) {\r\n $exceptionHandler(e);\r\n }\r\n }\r\n\r\n // Insanity Warning: scope depth-first traversal\r\n // yes, this code is a bit crazy, but it works and we have tests to prove it!\r\n // this piece should be kept in sync with the traversal in $digest\r\n // (though it differs due to having the extra check for $$listenerCount)\r\n if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||\r\n (current !== target && current.$$nextSibling)))) {\r\n while (current !== target && !(next = current.$$nextSibling)) {\r\n current = current.$parent;\r\n }\r\n }\r\n }\r\n\r\n event.currentScope = null;\r\n return event;\r\n }\r\n };\r\n\r\n var $rootScope = new Scope();\r\n\r\n //The internal queues. Expose them on the $rootScope for debugging/testing purposes.\r\n var asyncQueue = $rootScope.$$asyncQueue = [];\r\n var postDigestQueue = $rootScope.$$postDigestQueue = [];\r\n var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];\r\n\r\n return $rootScope;\r\n\r\n\r\n function beginPhase(phase) {\r\n if ($rootScope.$$phase) {\r\n throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);\r\n }\r\n\r\n $rootScope.$$phase = phase;\r\n }\r\n\r\n function clearPhase() {\r\n $rootScope.$$phase = null;\r\n }\r\n\r\n\r\n function decrementListenerCount(current, count, name) {\r\n do {\r\n current.$$listenerCount[name] -= count;\r\n\r\n if (current.$$listenerCount[name] === 0) {\r\n delete current.$$listenerCount[name];\r\n }\r\n } while ((current = current.$parent));\r\n }\r\n\r\n /**\r\n * function used as an initial value for watchers.\r\n * because it's unique we can easily tell it apart from other values\r\n */\r\n function initWatchVal() {}\r\n\r\n function flushApplyAsync() {\r\n while (applyAsyncQueue.length) {\r\n try {\r\n applyAsyncQueue.shift()();\r\n } catch (e) {\r\n $exceptionHandler(e);\r\n }\r\n }\r\n applyAsyncId = null;\r\n }\r\n\r\n function scheduleApplyAsync() {\r\n if (applyAsyncId === null) {\r\n applyAsyncId = $browser.defer(function() {\r\n $rootScope.$apply(flushApplyAsync);\r\n });\r\n }\r\n }\r\n }];\r\n}\r\n\r\n/**\r\n * @description\r\n * Private service to sanitize uris for links and images. Used by $compile and $sanitize.\r\n */\r\nfunction $$SanitizeUriProvider() {\r\n var aHrefSanitizationWhitelist = /^\\s*(https?|ftp|mailto|tel|file):/,\r\n imgSrcSanitizationWhitelist = /^\\s*((https?|ftp|file|blob):|data:image\\/)/;\r\n\r\n /**\r\n * @description\r\n * Retrieves or overrides the default regular expression that is used for whitelisting of safe\r\n * urls during a[href] sanitization.\r\n *\r\n * The sanitization is a security measure aimed at prevent XSS attacks via html links.\r\n *\r\n * Any url about to be assigned to a[href] via data-binding is first normalized and turned into\r\n * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`\r\n * regular expression. If a match is found, the original url is written into the dom. Otherwise,\r\n * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\r\n *\r\n * @param {RegExp=} regexp New regexp to whitelist urls with.\r\n * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\r\n * chaining otherwise.\r\n */\r\n this.aHrefSanitizationWhitelist = function(regexp) {\r\n if (isDefined(regexp)) {\r\n aHrefSanitizationWhitelist = regexp;\r\n return this;\r\n }\r\n return aHrefSanitizationWhitelist;\r\n };\r\n\r\n\r\n /**\r\n * @description\r\n * Retrieves or overrides the default regular expression that is used for whitelisting of safe\r\n * urls during img[src] sanitization.\r\n *\r\n * The sanitization is a security measure aimed at prevent XSS attacks via html links.\r\n *\r\n * Any url about to be assigned to img[src] via data-binding is first normalized and turned into\r\n * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`\r\n * regular expression. If a match is found, the original url is written into the dom. Otherwise,\r\n * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\r\n *\r\n * @param {RegExp=} regexp New regexp to whitelist urls with.\r\n * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\r\n * chaining otherwise.\r\n */\r\n this.imgSrcSanitizationWhitelist = function(regexp) {\r\n if (isDefined(regexp)) {\r\n imgSrcSanitizationWhitelist = regexp;\r\n return this;\r\n }\r\n return imgSrcSanitizationWhitelist;\r\n };\r\n\r\n this.$get = function() {\r\n return function sanitizeUri(uri, isImage) {\r\n var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;\r\n var normalizedVal;\r\n normalizedVal = urlResolve(uri).href;\r\n if (normalizedVal !== '' && !normalizedVal.match(regex)) {\r\n return 'unsafe:' + normalizedVal;\r\n }\r\n return uri;\r\n };\r\n };\r\n}\r\n\r\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\r\n * Any commits to this file should be reviewed with security in mind. *\r\n * Changes to this file can potentially create security vulnerabilities. *\r\n * An approval from 2 Core members with history of modifying *\r\n * this file is required. *\r\n * *\r\n * Does the change somehow allow for arbitrary javascript to be executed? *\r\n * Or allows for someone to change the prototype of built-in objects? *\r\n * Or gives undesired access to variables likes document or window? *\r\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\r\n\r\nvar $sceMinErr = minErr('$sce');\r\n\r\nvar SCE_CONTEXTS = {\r\n HTML: 'html',\r\n CSS: 'css',\r\n URL: 'url',\r\n // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a\r\n // url. (e.g. ng-include, script src, templateUrl)\r\n RESOURCE_URL: 'resourceUrl',\r\n JS: 'js'\r\n};\r\n\r\n// Helper functions follow.\r\n\r\nfunction adjustMatcher(matcher) {\r\n if (matcher === 'self') {\r\n return matcher;\r\n } else if (isString(matcher)) {\r\n // Strings match exactly except for 2 wildcards - '*' and '**'.\r\n // '*' matches any character except those from the set ':/.?&'.\r\n // '**' matches any character (like .* in a RegExp).\r\n // More than 2 *'s raises an error as it's ill defined.\r\n if (matcher.indexOf('***') > -1) {\r\n throw $sceMinErr('iwcard',\r\n 'Illegal sequence *** in string matcher. String: {0}', matcher);\r\n }\r\n matcher = escapeForRegexp(matcher).\r\n replace('\\\\*\\\\*', '.*').\r\n replace('\\\\*', '[^:/.?&;]*');\r\n return new RegExp('^' + matcher + '$');\r\n } else if (isRegExp(matcher)) {\r\n // The only other type of matcher allowed is a Regexp.\r\n // Match entire URL / disallow partial matches.\r\n // Flags are reset (i.e. no global, ignoreCase or multiline)\r\n return new RegExp('^' + matcher.source + '$');\r\n } else {\r\n throw $sceMinErr('imatcher',\r\n 'Matchers may only be \"self\", string patterns or RegExp objects');\r\n }\r\n}\r\n\r\n\r\nfunction adjustMatchers(matchers) {\r\n var adjustedMatchers = [];\r\n if (isDefined(matchers)) {\r\n forEach(matchers, function(matcher) {\r\n adjustedMatchers.push(adjustMatcher(matcher));\r\n });\r\n }\r\n return adjustedMatchers;\r\n}\r\n\r\n\r\n/**\r\n * @ngdoc service\r\n * @name $sceDelegate\r\n * @kind function\r\n *\r\n * @description\r\n *\r\n * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict\r\n * Contextual Escaping (SCE)} services to AngularJS.\r\n *\r\n * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of\r\n * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is\r\n * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to\r\n * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things\r\n * work because `$sce` delegates to `$sceDelegate` for these operations.\r\n *\r\n * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.\r\n *\r\n * The default instance of `$sceDelegate` should work out of the box with little pain. While you\r\n * can override it completely to change the behavior of `$sce`, the common case would\r\n * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting\r\n * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as\r\n * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist\r\n * $sceDelegateProvider.resourceUrlWhitelist} and {@link\r\n * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}\r\n */\r\n\r\n/**\r\n * @ngdoc provider\r\n * @name $sceDelegateProvider\r\n * @description\r\n *\r\n * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate\r\n * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure\r\n * that the URLs used for sourcing Angular templates are safe. Refer {@link\r\n * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and\r\n * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}\r\n *\r\n * For the general details about this service in Angular, read the main page for {@link ng.$sce\r\n * Strict Contextual Escaping (SCE)}.\r\n *\r\n * **Example**: Consider the following case. \r\n *\r\n * - your app is hosted at url `http://myapp.example.com/`\r\n * - but some of your templates are hosted on other domains you control such as\r\n * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.\r\n * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.\r\n *\r\n * Here is what a secure configuration for this scenario might look like:\r\n *\r\n * ```\r\n * angular.module('myApp', []).config(function($sceDelegateProvider) {\r\n * $sceDelegateProvider.resourceUrlWhitelist([\r\n * // Allow same origin resource loads.\r\n * 'self',\r\n * // Allow loading from our assets domain. Notice the difference between * and **.\r\n * 'http://srv*.assets.example.com/**'\r\n * ]);\r\n *\r\n * // The blacklist overrides the whitelist so the open redirect here is blocked.\r\n * $sceDelegateProvider.resourceUrlBlacklist([\r\n * 'http://myapp.example.com/clickThru**'\r\n * ]);\r\n * });\r\n * ```\r\n */\r\n\r\nfunction $SceDelegateProvider() {\r\n this.SCE_CONTEXTS = SCE_CONTEXTS;\r\n\r\n // Resource URLs can also be trusted by policy.\r\n var resourceUrlWhitelist = ['self'],\r\n resourceUrlBlacklist = [];\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $sceDelegateProvider#resourceUrlWhitelist\r\n * @kind function\r\n *\r\n * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value\r\n * provided. This must be an array or null. A snapshot of this array is used so further\r\n * changes to the array are ignored.\r\n *\r\n * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items\r\n * allowed in this array.\r\n *\r\n * Note: **an empty whitelist array will block all URLs**!\r\n *\r\n * @return {Array} the currently set whitelist array.\r\n *\r\n * The **default value** when no whitelist has been explicitly set is `['self']` allowing only\r\n * same origin resource requests.\r\n *\r\n * @description\r\n * Sets/Gets the whitelist of trusted resource URLs.\r\n */\r\n this.resourceUrlWhitelist = function(value) {\r\n if (arguments.length) {\r\n resourceUrlWhitelist = adjustMatchers(value);\r\n }\r\n return resourceUrlWhitelist;\r\n };\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $sceDelegateProvider#resourceUrlBlacklist\r\n * @kind function\r\n *\r\n * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value\r\n * provided. This must be an array or null. A snapshot of this array is used so further\r\n * changes to the array are ignored.\r\n *\r\n * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items\r\n * allowed in this array.\r\n *\r\n * The typical usage for the blacklist is to **block\r\n * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as\r\n * these would otherwise be trusted but actually return content from the redirected domain.\r\n *\r\n * Finally, **the blacklist overrides the whitelist** and has the final say.\r\n *\r\n * @return {Array} the currently set blacklist array.\r\n *\r\n * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there\r\n * is no blacklist.)\r\n *\r\n * @description\r\n * Sets/Gets the blacklist of trusted resource URLs.\r\n */\r\n\r\n this.resourceUrlBlacklist = function(value) {\r\n if (arguments.length) {\r\n resourceUrlBlacklist = adjustMatchers(value);\r\n }\r\n return resourceUrlBlacklist;\r\n };\r\n\r\n this.$get = ['$injector', function($injector) {\r\n\r\n var htmlSanitizer = function htmlSanitizer(html) {\r\n throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');\r\n };\r\n\r\n if ($injector.has('$sanitize')) {\r\n htmlSanitizer = $injector.get('$sanitize');\r\n }\r\n\r\n\r\n function matchUrl(matcher, parsedUrl) {\r\n if (matcher === 'self') {\r\n return urlIsSameOrigin(parsedUrl);\r\n } else {\r\n // definitely a regex. See adjustMatchers()\r\n return !!matcher.exec(parsedUrl.href);\r\n }\r\n }\r\n\r\n function isResourceUrlAllowedByPolicy(url) {\r\n var parsedUrl = urlResolve(url.toString());\r\n var i, n, allowed = false;\r\n // Ensure that at least one item from the whitelist allows this url.\r\n for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {\r\n if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {\r\n allowed = true;\r\n break;\r\n }\r\n }\r\n if (allowed) {\r\n // Ensure that no item from the blacklist blocked this url.\r\n for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {\r\n if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {\r\n allowed = false;\r\n break;\r\n }\r\n }\r\n }\r\n return allowed;\r\n }\r\n\r\n function generateHolderType(Base) {\r\n var holderType = function TrustedValueHolderType(trustedValue) {\r\n this.$$unwrapTrustedValue = function() {\r\n return trustedValue;\r\n };\r\n };\r\n if (Base) {\r\n holderType.prototype = new Base();\r\n }\r\n holderType.prototype.valueOf = function sceValueOf() {\r\n return this.$$unwrapTrustedValue();\r\n };\r\n holderType.prototype.toString = function sceToString() {\r\n return this.$$unwrapTrustedValue().toString();\r\n };\r\n return holderType;\r\n }\r\n\r\n var trustedValueHolderBase = generateHolderType(),\r\n byType = {};\r\n\r\n byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);\r\n byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);\r\n byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);\r\n byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);\r\n byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $sceDelegate#trustAs\r\n *\r\n * @description\r\n * Returns an object that is trusted by angular for use in specified strict\r\n * contextual escaping contexts (such as ng-bind-html, ng-include, any src\r\n * attribute interpolation, any dom event binding attribute interpolation\r\n * such as for onclick, etc.) that uses the provided value.\r\n * See {@link ng.$sce $sce} for enabling strict contextual escaping.\r\n *\r\n * @param {string} type The kind of context in which this value is safe for use. e.g. url,\r\n * resourceUrl, html, js and css.\r\n * @param {*} value The value that that should be considered trusted/safe.\r\n * @returns {*} A value that can be used to stand in for the provided `value` in places\r\n * where Angular expects a $sce.trustAs() return value.\r\n */\r\n function trustAs(type, trustedValue) {\r\n var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);\r\n if (!Constructor) {\r\n throw $sceMinErr('icontext',\r\n 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',\r\n type, trustedValue);\r\n }\r\n if (trustedValue === null || trustedValue === undefined || trustedValue === '') {\r\n return trustedValue;\r\n }\r\n // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting\r\n // mutable objects, we ensure here that the value passed in is actually a string.\r\n if (typeof trustedValue !== 'string') {\r\n throw $sceMinErr('itype',\r\n 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',\r\n type);\r\n }\r\n return new Constructor(trustedValue);\r\n }\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $sceDelegate#valueOf\r\n *\r\n * @description\r\n * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs\r\n * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link\r\n * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.\r\n *\r\n * If the passed parameter is not a value that had been returned by {@link\r\n * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.\r\n *\r\n * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}\r\n * call or anything else.\r\n * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs\r\n * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns\r\n * `value` unchanged.\r\n */\r\n function valueOf(maybeTrusted) {\r\n if (maybeTrusted instanceof trustedValueHolderBase) {\r\n return maybeTrusted.$$unwrapTrustedValue();\r\n } else {\r\n return maybeTrusted;\r\n }\r\n }\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $sceDelegate#getTrusted\r\n *\r\n * @description\r\n * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and\r\n * returns the originally supplied value if the queried context type is a supertype of the\r\n * created type. If this condition isn't satisfied, throws an exception.\r\n *\r\n * @param {string} type The kind of context in which this value is to be used.\r\n * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs\r\n * `$sceDelegate.trustAs`} call.\r\n * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs\r\n * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.\r\n */\r\n function getTrusted(type, maybeTrusted) {\r\n if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {\r\n return maybeTrusted;\r\n }\r\n var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);\r\n if (constructor && maybeTrusted instanceof constructor) {\r\n return maybeTrusted.$$unwrapTrustedValue();\r\n }\r\n // If we get here, then we may only take one of two actions.\r\n // 1. sanitize the value for the requested type, or\r\n // 2. throw an exception.\r\n if (type === SCE_CONTEXTS.RESOURCE_URL) {\r\n if (isResourceUrlAllowedByPolicy(maybeTrusted)) {\r\n return maybeTrusted;\r\n } else {\r\n throw $sceMinErr('insecurl',\r\n 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',\r\n maybeTrusted.toString());\r\n }\r\n } else if (type === SCE_CONTEXTS.HTML) {\r\n return htmlSanitizer(maybeTrusted);\r\n }\r\n throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');\r\n }\r\n\r\n return { trustAs: trustAs,\r\n getTrusted: getTrusted,\r\n valueOf: valueOf };\r\n }];\r\n}\r\n\r\n\r\n/**\r\n * @ngdoc provider\r\n * @name $sceProvider\r\n * @description\r\n *\r\n * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.\r\n * - enable/disable Strict Contextual Escaping (SCE) in a module\r\n * - override the default implementation with a custom delegate\r\n *\r\n * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.\r\n */\r\n\r\n/* jshint maxlen: false*/\r\n\r\n/**\r\n * @ngdoc service\r\n * @name $sce\r\n * @kind function\r\n *\r\n * @description\r\n *\r\n * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.\r\n *\r\n * # Strict Contextual Escaping\r\n *\r\n * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain\r\n * contexts to result in a value that is marked as safe to use for that context. One example of\r\n * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer\r\n * to these contexts as privileged or SCE contexts.\r\n *\r\n * As of version 1.2, Angular ships with SCE enabled by default.\r\n *\r\n * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow\r\n * one to execute arbitrary javascript by the use of the expression() syntax. Refer\r\n * to learn more about them.\r\n * You can ensure your document is in standards mode and not quirks mode by adding ``\r\n * to the top of your HTML document.\r\n *\r\n * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for\r\n * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.\r\n *\r\n * Here's an example of a binding in a privileged context:\r\n *\r\n * ```\r\n * \r\n *
    \r\n * ```\r\n *\r\n * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE\r\n * disabled, this application allows the user to render arbitrary HTML into the DIV.\r\n * In a more realistic example, one may be rendering user comments, blog articles, etc. via\r\n * bindings. (HTML is just one example of a context where rendering user controlled input creates\r\n * security vulnerabilities.)\r\n *\r\n * For the case of HTML, you might use a library, either on the client side, or on the server side,\r\n * to sanitize unsafe HTML before binding to the value and rendering it in the document.\r\n *\r\n * How would you ensure that every place that used these types of bindings was bound to a value that\r\n * was sanitized by your library (or returned as safe for rendering by your server?) How can you\r\n * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some\r\n * properties/fields and forgot to update the binding to the sanitized value?\r\n *\r\n * To be secure by default, you want to ensure that any such bindings are disallowed unless you can\r\n * determine that something explicitly says it's safe to use a value for binding in that\r\n * context. You can then audit your code (a simple grep would do) to ensure that this is only done\r\n * for those values that you can easily tell are safe - because they were received from your server,\r\n * sanitized by your library, etc. You can organize your codebase to help with this - perhaps\r\n * allowing only the files in a specific directory to do this. Ensuring that the internal API\r\n * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.\r\n *\r\n * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}\r\n * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to\r\n * obtain values that will be accepted by SCE / privileged contexts.\r\n *\r\n *\r\n * ## How does it work?\r\n *\r\n * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted\r\n * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link\r\n * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the\r\n * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.\r\n *\r\n * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link\r\n * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly\r\n * simplified):\r\n *\r\n * ```\r\n * var ngBindHtmlDirective = ['$sce', function($sce) {\r\n * return function(scope, element, attr) {\r\n * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {\r\n * element.html(value || '');\r\n * });\r\n * };\r\n * }];\r\n * ```\r\n *\r\n * ## Impact on loading templates\r\n *\r\n * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as\r\n * `templateUrl`'s specified by {@link guide/directive directives}.\r\n *\r\n * By default, Angular only loads templates from the same domain and protocol as the application\r\n * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl\r\n * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or\r\n * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist\r\n * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.\r\n *\r\n * *Please note*:\r\n * The browser's\r\n * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)\r\n * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)\r\n * policy apply in addition to this and may further restrict whether the template is successfully\r\n * loaded. This means that without the right CORS policy, loading templates from a different domain\r\n * won't work on all browsers. Also, loading templates from `file://` URL does not work on some\r\n * browsers.\r\n *\r\n * ## This feels like too much overhead\r\n *\r\n * It's important to remember that SCE only applies to interpolation expressions.\r\n *\r\n * If your expressions are constant literals, they're automatically trusted and you don't need to\r\n * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.\r\n * `
    implicitly trusted'\">
    `) just works.\r\n *\r\n * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them\r\n * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.\r\n *\r\n * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load\r\n * templates in `ng-include` from your application's domain without having to even know about SCE.\r\n * It blocks loading templates from other domains or loading templates over http from an https\r\n * served document. You can change these by setting your own custom {@link\r\n * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link\r\n * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.\r\n *\r\n * This significantly reduces the overhead. It is far easier to pay the small overhead and have an\r\n * application that's secure and can be audited to verify that with much more ease than bolting\r\n * security onto an application later.\r\n *\r\n * \r\n * ## What trusted context types are supported?\r\n *\r\n * | Context | Notes |\r\n * |---------------------|----------------|\r\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. |\r\n * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |\r\n * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`
    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. |\r\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. |\r\n *\r\n * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist}
    \r\n *\r\n * Each element in these arrays must be one of the following:\r\n *\r\n * - **'self'**\r\n * - The special **string**, `'self'`, can be used to match against all URLs of the **same\r\n * domain** as the application document using the **same protocol**.\r\n * - **String** (except the special value `'self'`)\r\n * - The string is matched against the full *normalized / absolute URL* of the resource\r\n * being tested (substring matches are not good enough.)\r\n * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters\r\n * match themselves.\r\n * - `*`: matches zero or more occurrences of any character other than one of the following 6\r\n * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use\r\n * in a whitelist.\r\n * - `**`: matches zero or more occurrences of *any* character. As such, it's not\r\n * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.\r\n * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might\r\n * not have been the intention.) Its usage at the very end of the path is ok. (e.g.\r\n * http://foo.example.com/templates/**).\r\n * - **RegExp** (*see caveat below*)\r\n * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax\r\n * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to\r\n * accidentally introduce a bug when one updates a complex expression (imho, all regexes should\r\n * have good test coverage). For instance, the use of `.` in the regex is correct only in a\r\n * small number of cases. A `.` character in the regex used when matching the scheme or a\r\n * subdomain could be matched against a `:` or literal `.` that was likely not intended. It\r\n * is highly recommended to use the string patterns and only fall back to regular expressions\r\n * as a last resort.\r\n * - The regular expression must be an instance of RegExp (i.e. not a string.) It is\r\n * matched against the **entire** *normalized / absolute URL* of the resource being tested\r\n * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags\r\n * present on the RegExp (such as multiline, global, ignoreCase) are ignored.\r\n * - If you are generating your JavaScript from some other templating engine (not\r\n * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),\r\n * remember to escape your regular expression (and be aware that you might need more than\r\n * one level of escaping depending on your templating engine and the way you interpolated\r\n * the value.) Do make use of your platform's escaping mechanism as it might be good\r\n * enough before coding your own. E.g. Ruby has\r\n * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)\r\n * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).\r\n * Javascript lacks a similar built in function for escaping. Take a look at Google\r\n * Closure library's [goog.string.regExpEscape(s)](\r\n * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).\r\n *\r\n * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.\r\n *\r\n * ## Show me an example using SCE.\r\n *\r\n * \r\n * \r\n *
    \r\n *

    \r\n * User comments
    \r\n * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when\r\n * $sanitize is available. If $sanitize isn't available, this results in an error instead of an\r\n * exploit.\r\n *
    \r\n *
    \r\n * {{userComment.name}}:\r\n * \r\n *
    \r\n *
    \r\n *
    \r\n *
    \r\n *
    \r\n *\r\n * \r\n * angular.module('mySceApp', ['ngSanitize'])\r\n * .controller('AppController', ['$http', '$templateCache', '$sce',\r\n * function($http, $templateCache, $sce) {\r\n * var self = this;\r\n * $http.get(\"test_data.json\", {cache: $templateCache}).success(function(userComments) {\r\n * self.userComments = userComments;\r\n * });\r\n * self.explicitlyTrustedHtml = $sce.trustAsHtml(\r\n * 'Hover over this text.');\r\n * }]);\r\n * \r\n *\r\n * \r\n * [\r\n * { \"name\": \"Alice\",\r\n * \"htmlComment\":\r\n * \"Is anyone reading this?\"\r\n * },\r\n * { \"name\": \"Bob\",\r\n * \"htmlComment\": \"Yes! Am I the only other one?\"\r\n * }\r\n * ]\r\n * \r\n *\r\n * \r\n * describe('SCE doc demo', function() {\r\n * it('should sanitize untrusted values', function() {\r\n * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())\r\n * .toBe('Is anyone reading this?');\r\n * });\r\n *\r\n * it('should NOT sanitize explicitly trusted values', function() {\r\n * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(\r\n * 'Hover over this text.');\r\n * });\r\n * });\r\n * \r\n *
    \r\n *\r\n *\r\n *\r\n * ## Can I disable SCE completely?\r\n *\r\n * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits\r\n * for little coding overhead. It will be much harder to take an SCE disabled application and\r\n * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE\r\n * for cases where you have a lot of existing code that was written before SCE was introduced and\r\n * you're migrating them a module at a time.\r\n *\r\n * That said, here's how you can completely disable SCE:\r\n *\r\n * ```\r\n * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {\r\n * // Completely disable SCE. For demonstration purposes only!\r\n * // Do not use in new projects.\r\n * $sceProvider.enabled(false);\r\n * });\r\n * ```\r\n *\r\n */\r\n/* jshint maxlen: 100 */\r\n\r\nfunction $SceProvider() {\r\n var enabled = true;\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $sceProvider#enabled\r\n * @kind function\r\n *\r\n * @param {boolean=} value If provided, then enables/disables SCE.\r\n * @return {boolean} true if SCE is enabled, false otherwise.\r\n *\r\n * @description\r\n * Enables/disables SCE and returns the current value.\r\n */\r\n this.enabled = function(value) {\r\n if (arguments.length) {\r\n enabled = !!value;\r\n }\r\n return enabled;\r\n };\r\n\r\n\r\n /* Design notes on the default implementation for SCE.\r\n *\r\n * The API contract for the SCE delegate\r\n * -------------------------------------\r\n * The SCE delegate object must provide the following 3 methods:\r\n *\r\n * - trustAs(contextEnum, value)\r\n * This method is used to tell the SCE service that the provided value is OK to use in the\r\n * contexts specified by contextEnum. It must return an object that will be accepted by\r\n * getTrusted() for a compatible contextEnum and return this value.\r\n *\r\n * - valueOf(value)\r\n * For values that were not produced by trustAs(), return them as is. For values that were\r\n * produced by trustAs(), return the corresponding input value to trustAs. Basically, if\r\n * trustAs is wrapping the given values into some type, this operation unwraps it when given\r\n * such a value.\r\n *\r\n * - getTrusted(contextEnum, value)\r\n * This function should return the a value that is safe to use in the context specified by\r\n * contextEnum or throw and exception otherwise.\r\n *\r\n * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be\r\n * opaque or wrapped in some holder object. That happens to be an implementation detail. For\r\n * instance, an implementation could maintain a registry of all trusted objects by context. In\r\n * such a case, trustAs() would return the same object that was passed in. getTrusted() would\r\n * return the same object passed in if it was found in the registry under a compatible context or\r\n * throw an exception otherwise. An implementation might only wrap values some of the time based\r\n * on some criteria. getTrusted() might return a value and not throw an exception for special\r\n * constants or objects even if not wrapped. All such implementations fulfill this contract.\r\n *\r\n *\r\n * A note on the inheritance model for SCE contexts\r\n * ------------------------------------------------\r\n * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This\r\n * is purely an implementation details.\r\n *\r\n * The contract is simply this:\r\n *\r\n * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)\r\n * will also succeed.\r\n *\r\n * Inheritance happens to capture this in a natural way. In some future, we\r\n * may not use inheritance anymore. That is OK because no code outside of\r\n * sce.js and sceSpecs.js would need to be aware of this detail.\r\n */\r\n\r\n this.$get = ['$parse', '$sceDelegate', function(\r\n $parse, $sceDelegate) {\r\n // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow\r\n // the \"expression(javascript expression)\" syntax which is insecure.\r\n if (enabled && msie < 8) {\r\n throw $sceMinErr('iequirks',\r\n 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +\r\n 'mode. You can fix this by adding the text to the top of your HTML ' +\r\n 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');\r\n }\r\n\r\n var sce = shallowCopy(SCE_CONTEXTS);\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $sce#isEnabled\r\n * @kind function\r\n *\r\n * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you\r\n * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.\r\n *\r\n * @description\r\n * Returns a boolean indicating if SCE is enabled.\r\n */\r\n sce.isEnabled = function() {\r\n return enabled;\r\n };\r\n sce.trustAs = $sceDelegate.trustAs;\r\n sce.getTrusted = $sceDelegate.getTrusted;\r\n sce.valueOf = $sceDelegate.valueOf;\r\n\r\n if (!enabled) {\r\n sce.trustAs = sce.getTrusted = function(type, value) { return value; };\r\n sce.valueOf = identity;\r\n }\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $sce#parseAs\r\n *\r\n * @description\r\n * Converts Angular {@link guide/expression expression} into a function. This is like {@link\r\n * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it\r\n * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,\r\n * *result*)}\r\n *\r\n * @param {string} type The kind of SCE context in which this result will be used.\r\n * @param {string} expression String expression to compile.\r\n * @returns {function(context, locals)} a function which represents the compiled expression:\r\n *\r\n * * `context` – `{object}` – an object against which any expressions embedded in the strings\r\n * are evaluated against (typically a scope object).\r\n * * `locals` – `{object=}` – local variables context object, useful for overriding values in\r\n * `context`.\r\n */\r\n sce.parseAs = function sceParseAs(type, expr) {\r\n var parsed = $parse(expr);\r\n if (parsed.literal && parsed.constant) {\r\n return parsed;\r\n } else {\r\n return $parse(expr, function(value) {\r\n return sce.getTrusted(type, value);\r\n });\r\n }\r\n };\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $sce#trustAs\r\n *\r\n * @description\r\n * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,\r\n * returns an object that is trusted by angular for use in specified strict contextual\r\n * escaping contexts (such as ng-bind-html, ng-include, any src attribute\r\n * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)\r\n * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual\r\n * escaping.\r\n *\r\n * @param {string} type The kind of context in which this value is safe for use. e.g. url,\r\n * resource_url, html, js and css.\r\n * @param {*} value The value that that should be considered trusted/safe.\r\n * @returns {*} A value that can be used to stand in for the provided `value` in places\r\n * where Angular expects a $sce.trustAs() return value.\r\n */\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $sce#trustAsHtml\r\n *\r\n * @description\r\n * Shorthand method. `$sce.trustAsHtml(value)` →\r\n * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}\r\n *\r\n * @param {*} value The value to trustAs.\r\n * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml\r\n * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives\r\n * only accept expressions that are either literal constants or are the\r\n * return value of {@link ng.$sce#trustAs $sce.trustAs}.)\r\n */\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $sce#trustAsUrl\r\n *\r\n * @description\r\n * Shorthand method. `$sce.trustAsUrl(value)` →\r\n * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}\r\n *\r\n * @param {*} value The value to trustAs.\r\n * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl\r\n * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives\r\n * only accept expressions that are either literal constants or are the\r\n * return value of {@link ng.$sce#trustAs $sce.trustAs}.)\r\n */\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $sce#trustAsResourceUrl\r\n *\r\n * @description\r\n * Shorthand method. `$sce.trustAsResourceUrl(value)` →\r\n * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}\r\n *\r\n * @param {*} value The value to trustAs.\r\n * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl\r\n * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives\r\n * only accept expressions that are either literal constants or are the return\r\n * value of {@link ng.$sce#trustAs $sce.trustAs}.)\r\n */\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $sce#trustAsJs\r\n *\r\n * @description\r\n * Shorthand method. `$sce.trustAsJs(value)` →\r\n * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}\r\n *\r\n * @param {*} value The value to trustAs.\r\n * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs\r\n * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives\r\n * only accept expressions that are either literal constants or are the\r\n * return value of {@link ng.$sce#trustAs $sce.trustAs}.)\r\n */\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $sce#getTrusted\r\n *\r\n * @description\r\n * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,\r\n * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the\r\n * originally supplied value if the queried context type is a supertype of the created type.\r\n * If this condition isn't satisfied, throws an exception.\r\n *\r\n * @param {string} type The kind of context in which this value is to be used.\r\n * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}\r\n * call.\r\n * @returns {*} The value the was originally provided to\r\n * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.\r\n * Otherwise, throws an exception.\r\n */\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $sce#getTrustedHtml\r\n *\r\n * @description\r\n * Shorthand method. `$sce.getTrustedHtml(value)` →\r\n * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}\r\n *\r\n * @param {*} value The value to pass to `$sce.getTrusted`.\r\n * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`\r\n */\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $sce#getTrustedCss\r\n *\r\n * @description\r\n * Shorthand method. `$sce.getTrustedCss(value)` →\r\n * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}\r\n *\r\n * @param {*} value The value to pass to `$sce.getTrusted`.\r\n * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`\r\n */\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $sce#getTrustedUrl\r\n *\r\n * @description\r\n * Shorthand method. `$sce.getTrustedUrl(value)` →\r\n * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}\r\n *\r\n * @param {*} value The value to pass to `$sce.getTrusted`.\r\n * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`\r\n */\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $sce#getTrustedResourceUrl\r\n *\r\n * @description\r\n * Shorthand method. `$sce.getTrustedResourceUrl(value)` →\r\n * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}\r\n *\r\n * @param {*} value The value to pass to `$sceDelegate.getTrusted`.\r\n * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`\r\n */\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $sce#getTrustedJs\r\n *\r\n * @description\r\n * Shorthand method. `$sce.getTrustedJs(value)` →\r\n * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}\r\n *\r\n * @param {*} value The value to pass to `$sce.getTrusted`.\r\n * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`\r\n */\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $sce#parseAsHtml\r\n *\r\n * @description\r\n * Shorthand method. `$sce.parseAsHtml(expression string)` →\r\n * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}\r\n *\r\n * @param {string} expression String expression to compile.\r\n * @returns {function(context, locals)} a function which represents the compiled expression:\r\n *\r\n * * `context` – `{object}` – an object against which any expressions embedded in the strings\r\n * are evaluated against (typically a scope object).\r\n * * `locals` – `{object=}` – local variables context object, useful for overriding values in\r\n * `context`.\r\n */\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $sce#parseAsCss\r\n *\r\n * @description\r\n * Shorthand method. `$sce.parseAsCss(value)` →\r\n * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}\r\n *\r\n * @param {string} expression String expression to compile.\r\n * @returns {function(context, locals)} a function which represents the compiled expression:\r\n *\r\n * * `context` – `{object}` – an object against which any expressions embedded in the strings\r\n * are evaluated against (typically a scope object).\r\n * * `locals` – `{object=}` – local variables context object, useful for overriding values in\r\n * `context`.\r\n */\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $sce#parseAsUrl\r\n *\r\n * @description\r\n * Shorthand method. `$sce.parseAsUrl(value)` →\r\n * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}\r\n *\r\n * @param {string} expression String expression to compile.\r\n * @returns {function(context, locals)} a function which represents the compiled expression:\r\n *\r\n * * `context` – `{object}` – an object against which any expressions embedded in the strings\r\n * are evaluated against (typically a scope object).\r\n * * `locals` – `{object=}` – local variables context object, useful for overriding values in\r\n * `context`.\r\n */\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $sce#parseAsResourceUrl\r\n *\r\n * @description\r\n * Shorthand method. `$sce.parseAsResourceUrl(value)` →\r\n * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}\r\n *\r\n * @param {string} expression String expression to compile.\r\n * @returns {function(context, locals)} a function which represents the compiled expression:\r\n *\r\n * * `context` – `{object}` – an object against which any expressions embedded in the strings\r\n * are evaluated against (typically a scope object).\r\n * * `locals` – `{object=}` – local variables context object, useful for overriding values in\r\n * `context`.\r\n */\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $sce#parseAsJs\r\n *\r\n * @description\r\n * Shorthand method. `$sce.parseAsJs(value)` →\r\n * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}\r\n *\r\n * @param {string} expression String expression to compile.\r\n * @returns {function(context, locals)} a function which represents the compiled expression:\r\n *\r\n * * `context` – `{object}` – an object against which any expressions embedded in the strings\r\n * are evaluated against (typically a scope object).\r\n * * `locals` – `{object=}` – local variables context object, useful for overriding values in\r\n * `context`.\r\n */\r\n\r\n // Shorthand delegations.\r\n var parse = sce.parseAs,\r\n getTrusted = sce.getTrusted,\r\n trustAs = sce.trustAs;\r\n\r\n forEach(SCE_CONTEXTS, function(enumValue, name) {\r\n var lName = lowercase(name);\r\n sce[camelCase(\"parse_as_\" + lName)] = function(expr) {\r\n return parse(enumValue, expr);\r\n };\r\n sce[camelCase(\"get_trusted_\" + lName)] = function(value) {\r\n return getTrusted(enumValue, value);\r\n };\r\n sce[camelCase(\"trust_as_\" + lName)] = function(value) {\r\n return trustAs(enumValue, value);\r\n };\r\n });\r\n\r\n return sce;\r\n }];\r\n}\r\n\r\n/**\r\n * !!! This is an undocumented \"private\" service !!!\r\n *\r\n * @name $sniffer\r\n * @requires $window\r\n * @requires $document\r\n *\r\n * @property {boolean} history Does the browser support html5 history api ?\r\n * @property {boolean} transitions Does the browser support CSS transition events ?\r\n * @property {boolean} animations Does the browser support CSS animation events ?\r\n *\r\n * @description\r\n * This is very simple implementation of testing browser's features.\r\n */\r\nfunction $SnifferProvider() {\r\n this.$get = ['$window', '$document', function($window, $document) {\r\n var eventSupport = {},\r\n android =\r\n int((/android (\\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),\r\n boxee = /Boxee/i.test(($window.navigator || {}).userAgent),\r\n document = $document[0] || {},\r\n vendorPrefix,\r\n vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,\r\n bodyStyle = document.body && document.body.style,\r\n transitions = false,\r\n animations = false,\r\n match;\r\n\r\n if (bodyStyle) {\r\n for (var prop in bodyStyle) {\r\n if (match = vendorRegex.exec(prop)) {\r\n vendorPrefix = match[0];\r\n vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);\r\n break;\r\n }\r\n }\r\n\r\n if (!vendorPrefix) {\r\n vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';\r\n }\r\n\r\n transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));\r\n animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));\r\n\r\n if (android && (!transitions || !animations)) {\r\n transitions = isString(document.body.style.webkitTransition);\r\n animations = isString(document.body.style.webkitAnimation);\r\n }\r\n }\r\n\r\n\r\n return {\r\n // Android has history.pushState, but it does not update location correctly\r\n // so let's not use the history API at all.\r\n // http://code.google.com/p/android/issues/detail?id=17471\r\n // https://github.com/angular/angular.js/issues/904\r\n\r\n // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has\r\n // so let's not use the history API also\r\n // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined\r\n // jshint -W018\r\n history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),\r\n // jshint +W018\r\n hasEvent: function(event) {\r\n // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have\r\n // it. In particular the event is not fired when backspace or delete key are pressed or\r\n // when cut operation is performed.\r\n // IE10+ implements 'input' event but it erroneously fires under various situations,\r\n // e.g. when placeholder changes, or a form is focused.\r\n if (event === 'input' && msie <= 11) return false;\r\n\r\n if (isUndefined(eventSupport[event])) {\r\n var divElm = document.createElement('div');\r\n eventSupport[event] = 'on' + event in divElm;\r\n }\r\n\r\n return eventSupport[event];\r\n },\r\n csp: csp(),\r\n vendorPrefix: vendorPrefix,\r\n transitions: transitions,\r\n animations: animations,\r\n android: android\r\n };\r\n }];\r\n}\r\n\r\nvar $compileMinErr = minErr('$compile');\r\n\r\n/**\r\n * @ngdoc service\r\n * @name $templateRequest\r\n *\r\n * @description\r\n * The `$templateRequest` service runs security checks then downloads the provided template using\r\n * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request\r\n * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the\r\n * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the\r\n * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted\r\n * when `tpl` is of type string and `$templateCache` has the matching entry.\r\n *\r\n * @param {string|TrustedResourceUrl} tpl The HTTP request template URL\r\n * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty\r\n *\r\n * @return {Promise} the HTTP Promise for the given.\r\n *\r\n * @property {number} totalPendingRequests total amount of pending template requests being downloaded.\r\n */\r\nfunction $TemplateRequestProvider() {\r\n this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {\r\n function handleRequestFn(tpl, ignoreRequestError) {\r\n handleRequestFn.totalPendingRequests++;\r\n\r\n // We consider the template cache holds only trusted templates, so\r\n // there's no need to go through whitelisting again for keys that already\r\n // are included in there. This also makes Angular accept any script\r\n // directive, no matter its name. However, we still need to unwrap trusted\r\n // types.\r\n if (!isString(tpl) || !$templateCache.get(tpl)) {\r\n tpl = $sce.getTrustedResourceUrl(tpl);\r\n }\r\n\r\n var transformResponse = $http.defaults && $http.defaults.transformResponse;\r\n\r\n if (isArray(transformResponse)) {\r\n transformResponse = transformResponse.filter(function(transformer) {\r\n return transformer !== defaultHttpResponseTransform;\r\n });\r\n } else if (transformResponse === defaultHttpResponseTransform) {\r\n transformResponse = null;\r\n }\r\n\r\n var httpOptions = {\r\n cache: $templateCache,\r\n transformResponse: transformResponse\r\n };\r\n\r\n return $http.get(tpl, httpOptions)\r\n ['finally'](function() {\r\n handleRequestFn.totalPendingRequests--;\r\n })\r\n .then(function(response) {\r\n return response.data;\r\n }, handleError);\r\n\r\n function handleError(resp) {\r\n if (!ignoreRequestError) {\r\n throw $compileMinErr('tpload', 'Failed to load template: {0}', tpl);\r\n }\r\n return $q.reject(resp);\r\n }\r\n }\r\n\r\n handleRequestFn.totalPendingRequests = 0;\r\n\r\n return handleRequestFn;\r\n }];\r\n}\r\n\r\nfunction $$TestabilityProvider() {\r\n this.$get = ['$rootScope', '$browser', '$location',\r\n function($rootScope, $browser, $location) {\r\n\r\n /**\r\n * @name $testability\r\n *\r\n * @description\r\n * The private $$testability service provides a collection of methods for use when debugging\r\n * or by automated test and debugging tools.\r\n */\r\n var testability = {};\r\n\r\n /**\r\n * @name $$testability#findBindings\r\n *\r\n * @description\r\n * Returns an array of elements that are bound (via ng-bind or {{}})\r\n * to expressions matching the input.\r\n *\r\n * @param {Element} element The element root to search from.\r\n * @param {string} expression The binding expression to match.\r\n * @param {boolean} opt_exactMatch If true, only returns exact matches\r\n * for the expression. Filters and whitespace are ignored.\r\n */\r\n testability.findBindings = function(element, expression, opt_exactMatch) {\r\n var bindings = element.getElementsByClassName('ng-binding');\r\n var matches = [];\r\n forEach(bindings, function(binding) {\r\n var dataBinding = angular.element(binding).data('$binding');\r\n if (dataBinding) {\r\n forEach(dataBinding, function(bindingName) {\r\n if (opt_exactMatch) {\r\n var matcher = new RegExp('(^|\\\\s)' + escapeForRegexp(expression) + '(\\\\s|\\\\||$)');\r\n if (matcher.test(bindingName)) {\r\n matches.push(binding);\r\n }\r\n } else {\r\n if (bindingName.indexOf(expression) != -1) {\r\n matches.push(binding);\r\n }\r\n }\r\n });\r\n }\r\n });\r\n return matches;\r\n };\r\n\r\n /**\r\n * @name $$testability#findModels\r\n *\r\n * @description\r\n * Returns an array of elements that are two-way found via ng-model to\r\n * expressions matching the input.\r\n *\r\n * @param {Element} element The element root to search from.\r\n * @param {string} expression The model expression to match.\r\n * @param {boolean} opt_exactMatch If true, only returns exact matches\r\n * for the expression.\r\n */\r\n testability.findModels = function(element, expression, opt_exactMatch) {\r\n var prefixes = ['ng-', 'data-ng-', 'ng\\\\:'];\r\n for (var p = 0; p < prefixes.length; ++p) {\r\n var attributeEquals = opt_exactMatch ? '=' : '*=';\r\n var selector = '[' + prefixes[p] + 'model' + attributeEquals + '\"' + expression + '\"]';\r\n var elements = element.querySelectorAll(selector);\r\n if (elements.length) {\r\n return elements;\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * @name $$testability#getLocation\r\n *\r\n * @description\r\n * Shortcut for getting the location in a browser agnostic way. Returns\r\n * the path, search, and hash. (e.g. /path?a=b#hash)\r\n */\r\n testability.getLocation = function() {\r\n return $location.url();\r\n };\r\n\r\n /**\r\n * @name $$testability#setLocation\r\n *\r\n * @description\r\n * Shortcut for navigating to a location without doing a full page reload.\r\n *\r\n * @param {string} url The location url (path, search and hash,\r\n * e.g. /path?a=b#hash) to go to.\r\n */\r\n testability.setLocation = function(url) {\r\n if (url !== $location.url()) {\r\n $location.url(url);\r\n $rootScope.$digest();\r\n }\r\n };\r\n\r\n /**\r\n * @name $$testability#whenStable\r\n *\r\n * @description\r\n * Calls the callback when $timeout and $http requests are completed.\r\n *\r\n * @param {function} callback\r\n */\r\n testability.whenStable = function(callback) {\r\n $browser.notifyWhenNoOutstandingRequests(callback);\r\n };\r\n\r\n return testability;\r\n }];\r\n}\r\n\r\nfunction $TimeoutProvider() {\r\n this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',\r\n function($rootScope, $browser, $q, $$q, $exceptionHandler) {\r\n var deferreds = {};\r\n\r\n\r\n /**\r\n * @ngdoc service\r\n * @name $timeout\r\n *\r\n * @description\r\n * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch\r\n * block and delegates any exceptions to\r\n * {@link ng.$exceptionHandler $exceptionHandler} service.\r\n *\r\n * The return value of registering a timeout function is a promise, which will be resolved when\r\n * the timeout is reached and the timeout function is executed.\r\n *\r\n * To cancel a timeout request, call `$timeout.cancel(promise)`.\r\n *\r\n * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to\r\n * synchronously flush the queue of deferred functions.\r\n *\r\n * @param {function()} fn A function, whose execution should be delayed.\r\n * @param {number=} [delay=0] Delay in milliseconds.\r\n * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise\r\n * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.\r\n * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this\r\n * promise will be resolved with is the return value of the `fn` function.\r\n *\r\n */\r\n function timeout(fn, delay, invokeApply) {\r\n var skipApply = (isDefined(invokeApply) && !invokeApply),\r\n deferred = (skipApply ? $$q : $q).defer(),\r\n promise = deferred.promise,\r\n timeoutId;\r\n\r\n timeoutId = $browser.defer(function() {\r\n try {\r\n deferred.resolve(fn());\r\n } catch (e) {\r\n deferred.reject(e);\r\n $exceptionHandler(e);\r\n }\r\n finally {\r\n delete deferreds[promise.$$timeoutId];\r\n }\r\n\r\n if (!skipApply) $rootScope.$apply();\r\n }, delay);\r\n\r\n promise.$$timeoutId = timeoutId;\r\n deferreds[timeoutId] = deferred;\r\n\r\n return promise;\r\n }\r\n\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $timeout#cancel\r\n *\r\n * @description\r\n * Cancels a task associated with the `promise`. As a result of this, the promise will be\r\n * resolved with a rejection.\r\n *\r\n * @param {Promise=} promise Promise returned by the `$timeout` function.\r\n * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully\r\n * canceled.\r\n */\r\n timeout.cancel = function(promise) {\r\n if (promise && promise.$$timeoutId in deferreds) {\r\n deferreds[promise.$$timeoutId].reject('canceled');\r\n delete deferreds[promise.$$timeoutId];\r\n return $browser.defer.cancel(promise.$$timeoutId);\r\n }\r\n return false;\r\n };\r\n\r\n return timeout;\r\n }];\r\n}\r\n\r\n// NOTE: The usage of window and document instead of $window and $document here is\r\n// deliberate. This service depends on the specific behavior of anchor nodes created by the\r\n// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and\r\n// cause us to break tests. In addition, when the browser resolves a URL for XHR, it\r\n// doesn't know about mocked locations and resolves URLs to the real document - which is\r\n// exactly the behavior needed here. There is little value is mocking these out for this\r\n// service.\r\nvar urlParsingNode = document.createElement(\"a\");\r\nvar originUrl = urlResolve(window.location.href);\r\n\r\n\r\n/**\r\n *\r\n * Implementation Notes for non-IE browsers\r\n * ----------------------------------------\r\n * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,\r\n * results both in the normalizing and parsing of the URL. Normalizing means that a relative\r\n * URL will be resolved into an absolute URL in the context of the application document.\r\n * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related\r\n * properties are all populated to reflect the normalized URL. This approach has wide\r\n * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See\r\n * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html\r\n *\r\n * Implementation Notes for IE\r\n * ---------------------------\r\n * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other\r\n * browsers. However, the parsed components will not be set if the URL assigned did not specify\r\n * them. (e.g. if you assign a.href = \"foo\", then a.protocol, a.host, etc. will be empty.) We\r\n * work around that by performing the parsing in a 2nd step by taking a previously normalized\r\n * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the\r\n * properties such as protocol, hostname, port, etc.\r\n *\r\n * References:\r\n * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement\r\n * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html\r\n * http://url.spec.whatwg.org/#urlutils\r\n * https://github.com/angular/angular.js/pull/2902\r\n * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/\r\n *\r\n * @kind function\r\n * @param {string} url The URL to be parsed.\r\n * @description Normalizes and parses a URL.\r\n * @returns {object} Returns the normalized URL as a dictionary.\r\n *\r\n * | member name | Description |\r\n * |---------------|----------------|\r\n * | href | A normalized version of the provided URL if it was not an absolute URL |\r\n * | protocol | The protocol including the trailing colon |\r\n * | host | The host and port (if the port is non-default) of the normalizedUrl |\r\n * | search | The search params, minus the question mark |\r\n * | hash | The hash string, minus the hash symbol\r\n * | hostname | The hostname\r\n * | port | The port, without \":\"\r\n * | pathname | The pathname, beginning with \"/\"\r\n *\r\n */\r\nfunction urlResolve(url) {\r\n var href = url;\r\n\r\n if (msie) {\r\n // Normalize before parse. Refer Implementation Notes on why this is\r\n // done in two steps on IE.\r\n urlParsingNode.setAttribute(\"href\", href);\r\n href = urlParsingNode.href;\r\n }\r\n\r\n urlParsingNode.setAttribute('href', href);\r\n\r\n // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils\r\n return {\r\n href: urlParsingNode.href,\r\n protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',\r\n host: urlParsingNode.host,\r\n search: urlParsingNode.search ? urlParsingNode.search.replace(/^\\?/, '') : '',\r\n hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',\r\n hostname: urlParsingNode.hostname,\r\n port: urlParsingNode.port,\r\n pathname: (urlParsingNode.pathname.charAt(0) === '/')\r\n ? urlParsingNode.pathname\r\n : '/' + urlParsingNode.pathname\r\n };\r\n}\r\n\r\n/**\r\n * Parse a request URL and determine whether this is a same-origin request as the application document.\r\n *\r\n * @param {string|object} requestUrl The url of the request as a string that will be resolved\r\n * or a parsed URL object.\r\n * @returns {boolean} Whether the request is for the same origin as the application document.\r\n */\r\nfunction urlIsSameOrigin(requestUrl) {\r\n var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;\r\n return (parsed.protocol === originUrl.protocol &&\r\n parsed.host === originUrl.host);\r\n}\r\n\r\n/**\r\n * @ngdoc service\r\n * @name $window\r\n *\r\n * @description\r\n * A reference to the browser's `window` object. While `window`\r\n * is globally available in JavaScript, it causes testability problems, because\r\n * it is a global variable. In angular we always refer to it through the\r\n * `$window` service, so it may be overridden, removed or mocked for testing.\r\n *\r\n * Expressions, like the one defined for the `ngClick` directive in the example\r\n * below, are evaluated with respect to the current scope. Therefore, there is\r\n * no risk of inadvertently coding in a dependency on a global value in such an\r\n * expression.\r\n *\r\n * @example\r\n \r\n \r\n \r\n
    \r\n \r\n \r\n
    \r\n
    \r\n \r\n it('should display the greeting in the input box', function() {\r\n element(by.model('greeting')).sendKeys('Hello, E2E Tests');\r\n // If we click the button it will block the test runner\r\n // element(':button').click();\r\n });\r\n \r\n
    \r\n */\r\nfunction $WindowProvider() {\r\n this.$get = valueFn(window);\r\n}\r\n\r\n/* global currencyFilter: true,\r\n dateFilter: true,\r\n filterFilter: true,\r\n jsonFilter: true,\r\n limitToFilter: true,\r\n lowercaseFilter: true,\r\n numberFilter: true,\r\n orderByFilter: true,\r\n uppercaseFilter: true,\r\n */\r\n\r\n/**\r\n * @ngdoc provider\r\n * @name $filterProvider\r\n * @description\r\n *\r\n * Filters are just functions which transform input to an output. However filters need to be\r\n * Dependency Injected. To achieve this a filter definition consists of a factory function which is\r\n * annotated with dependencies and is responsible for creating a filter function.\r\n *\r\n *
    \r\n * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.\r\n * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace\r\n * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores\r\n * (`myapp_subsection_filterx`).\r\n *
    \r\n *\r\n * ```js\r\n * // Filter registration\r\n * function MyModule($provide, $filterProvider) {\r\n * // create a service to demonstrate injection (not always needed)\r\n * $provide.value('greet', function(name){\r\n * return 'Hello ' + name + '!';\r\n * });\r\n *\r\n * // register a filter factory which uses the\r\n * // greet service to demonstrate DI.\r\n * $filterProvider.register('greet', function(greet){\r\n * // return the filter function which uses the greet service\r\n * // to generate salutation\r\n * return function(text) {\r\n * // filters need to be forgiving so check input validity\r\n * return text && greet(text) || text;\r\n * };\r\n * });\r\n * }\r\n * ```\r\n *\r\n * The filter function is registered with the `$injector` under the filter name suffix with\r\n * `Filter`.\r\n *\r\n * ```js\r\n * it('should be the same instance', inject(\r\n * function($filterProvider) {\r\n * $filterProvider.register('reverse', function(){\r\n * return ...;\r\n * });\r\n * },\r\n * function($filter, reverseFilter) {\r\n * expect($filter('reverse')).toBe(reverseFilter);\r\n * });\r\n * ```\r\n *\r\n *\r\n * For more information about how angular filters work, and how to create your own filters, see\r\n * {@link guide/filter Filters} in the Angular Developer Guide.\r\n */\r\n\r\n/**\r\n * @ngdoc service\r\n * @name $filter\r\n * @kind function\r\n * @description\r\n * Filters are used for formatting data displayed to the user.\r\n *\r\n * The general syntax in templates is as follows:\r\n *\r\n * {{ expression [| filter_name[:parameter_value] ... ] }}\r\n *\r\n * @param {String} name Name of the filter function to retrieve\r\n * @return {Function} the filter function\r\n * @example\r\n \r\n \r\n
    \r\n

    {{ originalText }}

    \r\n

    {{ filteredText }}

    \r\n
    \r\n
    \r\n\r\n \r\n angular.module('filterExample', [])\r\n .controller('MainCtrl', function($scope, $filter) {\r\n $scope.originalText = 'hello';\r\n $scope.filteredText = $filter('uppercase')($scope.originalText);\r\n });\r\n \r\n
    \r\n */\r\n$FilterProvider.$inject = ['$provide'];\r\nfunction $FilterProvider($provide) {\r\n var suffix = 'Filter';\r\n\r\n /**\r\n * @ngdoc method\r\n * @name $filterProvider#register\r\n * @param {string|Object} name Name of the filter function, or an object map of filters where\r\n * the keys are the filter names and the values are the filter factories.\r\n *\r\n *
    \r\n * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.\r\n * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace\r\n * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores\r\n * (`myapp_subsection_filterx`).\r\n *
    \r\n * @returns {Object} Registered filter instance, or if a map of filters was provided then a map\r\n * of the registered filter instances.\r\n */\r\n function register(name, factory) {\r\n if (isObject(name)) {\r\n var filters = {};\r\n forEach(name, function(filter, key) {\r\n filters[key] = register(key, filter);\r\n });\r\n return filters;\r\n } else {\r\n return $provide.factory(name + suffix, factory);\r\n }\r\n }\r\n this.register = register;\r\n\r\n this.$get = ['$injector', function($injector) {\r\n return function(name) {\r\n return $injector.get(name + suffix);\r\n };\r\n }];\r\n\r\n ////////////////////////////////////////\r\n\r\n /* global\r\n currencyFilter: false,\r\n dateFilter: false,\r\n filterFilter: false,\r\n jsonFilter: false,\r\n limitToFilter: false,\r\n lowercaseFilter: false,\r\n numberFilter: false,\r\n orderByFilter: false,\r\n uppercaseFilter: false,\r\n */\r\n\r\n register('currency', currencyFilter);\r\n register('date', dateFilter);\r\n register('filter', filterFilter);\r\n register('json', jsonFilter);\r\n register('limitTo', limitToFilter);\r\n register('lowercase', lowercaseFilter);\r\n register('number', numberFilter);\r\n register('orderBy', orderByFilter);\r\n register('uppercase', uppercaseFilter);\r\n}\r\n\r\n/**\r\n * @ngdoc filter\r\n * @name filter\r\n * @kind function\r\n *\r\n * @description\r\n * Selects a subset of items from `array` and returns it as a new array.\r\n *\r\n * @param {Array} array The source array.\r\n * @param {string|Object|function()} expression The predicate to be used for selecting items from\r\n * `array`.\r\n *\r\n * Can be one of:\r\n *\r\n * - `string`: The string is used for matching against the contents of the `array`. All strings or\r\n * objects with string properties in `array` that match this string will be returned. This also\r\n * applies to nested object properties.\r\n * The predicate can be negated by prefixing the string with `!`.\r\n *\r\n * - `Object`: A pattern object can be used to filter specific properties on objects contained\r\n * by `array`. For example `{name:\"M\", phone:\"1\"}` predicate will return an array of items\r\n * which have property `name` containing \"M\" and property `phone` containing \"1\". A special\r\n * property name `$` can be used (as in `{$:\"text\"}`) to accept a match against any\r\n * property of the object or its nested object properties. That's equivalent to the simple\r\n * substring match with a `string` as described above. The predicate can be negated by prefixing\r\n * the string with `!`.\r\n * For example `{name: \"!M\"}` predicate will return an array of items which have property `name`\r\n * not containing \"M\".\r\n *\r\n * Note that a named property will match properties on the same level only, while the special\r\n * `$` property will match properties on the same level or deeper. E.g. an array item like\r\n * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but\r\n * **will** be matched by `{$: 'John'}`.\r\n *\r\n * - `function(value, index)`: A predicate function can be used to write arbitrary filters. The\r\n * function is called for each element of `array`. The final result is an array of those\r\n * elements that the predicate returned true for.\r\n *\r\n * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in\r\n * determining if the expected value (from the filter expression) and actual value (from\r\n * the object in the array) should be considered a match.\r\n *\r\n * Can be one of:\r\n *\r\n * - `function(actual, expected)`:\r\n * The function will be given the object value and the predicate value to compare and\r\n * should return true if both values should be considered equal.\r\n *\r\n * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.\r\n * This is essentially strict comparison of expected and actual.\r\n *\r\n * - `false|undefined`: A short hand for a function which will look for a substring match in case\r\n * insensitive way.\r\n *\r\n * @example\r\n \r\n \r\n
    \r\n\r\n Search: \r\n \r\n \r\n \r\n \r\n \r\n \r\n
    NamePhone
    {{friend.name}}{{friend.phone}}
    \r\n
    \r\n Any:
    \r\n Name only
    \r\n Phone only
    \r\n Equality
    \r\n \r\n \r\n \r\n \r\n \r\n \r\n
    NamePhone
    {{friendObj.name}}{{friendObj.phone}}
    \r\n
    \r\n \r\n var expectFriendNames = function(expectedNames, key) {\r\n element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {\r\n arr.forEach(function(wd, i) {\r\n expect(wd.getText()).toMatch(expectedNames[i]);\r\n });\r\n });\r\n };\r\n\r\n it('should search across all fields when filtering with a string', function() {\r\n var searchText = element(by.model('searchText'));\r\n searchText.clear();\r\n searchText.sendKeys('m');\r\n expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');\r\n\r\n searchText.clear();\r\n searchText.sendKeys('76');\r\n expectFriendNames(['John', 'Julie'], 'friend');\r\n });\r\n\r\n it('should search in specific fields when filtering with a predicate object', function() {\r\n var searchAny = element(by.model('search.$'));\r\n searchAny.clear();\r\n searchAny.sendKeys('i');\r\n expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');\r\n });\r\n it('should use a equal comparison when comparator is true', function() {\r\n var searchName = element(by.model('search.name'));\r\n var strict = element(by.model('strict'));\r\n searchName.clear();\r\n searchName.sendKeys('Julie');\r\n strict.click();\r\n expectFriendNames(['Julie'], 'friendObj');\r\n });\r\n \r\n
    \r\n */\r\nfunction filterFilter() {\r\n return function(array, expression, comparator) {\r\n if (!isArray(array)) return array;\r\n\r\n var expressionType = (expression !== null) ? typeof expression : 'null';\r\n var predicateFn;\r\n var matchAgainstAnyProp;\r\n\r\n switch (expressionType) {\r\n case 'function':\r\n predicateFn = expression;\r\n break;\r\n case 'boolean':\r\n case 'null':\r\n case 'number':\r\n case 'string':\r\n matchAgainstAnyProp = true;\r\n //jshint -W086\r\n case 'object':\r\n //jshint +W086\r\n predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);\r\n break;\r\n default:\r\n return array;\r\n }\r\n\r\n return array.filter(predicateFn);\r\n };\r\n}\r\n\r\n// Helper functions for `filterFilter`\r\nfunction createPredicateFn(expression, comparator, matchAgainstAnyProp) {\r\n var shouldMatchPrimitives = isObject(expression) && ('$' in expression);\r\n var predicateFn;\r\n\r\n if (comparator === true) {\r\n comparator = equals;\r\n } else if (!isFunction(comparator)) {\r\n comparator = function(actual, expected) {\r\n if (isUndefined(actual)) {\r\n // No substring matching against `undefined`\r\n return false;\r\n }\r\n if ((actual === null) || (expected === null)) {\r\n // No substring matching against `null`; only match against `null`\r\n return actual === expected;\r\n }\r\n if (isObject(actual) || isObject(expected)) {\r\n // Prevent an object to be considered equal to a string like `'[object'`\r\n return false;\r\n }\r\n\r\n actual = lowercase('' + actual);\r\n expected = lowercase('' + expected);\r\n return actual.indexOf(expected) !== -1;\r\n };\r\n }\r\n\r\n predicateFn = function(item) {\r\n if (shouldMatchPrimitives && !isObject(item)) {\r\n return deepCompare(item, expression.$, comparator, false);\r\n }\r\n return deepCompare(item, expression, comparator, matchAgainstAnyProp);\r\n };\r\n\r\n return predicateFn;\r\n}\r\n\r\nfunction deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {\r\n var actualType = (actual !== null) ? typeof actual : 'null';\r\n var expectedType = (expected !== null) ? typeof expected : 'null';\r\n\r\n if ((expectedType === 'string') && (expected.charAt(0) === '!')) {\r\n return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);\r\n } else if (isArray(actual)) {\r\n // In case `actual` is an array, consider it a match\r\n // if ANY of it's items matches `expected`\r\n return actual.some(function(item) {\r\n return deepCompare(item, expected, comparator, matchAgainstAnyProp);\r\n });\r\n }\r\n\r\n switch (actualType) {\r\n case 'object':\r\n var key;\r\n if (matchAgainstAnyProp) {\r\n for (key in actual) {\r\n if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {\r\n return true;\r\n }\r\n }\r\n return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);\r\n } else if (expectedType === 'object') {\r\n for (key in expected) {\r\n var expectedVal = expected[key];\r\n if (isFunction(expectedVal) || isUndefined(expectedVal)) {\r\n continue;\r\n }\r\n\r\n var matchAnyProperty = key === '$';\r\n var actualVal = matchAnyProperty ? actual : actual[key];\r\n if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n } else {\r\n return comparator(actual, expected);\r\n }\r\n break;\r\n case 'function':\r\n return false;\r\n default:\r\n return comparator(actual, expected);\r\n }\r\n}\r\n\r\n/**\r\n * @ngdoc filter\r\n * @name currency\r\n * @kind function\r\n *\r\n * @description\r\n * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default\r\n * symbol for current locale is used.\r\n *\r\n * @param {number} amount Input to filter.\r\n * @param {string=} symbol Currency symbol or identifier to be displayed.\r\n * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale\r\n * @returns {string} Formatted number.\r\n *\r\n *\r\n * @example\r\n \r\n \r\n \r\n
    \r\n
    \r\n default currency symbol ($): {{amount | currency}}
    \r\n custom currency identifier (USD$): {{amount | currency:\"USD$\"}}\r\n no fractions (0): {{amount | currency:\"USD$\":0}}\r\n
    \r\n
    \r\n \r\n it('should init with 1234.56', function() {\r\n expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');\r\n expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');\r\n expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');\r\n });\r\n it('should update', function() {\r\n if (browser.params.browser == 'safari') {\r\n // Safari does not understand the minus key. See\r\n // https://github.com/angular/protractor/issues/481\r\n return;\r\n }\r\n element(by.model('amount')).clear();\r\n element(by.model('amount')).sendKeys('-1234');\r\n expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)');\r\n expect(element(by.id('currency-custom')).getText()).toBe('(USD$1,234.00)');\r\n expect(element(by.id('currency-no-fractions')).getText()).toBe('(USD$1,234)');\r\n });\r\n \r\n
    \r\n */\r\ncurrencyFilter.$inject = ['$locale'];\r\nfunction currencyFilter($locale) {\r\n var formats = $locale.NUMBER_FORMATS;\r\n return function(amount, currencySymbol, fractionSize) {\r\n if (isUndefined(currencySymbol)) {\r\n currencySymbol = formats.CURRENCY_SYM;\r\n }\r\n\r\n if (isUndefined(fractionSize)) {\r\n fractionSize = formats.PATTERNS[1].maxFrac;\r\n }\r\n\r\n // if null or undefined pass it through\r\n return (amount == null)\r\n ? amount\r\n : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).\r\n replace(/\\u00A4/g, currencySymbol);\r\n };\r\n}\r\n\r\n/**\r\n * @ngdoc filter\r\n * @name number\r\n * @kind function\r\n *\r\n * @description\r\n * Formats a number as text.\r\n *\r\n * If the input is null or undefined, it will just be returned.\r\n * If the input is infinite (Infinity/-Infinity) the Infinity symbol '∞' is returned.\r\n * If the input is not a number an empty string is returned.\r\n *\r\n * @param {number|string} number Number to format.\r\n * @param {(number|string)=} fractionSize Number of decimal places to round the number to.\r\n * If this is not provided then the fraction size is computed from the current locale's number\r\n * formatting pattern. In the case of the default locale, it will be 3.\r\n * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.\r\n *\r\n * @example\r\n \r\n \r\n \r\n
    \r\n Enter number:
    \r\n Default formatting: {{val | number}}
    \r\n No fractions: {{val | number:0}}
    \r\n Negative number: {{-val | number:4}}\r\n
    \r\n
    \r\n \r\n it('should format numbers', function() {\r\n expect(element(by.id('number-default')).getText()).toBe('1,234.568');\r\n expect(element(by.binding('val | number:0')).getText()).toBe('1,235');\r\n expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');\r\n });\r\n\r\n it('should update', function() {\r\n element(by.model('val')).clear();\r\n element(by.model('val')).sendKeys('3374.333');\r\n expect(element(by.id('number-default')).getText()).toBe('3,374.333');\r\n expect(element(by.binding('val | number:0')).getText()).toBe('3,374');\r\n expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');\r\n });\r\n \r\n
    \r\n */\r\n\r\n\r\nnumberFilter.$inject = ['$locale'];\r\nfunction numberFilter($locale) {\r\n var formats = $locale.NUMBER_FORMATS;\r\n return function(number, fractionSize) {\r\n\r\n // if null or undefined pass it through\r\n return (number == null)\r\n ? number\r\n : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,\r\n fractionSize);\r\n };\r\n}\r\n\r\nvar DECIMAL_SEP = '.';\r\nfunction formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {\r\n if (!isFinite(number) || isObject(number)) return '';\r\n\r\n var isNegative = number < 0;\r\n number = Math.abs(number);\r\n var numStr = number + '',\r\n formatedText = '',\r\n parts = [];\r\n\r\n var hasExponent = false;\r\n if (numStr.indexOf('e') !== -1) {\r\n var match = numStr.match(/([\\d\\.]+)e(-?)(\\d+)/);\r\n if (match && match[2] == '-' && match[3] > fractionSize + 1) {\r\n number = 0;\r\n } else {\r\n formatedText = numStr;\r\n hasExponent = true;\r\n }\r\n }\r\n\r\n if (!hasExponent) {\r\n var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;\r\n\r\n // determine fractionSize if it is not specified\r\n if (isUndefined(fractionSize)) {\r\n fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);\r\n }\r\n\r\n // safely round numbers in JS without hitting imprecisions of floating-point arithmetics\r\n // inspired by:\r\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round\r\n number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);\r\n\r\n var fraction = ('' + number).split(DECIMAL_SEP);\r\n var whole = fraction[0];\r\n fraction = fraction[1] || '';\r\n\r\n var i, pos = 0,\r\n lgroup = pattern.lgSize,\r\n group = pattern.gSize;\r\n\r\n if (whole.length >= (lgroup + group)) {\r\n pos = whole.length - lgroup;\r\n for (i = 0; i < pos; i++) {\r\n if ((pos - i) % group === 0 && i !== 0) {\r\n formatedText += groupSep;\r\n }\r\n formatedText += whole.charAt(i);\r\n }\r\n }\r\n\r\n for (i = pos; i < whole.length; i++) {\r\n if ((whole.length - i) % lgroup === 0 && i !== 0) {\r\n formatedText += groupSep;\r\n }\r\n formatedText += whole.charAt(i);\r\n }\r\n\r\n // format fraction part.\r\n while (fraction.length < fractionSize) {\r\n fraction += '0';\r\n }\r\n\r\n if (fractionSize && fractionSize !== \"0\") formatedText += decimalSep + fraction.substr(0, fractionSize);\r\n } else {\r\n if (fractionSize > 0 && number < 1) {\r\n formatedText = number.toFixed(fractionSize);\r\n number = parseFloat(formatedText);\r\n }\r\n }\r\n\r\n if (number === 0) {\r\n isNegative = false;\r\n }\r\n\r\n parts.push(isNegative ? pattern.negPre : pattern.posPre,\r\n formatedText,\r\n isNegative ? pattern.negSuf : pattern.posSuf);\r\n return parts.join('');\r\n}\r\n\r\nfunction padNumber(num, digits, trim) {\r\n var neg = '';\r\n if (num < 0) {\r\n neg = '-';\r\n num = -num;\r\n }\r\n num = '' + num;\r\n while (num.length < digits) num = '0' + num;\r\n if (trim)\r\n num = num.substr(num.length - digits);\r\n return neg + num;\r\n}\r\n\r\n\r\nfunction dateGetter(name, size, offset, trim) {\r\n offset = offset || 0;\r\n return function(date) {\r\n var value = date['get' + name]();\r\n if (offset > 0 || value > -offset)\r\n value += offset;\r\n if (value === 0 && offset == -12) value = 12;\r\n return padNumber(value, size, trim);\r\n };\r\n}\r\n\r\nfunction dateStrGetter(name, shortForm) {\r\n return function(date, formats) {\r\n var value = date['get' + name]();\r\n var get = uppercase(shortForm ? ('SHORT' + name) : name);\r\n\r\n return formats[get][value];\r\n };\r\n}\r\n\r\nfunction timeZoneGetter(date) {\r\n var zone = -1 * date.getTimezoneOffset();\r\n var paddedZone = (zone >= 0) ? \"+\" : \"\";\r\n\r\n paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +\r\n padNumber(Math.abs(zone % 60), 2);\r\n\r\n return paddedZone;\r\n}\r\n\r\nfunction getFirstThursdayOfYear(year) {\r\n // 0 = index of January\r\n var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();\r\n // 4 = index of Thursday (+1 to account for 1st = 5)\r\n // 11 = index of *next* Thursday (+1 account for 1st = 12)\r\n return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);\r\n}\r\n\r\nfunction getThursdayThisWeek(datetime) {\r\n return new Date(datetime.getFullYear(), datetime.getMonth(),\r\n // 4 = index of Thursday\r\n datetime.getDate() + (4 - datetime.getDay()));\r\n}\r\n\r\nfunction weekGetter(size) {\r\n return function(date) {\r\n var firstThurs = getFirstThursdayOfYear(date.getFullYear()),\r\n thisThurs = getThursdayThisWeek(date);\r\n\r\n var diff = +thisThurs - +firstThurs,\r\n result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week\r\n\r\n return padNumber(result, size);\r\n };\r\n}\r\n\r\nfunction ampmGetter(date, formats) {\r\n return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];\r\n}\r\n\r\nfunction eraGetter(date, formats) {\r\n return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];\r\n}\r\n\r\nfunction longEraGetter(date, formats) {\r\n return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];\r\n}\r\n\r\nvar DATE_FORMATS = {\r\n yyyy: dateGetter('FullYear', 4),\r\n yy: dateGetter('FullYear', 2, 0, true),\r\n y: dateGetter('FullYear', 1),\r\n MMMM: dateStrGetter('Month'),\r\n MMM: dateStrGetter('Month', true),\r\n MM: dateGetter('Month', 2, 1),\r\n M: dateGetter('Month', 1, 1),\r\n dd: dateGetter('Date', 2),\r\n d: dateGetter('Date', 1),\r\n HH: dateGetter('Hours', 2),\r\n H: dateGetter('Hours', 1),\r\n hh: dateGetter('Hours', 2, -12),\r\n h: dateGetter('Hours', 1, -12),\r\n mm: dateGetter('Minutes', 2),\r\n m: dateGetter('Minutes', 1),\r\n ss: dateGetter('Seconds', 2),\r\n s: dateGetter('Seconds', 1),\r\n // while ISO 8601 requires fractions to be prefixed with `.` or `,`\r\n // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions\r\n sss: dateGetter('Milliseconds', 3),\r\n EEEE: dateStrGetter('Day'),\r\n EEE: dateStrGetter('Day', true),\r\n a: ampmGetter,\r\n Z: timeZoneGetter,\r\n ww: weekGetter(2),\r\n w: weekGetter(1),\r\n G: eraGetter,\r\n GG: eraGetter,\r\n GGG: eraGetter,\r\n GGGG: longEraGetter\r\n};\r\n\r\nvar DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,\r\n NUMBER_STRING = /^\\-?\\d+$/;\r\n\r\n/**\r\n * @ngdoc filter\r\n * @name date\r\n * @kind function\r\n *\r\n * @description\r\n * Formats `date` to a string based on the requested `format`.\r\n *\r\n * `format` string can be composed of the following elements:\r\n *\r\n * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)\r\n * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)\r\n * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)\r\n * * `'MMMM'`: Month in year (January-December)\r\n * * `'MMM'`: Month in year (Jan-Dec)\r\n * * `'MM'`: Month in year, padded (01-12)\r\n * * `'M'`: Month in year (1-12)\r\n * * `'dd'`: Day in month, padded (01-31)\r\n * * `'d'`: Day in month (1-31)\r\n * * `'EEEE'`: Day in Week,(Sunday-Saturday)\r\n * * `'EEE'`: Day in Week, (Sun-Sat)\r\n * * `'HH'`: Hour in day, padded (00-23)\r\n * * `'H'`: Hour in day (0-23)\r\n * * `'hh'`: Hour in AM/PM, padded (01-12)\r\n * * `'h'`: Hour in AM/PM, (1-12)\r\n * * `'mm'`: Minute in hour, padded (00-59)\r\n * * `'m'`: Minute in hour (0-59)\r\n * * `'ss'`: Second in minute, padded (00-59)\r\n * * `'s'`: Second in minute (0-59)\r\n * * `'sss'`: Millisecond in second, padded (000-999)\r\n * * `'a'`: AM/PM marker\r\n * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)\r\n * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year\r\n * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year\r\n * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')\r\n * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')\r\n *\r\n * `format` string can also be one of the following predefined\r\n * {@link guide/i18n localizable formats}:\r\n *\r\n * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale\r\n * (e.g. Sep 3, 2010 12:05:08 PM)\r\n * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)\r\n * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale\r\n * (e.g. Friday, September 3, 2010)\r\n * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)\r\n * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)\r\n * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)\r\n * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)\r\n * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)\r\n *\r\n * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.\r\n * `\"h 'in the morning'\"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence\r\n * (e.g. `\"h 'o''clock'\"`).\r\n *\r\n * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or\r\n * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its\r\n * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is\r\n * specified in the string input, the time is considered to be in the local timezone.\r\n * @param {string=} format Formatting rules (see Description). If not specified,\r\n * `mediumDate` is used.\r\n * @param {string=} timezone Timezone to be used for formatting. Right now, only `'UTC'` is supported.\r\n * If not specified, the timezone of the browser will be used.\r\n * @returns {string} Formatted string or the input if input is not recognized as date/millis.\r\n *\r\n * @example\r\n \r\n \r\n {{1288323623006 | date:'medium'}}:\r\n {{1288323623006 | date:'medium'}}
    \r\n {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}:\r\n {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}
    \r\n {{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}:\r\n {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}
    \r\n {{1288323623006 | date:\"MM/dd/yyyy 'at' h:mma\"}}:\r\n {{'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"}}
    \r\n
    \r\n \r\n it('should format date', function() {\r\n expect(element(by.binding(\"1288323623006 | date:'medium'\")).getText()).\r\n toMatch(/Oct 2\\d, 2010 \\d{1,2}:\\d{2}:\\d{2} (AM|PM)/);\r\n expect(element(by.binding(\"1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'\")).getText()).\r\n toMatch(/2010\\-10\\-2\\d \\d{2}:\\d{2}:\\d{2} (\\-|\\+)?\\d{4}/);\r\n expect(element(by.binding(\"'1288323623006' | date:'MM/dd/yyyy @ h:mma'\")).getText()).\r\n toMatch(/10\\/2\\d\\/2010 @ \\d{1,2}:\\d{2}(AM|PM)/);\r\n expect(element(by.binding(\"'1288323623006' | date:\\\"MM/dd/yyyy 'at' h:mma\\\"\")).getText()).\r\n toMatch(/10\\/2\\d\\/2010 at \\d{1,2}:\\d{2}(AM|PM)/);\r\n });\r\n \r\n
    \r\n */\r\ndateFilter.$inject = ['$locale'];\r\nfunction dateFilter($locale) {\r\n\r\n\r\n var R_ISO8601_STR = /^(\\d{4})-?(\\d\\d)-?(\\d\\d)(?:T(\\d\\d)(?::?(\\d\\d)(?::?(\\d\\d)(?:\\.(\\d+))?)?)?(Z|([+-])(\\d\\d):?(\\d\\d))?)?$/;\r\n // 1 2 3 4 5 6 7 8 9 10 11\r\n function jsonStringToDate(string) {\r\n var match;\r\n if (match = string.match(R_ISO8601_STR)) {\r\n var date = new Date(0),\r\n tzHour = 0,\r\n tzMin = 0,\r\n dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,\r\n timeSetter = match[8] ? date.setUTCHours : date.setHours;\r\n\r\n if (match[9]) {\r\n tzHour = int(match[9] + match[10]);\r\n tzMin = int(match[9] + match[11]);\r\n }\r\n dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));\r\n var h = int(match[4] || 0) - tzHour;\r\n var m = int(match[5] || 0) - tzMin;\r\n var s = int(match[6] || 0);\r\n var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);\r\n timeSetter.call(date, h, m, s, ms);\r\n return date;\r\n }\r\n return string;\r\n }\r\n\r\n\r\n return function(date, format, timezone) {\r\n var text = '',\r\n parts = [],\r\n fn, match;\r\n\r\n format = format || 'mediumDate';\r\n format = $locale.DATETIME_FORMATS[format] || format;\r\n if (isString(date)) {\r\n date = NUMBER_STRING.test(date) ? int(date) : jsonStringToDate(date);\r\n }\r\n\r\n if (isNumber(date)) {\r\n date = new Date(date);\r\n }\r\n\r\n if (!isDate(date)) {\r\n return date;\r\n }\r\n\r\n while (format) {\r\n match = DATE_FORMATS_SPLIT.exec(format);\r\n if (match) {\r\n parts = concat(parts, match, 1);\r\n format = parts.pop();\r\n } else {\r\n parts.push(format);\r\n format = null;\r\n }\r\n }\r\n\r\n if (timezone && timezone === 'UTC') {\r\n date = new Date(date.getTime());\r\n date.setMinutes(date.getMinutes() + date.getTimezoneOffset());\r\n }\r\n forEach(parts, function(value) {\r\n fn = DATE_FORMATS[value];\r\n text += fn ? fn(date, $locale.DATETIME_FORMATS)\r\n : value.replace(/(^'|'$)/g, '').replace(/''/g, \"'\");\r\n });\r\n\r\n return text;\r\n };\r\n}\r\n\r\n\r\n/**\r\n * @ngdoc filter\r\n * @name json\r\n * @kind function\r\n *\r\n * @description\r\n * Allows you to convert a JavaScript object into JSON string.\r\n *\r\n * This filter is mostly useful for debugging. When using the double curly {{value}} notation\r\n * the binding is automatically converted to JSON.\r\n *\r\n * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.\r\n * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.\r\n * @returns {string} JSON string.\r\n *\r\n *\r\n * @example\r\n \r\n \r\n
    {{ {'name':'value'} | json }}
    \r\n
    {{ {'name':'value'} | json:4 }}
    \r\n
    \r\n \r\n it('should jsonify filtered objects', function() {\r\n expect(element(by.id('default-spacing')).getText()).toMatch(/\\{\\n \"name\": ?\"value\"\\n}/);\r\n expect(element(by.id('custom-spacing')).getText()).toMatch(/\\{\\n \"name\": ?\"value\"\\n}/);\r\n });\r\n \r\n
    \r\n *\r\n */\r\nfunction jsonFilter() {\r\n return function(object, spacing) {\r\n if (isUndefined(spacing)) {\r\n spacing = 2;\r\n }\r\n return toJson(object, spacing);\r\n };\r\n}\r\n\r\n\r\n/**\r\n * @ngdoc filter\r\n * @name lowercase\r\n * @kind function\r\n * @description\r\n * Converts string to lowercase.\r\n * @see angular.lowercase\r\n */\r\nvar lowercaseFilter = valueFn(lowercase);\r\n\r\n\r\n/**\r\n * @ngdoc filter\r\n * @name uppercase\r\n * @kind function\r\n * @description\r\n * Converts string to uppercase.\r\n * @see angular.uppercase\r\n */\r\nvar uppercaseFilter = valueFn(uppercase);\r\n\r\n/**\r\n * @ngdoc filter\r\n * @name limitTo\r\n * @kind function\r\n *\r\n * @description\r\n * Creates a new array or string containing only a specified number of elements. The elements\r\n * are taken from either the beginning or the end of the source array, string or number, as specified by\r\n * the value and sign (positive or negative) of `limit`. If a number is used as input, it is\r\n * converted to a string.\r\n *\r\n * @param {Array|string|number} input Source array, string or number to be limited.\r\n * @param {string|number} limit The length of the returned array or string. If the `limit` number\r\n * is positive, `limit` number of items from the beginning of the source array/string are copied.\r\n * If the number is negative, `limit` number of items from the end of the source array/string\r\n * are copied. The `limit` will be trimmed if it exceeds `array.length`\r\n * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array\r\n * had less than `limit` elements.\r\n *\r\n * @example\r\n \r\n \r\n \r\n
    \r\n Limit {{numbers}} to: \r\n

    Output numbers: {{ numbers | limitTo:numLimit }}

    \r\n Limit {{letters}} to: \r\n

    Output letters: {{ letters | limitTo:letterLimit }}

    \r\n Limit {{longNumber}} to: \r\n

    Output long number: {{ longNumber | limitTo:longNumberLimit }}

    \r\n
    \r\n
    \r\n \r\n var numLimitInput = element(by.model('numLimit'));\r\n var letterLimitInput = element(by.model('letterLimit'));\r\n var longNumberLimitInput = element(by.model('longNumberLimit'));\r\n var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));\r\n var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));\r\n var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));\r\n\r\n it('should limit the number array to first three items', function() {\r\n expect(numLimitInput.getAttribute('value')).toBe('3');\r\n expect(letterLimitInput.getAttribute('value')).toBe('3');\r\n expect(longNumberLimitInput.getAttribute('value')).toBe('3');\r\n expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');\r\n expect(limitedLetters.getText()).toEqual('Output letters: abc');\r\n expect(limitedLongNumber.getText()).toEqual('Output long number: 234');\r\n });\r\n\r\n // There is a bug in safari and protractor that doesn't like the minus key\r\n // it('should update the output when -3 is entered', function() {\r\n // numLimitInput.clear();\r\n // numLimitInput.sendKeys('-3');\r\n // letterLimitInput.clear();\r\n // letterLimitInput.sendKeys('-3');\r\n // longNumberLimitInput.clear();\r\n // longNumberLimitInput.sendKeys('-3');\r\n // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');\r\n // expect(limitedLetters.getText()).toEqual('Output letters: ghi');\r\n // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');\r\n // });\r\n\r\n it('should not exceed the maximum size of input array', function() {\r\n numLimitInput.clear();\r\n numLimitInput.sendKeys('100');\r\n letterLimitInput.clear();\r\n letterLimitInput.sendKeys('100');\r\n longNumberLimitInput.clear();\r\n longNumberLimitInput.sendKeys('100');\r\n expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');\r\n expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');\r\n expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');\r\n });\r\n \r\n
    \r\n*/\r\nfunction limitToFilter() {\r\n return function(input, limit) {\r\n if (isNumber(input)) input = input.toString();\r\n if (!isArray(input) && !isString(input)) return input;\r\n\r\n if (Math.abs(Number(limit)) === Infinity) {\r\n limit = Number(limit);\r\n } else {\r\n limit = int(limit);\r\n }\r\n\r\n //NaN check on limit\r\n if (limit) {\r\n return limit > 0 ? input.slice(0, limit) : input.slice(limit);\r\n } else {\r\n return isString(input) ? \"\" : [];\r\n }\r\n };\r\n}\r\n\r\n/**\r\n * @ngdoc filter\r\n * @name orderBy\r\n * @kind function\r\n *\r\n * @description\r\n * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically\r\n * for strings and numerically for numbers. Note: if you notice numbers are not being sorted\r\n * correctly, make sure they are actually being saved as numbers and not strings.\r\n *\r\n * @param {Array} array The array to sort.\r\n * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be\r\n * used by the comparator to determine the order of elements.\r\n *\r\n * Can be one of:\r\n *\r\n * - `function`: Getter function. The result of this function will be sorted using the\r\n * `<`, `===`, `>` operator.\r\n * - `string`: An Angular expression. The result of this expression is used to compare elements\r\n * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by\r\n * 3 first characters of a property called `name`). The result of a constant expression\r\n * is interpreted as a property name to be used in comparisons (for example `\"special name\"`\r\n * to sort object by the value of their `special name` property). An expression can be\r\n * optionally prefixed with `+` or `-` to control ascending or descending sort order\r\n * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array\r\n * element itself is used to compare where sorting.\r\n * - `Array`: An array of function or string predicates. The first predicate in the array\r\n * is used for sorting, but when two items are equivalent, the next predicate is used.\r\n *\r\n * If the predicate is missing or empty then it defaults to `'+'`.\r\n *\r\n * @param {boolean=} reverse Reverse the order of the array.\r\n * @returns {Array} Sorted copy of the source array.\r\n *\r\n *\r\n * @example\r\n * The example below demonstrates a simple ngRepeat, where the data is sorted\r\n * by age in descending order (predicate is set to `'-age'`).\r\n * `reverse` is not set, which means it defaults to `false`.\r\n \r\n \r\n \r\n
    \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n
    NamePhone NumberAge
    {{friend.name}}{{friend.phone}}{{friend.age}}
    \r\n
    \r\n
    \r\n
    \r\n *\r\n * The predicate and reverse parameters can be controlled dynamically through scope properties,\r\n * as shown in the next example.\r\n * @example\r\n \r\n \r\n \r\n
    \r\n
    Sorting predicate = {{predicate}}; reverse = {{reverse}}
    \r\n
    \r\n [ unsorted ]\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n
    Name\r\n (^)Phone NumberAge
    {{friend.name}}{{friend.phone}}{{friend.age}}
    \r\n
    \r\n
    \r\n
    \r\n *\r\n * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the\r\n * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the\r\n * desired parameters.\r\n *\r\n * Example:\r\n *\r\n * @example\r\n \r\n \r\n
    \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n
    Name\r\n (^)Phone NumberAge
    {{friend.name}}{{friend.phone}}{{friend.age}}
    \r\n
    \r\n
    \r\n\r\n \r\n angular.module('orderByExample', [])\r\n .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {\r\n var orderBy = $filter('orderBy');\r\n $scope.friends = [\r\n { name: 'John', phone: '555-1212', age: 10 },\r\n { name: 'Mary', phone: '555-9876', age: 19 },\r\n { name: 'Mike', phone: '555-4321', age: 21 },\r\n { name: 'Adam', phone: '555-5678', age: 35 },\r\n { name: 'Julie', phone: '555-8765', age: 29 }\r\n ];\r\n $scope.order = function(predicate, reverse) {\r\n $scope.friends = orderBy($scope.friends, predicate, reverse);\r\n };\r\n $scope.order('-age',false);\r\n }]);\r\n \r\n
    \r\n */\r\norderByFilter.$inject = ['$parse'];\r\nfunction orderByFilter($parse) {\r\n return function(array, sortPredicate, reverseOrder) {\r\n if (!(isArrayLike(array))) return array;\r\n sortPredicate = isArray(sortPredicate) ? sortPredicate : [sortPredicate];\r\n if (sortPredicate.length === 0) { sortPredicate = ['+']; }\r\n sortPredicate = sortPredicate.map(function(predicate) {\r\n var descending = false, get = predicate || identity;\r\n if (isString(predicate)) {\r\n if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {\r\n descending = predicate.charAt(0) == '-';\r\n predicate = predicate.substring(1);\r\n }\r\n if (predicate === '') {\r\n // Effectively no predicate was passed so we compare identity\r\n return reverseComparator(compare, descending);\r\n }\r\n get = $parse(predicate);\r\n if (get.constant) {\r\n var key = get();\r\n return reverseComparator(function(a, b) {\r\n return compare(a[key], b[key]);\r\n }, descending);\r\n }\r\n }\r\n return reverseComparator(function(a, b) {\r\n return compare(get(a),get(b));\r\n }, descending);\r\n });\r\n return slice.call(array).sort(reverseComparator(comparator, reverseOrder));\r\n\r\n function comparator(o1, o2) {\r\n for (var i = 0; i < sortPredicate.length; i++) {\r\n var comp = sortPredicate[i](o1, o2);\r\n if (comp !== 0) return comp;\r\n }\r\n return 0;\r\n }\r\n function reverseComparator(comp, descending) {\r\n return descending\r\n ? function(a, b) {return comp(b,a);}\r\n : comp;\r\n }\r\n\r\n function isPrimitive(value) {\r\n switch (typeof value) {\r\n case 'number': /* falls through */\r\n case 'boolean': /* falls through */\r\n case 'string':\r\n return true;\r\n default:\r\n return false;\r\n }\r\n }\r\n\r\n function objectToString(value) {\r\n if (value === null) return 'null';\r\n if (typeof value.valueOf === 'function') {\r\n value = value.valueOf();\r\n if (isPrimitive(value)) return value;\r\n }\r\n if (typeof value.toString === 'function') {\r\n value = value.toString();\r\n if (isPrimitive(value)) return value;\r\n }\r\n return '';\r\n }\r\n\r\n function compare(v1, v2) {\r\n var t1 = typeof v1;\r\n var t2 = typeof v2;\r\n if (t1 === t2 && t1 === \"object\") {\r\n v1 = objectToString(v1);\r\n v2 = objectToString(v2);\r\n }\r\n if (t1 === t2) {\r\n if (t1 === \"string\") {\r\n v1 = v1.toLowerCase();\r\n v2 = v2.toLowerCase();\r\n }\r\n if (v1 === v2) return 0;\r\n return v1 < v2 ? -1 : 1;\r\n } else {\r\n return t1 < t2 ? -1 : 1;\r\n }\r\n }\r\n };\r\n}\r\n\r\nfunction ngDirective(directive) {\r\n if (isFunction(directive)) {\r\n directive = {\r\n link: directive\r\n };\r\n }\r\n directive.restrict = directive.restrict || 'AC';\r\n return valueFn(directive);\r\n}\r\n\r\n/**\r\n * @ngdoc directive\r\n * @name a\r\n * @restrict E\r\n *\r\n * @description\r\n * Modifies the default behavior of the html A tag so that the default action is prevented when\r\n * the href attribute is empty.\r\n *\r\n * This change permits the easy creation of action links with the `ngClick` directive\r\n * without changing the location or causing page reloads, e.g.:\r\n * `Add Item`\r\n */\r\nvar htmlAnchorDirective = valueFn({\r\n restrict: 'E',\r\n compile: function(element, attr) {\r\n if (!attr.href && !attr.xlinkHref && !attr.name) {\r\n return function(scope, element) {\r\n // If the linked element is not an anchor tag anymore, do nothing\r\n if (element[0].nodeName.toLowerCase() !== 'a') return;\r\n\r\n // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.\r\n var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?\r\n 'xlink:href' : 'href';\r\n element.on('click', function(event) {\r\n // if we have no href url, then don't navigate anywhere.\r\n if (!element.attr(href)) {\r\n event.preventDefault();\r\n }\r\n });\r\n };\r\n }\r\n }\r\n});\r\n\r\n/**\r\n * @ngdoc directive\r\n * @name ngHref\r\n * @restrict A\r\n * @priority 99\r\n *\r\n * @description\r\n * Using Angular markup like `{{hash}}` in an href attribute will\r\n * make the link go to the wrong URL if the user clicks it before\r\n * Angular has a chance to replace the `{{hash}}` markup with its\r\n * value. Until Angular replaces the markup the link will be broken\r\n * and will most likely return a 404 error. The `ngHref` directive\r\n * solves this problem.\r\n *\r\n * The wrong way to write it:\r\n * ```html\r\n * link1\r\n * ```\r\n *\r\n * The correct way to write it:\r\n * ```html\r\n * link1\r\n * ```\r\n *\r\n * @element A\r\n * @param {template} ngHref any string which can contain `{{}}` markup.\r\n *\r\n * @example\r\n * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes\r\n * in links and their different behaviors:\r\n \r\n \r\n
    \r\n link 1 (link, don't reload)
    \r\n link 2 (link, don't reload)
    \r\n link 3 (link, reload!)
    \r\n anchor (link, don't reload)
    \r\n anchor (no link)
    \r\n link (link, change location)\r\n
    \r\n \r\n it('should execute ng-click but not reload when href without value', function() {\r\n element(by.id('link-1')).click();\r\n expect(element(by.model('value')).getAttribute('value')).toEqual('1');\r\n expect(element(by.id('link-1')).getAttribute('href')).toBe('');\r\n });\r\n\r\n it('should execute ng-click but not reload when href empty string', function() {\r\n element(by.id('link-2')).click();\r\n expect(element(by.model('value')).getAttribute('value')).toEqual('2');\r\n expect(element(by.id('link-2')).getAttribute('href')).toBe('');\r\n });\r\n\r\n it('should execute ng-click and change url when ng-href specified', function() {\r\n expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\\/123$/);\r\n\r\n element(by.id('link-3')).click();\r\n\r\n // At this point, we navigate away from an Angular page, so we need\r\n // to use browser.driver to get the base webdriver.\r\n\r\n browser.wait(function() {\r\n return browser.driver.getCurrentUrl().then(function(url) {\r\n return url.match(/\\/123$/);\r\n });\r\n }, 5000, 'page should navigate to /123');\r\n });\r\n\r\n xit('should execute ng-click but not reload when href empty string and name specified', function() {\r\n element(by.id('link-4')).click();\r\n expect(element(by.model('value')).getAttribute('value')).toEqual('4');\r\n expect(element(by.id('link-4')).getAttribute('href')).toBe('');\r\n });\r\n\r\n it('should execute ng-click but not reload when no href but name specified', function() {\r\n element(by.id('link-5')).click();\r\n expect(element(by.model('value')).getAttribute('value')).toEqual('5');\r\n expect(element(by.id('link-5')).getAttribute('href')).toBe(null);\r\n });\r\n\r\n it('should only change url when only ng-href', function() {\r\n element(by.model('value')).clear();\r\n element(by.model('value')).sendKeys('6');\r\n expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\\/6$/);\r\n\r\n element(by.id('link-6')).click();\r\n\r\n // At this point, we navigate away from an Angular page, so we need\r\n // to use browser.driver to get the base webdriver.\r\n browser.wait(function() {\r\n return browser.driver.getCurrentUrl().then(function(url) {\r\n return url.match(/\\/6$/);\r\n });\r\n }, 5000, 'page should navigate to /6');\r\n });\r\n \r\n
    \r\n */\r\n\r\n/**\r\n * @ngdoc directive\r\n * @name ngSrc\r\n * @restrict A\r\n * @priority 99\r\n *\r\n * @description\r\n * Using Angular markup like `{{hash}}` in a `src` attribute doesn't\r\n * work right: The browser will fetch from the URL with the literal\r\n * text `{{hash}}` until Angular replaces the expression inside\r\n * `{{hash}}`. The `ngSrc` directive solves this problem.\r\n *\r\n * The buggy way to write it:\r\n * ```html\r\n * \r\n * ```\r\n *\r\n * The correct way to write it:\r\n * ```html\r\n * \r\n * ```\r\n *\r\n * @element IMG\r\n * @param {template} ngSrc any string which can contain `{{}}` markup.\r\n */\r\n\r\n/**\r\n * @ngdoc directive\r\n * @name ngSrcset\r\n * @restrict A\r\n * @priority 99\r\n *\r\n * @description\r\n * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't\r\n * work right: The browser will fetch from the URL with the literal\r\n * text `{{hash}}` until Angular replaces the expression inside\r\n * `{{hash}}`. The `ngSrcset` directive solves this problem.\r\n *\r\n * The buggy way to write it:\r\n * ```html\r\n * \r\n * ```\r\n *\r\n * The correct way to write it:\r\n * ```html\r\n * \r\n * ```\r\n *\r\n * @element IMG\r\n * @param {template} ngSrcset any string which can contain `{{}}` markup.\r\n */\r\n\r\n/**\r\n * @ngdoc directive\r\n * @name ngDisabled\r\n * @restrict A\r\n * @priority 100\r\n *\r\n * @description\r\n *\r\n * This directive sets the `disabled` attribute on the element if the\r\n * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.\r\n *\r\n * A special directive is necessary because we cannot use interpolation inside the `disabled`\r\n * attribute. The following example would make the button enabled on Chrome/Firefox\r\n * but not on older IEs:\r\n *\r\n * ```html\r\n * \r\n *
    \r\n * \r\n *
    \r\n * ```\r\n *\r\n * This is because the HTML specification does not require browsers to preserve the values of\r\n * boolean attributes such as `disabled` (Their presence means true and their absence means false.)\r\n * If we put an Angular interpolation expression into such an attribute then the\r\n * binding information would be lost when the browser removes the attribute.\r\n *\r\n * @example\r\n \r\n \r\n Click me to toggle:
    \r\n \r\n
    \r\n \r\n it('should toggle button', function() {\r\n expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();\r\n element(by.model('checked')).click();\r\n expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();\r\n });\r\n \r\n
    \r\n *\r\n * @element INPUT\r\n * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,\r\n * then the `disabled` attribute will be set on the element\r\n */\r\n\r\n\r\n/**\r\n * @ngdoc directive\r\n * @name ngChecked\r\n * @restrict A\r\n * @priority 100\r\n *\r\n * @description\r\n * The HTML specification does not require browsers to preserve the values of boolean attributes\r\n * such as checked. (Their presence means true and their absence means false.)\r\n * If we put an Angular interpolation expression into such an attribute then the\r\n * binding information would be lost when the browser removes the attribute.\r\n * The `ngChecked` directive solves this problem for the `checked` attribute.\r\n * This complementary directive is not removed by the browser and so provides\r\n * a permanent reliable place to store the binding information.\r\n * @example\r\n \r\n \r\n Check me to check both:
    \r\n \r\n
    \r\n \r\n it('should check both checkBoxes', function() {\r\n expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();\r\n element(by.model('master')).click();\r\n expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();\r\n });\r\n \r\n
    \r\n *\r\n * @element INPUT\r\n * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,\r\n * then special attribute \"checked\" will be set on the element\r\n */\r\n\r\n\r\n/**\r\n * @ngdoc directive\r\n * @name ngReadonly\r\n * @restrict A\r\n * @priority 100\r\n *\r\n * @description\r\n * The HTML specification does not require browsers to preserve the values of boolean attributes\r\n * such as readonly. (Their presence means true and their absence means false.)\r\n * If we put an Angular interpolation expression into such an attribute then the\r\n * binding information would be lost when the browser removes the attribute.\r\n * The `ngReadonly` directive solves this problem for the `readonly` attribute.\r\n * This complementary directive is not removed by the browser and so provides\r\n * a permanent reliable place to store the binding information.\r\n * @example\r\n \r\n \r\n Check me to make text readonly:
    \r\n \r\n
    \r\n \r\n it('should toggle readonly attr', function() {\r\n expect(element(by.css('[type=\"text\"]')).getAttribute('readonly')).toBeFalsy();\r\n element(by.model('checked')).click();\r\n expect(element(by.css('[type=\"text\"]')).getAttribute('readonly')).toBeTruthy();\r\n });\r\n \r\n
    \r\n *\r\n * @element INPUT\r\n * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,\r\n * then special attribute \"readonly\" will be set on the element\r\n */\r\n\r\n\r\n/**\r\n * @ngdoc directive\r\n * @name ngSelected\r\n * @restrict A\r\n * @priority 100\r\n *\r\n * @description\r\n * The HTML specification does not require browsers to preserve the values of boolean attributes\r\n * such as selected. (Their presence means true and their absence means false.)\r\n * If we put an Angular interpolation expression into such an attribute then the\r\n * binding information would be lost when the browser removes the attribute.\r\n * The `ngSelected` directive solves this problem for the `selected` attribute.\r\n * This complementary directive is not removed by the browser and so provides\r\n * a permanent reliable place to store the binding information.\r\n *\r\n * @example\r\n \r\n \r\n Check me to select:
    \r\n \r\n
    \r\n \r\n it('should select Greetings!', function() {\r\n expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();\r\n element(by.model('selected')).click();\r\n expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();\r\n });\r\n \r\n
    \r\n *\r\n * @element OPTION\r\n * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,\r\n * then special attribute \"selected\" will be set on the element\r\n */\r\n\r\n/**\r\n * @ngdoc directive\r\n * @name ngOpen\r\n * @restrict A\r\n * @priority 100\r\n *\r\n * @description\r\n * The HTML specification does not require browsers to preserve the values of boolean attributes\r\n * such as open. (Their presence means true and their absence means false.)\r\n * If we put an Angular interpolation expression into such an attribute then the\r\n * binding information would be lost when the browser removes the attribute.\r\n * The `ngOpen` directive solves this problem for the `open` attribute.\r\n * This complementary directive is not removed by the browser and so provides\r\n * a permanent reliable place to store the binding information.\r\n * @example\r\n \r\n \r\n Check me check multiple:
    \r\n
    \r\n Show/Hide me\r\n
    \r\n
    \r\n \r\n it('should toggle open', function() {\r\n expect(element(by.id('details')).getAttribute('open')).toBeFalsy();\r\n element(by.model('open')).click();\r\n expect(element(by.id('details')).getAttribute('open')).toBeTruthy();\r\n });\r\n \r\n
    \r\n *\r\n * @element DETAILS\r\n * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,\r\n * then special attribute \"open\" will be set on the element\r\n */\r\n\r\nvar ngAttributeAliasDirectives = {};\r\n\r\n\r\n// boolean attrs are evaluated\r\nforEach(BOOLEAN_ATTR, function(propName, attrName) {\r\n // binding to multiple is not supported\r\n if (propName == \"multiple\") return;\r\n\r\n var normalized = directiveNormalize('ng-' + attrName);\r\n ngAttributeAliasDirectives[normalized] = function() {\r\n return {\r\n restrict: 'A',\r\n priority: 100,\r\n link: function(scope, element, attr) {\r\n scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {\r\n attr.$set(attrName, !!value);\r\n });\r\n }\r\n };\r\n };\r\n});\r\n\r\n// aliased input attrs are evaluated\r\nforEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {\r\n ngAttributeAliasDirectives[ngAttr] = function() {\r\n return {\r\n priority: 100,\r\n link: function(scope, element, attr) {\r\n //special case ngPattern when a literal regular expression value\r\n //is used as the expression (this way we don't have to watch anything).\r\n if (ngAttr === \"ngPattern\" && attr.ngPattern.charAt(0) == \"/\") {\r\n var match = attr.ngPattern.match(REGEX_STRING_REGEXP);\r\n if (match) {\r\n attr.$set(\"ngPattern\", new RegExp(match[1], match[2]));\r\n return;\r\n }\r\n }\r\n\r\n scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {\r\n attr.$set(ngAttr, value);\r\n });\r\n }\r\n };\r\n };\r\n});\r\n\r\n// ng-src, ng-srcset, ng-href are interpolated\r\nforEach(['src', 'srcset', 'href'], function(attrName) {\r\n var normalized = directiveNormalize('ng-' + attrName);\r\n ngAttributeAliasDirectives[normalized] = function() {\r\n return {\r\n priority: 99, // it needs to run after the attributes are interpolated\r\n link: function(scope, element, attr) {\r\n var propName = attrName,\r\n name = attrName;\r\n\r\n if (attrName === 'href' &&\r\n toString.call(element.prop('href')) === '[object SVGAnimatedString]') {\r\n name = 'xlinkHref';\r\n attr.$attr[name] = 'xlink:href';\r\n propName = null;\r\n }\r\n\r\n attr.$observe(normalized, function(value) {\r\n if (!value) {\r\n if (attrName === 'href') {\r\n attr.$set(name, null);\r\n }\r\n return;\r\n }\r\n\r\n attr.$set(name, value);\r\n\r\n // on IE, if \"ng:src\" directive declaration is used and \"src\" attribute doesn't exist\r\n // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need\r\n // to set the property as well to achieve the desired effect.\r\n // we use attr[attrName] value since $set can sanitize the url.\r\n if (msie && propName) element.prop(propName, attr[name]);\r\n });\r\n }\r\n };\r\n };\r\n});\r\n\r\n/* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true\r\n */\r\nvar nullFormCtrl = {\r\n $addControl: noop,\r\n $$renameControl: nullFormRenameControl,\r\n $removeControl: noop,\r\n $setValidity: noop,\r\n $setDirty: noop,\r\n $setPristine: noop,\r\n $setSubmitted: noop\r\n},\r\nSUBMITTED_CLASS = 'ng-submitted';\r\n\r\nfunction nullFormRenameControl(control, name) {\r\n control.$name = name;\r\n}\r\n\r\n/**\r\n * @ngdoc type\r\n * @name form.FormController\r\n *\r\n * @property {boolean} $pristine True if user has not interacted with the form yet.\r\n * @property {boolean} $dirty True if user has already interacted with the form.\r\n * @property {boolean} $valid True if all of the containing forms and controls are valid.\r\n * @property {boolean} $invalid True if at least one containing control or form is invalid.\r\n * @property {boolean} $submitted True if user has submitted the form even if its invalid.\r\n *\r\n * @property {Object} $error Is an object hash, containing references to controls or\r\n * forms with failing validators, where:\r\n *\r\n * - keys are validation tokens (error names),\r\n * - values are arrays of controls or forms that have a failing validator for given error name.\r\n *\r\n * Built-in validation tokens:\r\n *\r\n * - `email`\r\n * - `max`\r\n * - `maxlength`\r\n * - `min`\r\n * - `minlength`\r\n * - `number`\r\n * - `pattern`\r\n * - `required`\r\n * - `url`\r\n * - `date`\r\n * - `datetimelocal`\r\n * - `time`\r\n * - `week`\r\n * - `month`\r\n *\r\n * @description\r\n * `FormController` keeps track of all its controls and nested forms as well as the state of them,\r\n * such as being valid/invalid or dirty/pristine.\r\n *\r\n * Each {@link ng.directive:form form} directive creates an instance\r\n * of `FormController`.\r\n *\r\n */\r\n//asks for $scope to fool the BC controller module\r\nFormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];\r\nfunction FormController(element, attrs, $scope, $animate, $interpolate) {\r\n var form = this,\r\n controls = [];\r\n\r\n var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl;\r\n\r\n // init state\r\n form.$error = {};\r\n form.$$success = {};\r\n form.$pending = undefined;\r\n form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);\r\n form.$dirty = false;\r\n form.$pristine = true;\r\n form.$valid = true;\r\n form.$invalid = false;\r\n form.$submitted = false;\r\n\r\n parentForm.$addControl(form);\r\n\r\n /**\r\n * @ngdoc method\r\n * @name form.FormController#$rollbackViewValue\r\n *\r\n * @description\r\n * Rollback all form controls pending updates to the `$modelValue`.\r\n *\r\n * Updates may be pending by a debounced event or because the input is waiting for a some future\r\n * event defined in `ng-model-options`. This method is typically needed by the reset button of\r\n * a form that uses `ng-model-options` to pend updates.\r\n */\r\n form.$rollbackViewValue = function() {\r\n forEach(controls, function(control) {\r\n control.$rollbackViewValue();\r\n });\r\n };\r\n\r\n /**\r\n * @ngdoc method\r\n * @name form.FormController#$commitViewValue\r\n *\r\n * @description\r\n * Commit all form controls pending updates to the `$modelValue`.\r\n *\r\n * Updates may be pending by a debounced event or because the input is waiting for a some future\r\n * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`\r\n * usually handles calling this in response to input events.\r\n */\r\n form.$commitViewValue = function() {\r\n forEach(controls, function(control) {\r\n control.$commitViewValue();\r\n });\r\n };\r\n\r\n /**\r\n * @ngdoc method\r\n * @name form.FormController#$addControl\r\n *\r\n * @description\r\n * Register a control with the form.\r\n *\r\n * Input elements using ngModelController do this automatically when they are linked.\r\n */\r\n form.$addControl = function(control) {\r\n // Breaking change - before, inputs whose name was \"hasOwnProperty\" were quietly ignored\r\n // and not added to the scope. Now we throw an error.\r\n assertNotHasOwnProperty(control.$name, 'input');\r\n controls.push(control);\r\n\r\n if (control.$name) {\r\n form[control.$name] = control;\r\n }\r\n };\r\n\r\n // Private API: rename a form control\r\n form.$$renameControl = function(control, newName) {\r\n var oldName = control.$name;\r\n\r\n if (form[oldName] === control) {\r\n delete form[oldName];\r\n }\r\n form[newName] = control;\r\n control.$name = newName;\r\n };\r\n\r\n /**\r\n * @ngdoc method\r\n * @name form.FormController#$removeControl\r\n *\r\n * @description\r\n * Deregister a control from the form.\r\n *\r\n * Input elements using ngModelController do this automatically when they are destroyed.\r\n */\r\n form.$removeControl = function(control) {\r\n if (control.$name && form[control.$name] === control) {\r\n delete form[control.$name];\r\n }\r\n forEach(form.$pending, function(value, name) {\r\n form.$setValidity(name, null, control);\r\n });\r\n forEach(form.$error, function(value, name) {\r\n form.$setValidity(name, null, control);\r\n });\r\n forEach(form.$$success, function(value, name) {\r\n form.$setValidity(name, null, control);\r\n });\r\n\r\n arrayRemove(controls, control);\r\n };\r\n\r\n\r\n /**\r\n * @ngdoc method\r\n * @name form.FormController#$setValidity\r\n *\r\n * @description\r\n * Sets the validity of a form control.\r\n *\r\n * This method will also propagate to parent forms.\r\n */\r\n addSetValidityMethod({\r\n ctrl: this,\r\n $element: element,\r\n set: function(object, property, controller) {\r\n var list = object[property];\r\n if (!list) {\r\n object[property] = [controller];\r\n } else {\r\n var index = list.indexOf(controller);\r\n if (index === -1) {\r\n list.push(controller);\r\n }\r\n }\r\n },\r\n unset: function(object, property, controller) {\r\n var list = object[property];\r\n if (!list) {\r\n return;\r\n }\r\n arrayRemove(list, controller);\r\n if (list.length === 0) {\r\n delete object[property];\r\n }\r\n },\r\n parentForm: parentForm,\r\n $animate: $animate\r\n });\r\n\r\n /**\r\n * @ngdoc method\r\n * @name form.FormController#$setDirty\r\n *\r\n * @description\r\n * Sets the form to a dirty state.\r\n *\r\n * This method can be called to add the 'ng-dirty' class and set the form to a dirty\r\n * state (ng-dirty class). This method will also propagate to parent forms.\r\n */\r\n form.$setDirty = function() {\r\n $animate.removeClass(element, PRISTINE_CLASS);\r\n $animate.addClass(element, DIRTY_CLASS);\r\n form.$dirty = true;\r\n form.$pristine = false;\r\n parentForm.$setDirty();\r\n };\r\n\r\n /**\r\n * @ngdoc method\r\n * @name form.FormController#$setPristine\r\n *\r\n * @description\r\n * Sets the form to its pristine state.\r\n *\r\n * This method can be called to remove the 'ng-dirty' class and set the form to its pristine\r\n * state (ng-pristine class). This method will also propagate to all the controls contained\r\n * in this form.\r\n *\r\n * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after\r\n * saving or resetting it.\r\n */\r\n form.$setPristine = function() {\r\n $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);\r\n form.$dirty = false;\r\n form.$pristine = true;\r\n form.$submitted = false;\r\n forEach(controls, function(control) {\r\n control.$setPristine();\r\n });\r\n };\r\n\r\n /**\r\n * @ngdoc method\r\n * @name form.FormController#$setUntouched\r\n *\r\n * @description\r\n * Sets the form to its untouched state.\r\n *\r\n * This method can be called to remove the 'ng-touched' class and set the form controls to their\r\n * untouched state (ng-untouched class).\r\n *\r\n * Setting a form controls back to their untouched state is often useful when setting the form\r\n * back to its pristine state.\r\n */\r\n form.$setUntouched = function() {\r\n forEach(controls, function(control) {\r\n control.$setUntouched();\r\n });\r\n };\r\n\r\n /**\r\n * @ngdoc method\r\n * @name form.FormController#$setSubmitted\r\n *\r\n * @description\r\n * Sets the form to its submitted state.\r\n */\r\n form.$setSubmitted = function() {\r\n $animate.addClass(element, SUBMITTED_CLASS);\r\n form.$submitted = true;\r\n parentForm.$setSubmitted();\r\n };\r\n}\r\n\r\n/**\r\n * @ngdoc directive\r\n * @name ngForm\r\n * @restrict EAC\r\n *\r\n * @description\r\n * Nestable alias of {@link ng.directive:form `form`} directive. HTML\r\n * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a\r\n * sub-group of controls needs to be determined.\r\n *\r\n * Note: the purpose of `ngForm` is to group controls,\r\n * but not to be a replacement for the `
    ` tag with all of its capabilities\r\n * (e.g. posting to the server, ...).\r\n *\r\n * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into\r\n * related scope, under this name.\r\n *\r\n */\r\n\r\n /**\r\n * @ngdoc directive\r\n * @name form\r\n * @restrict E\r\n *\r\n * @description\r\n * Directive that instantiates\r\n * {@link form.FormController FormController}.\r\n *\r\n * If the `name` attribute is specified, the form controller is published onto the current scope under\r\n * this name.\r\n *\r\n * # Alias: {@link ng.directive:ngForm `ngForm`}\r\n *\r\n * In Angular, forms can be nested. This means that the outer form is valid when all of the child\r\n * forms are valid as well. However, browsers do not allow nesting of `` elements, so\r\n * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to\r\n * `` but can be nested. This allows you to have nested forms, which is very useful when\r\n * using Angular validation directives in forms that are dynamically generated using the\r\n * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`\r\n * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an\r\n * `ngForm` directive and nest these in an outer `form` element.\r\n *\r\n *\r\n * # CSS classes\r\n * - `ng-valid` is set if the form is valid.\r\n * - `ng-invalid` is set if the form is invalid.\r\n * - `ng-pristine` is set if the form is pristine.\r\n * - `ng-dirty` is set if the form is dirty.\r\n * - `ng-submitted` is set if the form was submitted.\r\n *\r\n * Keep in mind that ngAnimate can detect each of these classes when added and removed.\r\n *\r\n *\r\n * # Submitting a form and preventing the default action\r\n *\r\n * Since the role of forms in client-side Angular applications is different than in classical\r\n * roundtrip apps, it is desirable for the browser not to translate the form submission into a full\r\n * page reload that sends the data to the server. Instead some javascript logic should be triggered\r\n * to handle the form submission in an application-specific way.\r\n *\r\n * For this reason, Angular prevents the default action (form submission to the server) unless the\r\n * `` element has an `action` attribute specified.\r\n *\r\n * You can use one of the following two ways to specify what javascript method should be called when\r\n * a form is submitted:\r\n *\r\n * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element\r\n * - {@link ng.directive:ngClick ngClick} directive on the first\r\n * button or input field of type submit (input[type=submit])\r\n *\r\n * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}\r\n * or {@link ng.directive:ngClick ngClick} directives.\r\n * This is because of the following form submission rules in the HTML specification:\r\n *\r\n * - If a form has only one input field then hitting enter in this field triggers form submit\r\n * (`ngSubmit`)\r\n * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter\r\n * doesn't trigger submit\r\n * - if a form has one or more input fields and one or more buttons or input[type=submit] then\r\n * hitting enter in any of the input fields will trigger the click handler on the *first* button or\r\n * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)\r\n *\r\n * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is\r\n * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`\r\n * to have access to the updated model.\r\n *\r\n * ## Animation Hooks\r\n *\r\n * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.\r\n * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any\r\n * other validations that are performed within the form. Animations in ngForm are similar to how\r\n * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well\r\n * as JS animations.\r\n *\r\n * The following example shows a simple way to utilize CSS transitions to style a form element\r\n * that has been rendered as invalid after it has been validated:\r\n *\r\n *
    \r\n * //be sure to include ngAnimate as a module to hook into more\r\n * //advanced animations\r\n * .my-form {\r\n *   transition:0.5s linear all;\r\n *   background: white;\r\n * }\r\n * .my-form.ng-invalid {\r\n *   background: red;\r\n *   color:white;\r\n * }\r\n * 
    \r\n *\r\n * @example\r\n \r\n \r\n \r\n \r\n \r\n userType: \r\n Required!
    \r\n userType = {{userType}}
    \r\n myForm.input.$valid = {{myForm.input.$valid}}
    \r\n myForm.input.$error = {{myForm.input.$error}}
    \r\n myForm.$valid = {{myForm.$valid}}
    \r\n myForm.$error.required = {{!!myForm.$error.required}}
    \r\n \r\n
    \r\n \r\n it('should initialize to model', function() {\r\n var userType = element(by.binding('userType'));\r\n var valid = element(by.binding('myForm.input.$valid'));\r\n\r\n expect(userType.getText()).toContain('guest');\r\n expect(valid.getText()).toContain('true');\r\n });\r\n\r\n it('should be invalid if empty', function() {\r\n var userType = element(by.binding('userType'));\r\n var valid = element(by.binding('myForm.input.$valid'));\r\n var userInput = element(by.model('userType'));\r\n\r\n userInput.clear();\r\n userInput.sendKeys('');\r\n\r\n expect(userType.getText()).toEqual('userType =');\r\n expect(valid.getText()).toContain('false');\r\n });\r\n \r\n
    \r\n *\r\n * @param {string=} name Name of the form. If specified, the form controller will be published into\r\n * related scope, under this name.\r\n */\r\nvar formDirectiveFactory = function(isNgForm) {\r\n return ['$timeout', function($timeout) {\r\n var formDirective = {\r\n name: 'form',\r\n restrict: isNgForm ? 'EAC' : 'E',\r\n controller: FormController,\r\n compile: function ngFormCompile(formElement, attr) {\r\n // Setup initial state of the control\r\n formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);\r\n\r\n var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);\r\n\r\n return {\r\n pre: function ngFormPreLink(scope, formElement, attr, controller) {\r\n // if `action` attr is not present on the form, prevent the default action (submission)\r\n if (!('action' in attr)) {\r\n // we can't use jq events because if a form is destroyed during submission the default\r\n // action is not prevented. see #1238\r\n //\r\n // IE 9 is not affected because it doesn't fire a submit event and try to do a full\r\n // page reload if the form was destroyed by submission of the form via a click handler\r\n // on a button in the form. Looks like an IE9 specific bug.\r\n var handleFormSubmission = function(event) {\r\n scope.$apply(function() {\r\n controller.$commitViewValue();\r\n controller.$setSubmitted();\r\n });\r\n\r\n event.preventDefault();\r\n };\r\n\r\n addEventListenerFn(formElement[0], 'submit', handleFormSubmission);\r\n\r\n // unregister the preventDefault listener so that we don't not leak memory but in a\r\n // way that will achieve the prevention of the default action.\r\n formElement.on('$destroy', function() {\r\n $timeout(function() {\r\n removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);\r\n }, 0, false);\r\n });\r\n }\r\n\r\n var parentFormCtrl = controller.$$parentForm;\r\n\r\n if (nameAttr) {\r\n setter(scope, null, controller.$name, controller, controller.$name);\r\n attr.$observe(nameAttr, function(newValue) {\r\n if (controller.$name === newValue) return;\r\n setter(scope, null, controller.$name, undefined, controller.$name);\r\n parentFormCtrl.$$renameControl(controller, newValue);\r\n setter(scope, null, controller.$name, controller, controller.$name);\r\n });\r\n }\r\n formElement.on('$destroy', function() {\r\n parentFormCtrl.$removeControl(controller);\r\n if (nameAttr) {\r\n setter(scope, null, attr[nameAttr], undefined, controller.$name);\r\n }\r\n extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards\r\n });\r\n }\r\n };\r\n }\r\n };\r\n\r\n return formDirective;\r\n }];\r\n};\r\n\r\nvar formDirective = formDirectiveFactory();\r\nvar ngFormDirective = formDirectiveFactory(true);\r\n\r\n/* global VALID_CLASS: false,\r\n INVALID_CLASS: false,\r\n PRISTINE_CLASS: false,\r\n DIRTY_CLASS: false,\r\n UNTOUCHED_CLASS: false,\r\n TOUCHED_CLASS: false,\r\n ngModelMinErr: false,\r\n*/\r\n\r\n// Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231\r\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)/;\r\nvar URL_REGEXP = /^(ftp|http|https):\\/\\/(\\w+:{0,1}\\w*@)?(\\S+)(:[0-9]+)?(\\/|\\/([\\w#!:.?+=&%@!\\-\\/]))?$/;\r\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;\r\nvar NUMBER_REGEXP = /^\\s*(\\-|\\+)?(\\d+|(\\d*(\\.\\d*)))\\s*$/;\r\nvar DATE_REGEXP = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\r\nvar DATETIMELOCAL_REGEXP = /^(\\d{4})-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d)(?::(\\d\\d)(\\.\\d{1,3})?)?$/;\r\nvar WEEK_REGEXP = /^(\\d{4})-W(\\d\\d)$/;\r\nvar MONTH_REGEXP = /^(\\d{4})-(\\d\\d)$/;\r\nvar TIME_REGEXP = /^(\\d\\d):(\\d\\d)(?::(\\d\\d)(\\.\\d{1,3})?)?$/;\r\n\r\nvar inputType = {\r\n\r\n /**\r\n * @ngdoc input\r\n * @name input[text]\r\n *\r\n * @description\r\n * Standard HTML text input with angular data binding, inherited by most of the `input` elements.\r\n *\r\n *\r\n * @param {string} ngModel Assignable angular expression to data-bind to.\r\n * @param {string=} name Property name of the form under which the control is published.\r\n * @param {string=} required Adds `required` validation error key if the value is not entered.\r\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\r\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\r\n * `required` when you want to data-bind to the `required` attribute.\r\n * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\r\n * minlength.\r\n * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\r\n * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\r\n * any length.\r\n * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\r\n * that contains the regular expression body that will be converted to a regular expression\r\n * as in the ngPattern directive.\r\n * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match\r\n * a RegExp found by evaluating the Angular expression given in the attribute value.\r\n * If the expression evaluates to a RegExp object then this is used directly.\r\n * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`\r\n * characters. For instance, `\"abc\"` will be converted to `new RegExp('^abc$')`.\r\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\r\n * interaction with the input element.\r\n * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.\r\n * This parameter is ignored for input[type=password] controls, which will never trim the\r\n * input.\r\n *\r\n * @example\r\n \r\n \r\n \r\n
    \r\n Single word: \r\n \r\n Required!\r\n \r\n Single word only!\r\n\r\n text = {{example.text}}
    \r\n myForm.input.$valid = {{myForm.input.$valid}}
    \r\n myForm.input.$error = {{myForm.input.$error}}
    \r\n myForm.$valid = {{myForm.$valid}}
    \r\n myForm.$error.required = {{!!myForm.$error.required}}
    \r\n
    \r\n
    \r\n \r\n var text = element(by.binding('example.text'));\r\n var valid = element(by.binding('myForm.input.$valid'));\r\n var input = element(by.model('example.text'));\r\n\r\n it('should initialize to model', function() {\r\n expect(text.getText()).toContain('guest');\r\n expect(valid.getText()).toContain('true');\r\n });\r\n\r\n it('should be invalid if empty', function() {\r\n input.clear();\r\n input.sendKeys('');\r\n\r\n expect(text.getText()).toEqual('text =');\r\n expect(valid.getText()).toContain('false');\r\n });\r\n\r\n it('should be invalid if multi word', function() {\r\n input.clear();\r\n input.sendKeys('hello world');\r\n\r\n expect(valid.getText()).toContain('false');\r\n });\r\n \r\n
    \r\n */\r\n 'text': textInputType,\r\n\r\n /**\r\n * @ngdoc input\r\n * @name input[date]\r\n *\r\n * @description\r\n * Input with date validation and transformation. In browsers that do not yet support\r\n * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601\r\n * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many\r\n * modern browsers do not yet support this input type, it is important to provide cues to users on the\r\n * expected input format via a placeholder or label.\r\n *\r\n * The model must always be a Date object, otherwise Angular will throw an error.\r\n * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\r\n *\r\n * The timezone to be used to read/write the `Date` instance in the model can be defined using\r\n * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\r\n *\r\n * @param {string} ngModel Assignable angular expression to data-bind to.\r\n * @param {string=} name Property name of the form under which the control is published.\r\n * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a\r\n * valid ISO date string (yyyy-MM-dd).\r\n * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be\r\n * a valid ISO date string (yyyy-MM-dd).\r\n * @param {string=} required Sets `required` validation error key if the value is not entered.\r\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\r\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\r\n * `required` when you want to data-bind to the `required` attribute.\r\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\r\n * interaction with the input element.\r\n *\r\n * @example\r\n \r\n \r\n \r\n
    \r\n Pick a date in 2013:\r\n \r\n \r\n Required!\r\n \r\n Not a valid date!\r\n value = {{example.value | date: \"yyyy-MM-dd\"}}
    \r\n myForm.input.$valid = {{myForm.input.$valid}}
    \r\n myForm.input.$error = {{myForm.input.$error}}
    \r\n myForm.$valid = {{myForm.$valid}}
    \r\n myForm.$error.required = {{!!myForm.$error.required}}
    \r\n
    \r\n
    \r\n \r\n var value = element(by.binding('example.value | date: \"yyyy-MM-dd\"'));\r\n var valid = element(by.binding('myForm.input.$valid'));\r\n var input = element(by.model('example.value'));\r\n\r\n // currently protractor/webdriver does not support\r\n // sending keys to all known HTML5 input controls\r\n // for various browsers (see https://github.com/angular/protractor/issues/562).\r\n function setInput(val) {\r\n // set the value of the element and force validation.\r\n var scr = \"var ipt = document.getElementById('exampleInput'); \" +\r\n \"ipt.value = '\" + val + \"';\" +\r\n \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\r\n browser.executeScript(scr);\r\n }\r\n\r\n it('should initialize to model', function() {\r\n expect(value.getText()).toContain('2013-10-22');\r\n expect(valid.getText()).toContain('myForm.input.$valid = true');\r\n });\r\n\r\n it('should be invalid if empty', function() {\r\n setInput('');\r\n expect(value.getText()).toEqual('value =');\r\n expect(valid.getText()).toContain('myForm.input.$valid = false');\r\n });\r\n\r\n it('should be invalid if over max', function() {\r\n setInput('2015-01-01');\r\n expect(value.getText()).toContain('');\r\n expect(valid.getText()).toContain('myForm.input.$valid = false');\r\n });\r\n \r\n
    \r\n */\r\n 'date': createDateInputType('date', DATE_REGEXP,\r\n createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),\r\n 'yyyy-MM-dd'),\r\n\r\n /**\r\n * @ngdoc input\r\n * @name input[datetime-local]\r\n *\r\n * @description\r\n * Input with datetime validation and transformation. In browsers that do not yet support\r\n * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\r\n * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.\r\n *\r\n * The model must always be a Date object, otherwise Angular will throw an error.\r\n * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\r\n *\r\n * The timezone to be used to read/write the `Date` instance in the model can be defined using\r\n * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\r\n *\r\n * @param {string} ngModel Assignable angular expression to data-bind to.\r\n * @param {string=} name Property name of the form under which the control is published.\r\n * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a\r\n * valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).\r\n * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be\r\n * a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).\r\n * @param {string=} required Sets `required` validation error key if the value is not entered.\r\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\r\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\r\n * `required` when you want to data-bind to the `required` attribute.\r\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\r\n * interaction with the input element.\r\n *\r\n * @example\r\n \r\n \r\n \r\n
    \r\n Pick a date between in 2013:\r\n \r\n \r\n Required!\r\n \r\n Not a valid date!\r\n value = {{example.value | date: \"yyyy-MM-ddTHH:mm:ss\"}}
    \r\n myForm.input.$valid = {{myForm.input.$valid}}
    \r\n myForm.input.$error = {{myForm.input.$error}}
    \r\n myForm.$valid = {{myForm.$valid}}
    \r\n myForm.$error.required = {{!!myForm.$error.required}}
    \r\n
    \r\n
    \r\n \r\n var value = element(by.binding('example.value | date: \"yyyy-MM-ddTHH:mm:ss\"'));\r\n var valid = element(by.binding('myForm.input.$valid'));\r\n var input = element(by.model('example.value'));\r\n\r\n // currently protractor/webdriver does not support\r\n // sending keys to all known HTML5 input controls\r\n // for various browsers (https://github.com/angular/protractor/issues/562).\r\n function setInput(val) {\r\n // set the value of the element and force validation.\r\n var scr = \"var ipt = document.getElementById('exampleInput'); \" +\r\n \"ipt.value = '\" + val + \"';\" +\r\n \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\r\n browser.executeScript(scr);\r\n }\r\n\r\n it('should initialize to model', function() {\r\n expect(value.getText()).toContain('2010-12-28T14:57:00');\r\n expect(valid.getText()).toContain('myForm.input.$valid = true');\r\n });\r\n\r\n it('should be invalid if empty', function() {\r\n setInput('');\r\n expect(value.getText()).toEqual('value =');\r\n expect(valid.getText()).toContain('myForm.input.$valid = false');\r\n });\r\n\r\n it('should be invalid if over max', function() {\r\n setInput('2015-01-01T23:59:00');\r\n expect(value.getText()).toContain('');\r\n expect(valid.getText()).toContain('myForm.input.$valid = false');\r\n });\r\n \r\n
    \r\n */\r\n 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,\r\n createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),\r\n 'yyyy-MM-ddTHH:mm:ss.sss'),\r\n\r\n /**\r\n * @ngdoc input\r\n * @name input[time]\r\n *\r\n * @description\r\n * Input with time validation and transformation. In browsers that do not yet support\r\n * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\r\n * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a\r\n * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.\r\n *\r\n * The model must always be a Date object, otherwise Angular will throw an error.\r\n * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\r\n *\r\n * The timezone to be used to read/write the `Date` instance in the model can be defined using\r\n * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\r\n *\r\n * @param {string} ngModel Assignable angular expression to data-bind to.\r\n * @param {string=} name Property name of the form under which the control is published.\r\n * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a\r\n * valid ISO time format (HH:mm:ss).\r\n * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a\r\n * valid ISO time format (HH:mm:ss).\r\n * @param {string=} required Sets `required` validation error key if the value is not entered.\r\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\r\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\r\n * `required` when you want to data-bind to the `required` attribute.\r\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\r\n * interaction with the input element.\r\n *\r\n * @example\r\n \r\n \r\n \r\n
    \r\n Pick a between 8am and 5pm:\r\n \r\n \r\n Required!\r\n \r\n Not a valid date!\r\n value = {{example.value | date: \"HH:mm:ss\"}}
    \r\n myForm.input.$valid = {{myForm.input.$valid}}
    \r\n myForm.input.$error = {{myForm.input.$error}}
    \r\n myForm.$valid = {{myForm.$valid}}
    \r\n myForm.$error.required = {{!!myForm.$error.required}}
    \r\n
    \r\n
    \r\n \r\n var value = element(by.binding('example.value | date: \"HH:mm:ss\"'));\r\n var valid = element(by.binding('myForm.input.$valid'));\r\n var input = element(by.model('example.value'));\r\n\r\n // currently protractor/webdriver does not support\r\n // sending keys to all known HTML5 input controls\r\n // for various browsers (https://github.com/angular/protractor/issues/562).\r\n function setInput(val) {\r\n // set the value of the element and force validation.\r\n var scr = \"var ipt = document.getElementById('exampleInput'); \" +\r\n \"ipt.value = '\" + val + \"';\" +\r\n \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\r\n browser.executeScript(scr);\r\n }\r\n\r\n it('should initialize to model', function() {\r\n expect(value.getText()).toContain('14:57:00');\r\n expect(valid.getText()).toContain('myForm.input.$valid = true');\r\n });\r\n\r\n it('should be invalid if empty', function() {\r\n setInput('');\r\n expect(value.getText()).toEqual('value =');\r\n expect(valid.getText()).toContain('myForm.input.$valid = false');\r\n });\r\n\r\n it('should be invalid if over max', function() {\r\n setInput('23:59:00');\r\n expect(value.getText()).toContain('');\r\n expect(valid.getText()).toContain('myForm.input.$valid = false');\r\n });\r\n \r\n
    \r\n */\r\n 'time': createDateInputType('time', TIME_REGEXP,\r\n createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),\r\n 'HH:mm:ss.sss'),\r\n\r\n /**\r\n * @ngdoc input\r\n * @name input[week]\r\n *\r\n * @description\r\n * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support\r\n * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\r\n * week format (yyyy-W##), for example: `2013-W02`.\r\n *\r\n * The model must always be a Date object, otherwise Angular will throw an error.\r\n * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\r\n *\r\n * The timezone to be used to read/write the `Date` instance in the model can be defined using\r\n * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\r\n *\r\n * @param {string} ngModel Assignable angular expression to data-bind to.\r\n * @param {string=} name Property name of the form under which the control is published.\r\n * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a\r\n * valid ISO week format (yyyy-W##).\r\n * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be\r\n * a valid ISO week format (yyyy-W##).\r\n * @param {string=} required Sets `required` validation error key if the value is not entered.\r\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\r\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\r\n * `required` when you want to data-bind to the `required` attribute.\r\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\r\n * interaction with the input element.\r\n *\r\n * @example\r\n \r\n \r\n \r\n
    \r\n Pick a date between in 2013:\r\n \r\n \r\n Required!\r\n \r\n Not a valid date!\r\n value = {{example.value | date: \"yyyy-Www\"}}
    \r\n myForm.input.$valid = {{myForm.input.$valid}}
    \r\n myForm.input.$error = {{myForm.input.$error}}
    \r\n myForm.$valid = {{myForm.$valid}}
    \r\n myForm.$error.required = {{!!myForm.$error.required}}
    \r\n
    \r\n
    \r\n \r\n var value = element(by.binding('example.value | date: \"yyyy-Www\"'));\r\n var valid = element(by.binding('myForm.input.$valid'));\r\n var input = element(by.model('example.value'));\r\n\r\n // currently protractor/webdriver does not support\r\n // sending keys to all known HTML5 input controls\r\n // for various browsers (https://github.com/angular/protractor/issues/562).\r\n function setInput(val) {\r\n // set the value of the element and force validation.\r\n var scr = \"var ipt = document.getElementById('exampleInput'); \" +\r\n \"ipt.value = '\" + val + \"';\" +\r\n \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\r\n browser.executeScript(scr);\r\n }\r\n\r\n it('should initialize to model', function() {\r\n expect(value.getText()).toContain('2013-W01');\r\n expect(valid.getText()).toContain('myForm.input.$valid = true');\r\n });\r\n\r\n it('should be invalid if empty', function() {\r\n setInput('');\r\n expect(value.getText()).toEqual('value =');\r\n expect(valid.getText()).toContain('myForm.input.$valid = false');\r\n });\r\n\r\n it('should be invalid if over max', function() {\r\n setInput('2015-W01');\r\n expect(value.getText()).toContain('');\r\n expect(valid.getText()).toContain('myForm.input.$valid = false');\r\n });\r\n \r\n
    \r\n */\r\n 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),\r\n\r\n /**\r\n * @ngdoc input\r\n * @name input[month]\r\n *\r\n * @description\r\n * Input with month validation and transformation. In browsers that do not yet support\r\n * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\r\n * month format (yyyy-MM), for example: `2009-01`.\r\n *\r\n * The model must always be a Date object, otherwise Angular will throw an error.\r\n * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\r\n * If the model is not set to the first of the month, the next view to model update will set it\r\n * to the first of the month.\r\n *\r\n * The timezone to be used to read/write the `Date` instance in the model can be defined using\r\n * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\r\n *\r\n * @param {string} ngModel Assignable angular expression to data-bind to.\r\n * @param {string=} name Property name of the form under which the control is published.\r\n * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be\r\n * a valid ISO month format (yyyy-MM).\r\n * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must\r\n * be a valid ISO month format (yyyy-MM).\r\n * @param {string=} required Sets `required` validation error key if the value is not entered.\r\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\r\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\r\n * `required` when you want to data-bind to the `required` attribute.\r\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\r\n * interaction with the input element.\r\n *\r\n * @example\r\n \r\n \r\n \r\n
    \r\n Pick a month in 2013:\r\n \r\n \r\n Required!\r\n \r\n Not a valid month!\r\n value = {{example.value | date: \"yyyy-MM\"}}
    \r\n myForm.input.$valid = {{myForm.input.$valid}}
    \r\n myForm.input.$error = {{myForm.input.$error}}
    \r\n myForm.$valid = {{myForm.$valid}}
    \r\n myForm.$error.required = {{!!myForm.$error.required}}
    \r\n
    \r\n
    \r\n \r\n var value = element(by.binding('example.value | date: \"yyyy-MM\"'));\r\n var valid = element(by.binding('myForm.input.$valid'));\r\n var input = element(by.model('example.value'));\r\n\r\n // currently protractor/webdriver does not support\r\n // sending keys to all known HTML5 input controls\r\n // for various browsers (https://github.com/angular/protractor/issues/562).\r\n function setInput(val) {\r\n // set the value of the element and force validation.\r\n var scr = \"var ipt = document.getElementById('exampleInput'); \" +\r\n \"ipt.value = '\" + val + \"';\" +\r\n \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\r\n browser.executeScript(scr);\r\n }\r\n\r\n it('should initialize to model', function() {\r\n expect(value.getText()).toContain('2013-10');\r\n expect(valid.getText()).toContain('myForm.input.$valid = true');\r\n });\r\n\r\n it('should be invalid if empty', function() {\r\n setInput('');\r\n expect(value.getText()).toEqual('value =');\r\n expect(valid.getText()).toContain('myForm.input.$valid = false');\r\n });\r\n\r\n it('should be invalid if over max', function() {\r\n setInput('2015-01');\r\n expect(value.getText()).toContain('');\r\n expect(valid.getText()).toContain('myForm.input.$valid = false');\r\n });\r\n \r\n
    \r\n */\r\n 'month': createDateInputType('month', MONTH_REGEXP,\r\n createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),\r\n 'yyyy-MM'),\r\n\r\n /**\r\n * @ngdoc input\r\n * @name input[number]\r\n *\r\n * @description\r\n * Text input with number validation and transformation. Sets the `number` validation\r\n * error if not a valid number.\r\n *\r\n *
    \r\n * The model must always be of type `number` otherwise Angular will throw an error.\r\n * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}\r\n * error docs for more information and an example of how to convert your model if necessary.\r\n *
    \r\n *\r\n * @param {string} ngModel Assignable angular expression to data-bind to.\r\n * @param {string=} name Property name of the form under which the control is published.\r\n * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.\r\n * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.\r\n * @param {string=} required Sets `required` validation error key if the value is not entered.\r\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\r\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\r\n * `required` when you want to data-bind to the `required` attribute.\r\n * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\r\n * minlength.\r\n * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\r\n * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\r\n * any length.\r\n * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\r\n * that contains the regular expression body that will be converted to a regular expression\r\n * as in the ngPattern directive.\r\n * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match\r\n * a RegExp found by evaluating the Angular expression given in the attribute value.\r\n * If the expression evaluates to a RegExp object then this is used directly.\r\n * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`\r\n * characters. For instance, `\"abc\"` will be converted to `new RegExp('^abc$')`.\r\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\r\n * interaction with the input element.\r\n *\r\n * @example\r\n \r\n \r\n \r\n
    \r\n Number: \r\n \r\n Required!\r\n \r\n Not valid number!\r\n value = {{example.value}}
    \r\n myForm.input.$valid = {{myForm.input.$valid}}
    \r\n myForm.input.$error = {{myForm.input.$error}}
    \r\n myForm.$valid = {{myForm.$valid}}
    \r\n myForm.$error.required = {{!!myForm.$error.required}}
    \r\n
    \r\n
    \r\n \r\n var value = element(by.binding('example.value'));\r\n var valid = element(by.binding('myForm.input.$valid'));\r\n var input = element(by.model('example.value'));\r\n\r\n it('should initialize to model', function() {\r\n expect(value.getText()).toContain('12');\r\n expect(valid.getText()).toContain('true');\r\n });\r\n\r\n it('should be invalid if empty', function() {\r\n input.clear();\r\n input.sendKeys('');\r\n expect(value.getText()).toEqual('value =');\r\n expect(valid.getText()).toContain('false');\r\n });\r\n\r\n it('should be invalid if over max', function() {\r\n input.clear();\r\n input.sendKeys('123');\r\n expect(value.getText()).toEqual('value =');\r\n expect(valid.getText()).toContain('false');\r\n });\r\n \r\n
    \r\n */\r\n 'number': numberInputType,\r\n\r\n\r\n /**\r\n * @ngdoc input\r\n * @name input[url]\r\n *\r\n * @description\r\n * Text input with URL validation. Sets the `url` validation error key if the content is not a\r\n * valid URL.\r\n *\r\n *
    \r\n * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex\r\n * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify\r\n * the built-in validators (see the {@link guide/forms Forms guide})\r\n *
    \r\n *\r\n * @param {string} ngModel Assignable angular expression to data-bind to.\r\n * @param {string=} name Property name of the form under which the control is published.\r\n * @param {string=} required Sets `required` validation error key if the value is not entered.\r\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\r\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\r\n * `required` when you want to data-bind to the `required` attribute.\r\n * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\r\n * minlength.\r\n * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\r\n * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\r\n * any length.\r\n * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\r\n * that contains the regular expression body that will be converted to a regular expression\r\n * as in the ngPattern directive.\r\n * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match\r\n * a RegExp found by evaluating the Angular expression given in the attribute value.\r\n * If the expression evaluates to a RegExp object then this is used directly.\r\n * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`\r\n * characters. For instance, `\"abc\"` will be converted to `new RegExp('^abc$')`.\r\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\r\n * interaction with the input element.\r\n *\r\n * @example\r\n \r\n \r\n \r\n
    \r\n URL: \r\n \r\n Required!\r\n \r\n Not valid url!\r\n text = {{url.text}}
    \r\n myForm.input.$valid = {{myForm.input.$valid}}
    \r\n myForm.input.$error = {{myForm.input.$error}}
    \r\n myForm.$valid = {{myForm.$valid}}
    \r\n myForm.$error.required = {{!!myForm.$error.required}}
    \r\n myForm.$error.url = {{!!myForm.$error.url}}
    \r\n
    \r\n
    \r\n \r\n var text = element(by.binding('url.text'));\r\n var valid = element(by.binding('myForm.input.$valid'));\r\n var input = element(by.model('url.text'));\r\n\r\n it('should initialize to model', function() {\r\n expect(text.getText()).toContain('http://google.com');\r\n expect(valid.getText()).toContain('true');\r\n });\r\n\r\n it('should be invalid if empty', function() {\r\n input.clear();\r\n input.sendKeys('');\r\n\r\n expect(text.getText()).toEqual('text =');\r\n expect(valid.getText()).toContain('false');\r\n });\r\n\r\n it('should be invalid if not url', function() {\r\n input.clear();\r\n input.sendKeys('box');\r\n\r\n expect(valid.getText()).toContain('false');\r\n });\r\n \r\n
    \r\n */\r\n 'url': urlInputType,\r\n\r\n\r\n /**\r\n * @ngdoc input\r\n * @name input[email]\r\n *\r\n * @description\r\n * Text input with email validation. Sets the `email` validation error key if not a valid email\r\n * address.\r\n *\r\n *
    \r\n * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex\r\n * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can\r\n * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})\r\n *
    \r\n *\r\n * @param {string} ngModel Assignable angular expression to data-bind to.\r\n * @param {string=} name Property name of the form under which the control is published.\r\n * @param {string=} required Sets `required` validation error key if the value is not entered.\r\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\r\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\r\n * `required` when you want to data-bind to the `required` attribute.\r\n * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\r\n * minlength.\r\n * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\r\n * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\r\n * any length.\r\n * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\r\n * that contains the regular expression body that will be converted to a regular expression\r\n * as in the ngPattern directive.\r\n * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match\r\n * a RegExp found by evaluating the Angular expression given in the attribute value.\r\n * If the expression evaluates to a RegExp object then this is used directly.\r\n * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`\r\n * characters. For instance, `\"abc\"` will be converted to `new RegExp('^abc$')`.\r\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\r\n * interaction with the input element.\r\n *\r\n * @example\r\n \r\n \r\n \r\n
    \r\n Email: \r\n \r\n Required!\r\n \r\n Not valid email!\r\n text = {{email.text}}
    \r\n myForm.input.$valid = {{myForm.input.$valid}}
    \r\n myForm.input.$error = {{myForm.input.$error}}
    \r\n myForm.$valid = {{myForm.$valid}}
    \r\n myForm.$error.required = {{!!myForm.$error.required}}
    \r\n myForm.$error.email = {{!!myForm.$error.email}}
    \r\n
    \r\n
    \r\n \r\n var text = element(by.binding('email.text'));\r\n var valid = element(by.binding('myForm.input.$valid'));\r\n var input = element(by.model('email.text'));\r\n\r\n it('should initialize to model', function() {\r\n expect(text.getText()).toContain('me@example.com');\r\n expect(valid.getText()).toContain('true');\r\n });\r\n\r\n it('should be invalid if empty', function() {\r\n input.clear();\r\n input.sendKeys('');\r\n expect(text.getText()).toEqual('text =');\r\n expect(valid.getText()).toContain('false');\r\n });\r\n\r\n it('should be invalid if not email', function() {\r\n input.clear();\r\n input.sendKeys('xxx');\r\n\r\n expect(valid.getText()).toContain('false');\r\n });\r\n \r\n
    \r\n */\r\n 'email': emailInputType,\r\n\r\n\r\n /**\r\n * @ngdoc input\r\n * @name input[radio]\r\n *\r\n * @description\r\n * HTML radio button.\r\n *\r\n * @param {string} ngModel Assignable angular expression to data-bind to.\r\n * @param {string} value The value to which the expression should be set when selected.\r\n * @param {string=} name Property name of the form under which the control is published.\r\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\r\n * interaction with the input element.\r\n * @param {string} ngValue Angular expression which sets the value to which the expression should\r\n * be set when selected.\r\n *\r\n * @example\r\n \r\n \r\n \r\n
    \r\n Red
    \r\n Green
    \r\n Blue
    \r\n color = {{color.name | json}}
    \r\n
    \r\n Note that `ng-value=\"specialValue\"` sets radio item's value to be the value of `$scope.specialValue`.\r\n
    \r\n \r\n it('should change state', function() {\r\n var color = element(by.binding('color.name'));\r\n\r\n expect(color.getText()).toContain('blue');\r\n\r\n element.all(by.model('color.name')).get(0).click();\r\n\r\n expect(color.getText()).toContain('red');\r\n });\r\n \r\n
    \r\n */\r\n 'radio': radioInputType,\r\n\r\n\r\n /**\r\n * @ngdoc input\r\n * @name input[checkbox]\r\n *\r\n * @description\r\n * HTML checkbox.\r\n *\r\n * @param {string} ngModel Assignable angular expression to data-bind to.\r\n * @param {string=} name Property name of the form under which the control is published.\r\n * @param {expression=} ngTrueValue The value to which the expression should be set when selected.\r\n * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.\r\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\r\n * interaction with the input element.\r\n *\r\n * @example\r\n \r\n \r\n \r\n
    \r\n Value1:
    \r\n Value2:
    \r\n value1 = {{checkboxModel.value1}}
    \r\n value2 = {{checkboxModel.value2}}
    \r\n
    \r\n
    \r\n \r\n it('should change state', function() {\r\n var value1 = element(by.binding('checkboxModel.value1'));\r\n var value2 = element(by.binding('checkboxModel.value2'));\r\n\r\n expect(value1.getText()).toContain('true');\r\n expect(value2.getText()).toContain('YES');\r\n\r\n element(by.model('checkboxModel.value1')).click();\r\n element(by.model('checkboxModel.value2')).click();\r\n\r\n expect(value1.getText()).toContain('false');\r\n expect(value2.getText()).toContain('NO');\r\n });\r\n \r\n
    \r\n */\r\n 'checkbox': checkboxInputType,\r\n\r\n 'hidden': noop,\r\n 'button': noop,\r\n 'submit': noop,\r\n 'reset': noop,\r\n 'file': noop\r\n};\r\n\r\nfunction stringBasedInputType(ctrl) {\r\n ctrl.$formatters.push(function(value) {\r\n return ctrl.$isEmpty(value) ? value : value.toString();\r\n });\r\n}\r\n\r\nfunction textInputType(scope, element, attr, ctrl, $sniffer, $browser) {\r\n baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\r\n stringBasedInputType(ctrl);\r\n}\r\n\r\nfunction baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {\r\n var type = lowercase(element[0].type);\r\n\r\n // In composition mode, users are still inputing intermediate text buffer,\r\n // hold the listener until composition is done.\r\n // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent\r\n if (!$sniffer.android) {\r\n var composing = false;\r\n\r\n element.on('compositionstart', function(data) {\r\n composing = true;\r\n });\r\n\r\n element.on('compositionend', function() {\r\n composing = false;\r\n listener();\r\n });\r\n }\r\n\r\n var listener = function(ev) {\r\n if (timeout) {\r\n $browser.defer.cancel(timeout);\r\n timeout = null;\r\n }\r\n if (composing) return;\r\n var value = element.val(),\r\n event = ev && ev.type;\r\n\r\n // By default we will trim the value\r\n // If the attribute ng-trim exists we will avoid trimming\r\n // If input type is 'password', the value is never trimmed\r\n if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {\r\n value = trim(value);\r\n }\r\n\r\n // If a control is suffering from bad input (due to native validators), browsers discard its\r\n // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the\r\n // control's value is the same empty value twice in a row.\r\n if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {\r\n ctrl.$setViewValue(value, event);\r\n }\r\n };\r\n\r\n // if the browser does support \"input\" event, we are fine - except on IE9 which doesn't fire the\r\n // input event on backspace, delete or cut\r\n if ($sniffer.hasEvent('input')) {\r\n element.on('input', listener);\r\n } else {\r\n var timeout;\r\n\r\n var deferListener = function(ev, input, origValue) {\r\n if (!timeout) {\r\n timeout = $browser.defer(function() {\r\n timeout = null;\r\n if (!input || input.value !== origValue) {\r\n listener(ev);\r\n }\r\n });\r\n }\r\n };\r\n\r\n element.on('keydown', function(event) {\r\n var key = event.keyCode;\r\n\r\n // ignore\r\n // command modifiers arrows\r\n if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;\r\n\r\n deferListener(event, this, this.value);\r\n });\r\n\r\n // if user modifies input value using context menu in IE, we need \"paste\" and \"cut\" events to catch it\r\n if ($sniffer.hasEvent('paste')) {\r\n element.on('paste cut', deferListener);\r\n }\r\n }\r\n\r\n // if user paste into input using mouse on older browser\r\n // or form autocomplete on newer browser, we need \"change\" event to catch it\r\n element.on('change', listener);\r\n\r\n ctrl.$render = function() {\r\n element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);\r\n };\r\n}\r\n\r\nfunction weekParser(isoWeek, existingDate) {\r\n if (isDate(isoWeek)) {\r\n return isoWeek;\r\n }\r\n\r\n if (isString(isoWeek)) {\r\n WEEK_REGEXP.lastIndex = 0;\r\n var parts = WEEK_REGEXP.exec(isoWeek);\r\n if (parts) {\r\n var year = +parts[1],\r\n week = +parts[2],\r\n hours = 0,\r\n minutes = 0,\r\n seconds = 0,\r\n milliseconds = 0,\r\n firstThurs = getFirstThursdayOfYear(year),\r\n addDays = (week - 1) * 7;\r\n\r\n if (existingDate) {\r\n hours = existingDate.getHours();\r\n minutes = existingDate.getMinutes();\r\n seconds = existingDate.getSeconds();\r\n milliseconds = existingDate.getMilliseconds();\r\n }\r\n\r\n return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);\r\n }\r\n }\r\n\r\n return NaN;\r\n}\r\n\r\nfunction createDateParser(regexp, mapping) {\r\n return function(iso, date) {\r\n var parts, map;\r\n\r\n if (isDate(iso)) {\r\n return iso;\r\n }\r\n\r\n if (isString(iso)) {\r\n // When a date is JSON'ified to wraps itself inside of an extra\r\n // set of double quotes. This makes the date parsing code unable\r\n // to match the date string and parse it as a date.\r\n if (iso.charAt(0) == '\"' && iso.charAt(iso.length - 1) == '\"') {\r\n iso = iso.substring(1, iso.length - 1);\r\n }\r\n if (ISO_DATE_REGEXP.test(iso)) {\r\n return new Date(iso);\r\n }\r\n regexp.lastIndex = 0;\r\n parts = regexp.exec(iso);\r\n\r\n if (parts) {\r\n parts.shift();\r\n if (date) {\r\n map = {\r\n yyyy: date.getFullYear(),\r\n MM: date.getMonth() + 1,\r\n dd: date.getDate(),\r\n HH: date.getHours(),\r\n mm: date.getMinutes(),\r\n ss: date.getSeconds(),\r\n sss: date.getMilliseconds() / 1000\r\n };\r\n } else {\r\n map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };\r\n }\r\n\r\n forEach(parts, function(part, index) {\r\n if (index < mapping.length) {\r\n map[mapping[index]] = +part;\r\n }\r\n });\r\n return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);\r\n }\r\n }\r\n\r\n return NaN;\r\n };\r\n}\r\n\r\nfunction createDateInputType(type, regexp, parseDate, format) {\r\n return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {\r\n badInputChecker(scope, element, attr, ctrl);\r\n baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\r\n var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;\r\n var previousDate;\r\n\r\n ctrl.$$parserName = type;\r\n ctrl.$parsers.push(function(value) {\r\n if (ctrl.$isEmpty(value)) return null;\r\n if (regexp.test(value)) {\r\n // Note: We cannot read ctrl.$modelValue, as there might be a different\r\n // parser/formatter in the processing chain so that the model\r\n // contains some different data format!\r\n var parsedDate = parseDate(value, previousDate);\r\n if (timezone === 'UTC') {\r\n parsedDate.setMinutes(parsedDate.getMinutes() - parsedDate.getTimezoneOffset());\r\n }\r\n return parsedDate;\r\n }\r\n return undefined;\r\n });\r\n\r\n ctrl.$formatters.push(function(value) {\r\n if (value && !isDate(value)) {\r\n throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);\r\n }\r\n if (isValidDate(value)) {\r\n previousDate = value;\r\n if (previousDate && timezone === 'UTC') {\r\n var timezoneOffset = 60000 * previousDate.getTimezoneOffset();\r\n previousDate = new Date(previousDate.getTime() + timezoneOffset);\r\n }\r\n return $filter('date')(value, format, timezone);\r\n } else {\r\n previousDate = null;\r\n return '';\r\n }\r\n });\r\n\r\n if (isDefined(attr.min) || attr.ngMin) {\r\n var minVal;\r\n ctrl.$validators.min = function(value) {\r\n return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;\r\n };\r\n attr.$observe('min', function(val) {\r\n minVal = parseObservedDateValue(val);\r\n ctrl.$validate();\r\n });\r\n }\r\n\r\n if (isDefined(attr.max) || attr.ngMax) {\r\n var maxVal;\r\n ctrl.$validators.max = function(value) {\r\n return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;\r\n };\r\n attr.$observe('max', function(val) {\r\n maxVal = parseObservedDateValue(val);\r\n ctrl.$validate();\r\n });\r\n }\r\n\r\n function isValidDate(value) {\r\n // Invalid Date: getTime() returns NaN\r\n return value && !(value.getTime && value.getTime() !== value.getTime());\r\n }\r\n\r\n function parseObservedDateValue(val) {\r\n return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined;\r\n }\r\n };\r\n}\r\n\r\nfunction badInputChecker(scope, element, attr, ctrl) {\r\n var node = element[0];\r\n var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);\r\n if (nativeValidation) {\r\n ctrl.$parsers.push(function(value) {\r\n var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};\r\n // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):\r\n // - also sets validity.badInput (should only be validity.typeMismatch).\r\n // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)\r\n // - can ignore this case as we can still read out the erroneous email...\r\n return validity.badInput && !validity.typeMismatch ? undefined : value;\r\n });\r\n }\r\n}\r\n\r\nfunction numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {\r\n badInputChecker(scope, element, attr, ctrl);\r\n baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\r\n\r\n ctrl.$$parserName = 'number';\r\n ctrl.$parsers.push(function(value) {\r\n if (ctrl.$isEmpty(value)) return null;\r\n if (NUMBER_REGEXP.test(value)) return parseFloat(value);\r\n return undefined;\r\n });\r\n\r\n ctrl.$formatters.push(function(value) {\r\n if (!ctrl.$isEmpty(value)) {\r\n if (!isNumber(value)) {\r\n throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);\r\n }\r\n value = value.toString();\r\n }\r\n return value;\r\n });\r\n\r\n if (isDefined(attr.min) || attr.ngMin) {\r\n var minVal;\r\n ctrl.$validators.min = function(value) {\r\n return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;\r\n };\r\n\r\n attr.$observe('min', function(val) {\r\n if (isDefined(val) && !isNumber(val)) {\r\n val = parseFloat(val, 10);\r\n }\r\n minVal = isNumber(val) && !isNaN(val) ? val : undefined;\r\n // TODO(matsko): implement validateLater to reduce number of validations\r\n ctrl.$validate();\r\n });\r\n }\r\n\r\n if (isDefined(attr.max) || attr.ngMax) {\r\n var maxVal;\r\n ctrl.$validators.max = function(value) {\r\n return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;\r\n };\r\n\r\n attr.$observe('max', function(val) {\r\n if (isDefined(val) && !isNumber(val)) {\r\n val = parseFloat(val, 10);\r\n }\r\n maxVal = isNumber(val) && !isNaN(val) ? val : undefined;\r\n // TODO(matsko): implement validateLater to reduce number of validations\r\n ctrl.$validate();\r\n });\r\n }\r\n}\r\n\r\nfunction urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {\r\n // Note: no badInputChecker here by purpose as `url` is only a validation\r\n // in browsers, i.e. we can always read out input.value even if it is not valid!\r\n baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\r\n stringBasedInputType(ctrl);\r\n\r\n ctrl.$$parserName = 'url';\r\n ctrl.$validators.url = function(modelValue, viewValue) {\r\n var value = modelValue || viewValue;\r\n return ctrl.$isEmpty(value) || URL_REGEXP.test(value);\r\n };\r\n}\r\n\r\nfunction emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {\r\n // Note: no badInputChecker here by purpose as `url` is only a validation\r\n // in browsers, i.e. we can always read out input.value even if it is not valid!\r\n baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\r\n stringBasedInputType(ctrl);\r\n\r\n ctrl.$$parserName = 'email';\r\n ctrl.$validators.email = function(modelValue, viewValue) {\r\n var value = modelValue || viewValue;\r\n return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);\r\n };\r\n}\r\n\r\nfunction radioInputType(scope, element, attr, ctrl) {\r\n // make the name unique, if not defined\r\n if (isUndefined(attr.name)) {\r\n element.attr('name', nextUid());\r\n }\r\n\r\n var listener = function(ev) {\r\n if (element[0].checked) {\r\n ctrl.$setViewValue(attr.value, ev && ev.type);\r\n }\r\n };\r\n\r\n element.on('click', listener);\r\n\r\n ctrl.$render = function() {\r\n var value = attr.value;\r\n element[0].checked = (value == ctrl.$viewValue);\r\n };\r\n\r\n attr.$observe('value', ctrl.$render);\r\n}\r\n\r\nfunction parseConstantExpr($parse, context, name, expression, fallback) {\r\n var parseFn;\r\n if (isDefined(expression)) {\r\n parseFn = $parse(expression);\r\n if (!parseFn.constant) {\r\n throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +\r\n '`{1}`.', name, expression);\r\n }\r\n return parseFn(context);\r\n }\r\n return fallback;\r\n}\r\n\r\nfunction checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {\r\n var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);\r\n var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);\r\n\r\n var listener = function(ev) {\r\n ctrl.$setViewValue(element[0].checked, ev && ev.type);\r\n };\r\n\r\n element.on('click', listener);\r\n\r\n ctrl.$render = function() {\r\n element[0].checked = ctrl.$viewValue;\r\n };\r\n\r\n // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`\r\n // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert\r\n // it to a boolean.\r\n ctrl.$isEmpty = function(value) {\r\n return value === false;\r\n };\r\n\r\n ctrl.$formatters.push(function(value) {\r\n return equals(value, trueValue);\r\n });\r\n\r\n ctrl.$parsers.push(function(value) {\r\n return value ? trueValue : falseValue;\r\n });\r\n}\r\n\r\n\r\n/**\r\n * @ngdoc directive\r\n * @name textarea\r\n * @restrict E\r\n *\r\n * @description\r\n * HTML textarea element control with angular data-binding. The data-binding and validation\r\n * properties of this element are exactly the same as those of the\r\n * {@link ng.directive:input input element}.\r\n *\r\n * @param {string} ngModel Assignable angular expression to data-bind to.\r\n * @param {string=} name Property name of the form under which the control is published.\r\n * @param {string=} required Sets `required` validation error key if the value is not entered.\r\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\r\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\r\n * `required` when you want to data-bind to the `required` attribute.\r\n * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\r\n * minlength.\r\n * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\r\n * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any\r\n * length.\r\n * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the\r\n * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for\r\n * patterns defined as scope expressions.\r\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\r\n * interaction with the input element.\r\n * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.\r\n */\r\n\r\n\r\n/**\r\n * @ngdoc directive\r\n * @name input\r\n * @restrict E\r\n *\r\n * @description\r\n * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,\r\n * input state control, and validation.\r\n * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.\r\n *\r\n *
    \r\n * **Note:** Not every feature offered is available for all input types.\r\n * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.\r\n *
    \r\n *\r\n * @param {string} ngModel Assignable angular expression to data-bind to.\r\n * @param {string=} name Property name of the form under which the control is published.\r\n * @param {string=} required Sets `required` validation error key if the value is not entered.\r\n * @param {boolean=} ngRequired Sets `required` attribute if set to true\r\n * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\r\n * minlength.\r\n * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\r\n * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any\r\n * length.\r\n * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the\r\n * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for\r\n * patterns defined as scope expressions.\r\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\r\n * interaction with the input element.\r\n * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.\r\n * This parameter is ignored for input[type=password] controls, which will never trim the\r\n * input.\r\n *\r\n * @example\r\n \r\n \r\n \r\n
    \r\n
    \r\n User name: \r\n \r\n Required!
    \r\n Last name: \r\n \r\n Too short!\r\n \r\n Too long!
    \r\n
    \r\n
    \r\n user = {{user}}
    \r\n myForm.userName.$valid = {{myForm.userName.$valid}}
    \r\n myForm.userName.$error = {{myForm.userName.$error}}
    \r\n myForm.lastName.$valid = {{myForm.lastName.$valid}}
    \r\n myForm.lastName.$error = {{myForm.lastName.$error}}
    \r\n myForm.$valid = {{myForm.$valid}}
    \r\n myForm.$error.required = {{!!myForm.$error.required}}
    \r\n myForm.$error.minlength = {{!!myForm.$error.minlength}}
    \r\n myForm.$error.maxlength = {{!!myForm.$error.maxlength}}
    \r\n
    \r\n
    \r\n \r\n var user = element(by.exactBinding('user'));\r\n var userNameValid = element(by.binding('myForm.userName.$valid'));\r\n var lastNameValid = element(by.binding('myForm.lastName.$valid'));\r\n var lastNameError = element(by.binding('myForm.lastName.$error'));\r\n var formValid = element(by.binding('myForm.$valid'));\r\n var userNameInput = element(by.model('user.name'));\r\n var userLastInput = element(by.model('user.last'));\r\n\r\n it('should initialize to model', function() {\r\n expect(user.getText()).toContain('{\"name\":\"guest\",\"last\":\"visitor\"}');\r\n expect(userNameValid.getText()).toContain('true');\r\n expect(formValid.getText()).toContain('true');\r\n });\r\n\r\n it('should be invalid if empty when required', function() {\r\n userNameInput.clear();\r\n userNameInput.sendKeys('');\r\n\r\n expect(user.getText()).toContain('{\"last\":\"visitor\"}');\r\n expect(userNameValid.getText()).toContain('false');\r\n expect(formValid.getText()).toContain('false');\r\n });\r\n\r\n it('should be valid if empty when min length is set', function() {\r\n userLastInput.clear();\r\n userLastInput.sendKeys('');\r\n\r\n expect(user.getText()).toContain('{\"name\":\"guest\",\"last\":\"\"}');\r\n expect(lastNameValid.getText()).toContain('true');\r\n expect(formValid.getText()).toContain('true');\r\n });\r\n\r\n it('should be invalid if less than required min length', function() {\r\n userLastInput.clear();\r\n userLastInput.sendKeys('xx');\r\n\r\n expect(user.getText()).toContain('{\"name\":\"guest\"}');\r\n expect(lastNameValid.getText()).toContain('false');\r\n expect(lastNameError.getText()).toContain('minlength');\r\n expect(formValid.getText()).toContain('false');\r\n });\r\n\r\n it('should be invalid if longer than max length', function() {\r\n userLastInput.clear();\r\n userLastInput.sendKeys('some ridiculously long name');\r\n\r\n expect(user.getText()).toContain('{\"name\":\"guest\"}');\r\n expect(lastNameValid.getText()).toContain('false');\r\n expect(lastNameError.getText()).toContain('maxlength');\r\n expect(formValid.getText()).toContain('false');\r\n });\r\n \r\n
    \r\n */\r\nvar inputDirective = ['$browser', '$sniffer', '$filter', '$parse',\r\n function($browser, $sniffer, $filter, $parse) {\r\n return {\r\n restrict: 'E',\r\n require: ['?ngModel'],\r\n link: {\r\n pre: function(scope, element, attr, ctrls) {\r\n if (ctrls[0]) {\r\n (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,\r\n $browser, $filter, $parse);\r\n }\r\n }\r\n }\r\n };\r\n}];\r\n\r\n\r\n\r\nvar CONSTANT_VALUE_REGEXP = /^(true|false|\\d+)$/;\r\n/**\r\n * @ngdoc directive\r\n * @name ngValue\r\n *\r\n * @description\r\n * Binds the given expression to the value of `