From 4406116bd8d3a9c3d0ed0ff41d678f74e9b1a6bf Mon Sep 17 00:00:00 2001 From: Alejandro Alonso Date: Fri, 29 Jan 2016 13:15:51 +0100 Subject: [PATCH] 963a4c42f7337f89ad37f7a1e34d688b622aa104 --- dist/index.html | 13 +- dist/v-1451995127167/js/app.js | 22 - dist/v-1451995127167/js/libs.js | 46 - dist/v-1451995127167/js/maps/app.js.map | 1 - dist/v-1451995127167/js/maps/libs.js.map | 1 - .../styles/theme-high-contrast.css | 4 - .../styles/theme-material-design.css | 4 - dist/v-1451995127167/styles/theme-taiga.css | 4 - dist/v-1451995127167/svg/lock.svg | 7 - .../fonts/OpenSans-Bold.ttf | Bin .../fonts/OpenSans-CondLight.eot | Bin .../fonts/OpenSans-CondLight.svg | 0 .../fonts/OpenSans-CondLight.ttf | Bin .../fonts/OpenSans-CondLight.woff | Bin .../fonts/OpenSans-Light.ttf | Bin .../fonts/OpenSans-Regular.ttf | Bin .../fonts/OpenSans-Semibold.ttf | Bin .../fonts/taiga.eot | Bin .../fonts/taiga.svg | 0 .../fonts/taiga.ttf | Bin .../fonts/taiga.woff | Bin .../images/attachment-gallery.png | Bin 0 -> 1797 bytes .../images/backlog-empty.png | Bin .../images/beta.png | Bin .../images/bg.png | Bin dist/v-1454069705160/images/discover.png | Bin 0 -> 8211 bytes .../images/favicon.png | Bin .../images/invitation_bg.jpg | Bin .../images/issues-empty.png | Bin .../images/logo-color.png | Bin .../images/logo.png | Bin .../images/looking-for-people.png | Bin 0 -> 12019 bytes .../images/markitup/bg-container.png | Bin .../images/markitup/bg-editor-bbcode.png | Bin .../images/markitup/bg-editor-dotclear.png | Bin .../images/markitup/bg-editor-html.png | Bin .../images/markitup/bg-editor-json.png | Bin .../images/markitup/bg-editor-markdown.png | Bin .../images/markitup/bg-editor-textile.png | Bin .../images/markitup/bg-editor-wiki.png | Bin .../images/markitup/bg-editor-xml.png | Bin .../images/markitup/bg-editor.png | Bin .../images/markitup/body.png | Bin .../images/markitup/bold.png | Bin .../images/markitup/clean.png | Bin .../images/markitup/code.png | Bin .../images/markitup/h1.png | Bin .../images/markitup/h2.png | Bin .../images/markitup/h3.png | Bin .../images/markitup/h4.png | Bin .../images/markitup/h5.png | Bin .../images/markitup/h6.png | Bin .../images/markitup/handle.png | Bin .../images/markitup/help.png | Bin .../images/markitup/image.png | Bin .../images/markitup/italic.png | Bin .../images/markitup/jaysalvat.png | Bin .../images/markitup/link.png | Bin .../images/markitup/list-bullet.png | Bin .../images/markitup/list-numeric.png | Bin .../images/markitup/markitup.png | Bin .../images/markitup/menu.png | Bin .../images/markitup/picture.png | Bin .../images/markitup/preview.png | Bin .../images/markitup/preview_ico.png | Bin .../images/markitup/quotes.png | Bin .../images/markitup/stroke.png | Bin .../images/markitup/submenu.png | Bin .../images/menu-vert.png | Bin .../images/menu.png | Bin .../images/notification-decoration.png | Bin .../images/project-logos/project-logo-01.png | Bin 0 -> 724 bytes .../images/project-logos/project-logo-02.png | Bin 0 -> 927 bytes .../images/project-logos/project-logo-03.png | Bin 0 -> 623 bytes .../images/project-logos/project-logo-04.png | Bin 0 -> 1098 bytes .../images/project-logos/project-logo-05.png | Bin 0 -> 1383 bytes .../images/quote.png | Bin .../images/search-empty.png | Bin .../images/sprint-empty.png | Bin .../images/unnamed.png | Bin .../images/user-noimage.png | Bin .../js/app-loader.js | 4 +- dist/v-1454069705160/js/app.js | 23 + dist/v-1454069705160/js/libs.js | 46 + dist/v-1454069705160/js/maps/app.js.map | 1 + dist/v-1454069705160/js/maps/libs.js.map | 1 + .../js/templates.js | 159 +- .../locales/taiga/locale-ca.json | 98 +- .../locales/taiga/locale-de.json | 98 +- .../locales/taiga/locale-en.json | 84 +- .../locales/taiga/locale-es.json | 100 +- .../locales/taiga/locale-fi.json | 98 +- .../locales/taiga/locale-fr.json | 384 +++-- .../locales/taiga/locale-it.json | 142 +- .../locales/taiga/locale-nl.json | 98 +- .../locales/taiga/locale-pl.json | 98 +- .../locales/taiga/locale-pt-br.json | 138 +- .../locales/taiga/locale-ru.json | 98 +- .../locales/taiga/locale-sv.json | 1476 +++++++++++++++++ .../locales/taiga/locale-tr.json | 1476 +++++++++++++++++ .../locales/taiga/locale-zh-hant.json | 250 +-- .../styles/theme-high-contrast.css | 4 + .../styles/theme-material-design.css | 4 + dist/v-1454069705160/styles/theme-taiga.css | 4 + dist/v-1454069705160/svg/activity.svg | 5 + .../svg/add.svg | 0 dist/v-1454069705160/svg/attachment.svg | 3 + .../svg/check.svg | 0 .../svg/client-requirement.svg | 4 + .../svg/dashboard.svg | 0 dist/v-1454069705160/svg/discover.svg | 3 + .../svg/empty-project.svg | 0 .../svg/eye.svg | 0 .../svg/flag.svg | 0 dist/v-1454069705160/svg/gallery.svg | 3 + .../svg/graph.svg | 0 dist/v-1454069705160/svg/help.svg | 4 + .../svg/hide.svg | 0 dist/v-1454069705160/svg/iocaine.svg | 4 + .../svg/like.svg | 0 dist/v-1454069705160/svg/list.svg | 3 + .../svg/location.svg | 0 dist/v-1454069705160/svg/lock.svg | 3 + .../svg/logo-color.svg | 0 .../svg/logo-moustache.svg | 0 .../svg/logo-nav.svg | 0 .../svg/logo.svg | 0 .../svg/organizations.svg | 0 dist/v-1454069705160/svg/pattern.svg | 1 + dist/v-1454069705160/svg/project.svg | 3 + .../svg/projects.svg | 0 dist/v-1454069705160/svg/promote.svg | 3 + dist/v-1454069705160/svg/recruit.svg | 4 + .../svg/remove.svg | 0 dist/v-1454069705160/svg/search.svg | 5 + .../svg/spinner-circle.svg | 0 .../svg/spinner.svg | 0 dist/v-1454069705160/svg/team-requirement.svg | 4 + dist/v-1454069705160/svg/team.svg | 4 + .../svg/timeline.svg | 0 dist/v-1454069705160/svg/trash.svg | 3 + dist/v-1454069705160/svg/unlock.svg | 3 + .../svg/unwatch.svg | 0 .../svg/upvote.svg | 0 .../svg/watch.svg | 0 145 files changed, 4416 insertions(+), 632 deletions(-) delete mode 100644 dist/v-1451995127167/js/app.js delete mode 100644 dist/v-1451995127167/js/libs.js delete mode 100644 dist/v-1451995127167/js/maps/app.js.map delete mode 100644 dist/v-1451995127167/js/maps/libs.js.map delete mode 100644 dist/v-1451995127167/styles/theme-high-contrast.css delete mode 100644 dist/v-1451995127167/styles/theme-material-design.css delete mode 100644 dist/v-1451995127167/styles/theme-taiga.css delete mode 100644 dist/v-1451995127167/svg/lock.svg rename dist/{v-1451995127167 => v-1454069705160}/fonts/OpenSans-Bold.ttf (100%) rename dist/{v-1451995127167 => v-1454069705160}/fonts/OpenSans-CondLight.eot (100%) rename dist/{v-1451995127167 => v-1454069705160}/fonts/OpenSans-CondLight.svg (100%) rename dist/{v-1451995127167 => v-1454069705160}/fonts/OpenSans-CondLight.ttf (100%) rename dist/{v-1451995127167 => v-1454069705160}/fonts/OpenSans-CondLight.woff (100%) rename dist/{v-1451995127167 => v-1454069705160}/fonts/OpenSans-Light.ttf (100%) rename dist/{v-1451995127167 => v-1454069705160}/fonts/OpenSans-Regular.ttf (100%) rename dist/{v-1451995127167 => v-1454069705160}/fonts/OpenSans-Semibold.ttf (100%) rename dist/{v-1451995127167 => v-1454069705160}/fonts/taiga.eot (100%) rename dist/{v-1451995127167 => v-1454069705160}/fonts/taiga.svg (100%) rename dist/{v-1451995127167 => v-1454069705160}/fonts/taiga.ttf (100%) rename dist/{v-1451995127167 => v-1454069705160}/fonts/taiga.woff (100%) create mode 100644 dist/v-1454069705160/images/attachment-gallery.png rename dist/{v-1451995127167 => v-1454069705160}/images/backlog-empty.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/beta.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/bg.png (100%) create mode 100644 dist/v-1454069705160/images/discover.png rename dist/{v-1451995127167 => v-1454069705160}/images/favicon.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/invitation_bg.jpg (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/issues-empty.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/logo-color.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/logo.png (100%) create mode 100644 dist/v-1454069705160/images/looking-for-people.png rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/bg-container.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/bg-editor-bbcode.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/bg-editor-dotclear.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/bg-editor-html.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/bg-editor-json.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/bg-editor-markdown.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/bg-editor-textile.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/bg-editor-wiki.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/bg-editor-xml.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/bg-editor.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/body.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/bold.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/clean.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/code.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/h1.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/h2.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/h3.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/h4.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/h5.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/h6.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/handle.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/help.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/image.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/italic.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/jaysalvat.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/link.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/list-bullet.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/list-numeric.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/markitup.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/menu.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/picture.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/preview.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/preview_ico.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/quotes.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/stroke.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/markitup/submenu.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/menu-vert.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/menu.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/notification-decoration.png (100%) create mode 100644 dist/v-1454069705160/images/project-logos/project-logo-01.png create mode 100644 dist/v-1454069705160/images/project-logos/project-logo-02.png create mode 100644 dist/v-1454069705160/images/project-logos/project-logo-03.png create mode 100644 dist/v-1454069705160/images/project-logos/project-logo-04.png create mode 100644 dist/v-1454069705160/images/project-logos/project-logo-05.png rename dist/{v-1451995127167 => v-1454069705160}/images/quote.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/search-empty.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/sprint-empty.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/unnamed.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/images/user-noimage.png (100%) rename dist/{v-1451995127167 => v-1454069705160}/js/app-loader.js (96%) create mode 100644 dist/v-1454069705160/js/app.js create mode 100644 dist/v-1454069705160/js/libs.js create mode 100644 dist/v-1454069705160/js/maps/app.js.map create mode 100644 dist/v-1454069705160/js/maps/libs.js.map rename dist/{v-1451995127167 => v-1454069705160}/js/templates.js (66%) rename dist/{v-1451995127167 => v-1454069705160}/locales/taiga/locale-ca.json (93%) rename dist/{v-1451995127167 => v-1454069705160}/locales/taiga/locale-de.json (94%) rename dist/{v-1451995127167 => v-1454069705160}/locales/taiga/locale-en.json (94%) rename dist/{v-1451995127167 => v-1454069705160}/locales/taiga/locale-es.json (93%) rename dist/{v-1451995127167 => v-1454069705160}/locales/taiga/locale-fi.json (93%) rename dist/{v-1451995127167 => v-1454069705160}/locales/taiga/locale-fr.json (82%) rename dist/{v-1451995127167 => v-1454069705160}/locales/taiga/locale-it.json (90%) rename dist/{v-1451995127167 => v-1454069705160}/locales/taiga/locale-nl.json (94%) rename dist/{v-1451995127167 => v-1454069705160}/locales/taiga/locale-pl.json (94%) rename dist/{v-1451995127167 => v-1454069705160}/locales/taiga/locale-pt-br.json (92%) rename dist/{v-1451995127167 => v-1454069705160}/locales/taiga/locale-ru.json (95%) create mode 100644 dist/v-1454069705160/locales/taiga/locale-sv.json create mode 100644 dist/v-1454069705160/locales/taiga/locale-tr.json rename dist/{v-1451995127167 => v-1454069705160}/locales/taiga/locale-zh-hant.json (86%) create mode 100644 dist/v-1454069705160/styles/theme-high-contrast.css create mode 100644 dist/v-1454069705160/styles/theme-material-design.css create mode 100644 dist/v-1454069705160/styles/theme-taiga.css create mode 100644 dist/v-1454069705160/svg/activity.svg rename dist/{v-1451995127167 => v-1454069705160}/svg/add.svg (100%) create mode 100644 dist/v-1454069705160/svg/attachment.svg rename dist/{v-1451995127167 => v-1454069705160}/svg/check.svg (100%) create mode 100644 dist/v-1454069705160/svg/client-requirement.svg rename dist/{v-1451995127167 => v-1454069705160}/svg/dashboard.svg (100%) create mode 100644 dist/v-1454069705160/svg/discover.svg rename dist/{v-1451995127167 => v-1454069705160}/svg/empty-project.svg (100%) rename dist/{v-1451995127167 => v-1454069705160}/svg/eye.svg (100%) rename dist/{v-1451995127167 => v-1454069705160}/svg/flag.svg (100%) create mode 100644 dist/v-1454069705160/svg/gallery.svg rename dist/{v-1451995127167 => v-1454069705160}/svg/graph.svg (100%) create mode 100644 dist/v-1454069705160/svg/help.svg rename dist/{v-1451995127167 => v-1454069705160}/svg/hide.svg (100%) create mode 100644 dist/v-1454069705160/svg/iocaine.svg rename dist/{v-1451995127167 => v-1454069705160}/svg/like.svg (100%) create mode 100644 dist/v-1454069705160/svg/list.svg rename dist/{v-1451995127167 => v-1454069705160}/svg/location.svg (100%) create mode 100644 dist/v-1454069705160/svg/lock.svg rename dist/{v-1451995127167 => v-1454069705160}/svg/logo-color.svg (100%) rename dist/{v-1451995127167 => v-1454069705160}/svg/logo-moustache.svg (100%) rename dist/{v-1451995127167 => v-1454069705160}/svg/logo-nav.svg (100%) rename dist/{v-1451995127167 => v-1454069705160}/svg/logo.svg (100%) rename dist/{v-1451995127167 => v-1454069705160}/svg/organizations.svg (100%) create mode 100644 dist/v-1454069705160/svg/pattern.svg create mode 100644 dist/v-1454069705160/svg/project.svg rename dist/{v-1451995127167 => v-1454069705160}/svg/projects.svg (100%) create mode 100644 dist/v-1454069705160/svg/promote.svg create mode 100644 dist/v-1454069705160/svg/recruit.svg rename dist/{v-1451995127167 => v-1454069705160}/svg/remove.svg (100%) create mode 100644 dist/v-1454069705160/svg/search.svg rename dist/{v-1451995127167 => v-1454069705160}/svg/spinner-circle.svg (100%) rename dist/{v-1451995127167 => v-1454069705160}/svg/spinner.svg (100%) create mode 100644 dist/v-1454069705160/svg/team-requirement.svg create mode 100644 dist/v-1454069705160/svg/team.svg rename dist/{v-1451995127167 => v-1454069705160}/svg/timeline.svg (100%) create mode 100644 dist/v-1454069705160/svg/trash.svg create mode 100644 dist/v-1454069705160/svg/unlock.svg rename dist/{v-1451995127167 => v-1454069705160}/svg/unwatch.svg (100%) rename dist/{v-1451995127167 => v-1454069705160}/svg/upvote.svg (100%) rename dist/{v-1451995127167 => v-1454069705160}/svg/watch.svg (100%) diff --git a/dist/index.html b/dist/index.html index b0408f4..e2a99b0 100644 --- a/dist/index.html +++ b/dist/index.html @@ -8,8 +8,9 @@ Taiga - - + + + - - + + + \ No newline at end of file diff --git a/dist/v-1451995127167/js/app.js b/dist/v-1451995127167/js/app.js deleted file mode 100644 index 88db2cc..0000000 --- a/dist/v-1451995127167/js/app.js +++ /dev/null @@ -1,22 +0,0 @@ -(function(){var configure,i18nInit,init,module,modules,pluginsWithModule,taiga;this.taiga=taiga={},this.taigaContribPlugins=this.taigaContribPlugins||window.taigaContribPlugins||[],taiga.generateHash=function(components){return null==components&&(components=[]),components=_.map(components,function(x){return JSON.stringify(x)}),hex_sha1(components.join(":"))},taiga.generateUniqueSessionIdentifier=function(){var date,randomNumber;return date=(new Date).getTime(),randomNumber=Math.floor(150994944*Math.random()),taiga.generateHash([date,randomNumber])},taiga.sessionId=taiga.generateUniqueSessionIdentifier(),configure=function($routeProvider,$locationProvider,$httpProvider,$provide,$tgEventsProvider,$compileProvider,$translateProvider,$translatePartialLoaderProvider,$animateProvider){var authHttpIntercept,decorators,defaultHeaders,loaderIntercept,originalWhen,preferedLangCode,userInfo,versionCheckHttpIntercept;return $animateProvider.classNameFilter(/^(?:(?!ng-animate-disabled).)*$/),originalWhen=$routeProvider.when,$routeProvider.when=function(path,route){return route.resolve||(route.resolve={}),angular.extend(route.resolve,{languageLoad:["$q","$translate",function($q,$translate){var deferred;return deferred=$q.defer(),$translate().then(function(){return deferred.resolve()}),deferred.promise}]}),originalWhen.call($routeProvider,path,route)},$routeProvider.when("/",{templateUrl:"home/home.html",access:{requiresLogin:!0},loader:!0,title:"HOME.PAGE_TITLE",loader:!0,description:"HOME.PAGE_DESCRIPTION",joyride:"dashboard"}),$routeProvider.when("/projects/",{templateUrl:"projects/listing/projects-listing.html",access:{requiresLogin:!0},title:"PROJECTS.PAGE_TITLE",description:"PROJECTS.PAGE_DESCRIPTION",loader:!0,controller:"ProjectsListing",controllerAs:"vm"}),$routeProvider.when("/project/:pslug/",{templateUrl:"projects/project/project.html",loader:!0,controller:"Project",controllerAs:"vm",section:"project-timeline"}),$routeProvider.when("/project/:pslug/search",{templateUrl:"search/search.html",reloadOnSearch:!1,section:"search",loader:!0}),$routeProvider.when("/project/:pslug/backlog",{templateUrl:"backlog/backlog.html",loader:!0,section:"backlog",joyride:"backlog"}),$routeProvider.when("/project/:pslug/kanban",{templateUrl:"kanban/kanban.html",loader:!0,section:"kanban",joyride:"kanban"}),$routeProvider.when("/project/:pslug/taskboard/:sslug",{templateUrl:"taskboard/taskboard.html",loader:!0,section:"backlog"}),$routeProvider.when("/project/:pslug/us/:usref",{templateUrl:"us/us-detail.html",loader:!0,section:"backlog-kanban"}),$routeProvider.when("/project/:pslug/task/:taskref",{templateUrl:"task/task-detail.html",loader:!0,section:"backlog-kanban"}),$routeProvider.when("/project/:pslug/wiki",{redirectTo:function(params){return"/project/"+params.pslug+"/wiki/home"}}),$routeProvider.when("/project/:pslug/wiki/:slug",{templateUrl:"wiki/wiki.html",loader:!0,section:"wiki"}),$routeProvider.when("/project/:pslug/team",{templateUrl:"team/team.html",loader:!0,section:"team"}),$routeProvider.when("/project/:pslug/issues",{templateUrl:"issue/issues.html",loader:!0,section:"issues"}),$routeProvider.when("/project/:pslug/issue/:issueref",{templateUrl:"issue/issues-detail.html",loader:!0,section:"issues"}),$routeProvider.when("/project/:pslug/admin/project-profile/details",{templateUrl:"admin/admin-project-profile.html",section:"admin"}),$routeProvider.when("/project/:pslug/admin/project-profile/default-values",{templateUrl:"admin/admin-project-default-values.html",section:"admin"}),$routeProvider.when("/project/:pslug/admin/project-profile/modules",{templateUrl:"admin/admin-project-modules.html",section:"admin"}),$routeProvider.when("/project/:pslug/admin/project-profile/export",{templateUrl:"admin/admin-project-export.html",section:"admin"}),$routeProvider.when("/project/:pslug/admin/project-profile/reports",{templateUrl:"admin/admin-project-reports.html",section:"admin"}),$routeProvider.when("/project/:pslug/admin/project-values/status",{templateUrl:"admin/admin-project-values-status.html",section:"admin"}),$routeProvider.when("/project/:pslug/admin/project-values/points",{templateUrl:"admin/admin-project-values-points.html",section:"admin"}),$routeProvider.when("/project/:pslug/admin/project-values/priorities",{templateUrl:"admin/admin-project-values-priorities.html",section:"admin"}),$routeProvider.when("/project/:pslug/admin/project-values/severities",{templateUrl:"admin/admin-project-values-severities.html",section:"admin"}),$routeProvider.when("/project/:pslug/admin/project-values/types",{templateUrl:"admin/admin-project-values-types.html",section:"admin"}),$routeProvider.when("/project/:pslug/admin/project-values/custom-fields",{templateUrl:"admin/admin-project-values-custom-fields.html",section:"admin"}),$routeProvider.when("/project/:pslug/admin/memberships",{templateUrl:"admin/admin-memberships.html",section:"admin"}),$routeProvider.when("/project/:pslug/admin/roles",{templateUrl:"admin/admin-roles.html",section:"admin"}),$routeProvider.when("/project/:pslug/admin/third-parties/webhooks",{templateUrl:"admin/admin-third-parties-webhooks.html",section:"admin"}),$routeProvider.when("/project/:pslug/admin/third-parties/github",{templateUrl:"admin/admin-third-parties-github.html",section:"admin"}),$routeProvider.when("/project/:pslug/admin/third-parties/gitlab",{templateUrl:"admin/admin-third-parties-gitlab.html",section:"admin"}),$routeProvider.when("/project/:pslug/admin/third-parties/bitbucket",{templateUrl:"admin/admin-third-parties-bitbucket.html",section:"admin"}),$routeProvider.when("/project/:pslug/admin/contrib/:plugin",{templateUrl:"contrib/main.html"}),$routeProvider.when("/user-settings/user-profile",{templateUrl:"user/user-profile.html"}),$routeProvider.when("/user-settings/user-change-password",{templateUrl:"user/user-change-password.html"}),$routeProvider.when("/user-settings/mail-notifications",{templateUrl:"user/mail-notifications.html"}),$routeProvider.when("/change-email/:email_token",{templateUrl:"user/change-email.html"}),$routeProvider.when("/cancel-account/:cancel_token",{templateUrl:"user/cancel-account.html"}),$routeProvider.when("/profile",{templateUrl:"profile/profile.html",loader:!0,access:{requiresLogin:!0},controller:"Profile",controllerAs:"vm"}),$routeProvider.when("/profile/:slug",{templateUrl:"profile/profile.html",loader:!0,controller:"Profile",controllerAs:"vm"}),$routeProvider.when("/login",{templateUrl:"auth/login.html",title:"LOGIN.PAGE_TITLE",description:"LOGIN.PAGE_DESCRIPTION",disableHeader:!0}),$routeProvider.when("/register",{templateUrl:"auth/register.html",title:"REGISTER.PAGE_TITLE",description:"REGISTER.PAGE_DESCRIPTION",disableHeader:!0}),$routeProvider.when("/forgot-password",{templateUrl:"auth/forgot-password.html",title:"FORGOT_PASSWORD.PAGE_TITLE",description:"FORGOT_PASSWORD.PAGE_DESCRIPTION",disableHeader:!0}),$routeProvider.when("/change-password/:token",{templateUrl:"auth/change-password-from-recovery.html",title:"CHANGE_PASSWORD.PAGE_TITLE",description:"CHANGE_PASSWORD.PAGE_TITLE",disableHeader:!0}),$routeProvider.when("/invitation/:token",{templateUrl:"auth/invitation.html",title:"INVITATION.PAGE_TITLE",description:"INVITATION.PAGE_DESCRIPTION",disableHeader:!0}),$routeProvider.when("/external-apps",{templateUrl:"external-apps/external-app.html",title:"EXTERNAL_APP.PAGE_TITLE",description:"EXTERNAL_APP.PAGE_DESCRIPTION",controller:"ExternalApp",controllerAs:"vm",disableHeader:!0,mobileViewport:!0}),$routeProvider.when("/error",{templateUrl:"error/error.html"}),$routeProvider.when("/not-found",{templateUrl:"error/not-found.html"}),$routeProvider.when("/permission-denied",{templateUrl:"error/permission-denied.html"}),$routeProvider.otherwise({redirectTo:"/not-found"}),$locationProvider.html5Mode({enabled:!0,requireBase:!1}),defaultHeaders={"Content-Type":"application/json","Accept-Language":window.taigaConfig.defaultLanguage||"en","X-Session-Id":taiga.sessionId},$httpProvider.defaults.headers["delete"]=defaultHeaders,$httpProvider.defaults.headers.patch=defaultHeaders,$httpProvider.defaults.headers.post=defaultHeaders,$httpProvider.defaults.headers.put=defaultHeaders,$httpProvider.defaults.headers.get={"X-Session-Id":taiga.sessionId},$httpProvider.useApplyAsync(!0),$tgEventsProvider.setSessionId(taiga.sessionId),authHttpIntercept=function($q,$location,$navUrls,$lightboxService){var httpResponseError;return httpResponseError=function(response){var nextUrl;return 0===response.status||-1===response.status&&!response.config.cancelable?($lightboxService.closeAll(),$location.path($navUrls.resolve("error")),$location.replace()):401===response.status&&-1===$location.url().indexOf("/login")&&(nextUrl=encodeURIComponent($location.url()),$location.url($navUrls.resolve("login")).search("next="+nextUrl)),$q.reject(response)},{responseError:httpResponseError}},$provide.factory("authHttpIntercept",["$q","$location","$tgNavUrls","lightboxService",authHttpIntercept]),$httpProvider.interceptors.push("authHttpIntercept"),loaderIntercept=function($q,loaderService){return{request:function(config){return loaderService.logRequest(),config},requestError:function(rejection){return loaderService.logResponse(),$q.reject(rejection)},responseError:function(rejection){return loaderService.logResponse(),$q.reject(rejection)},response:function(response){return loaderService.logResponse(),response}}},$provide.factory("loaderIntercept",["$q","tgLoader",loaderIntercept]),$httpProvider.interceptors.push("loaderIntercept"),versionCheckHttpIntercept=function($q){var httpResponseError;return httpResponseError=function(response){var $injector;return 400===response.status&&response.data.version&&($injector=angular.element("body").injector(),$injector.invoke(["$tgConfirm","$translate",function(_this){return function($confirm,$translate){var versionErrorMsg;return versionErrorMsg=$translate.instant("ERROR.VERSION_ERROR"),$confirm.notify("error",versionErrorMsg,null,1e4)}}(this)])),$q.reject(response)},{responseError:httpResponseError}},$provide.factory("versionCheckHttpIntercept",["$q",versionCheckHttpIntercept]),$httpProvider.interceptors.push("versionCheckHttpIntercept"),window.checksley.updateValidators({linewidth:function(val,width){var lines,valid;return lines=taiga.nl2br(val).split("
"),valid=_.every(lines,function(line){return line.lengthi;i++)if(i in this&&this[i]===item)return i;return-1},slice=[].slice,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;nl2br=function(_this){return function(str){var breakTag;return breakTag="
",(str+"").replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g,"$1"+breakTag+"$2")}}(this),bindMethods=function(_this){return function(object){var dependencies,methods;return dependencies=_.keys(object),methods=[],_.forIn(object,function(value,key){return indexOf.call(dependencies,key)<0?methods.push(key):void 0}),_.bindAll(object,methods)}}(this),bindOnce=function(_this){return function(scope,attr,continuation){var delBind,val;return val=scope.$eval(attr),void 0!==val?continuation(val):(delBind=null,delBind=scope.$watch(attr,function(val){return void 0!==val?(continuation(val),delBind?delBind():void 0):void 0}))}}(this),mixOf=function(){var Mixed,base,i,method,mixin,mixins,name,ref;for(base=arguments[0],mixins=2<=arguments.length?slice.call(arguments,1):[],Mixed=function(superClass){function Mixed(){return Mixed.__super__.constructor.apply(this,arguments)}return extend(Mixed,superClass),Mixed}(base),i=mixins.length-1;i>=0;i+=-1){mixin=mixins[i],ref=mixin.prototype;for(name in ref)method=ref[name],Mixed.prototype[name]=method}return Mixed},trim=function(data,char){return _.str.trim(data,char)},slugify=function(data){return _.str.slugify(data)},unslugify=function(data){return data?_.str.capitalize(data.replace(/-/g," ")):data},toggleText=function(element,texts){var nextTextPosition,text;return nextTextPosition=element.data("nextTextPosition"),(null==nextTextPosition||nextTextPosition>=texts.length)&&(nextTextPosition=0),text=texts[nextTextPosition],element.data("nextTextPosition",nextTextPosition+1),element.text(text)},groupBy=function(coll,pred){var i,item,len,result;for(result={},i=0,len=coll.length;len>i;i++)item=coll[i],result[pred(item)]=item;return result},timeout=function(wait,continuation){return window.setTimeout(continuation,wait)},cancelTimeout=function(timeoutVar){return window.clearTimeout(timeoutVar)},scopeDefer=function(scope,func){return _.defer(function(_this){return function(){return scope.$apply(func)}}(this))},toString=function(value){return _.isNumber(value)?value+"":_.isString(value)?value:_.isPlainObject(value)?JSON.stringify(value):_.isUndefined(value)?"":value.toString()},joinStr=function(str,coll){return _.str.join(str,coll)},debounce=function(wait,func){return _.debounce(func,wait,{leading:!0,trailing:!1})},debounceLeading=function(wait,func){return _.debounce(func,wait,{leading:!1,trailing:!0})},startswith=function(str1,str2){return _.str.startsWith(str1,str2)},truncate=function(str,maxLength,suffix){var out;return null==suffix&&(suffix="..."),"string"==typeof str||str instanceof String?(out=str.slice(0),out.length>maxLength&&(out=out.substring(0,maxLength+1),out=out.substring(0,Math.min(out.length,out.lastIndexOf(" "))),out+=suffix),out):str},sizeFormat=function(input,precision){var number,size,units;return null==precision&&(precision=1),isNaN(parseFloat(input))||!isFinite(input)?"-":0===input?"0 bytes":(units=["bytes","KB","MB","GB","TB","PB"],number=Math.floor(Math.log(input)/Math.log(1024)),number>5&&(number=5),size=(input/Math.pow(1024,number)).toFixed(precision),size+" "+units[number])},stripTags=function(str,exception){var pattern;return exception?(pattern=new RegExp("<(?!"+exception+"s*/?)[^>]+>","gi"),String(str).replace(pattern,"")):String(str).replace(/<\/?[^>]+>/g,"")},replaceTags=function(str,tags,replace){var pattern;return pattern=new RegExp("<("+tags+")>","gi"),str=str.replace(pattern,"<"+replace+">"),pattern=new RegExp("","gi"),str=str.replace(pattern,"")},defineImmutableProperty=function(_this){return function(obj,name,fn){return Object.defineProperty(obj,name,{get:function(){var fn_result;if(!_.isFunction(fn))throw"defineImmutableProperty third param must be a function";if(fn_result=fn(),fn_result&&_.isObject(fn_result)&&void 0===fn_result.size)throw"defineImmutableProperty must return immutable data";return fn_result}})}}(this),_.mixin({removeKeys:function(obj,keys){return _.chain([keys]).flatten().reduce(function(obj,key){return delete obj[key],obj},obj).value()}}),taiga=this.taiga,taiga.nl2br=nl2br,taiga.bindMethods=bindMethods,taiga.bindOnce=bindOnce,taiga.mixOf=mixOf,taiga.trim=trim,taiga.slugify=slugify,taiga.unslugify=unslugify,taiga.toggleText=toggleText,taiga.groupBy=groupBy,taiga.timeout=timeout,taiga.cancelTimeout=cancelTimeout,taiga.scopeDefer=scopeDefer,taiga.toString=toString,taiga.joinStr=joinStr,taiga.truncate=truncate,taiga.debounce=debounce,taiga.debounceLeading=debounceLeading,taiga.startswith=startswith,taiga.sizeFormat=sizeFormat,taiga.stripTags=stripTags,taiga.replaceTags=replaceTags,taiga.defineImmutableProperty=defineImmutableProperty}.call(this),function(){var FiltersMixin,PageMixin,groupBy,joinStr,taiga,toString,trim;taiga=this.taiga,groupBy=this.taiga.groupBy,joinStr=this.taiga.joinStr,trim=this.taiga.trim,toString=this.taiga.toString,PageMixin=function(){function PageMixin(){}return PageMixin.prototype.fillUsersAndRoles=function(users,roles){var activeUsers,computableRoles;return activeUsers=_.filter(users,function(_this){return function(user){return user.is_active}}(this)),this.scope.activeUsers=_.sortBy(activeUsers,"full_name_display"),this.scope.activeUsersById=groupBy(this.scope.activeUsers,function(e){return e.id}),this.scope.users=_.sortBy(users,"full_name_display"),this.scope.usersById=groupBy(this.scope.users,function(e){return e.id}),this.scope.roles=_.sortBy(roles,"order"),computableRoles=_(this.scope.project.members).map("role").uniq().value(),this.scope.computableRoles=_(roles).filter("computable").filter(function(x){return _.contains(computableRoles,x.id)}).value()},PageMixin.prototype.loadUsersAndRoles=function(){var promise;return promise=this.q.all([this.rs.projects.usersList(this.scope.projectId),this.rs.projects.rolesList(this.scope.projectId)]),promise.then(function(_this){return function(results){var roles,users;return users=results[0],roles=results[1],_this.fillUsersAndRoles(users,roles),results}}(this))},PageMixin}(),taiga.PageMixin=PageMixin,FiltersMixin=function(){function FiltersMixin(){}return FiltersMixin.prototype.selectFilter=function(name,value,load){var existing,location,params;return null==load&&(load=!1),params=this.location.search(),void 0!==params[name]&&"page"!==name&&(existing=_.map(taiga.toString(params[name]).split(","),function(x){return trim(x)}),existing.push(taiga.toString(value)),existing=_.compact(existing),value=joinStr(",",_.uniq(existing))),this.location.isInCurrentRouteParams(name,value)?void 0:(location=load?this.location:this.location.noreload(this.scope),location.search(name,value))},FiltersMixin.prototype.replaceFilter=function(name,value,load){var location;return null==load&&(load=!1),this.location.isInCurrentRouteParams(name,value)?void 0:(location=load?this.location:this.location.noreload(this.scope),location.search(name,value))},FiltersMixin.prototype.replaceAllFilters=function(filters,load){var location;return null==load&&(load=!1),location=load?this.location:this.location.noreload(this.scope),location.search(filters)},FiltersMixin.prototype.unselectFilter=function(name,value,load){var location,newValues,params,parsedValues;return null==load&&(load=!1),params=this.location.search(),void 0!==params[name]?((void 0===value||null===value)&&delete params[name],parsedValues=_.map(taiga.toString(params[name]).split(","),function(x){return trim(x)}),newValues=_.reject(parsedValues,function(x){return x===taiga.toString(value)}),newValues=_.compact(newValues),value=_.isEmpty(newValues)?null:joinStr(",",_.uniq(newValues)),location=load?this.location:this.location.noreload(this.scope),location.search(name,value)):void 0},FiltersMixin}(),taiga.FiltersMixin=FiltersMixin}.call(this),function(){var module;module=angular.module("taigaAdmin",[])}.call(this),function(){var AuthService,CancelAccountDirective,ChangeEmailDirective,ChangePasswordFromRecoveryDirective,ForgotPasswordDirective,InvitationDirective,LoginDirective,PublicRegisterMessageDirective,RegisterDirective,debounce,module,taiga,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,debounce=this.taiga.debounce,module=angular.module("taigaAuth",["taigaResources"]),AuthService=function(superClass){function AuthService(rootscope,storage,model,rs,http,urls,config,translate,currentUserService,themeService){var userModel;this.rootscope=rootscope,this.storage=storage,this.model=model,this.rs=rs,this.http=http,this.urls=urls,this.config=config,this.translate=translate,this.currentUserService=currentUserService,this.themeService=themeService,AuthService.__super__.constructor.call(this),userModel=this.getUser(),this._currentTheme=this._getUserTheme(),this.setUserdata(userModel)}return extend(AuthService,superClass),AuthService.$inject=["$rootScope","$tgStorage","$tgModel","$tgResources","$tgHttp","$tgUrls","$tgConfig","$translate","tgCurrentUserService","tgThemeService"],AuthService.prototype.setUserdata=function(userModel){return userModel?(this.userData=Immutable.fromJS(userModel.getAttrs()),this.currentUserService.setUser(this.userData)):this.userData=null},AuthService.prototype._getUserTheme=function(){var ref;return(null!=(ref=this.rootscope.user)?ref.theme:void 0)||this.config.get("defaultTheme")||"taiga"},AuthService.prototype._setTheme=function(){var newTheme;return newTheme=this._getUserTheme(),this._currentTheme!==newTheme?(this._currentTheme=newTheme,this.themeService.use(this._currentTheme)):void 0},AuthService.prototype._setLocales=function(){var lang,ref;return lang=(null!=(ref=this.rootscope.user)?ref.lang:void 0)||this.config.get("defaultLanguage")||"en",this.translate.preferredLanguage(lang),this.translate.use(lang)},AuthService.prototype.getUser=function(){var user,userData;return this.rootscope.user?this.rootscope.user:(userData=this.storage.get("userInfo"))?(user=this.model.make_model("users",userData),this.rootscope.user=user,this._setLocales(),this._setTheme(),user):(this._setTheme(),null)},AuthService.prototype.setUser=function(user){return this.rootscope.auth=user,this.storage.set("userInfo",user.getAttrs()),this.rootscope.user=user,this.setUserdata(user),this._setLocales(),this._setTheme()},AuthService.prototype.clear=function(){return this.rootscope.auth=null,this.rootscope.user=null,this.storage.remove("userInfo")},AuthService.prototype.setToken=function(token){return this.storage.set("token",token)},AuthService.prototype.getToken=function(){return this.storage.get("token")},AuthService.prototype.removeToken=function(){return this.storage.remove("token")},AuthService.prototype.isAuthenticated=function(){return null!==this.getUser()?!0:!1},AuthService.prototype.login=function(data,type){var url;return url=this.urls.resolve("auth"),data=_.clone(data,!1),data.type=type?type:"normal",this.removeToken(),this.http.post(url,data).then(function(_this){return function(data,status){var user;return user=_this.model.make_model("users",data.data),_this.setToken(user.auth_token),_this.setUser(user),user}}(this))},AuthService.prototype.logout=function(){return this.removeToken(),this.clear(),this.currentUserService.removeUser(),this._setTheme(),this._setLocales()},AuthService.prototype.register=function(data,type,existing){var url;return url=this.urls.resolve("auth-register"),data=_.clone(data,!1),data.type=type?type:"public","private"===type&&(data.existing=existing?existing:!1),this.removeToken(),this.http.post(url,data).then(function(_this){return function(response){var user;return user=_this.model.make_model("users",response.data),_this.setToken(user.auth_token),_this.setUser(user),user}}(this))},AuthService.prototype.getInvitation=function(token){return this.rs.invitations.get(token)},AuthService.prototype.acceptInvitiationWithNewUser=function(data){return this.register(data,"private",!1)},AuthService.prototype.acceptInvitiationWithExistingUser=function(data){return this.register(data,"private",!0)},AuthService.prototype.forgotPassword=function(data){var url;return url=this.urls.resolve("users-password-recovery"),data=_.clone(data,!1),this.removeToken(),this.http.post(url,data)},AuthService.prototype.changePasswordFromRecovery=function(data){var url;return url=this.urls.resolve("users-change-password-from-recovery"),data=_.clone(data,!1),this.removeToken(),this.http.post(url,data)},AuthService.prototype.changeEmail=function(data){var url;return url=this.urls.resolve("users-change-email"),data=_.clone(data,!1),this.http.post(url,data)},AuthService.prototype.cancelAccount=function(data){var url;return url=this.urls.resolve("users-cancel-account"),data=_.clone(data,!1),this.http.post(url,data)},AuthService}(taiga.Service),module.service("$tgAuth",AuthService),PublicRegisterMessageDirective=function($config,$navUrls,templates){var template,templateFn;return template=templates.get("auth/login-text.html",!0),templateFn=function(){var publicRegisterEnabled;return publicRegisterEnabled=$config.get("publicRegisterEnabled"),publicRegisterEnabled?template({url:$navUrls.resolve("register")}):""},{restrict:"AE",scope:{},template:templateFn}},module.directive("tgPublicRegisterMessage",["$tgConfig","$tgNavUrls","$tgTemplate",PublicRegisterMessageDirective]),LoginDirective=function($auth,$confirm,$location,$config,$routeParams,$navUrls,$events,$translate){var link;return link=function($scope,$el,$attrs){var form,onError,onSuccess,submit;return form=new checksley.Form($el.find("form.login-form")),onSuccess=function(response){var nextUrl;return nextUrl=$routeParams.next&&$routeParams.next!==$navUrls.resolve("login")?decodeURIComponent($routeParams.next):$navUrls.resolve("home"),$events.setupConnection(),$location.url(nextUrl)},onError=function(response){return $confirm.notify("light-error",$translate.instant("LOGIN_FORM.ERROR_AUTH_INCORRECT"))},submit=debounce(2e3,function(_this){return function(event){var data,loginFormType,promise;return event.preventDefault(),form.validate()?(data={username:$el.find("form.login-form input[name=username]").val(),password:$el.find("form.login-form input[name=password]").val()},loginFormType=$config.get("loginFormType","normal"),promise=$auth.login(data,loginFormType),promise.then(onSuccess,onError)):void 0}}(this)),$el.on("submit","form",submit),window.prerenderReady=!0,$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgLogin",["$tgAuth","$tgConfirm","$tgLocation","$tgConfig","$routeParams","$tgNavUrls","$tgEvents","$translate",LoginDirective]),RegisterDirective=function($auth,$confirm,$location,$navUrls,$config,$analytics,$translate){ -var link;return link=function($scope,$el,$attrs){var form,onErrorSubmit,onSuccessSubmit,submit;return $config.get("publicRegisterEnabled")||($location.path($navUrls.resolve("not-found")),$location.replace()),$scope.data={},form=$el.find("form").checksley({onlyOneErrorElement:!0}),onSuccessSubmit=function(response){return $analytics.trackEvent("auth","register","user registration",1),$confirm.notify("success",$translate.instant("LOGIN_FORM.SUCCESS")),$location.path($navUrls.resolve("home"))},onErrorSubmit=function(response){var text;return response.data._error_message&&(text=$translate.instant("COMMON.GENERIC_ERROR",{error:response.data._error_message}),$confirm.notify("light-error",text)),form.setErrors(response.data)},submit=debounce(2e3,function(_this){return function(event){var promise;return event.preventDefault(),form.validate()?(promise=$auth.register($scope.data),promise.then(onSuccessSubmit,onErrorSubmit)):void 0}}(this)),$el.on("submit","form",submit),$scope.$on("$destroy",function(){return $el.off()}),window.prerenderReady=!0},{link:link}},module.directive("tgRegister",["$tgAuth","$tgConfirm","$tgLocation","$tgNavUrls","$tgConfig","$tgAnalytics","$translate",RegisterDirective]),ForgotPasswordDirective=function($auth,$confirm,$location,$navUrls,$translate){var link;return link=function($scope,$el,$attrs){var form,onErrorSubmit,onSuccessSubmit,submit;return $scope.data={},form=$el.find("form").checksley(),onSuccessSubmit=function(response){var text;return $location.path($navUrls.resolve("login")),text=$translate.instant("FORGOT_PASSWORD_FORM.SUCCESS"),$confirm.success(text)},onErrorSubmit=function(response){var text;return text=$translate.instant("FORGOT_PASSWORD_FORM.ERROR"),$confirm.notify("light-error",text)},submit=debounce(2e3,function(_this){return function(event){var promise;return event.preventDefault(),form.validate()?(promise=$auth.forgotPassword($scope.data),promise.then(onSuccessSubmit,onErrorSubmit)):void 0}}(this)),$el.on("submit","form",submit),$scope.$on("$destroy",function(){return $el.off()}),window.prerenderReady=!0},{link:link}},module.directive("tgForgotPassword",["$tgAuth","$tgConfirm","$tgLocation","$tgNavUrls","$translate",ForgotPasswordDirective]),ChangePasswordFromRecoveryDirective=function($auth,$confirm,$location,$params,$navUrls,$translate){var link;return link=function($scope,$el,$attrs){var form,onErrorSubmit,onSuccessSubmit,submit,text;return $scope.data={},null!=$params.token?($scope.tokenInParams=!0,$scope.data.token=$params.token):($location.path($navUrls.resolve("login")),text=$translate.instant("CHANGE_PASSWORD_RECOVERY_FORM.ERROR"),$confirm.notify("light-error",text)),form=$el.find("form").checksley(),onSuccessSubmit=function(response){return $location.path($navUrls.resolve("login")),text=$translate.instant("CHANGE_PASSWORD_RECOVERY_FORM.SUCCESS"),$confirm.success(text)},onErrorSubmit=function(response){return text=$translate.instant("CHANGE_PASSWORD_RECOVERY_FORM.ERROR"),$confirm.notify("light-error",text)},submit=debounce(2e3,function(_this){return function(event){var promise;return event.preventDefault(),form.validate()?(promise=$auth.changePasswordFromRecovery($scope.data),promise.then(onSuccessSubmit,onErrorSubmit)):void 0}}(this)),$el.on("submit","form",submit),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgChangePasswordFromRecovery",["$tgAuth","$tgConfirm","$tgLocation","$routeParams","$tgNavUrls","$translate",ChangePasswordFromRecoveryDirective]),InvitationDirective=function($auth,$confirm,$location,$params,$navUrls,$analytics,$translate){var link;return link=function($scope,$el,$attrs){var loginForm,onErrorSubmitLogin,onErrorSubmitRegister,onSuccessSubmitLogin,onSuccessSubmitRegister,promise,registerForm,submitLogin,submitRegister,token;return token=$params.token,promise=$auth.getInvitation(token),promise.then(function(invitation){return $scope.invitation=invitation}),promise.then(null,function(response){var text;return $location.path($navUrls.resolve("login")),text=$translate.instant("INVITATION_LOGIN_FORM.NOT_FOUND"),$confirm.notify("light-error",text)}),$scope.dataLogin={token:token},loginForm=$el.find("form.login-form").checksley({onlyOneErrorElement:!0}),onSuccessSubmitLogin=function(response){var text;return $analytics.trackEvent("auth","invitationAccept","invitation accept with existing user",1),$location.path($navUrls.resolve("project",{project:$scope.invitation.project_slug})),text=$translate.instant("INVITATION_LOGIN_FORM.SUCCESS",{project_name:$scope.invitation.project_name}),$confirm.notify("success",text)},onErrorSubmitLogin=function(response){var text;return text=$translate.instant("INVITATION_LOGIN_FORM.ERROR"),$confirm.notify("light-error",text)},submitLogin=debounce(2e3,function(_this){return function(event){return event.preventDefault(),loginForm.validate()?(promise=$auth.acceptInvitiationWithExistingUser($scope.dataLogin),promise.then(onSuccessSubmitLogin,onErrorSubmitLogin)):void 0}}(this)),$el.on("submit","form.login-form",submitLogin),$el.on("click",".button-login",submitLogin),$scope.dataRegister={token:token},registerForm=$el.find("form.register-form").checksley({onlyOneErrorElement:!0}),onSuccessSubmitRegister=function(response){return $analytics.trackEvent("auth","invitationAccept","invitation accept with new user",1),$location.path($navUrls.resolve("project",{project:$scope.invitation.project_slug})),$confirm.notify("success","You've successfully joined this project","Welcome to "+_.escape($scope.invitation.project_name))},onErrorSubmitRegister=function(response){var text;return response.data._error_message&&(text=$translate.instant("COMMON.GENERIC_ERROR",{error:response.data._error_message}),$confirm.notify("light-error",text)),registerForm.setErrors(response.data)},submitRegister=debounce(2e3,function(_this){return function(event){return event.preventDefault(),registerForm.validate()?(promise=$auth.acceptInvitiationWithNewUser($scope.dataRegister),promise.then(onSuccessSubmitRegister,onErrorSubmitRegister)):void 0}}(this)),$el.on("submit","form.register-form",submitRegister),$el.on("click",".button-register",submitRegister),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgInvitation",["$tgAuth","$tgConfirm","$tgLocation","$routeParams","$tgNavUrls","$tgAnalytics","$translate",InvitationDirective]),ChangeEmailDirective=function($repo,$model,$auth,$confirm,$location,$params,$navUrls,$translate){var link;return link=function($scope,$el,$attrs){var form,onErrorSubmit,onSuccessSubmit,submit;return $scope.data={},$scope.data.email_token=$params.email_token,form=$el.find("form").checksley(),onSuccessSubmit=function(response){var text;return $auth.isAuthenticated()?$repo.queryOne("users",$auth.getUser().id).then(function(_this){return function(data){return $auth.setUser(data),$location.path($navUrls.resolve("home"))}}(this)):$location.path($navUrls.resolve("login")),text=$translate.instant("CHANGE_EMAIL_FORM.SUCCESS"),$confirm.success(text)},onErrorSubmit=function(response){var text;return text=$translate.instant("COMMON.GENERIC_ERROR",{error:response.data._error_message}),$confirm.notify("light-error",text)},submit=function(){var promise;if(form.validate())return promise=$auth.changeEmail($scope.data),promise.then(onSuccessSubmit,onErrorSubmit)},$el.on("submit",function(event){return event.preventDefault(),submit()}),$el.on("click","a.button-change-email",function(event){return event.preventDefault(),submit()}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgChangeEmail",["$tgRepo","$tgModel","$tgAuth","$tgConfirm","$tgLocation","$routeParams","$tgNavUrls","$translate",ChangeEmailDirective]),CancelAccountDirective=function($repo,$model,$auth,$confirm,$location,$params,$navUrls){var link;return link=function($scope,$el,$attrs){var form,onErrorSubmit,onSuccessSubmit,submit;return $scope.data={},$scope.data.cancel_token=$params.cancel_token,form=$el.find("form").checksley(),onSuccessSubmit=function(response){var text;return $auth.logout(),$location.path($navUrls.resolve("home")),text=$translate.instant("CANCEL_ACCOUNT.SUCCESS"),$confirm.success(text)},onErrorSubmit=function(response){var text;return text=$translate.instant("COMMON.GENERIC_ERROR",{error:response.data._error_message}),$confirm.notify("error",text)},submit=debounce(2e3,function(_this){return function(event){var promise;return event.preventDefault(),form.validate()?(promise=$auth.cancelAccount($scope.data),promise.then(onSuccessSubmit,onErrorSubmit)):void 0}}(this)),$el.on("submit","form",submit),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgCancelAccount",["$tgRepo","$tgModel","$tgAuth","$tgConfirm","$tgLocation","$routeParams","$tgNavUrls",CancelAccountDirective])}.call(this),function(){var module;module=angular.module("taigaBacklog",[])}.call(this),function(){var TaigaMainDirective,bindOnce,groupBy,init,module,taiga,urls;taiga=this.taiga,groupBy=this.taiga.groupBy,bindOnce=this.taiga.bindOnce,module=angular.module("taigaBase",[]),TaigaMainDirective=function($rootscope,$window){var link;return link=function($scope,$el,$attrs){return $window.onresize=function(){return $rootscope.$broadcast("resize")}},{link:link}},module.directive("tgMain",["$rootScope","$window",TaigaMainDirective]),urls={home:"/",projects:"/projects",error:"/error","not-found":"/not-found","permission-denied":"/permission-denied",login:"/login","forgot-password":"/forgot-password","change-password":"/change-password/:token","change-email":"/change-email/:token","cancel-account":"/cancel-account/:token",register:"/register",invitation:"/invitation/:token","create-project":"/create-project",profile:"/profile","user-profile":"/profile/:username",project:"/project/:project","project-backlog":"/project/:project/backlog","project-taskboard":"/project/:project/taskboard/:sprint","project-kanban":"/project/:project/kanban","project-issues":"/project/:project/issues","project-search":"/project/:project/search","project-userstories-detail":"/project/:project/us/:ref","project-tasks-detail":"/project/:project/task/:ref","project-issues-detail":"/project/:project/issue/:ref","project-wiki":"/project/:project/wiki","project-wiki-page":"/project/:project/wiki/:slug","project-team":"/project/:project/team","project-admin-home":"/project/:project/admin/project-profile/details","project-admin-project-profile-details":"/project/:project/admin/project-profile/details","project-admin-project-profile-default-values":"/project/:project/admin/project-profile/default-values","project-admin-project-profile-modules":"/project/:project/admin/project-profile/modules","project-admin-project-profile-export":"/project/:project/admin/project-profile/export","project-admin-project-profile-reports":"/project/:project/admin/project-profile/reports","project-admin-project-values-status":"/project/:project/admin/project-values/status","project-admin-project-values-points":"/project/:project/admin/project-values/points","project-admin-project-values-priorities":"/project/:project/admin/project-values/priorities","project-admin-project-values-severities":"/project/:project/admin/project-values/severities","project-admin-project-values-types":"/project/:project/admin/project-values/types","project-admin-project-values-custom-fields":"/project/:project/admin/project-values/custom-fields","project-admin-memberships":"/project/:project/admin/memberships","project-admin-roles":"/project/:project/admin/roles","project-admin-third-parties-webhooks":"/project/:project/admin/third-parties/webhooks","project-admin-third-parties-github":"/project/:project/admin/third-parties/github","project-admin-third-parties-gitlab":"/project/:project/admin/third-parties/gitlab","project-admin-third-parties-bitbucket":"/project/:project/admin/third-parties/bitbucket","project-admin-contrib":"/project/:project/admin/contrib/:plugin","user-settings-user-profile":"/user-settings/user-profile","user-settings-user-change-password":"/user-settings/user-change-password","user-settings-user-avatar":"/user-settings/user-avatar","user-settings-mail-notifications":"/user-settings/mail-notifications"},init=function($log,$navurls){return $log.debug("Initialize navigation urls"),$navurls.update(urls)},module.run(["$log","$tgNavUrls",init])}.call(this),function(){var AnimationFrame,Capslock,CheckPermissionDirective,ClassPermissionDirective,DataPickerConfig,LimitLineLengthDirective,ProjectUrl,Qqueue,SelectedText,Template,ToggleCommentDirective,module,taiga,slice=[].slice;taiga=this.taiga,module=angular.module("taigaCommon",[]),DataPickerConfig=function($translate){return{get:function(){return{i18n:{previousMonth:$translate.instant("COMMON.PICKERDATE.PREV_MONTH"),nextMonth:$translate.instant("COMMON.PICKERDATE.NEXT_MONTH"),months:[$translate.instant("COMMON.PICKERDATE.MONTHS.JAN"),$translate.instant("COMMON.PICKERDATE.MONTHS.FEB"),$translate.instant("COMMON.PICKERDATE.MONTHS.MAR"),$translate.instant("COMMON.PICKERDATE.MONTHS.APR"),$translate.instant("COMMON.PICKERDATE.MONTHS.MAY"),$translate.instant("COMMON.PICKERDATE.MONTHS.JUN"),$translate.instant("COMMON.PICKERDATE.MONTHS.JUL"),$translate.instant("COMMON.PICKERDATE.MONTHS.AUG"),$translate.instant("COMMON.PICKERDATE.MONTHS.SEP"),$translate.instant("COMMON.PICKERDATE.MONTHS.OCT"),$translate.instant("COMMON.PICKERDATE.MONTHS.NOV"),$translate.instant("COMMON.PICKERDATE.MONTHS.DEC")],weekdays:[$translate.instant("COMMON.PICKERDATE.WEEK_DAYS.SUN"),$translate.instant("COMMON.PICKERDATE.WEEK_DAYS.MON"),$translate.instant("COMMON.PICKERDATE.WEEK_DAYS.TUE"),$translate.instant("COMMON.PICKERDATE.WEEK_DAYS.WED"),$translate.instant("COMMON.PICKERDATE.WEEK_DAYS.THU"),$translate.instant("COMMON.PICKERDATE.WEEK_DAYS.FRI"),$translate.instant("COMMON.PICKERDATE.WEEK_DAYS.SAT")],weekdaysShort:[$translate.instant("COMMON.PICKERDATE.WEEK_DAYS_SHORT.SUN"),$translate.instant("COMMON.PICKERDATE.WEEK_DAYS_SHORT.MON"),$translate.instant("COMMON.PICKERDATE.WEEK_DAYS_SHORT.TUE"),$translate.instant("COMMON.PICKERDATE.WEEK_DAYS_SHORT.WED"),$translate.instant("COMMON.PICKERDATE.WEEK_DAYS_SHORT.THU"),$translate.instant("COMMON.PICKERDATE.WEEK_DAYS_SHORT.FRI"),$translate.instant("COMMON.PICKERDATE.WEEK_DAYS_SHORT.SAT")]},isRTL:"true"===$translate.instant("COMMON.PICKERDATE.IS_RTL"),firstDay:parseInt($translate.instant("COMMON.PICKERDATE.FIRST_DAY_OF_WEEK"),10),format:$translate.instant("COMMON.PICKERDATE.FORMAT")}}}},module.factory("tgDatePickerConfigService",["$translate",DataPickerConfig]),SelectedText=function($window,$document){var get;return get=function(){return $window.getSelection?$window.getSelection().toString():$document.selection?$document.selection.createRange().text:""},{get:get}},module.factory("$selectedText",["$window","$document",SelectedText]),CheckPermissionDirective=function(){var link,render;return render=function($el,project,permission){return project.my_permissions.indexOf(permission)>-1?$el.removeClass("hidden"):void 0},link=function($scope,$el,$attrs){var permission;return $el.addClass("hidden"),permission=$attrs.tgCheckPermission,$scope.$watch("project",function(project){return null!=project?render($el,project,permission):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgCheckPermission",CheckPermissionDirective),ClassPermissionDirective=function(){var link,name;return name="tgClassPermission",link=function($scope,$el,$attrs){var checkPermissions,tgClassPermissionWatchAction,unbindWatcher;return checkPermissions=function(project,className,permission){var negation;return negation="!"===permission[0],negation&&(permission=permission.slice(1)),negation&&-1===project.my_permissions.indexOf(permission)?$el.addClass(className):negation||-1===project.my_permissions.indexOf(permission)?$el.removeClass(className):$el.addClass(className)},tgClassPermissionWatchAction=function(project){var className,classes,permission,results;if(project){unbindWatcher(),classes=$scope.$eval($attrs[name]),results=[];for(className in classes)permission=classes[className],results.push(checkPermissions(project,className,permission));return results}},unbindWatcher=$scope.$watch("project",tgClassPermissionWatchAction)},{link:link}},module.directive("tgClassPermission",ClassPermissionDirective),AnimationFrame=function(){var add,animationFrame,performAnimation,tail;return animationFrame=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame,performAnimation=function(_this){return function(time){var fn;return fn=tail.shift(),fn(),tail.length?animationFrame(performAnimation):void 0}}(this),tail=[],add=function(){var fn,i,len,results;for(results=[],i=0,len=arguments.length;len>i;i++)fn=arguments[i],tail.push(fn),1===tail.length?results.push(animationFrame(performAnimation)):results.push(void 0);return results},{add:add}},module.factory("animationFrame",AnimationFrame),ToggleCommentDirective=function(){var link;return link=function($scope,$el,$attrs){return $el.find("textarea").on("focus",function(){return $el.addClass("active")})},{link:link}},module.directive("tgToggleComment",ToggleCommentDirective),ProjectUrl=function($navurls){var get;return get=function(project){var ctx;return ctx={project:project.slug},project.is_backlog_activated&&project.my_permissions.indexOf("view_us")>-1?$navurls.resolve("project-backlog",ctx):project.is_kanban_activated&&project.my_permissions.indexOf("view_us")>-1?$navurls.resolve("project-kanban",ctx):project.is_wiki_activated&&project.my_permissions.indexOf("view_wiki_pages")>-1?$navurls.resolve("project-wiki",ctx):project.is_issues_activated&&project.my_permissions.indexOf("view_issues")>-1?$navurls.resolve("project-issues",ctx):$navurls.resolve("project",ctx)},{get:get}},module.factory("$projectUrl",["$tgNavUrls",ProjectUrl]),LimitLineLengthDirective=function(){var link;return link=function($scope,$el,$attrs){var maxColsPerLine;return maxColsPerLine=parseInt($el.attr("cols")),$el.on("keyup",function(event){var code,lines;return code=event.keyCode,lines=$el.val().split("\n"),_.each(lines,function(line,index){return lines[index]=line.substring(0,maxColsPerLine-2)}),$el.val(lines.join("\n"))})},{link:link}},module.directive("tgLimitLineLength",LimitLineLengthDirective),Qqueue=function($q){var deferred,lastPromise,qqueue;return deferred=$q.defer(),deferred.resolve(),lastPromise=deferred.promise,qqueue={bindAdd:function(_this){return function(fn){return function(){var args;return args=1<=arguments.length?slice.call(arguments,0):[],lastPromise=lastPromise.then(function(){return fn.apply(_this,args)})}}}(this),add:function(_this){return function(fn){return lastPromise=lastPromise?lastPromise.then(fn):fn(),qqueue}}(this)}},module.factory("$tgQqueue",["$q",Qqueue]),Template=function($templateCache){return{get:function(_this){return function(name,lodash){var tmp;return null==lodash&&(lodash=!1),tmp=$templateCache.get(name),lodash&&(tmp=_.template(tmp)),tmp}}(this)}},module.factory("$tgTemplate",["$templateCache",Template]),Capslock=function($translate){var link;return link=function($scope,$el,$attrs){var hideIcon,open,showIcon,warningIcon;return open=!1,warningIcon=$("
").addClass("icon").addClass("icon-capslock").attr("title",$translate.instant("COMMON.CAPSLOCK_WARNING")),hideIcon=function(){return warningIcon.fadeOut(function(){return open=!1,$(this).remove()})},showIcon=function(e){var element;if(!open)return element=e.currentTarget,$(element).parent().append(warningIcon),$(".icon-capslock").fadeIn(),open=!0},$el.on("blur",function(e){return hideIcon()}),$el.on("keyup.capslock, focus",function(e){return $el.val()===$el.val().toLowerCase()?hideIcon(e):showIcon(e)}),$scope.$on("$destroy",function(){return $el.off(".capslock")})},{link:link}},module.directive("tgCapslock",["$translate",Capslock])}.call(this),function(){var EventsProvider,EventsService,bindMethods,module,startswith,taiga,bind=function(fn,me){return function(){return fn.apply(me,arguments)}};taiga=this.taiga,startswith=this.taiga.startswith,bindMethods=this.taiga.bindMethods,module=angular.module("taigaEvents",[]),EventsService=function(){function EventsService(win,log,config,auth,liveAnnouncementService1,rootScope){this.win=win,this.log=log,this.config=config,this.auth=auth,this.liveAnnouncementService=liveAnnouncementService1,this.rootScope=rootScope,this.processMessage=bind(this.processMessage,this),bindMethods(this)}return EventsService.prototype.initialize=function(sessionId){return this.sessionId=sessionId,this.subscriptions={},this.connected=!1,this.error=!1,this.pendingMessages=[],this.missedHeartbeats=0,this.heartbeatInterval=null,void 0===this.win.WebSocket?this.log.info("WebSockets not supported on your browser"):void 0},EventsService.prototype.setupConnection=function(){var loc,path,scheme,url;return this.stopExistingConnection(),(url=this.config.get("eventsUrl"))?(startswith(url,"ws:")||startswith(url,"wss:")||(loc=this.win.location,scheme="https:"===loc.protocol?"wss:":"ws:",path=_.str.ltrim(url,"/"),url=scheme+"//"+loc.host+"/"+path),this.ws=new this.win.WebSocket(url),this.ws.addEventListener("open",this.onOpen),this.ws.addEventListener("message",this.onMessage),this.ws.addEventListener("error",this.onError),this.ws.addEventListener("close",this.onClose)):void 0},EventsService.prototype.stopExistingConnection=function(){return void 0!==this.ws?(this.ws.removeEventListener("open",this.onOpen),this.ws.removeEventListener("close",this.onClose),this.ws.removeEventListener("error",this.onError),this.ws.removeEventListener("message",this.onMessage),this.stopHeartBeatMessages(),this.ws.close(),delete this.ws):void 0},EventsService.prototype.notifications=function(){return this.subscribe(null,"notifications",function(_this){return function(data){return _this.liveAnnouncementService.show(data.title,data.desc),_this.rootScope.$digest()}}(this))},EventsService.prototype.startHeartBeatMessages=function(){var heartbeatIntervalTime,maxMissedHeartbeats;if(!this.heartbeatInterval)return maxMissedHeartbeats=this.config.get("eventsMaxMissedHeartbeats",5),heartbeatIntervalTime=this.config.get("eventsHeartbeatIntervalTime",6e4),this.missedHeartbeats=0,this.heartbeatInterval=setInterval(function(_this){return function(){var e,error1;try{if(_this.missedHeartbeats>=maxMissedHeartbeats)throw new Error("Too many missed heartbeats PINGs.");return _this.missedHeartbeats++,_this.sendMessage({cmd:"ping"}),_this.log.debug("HeartBeat send PING")}catch(error1){return e=error1,_this.log.error("HeartBeat error: "+e.message),_this.stopHeartBeatMessages()}}}(this),heartbeatIntervalTime),this.log.debug("HeartBeat enabled")},EventsService.prototype.stopHeartBeatMessages=function(){return this.heartbeatInterval?(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null,this.log.debug("HeartBeat disabled")):void 0},EventsService.prototype.processHeartBeatPongMessage=function(data){return this.missedHeartbeats=0,this.log.debug("HeartBeat recived PONG")},EventsService.prototype.serialize=function(message){return _.isObject(message)?JSON.stringify(message):message},EventsService.prototype.sendMessage=function(message){var i,len,messages,msg,results;if(this.pendingMessages.push(message),this.connected){for(messages=_.map(this.pendingMessages,this.serialize),this.pendingMessages=[],results=[],i=0,len=messages.length;len>i;i++)msg=messages[i],results.push(this.ws.send(msg));return results}},EventsService.prototype.processMessage=function(data){var routingKey,subscription;return routingKey=data.routing_key,null!=this.subscriptions[routingKey]?(subscription=this.subscriptions[routingKey],subscription.scope?subscription.scope.$apply(function(){return subscription.callback(data.data)}):subscription.callback(data.data)):void 0},EventsService.prototype.subscribe=function(scope,routingKey,callback){var message,subscription;if(!this.error)return this.log.debug("Subscribe to: "+routingKey),subscription={scope:scope,routingKey:routingKey,callback:_.debounce(callback,500,{leading:!0,trailing:!1})},message={cmd:"subscribe",routing_key:routingKey},this.subscriptions[routingKey]=subscription,this.sendMessage(message),scope?scope.$on("$destroy",function(_this){return function(){return _this.unsubscribe(routingKey)}}(this)):void 0},EventsService.prototype.unsubscribe=function(routingKey){var message;if(!this.error)return this.log.debug("Unsubscribe from: "+routingKey),message={cmd:"unsubscribe",routing_key:routingKey},this.sendMessage(message)},EventsService.prototype.onOpen=function(){var message,token;return this.connected=!0,this.startHeartBeatMessages(),this.notifications(),this.log.debug("WebSocket connection opened"),token=this.auth.getToken(),message={cmd:"auth",data:{token:token,sessionId:this.sessionId}},this.sendMessage(message)},EventsService.prototype.onMessage=function(event){var data;return this.log.debug("WebSocket message received: "+event.data),data=JSON.parse(event.data),"pong"===data.cmd?this.processHeartBeatPongMessage(data):this.processMessage(data)},EventsService.prototype.onError=function(error){return this.log.error("WebSocket error: "+error),this.error=!0},EventsService.prototype.onClose=function(){return this.log.debug("WebSocket closed."),this.connected=!1,this.stopHeartBeatMessages()},EventsService}(),EventsProvider=function(){function EventsProvider(){}return EventsProvider.prototype.setSessionId=function(sessionId){return this.sessionId=sessionId},EventsProvider.prototype.$get=function($win,$log,$conf,$auth,liveAnnouncementService,$rootScope){var service;return service=new EventsService($win,$log,$conf,$auth,liveAnnouncementService,$rootScope),service.initialize(this.sessionId),service},EventsProvider.prototype.$get.$inject=["$window","$log","$tgConfig","$tgAuth","tgLiveAnnouncementService","$rootScope"],EventsProvider}(),module.provider("$tgEvents",EventsProvider)}.call(this),function(){var FeedbackDirective,bindOnce,debounce,groupBy,mixOf,module,taiga,trim;taiga=this.taiga,groupBy=this.taiga.groupBy,bindOnce=this.taiga.bindOnce,mixOf=this.taiga.mixOf,debounce=this.taiga.debounce,trim=this.taiga.trim,module=angular.module("taigaFeedback",[]),FeedbackDirective=function($lightboxService,$repo,$confirm,$loading,feedbackService){var directive,link;return link=function($scope,$el,$attrs){var form,openLightbox,submit,submitButton;return form=$el.find("form").checksley(),submit=debounce(2e3,function(_this){return function(event){var currentLoading,promise;return event.preventDefault(),form.validate()?(currentLoading=$loading().target(submitButton).start(),promise=$repo.create("feedback",$scope.feedback),promise.then(function(data){return currentLoading.finish(),$lightboxService.close($el),$confirm.notify("success","\\o/ we'll be happy to read your")}),promise.then(null,function(){return currentLoading.finish(),$confirm.notify("error")})):void 0}}(this)),submitButton=$el.find(".submit-button"),$el.on("submit","form",submit),openLightbox=function(){return $scope.feedback={},$lightboxService.open($el),$el.find("textarea").focus()},$scope.$on("$destroy",function(){return $el.off()}),openLightbox()},directive={link:link,templateUrl:"common/lightbox-feedback.html",scope:{}}},module.directive("tgLbFeedback",["lightboxService","$tgRepo","$tgConfirm","$tgLoading","tgFeedbackService",FeedbackDirective])}.call(this),function(){var module;module=angular.module("taigaIntegrations",[])}.call(this),function(){var module;module=angular.module("taigaIssues",[])}.call(this),function(){var module;module=angular.module("taigaKanban",[])}.call(this),function(){var module;module=angular.module("taigaPlugins",["ngRoute"])}.call(this),function(){var module;module=angular.module("taigaProject",[])}.call(this),function(){var RelatedTaskAssignedToInlineEditionDirective,RelatedTaskCreateButtonDirective,RelatedTaskCreateFormDirective,RelatedTaskRowDirective,RelatedTasksDirective,debounce,module,taiga,trim;taiga=this.taiga,trim=this.taiga.trim,debounce=this.taiga.debounce,module=angular.module("taigaRelatedTasks",[]),RelatedTaskRowDirective=function($repo,$compile,$confirm,$rootscope,$loading,$template,$translate){var link,templateEdit,templateView;return templateView=$template.get("task/related-task-row.html",!0),templateEdit=$template.get("task/related-task-row-edit.html",!0),link=function($scope,$el,$attrs,$model){var renderEdit,renderView,saveTask;return saveTask=debounce(2e3,function(task){var currentLoading,promise;return task.subject=$el.find("input").val(),currentLoading=$loading().target($el.find(".task-name")).start(),promise=$repo.save(task),promise.then(function(_this){return function(){return currentLoading.finish(),$confirm.notify("success"),$rootscope.$broadcast("related-tasks:update")}}(this)),promise.then(null,function(_this){return function(){return currentLoading.finish(),$el.find("input").val(task.subject),$confirm.notify("error")}}(this)),promise}),renderEdit=function(task){return $el.html($compile(templateEdit({task:task}))($scope)),$el.on("keyup","input",function(event){return 13===event.keyCode?saveTask($model.$modelValue).then(function(){return renderView($model.$modelValue)}):27===event.keyCode?renderView($model.$modelValue):void 0}),$el.on("click",".icon-floppy",function(event){return saveTask($model.$modelValue).then(function(){return renderView($model.$modelValue)})}),$el.on("click",".cancel-edit",function(event){return renderView($model.$modelValue)})},renderView=function(task){var perms;return $el.off(),perms={modify_task:-1!==$scope.project.my_permissions.indexOf("modify_task"),delete_task:-1!==$scope.project.my_permissions.indexOf("delete_task")},$el.html($compile(templateView({task:task,perms:perms}))($scope)),$el.on("click",".icon-edit",function(){return renderEdit($model.$modelValue),$el.find("input").focus().select()}),$el.on("click",".delete-task",function(event){var message,title;return title=$translate.instant("TASK.TITLE_DELETE_ACTION"),task=$model.$modelValue,message=task.subject,$confirm.askOnDelete(title,message).then(function(askResponse){var promise;return promise=$repo.remove(task),promise.then(function(){return askResponse.finish(),$confirm.notify("success"),$scope.$emit("related-tasks:delete")}),promise.then(null,function(){return askResponse.finish(!1),$confirm.notify("error")})})})},$scope.$watch($attrs.ngModel,function(val){return val?renderView(val):void 0}),$scope.$on("related-tasks:assigned-to-changed",function(){return $rootscope.$broadcast("related-tasks:update")}),$scope.$on("related-tasks:status-changed",function(){return $rootscope.$broadcast("related-tasks:update")}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,require:"ngModel"}},module.directive("tgRelatedTaskRow",["$tgRepo","$compile","$tgConfirm","$rootScope","$tgLoading","$tgTemplate","$translate",RelatedTaskRowDirective]),RelatedTaskCreateFormDirective=function($repo,$compile,$confirm,$tgmodel,$loading,$analytics,$template){var link,newTask,template;return template=$template.get("task/related-task-create-form.html",!0),newTask={subject:"",assigned_to:null},link=function($scope,$el,$attrs){var close,createTask,render;return createTask=debounce(2e3,function(task){var currentLoading,promise;return task.subject=$el.find("input").val(),task.assigned_to=$scope.newTask.assigned_to,task.status=$scope.newTask.status,$scope.newTask.status=$scope.project.default_task_status,$scope.newTask.assigned_to=null,currentLoading=$loading().target($el.find(".task-name")).start(),promise=$repo.create("tasks",task),promise.then(function(){return $analytics.trackEvent("task","create","create task on userstory",1),currentLoading.finish(),$scope.$emit("related-tasks:add"),$confirm.notify("success")}),promise.then(null,function(){return $el.find("input").val(task.subject),currentLoading.finish(),$confirm.notify("error")}),promise}),close=function(){return $el.off(),$el.html(""),$scope.newRelatedTaskFormOpen=!1},render=function(){return $scope.newRelatedTaskFormOpen=!0, -$el.html($compile(template())($scope)),$el.find("input").focus().select(),$el.addClass("active"),$el.on("keyup","input",function(event){return 13===event.keyCode?createTask(newTask).then(function(){return render()}):27===event.keyCode?$scope.$apply(function(){return close()}):void 0}),$el.on("click",".icon-delete",function(event){return $scope.$apply(function(){return close()})}),$el.on("click",".icon-floppy",function(event){return createTask(newTask).then(function(){return close()})})},taiga.bindOnce($scope,"us",function(val){return newTask.status=$scope.project.default_task_status,newTask.project=$scope.project.id,newTask.user_story=$scope.us.id,$scope.newTask=$tgmodel.make_model("tasks",newTask),$el.html("")}),$scope.$on("related-tasks:show-form",function(){return render()}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgRelatedTaskCreateForm",["$tgRepo","$compile","$tgConfirm","$tgModel","$tgLoading","$tgAnalytics","$tgTemplate",RelatedTaskCreateFormDirective]),RelatedTaskCreateButtonDirective=function($repo,$compile,$confirm,$tgmodel){var link,template;return template=_.template(''),link=function($scope,$el,$attrs){return $scope.$watch("project",function(val){return val?($el.off(),-1!==$scope.project.my_permissions.indexOf("add_task")?$el.html($compile(template())($scope)):$el.html(""),$el.on("click",".icon",function(event){return $scope.$emit("related-tasks:add-new-clicked")})):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgRelatedTaskCreateButton",["$tgRepo","$compile","$tgConfirm","$tgModel",RelatedTaskCreateButtonDirective]),RelatedTasksDirective=function($repo,$rs,$rootscope){var link;return link=function($scope,$el,$attrs){var loadTasks;return loadTasks=function(){return $rs.tasks.list($scope.projectId,null,$scope.usId).then(function(_this){return function(tasks){return $scope.tasks=_.sortBy(tasks,"ref"),tasks}}(this))},$scope.$on("related-tasks:add",function(){return loadTasks().then(function(){return $rootscope.$broadcast("related-tasks:update")})}),$scope.$on("related-tasks:delete",function(){return loadTasks().then(function(){return $rootscope.$broadcast("related-tasks:update")})}),$scope.$on("related-tasks:add-new-clicked",function(){return $scope.$broadcast("related-tasks:show-form")}),taiga.bindOnce($scope,"us",function(val){return loadTasks()}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgRelatedTasks",["$tgRepo","$tgResources","$rootScope",RelatedTasksDirective]),RelatedTaskAssignedToInlineEditionDirective=function($repo,$rootscope,popoverService){var link,template;return template=_.template('<%- name %>\n
<%- name %>
'),link=function($scope,$el,$attrs){var $ctrl,autoSave,notAutoSave,task,updateRelatedTask;return updateRelatedTask=function(task){var ctx,member;return ctx={name:"Unassigned",imgurl:"/"+window._version+"/images/unnamed.png"},member=$scope.usersById[task.assigned_to],member&&(ctx.imgurl=member.photo,ctx.name=member.full_name_display),$el.find(".avatar").html(template(ctx)),$el.find(".task-assignedto").attr("title",ctx.name)},$ctrl=$el.controller(),task=$scope.$eval($attrs.tgRelatedTaskAssignedToInlineEdition),notAutoSave=$scope.$eval($attrs.notAutoSave),autoSave=!notAutoSave,updateRelatedTask(task),$el.on("click",".task-assignedto",function(event){return $rootscope.$broadcast("assigned-to:add",task)}),taiga.bindOnce($scope,"project",function(project){return-1===project.my_permissions.indexOf("modify_task")?($el.unbind("click"),$el.find("a").addClass("not-clickable")):void 0}),$scope.$on("assigned-to:added",debounce(2e3,function(_this){return function(ctx,userId,updatedRelatedTask){return updatedRelatedTask.id===task.id?(updatedRelatedTask.assigned_to=userId,autoSave&&$repo.save(updatedRelatedTask).then(function(){return $scope.$emit("related-tasks:assigned-to-changed")}),updateRelatedTask(updatedRelatedTask)):void 0}}(this))),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgRelatedTaskAssignedToInlineEdition",["$tgRepo","$rootScope",RelatedTaskAssignedToInlineEditionDirective])}.call(this),function(){var ResourcesService,initResources,initUrls,module,taiga,urls,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,ResourcesService=function(superClass){function ResourcesService(){return ResourcesService.__super__.constructor.apply(this,arguments)}return extend(ResourcesService,superClass),ResourcesService}(taiga.Service),urls={auth:"/auth","auth-register":"/auth/register",invitations:"/invitations",users:"/users",by_username:"/users/by_username","users-password-recovery":"/users/password_recovery","users-change-password-from-recovery":"/users/change_password_from_recovery","users-change-password":"/users/change_password","users-change-email":"/users/change_email","users-cancel-account":"/users/cancel","user-stats":"/users/%s/stats","user-liked":"/users/%s/liked","user-voted":"/users/%s/voted","user-watched":"/users/%s/watched","user-contacts":"/users/%s/contacts",permissions:"/permissions","notify-policies":"/notify-policies","user-storage":"/user-storage",memberships:"/memberships","bulk-create-memberships":"/memberships/bulk_create",roles:"/roles",permissions:"/permissions",resolver:"/resolver",projects:"/projects","project-templates":"/project-templates","project-modules":"/projects/%s/modules","bulk-update-projects-order":"/projects/bulk_update_order","project-like":"/projects/%s/like","project-unlike":"/projects/%s/unlike","project-watch":"/projects/%s/watch","project-unwatch":"/projects/%s/unwatch","userstory-statuses":"/userstory-statuses",points:"/points","task-statuses":"/task-statuses","issue-statuses":"/issue-statuses","issue-types":"/issue-types",priorities:"/priorities",severities:"/severities",milestones:"/milestones",userstories:"/userstories","bulk-create-us":"/userstories/bulk_create","bulk-update-us-backlog-order":"/userstories/bulk_update_backlog_order","bulk-update-us-sprint-order":"/userstories/bulk_update_sprint_order","bulk-update-us-kanban-order":"/userstories/bulk_update_kanban_order","userstories-filters":"/userstories/filters_data","userstory-upvote":"/userstories/%s/upvote","userstory-downvote":"/userstories/%s/downvote","userstory-watch":"/userstories/%s/watch","userstory-unwatch":"/userstories/%s/unwatch",tasks:"/tasks","bulk-create-tasks":"/tasks/bulk_create","bulk-update-task-taskboard-order":"/tasks/bulk_update_taskboard_order","task-upvote":"/tasks/%s/upvote","task-downvote":"/tasks/%s/downvote","task-watch":"/tasks/%s/watch","task-unwatch":"/tasks/%s/unwatch",issues:"/issues","bulk-create-issues":"/issues/bulk_create","issues-filters":"/issues/filters_data","issue-upvote":"/issues/%s/upvote","issue-downvote":"/issues/%s/downvote","issue-watch":"/issues/%s/watch","issue-unwatch":"/issues/%s/unwatch",wiki:"/wiki","wiki-restore":"/wiki/%s/restore","wiki-links":"/wiki-links","history/us":"/history/userstory","history/issue":"/history/issue","history/task":"/history/task","history/wiki":"/history/wiki","attachments/us":"/userstories/attachments","attachments/issue":"/issues/attachments","attachments/task":"/tasks/attachments","attachments/wiki_page":"/wiki/attachments","custom-attributes/userstory":"/userstory-custom-attributes","custom-attributes/issue":"/issue-custom-attributes","custom-attributes/task":"/task-custom-attributes","custom-attributes-values/userstory":"/userstories/custom-attributes-values","custom-attributes-values/issue":"/issues/custom-attributes-values","custom-attributes-values/task":"/tasks/custom-attributes-values",webhooks:"/webhooks","webhooks-test":"/webhooks/%s/test",webhooklogs:"/webhooklogs","webhooklogs-resend":"/webhooklogs/%s/resend","userstories-csv":"/userstories/csv?uuid=%s","tasks-csv":"/tasks/csv?uuid=%s","issues-csv":"/issues/csv?uuid=%s","timeline-profile":"/timeline/profile","timeline-user":"/timeline/user","timeline-project":"/timeline/project",search:"/search",exporter:"/exporter",importer:"/importer/load_dump",feedback:"/feedback",locales:"/locales",applications:"/applications","application-tokens":"/application-tokens"},initUrls=function($log,$urls){return $log.debug("Initialize api urls"),$urls.update(urls)},initResources=function($log,$rs){var i,len,provider,providers,results;for($log.debug("Initialize resources"),providers=_.toArray(arguments).slice(2),results=[],i=0,len=providers.length;len>i;i++)provider=providers[i],results.push(provider($rs));return results},module=angular.module("taigaResources",["taigaBase"]),module.service("$tgResources",ResourcesService),module.run(["$log","$tgUrls",initUrls]),module.run(["$log","$tgResources","$tgProjectsResourcesProvider","$tgCustomAttributesResourcesProvider","$tgCustomAttributesValuesResourcesProvider","$tgMembershipsResourcesProvider","$tgNotifyPoliciesResourcesProvider","$tgInvitationsResourcesProvider","$tgRolesResourcesProvider","$tgUserSettingsResourcesProvider","$tgSprintsResourcesProvider","$tgUserstoriesResourcesProvider","$tgTasksResourcesProvider","$tgIssuesResourcesProvider","$tgWikiResourcesProvider","$tgSearchResourcesProvider","$tgAttachmentsResourcesProvider","$tgMdRenderResourcesProvider","$tgHistoryResourcesProvider","$tgKanbanResourcesProvider","$tgModulesResourcesProvider","$tgWebhooksResourcesProvider","$tgWebhookLogsResourcesProvider","$tgLocalesResourcesProvider","$tgUsersResourcesProvider",initResources])}.call(this),function(){var SearchBoxDirective,SearchController,SearchDirective,bindOnce,debounce,debounceLeading,groupBy,mixOf,module,taiga,trim,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,groupBy=this.taiga.groupBy,bindOnce=this.taiga.bindOnce,mixOf=this.taiga.mixOf,debounceLeading=this.taiga.debounceLeading,trim=this.taiga.trim,debounce=this.taiga.debounce,module=angular.module("taigaSearch",[]),SearchController=function(superClass){function SearchController(scope1,repo,rs,params,q,location,appMetaService,navUrls,translate){var loadSearchData,promise;this.scope=scope1,this.repo=repo,this.rs=rs,this.params=params,this.q=q,this.location=location,this.appMetaService=appMetaService,this.navUrls=navUrls,this.translate=translate,this.scope.sectionName="Search",promise=this.loadInitialData(),promise.then(function(_this){return function(){var description,title;return title=_this.translate.instant("SEARCH.PAGE_TITLE",{projectName:_this.scope.project.name}),description=_this.translate.instant("SEARCH.PAGE_DESCRIPTION",{projectName:_this.scope.project.name,projectDescription:_this.scope.project.description}),_this.appMetaService.setAll(title,description)}}(this)),promise.then(null,this.onInitialDataError.bind(this)),this.scope.searchTerm=null,loadSearchData=debounceLeading(100,function(_this){return function(t){return _this.loadSearchData(t)}}(this)),bindOnce(this.scope,"projectId",function(_this){return function(projectId){return!_this.scope.searchResults&&_this.scope.searchTerm?_this.loadSearchData():void 0}}(this)),this.scope.$watch("searchTerm",function(_this){return function(term){return void 0!==term&&_this.scope.projectId?_this.loadSearchData(term):void 0}}(this))}return extend(SearchController,superClass),SearchController.$inject=["$scope","$tgRepo","$tgResources","$routeParams","$q","$tgLocation","tgAppMetaService","$tgNavUrls","$translate"],SearchController.prototype.loadFilters=function(){var defered;return defered=this.q.defer(),defered.resolve(),defered.promise},SearchController.prototype.loadProject=function(){return this.rs.projects.getBySlug(this.params.pslug).then(function(_this){return function(project){return _this.scope.project=project,_this.scope.$emit("project:loaded",project),_this.scope.issueStatusById=groupBy(project.issue_statuses,function(x){return x.id}),_this.scope.taskStatusById=groupBy(project.task_statuses,function(x){return x.id}),_this.scope.severityById=groupBy(project.severities,function(x){return x.id}),_this.scope.priorityById=groupBy(project.priorities,function(x){return x.id}),_this.scope.usStatusById=groupBy(project.us_statuses,function(x){return x.id}),project}}(this))},SearchController.prototype.loadSearchData=function(term){return null==term&&(term=""),this.scope.loading=!0,this._loadSearchData(term).then(function(_this){return function(data){return _this.scope.searchResults=data,_this.scope.loading=!1}}(this))},SearchController.prototype._loadSearchData=function(term){return null==term&&(term=""),this._promise&&this._promise.abort(),this._promise=this.rs.search["do"](this.scope.projectId,term),this._promise},SearchController.prototype.loadInitialData=function(){return this.loadProject().then(function(_this){return function(project){return _this.scope.projectId=project.id,_this.fillUsersAndRoles(project.members,project.roles)}}(this))},SearchController}(mixOf(taiga.Controller,taiga.PageMixin)),module.controller("SearchController",SearchController),SearchBoxDirective=function(projectService,$lightboxService,$navurls,$location,$route){var link;return link=function($scope,$el,$attrs){var openLightbox,project,submit;return project=null,submit=debounce(2e3,function(_this){return function(event){var form,text,url;return event.preventDefault(),form=$el.find("form").checksley(),form.validate()?(text=$el.find("#search-text").val(),url=$navurls.resolve("project-search",{project:project.get("slug")}),$scope.$apply(function(){return $lightboxService.close($el),$location.path(url),$location.search("text",text).path(url),$route.reload()})):void 0}}(this)),openLightbox=function(){return project=projectService.project,$lightboxService.open($el).then(function(){return $el.find("#search-text").focus()})},$el.on("submit","form",submit),openLightbox()},{templateUrl:"search/lightbox-search.html",link:link}},SearchBoxDirective.$inject=["tgProjectService","lightboxService","$tgNavUrls","$tgLocation","$route"],module.directive("tgSearchBox",SearchBoxDirective),SearchDirective=function($log,$compile,$templatecache,$routeparams,$location){var link,linkTable;return linkTable=function($scope,$el,$attrs,$ctrl){var activeSectionName,applyAutoTab,getActiveSection,lastSearchResults,markSectionTabActive,renderFilterTabs,renderTableContent,tabsDom,templates;return applyAutoTab=!0,activeSectionName="userstories",tabsDom=$el.find("section.search-filter"),lastSearchResults=null,getActiveSection=function(data){var i,len,maxVal,name,ref,selectedSection,value;if(maxVal=0,selectedSection={},selectedSection.name="userstories",selectedSection.value=[],!applyAutoTab)return selectedSection.name=activeSectionName,selectedSection.value=data[activeSectionName],selectedSection;if(data)for(ref=["userstories","issues","tasks","wikipages"],i=0,len=ref.length;len>i;i++)if(name=ref[i],value=data[name],value.length>maxVal){maxVal=value.length,selectedSection.name=name,selectedSection.value=value;break}return 0===maxVal?selectedSection:selectedSection},renderFilterTabs=function(data){var name,results,value;results=[];for(name in data)value=data[name],"count"!==name&&results.push(tabsDom.find("li."+name+" .num").html(value.length));return results},markSectionTabActive=function(section){return tabsDom.find("a.active").removeClass("active"),tabsDom.find("li."+section.name+" a").addClass("active"),applyAutoTab=!1,activeSectionName=section.name},templates={issues:$templatecache.get("search-issues"),tasks:$templatecache.get("search-tasks"),userstories:$templatecache.get("search-userstories"),wikipages:$templatecache.get("search-wikipages")},renderTableContent=function(section){var element,oldElements,oldScope,scope,template;return oldElements=$el.find(".search-result-table").children(),oldScope=oldElements.scope(),oldScope&&(oldScope.$destroy(),oldElements.remove()),scope=$scope.$new(),scope[section.name]=section.value,template=angular.element.parseHTML(trim(templates[section.name])),element=$compile(template)(scope),$el.find(".search-result-table").html(element)},$scope.$watch("searchResults",function(data){var activeSection;return(lastSearchResults=data)?(activeSection=getActiveSection(data),renderFilterTabs(data),renderTableContent(activeSection),markSectionTabActive(activeSection)):void 0}),$scope.$watch("searchTerm",function(searchTerm){return void 0!==searchTerm?$location.search("text",searchTerm):void 0}),$el.on("click",".search-filter li > a",function(event){var section,sectionData,sectionName,target;return event.preventDefault(),target=angular.element(event.currentTarget),sectionName=target.parent().data("name"),sectionData=lastSearchResults?lastSearchResults[sectionName]:[],section={name:sectionName,value:sectionData},$scope.$apply(function(){return renderTableContent(section),markSectionTabActive(section)})})},link=function($scope,$el,$attrs){var $ctrl,searchText;return $ctrl=$el.controller(),linkTable($scope,$el,$attrs,$ctrl),searchText=$routeparams.text,$scope.$watch("projectId",function(projectId){return null!=projectId?$scope.searchTerm=searchText:void 0})},{link:link}},module.directive("tgSearch",["$log","$compile","$templateCache","$routeParams","$tgLocation",SearchDirective])}.call(this),function(){var module;module=angular.module("taigaTaskboard",[])}.call(this),function(){var module;module=angular.module("taigaTasks",[])}.call(this),function(){var module;module=angular.module("taigaTeam",[])}.call(this),function(){var module;module=angular.module("taigaUserSettings",[])}.call(this),function(){var module;module=angular.module("taigaUserStories",[])}.call(this),function(){var module;module=angular.module("taigaWiki",[])}.call(this),function(){var AnalyticsService,module,taiga,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,module=angular.module("taigaCommon"),AnalyticsService=function(superClass){function AnalyticsService(rootscope,log,config,win,doc,location){var conf;this.rootscope=rootscope,this.log=log,this.config=config,this.win=win,this.doc=doc,this.location=location,this.initialized=!1,conf=this.config.get("analytics",{}),this.accountId=conf.accountId,this.pageEvent=conf.pageEvent||"$routeChangeSuccess",this.trackRoutes=conf.trackRoutes||!0,this.ignoreFirstPageLoad=conf.ignoreFirstPageLoad||!1}return extend(AnalyticsService,superClass),AnalyticsService.$inject=["$rootScope","$log","$tgConfig","$window","$document","$location"],AnalyticsService.prototype.initialize=function(){return this.accountId?(this.injectAnalytics(),this.win.ga("create",this.accountId,"auto"),this.win.ga("require","displayfeatures"),this.trackRoutes&&!this.ignoreFirstPageLoad&&this.win.ga("send","pageview",this.getUrl()),this.trackRoutes&&this.rootscope.$on(this.pageEvent,function(_this){return function(){return _this.trackPage(_this.getUrl(),"Taiga")}}(this)),this.initialized=!0):void this.log.debug("Analytics: no acount id provided. Disabling.")},AnalyticsService.prototype.getUrl=function(){return this.location.path()},AnalyticsService.prototype.injectAnalytics=function(){var fn;return(fn=function(i,s,o,g,r,a,m){i.GoogleAnalyticsObject=r,i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date,a=s.createElement(o),m=s.getElementsByTagName(o)[0],a.async=1,a.src=g,m.parentNode.insertBefore(a,m)})(window,document,"script","//www.google-analytics.com/analytics.js","ga")},AnalyticsService.prototype.trackPage=function(url,title){return this.initialized&&this.win.ga?(title=title||this.doc[0].title,this.win.ga("send","pageview",{page:url,title:title})):void 0},AnalyticsService.prototype.trackEvent=function(category,action,label,value){return this.initialized&&this.win.ga?this.win.ga("send","event",category,action,label,value):void 0},AnalyticsService}(taiga.Service),module.service("$tgAnalytics",AnalyticsService)}.call(this),function(){var AttachmentDirective,AttachmentsController,AttachmentsDirective,bindMethods,bindOnce,module,sizeFormat,taiga,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,sizeFormat=this.taiga.sizeFormat,bindOnce=this.taiga.bindOnce,bindMethods=this.taiga.bindMethods,module=angular.module("taigaCommon"),AttachmentsController=function(superClass){function AttachmentsController(scope,rootscope,repo,rs,confirm,q,translate){this.scope=scope,this.rootscope=rootscope,this.repo=repo,this.rs=rs,this.confirm=confirm,this.q=q,this.translate=translate,bindMethods(this),this.type=null,this.objectId=null,this.projectId=null,this.uploadingAttachments=[],this.attachments=[],this.attachmentsCount=0,this.deprecatedAttachmentsCount=0,this.showDeprecated=!1}return extend(AttachmentsController,superClass),AttachmentsController.$inject=["$scope","$rootScope","$tgRepo","$tgResources","$tgConfirm","$q","$translate"],AttachmentsController.prototype.initialize=function(type,objectId){return this.type=type,this.objectId=objectId,this.projectId=this.scope.projectId},AttachmentsController.prototype.loadAttachments=function(){var urlname;return this.objectId?(urlname="attachments/"+this.type,this.rs.attachments.list(urlname,this.objectId,this.projectId).then(function(_this){return function(attachments){return _this.attachments=_.sortBy(attachments,"order"),_this.updateCounters(),attachments}}(this))):this.attachments},AttachmentsController.prototype.updateCounters=function(){return this.attachmentsCount=this.attachments.length,this.deprecatedAttachmentsCount=_.filter(this.attachments,{is_deprecated:!0}).length},AttachmentsController.prototype._createAttachment=function(attachment){var promise,urlName;return urlName="attachments/"+this.type,promise=this.rs.attachments.create(urlName,this.projectId,this.objectId,attachment),promise=promise.then(function(_this){return function(data){var index;return data.isCreatedRightNow=!0,index=_this.uploadingAttachments.indexOf(attachment),_this.uploadingAttachments.splice(index,1),_this.attachments.push(data),_this.rootscope.$broadcast("attachment:create")}}(this)),promise=promise.then(null,function(_this){return function(data){var index,message;return 413===data.status&&_this.scope.$emit("attachments:size-error"),index=_this.uploadingAttachments.indexOf(attachment),_this.uploadingAttachments.splice(index,1),message=_this.translate.instant("ATTACHMENT.ERROR_UPLOAD_ATTACHMENT",{fileName:attachment.name,errorMessage:data.data._error_message}),_this.confirm.notify("error",message),_this.q.reject(data)}}(this))},AttachmentsController.prototype.createAttachments=function(attachments){var promises;return promises=_.map(attachments,function(_this){return function(x){return _this._createAttachment(x)}}(this)),this.q.all(promises).then(function(_this){return function(){return _this.updateCounters()}}(this))},AttachmentsController.prototype.addUploadingAttachments=function(attachments){return this.uploadingAttachments=_.union(this.uploadingAttachments,attachments)},AttachmentsController.prototype.reorderAttachment=function(attachment,newIndex){var oldIndex;return oldIndex=this.attachments.indexOf(attachment),oldIndex!==newIndex?(this.attachments.splice(oldIndex,1),this.attachments.splice(newIndex,0,attachment),_.each(this.attachments,function(x,i){return x.order=i+1})):void 0},AttachmentsController.prototype.updateAttachment=function(attachment){var onError,onSuccess;return onSuccess=function(_this){return function(){return _this.updateCounters(),_this.rootscope.$broadcast("attachment:edit")}}(this),onError=function(_this){return function(response){return 413===response.status&&$scope.$emit("attachments:size-error"),_this.confirm.notify("error"),_this.q.reject()}}(this),this.repo.save(attachment).then(onSuccess,onError)},AttachmentsController.prototype.saveAttachments=function(){return this.repo.saveAll(this.attachments).then(null,function(_this){return function(){var item,j,len,ref;for(ref=_this.attachments,j=0,len=ref.length;len>j;j++)item=ref[j],item.revert();return _this.attachments=_.sortBy(_this.attachments,"order")}}(this))},AttachmentsController.prototype.removeAttachment=function(attachment){var message,title;return title=this.translate.instant("ATTACHMENT.TITLE_LIGHTBOX_DELETE_ATTACHMENT"),message=this.translate.instant("ATTACHMENT.MSG_LIGHTBOX_DELETE_ATTACHMENT",{fileName:attachment.name}),this.confirm.askOnDelete(title,message).then(function(_this){return function(askResponse){var onError,onSuccess;return onSuccess=function(){var index;return askResponse.finish(),index=_this.attachments.indexOf(attachment),_this.attachments.splice(index,1),_this.updateCounters(),_this.rootscope.$broadcast("attachment:delete")},onError=function(){return askResponse.finish(!1),message=_this.translate.instant("ATTACHMENT.ERROR_DELETE_ATTACHMENT",{errorMessage:message}),_this.confirm.notify("error",null,message),_this.q.reject()},_this.repo.remove(attachment).then(onSuccess,onError)}}(this))},AttachmentsController.prototype.filterAttachments=function(item){return this.showDeprecated?!0:!item.is_deprecated},AttachmentsController}(taiga.Controller),AttachmentsDirective=function($config,$confirm,$templates,$translate){var link,template,templateFn;return template=$templates.get("attachment/attachments.html",!0),link=function($scope,$el,$attrs,$ctrls){var $ctrl,$model,showSizeInfo,tdom;return $ctrl=$ctrls[0],$model=$ctrls[1],bindOnce($scope,$attrs.ngModel,function(value){return $ctrl.initialize($attrs.type,value.id),$ctrl.loadAttachments()}),tdom=$el.find("div.attachment-body.sortable"),tdom.sortable({items:"div.single-attachment",handle:"a.settings.icon.icon-drag-v",containment:".attachments",dropOnEmpty:!0,scroll:!1,tolerance:"pointer",placeholder:"sortable-placeholder single-attachment"}),tdom.on("sortstop",function(event,ui){var attachment,newIndex;return attachment=ui.item.scope().attach,newIndex=ui.item.index(),$ctrl.reorderAttachment(attachment,newIndex),$ctrl.saveAttachments().then(function(){return $scope.$emit("attachment:edit")})}),showSizeInfo=function(){return $el.find(".size-info").removeClass("hidden")},$scope.$on("attachments:size-error",function(){return showSizeInfo()}),$el.on("change",".attachments-header input",function(event){var files;return files=_.toArray(event.target.files),files.length<1?void 0:$scope.$apply(function(){return $ctrl.addUploadingAttachments(files),$ctrl.createAttachments(files)})}),$el.on("click",".more-attachments",function(event){var target;return event.preventDefault(),target=angular.element(event.currentTarget),$scope.$apply(function(){return $ctrl.showDeprecated=!$ctrl.showDeprecated}),target.find("span.text").addClass("hidden"),$ctrl.showDeprecated?(target.find("span[data-type=hide]").removeClass("hidden"),target.find("more-attachments-num").addClass("hidden")):(target.find("span[data-type=show]").removeClass("hidden"),target.find("more-attachments-num").removeClass("hidden"))}),$scope.$on("$destroy",function(){return $el.off()})},templateFn=function($el,$attrs){var ctx,maxFileSize,maxFileSizeMsg;return maxFileSize=$config.get("maxUploadFileSize",null),maxFileSize&&(maxFileSize=sizeFormat(maxFileSize)),maxFileSizeMsg=maxFileSize?$translate.instant("ATTACHMENT.MAX_UPLOAD_SIZE",{maxFileSize:maxFileSize}):"",ctx={type:$attrs.type,maxFileSize:maxFileSize,maxFileSizeMsg:maxFileSizeMsg},template(ctx)},{require:["tgAttachments","ngModel"],controller:AttachmentsController,controllerAs:"ctrl",restrict:"AE",scope:!0,link:link,template:templateFn}},module.directive("tgAttachments",["$tgConfig","$tgConfirm","$tgTemplate","$translate",AttachmentsDirective]),AttachmentDirective=function($template,$compile,$translate,$rootScope){var link,template,templateEdit;return template=$template.get("attachment/attachment.html",!0),templateEdit=$template.get("attachment/attachment-edit.html",!0),link=function($scope,$el,$attrs,$ctrl){var attachment,render,saveAttachment;return render=function(attachment,edit){var ctx,html,modifyPermission,permissions;return null==edit&&(edit=!1),permissions=$scope.project.my_permissions,modifyPermission=permissions.indexOf("modify_"+$ctrl.type)>-1,ctx={id:attachment.id,name:attachment.name,title:$translate.instant("ATTACHMENT.TITLE",{fileName:attachment.name,date:moment(attachment.created_date).format($translate.instant("ATTACHMENT.DATE"))}),url:attachment.url,size:sizeFormat(attachment.size),description:attachment.description,isDeprecated:attachment.is_deprecated,modifyPermission:modifyPermission},html=edit?$compile(templateEdit(ctx))($scope):$compile(template(ctx))($scope),$el.html(html),attachment.is_deprecated?($el.addClass("deprecated"),$el.find("input:checkbox").prop("checked",!0)):$el.removeClass("deprecated")},saveAttachment=function(){return attachment.description=$el.find("input[name='description']").val(),attachment.is_deprecated=$el.find("input[name='is-deprecated']").prop("checked"),attachment.isCreatedRightNow=!1,$scope.$apply(function(){return $ctrl.updateAttachment(attachment).then(function(){return render(attachment,!1)})})},$el.on("click","a.editable-settings.icon-floppy",function(event){return event.preventDefault(),saveAttachment()}),$el.on("keyup","input[name=description]",function(event){return 13===event.keyCode?saveAttachment():27===event.keyCode?$scope.$apply(function(){return render(attachment,!1)}):void 0}),$el.on("click","a.editable-settings.icon-delete",function(event){return event.preventDefault(),render(attachment,!1)}),$el.on("click","a.settings.icon-edit",function(event){return event.preventDefault(),render(attachment,!0),$el.find("input[name='description']").focus().select()}),$el.on("click","a.settings.icon-delete",function(event){return event.preventDefault(),$scope.$apply(function(){return $ctrl.removeAttachment(attachment)})}),$el.on("click","div.attachment-name a",function(event){return null!==attachment.name.match(/\.(jpe?g|png|gif|gifv|webm)/i)?(event.preventDefault(),$scope.$apply(function(){return $rootScope.$broadcast("attachment:preview",attachment)})):void 0}),$scope.$on("$destroy",function(){return $el.off()}),attachment=$scope.$eval($attrs.tgAttachment),render(attachment,attachment.isCreatedRightNow),attachment.isCreatedRightNow?$el.find("input[name='description']").focus().select():void 0},{link:link,require:"^tgAttachments",restrict:"AE"}},module.directive("tgAttachment",["$tgTemplate","$compile","$translate","$rootScope",AttachmentDirective])}.call(this),function(){var BindScope,module;module=angular.module("taigaCommon"),BindScope=function(config){var link;return config.debugInfo||(jQuery.fn.scope=function(){return this.data("scope")}),link=function($scope,$el){return config.debugInfo?void 0:$el.data("scope",$scope).addClass("tg-scope")},{link:link}},module.directive("tgBindScope",["$tgConfig",BindScope])}.call(this),function(){var CompileHtmlDirective;CompileHtmlDirective=function($compile){var link;return link=function(scope,element,attrs){return scope.$watch(attrs.tgCompileHtml,function(newValue,oldValue){return element.html(newValue),$compile(element.contents())(scope)})},{link:link}},CompileHtmlDirective.$inject=["$compile"],angular.module("taigaCommon").directive("tgCompileHtml",CompileHtmlDirective)}.call(this),function(){var AssignedToDirective,BlockButtonDirective,CreatedByDisplayDirective,DateRangeDirective,DateSelectorDirective,DeleteButtonDirective,EditableDescriptionDirective,EditableSubjectDirective,ListItemAssignedtoDirective,ListItemIssueStatusDirective,ListItemPriorityDirective,ListItemSeverityDirective,ListItemTaskStatusDirective,ListItemTypeDirective,ListItemUsStatusDirective,SprintProgressBarDirective,TgMainTitleDirective,TgProgressBarDirective,WatchersDirective,bindOnce,module,taiga; -taiga=this.taiga,bindOnce=this.taiga.bindOnce,module=angular.module("taigaCommon"),DateRangeDirective=function($translate){var link,renderRange;return renderRange=function($el,first,second){var endDate,initDate,prettyDate;return prettyDate=$translate.instant("BACKLOG.SPRINTS.DATE"),initDate=moment(first).format(prettyDate),endDate=moment(second).format(prettyDate),$el.html(initDate+"-"+endDate)},link=function($scope,$el,$attrs){var first,ref,second;return ref=$attrs.tgDateRange.split(","),first=ref[0],second=ref[1],bindOnce($scope,first,function(valFirst){return bindOnce($scope,second,function(valSecond){return renderRange($el,valFirst,valSecond)})})},{link:link}},module.directive("tgDateRange",["$translate",DateRangeDirective]),DateSelectorDirective=function($rootscope,datePickerConfigService){var link;return link=function($scope,$el,$attrs,$model){var initialize,selectedDate,unbind;return selectedDate=null,initialize=function(){var datePickerConfig;return datePickerConfig=datePickerConfigService.get(),_.merge(datePickerConfig,{field:$el[0],onSelect:function(_this){return function(date){return selectedDate=date}}(this),onOpen:function(_this){return function(){return null!=selectedDate?$el.picker.setDate(selectedDate):void 0}}(this)}),$el.picker=new Pikaday(datePickerConfig)},unbind=$rootscope.$on("$translateChangeEnd",function(_this){return function(ctx){return initialize()}}(this)),$scope.$watch($attrs.ngModel,function(val){return null==val||$el.picker||initialize(),null!=val?$el.picker.setDate(val):void 0}),$scope.$on("$destroy",function(){return $el.off(),unbind()})},{link:link,require:"ngModel"}},module.directive("tgDateSelector",["$rootScope","tgDatePickerConfigService",DateSelectorDirective]),SprintProgressBarDirective=function(){var link,renderProgress;return renderProgress=function($el,percentage,visual_percentage){return $el.hasClass(".current-progress")?$el.css("width",percentage+"%"):($el.find(".current-progress").css("width",visual_percentage+"%"),$el.find(".number").html(percentage+" %"))},link=function($scope,$el,$attrs){return bindOnce($scope,$attrs.tgSprintProgressbar,function(sprint){var closedPoints,percentage,totalPoints,visual_percentage;return closedPoints=sprint.closed_points,totalPoints=sprint.total_points,percentage=0,0!==totalPoints&&(percentage=Math.round(100*(closedPoints/totalPoints))),visual_percentage=0,0!==totalPoints&&(visual_percentage=Math.round(98*(closedPoints/totalPoints))),renderProgress($el,percentage,visual_percentage)}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgSprintProgressbar",SprintProgressBarDirective),CreatedByDisplayDirective=function($template,$compile,$translate,$navUrls){var link;return link=function($scope,$el,$attrs){return bindOnce($scope,$attrs.ngModel,function(model){var ref;return null!=model?($scope.owner=model.owner_extra_info||{full_name_display:$translate.instant("COMMON.EXTERNAL_USER"),photo:"/"+window._version+"/images/user-noimage.png"},$scope.url=(null!=(ref=$scope.owner)?ref.is_active:void 0)?$navUrls.resolve("user-profile",{username:$scope.owner.username}):"",$scope.date=moment(model.created_date).format($translate.instant("COMMON.DATETIME"))):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,restrict:"EA",require:"ngModel",scope:!0,templateUrl:"common/components/created-by.html"}},module.directive("tgCreatedByDisplay",["$tgTemplate","$compile","$translate","$tgNavUrls",CreatedByDisplayDirective]),WatchersDirective=function($rootscope,$confirm,$repo,$qqueue,$template,$compile,$translate){var link,template;return template=$template.get("common/components/watchers.html",!0),link=function($scope,$el,$attrs,$model){var deleteWatcher,isEditable,renderWatchers,save;return isEditable=function(){var ref,ref1;return-1!==(null!=(ref=$scope.project)&&null!=(ref1=ref.my_permissions)?ref1.indexOf($attrs.requiredPerm):void 0)},save=$qqueue.bindAdd(function(_this){return function(watchers){var item,promise;return item=$model.$modelValue.clone(),item.watchers=watchers,$model.$setViewValue(item),promise=$repo.save($model.$modelValue),promise.then(function(){return $confirm.notify("success"),watchers=_.map(watchers,function(watcherId){return $scope.usersById[watcherId]}),renderWatchers(watchers),$rootscope.$broadcast("object:updated")}),promise.then(null,function(){return $model.$modelValue.revert()})}}(this)),deleteWatcher=$qqueue.bindAdd(function(_this){return function(watcherIds){var item,promise;return item=$model.$modelValue.clone(),item.watchers=watcherIds,$model.$setViewValue(item),promise=$repo.save($model.$modelValue),promise.then(function(){var watchers;return $confirm.notify("success"),watchers=_.map(item.watchers,function(watcherId){return $scope.usersById[watcherId]}),renderWatchers(watchers),$rootscope.$broadcast("object:updated")}),promise.then(null,function(){return item.revert(),$confirm.notify("error")})}}(this)),renderWatchers=function(watchers){var ctx,html;return ctx={watchers:watchers,isEditable:isEditable()},html=$compile(template(ctx))($scope),$el.html(html)},$el.on("click",".js-delete-watcher",function(event){var message,target,title,watcherId;return event.preventDefault(),isEditable()?(target=angular.element(event.currentTarget),watcherId=target.data("watcher-id"),title=$translate.instant("COMMON.WATCHERS.TITLE_LIGHTBOX_DELETE_WARTCHER"),message=$scope.usersById[watcherId].full_name_display,$confirm.askOnDelete(title,message).then(function(_this){return function(askResponse){var watcherIds;return askResponse.finish(),watcherIds=_.clone($model.$modelValue.watchers,!1),watcherIds=_.pull(watcherIds,watcherId),deleteWatcher(watcherIds)}}(this))):void 0}),$el.on("click",".js-add-watcher",function(event){return event.preventDefault(),isEditable()?$scope.$apply(function(){return $rootscope.$broadcast("watcher:add",$model.$modelValue)}):void 0}),$scope.$on("watcher:added",function(ctx,watcherId){var watchers;return watchers=_.clone($model.$modelValue.watchers,!1),watchers.push(watcherId),watchers=_.uniq(watchers),save(watchers)}),$scope.$watch($attrs.ngModel,function(item){var watchers;if(null!=item)return watchers=_.map(item.watchers,function(watcherId){return $scope.usersById[watcherId]}),renderWatchers(watchers)}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,require:"ngModel"}},module.directive("tgWatchers",["$rootScope","$tgConfirm","$tgRepo","$tgQqueue","$tgTemplate","$compile","$translate",WatchersDirective]),AssignedToDirective=function($rootscope,$confirm,$repo,$loading,$qqueue,$template,$translate,$compile){var link,template;return template=$template.get("common/components/assigned-to.html",!0),link=function($scope,$el,$attrs,$model){var isEditable,renderAssignedTo,save;return isEditable=function(){var ref,ref1;return-1!==(null!=(ref=$scope.project)&&null!=(ref1=ref.my_permissions)?ref1.indexOf($attrs.requiredPerm):void 0)},save=$qqueue.bindAdd(function(_this){return function(userId){var currentLoading,promise;return $model.$modelValue.assigned_to=userId,currentLoading=$loading().target($el).start(),promise=$repo.save($model.$modelValue),promise.then(function(){return currentLoading.finish(),$confirm.notify("success"),renderAssignedTo($model.$modelValue),$rootscope.$broadcast("object:updated")}),promise.then(null,function(){return $model.$modelValue.revert(),$confirm.notify("error"),currentLoading.finish()}),promise}}(this)),renderAssignedTo=function(issue){var assignedTo,assignedToId,ctx,html;return assignedToId=null!=issue?issue.assigned_to:void 0,assignedTo=null!=assignedToId?$scope.usersById[assignedToId]:null,ctx={assignedTo:assignedTo,isEditable:isEditable()},html=$compile(template(ctx))($scope),$el.html(html)},$el.on("click",".user-assigned",function(event){return event.preventDefault(),isEditable()?$scope.$apply(function(){return $rootscope.$broadcast("assigned-to:add",$model.$modelValue)}):void 0}),$el.on("click",".icon-delete",function(event){var title;return event.preventDefault(),isEditable()?(title=$translate.instant("COMMON.ASSIGNED_TO.CONFIRM_UNASSIGNED"),$confirm.ask(title).then(function(_this){return function(response){return response.finish(),$model.$modelValue.assigned_to=null,save(null)}}(this))):void 0}),$scope.$on("assigned-to:added",function(ctx,userId,item){return item.id===$model.$modelValue.id?save(userId):void 0}),$scope.$watch($attrs.ngModel,function(instance){return renderAssignedTo(instance)}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,require:"ngModel"}},module.directive("tgAssignedTo",["$rootScope","$tgConfirm","$tgRepo","$tgLoading","$tgQqueue","$tgTemplate","$translate","$compile",AssignedToDirective]),BlockButtonDirective=function($rootscope,$loading,$template){var link,template;return template=$template.get("common/components/block-button.html"),link=function($scope,$el,$attrs,$model){var isEditable;return isEditable=function(){return-1!==$scope.project.my_permissions.indexOf("modify_us")},$scope.$watch($attrs.ngModel,function(item){return item?(isEditable()&&$el.find(".item-block").addClass("editable"),item.is_blocked?($el.find(".item-block").hide(),$el.find(".item-unblock").show()):($el.find(".item-block").show(),$el.find(".item-unblock").hide())):void 0}),$el.on("click",".item-block",function(event){return event.preventDefault(),$rootscope.$broadcast("block",$model.$modelValue)}),$el.on("click",".item-unblock",function(event){var currentLoading,finish;return event.preventDefault(),currentLoading=$loading().target($el.find(".item-unblock")).start(),finish=function(){return currentLoading.finish()},$rootscope.$broadcast("unblock",$model.$modelValue,finish)}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,restrict:"EA",require:"ngModel",template:template}},module.directive("tgBlockButton",["$rootScope","$tgLoading","$tgTemplate",BlockButtonDirective]),DeleteButtonDirective=function($log,$repo,$confirm,$location,$template){var link,template;return template=$template.get("common/components/delete-button.html"),link=function($scope,$el,$attrs,$model){return $attrs.onDeleteGoToUrl?$attrs.onDeleteTitle?($el.on("click",".button-delete",function(event){var subtitle,title;return title=$attrs.onDeleteTitle,subtitle=$model.$modelValue.subject,$confirm.askOnDelete(title,subtitle).then(function(_this){return function(askResponse){var promise;return promise=$repo.remove($model.$modelValue),promise.then(function(){var url;return askResponse.finish(),url=$scope.$eval($attrs.onDeleteGoToUrl),$location.path(url)}),promise.then(null,function(){return askResponse.finish(!1),$confirm.notify("error")})}}(this))}),$scope.$on("$destroy",function(){return $el.off()})):$log.error("DeleteButtonDirective requires on-delete-title set in scope."):$log.error("DeleteButtonDirective requires on-delete-go-to-url set in scope.")},{link:link,restrict:"EA",require:"ngModel",template:template}},module.directive("tgDeleteButton",["$log","$tgRepo","$tgConfirm","$tgLocation","$tgTemplate",DeleteButtonDirective]),EditableSubjectDirective=function($rootscope,$repo,$confirm,$loading,$qqueue,$template){var link,template;return template=$template.get("common/components/editable-subject.html"),link=function($scope,$el,$attrs,$model){var isEditable,save;return $scope.$on("object:updated",function(){return $el.find(".edit-subject").hide(),$el.find(".view-subject").show()}),isEditable=function(){return-1!==$scope.project.my_permissions.indexOf($attrs.requiredPerm)},save=$qqueue.bindAdd(function(_this){return function(subject){var currentLoading,promise;return $model.$modelValue.subject=subject,currentLoading=$loading().target($el.find(".save-container")).start(),promise=$repo.save($model.$modelValue),promise.then(function(){return $confirm.notify("success"),$rootscope.$broadcast("object:updated"),$el.find(".edit-subject").hide(),$el.find(".view-subject").show()}),promise.then(null,function(){return $confirm.notify("error")}),promise["finally"](function(){return currentLoading.finish()}),promise}}(this)),$el.click(function(){return isEditable()?($el.find(".edit-subject").show(),$el.find(".view-subject").hide(),$el.find("input").focus()):void 0}),$el.on("click",".save",function(e){var subject;return e.preventDefault(),subject=$scope.item.subject,save(subject)}),$el.on("keyup","input",function(event){var subject;return 13===event.keyCode?(subject=$scope.item.subject,save(subject)):27===event.keyCode?($scope.$apply(function(_this){return function(){return $model.$modelValue.revert()}}(this)),$el.find("div.edit-subject").hide(),$el.find("div.view-subject").show()):void 0}),$el.find("div.edit-subject").hide(),$el.find("div.view-subject span.edit").hide(),$scope.$watch($attrs.ngModel,function(value){return value?($scope.item=value,isEditable()?void 0:$el.find(".view-subject .edit").remove()):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,restrict:"EA",require:"ngModel",template:template}},module.directive("tgEditableSubject",["$rootScope","$tgRepo","$tgConfirm","$tgLoading","$tgQqueue","$tgTemplate",EditableSubjectDirective]),EditableDescriptionDirective=function($rootscope,$repo,$confirm,$compile,$loading,$selectedText,$qqueue,$template){var link,noDescriptionMegEditMode,noDescriptionMegReadMode,template;return template=$template.get("common/components/editable-description.html"),noDescriptionMegEditMode=$template.get("common/components/editable-description-msg-edit-mode.html"),noDescriptionMegReadMode=$template.get("common/components/editable-description-msg-read-mode.html"),link=function($scope,$el,$attrs,$model){var isEditable,save;return $el.find(".edit-description").hide(),$el.find(".view-description .edit").hide(),$scope.$on("object:updated",function(){return $el.find(".edit-description").hide(),$el.find(".view-description").show()}),isEditable=function(){return-1!==$scope.project.my_permissions.indexOf($attrs.requiredPerm)},save=$qqueue.bindAdd(function(_this){return function(description){var currentLoading,promise;return $model.$modelValue.description=description,currentLoading=$loading().target($el.find(".save-container")).start(),promise=$repo.save($model.$modelValue),promise.then(function(){return $confirm.notify("success"),$rootscope.$broadcast("object:updated"),$el.find(".edit-description").hide(),$el.find(".view-description").show()}),promise.then(null,function(){return $confirm.notify("error")}),promise["finally"](function(){return currentLoading.finish()})}}(this)),$el.on("mouseup",".view-description",function(event){var target;return target=angular.element(event.target),!isEditable()||target.is("a")||$selectedText.get().length?void 0:($el.find(".edit-description").show(),$el.find(".view-description").hide(),$el.find("textarea").focus())}),$el.on("click","a",function(event){var href,target;return target=angular.element(event.target),href=target.attr("href"),0===href.indexOf("#")?(event.preventDefault(),$("body").scrollTop($(href).offset().top)):void 0}),$el.on("click",".save",function(e){var description;return e.preventDefault(),description=$scope.item.description,save(description)}),$el.on("keydown","textarea",function(event){return 27===event.keyCode?($scope.$apply(function(_this){return function(){return $scope.item.revert()}}(this)),$el.find(".edit-description").hide(),$el.find(".view-description").show()):void 0}),$scope.$watch($attrs.ngModel,function(value){return value?($scope.item=value,isEditable()?($el.find(".view-description .edit").show(),$el.find(".view-description .us-content").addClass("editable"),$scope.noDescriptionMsg=$compile(noDescriptionMegEditMode)($scope)):$scope.noDescriptionMsg=$compile(noDescriptionMegReadMode)($scope)):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,restrict:"EA",require:"ngModel",template:template}},module.directive("tgEditableDescription",["$rootScope","$tgRepo","$tgConfirm","$compile","$tgLoading","$selectedText","$tgQqueue","$tgTemplate",EditableDescriptionDirective]),ListItemUsStatusDirective=function(){var link;return link=function($scope,$el,$attrs){var us;return us=$scope.$eval($attrs.tgListitemUsStatus),bindOnce($scope,"usStatusById",function(usStatusById){return $el.html(usStatusById[us.status].name)})},{link:link}},module.directive("tgListitemUsStatus",ListItemUsStatusDirective),ListItemTaskStatusDirective=function(){var link;return link=function($scope,$el,$attrs){var task;return task=$scope.$eval($attrs.tgListitemTaskStatus),bindOnce($scope,"taskStatusById",function(taskStatusById){return $el.html(taskStatusById[task.status].name)})},{link:link}},module.directive("tgListitemTaskStatus",ListItemTaskStatusDirective),ListItemAssignedtoDirective=function($template){var link,template;return template=$template.get("common/components/list-item-assigned-to-avatar.html",!0),link=function($scope,$el,$attrs){return bindOnce($scope,"usersById",function(usersById){var ctx,item,member;return item=$scope.$eval($attrs.tgListitemAssignedto),ctx={name:"Unassigned",imgurl:"/"+window._version+"/images/unnamed.png"},member=usersById[item.assigned_to],member&&(ctx.imgurl=member.photo,ctx.name=member.full_name_display),$el.html(template(ctx))})},{link:link}},module.directive("tgListitemAssignedto",["$tgTemplate",ListItemAssignedtoDirective]),ListItemIssueStatusDirective=function(){var link;return link=function($scope,$el,$attrs){var issue;return issue=$scope.$eval($attrs.tgListitemIssueStatus),bindOnce($scope,"issueStatusById",function(issueStatusById){return $el.html(issueStatusById[issue.status].name)})},{link:link}},module.directive("tgListitemIssueStatus",ListItemIssueStatusDirective),ListItemTypeDirective=function(){var link;return link=function($scope,$el,$attrs){var render;return render=function(issueTypeById,issue){var domNode,type;return type=issueTypeById[issue.type],domNode=$el.find(".level"),domNode.css("background-color",type.color),domNode.attr("title",type.name)},bindOnce($scope,"issueTypeById",function(issueTypeById){var issue;return issue=$scope.$eval($attrs.tgListitemType),render(issueTypeById,issue)}),$scope.$watch($attrs.tgListitemType,function(issue){return render($scope.issueTypeById,issue)})},{link:link,templateUrl:"common/components/level.html"}},module.directive("tgListitemType",ListItemTypeDirective),ListItemPriorityDirective=function(){var link;return link=function($scope,$el,$attrs){var render;return render=function(priorityById,issue){var domNode,priority;return priority=priorityById[issue.priority],domNode=$el.find(".level"),domNode.css("background-color",priority.color),domNode.attr("title",priority.name)},bindOnce($scope,"priorityById",function(priorityById){var issue;return issue=$scope.$eval($attrs.tgListitemPriority),render(priorityById,issue)}),$scope.$watch($attrs.tgListitemPriority,function(issue){return render($scope.priorityById,issue)})},{link:link,templateUrl:"common/components/level.html"}},module.directive("tgListitemPriority",ListItemPriorityDirective),ListItemSeverityDirective=function(){var link;return link=function($scope,$el,$attrs){var render;return render=function(severityById,issue){var domNode,severity;return severity=severityById[issue.severity],domNode=$el.find(".level"),domNode.css("background-color",severity.color),domNode.attr("title",severity.name)},bindOnce($scope,"severityById",function(severityById){var issue;return issue=$scope.$eval($attrs.tgListitemSeverity),render(severityById,issue)}),$scope.$watch($attrs.tgListitemSeverity,function(issue){return render($scope.severityById,issue)})},{link:link,templateUrl:"common/components/level.html"}},module.directive("tgListitemSeverity",ListItemSeverityDirective),TgProgressBarDirective=function($template){var link,render,template;return template=$template.get("common/components/progress-bar.html",!0),render=function(el,percentage){return el.html(template({percentage:percentage}))},link=function($scope,$el,$attrs){var element;return element=angular.element($el),$scope.$watch($attrs.tgProgressBar,function(percentage){return percentage=_.max([0,percentage]),percentage=_.min([100,percentage]),render($el,percentage)}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgProgressBar",["$tgTemplate",TgProgressBarDirective]),TgMainTitleDirective=function($translate){var link;return link=function($scope,$el,$attrs){return $attrs.$observe("i18nSectionName",function(i18nSectionName){return $scope.sectionName=$translate.instant(i18nSectionName)}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,templateUrl:"common/components/main-title.html",scope:{projectName:"=projectName"}}},module.directive("tgMainTitle",["$translate",TgMainTitleDirective])}.call(this),function(){var ConfirmService,NOTIFICATION_MSG,bindMethods,cancelTimeout,debounce,module,taiga,timeout,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,timeout=this.taiga.timeout,cancelTimeout=this.taiga.cancelTimeout,debounce=this.taiga.debounce,bindMethods=this.taiga.bindMethods,NOTIFICATION_MSG={success:{title:"NOTIFICATION.OK",message:"NOTIFICATION.SAVED"},error:{title:"NOTIFICATION.WARNING",message:"NOTIFICATION.WARNING_TEXT"},"light-error":{title:"NOTIFICATION.WARNING",message:"NOTIFICATION.WARNING_TEXT"}},ConfirmService=function(superClass){function ConfirmService(q,lightboxService,loading,translate){this.q=q,this.lightboxService=lightboxService,this.loading=loading,this.translate=translate,bindMethods(this)}return extend(ConfirmService,superClass),ConfirmService.$inject=["$q","lightboxService","$tgLoading","$translate"],ConfirmService.prototype.hide=function(el){return el?(this.lightboxService.close(el),el.off(".confirm-dialog")):void 0},ConfirmService.prototype.ask=function(title,subtitle,message,lightboxSelector){var defered,el;return null==lightboxSelector&&(lightboxSelector=".lightbox-generic-ask"),defered=this.q.defer(),el=angular.element(lightboxSelector),el.find("h2.title").text(title),el.find("span.subtitle").text(subtitle),el.find("span.message").text(message),el.on("click.confirm-dialog","a.button-green",debounce(2e3,function(_this){return function(event){var currentLoading,target;return event.preventDefault(),target=angular.element(event.currentTarget),currentLoading=_this.loading().target(target).start(),defered.resolve({finish:function(ok){return null==ok&&(ok=!0),currentLoading.finish(),ok?_this.hide(el):void 0}})}}(this))),el.on("click.confirm-dialog","a.button-red",function(_this){return function(event){return event.preventDefault(),defered.reject(),_this.hide(el)}}(this)),this.lightboxService.open(el),defered.promise},ConfirmService.prototype.askOnDelete=function(title,message){return this.ask(title,this.translate.instant("NOTIFICATION.ASK_DELETE"),message)},ConfirmService.prototype.askChoice=function(title,subtitle,choices,replacement,warning,lightboxSelector){var choicesField,defered,el;return null==lightboxSelector&&(lightboxSelector=".lightbox-ask-choice"),defered=this.q.defer(),el=angular.element(lightboxSelector),el.find(".title").html(title),el.find(".subtitle").html(subtitle),replacement?el.find(".replacement").html(replacement):el.find(".replacement").remove(),warning?el.find(".warning").html(warning):el.find(".warning").remove(),choicesField=el.find(".choices"),choicesField.html(""),_.each(choices,function(value,key){return choicesField.append(angular.element(""))}),el.on("click.confirm-dialog","a.button-green",debounce(2e3,function(_this){return function(event){var currentLoading,target;return event.preventDefault(),target=angular.element(event.currentTarget),currentLoading=_this.loading().target(target).start(),defered.resolve({selected:choicesField.val(),finish:function(ok){return null==ok&&(ok=!0),currentLoading.finish(),ok?_this.hide(el):void 0}})}}(this))),el.on("click.confirm-dialog","a.button-red",function(_this){return function(event){return event.preventDefault(),defered.reject(),_this.hide(el)}}(this)),this.lightboxService.open(el),defered.promise},ConfirmService.prototype.error=function(message){var defered,el;return defered=this.q.defer(),el=angular.element(".lightbox-generic-error"),el.find("h2.title").html(message),el.on("click.confirm-dialog","a.button-green",function(_this){return function(event){return event.preventDefault(),defered.resolve(),_this.hide(el)}}(this)),el.on("click.confirm-dialog","a.close",function(_this){return function(event){return event.preventDefault(),defered.resolve(),_this.hide(el)}}(this)),this.lightboxService.open(el),defered.promise},ConfirmService.prototype.success=function(title,message){var defered,el;return defered=this.q.defer(),el=angular.element(".lightbox-generic-success"),title&&el.find("h2.title").html(title),message&&el.find("p.message").html(message),el.on("click.confirm-dialog","a.button-green",function(_this){return function(event){return event.preventDefault(),defered.resolve(),_this.hide(el)}}(this)),el.on("click.confirm-dialog","a.close",function(_this){return function(event){return event.preventDefault(),defered.resolve(),_this.hide(el)}}(this)),this.lightboxService.open(el),defered.promise},ConfirmService.prototype.loader=function(title,message){var el;return el=angular.element(".lightbox-generic-loading"),title&&el.find("h2.title").html(title),message&&el.find("p.message").html(message),{start:function(_this){return function(){return _this.lightboxService.open(el)}}(this),stop:function(_this){return function(){return _this.lightboxService.close(el)}}(this),update:function(_this){return function(status,title,message,percent){return title&&el.find("h2.title").html(title),message&&el.find("p.message").html(message),percent?(el.find(".spin").addClass("hidden"),el.find(".progress-bar-wrapper").removeClass("hidden"),el.find(".progress-bar-wrapper > .bar").width(percent+"%"),el.find(".progress-bar-wrapper > span").html(percent+"%").css("left",percent-9+"%")):(el.find(".spin").removeClass("hidden"),el.find(".progress-bar-wrapper").addClass("hidden"))}}(this)}},ConfirmService.prototype.notify=function(type,message,title,time){var body,el,selector;return selector=".notification-message-"+type,el=angular.element(selector),el.hasClass("active")?void 0:(title?el.find("h4").html(title):el.find("h4").html(this.translate.instant(NOTIFICATION_MSG[type].title)),message?el.find("p").html(message):el.find("p").html(this.translate.instant(NOTIFICATION_MSG[type].message)),body=angular.element("body"),body.find(".notification-message .notification-light").removeClass("active").addClass("inactive"),body.find(selector).removeClass("inactive").addClass("active"),this.tsem&&cancelTimeout(this.tsem),time||(time="error"===type||"light-error"===type?3500:1500),this.tsem=timeout(time,function(_this){return function(){return body.find(selector).removeClass("active").addClass("inactive"),delete _this.tsem}}(this)),el.on("click",".icon-delete, .close",function(_this){return function(event){return body.find(selector).removeClass("active").addClass("inactive")}}(this)))},ConfirmService}(taiga.Service),module=angular.module("taigaCommon"),module.service("$tgConfirm",ConfirmService)}.call(this),function(){var CustomAttributeValueDirective,CustomAttributesValuesController,CustomAttributesValuesDirective,DATE_TYPE,MULTILINE_TYPE,TEXT_TYPE,TYPE_CHOICES,bindMethods,bindOnce,debounce,generateHash,module,taiga,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,bindMethods=this.taiga.bindMethods,bindOnce=this.taiga.bindOnce,debounce=this.taiga.debounce,generateHash=taiga.generateHash,module=angular.module("taigaCommon"),TEXT_TYPE="text",MULTILINE_TYPE="multiline",DATE_TYPE="date",TYPE_CHOICES=[{key:TEXT_TYPE,name:"ADMIN.CUSTOM_FIELDS.FIELD_TYPE_TEXT"},{key:MULTILINE_TYPE,name:"ADMIN.CUSTOM_FIELDS.FIELD_TYPE_MULTI"},{key:DATE_TYPE,name:"ADMIN.CUSTOM_FIELDS.FIELD_TYPE_DATE"}],CustomAttributesValuesController=function(superClass){function CustomAttributesValuesController(scope,rootscope,repo,rs,confirm,q){this.scope=scope,this.rootscope=rootscope,this.repo=repo,this.rs=rs,this.confirm=confirm,this.q=q,bindMethods(this),this.type=null,this.objectId=null,this.projectId=null,this.customAttributes=[],this.customAttributesValues=null}return extend(CustomAttributesValuesController,superClass),CustomAttributesValuesController.$inject=["$scope","$rootScope","$tgRepo","$tgResources","$tgConfirm","$q"],CustomAttributesValuesController.prototype.initialize=function(type,objectId){return this.project=this.scope.project,this.type=type,this.objectId=objectId,this.projectId=this.scope.projectId},CustomAttributesValuesController.prototype.loadCustomAttributesValues=function(){return this.objectId?this.rs.customAttributesValues[this.type].get(this.objectId).then(function(_this){return function(customAttributesValues){return _this.customAttributes=_this.project[_this.type+"_custom_attributes"],_this.customAttributesValues=customAttributesValues,customAttributesValues}}(this)):this.customAttributesValues},CustomAttributesValuesController.prototype.getAttributeValue=function(attribute){var attributeValue;return attributeValue=_.clone(attribute,!1),attributeValue.value=this.customAttributesValues.attributes_values[attribute.id],attributeValue},CustomAttributesValuesController.prototype.updateAttributeValue=function(attributeValue){var attributesValues,onError,onSuccess;return onSuccess=function(_this){return function(){return _this.rootscope.$broadcast("custom-attributes-values:edit")}}(this),onError=function(_this){return function(response){return _this.confirm.notify("error"),_this.q.reject()}}(this),attributesValues=_.clone(this.customAttributesValues.attributes_values,!0),attributesValues[attributeValue.id]=attributeValue.value,this.customAttributesValues.attributes_values=attributesValues,this.customAttributesValues.id=this.objectId,this.repo.save(this.customAttributesValues).then(onSuccess,onError)},CustomAttributesValuesController}(taiga.Controller),CustomAttributesValuesDirective=function($templates,$storage){var collapsedHash,link,template,templateFn;return template=$templates.get("custom-attributes/custom-attributes-values.html",!0),collapsedHash=function(type){return generateHash(["custom-attributes-collapsed",type])},link=function($scope,$el,$attrs,$ctrls){var $ctrl,$model;return $ctrl=$ctrls[0],$model=$ctrls[1],bindOnce($scope,$attrs.ngModel,function(value){return $ctrl.initialize($attrs.type,value.id),$ctrl.loadCustomAttributesValues()}),$el.on("click",".custom-fields-header a",function(){var collapsed,hash;return hash=collapsedHash($attrs.type),collapsed=!$storage.get(hash),$storage.set(hash,collapsed),collapsed?($el.find(".custom-fields-header a").removeClass("open"),$el.find(".custom-fields-body").removeClass("open")):($el.find(".custom-fields-header a").addClass("open"),$el.find(".custom-fields-body").addClass("open"))}),$scope.$on("$destroy",function(){return $el.off()})},templateFn=function($el,$attrs){var collapsed;return collapsed=$storage.get(collapsedHash($attrs.type))||!1,template({requiredEditionPerm:$attrs.requiredEditionPerm,collapsed:collapsed})},{require:["tgCustomAttributesValues","ngModel"],controller:CustomAttributesValuesController,controllerAs:"ctrl",restrict:"AE",scope:!0,link:link,template:templateFn}},module.directive("tgCustomAttributesValues",["$tgTemplate","$tgStorage","$translate",CustomAttributesValuesDirective]),CustomAttributeValueDirective=function($template,$selectedText,$compile,$translate,datePickerConfigService){var link,template,templateEdit;return template=$template.get("custom-attributes/custom-attribute-value.html",!0), -templateEdit=$template.get("custom-attributes/custom-attribute-value-edit.html",!0),link=function($scope,$el,$attrs,$ctrl){var attributeValue,isEditable,prettyDate,render,setFocusAndSelectOnInputField,submit;return prettyDate=$translate.instant("COMMON.PICKERDATE.FORMAT"),render=function(attributeValue,edit){var ctx,datePickerConfig,editable,html,value;return null==edit&&(edit=!1),value=attributeValue.type===DATE_TYPE&&attributeValue.value?moment(attributeValue.value,"YYYY-MM-DD").format(prettyDate):attributeValue.value,editable=isEditable(),ctx={id:attributeValue.id,name:attributeValue.name,description:attributeValue.description,value:value,isEditable:editable,type:attributeValue.type},!editable||!edit&&value?(html=template(ctx),html=$compile(html)($scope),$el.html(html)):(html=templateEdit(ctx),html=$compile(html)($scope),$el.html(html),attributeValue.type===DATE_TYPE?(datePickerConfig=datePickerConfigService.get(),_.merge(datePickerConfig,{field:$el.find("input[name=value]")[0],onSelect:function(_this){return function(date){var selectedDate;return selectedDate=date}}(this),onOpen:function(_this){return function(){return"undefined"!=typeof selectedDate&&null!==selectedDate?$el.picker.setDate(selectedDate):void 0}}(this)}),$el.picker=new Pikaday(datePickerConfig)):void 0)},isEditable=function(){var permissions,requiredEditionPerm;return permissions=$scope.project.my_permissions,requiredEditionPerm=$attrs.requiredEditionPerm,permissions.indexOf(requiredEditionPerm)>-1},submit=debounce(2e3,function(_this){return function(event){return event.preventDefault(),attributeValue.value=$el.find("input[name=value], textarea[name='value']").val(),attributeValue.type===DATE_TYPE&&(moment(attributeValue.value,prettyDate).isValid()?attributeValue.value=moment(attributeValue.value,prettyDate).format("YYYY-MM-DD"):attributeValue.value=""),$scope.$apply(function(){return $ctrl.updateAttributeValue(attributeValue).then(function(){return render(attributeValue,!1)})})}}(this)),setFocusAndSelectOnInputField=function(){return $el.find("input[name='value'], textarea[name='value']").focus().select()},attributeValue=$scope.$eval($attrs.tgCustomAttributeValue),render(attributeValue),$el.on("click",".js-value-view-mode",function(){return isEditable()&&!$selectedText.get().length?(render(attributeValue,!0),setFocusAndSelectOnInputField()):void 0}),$el.on("click","a.icon-edit",function(event){return event.preventDefault(),render(attributeValue,!0),setFocusAndSelectOnInputField()}),$el.on("keyup","input[name=value], textarea[name='value']",function(event){return 13===event.keyCode&&"textarea"!==event.currentTarget.type?submit(event):27===event.keyCode?render(attributeValue,!1):void 0}),$el.on("submit","form",submit),$el.on("click","a.icon-floppy",submit),$scope.$on("$destroy",function(){return $el.off()})},{link:link,require:"^tgCustomAttributesValues",restrict:"AE"}},module.directive("tgCustomAttributeValue",["$tgTemplate","$selectedText","$compile","$translate","tgDatePickerConfigService",CustomAttributeValueDirective])}.call(this),function(){var EstimationsService,LbUsEstimationDirective,UsEstimationDirective,groupBy,module,taiga,bind=function(fn,me){return function(){return fn.apply(me,arguments)}};taiga=this.taiga,groupBy=this.taiga.groupBy,module=angular.module("taigaCommon"),LbUsEstimationDirective=function($tgEstimationsService,$rootScope,$repo,$confirm,$template,$compile){var link;return link=function($scope,$el,$attrs,$model){return $scope.$watch($attrs.ngModel,function(us){var estimationProcess;return us?(estimationProcess=$tgEstimationsService.create($el,us,$scope.project),estimationProcess.onSelectedPointForRole=function(roleId,pointId){return $scope.$apply(function(){return $model.$setViewValue(us)})},estimationProcess.render=function(){var ctx,html,mainTemplate,template;return ctx={totalPoints:this.calculateTotalPoints(),roles:this.calculateRoles(),editable:this.isEditable},mainTemplate="common/estimation/us-estimation-points-per-role.html",template=$template.get(mainTemplate,!0),html=template(ctx),html=$compile(html)($scope),this.$el.html(html)},estimationProcess.render()):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,restrict:"EA",require:"ngModel"}},module.directive("tgLbUsEstimation",["$tgEstimationsService","$rootScope","$tgRepo","$tgConfirm","$tgTemplate","$compile",LbUsEstimationDirective]),UsEstimationDirective=function($tgEstimationsService,$rootScope,$repo,$confirm,$qqueue,$template,$compile){var link;return link=function($scope,$el,$attrs,$model){return $scope.$watch($attrs.ngModel,function(us){var estimationProcess;return us?(estimationProcess=$tgEstimationsService.create($el,us,$scope.project),estimationProcess.onSelectedPointForRole=function(roleId,pointId){return this.save(roleId,pointId).then(function(){return $rootScope.$broadcast("object:updated")})},estimationProcess.render=function(){var ctx,html,mainTemplate,template;return ctx={totalPoints:this.calculateTotalPoints(),roles:this.calculateRoles(),editable:this.isEditable},mainTemplate="common/estimation/us-estimation-points-per-role.html",template=$template.get(mainTemplate,!0),html=template(ctx),html=$compile(html)($scope),this.$el.html(html)},estimationProcess.render()):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,restrict:"EA",require:"ngModel"}},module.directive("tgUsEstimation",["$tgEstimationsService","$rootScope","$tgRepo","$tgConfirm","$tgQqueue","$tgTemplate","$compile",UsEstimationDirective]),EstimationsService=function($template,$qqueue,$repo,$confirm,$q){var EstimationProcess,create,pointsTemplate;return pointsTemplate=$template.get("common/estimation/us-estimation-points.html",!0),EstimationProcess=function(){function EstimationProcess($el1,us1,project1){this.$el=$el1,this.us=us1,this.project=project1,this.bindClickEvents=bind(this.bindClickEvents,this),this.isEditable=-1!==this.project.my_permissions.indexOf("modify_us"),this.roles=this.project.roles,this.points=this.project.points,this.pointsById=groupBy(this.points,function(x){return x.id}),this.onSelectedPointForRole=function(roleId,pointId){},this.render=function(){}}return EstimationProcess.prototype.save=function(roleId,pointId){var deferred;return deferred=$q.defer(),$qqueue.add(function(_this){return function(){var onError,onSuccess;return onSuccess=function(){return deferred.resolve(),$confirm.notify("success")},onError=function(){return $confirm.notify("error"),_this.us.revert(),_this.render(),deferred.reject()},$repo.save(_this.us).then(onSuccess,onError)}}(this)),deferred.promise},EstimationProcess.prototype.calculateTotalPoints=function(){var notNullValues,values;return values=_.map(this.us.points,function(_this){return function(v,k){var ref;return null!=(ref=_this.pointsById[v])?ref.value:void 0}}(this)),0===values.length?"0":(notNullValues=_.filter(values,function(v){return null!=v}),0===notNullValues.length?"?":_.reduce(notNullValues,function(acc,num){return acc+num}))},EstimationProcess.prototype.calculateRoles=function(){var computableRoles,roles;return computableRoles=_.filter(this.project.roles,"computable"),roles=_.map(computableRoles,function(_this){return function(role){var pointId,pointObj;return pointId=_this.us.points[role.id],pointObj=_this.pointsById[pointId],role=_.clone(role,!0),role.points=null!=pointObj&&null!=pointObj.name?pointObj.name:"?",role}}(this))},EstimationProcess.prototype.bindClickEvents=function(){return this.$el.on("click",".total.clickable",function(_this){return function(event){var roleId,target;return event.preventDefault(),event.stopPropagation(),target=angular.element(event.currentTarget),roleId=target.data("role-id"),_this.renderPointsSelector(roleId,target),target.siblings().removeClass("active"),target.addClass("active")}}(this)),this.$el.on("click",".point",function(_this){return function(event){var pointId,points,roleId,target;return event.preventDefault(),event.stopPropagation(),target=angular.element(event.currentTarget),roleId=target.data("role-id"),pointId=target.data("point-id"),_this.$el.find(".popover").popover().close(),points=_.clone(_this.us.points,!0),points[roleId]=pointId,_this.us.points=points,_this.render(),_this.onSelectedPointForRole(roleId,pointId)}}(this))},EstimationProcess.prototype.renderPointsSelector=function(roleId,target){var horizontalList,html,maxPointLength,points,pop;return points=_.map(this.points,function(_this){return function(point){return point=_.clone(point,!0),point.selected=_this.us.points[roleId]===point.id?!1:!0,point}}(this)),maxPointLength=5,horizontalList=_.some(points,function(_this){return function(point){return point.name.length>maxPointLength}}(this)),html=pointsTemplate({points:points,roleId:roleId,horizontal:horizontalList}),this.$el.find(".popover").popover().close(),this.$el.find(".pop-points-open").remove(),null!=target?this.$el.find(target).append(html):this.$el.append(html),this.$el.find(".pop-points-open").popover().open(function(){return $(this).removeClass("active").closest("li").removeClass("active")}),this.$el.find(".pop-points-open").show(),pop=this.$el.find(".pop-points-open"),pop.offset().top+pop.height()>document.body.clientHeight?pop.addClass("pop-bottom"):void 0},EstimationProcess}(),create=function($el,us,project){var estimationProcess;return $el.unbind("click"),estimationProcess=new EstimationProcess($el,us,project),estimationProcess.isEditable&&estimationProcess.bindClickEvents(),estimationProcess},{create:create}},module.factory("$tgEstimationsService",["$tgTemplate","$tgQqueue","$tgRepo","$tgConfirm","$q",EstimationsService])}.call(this),function(){var defaultFilter,module,momentFormat,momentFromNow,taiga,unslugify,yesNoFilter;taiga=this.taiga,module=angular.module("taigaCommon"),defaultFilter=function(){return function(value,defaultValue){return value===[null,void 0]?defaultValue:value}},module.filter("default",defaultFilter),yesNoFilter=function($translate){return function(value){return value?$translate.instant("COMMON.YES"):$translate.instant("COMMON.NO")}},module.filter("yesNo",["$translate",yesNoFilter]),unslugify=function(){return taiga.unslugify},module.filter("unslugify",unslugify),momentFormat=function(){return function(input,format){return input?moment(input).format(format):""}},module.filter("momentFormat",momentFormat),momentFromNow=function(){return function(input,without_suffix){return input?moment(input).fromNow(without_suffix||!1):""}},module.filter("momentFromNow",momentFromNow)}.call(this),function(){var HistoryController,HistoryDirective,IGNORED_FIELDS,bindOnce,debounce,module,taiga,trim,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,trim=this.taiga.trim,bindOnce=this.taiga.bindOnce,debounce=this.taiga.debounce,module=angular.module("taigaCommon"),IGNORED_FIELDS={"userstories.userstory":["watchers","kanban_order","backlog_order","sprint_order","finish_date","tribe_gig"],"tasks.task":["watchers","us_order","taskboard_order"],"issues.issue":["watchers"]},HistoryController=function(superClass){function HistoryController(scope,repo,rs){this.scope=scope,this.repo=repo,this.rs=rs}return extend(HistoryController,superClass),HistoryController.$inject=["$scope","$tgRepo","$tgResources"],HistoryController.prototype.initialize=function(type,objectId){return this.type=type,this.objectId=objectId},HistoryController.prototype.loadHistory=function(type,objectId){return this.rs.history.get(type,objectId).then(function(_this){return function(history){var changeModel,historyEntry,historyResult,i,j,len,len1;for(i=0,len=history.length;len>i;i++)historyResult=history[i],null!=historyResult.values_diff.description_diff&&(historyResult.values_diff.description=historyResult.values_diff.description_diff),delete historyResult.values_diff.description_html,delete historyResult.values_diff.description_diff,null!=historyResult.values_diff.blocked_note_diff&&(historyResult.values_diff.blocked_note=historyResult.values_diff.blocked_note_diff),delete historyResult.values_diff.blocked_note_html,delete historyResult.values_diff.blocked_note_diff;for(j=0,len1=history.length;len1>j;j++)historyEntry=history[j],changeModel=historyEntry.key.split(":")[0],null!=IGNORED_FIELDS[changeModel]&&(historyEntry.values_diff=_.removeKeys(historyEntry.values_diff,IGNORED_FIELDS[changeModel]));return _this.scope.history=_.filter(history,function(item){return Object.keys(item.values_diff).length>0}),_this.scope.comments=_.filter(history,function(item){return""!==item.comment})}}(this))},HistoryController.prototype.deleteComment=function(type,objectId,activityId){return this.rs.history.deleteComment(type,objectId,activityId).then(function(_this){return function(){return _this.loadHistory(type,objectId)}}(this))},HistoryController.prototype.undeleteComment=function(type,objectId,activityId){return this.rs.history.undeleteComment(type,objectId,activityId).then(function(_this){return function(){return _this.loadHistory(type,objectId)}}(this))},HistoryController}(taiga.Controller),HistoryDirective=function($log,$loading,$qqueue,$template,$confirm,$translate,$compile,$navUrls,$rootScope){var link,templateActivity,templateBase,templateBaseEntries,templateChangeAttachment,templateChangeDiff,templateChangeGeneric,templateChangeList,templateChangePoints,templateDeletedComment,templateFn;return templateChangeDiff=$template.get("common/history/history-change-diff.html",!0),templateChangePoints=$template.get("common/history/history-change-points.html",!0),templateChangeGeneric=$template.get("common/history/history-change-generic.html",!0),templateChangeAttachment=$template.get("common/history/history-change-attachment.html",!0),templateChangeList=$template.get("common/history/history-change-list.html",!0),templateDeletedComment=$template.get("common/history/history-deleted-comment.html",!0),templateActivity=$template.get("common/history/history-activity.html",!0),templateBaseEntries=$template.get("common/history/history-base-entries.html",!0),templateBase=$template.get("common/history/history-base.html",!0),link=function($scope,$el,$attrs,$ctrl){var countChanges,formatChange,getHumanizedFieldName,getPrettyDateFormat,objectId,renderActivity,renderAttachmentEntry,renderChange,renderChangeEntries,renderChangeEntry,renderChangesHelperText,renderComment,renderComments,renderCustomAttributesEntry,renderHistory,save,showAllActivity,showAllComments,type;return type=$attrs.type,objectId=null,showAllComments=!1,showAllActivity=!1,getPrettyDateFormat=function(){return $translate.instant("ACTIVITY.DATETIME")},bindOnce($scope,$attrs.ngModel,function(model){return type=$attrs.type,objectId=model.id,$ctrl.initialize(type,objectId),$ctrl.loadHistory(type,objectId)}),getHumanizedFieldName=function(field){var humanizedFieldNames;return humanizedFieldNames={subject:$translate.instant("ACTIVITY.FIELDS.SUBJECT"),name:$translate.instant("ACTIVITY.FIELDS.NAME"),description:$translate.instant("ACTIVITY.FIELDS.DESCRIPTION"),content:$translate.instant("ACTIVITY.FIELDS.CONTENT"),status:$translate.instant("ACTIVITY.FIELDS.STATUS"),is_closed:$translate.instant("ACTIVITY.FIELDS.IS_CLOSED"),finish_date:$translate.instant("ACTIVITY.FIELDS.FINISH_DATE"),type:$translate.instant("ACTIVITY.FIELDS.TYPE"),priority:$translate.instant("ACTIVITY.FIELDS.PRIORITY"),severity:$translate.instant("ACTIVITY.FIELDS.SEVERITY"),assigned_to:$translate.instant("ACTIVITY.FIELDS.ASSIGNED_TO"),watchers:$translate.instant("ACTIVITY.FIELDS.WATCHERS"),milestone:$translate.instant("ACTIVITY.FIELDS.MILESTONE"),user_story:$translate.instant("ACTIVITY.FIELDS.USER_STORY"),project:$translate.instant("ACTIVITY.FIELDS.PROJECT"),is_blocked:$translate.instant("ACTIVITY.FIELDS.IS_BLOCKED"),blocked_note:$translate.instant("ACTIVITY.FIELDS.BLOCKED_NOTE"),points:$translate.instant("ACTIVITY.FIELDS.POINTS"),client_requirement:$translate.instant("ACTIVITY.FIELDS.CLIENT_REQUIREMENT"),team_requirement:$translate.instant("ACTIVITY.FIELDS.TEAM_REQUIREMENT"),is_iocaine:$translate.instant("ACTIVITY.FIELDS.IS_IOCAINE"),tags:$translate.instant("ACTIVITY.FIELDS.TAGS"),attachments:$translate.instant("ACTIVITY.FIELDS.ATTACHMENTS"),is_deprecated:$translate.instant("ACTIVITY.FIELDS.IS_DEPRECATED"),blocked_note:$translate.instant("ACTIVITY.FIELDS.BLOCKED_NOTE"),is_blocked:$translate.instant("ACTIVITY.FIELDS.IS_BLOCKED"),order:$translate.instant("ACTIVITY.FIELDS.ORDER"),backlog_order:$translate.instant("ACTIVITY.FIELDS.BACKLOG_ORDER"),sprint_order:$translate.instant("ACTIVITY.FIELDS.SPRINT_ORDER"),kanban_order:$translate.instant("ACTIVITY.FIELDS.KANBAN_ORDER"),taskboard_order:$translate.instant("ACTIVITY.FIELDS.TASKBOARD_ORDER"),us_order:$translate.instant("ACTIVITY.FIELDS.US_ORDER")},humanizedFieldNames[field]||field},countChanges=function(comment){return _.keys(comment.values_diff).length},formatChange=function(change){return _.isArray(change)?0===change.length?$translate.instant("ACTIVITY.VALUES.EMPTY"):change.join(", "):""===change?$translate.instant("ACTIVITY.VALUES.EMPTY"):null==change||change===!1?$translate.instant("ACTIVITY.VALUES.NO"):change===!0?$translate.instant("ACTIVITY.VALUES.YES"):change},renderAttachmentEntry=function(value){var attachments;return attachments=_.map(value,function(changes,type){return"new"===type?_.map(changes,function(change){return templateChangeDiff({name:$translate.instant("ACTIVITY.NEW_ATTACHMENT"),diff:change.filename})}):"deleted"===type?_.map(changes,function(change){return templateChangeDiff({name:$translate.instant("ACTIVITY.DELETED_ATTACHMENT"),diff:change.filename})}):_.map(changes,function(change){var diff,name;return name=$translate.instant("ACTIVITY.UPDATED_ATTACHMENT",{filename:change.filename}),diff=_.map(change.changes,function(values,name){return{name:getHumanizedFieldName(name),from:formatChange(values[0]),to:formatChange(values[1])}}),templateChangeAttachment({name:name,diff:diff})})}),_.flatten(attachments).join("\n")},renderCustomAttributesEntry=function(value){var customAttributes;return customAttributes=_.map(value,function(changes,type){return"new"===type?_.map(changes,function(change){var html;return html=templateChangeGeneric({name:change.name,from:formatChange(""),to:formatChange(change.value)}),html=$compile(html)($scope),html[0].outerHTML}):"deleted"===type?_.map(changes,function(change){return templateChangeDiff({name:$translate.instant("ACTIVITY.DELETED_CUSTOM_ATTRIBUTE"),diff:change.name})}):_.map(changes,function(change){var customAttrsChanges;return customAttrsChanges=_.map(change.changes,function(values){return templateChangeGeneric({name:change.name,from:formatChange(values[0]),to:formatChange(values[1])})}),_.flatten(customAttrsChanges).join("\n")})}),_.flatten(customAttributes).join("\n")},renderChangeEntry=function(field,value){var added,from,html,name,removed,to;return"description"===field?templateChangeDiff({name:getHumanizedFieldName("description"),diff:value[1]}):"blocked_note"===field?templateChangeDiff({name:getHumanizedFieldName("blocked_note"),diff:value[1]}):"points"===field?(html=templateChangePoints({points:value}),html=$compile(html)($scope),html[0].outerHTML):"attachments"===field?renderAttachmentEntry(value):"custom_attributes"===field?renderCustomAttributesEntry(value):"tags"===field||"watchers"===field?(name=getHumanizedFieldName(field),removed=_.difference(value[0],value[1]),added=_.difference(value[1],value[0]),html=templateChangeList({name:name,removed:removed,added:added}),html=$compile(html)($scope),html[0].outerHTML):"assigned_to"===field?(name=getHumanizedFieldName(field),from=formatChange(value[0]||$translate.instant("ACTIVITY.VALUES.UNASSIGNED")),to=formatChange(value[1]||$translate.instant("ACTIVITY.VALUES.UNASSIGNED")),templateChangeGeneric({name:name,from:from,to:to})):(name=getHumanizedFieldName(field),from=formatChange(value[0]),to=formatChange(value[1]),templateChangeGeneric({name:name,from:from,to:to}))},renderChangeEntries=function(change){return _.map(change.values_diff,function(value,field){return renderChangeEntry(field,value)})},renderChangesHelperText=function(change){var size;return size=countChanges(change),$translate.instant("ACTIVITY.SIZE_CHANGE",{size:size},"messageformat")},renderComment=function(comment){var html,ref,ref1,ref2;return comment.delete_comment_date||(null!=(ref=comment.delete_comment_user)?ref.name:void 0)?(html=templateDeletedComment({deleteCommentDate:comment.delete_comment_date?moment(comment.delete_comment_date).format(getPrettyDateFormat()):void 0,deleteCommentUser:comment.delete_comment_user.name,deleteComment:comment.comment_html,activityId:comment.id,canRestoreComment:$scope.user&&(comment.delete_comment_user.pk===$scope.user.id||$scope.project.my_permissions.indexOf("modify_project")>-1)}),html=$compile(html)($scope),html[0].outerHTML):(html=templateActivity({avatar:comment.user.photo,userFullName:comment.user.name,userProfileUrl:comment.user.is_active?$navUrls.resolve("user-profile",{username:comment.user.username}):"",creationDate:moment(comment.created_at).format(getPrettyDateFormat()),comment:comment.comment_html,changesText:renderChangesHelperText(comment),changes:renderChangeEntries(comment),mode:"comment",deleteCommentDate:comment.delete_comment_date?moment(comment.delete_comment_date).format(getPrettyDateFormat()):void 0,deleteCommentUser:(null!=(ref1=comment.delete_comment_user)?ref1.name:void 0)?comment.delete_comment_user.name:void 0,activityId:comment.id,canDeleteComment:comment.user.pk===(null!=(ref2=$scope.user)?ref2.id:void 0)||$scope.project.my_permissions.indexOf("modify_project")>-1}),html=$compile(html)($scope),html[0].outerHTML)},renderChange=function(change){var ref;return templateActivity({avatar:change.user.photo,userFullName:change.user.name,userProfileUrl:change.user.is_active?$navUrls.resolve("user-profile",{username:change.user.username}):"",creationDate:moment(change.created_at).format(getPrettyDateFormat()),comment:change.comment_html,changes:renderChangeEntries(change),changesText:"",mode:"activity",deleteCommentDate:change.delete_comment_date?moment(change.delete_comment_date).format(getPrettyDateFormat()):void 0,deleteCommentUser:(null!=(ref=change.delete_comment_user)?ref.name:void 0)?change.delete_comment_user.name:void 0,activityId:change.id})},renderHistory=function(entries,totalEntries){var html,showMore;return showMore=entries.length===totalEntries?0:totalEntries-entries.length,html=templateBaseEntries({entries:entries,showMore:showMore}),html=$compile(html)($scope)},renderComments=function(){var comments,html,totalComments;return comments=$scope.comments||[],totalComments=comments.length,showAllComments||(comments=_.last(comments,4)),comments=_.map(comments,function(x){return renderComment(x)}),html=renderHistory(comments,totalComments),$el.find(".comments-list").html(html)},renderActivity=function(){var changes,html,totalChanges;return changes=$scope.history||[],totalChanges=changes.length,showAllActivity||(changes=_.last(changes,4)),changes=_.map(changes,function(x){return renderChange(x)}),html=renderHistory(changes,totalChanges),$el.find(".changes-list").html(html)},save=$qqueue.bindAdd(function(_this){return function(target){var currentLoading,model,onError,onSuccess;return $scope.$broadcast("markdown-editor:submit"),$el.find(".comment-list").addClass("activeanimation"),currentLoading=$loading().target(target).start(),onSuccess=function(){return $rootScope.$broadcast("comment:new"),$ctrl.loadHistory(type,objectId)["finally"](function(){return currentLoading.finish()})},onError=function(){return currentLoading.finish(),$confirm.notify("error")},model=$scope.$eval($attrs.ngModel),$ctrl.repo.save(model).then(onSuccess,onError)}}(this)),$scope.$watch("comments",renderComments),$scope.$watch("history",renderActivity),$scope.$on("object:updated",function(){return $ctrl.loadHistory(type,objectId)}),$el.on("click",".add-comment button.button-green",debounce(2e3,function(event){var target;return event.preventDefault(),target=angular.element(event.currentTarget),save(target)})),$el.on("click","a",function(event){var href,target;return target=angular.element(event.target),href=target.attr("href"),href&&0===href.indexOf("#")?(event.preventDefault(),$("body").scrollTop($(href).offset().top)):void 0}),$el.on("click",".show-more",function(event){var target;return event.preventDefault(),target=angular.element(event.currentTarget),target.parent().is(".changes-list")?(showAllActivity=!showAllActivity,renderActivity()):(showAllComments=!showAllComments,renderComments())}),$el.on("click",".show-deleted-comment",function(event){var target;return event.preventDefault(),target=angular.element(event.currentTarget),target.parents(".activity-single").find(".hide-deleted-comment").show(),target.parents(".activity-single").find(".show-deleted-comment").hide(),target.parents(".activity-single").find(".comment-body").show()}),$el.on("click",".hide-deleted-comment",function(event){var target;return event.preventDefault(),target=angular.element(event.currentTarget),target.parents(".activity-single").find(".hide-deleted-comment").hide(),target.parents(".activity-single").find(".show-deleted-comment").show(),target.parents(".activity-single").find(".comment-body").hide()}),$el.on("click",".changes-title",function(event){var target;return event.preventDefault(),target=angular.element(event.currentTarget),target.parent().find(".change-entry").toggleClass("active")}),$el.on("focus",".add-comment textarea",function(event){return $(this).addClass("active")}),$el.on("click",".history-tabs li a",function(event){var target;return target=angular.element(event.currentTarget),$el.find(".history-tabs li a").removeClass("active"),target.addClass("active"),$el.find(".history section").addClass("hidden"),$el.find(".history section."+target.data("section-class")).removeClass("hidden")}),$el.on("click",".comment-delete",debounce(2e3,function(event){var activityId,target;return event.preventDefault(),target=angular.element(event.currentTarget),activityId=target.data("activity-id"),$ctrl.deleteComment(type,objectId,activityId)})),$el.on("click",".comment-restore",debounce(2e3,function(event){var activityId,target;return event.preventDefault(),target=angular.element(event.currentTarget),activityId=target.data("activity-id"),$ctrl.undeleteComment(type,objectId,activityId)})),$scope.$on("$destroy",function(){return $el.off()})},templateFn=function($el,$attrs){var html;return html=templateBase({ngmodel:$attrs.ngModel,type:$attrs.type,mode:$attrs.mode})},{controller:HistoryController,template:templateFn,restrict:"AE",link:link}},module.directive("tgHistory",["$log","$tgLoading","$tgQqueue","$tgTemplate","$tgConfirm","$translate","$compile","$tgNavUrls","$rootScope",HistoryDirective])}.call(this),function(){var ImportProjectButtonDirective,module;module=angular.module("taigaCommon"),ImportProjectButtonDirective=function($rs,$confirm,$location,$navUrls,$translate){var link;return link=function($scope,$el,$attrs){return $el.on("click",".import-project-button",function(event){return event.preventDefault(),$el.find("input.import-file").val(""),$el.find("input.import-file").trigger("click")}),$el.on("change","input.import-file",function(event){var file,loader,onError,onSuccess;return event.preventDefault(),(file=event.target.files[0])?(loader=$confirm.loader($translate.instant("PROJECT.IMPORT.UPLOADING_FILE")),onSuccess=function(result){var ctx,message,msg,title;return loader.stop(),202===result.status?(title=$translate.instant("PROJECT.IMPORT.ASYNC_IN_PROGRESS_TITLE"),message=$translate.instant("PROJECT.IMPORT.ASYNC_IN_PROGRESS_MESSAGE"),$confirm.success(title,message)):(ctx={project:result.data.slug},$location.path($navUrls.resolve("project-admin-project-profile-details",ctx)),msg=$translate.instant("PROJECT.IMPORT.SYNC_SUCCESS"),$confirm.notify("success",msg))},onError=function(result){var errorMsg,ref;return loader.stop(),errorMsg=$translate.instant("PROJECT.IMPORT.ERROR"),429===result.status?errorMsg=$translate.instant("PROJECT.IMPORT.ERROR_TOO_MANY_REQUEST"):(null!=(ref=result.data)?ref._error_message:void 0)&&(errorMsg=$translate.instant("PROJECT.IMPORT.ERROR_MESSAGE",{error_message:result.data._error_message})),$confirm.notify("error",errorMsg)},loader.start(),$rs.projects["import"](file,loader.update).then(onSuccess,onError)):void 0})},{link:link}},module.directive("tgImportProjectButton",["$tgResources","$tgConfirm","$location","$tgNavUrls","$translate",ImportProjectButtonDirective])}.call(this),function(){var AssignedToLightboxDirective,AttachmentPreviewLightboxDirective,BlockLightboxDirective,BlockingMessageInputDirective,CreateBulkUserstoriesDirective,CreateEditUserstoryDirective,LightboxDirective,LightboxKeyboardNavigationService,LightboxService,WatchersLightboxDirective,bindOnce,debounce,module,timeout,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;module=angular.module("taigaCommon"),bindOnce=this.taiga.bindOnce,timeout=this.taiga.timeout,debounce=this.taiga.debounce,LightboxService=function(superClass){function LightboxService(animationFrame,q){this.animationFrame=animationFrame,this.q=q}return extend(LightboxService,superClass),LightboxService.prototype.open=function($el){var defered,docEl,lightboxContent;return defered=this.q.defer(),lightboxContent=$el.children().not(".close"),lightboxContent.hide(),this.animationFrame.add(function(){return $el.css("display","flex")}),this.animationFrame.add(function(){return $el.addClass("open"),$el.one("transitionend",function(_this){return function(){return $el.find("input,textarea").first().focus()}}(this))}),this.animationFrame.add(function(_this){return function(){return lightboxContent.show(),defered.resolve()}}(this)),docEl=angular.element(document),docEl.on("keydown.lightbox",function(_this){return function(e){var code;return code=e.keyCode?e.keyCode:e.which,27===code?_this.close($el):void 0}}(this)),defered.promise},LightboxService.prototype.close=function($el){var docEl,scope;return docEl=angular.element(document),docEl.off(".lightbox"),docEl.off(".keyboard-navigation"),$el.one("transitionend",function(_this){return function(){return $el.removeAttr("style"),$el.removeClass("open").removeClass("close")}}(this)),$el.addClass("close"),$el.hasClass("remove-on-close")?(scope=$el.data("scope"),scope.$destroy(),$el.remove()):void 0},LightboxService.prototype.closeAll=function(){var docEl,i,len,lightboxEl,ref,results;for(docEl=angular.element(document),ref=docEl.find(".lightbox.open"),results=[],i=0,len=ref.length;len>i;i++)lightboxEl=ref[i],results.push(this.close($(lightboxEl)));return results},LightboxService}(taiga.Service),module.service("lightboxService",["animationFrame","$q",LightboxService]),LightboxKeyboardNavigationService=function(superClass){function LightboxKeyboardNavigationService(){return LightboxKeyboardNavigationService.__super__.constructor.apply(this,arguments)}return extend(LightboxKeyboardNavigationService,superClass),LightboxKeyboardNavigationService.prototype.stop=function(){var docEl;return docEl=angular.element(document),docEl.off(".keyboard-navigation")},LightboxKeyboardNavigationService.prototype.dispatch=function($el,code){var activeElement,next,prev;if(activeElement=$el.find(".selected"),13===code)return 1===$el.find(".user-list-single").length?$el.find(".user-list-single:first").trigger("click"):activeElement.trigger("click");if(40===code){if(!activeElement.length)return $el.find('.user-list-single:not(".is-active"):first').addClass("selected");if(next=activeElement.next(".user-list-single"),next.length)return activeElement.removeClass("selected"),next.addClass("selected"); -}else if(38===code){if(!activeElement.length)return $el.find(".user-list-single:last").addClass("selected");if(prev=activeElement.prev('.user-list-single:not(".is-active")'),prev.length)return activeElement.removeClass("selected"),prev.addClass("selected")}},LightboxKeyboardNavigationService.prototype.init=function($el){var docEl;return this.stop(),docEl=angular.element(document),docEl.on("keydown.keyboard-navigation",function(_this){return function(event){var code;return code=event.keyCode?event.keyCode:event.which,40===code||38===code||13===code?(event.preventDefault(),_this.dispatch($el,code)):void 0}}(this))},LightboxKeyboardNavigationService}(taiga.Service),module.service("lightboxKeyboardNavigationService",LightboxKeyboardNavigationService),LightboxDirective=function(lightboxService){var link;return link=function($scope,$el,$attrs){return $el.on("click",".close",function(event){return event.preventDefault(),lightboxService.close($el)})},{restrict:"C",link:link}},module.directive("lightbox",["lightboxService",LightboxDirective]),BlockLightboxDirective=function($rootscope,$tgrepo,$confirm,lightboxService,$loading,$qqueue,$translate){var link;return link=function($scope,$el,$attrs,$model){var block,title,unblock;return title=$translate.instant($attrs.title),$el.find("h2.title").text(title),unblock=$qqueue.bindAdd(function(_this){return function(item,finishCallback){var promise;return promise=$tgrepo.save(item),promise.then(function(){return $confirm.notify("success"),$rootscope.$broadcast("object:updated"),$model.$setViewValue(item),finishCallback()}),promise.then(null,function(){return $confirm.notify("error"),item.revert(),$model.$setViewValue(item)}),promise["finally"](function(){return finishCallback()}),promise}}(this)),block=$qqueue.bindAdd(function(_this){return function(item){var currentLoading,promise;return $model.$setViewValue(item),currentLoading=$loading().target($el.find(".button-green")).start(),promise=$tgrepo.save($model.$modelValue),promise.then(function(){return $confirm.notify("success"),$rootscope.$broadcast("object:updated")}),promise.then(null,function(){return $confirm.notify("error"),item.revert(),$model.$setViewValue(item)}),promise["finally"](function(){return currentLoading.finish(),lightboxService.close($el)})}}(this)),$scope.$on("block",function(){return $el.find(".reason").val($model.$modelValue.blocked_note),lightboxService.open($el)}),$scope.$on("unblock",function(_this){return function(event,model,finishCallback){var item;return item=$model.$modelValue.clone(),item.is_blocked=!1,item.blocked_note="",unblock(item,finishCallback)}}(this)),$scope.$on("$destroy",function(){return $el.off()}),$el.on("click",".button-green",function(event){var item;return event.preventDefault(),item=$model.$modelValue.clone(),item.is_blocked=!0,item.blocked_note=$el.find(".reason").val(),block(item)})},{templateUrl:"common/lightbox/lightbox-block.html",link:link,require:"ngModel"}},module.directive("tgLbBlock",["$rootScope","$tgRepo","$tgConfirm","lightboxService","$tgLoading","$tgQqueue","$translate",BlockLightboxDirective]),BlockingMessageInputDirective=function($log,$template,$compile){var link,template,templateFn;return template=$template.get("common/lightbox/lightbox-blocking-message-input.html",!0),link=function($scope,$el,$attrs,$model){return $attrs.watch?$scope.$watch($attrs.watch,function(value){return value===!0&&value===!0?$el.find(".blocked-note").removeClass("hidden"):$el.find(".blocked-note").addClass("hidden")}):$log.error("No watch attribute on tg-blocking-message-input directive")},templateFn=function($el,$attrs){return template({ngmodel:$attrs.ngModel})},{template:templateFn,link:link,require:"ngModel",restrict:"EA"}},module.directive("tgBlockingMessageInput",["$log","$tgTemplate","$compile",BlockingMessageInputDirective]),CreateEditUserstoryDirective=function($repo,$model,$rs,$rootScope,lightboxService,$loading,$translate){var link;return link=function($scope,$el,attrs){var submit,submitButton;return $scope.isNew=!0,$scope.$on("usform:new",function(ctx,projectId,status,statusList){return $scope.isNew=!0,$scope.usStatusList=statusList,$scope.us=$model.make_model("userstories",{project:projectId,points:{},status:status,is_archived:!1,tags:[]}),$el.find(".button-green").html($translate.instant("COMMON.CREATE")),$el.find(".title").html($translate.instant("LIGHTBOX.CREATE_EDIT_US.NEW_US")),$el.find(".tag-input").val(""),$el.find(".blocked-note").addClass("hidden"),$el.find("label.blocked").removeClass("selected"),$el.find("label.team-requirement").removeClass("selected"),$el.find("label.client-requirement").removeClass("selected"),lightboxService.open($el)}),$scope.$on("usform:edit",function(ctx,us){return $scope.us=us,$scope.isNew=!1,$el.find(".button-green").html($translate.instant("COMMON.SAVE")),$el.find(".title").html($translate.instant("LIGHTBOX.CREATE_EDIT_US.EDIT_US")),$el.find(".tag-input").val(""),us.is_blocked?($el.find(".blocked-note").removeClass("hidden"),$el.find("label.blocked").addClass("selected")):($el.find(".blocked-note").addClass("hidden"),$el.find("label.blocked").removeClass("selected")),us.team_requirement?$el.find("label.team-requirement").addClass("selected"):$el.find("label.team-requirement").removeClass("selected"),us.client_requirement?$el.find("label.client-requirement").addClass("selected"):$el.find("label.client-requirement").removeClass("selected"),lightboxService.open($el)}),submit=debounce(2e3,function(_this){return function(event){var broadcastEvent,currentLoading,form,promise;return event.preventDefault(),form=$el.find("form").checksley(),form.validate()?(currentLoading=$loading().target(submitButton).start(),$scope.isNew?(promise=$repo.create("userstories",$scope.us),broadcastEvent="usform:new:success"):(promise=$repo.save($scope.us),broadcastEvent="usform:edit:success"),promise.then(function(data){return currentLoading.finish(),lightboxService.close($el),$rootScope.$broadcast(broadcastEvent,data)}),promise.then(null,function(data){return currentLoading.finish(),form.setErrors(data),data._error_message?$confirm.notify("error",data._error_message):void 0})):void 0}}(this)),submitButton=$el.find(".submit-button"),$el.on("submit","form",submit),$el.on("click",".close",function(event){return event.preventDefault(),$scope.$apply(function(){return $scope.us.revert()}),lightboxService.close($el)}),$el.keydown(function(event){var code;return code=event.keyCode?event.keyCode:event.which,27===code?(lightboxService.close($el),$scope.$apply(function(){return $scope.us.revert()})):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgLbCreateEditUserstory",["$tgRepo","$tgModel","$tgResources","$rootScope","lightboxService","$tgLoading","$translate",CreateEditUserstoryDirective]),CreateBulkUserstoriesDirective=function($repo,$rs,$rootscope,lightboxService,$loading){var link;return link=function($scope,$el,attrs){var submit,submitButton;return $scope.$on("usform:bulk",function(ctx,projectId,status){return $scope["new"]={projectId:projectId,statusId:status,bulk:""},lightboxService.open($el)}),submit=debounce(2e3,function(_this){return function(event){var currentLoading,form,promise;return event.preventDefault(),form=$el.find("form").checksley({onlyOneErrorElement:!0}),form.validate()?(currentLoading=$loading().target(submitButton).start(),promise=$rs.userstories.bulkCreate($scope["new"].projectId,$scope["new"].statusId,$scope["new"].bulk),promise.then(function(result){return currentLoading.finish(),$rootscope.$broadcast("usform:bulk:success",result),lightboxService.close($el)}),promise.then(null,function(data){return currentLoading.finish(),form.setErrors(data),data._error_message?$confirm.notify("error",data._error_message):void 0})):void 0}}(this)),submitButton=$el.find(".submit-button"),$el.on("submit","form",submit),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgLbCreateBulkUserstories",["$tgRepo","$tgResources","$rootScope","lightboxService","$tgLoading",CreateBulkUserstoriesDirective]),AssignedToLightboxDirective=function(lightboxService,lightboxKeyboardNavigationService,$template,$compile){var link;return link=function($scope,$el,$attrs){var closeLightbox,filterUsers,normalizeString,render,selectedItem,selectedUser,usersTemplate;return selectedUser=null,selectedItem=null,usersTemplate=$template.get("common/lightbox/lightbox-assigned-to-users.html",!0),normalizeString=function(string){var normalizedString;return normalizedString=string,normalizedString=normalizedString.replace("Á","A").replace("Ä","A").replace("À","A"),normalizedString=normalizedString.replace("É","E").replace("Ë","E").replace("È","E"),normalizedString=normalizedString.replace("Í","I").replace("Ï","I").replace("Ì","I"),normalizedString=normalizedString.replace("Ó","O").replace("Ö","O").replace("Ò","O"),normalizedString=normalizedString.replace("Ú","U").replace("Ü","U").replace("Ù","U")},filterUsers=function(text,user){var username;return username=user.full_name_display.toUpperCase(),username=normalizeString(username),text=text.toUpperCase(),text=normalizeString(text),_.contains(username,text)},render=function(selected,text){var ctx,html,users;return users=_.clone($scope.activeUsers,!0),null!=selected&&(users=_.reject(users,{id:selected.id})),null!=text&&(users=_.filter(users,_.partial(filterUsers,text))),ctx={selected:selected,users:_.first(users,5),showMore:users.length>5},html=usersTemplate(ctx),html=$compile(html)($scope),$el.find(".assigned-to-list").html(html)},closeLightbox=function(){return lightboxKeyboardNavigationService.stop(),lightboxService.close($el)},$scope.$on("assigned-to:add",function(ctx,item){var assignedToId;return selectedItem=item,assignedToId=item.assigned_to,selectedUser=$scope.usersById[assignedToId],render(selectedUser),lightboxService.open($el).then(function(){return $el.find("input").focus(),lightboxKeyboardNavigationService.init($el)})}),$scope.$watch("usersSearch",function(searchingText){return null!=searchingText?(render(selectedUser,searchingText),$el.find("input").focus()):void 0}),$el.on("click",".user-list-single",function(event){var target;return event.preventDefault(),target=angular.element(event.currentTarget),closeLightbox(),$scope.$apply(function(){return $scope.$broadcast("assigned-to:added",target.data("user-id"),selectedItem),$scope.usersSearch=null})}),$el.on("click",".remove-assigned-to",function(event){return event.preventDefault(),event.stopPropagation(),closeLightbox(),$scope.$apply(function(){return $scope.usersSearch=null,$scope.$broadcast("assigned-to:added",null,selectedItem)})}),$el.on("click",".close",function(event){return event.preventDefault(),closeLightbox(),$scope.$apply(function(){return $scope.usersSearch=null})}),$scope.$on("$destroy",function(){return $el.off()})},{templateUrl:"common/lightbox/lightbox-assigned-to.html",link:link}},module.directive("tgLbAssignedto",["lightboxService","lightboxKeyboardNavigationService","$tgTemplate","$compile",AssignedToLightboxDirective]),WatchersLightboxDirective=function($repo,lightboxService,lightboxKeyboardNavigationService,$template,$compile){var link;return link=function($scope,$el,$attrs){var closeLightbox,getFilteredUsers,render,selectedItem,usersTemplate;return selectedItem=null,usersTemplate=$template.get("common/lightbox/lightbox-assigned-to-users.html",!0),getFilteredUsers=function(text){var _filterUsers,users;return null==text&&(text=""),_filterUsers=function(text,user){var username;return selectedItem&&_.find(selectedItem.watchers,function(x){return x===user.id})?!1:(username=user.full_name_display.toUpperCase(),text=text.toUpperCase(),_.contains(username,text))},users=_.clone($scope.activeUsers,!0),users=_.filter(users,_.partial(_filterUsers,text))},render=function(users){var ctx,html;return ctx={selected:!1,users:_.first(users,5),showMore:users.length>5},html=usersTemplate(ctx),html=$compile(html)($scope),$el.find(".ticket-watchers").html(html)},closeLightbox=function(){return lightboxKeyboardNavigationService.stop(),lightboxService.close($el)},$scope.$on("watcher:add",function(ctx,item){var users;return selectedItem=item,users=getFilteredUsers(),render(users),lightboxService.open($el).then(function(){return $el.find("input").focus(),lightboxKeyboardNavigationService.init($el)})}),$scope.$watch("usersSearch",function(searchingText){var users;if(null!=searchingText)return users=getFilteredUsers(searchingText),render(users),$el.find("input").focus()}),$el.on("click",".user-list-single",debounce(2e3,function(event){var target;return closeLightbox(),event.preventDefault(),target=angular.element(event.currentTarget),$scope.$apply(function(){return $scope.usersSearch=null,$scope.$broadcast("watcher:added",target.data("user-id"))})})),$el.on("click",".close",function(event){return event.preventDefault(),closeLightbox(),$scope.$apply(function(){return $scope.usersSearch=null})}),$scope.$on("$destroy",function(){return $el.off()})},{templateUrl:"common/lightbox/lightbox-users.html",link:link}},module.directive("tgLbWatchers",["$tgRepo","lightboxService","lightboxKeyboardNavigationService","$tgTemplate","$compile",WatchersLightboxDirective]),AttachmentPreviewLightboxDirective=function($repo,lightboxService,lightboxKeyboardNavigationService,$template,$compile){var link;return link=function($scope,$el,attrs){var render,template;return template=$template.get("common/lightbox/lightbox-attachment-preview.html",!0),$scope.$on("attachment:preview",function(event,attachment){return lightboxService.open($el),render(attachment)}),$scope.$on("$destroy",function(){return $el.off()}),render=function(attachment){var ctx,html;return ctx={url:attachment.url,title:attachment.description,name:attachment.name},html=template(ctx),html=$compile(html)($scope),$el.html(html)}},{link:link}},module.directive("tgLbAttachmentPreview",["$tgRepo","lightboxService","lightboxKeyboardNavigationService","$tgTemplate","$compile",AttachmentPreviewLightboxDirective])}.call(this),function(){var Loader,LoaderDirective,module,sizeFormat,taiga,timeout;taiga=this.taiga,sizeFormat=this.taiga.sizeFormat,timeout=this.taiga.timeout,module=angular.module("taigaCommon"),LoaderDirective=function(tgLoader,$rootscope){var link;return link=function($scope,$el,$attrs){return tgLoader.onStart(function(){return $(document.body).addClass("loader-active"),$el.addClass("active")}),tgLoader.onEnd(function(){return $(document.body).removeClass("loader-active"),$el.removeClass("active")})},{link:link}},module.directive("tgLoader",["tgLoader","$rootScope",LoaderDirective]),Loader=function($rootscope){var autoClose,config,lastResponseDate,open,pageLoaded,requestCount,start,startLoadTime;return config={minTime:300},open=!1,startLoadTime=0,requestCount=0,lastResponseDate=0,pageLoaded=function(force){var diff,endTime,timeoutValue;return null==force&&(force=!1),startLoadTime&&(timeoutValue=0,force||(endTime=(new Date).getTime(),diff=endTime-startLoadTime,diff",function(){var service;return service={settings:{target:null,scope:null,classes:[],timeout:0,template:null},target:function(target){return service.settings.target=target,service},scope:function(scope){return service.settings.scope=scope,service},template:function(template){return service.settings.template=template,service},removeClasses:function(){var classess;return classess=1<=arguments.length?slice.call(arguments,0):[],service.settings.classes=classess,service},timeout:function(timeout){return service.settings.timeout=timeout,service},start:function(){var target,timeoutId;return target=service.settings.target,service.settings.classes.map(function(className){return target.removeClass(className)}),timeoutId=setTimeout(function(){return target.hasClass("loading")?void 0:(service.settings.template||(service.settings.template=target.html()),target.addClass("loading"),target.html(spinner))},service.settings.timeout),service.settings.timeoutId=timeoutId,service},finish:function(){var removeClasses,target,timeoutId;return target=service.settings.target,timeoutId=service.settings.timeoutId,timeoutId&&(clearTimeout(timeoutId),removeClasses=service.settings.classes,removeClasses.map(function(className){return service.settings.target.addClass(className)}),target.html(service.settings.template),target.removeClass("loading"),service.settings.scope&&$compile(target.contents())(service.settings.scope)),service}}}},TgLoadingService.$inject=["$compile"],module.factory("$tgLoading",TgLoadingService),LoadingDirective=function($loading){var link;return link=function($scope,$el,attr){var currentLoading,template;return currentLoading=null,template=$el.html(),$scope.$watch(attr.tgLoading,function(_this){return function(showLoading){return showLoading?currentLoading=$loading().target($el).timeout(50).template(template).scope($scope).start():currentLoading?currentLoading.finish():void 0}}(this))},{link:link}},module.directive("tgLoading",["$tgLoading",LoadingDirective])}.call(this),function(){var RelatedTaskStatusDirective,UsStatusDirective,bindOnce,debounce,module,taiga;taiga=this.taiga,bindOnce=this.taiga.bindOnce,debounce=this.taiga.debounce,module=angular.module("taigaCommon"),UsStatusDirective=function($repo,$template){var link,template;return template=$template.get("common/popover/popover-us-status.html",!0),link=function($scope,$el,$attrs){var $ctrl,render,us;return $ctrl=$el.controller(),render=function(us){var usStatusById,usStatusDom,usStatusDomParent;return usStatusDomParent=$el.find(".us-status"),usStatusDom=$el.find(".us-status .us-status-bind"),usStatusById=$scope.usStatusById,usStatusById[us.status]?(usStatusDom.text(usStatusById[us.status].name),usStatusDomParent.css("color",usStatusById[us.status].color)):void 0},$el.on("click",".us-status",function(event){return event.preventDefault(),event.stopPropagation(),$el.find(".pop-status").popover().open()}),$el.on("click",".status",debounce(2e3,function(event){var target,us;return event.preventDefault(),event.stopPropagation(),target=angular.element(event.currentTarget),us=$scope.$eval($attrs.tgUsStatus),us.status=target.data("status-id"),render(us),$el.find(".pop-status").popover().close(),$scope.$apply(function(){return $repo.save(us).then(function(){return $scope.$eval($attrs.onUpdate)})})})),$scope.$on("userstories:loaded",function(){return render($scope.$eval($attrs.tgUsStatus))}),$scope.$on("$destroy",function(){return $el.off()}),us=$scope.$eval($attrs.tgUsStatus),render(us),bindOnce($scope,"project",function(project){var html;return html=template({statuses:project.us_statuses}),$el.append(html),-1===$scope.project.my_permissions.indexOf("modify_us")?($el.unbind("click"),$el.find("a").addClass("not-clickable")):void 0})},{link:link}},module.directive("tgUsStatus",["$tgRepo","$tgTemplate",UsStatusDirective]),RelatedTaskStatusDirective=function($repo,$template){var link,selectionTemplate,updateTaskStatus;return selectionTemplate=$template.get("common/popover/popover-related-task-status.html",!0),updateTaskStatus=function($el,task,taskStatusById){var taskStatusDom,taskStatusDomParent;return taskStatusDomParent=$el.find(".us-status"),taskStatusDom=$el.find(".task-status .task-status-bind"),taskStatusById[task.status]?(taskStatusDom.text(taskStatusById[task.status].name),taskStatusDomParent.css("color",taskStatusById[task.status].color)):void 0},link=function($scope,$el,$attrs){var $ctrl,autoSave,notAutoSave,task;return $ctrl=$el.controller(),task=$scope.$eval($attrs.tgRelatedTaskStatus),notAutoSave=$scope.$eval($attrs.notAutoSave),autoSave=!notAutoSave,$el.on("click",".task-status",function(event){return event.preventDefault(),event.stopPropagation(),$el.find(".pop-status").popover().open()}),$el.on("click",".status",debounce(2e3,function(event){var target;return event.preventDefault(),event.stopPropagation(),target=angular.element(event.currentTarget),task.status=target.data("status-id"),$el.find(".pop-status").popover().close(),updateTaskStatus($el,task,$scope.taskStatusById),autoSave?$scope.$apply(function(){return $repo.save(task).then(function(){return $scope.$eval($attrs.onUpdate),$scope.$emit("related-tasks:status-changed")})}):void 0})),taiga.bindOnce($scope,"project",function(project){return $el.append(selectionTemplate({statuses:project.task_statuses})),updateTaskStatus($el,task,$scope.taskStatusById),-1===project.my_permissions.indexOf("modify_task")?($el.unbind("click"),$el.find("a").addClass("not-clickable")):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgRelatedTaskStatus",["$tgRepo","$tgTemplate",RelatedTaskStatusDirective]),$.fn.popover=function(){var $el,close,closeAll,closePopover,isVisible,open;return $el=this,isVisible=function(_this){return function(){var docViewBottom,docViewLeft,docViewRight,docViewTop,docViewWidth,elemBottom,elemLeft,elemRight,elemTop,elemWidth;return $el.css({display:"block",visibility:"hidden"}),docViewTop=$(window).scrollTop(),docViewBottom=docViewTop+$(window).height(),docViewWidth=$(window).width(),docViewRight=docViewWidth,docViewLeft=0,elemTop=$el.offset().top,elemBottom=elemTop+$el.height(),elemWidth=$el.width(),elemLeft=$el.offset().left,elemRight=$el.offset().left+elemWidth,$el.css({display:"none",visibility:"visible"}),docViewBottom>=elemBottom&&elemTop>=docViewTop&&elemLeft>=docViewLeft&&docViewRight>=elemRight}}(this),closePopover=function(_this){return function(onClose){return onClose&&onClose.call($el),$el.fadeOut(function(){return $el.removeClass("active").removeClass("fix")}),$el.off("popup:close")}}(this),closeAll=function(_this){return function(){return $(".popover.active").each(function(){return $(this).trigger("popup:close")})}}(this),open=function(_this){return function(onClose){return $el.hasClass("active")?close():(closeAll(),isVisible()||$el.addClass("fix"),$el.fadeIn(function(){return $el.addClass("active"),$(document.body).off("popover"),$(document.body).one("click.popover",function(){return closeAll()})}),$el.on("popup:close",function(e){return closePopover(onClose)}))}}(this),close=function(_this){return function(){return $el.trigger("popup:close")}}(this),{open:open,close:close,closeAll:closeAll}}}.call(this),function(){var ExceptionHandlerFactory,module,taiga;taiga=this.taiga,module=angular.module("taigaCommon"),ExceptionHandlerFactory=function($log,config){var ravenConfig;return this.config=config,ravenConfig=this.config.get("ravenConfig",null),ravenConfig?($log.debug("Using the RavenJS exception handler."),Raven.config(ravenConfig).install(),function(exception,cause){return $log.error.apply($log,arguments),Raven.captureException(exception)}):($log.debug("Using the default logging exception handler."),function(exception,cause){return $log.error.apply($log,arguments)})},module.factory("$exceptionHandler",["$log","$tgConfig",ExceptionHandlerFactory])}.call(this),function(){var ColorizeTagsDirective,LbTagLineDirective,TagLineDirective,TagsDirective,bindOnce,module,taiga,trim,indexOf=[].indexOf||function(item){for(var i=0,l=this.length;l>i;i++)if(i in this&&this[i]===item)return i;return-1};taiga=this.taiga,trim=this.taiga.trim,bindOnce=this.taiga.bindOnce,module=angular.module("taigaCommon"),TagsDirective=function(){var formatter,link,parser;return formatter=function(v){return _.isArray(v)?v.join(", "):""},parser=function(v){var result;return v?(result=_(v.split(",")).map(function(x){return _.str.trim(x)}),result.value()):[]},link=function($scope,$el,$attrs,$ctrl){return $ctrl.$formatters.push(formatter),$ctrl.$parsers.push(parser),$scope.$on("$destroy",function(){return $el.off()})},{require:"ngModel",link:link}},module.directive("tgTags",TagsDirective),ColorizeTagsDirective=function(){var link,templates;return templates={backlog:_.template('<% _.each(tags, function(tag) { %>\n <%- tag.name %>\n<% }) %>'),kanban:_.template('<% _.each(tags, function(tag) { %>\n \n<% }) %>'),taskboard:_.template('<% _.each(tags, function(tag) { %>\n \n<% }) %>')},link=function($scope,$el,$attrs,$ctrl){var render;return render=function(srcTags){var html,tags,template;return template=templates[$attrs.tgColorizeTagsType],srcTags.sort(),tags=_.map(srcTags,function(tag){var color;return color=$scope.project.tags_colors[tag],{name:tag,color:color}}),html=template({tags:tags}),$el.html(html)},$scope.$watch($attrs.tgColorizeTags,function(tags){return null!=tags?render(tags):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgColorizeTags",ColorizeTagsDirective),LbTagLineDirective=function($rs,$template,$compile){var COMMA_KEY,ENTER_KEY,link,templateTags;return ENTER_KEY=13,COMMA_KEY=188,templateTags=$template.get("common/tag/lb-tag-line-tags.html",!0),link=function($scope,$el,$attrs,$model){var addValue,deleteValue,hideSaveButton,removeInputLastCharacter,renderTags,resetInput,saveInputTag,showSaveButton;return renderTags=function(tags,tagsColors){var ctx,html;return ctx={tags:_.map(tags,function(t){return{name:t,color:tagsColors[t]}})},_.map(ctx.tags,function(_this){return function(tag){return tag.color?tag.style="border-left: 5px solid "+tag.color:void 0}}(this)),html=$compile(templateTags(ctx))($scope),$el.find("div.tags-container").html(html)},showSaveButton=function(){return $el.find(".save").removeClass("hidden")},hideSaveButton=function(){return $el.find(".save").addClass("hidden")},resetInput=function(){return $el.find("input").val(""),$el.find("input").autocomplete("close")},addValue=function(value){var tags;return value=trim(value.toLowerCase()),0!==value.length?(tags=_.clone($model.$modelValue,!1),null==tags&&(tags=[]),indexOf.call(tags,value)<0&&tags.push(value),$scope.$apply(function(){return $model.$setViewValue(tags)}),hideSaveButton()):void 0},deleteValue=function(value){var tags;return value=trim(value.toLowerCase()),0!==value.length?(tags=_.clone($model.$modelValue,!1),tags=_.pull(tags,value),$scope.$apply(function(){return $model.$setViewValue(tags)})):void 0},saveInputTag=function(){var value;return value=$el.find("input").val(),addValue(value),resetInput()},removeInputLastCharacter=function(_this){return function(input){var inputValue;return inputValue=input.val(),input.val(inputValue.substring(0,inputValue.length-1))}}(this),$el.on("keypress","input",function(event){return event.keyCode===ENTER_KEY?event.preventDefault():void 0}),$el.on("keyup","input",function(event){var target;return target=angular.element(event.currentTarget),event.keyCode===ENTER_KEY?saveInputTag():event.keyCode===COMMA_KEY?(removeInputLastCharacter(target),saveInputTag()):target.val().length?showSaveButton():hideSaveButton()}),$el.on("click",".save",function(event){return event.preventDefault(),saveInputTag()}),$el.on("click",".icon-delete",function(event){var target,value;return event.preventDefault(),target=angular.element(event.currentTarget),value=target.siblings(".tag-name").text(),deleteValue(value)}),bindOnce($scope,"project",function(project){var positioningFunction;return positioningFunction=function(position,elements){var menu;return menu=elements.element.element,menu.css("width",elements.target.width),menu.css("top",position.top),menu.css("left",position.left)},$el.find("input").autocomplete({source:_.keys(project.tags_colors),position:{my:"left top",using:positioningFunction},select:function(event,ui){return addValue(ui.item.value),ui.item.value=""}})}),$scope.$watch($attrs.ngModel,function(tags){var ref,tagsColors;return tagsColors=(null!=(ref=$scope.project)?ref.tags_colors:void 0)||[],renderTags(tags,tagsColors)}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,require:"ngModel",templateUrl:"common/tag/lb-tag-line.html"}},module.directive("tgLbTagLine",["$tgResources","$tgTemplate","$compile",LbTagLineDirective]),TagLineDirective=function($rootScope,$repo,$rs,$confirm,$qqueue,$template,$compile){var COMMA_KEY,ENTER_KEY,ESC_KEY,link,templateTags;return ENTER_KEY=13,ESC_KEY=27,COMMA_KEY=188,templateTags=$template.get("common/tag/tags-line-tags.html",!0),link=function($scope,$el,$attrs,$model){var addValue,deleteValue,hideAddTagButton,hideAddTagButtonText,hideInput,hideSaveButton,isEditable,removeInputLastCharacter,renderInReadModeOnly,renderTags,resetInput,saveInputTag,showAddTagButton,showAddTagButtonText,showInput,showSaveButton;return isEditable=function(){return null!=$attrs.requiredPerm?-1!==$scope.project.my_permissions.indexOf($attrs.requiredPerm):!0},renderTags=function(tags,tagsColors){var ctx,html;return ctx={tags:_.map(tags,function(t){return{name:t,color:tagsColors[t]}}),isEditable:isEditable()},html=$compile(templateTags(ctx))($scope),$el.find("div.tags-container").html(html)},renderInReadModeOnly=function(){return $el.find(".add-tag").remove(),$el.find("input").remove(),$el.find(".save").remove()},showAddTagButton=function(){return $el.find(".add-tag").removeClass("hidden")},hideAddTagButton=function(){return $el.find(".add-tag").addClass("hidden")},showAddTagButtonText=function(){return $el.find(".add-tag-text").removeClass("hidden")},hideAddTagButtonText=function(){return $el.find(".add-tag-text").addClass("hidden")},showSaveButton=function(){return $el.find(".save").removeClass("hidden")},hideSaveButton=function(){return $el.find(".save").addClass("hidden")},showInput=function(){return $el.find("input").removeClass("hidden").focus()},hideInput=function(){return $el.find("input").addClass("hidden").blur()},resetInput=function(){return $el.find("input").val(""),$el.find("input").autocomplete("close")},addValue=$qqueue.bindAdd(function(value){var model,onError,onSuccess,tags;return value=trim(value.toLowerCase()),0!==value.length?(tags=_.clone($model.$modelValue.tags,!1),null==tags&&(tags=[]),indexOf.call(tags,value)<0&&tags.push(value),model=$model.$modelValue.clone(),model.tags=tags,$model.$setViewValue(model),onSuccess=function(){return $rootScope.$broadcast("object:updated")},onError=function(){return $confirm.notify("error"),model.revert(),$model.$setViewValue(model)},$repo.save(model).then(onSuccess,onError),hideSaveButton()):void 0}),deleteValue=$qqueue.bindAdd(function(value){var model,onError,onSuccess,tags;return value=trim(value.toLowerCase()),0!==value.length?(tags=_.clone($model.$modelValue.tags,!1),tags=_.pull(tags,value),model=$model.$modelValue.clone(),model.tags=tags,$model.$setViewValue(model),onSuccess=function(){return $rootScope.$broadcast("object:updated")},onError=function(){return $confirm.notify("error"),model.revert(),$model.$setViewValue(model)},$repo.save(model).then(onSuccess,onError)):void 0; -}),saveInputTag=function(){var value;return value=$el.find("input").val(),addValue(value),resetInput()},removeInputLastCharacter=function(_this){return function(input){var inputValue;return inputValue=input.val(),input.val(inputValue.substring(0,inputValue.length-1))}}(this),$el.on("keypress","input",function(event){var ref;if((ref=event.keyCode)===ENTER_KEY||ref===ESC_KEY)return event.preventDefault()}),$el.on("keyup","input",function(event){var target;return target=angular.element(event.currentTarget),event.keyCode===ENTER_KEY?saveInputTag():event.keyCode===COMMA_KEY?(removeInputLastCharacter(target),saveInputTag()):event.keyCode===ESC_KEY?(resetInput(),hideInput(),hideSaveButton(),showAddTagButton()):target.val().length?showSaveButton():hideSaveButton()}),$el.on("click",".save",function(event){return event.preventDefault(),saveInputTag()}),$el.on("click",".add-tag",function(event){return event.preventDefault(),hideAddTagButton(),showInput()}),$el.on("click",".icon-delete",function(event){var target,value;return event.preventDefault(),target=angular.element(event.currentTarget),value=target.siblings(".tag-name").text(),deleteValue(value)}),bindOnce($scope,"project.tags_colors",function(tags_colors){var positioningFunction;return isEditable()?(showAddTagButton(),positioningFunction=function(position,elements){var menu;return menu=elements.element.element,menu.css("width",elements.target.width),menu.css("top",position.top),menu.css("left",position.left)},$el.find("input").autocomplete({source:_.keys(tags_colors),position:{my:"left top",using:positioningFunction},select:function(event,ui){return addValue(ui.item.value),ui.item.value=""}})):void renderInReadModeOnly()}),$scope.$watch($attrs.ngModel,function(model){var ref,ref1,tagsColors;if(model)return(null!=(ref=model.tags)?ref.length:void 0)?hideAddTagButtonText():showAddTagButtonText(),tagsColors=(null!=(ref1=$scope.project)?ref1.tags_colors:void 0)||[],renderTags(model.tags,tagsColors)}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,require:"ngModel",templateUrl:"common/tag/tag-line.html"}},module.directive("tgTagLine",["$rootScope","$tgRepo","$tgResources","$tgConfirm","$tgQqueue","$tgTemplate","$compile",TagLineDirective])}.call(this),function(){var MarkitupDirective,bindOnce,module,taiga,indexOf=[].indexOf||function(item){for(var i=0,l=this.length;l>i;i++)if(i in this&&this[i]===item)return i;return-1};taiga=this.taiga,bindOnce=this.taiga.bindOnce,module=angular.module("taigaCommon"),MarkitupDirective=function($rootscope,$rs,$selectedText,$template,$compile,$translate){var link,previewTemplate;return previewTemplate=$template.get("common/wysiwyg/wysiwyg-markitup-preview.html",!0),link=function($scope,$el,$attrs,$model){var addLine,cancelablePromise,closePreviewMode,element,markdownTitle,prepareUrlFormatting,preview,previewDomNode,renderMarkItUp,setCaretPosition,unbind,urlFormatting;return element=angular.element($el),previewDomNode=$("
",{"class":"preview"}),closePreviewMode=function(){return element.parents(".markdown").find(".preview").remove(),element.parents(".markItUp").show()},$scope.$on("markdown-editor:submit",function(){return closePreviewMode()}),cancelablePromise=null,preview=function(){var markItUpDomNode,markdownDomNode;return markdownDomNode=element.parents(".markdown"),markItUpDomNode=element.parents(".markItUp"),$rs.mdrender.render($scope.projectId,$model.$modelValue).then(function(data){var html,markdown;return html=previewTemplate({data:data.data}),html=$compile(html)($scope),markdownDomNode.append(html),markItUpDomNode.hide(),markdown=element.closest(".markdown"),markdown.on("mouseup.preview",".preview",function(event){var target;return event.preventDefault(),target=angular.element(event.target),target.is("a")||!$selectedText.get().length?(markdown.off(".preview"),closePreviewMode()):void 0})})},setCaretPosition=function(textarea,caretPosition){var line,range,scrollRelation,totalLines;return textarea.createTextRange?(range=textarea.createTextRange(),range.move("character",caretPosition),range.select()):textarea.selectionStart&&(textarea.focus(),textarea.setSelectionRange(caretPosition,caretPosition)),totalLines=textarea.value.split("\n").length,line=textarea.value.slice(0,+(caretPosition-1)+1||9e9).split("\n").length,scrollRelation=line/totalLines,$el.scrollTop(scrollRelation*$el[0].scrollHeight-$el.height()/2)},addLine=function(textarea,nline,replace){var cursorPosition,j,key,len,line,lines;for(lines=textarea.value.split("\n"),replace?lines[nline]=replace+lines[nline]:lines[nline]="",cursorPosition=0,key=j=0,len=lines.length;len>j&&(line=lines[key],cursorPosition+=line.length+1||1,key!==nline);key=++j);return textarea.value=lines.join("\n"),replace?cursorPosition-lines[nline].length+replace.length-1:cursorPosition},prepareUrlFormatting=function(markItUp){var indices,regex,result;for(regex=/(<<<|>>>)/gi,result=0,indices=[];result=regex.exec(markItUp.textarea.value);)indices.push(result.index);return markItUp.donotparse=indices},urlFormatting=function(markItUp){var endIndex,ref,ref1,regex,result,startIndex,url,value;for(regex=/<<>>/gi,endIndex=0;;){if(result=regex.exec(markItUp.textarea.value),!result)break;if(ref1=result.index,indexOf.call(markItUp.donotparse,ref1)<0){endIndex=result.index;break}}return value=markItUp.textarea.value,url=value.substring(startIndex,endIndex).replace("<<<","").replace(">>>",""),url=url.replace("(","%28").replace(")","%29"),url=url.replace("[","%5B").replace("]","%5D"),value=value.substring(0,startIndex)+url+value.substring(endIndex+3,value.length),markItUp.textarea.value=value,markItUp.donotparse=void 0}},markdownTitle=function(markItUp,char){var heading,i,j,n,ref;for(heading="",n=$.trim(markItUp.selection||markItUp.placeHolder).length,i=j=0,ref=n-1;ref>=0?ref>=j:j>=ref;i=ref>=0?++j:--j)heading+=char;return"\n"+heading+"\n"},renderMarkItUp=function(){var markdownSettings;return markdownSettings={nameSpace:"markdown",onShiftEnter:{keepDefault:!1,openWith:"\n\n"},onEnter:{keepDefault:!1,replaceWith:function(){return $(".textcomplete-dropdown").is(":visible")?void 0:"\n"},afterInsert:function(data){var cursorLine,emptyListItem,lastLine,lines,markdownCaretPositon,match,newLineContent,nline,replace;return lines=data.textarea.value.split("\n"),cursorLine=data.caretPosition>0?data.textarea.value.slice(0,+(data.caretPosition-1)+1||9e9).split("\n").length:1,newLineContent=data.textarea.value.slice(data.caretPosition).split("\n")[0],lastLine=lines[cursorLine-1],match=lastLine.match(/^(\s*- ).*/),match&&(emptyListItem=lastLine.match(/^(\s*)\-\s$/),emptyListItem?(nline=cursorLine-1,replace=null):(nline=cursorLine,replace=""+match[1]),markdownCaretPositon=addLine(data.textarea,nline,replace)),match=lastLine.match(/^(\s*\* ).*/),match&&(emptyListItem=lastLine.match(/^(\s*\* )$/),emptyListItem?(nline=cursorLine-1,replace=null):(nline=cursorLine,replace=""+match[1]),markdownCaretPositon=addLine(data.textarea,nline,replace)),match=lastLine.match(/^(\s*)(\d+)\.\s/),match&&(emptyListItem=lastLine.match(/^(\s*)(\d+)\.\s$/),emptyListItem?(nline=cursorLine-1,replace=null):(nline=cursorLine,replace=match[1]+(parseInt(match[2],10)+1)+". "),markdownCaretPositon=addLine(data.textarea,nline,replace)),markdownCaretPositon?setCaretPosition(data.textarea,markdownCaretPositon):void 0}},markupSet:[{name:$translate.instant("COMMON.WYSIWYG.H1_BUTTON"),key:"1",placeHolder:$translate.instant("COMMON.WYSIWYG.H1_SAMPLE_TEXT"),closeWith:function(markItUp){return markdownTitle(markItUp,"=")}},{name:$translate.instant("COMMON.WYSIWYG.H2_BUTTON"),key:"2",placeHolder:$translate.instant("COMMON.WYSIWYG.H2_SAMPLE_TEXT"),closeWith:function(markItUp){return markdownTitle(markItUp,"-")}},{name:$translate.instant("COMMON.WYSIWYG.H3_BUTTON"),key:"3",openWith:"### ",placeHolder:$translate.instant("COMMON.WYSIWYG.H3_SAMPLE_TEXT")},{separator:"---------------"},{name:$translate.instant("COMMON.WYSIWYG.BOLD_BUTTON"),key:"B",openWith:"**",closeWith:"**",placeHolder:$translate.instant("COMMON.WYSIWYG.BOLD_BUTTON_SAMPLE_TEXT")},{name:$translate.instant("COMMON.WYSIWYG.ITALIC_SAMPLE_TEXT"),key:"I",openWith:"_",closeWith:"_",placeHolder:$translate.instant("COMMON.WYSIWYG.ITALIC_SAMPLE_TEXT")},{name:$translate.instant("COMMON.WYSIWYG.STRIKE_BUTTON"),key:"S",openWith:"~~",closeWith:"~~",placeHolder:$translate.instant("COMMON.WYSIWYG.STRIKE_SAMPLE_TEXT")},{separator:"---------------"},{name:$translate.instant("COMMON.WYSIWYG.BULLETED_LIST_BUTTON"),openWith:"- ",placeHolder:$translate.instant("COMMON.WYSIWYG.BULLETED_LIST_SAMPLE_TEXT")},{name:$translate.instant("COMMON.WYSIWYG.NUMERIC_LIST_BUTTON"),openWith:function(markItUp){return markItUp.line+". "},placeHolder:$translate.instant("COMMON.WYSIWYG.NUMERIC_LIST_SAMPLE_TEXT")},{separator:"---------------"},{name:$translate.instant("COMMON.WYSIWYG.PICTURE_BUTTON"),key:"P",openWith:"![",closeWith:'](<<<[![Url:!:http://]!]>>> "[![Title]!]")',placeHolder:$translate.instant("COMMON.WYSIWYG.PICTURE_SAMPLE_TEXT"),beforeInsert:function(markItUp){return prepareUrlFormatting(markItUp)},afterInsert:function(markItUp){return urlFormatting(markItUp)}},{name:$translate.instant("COMMON.WYSIWYG.LINK_BUTTON"),key:"L",openWith:"[",closeWith:'](<<<[![Url:!:http://]!]>>> "[![Title]!]")',placeHolder:$translate.instant("COMMON.WYSIWYG.LINK_SAMPLE_TEXT"),beforeInsert:function(markItUp){return prepareUrlFormatting(markItUp)},afterInsert:function(markItUp){return urlFormatting(markItUp)}},{separator:"---------------"},{name:$translate.instant("COMMON.WYSIWYG.QUOTE_BLOCK_BUTTON"),openWith:"> ",placeHolder:$translate.instant("COMMON.WYSIWYG.QUOTE_BLOCK_SAMPLE_TEXT")},{name:$translate.instant("COMMON.WYSIWYG.CODE_BLOCK_BUTTON"),openWith:"```\n",placeHolder:$translate.instant("COMMON.WYSIWYG.CODE_BLOCK_SAMPLE_TEXT"),closeWith:"\n```"},{separator:"---------------"},{name:$translate.instant("COMMON.WYSIWYG.PREVIEW_BUTTON"),call:preview,className:"preview-icon"}],afterInsert:function(event){var target;return target=angular.element(event.textarea),$model.$setViewValue(target.val())}},element.markItUpRemove().markItUp(markdownSettings).textcomplete([{cache:!0,match:/(^|\s)#([a-z0-9]+)$/i,search:function(term,callback){var filter,searchProps,searchTypes;return term=taiga.slugify(term),searchTypes=["issues","tasks","userstories"],searchProps=["ref","subject"],filter=function(_this){return function(item){var j,len,prop;for(j=0,len=searchProps.length;len>j;j++)if(prop=searchProps[j],taiga.slugify(item[prop]).indexOf(term)>=0)return!0;return!1}}(this),cancelablePromise&&cancelablePromise.abort(),cancelablePromise=$rs.search["do"]($scope.projectId,term),cancelablePromise.then(function(_this){return function(res){var j,len,results,type;if(res.count<1||res.count===res.wikipages.length)return callback([]);for(results=[],j=0,len=searchTypes.length;len>j;j++)type=searchTypes[j],res[type]&&res[type].length>0?results.push(callback(res[type].filter(filter),!0)):results.push(void 0);return results}}(this)),callback([])},replace:function(res){return"$1#"+res.ref+" "},template:function(res,term){return"#"+res.ref+" - "+res.subject}},{cache:!0,match:/(^|\s)@([a-z0-9\-\._]{2,})$/i,search:function(term,callback){var searchProps,username;return username=taiga.slugify(term),searchProps=["username","full_name","full_name_display"],callback($scope.project.members.length<1?[]:$scope.project.members.filter(function(_this){return function(user){var j,len,prop;for(j=0,len=searchProps.length;len>j;j++)if(prop=searchProps[j],taiga.slugify(user[prop]).indexOf(username)>=0)return!0;return!1}}(this)))},replace:function(user){return"$1@"+user.username+" "},template:function(user){return user.username+" - "+user.full_name_display}},{cache:!0,match:/(^|\s)\[\[([a-z0-9\-]+)$/i,search:function(term,callback){return term=taiga.slugify(term),$rs.search["do"]($scope.projectId,term).then(function(_this){return function(res){return res.count<1&&callback([]),res.count<1||!res.wikipages||res.wikipages.length<=0?callback([]):callback(res.wikipages.filter(function(page){return taiga.slugify(page.slug).indexOf(term)>=0}),!0),callback([])}}(this))},replace:function(res){return"$1[["+res.slug+"]]"},template:function(res,term){return res.slug}}],{debounce:200})},renderMarkItUp(),unbind=$rootscope.$on("$translateChangeEnd",renderMarkItUp),element.on("keypress",function(event){return $scope.$apply()}),$scope.$on("$destroy",function(){return $el.off(),unbind()})},{link:link,require:"ngModel"}},module.directive("tgMarkitup",["$rootScope","$tgResources","$selectedText","$tgTemplate","$compile","$translate",MarkitupDirective])}.call(this),function(){var BacklogFiltersDirective,bindOnce,debounceLeading,groupBy,mixOf,module,scopeDefer,taiga,toggleText;taiga=this.taiga,mixOf=this.taiga.mixOf,toggleText=this.taiga.toggleText,scopeDefer=this.taiga.scopeDefer,bindOnce=this.taiga.bindOnce,groupBy=this.taiga.groupBy,debounceLeading=this.taiga.debounceLeading,module=angular.module("taigaBacklog"),BacklogFiltersDirective=function($q,$log,$location,$templates){var link,template,templateSelected;return template=$templates.get("backlog/filters.html",!0),templateSelected=$templates.get("backlog/filter-selected.html",!0),link=function($scope,$el,$attrs){var $ctrl,currentFiltersType,getFiltersType,initializeSelectedFilters,reloadUserstories,renderFilters,renderSelectedFilters,selectQFilter,selectedFilters,showCategories,showFilters,toggleFilterSelection;return currentFiltersType="",$ctrl=$el.closest(".wrapper").controller(),selectedFilters=[],showFilters=function(title,type){return $el.find(".filters-cats").hide(),$el.find(".filter-list").removeClass("hidden"),$el.find("h2.breadcrumb").removeClass("hidden"),$el.find("h2 a.subfilter span.title").html(title),$el.find("h2 a.subfilter span.title").prop("data-type",type),currentFiltersType=getFiltersType()},showCategories=function(){return $el.find(".filters-cats").show(),$el.find(".filter-list").addClass("hidden"),$el.find("h2.breadcrumb").addClass("hidden")},initializeSelectedFilters=function(){var i,len,name,ref,val,values;showCategories(),selectedFilters=[],ref=$scope.filters;for(name in ref)for(values=ref[name],i=0,len=values.length;len>i;i++)val=values[i],val.selected&&selectedFilters.push(val);return renderSelectedFilters()},renderSelectedFilters=function(){var html;return _.map(selectedFilters,function(_this){return function(f){return f.color?f.style="border-left: 3px solid "+f.color:void 0}}(this)),html=templateSelected({filters:selectedFilters}),$el.find(".filters-applied").html(html)},renderFilters=function(filters){var html;return _.map(filters,function(_this){return function(f){return f.color?f.style="border-left: 3px solid "+f.color:void 0}}(this)),html=template({filters:filters}),$el.find(".filter-list").html(html)},getFiltersType=function(){return $el.find("h2 a.subfilter span.title").prop("data-type")},reloadUserstories=function(){return currentFiltersType=getFiltersType(),$q.all([$ctrl.loadUserstories(),$ctrl.generateFilters()]).then(function(){var currentFilters;return currentFilters=$scope.filters[currentFiltersType],renderFilters(_.reject(currentFilters,"selected"))})},toggleFilterSelection=function(type,id){var filter,filters;return currentFiltersType=getFiltersType(),filters=$scope.filters[type],filter=_.find(filters,{id:id}),filter.selected=!filter.selected,filter.selected?(selectedFilters.push(filter),$scope.$apply(function(){return $ctrl.selectFilter(type,id)})):(selectedFilters=_.reject(selectedFilters,function(selected){return filter.type===selected.type&&filter.id===selected.id}),$ctrl.unselectFilter(type,id)),renderSelectedFilters(selectedFilters),type===currentFiltersType&&renderFilters(_.reject(filters,"selected")),reloadUserstories()},selectQFilter=debounceLeading(100,function(value){return void 0!==value?(0===value.length?$ctrl.replaceFilter("q",null):$ctrl.replaceFilter("q",value),reloadUserstories()):void 0}),$scope.$watch("filtersQ",selectQFilter),$scope.$on("backlog:loaded",function(ctx){return initializeSelectedFilters()}),$scope.$on("filters:update",function(ctx){return $ctrl.generateFilters().then(function(){var filters;return filters=$scope.filters[currentFiltersType],currentFiltersType?renderFilters(_.reject(filters,"selected")):void 0})}),$el.on("click",".filters-cats > ul > li > a",function(event){var tags,target;return event.preventDefault(),target=angular.element(event.currentTarget),tags=$scope.filters[target.data("type")],renderFilters(_.reject(tags,"selected")),showFilters(target.attr("title"),target.data("type"))}),$el.on("click",".filters-inner > .filters-step-cat > .breadcrumb > .back",function(event){return event.preventDefault(),showCategories()}),$el.on("click",".filters-applied a",function(event){var id,target,type;return event.preventDefault(),target=angular.element(event.currentTarget),id=target.data("id"),type=target.data("type"),toggleFilterSelection(type,id)}),$el.on("click",".filter-list .single-filter",function(event){var id,target,type;return event.preventDefault(),target=angular.element(event.currentTarget),target.hasClass("active")?target.removeClass("active"):target.addClass("active"),id=target.data("id"),type=target.data("type"),toggleFilterSelection(type,id)})},{link:link}},module.directive("tgBacklogFilters",["$q","$log","$tgLocation","$tgTemplate",BacklogFiltersDirective])}.call(this),function(){var CreateEditSprint,bindOnce,debounce,module,taiga;taiga=this.taiga,bindOnce=this.taiga.bindOnce,debounce=this.taiga.debounce,module=angular.module("taigaBacklog"),CreateEditSprint=function($repo,$confirm,$rs,$rootscope,lightboxService,$loading,$translate){var link;return link=function($scope,$el,attrs){var createSprint,getLastSprint,hasErrors,remove,resetSprint,submit;return hasErrors=!1,createSprint=!0,resetSprint=function(){return $scope.sprint={project:null,name:null,estimated_start:null,estimated_finish:null}},submit=debounce(2e3,function(_this){return function(event){var broadcastEvent,currentLoading,form,newSprint,prettyDate,promise,submitButton,target;return event.preventDefault(),target=angular.element(event.currentTarget),prettyDate=$translate.instant("COMMON.PICKERDATE.FORMAT"),submitButton=$el.find(".submit-button"),form=$el.find("form").checksley(),form.validate()?(hasErrors=!1,newSprint=angular.copy($scope.sprint),broadcastEvent=null,createSprint?(newSprint.estimated_start=moment(newSprint.estimated_start,prettyDate).format("YYYY-MM-DD"),newSprint.estimated_finish=moment(newSprint.estimated_finish,prettyDate).format("YYYY-MM-DD"),promise=$repo.create("milestones",newSprint),broadcastEvent="sprintform:create:success"):(newSprint.setAttr("estimated_start",moment(newSprint.estimated_start,prettyDate).format("YYYY-MM-DD")),newSprint.setAttr("estimated_finish",moment(newSprint.estimated_finish,prettyDate).format("YYYY-MM-DD")),promise=$repo.save(newSprint),broadcastEvent="sprintform:edit:success"),currentLoading=$loading().target(submitButton).start(),promise.then(function(data){return currentLoading.finish(),createSprint&&($scope.sprintsCounter+=1),$rootscope.$broadcast(broadcastEvent,data),lightboxService.close($el)}),promise.then(null,function(data){return currentLoading.finish(),form.setErrors(data),data._error_message?$confirm.notify("light-error",data._error_message):data.__all__?$confirm.notify("light-error",data.__all__[0]):void 0})):(hasErrors=!0,void $el.find(".last-sprint-name").addClass("disappear"))}}(this)),remove=function(){var message,title;return title=$translate.instant("LIGHTBOX.DELETE_SPRINT.TITLE"),message=$scope.sprint.name,$confirm.askOnDelete(title,message).then(function(_this){return function(askResponse){var onError,onSuccess;return onSuccess=function(){return askResponse.finish(),$scope.milestonesCounter-=1,lightboxService.close($el),$rootscope.$broadcast("sprintform:remove:success",$scope.sprint)},onError=function(){return askResponse.finish(!1),$confirm.notify("error")},$repo.remove($scope.sprint).then(onSuccess,onError)}}(this))},getLastSprint=function(){var openSprints,sortedSprints;return openSprints=_.filter($scope.sprints,function(sprint){return!sprint.closed}),sortedSprints=_.sortBy(openSprints,function(sprint){return moment(sprint.estimated_finish,"YYYY-MM-DD").format("X")}),sortedSprints[sortedSprints.length-1]},$scope.$on("sprintform:create",function(event,projectId){var estimatedFinish,estimatedStart,form,lastSprint,lastSprintNameDom,prettyDate,text;return resetSprint(),form=$el.find("form").checksley(),form.reset(),createSprint=!0,prettyDate=$translate.instant("COMMON.PICKERDATE.FORMAT"),$scope.sprint.project=projectId,$scope.sprint.name=null,$scope.sprint.slug=null,lastSprint=getLastSprint(),estimatedStart=moment(),lastSprint?estimatedStart=moment(lastSprint.estimated_finish):$scope.sprint.estimated_start&&(estimatedStart=moment($scope.sprint.estimated_start)),$scope.sprint.estimated_start=estimatedStart.format(prettyDate),estimatedFinish=moment().add(2,"weeks"),lastSprint?estimatedFinish=moment(lastSprint.estimated_finish).add(2,"weeks"):$scope.sprint.estimated_finish&&(estimatedFinish=moment($scope.sprint.estimated_finish)),$scope.sprint.estimated_finish=estimatedFinish.format(prettyDate),lastSprintNameDom=$el.find(".last-sprint-name"),null!=(null!=lastSprint?lastSprint.name:void 0)&&(text=$translate.instant("LIGHTBOX.ADD_EDIT_SPRINT.LAST_SPRINT_NAME",{lastSprint:lastSprint.name}),lastSprintNameDom.html(text)),$el.find(".delete-sprint").addClass("hidden"),text=$translate.instant("LIGHTBOX.ADD_EDIT_SPRINT.TITLE"),$el.find(".title").text(text),text=$translate.instant("COMMON.CREATE"),$el.find(".button-green").text(text),lightboxService.open($el),$el.find(".sprint-name").focus(),$el.find(".last-sprint-name").removeClass("disappear")}),$scope.$on("sprintform:edit",function(ctx,sprint){var editSprint,prettyDate,save;return resetSprint(),createSprint=!1,prettyDate=$translate.instant("COMMON.PICKERDATE.FORMAT"),$scope.$apply(function(){return $scope.sprint=sprint,$scope.sprint.estimated_start=moment($scope.sprint.estimated_start).format(prettyDate),$scope.sprint.estimated_finish=moment($scope.sprint.estimated_finish).format(prettyDate)}),$el.find(".delete-sprint").removeClass("hidden"),editSprint=$translate.instant("BACKLOG.EDIT_SPRINT"),$el.find(".title").text(editSprint),save=$translate.instant("COMMON.SAVE"),$el.find(".button-green").text(save),lightboxService.open($el),$el.find(".sprint-name").focus().select(),$el.find(".last-sprint-name").addClass("disappear")}),$el.on("keyup",".sprint-name",function(event){return $el.find(".sprint-name").val().length>0||hasErrors?$el.find(".last-sprint-name").addClass("disappear"):$el.find(".last-sprint-name").removeClass("disappear")}),$el.on("submit","form",submit),$el.on("click",".delete-sprint .icon-delete",function(event){return event.preventDefault(),remove()}),$scope.$on("$destroy",function(){return $el.off()}),resetSprint()},{link:link}},module.directive("tgLbCreateEditSprint",["$tgRepo","$tgConfirm","$tgResources","$rootScope","lightboxService","$tgLoading","$translate",CreateEditSprint])}.call(this),function(){var BacklogController,BacklogDirective,BurndownBacklogGraphDirective,TgBacklogProgressBarDirective,ToggleBurndownVisibility,UsPointsDirective,UsRolePointsSelectorDirective,bindMethods,bindOnce,generateHash,groupBy,mixOf,module,scopeDefer,taiga,timeout,toggleText,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,mixOf=this.taiga.mixOf,toggleText=this.taiga.toggleText,scopeDefer=this.taiga.scopeDefer,bindOnce=this.taiga.bindOnce,groupBy=this.taiga.groupBy,timeout=this.taiga.timeout,bindMethods=this.taiga.bindMethods,generateHash=this.taiga.generateHash,module=angular.module("taigaBacklog"),BacklogController=function(superClass){function BacklogController(scope1,rootscope,repo,confirm,rs,params1,q,location,appMetaService,navUrls,events,analytics,translate,loading){var promise;this.scope=scope1,this.rootscope=rootscope,this.repo=repo,this.confirm=confirm,this.rs=rs,this.params=params1,this.q=q,this.location=location,this.appMetaService=appMetaService,this.navUrls=navUrls,this.events=events,this.analytics=analytics,this.translate=translate,this.loading=loading,bindMethods(this),this.scope.sectionName=this.translate.instant("BACKLOG.SECTION_NAME"),this.showTags=!1,this.activeFilters=!1,this.scope.showGraphPlaceholder=null,this.initializeEventHandlers(),promise=this.loadInitialData(),promise.then(function(_this){return function(){var description,title;return title=_this.translate.instant("BACKLOG.PAGE_TITLE",{projectName:_this.scope.project.name}),description=_this.translate.instant("BACKLOG.PAGE_DESCRIPTION",{projectName:_this.scope.project.name,projectDescription:_this.scope.project.description}),_this.appMetaService.setAll(title,description),_this.rs.userstories.getShowTags(_this.scope.projectId)?(_this.showTags=!0,_this.scope.$broadcast("showTags",_this.showTags)):void 0}}(this)),promise.then(null,this.onInitialDataError.bind(this))}return extend(BacklogController,superClass),BacklogController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","tgAppMetaService","$tgNavUrls","$tgEvents","$tgAnalytics","$translate","$tgLoading"],BacklogController.prototype.initializeEventHandlers=function(){return this.scope.$on("usform:bulk:success",function(_this){return function(){return _this.loadUserstories(),_this.loadProjectStats(),_this.analytics.trackEvent("userstory","create","bulk create userstory on backlog",1)}}(this)),this.scope.$on("sprintform:create:success",function(_this){return function(){return _this.loadSprints(),_this.loadProjectStats(),_this.analytics.trackEvent("sprint","create","create sprint on backlog",1)}}(this)),this.scope.$on("usform:new:success",function(_this){return function(){return _this.loadUserstories(),_this.loadProjectStats(),_this.rootscope.$broadcast("filters:update"),_this.analytics.trackEvent("userstory","create","create userstory on backlog",1)}}(this)),this.scope.$on("sprintform:edit:success",function(_this){return function(){return _this.loadProjectStats()}}(this)),this.scope.$on("sprintform:remove:success",function(_this){return function(event,sprint){return _this.loadSprints(),_this.loadProjectStats(),_this.loadUserstories(),sprint.closed&&_this.loadClosedSprints(),_this.rootscope.$broadcast("filters:update")}}(this)),this.scope.$on("usform:edit:success",function(_this){return function(){return _this.loadUserstories(),_this.rootscope.$broadcast("filters:update")}}(this)),this.scope.$on("sprint:us:move",this.moveUs),this.scope.$on("sprint:us:moved",this.loadSprints),this.scope.$on("sprint:us:moved",this.loadProjectStats),this.scope.$on("backlog:load-closed-sprints",this.loadClosedSprints),this.scope.$on("backlog:unload-closed-sprints",this.unloadClosedSprints)},BacklogController.prototype.initializeSubscription=function(){var routingKey1,routingKey2;return routingKey1="changes.project."+this.scope.projectId+".userstories",this.events.subscribe(this.scope,routingKey1,function(_this){return function(message){return _this.loadUserstories(),_this.loadSprints()}}(this)),routingKey2="changes.project."+this.scope.projectId+".milestones",this.events.subscribe(this.scope,routingKey2,function(_this){return function(message){return _this.loadSprints()}}(this))},BacklogController.prototype.toggleShowTags=function(){return this.scope.$apply(function(_this){return function(){return _this.showTags=!_this.showTags,_this.rs.userstories.storeShowTags(_this.scope.projectId,_this.showTags)}}(this))},BacklogController.prototype.toggleActiveFilters=function(){return this.activeFilters=!this.activeFilters},BacklogController.prototype.loadProjectStats=function(){return this.rs.projects.stats(this.scope.projectId).then(function(_this){return function(stats){var totalPoints;return _this.scope.stats=stats,totalPoints=stats.total_points?stats.total_points:stats.defined_points,totalPoints?_this.scope.stats.completedPercentage=Math.round(100*stats.closed_points/totalPoints):_this.scope.stats.completedPercentage=0,_this.scope.showGraphPlaceholder=!(null!=stats.total_points&&null!=stats.total_milestones),stats}}(this))},BacklogController.prototype.unloadClosedSprints=function(){return this.scope.$apply(function(_this){return function(){return _this.scope.closedSprints=[],_this.rootscope.$broadcast("closed-sprints:reloaded",[])}}(this))},BacklogController.prototype.loadClosedSprints=function(){var params;return params={closed:!0},this.rs.sprints.list(this.scope.projectId,params).then(function(_this){return function(result){var j,len,sprint,sprints;for(sprints=result.milestones,_this.scope.totalClosedMilestones=result.closed,j=0,len=sprints.length;len>j;j++)sprint=sprints[j],sprint.user_stories=_.sortBy(sprint.user_stories,"sprint_order");return _this.scope.closedSprints=sprints,_this.scope.closedSprintsById=groupBy(sprints,function(x){return x.id}),_this.rootscope.$broadcast("closed-sprints:reloaded",sprints),sprints}}(this))},BacklogController.prototype.loadSprints=function(){var params;return params={closed:!1},this.rs.sprints.list(this.scope.projectId,params).then(function(_this){return function(result){var j,len,sprint,sprints;for(sprints=result.milestones,_this.scope.totalMilestones=sprints,_this.scope.totalClosedMilestones=result.closed,_this.scope.totalOpenMilestones=result.open,_this.scope.totalMilestones=_this.scope.totalOpenMilestones+_this.scope.totalClosedMilestones,j=0,len=sprints.length;len>j;j++)sprint=sprints[j],sprint.user_stories=_.sortBy(sprint.user_stories,"sprint_order");return _this.scope.sprints=sprints,_this.scope.openSprints=_.filter(sprints,function(sprint){return!sprint.closed}).reverse(),_this.scope.closedSprints||(_this.scope.closedSprints=[]),_this.scope.sprintsCounter=sprints.length,_this.scope.sprintsById=groupBy(sprints,function(x){return x.id}),_this.rootscope.$broadcast("sprints:loaded",sprints),sprints}}(this))},BacklogController.prototype.restoreFilters=function(){var selectedStatuses,selectedTags;return selectedTags=this.scope.oldSelectedTags,selectedStatuses=this.scope.oldSelectedStatuses,selectedStatuses||selectedStatuses?(this.scope.filtersQ=this.scope.filtersQOld,this.replaceFilter("q",this.scope.filtersQ),_.each([selectedTags,selectedStatuses],function(_this){return function(filterGrp){return _.each(filterGrp,function(item){var filter,filters;return filters=_this.scope.filters[item.type],filter=_.find(filters,{id:item.id}),filter.selected=!0,_this.selectFilter(item.type,item.id)})}}(this)),this.loadUserstories()):void 0},BacklogController.prototype.resetFilters=function(){var selectedStatuses,selectedTags;return selectedTags=_.filter(this.scope.filters.tags,"selected"),selectedStatuses=_.filter(this.scope.filters.status,"selected"),this.scope.oldSelectedTags=selectedTags,this.scope.oldSelectedStatuses=selectedStatuses,this.scope.filtersQOld=this.scope.filtersQ,this.scope.filtersQ="",this.replaceFilter("q",null),_.each([selectedTags,selectedStatuses],function(_this){return function(filterGrp){return _.each(filterGrp,function(item){var filter,filters;return filters=_this.scope.filters[item.type],filter=_.find(filters,{id:item.id}),filter.selected=!1,_this.unselectFilter(item.type,item.id)})}}(this)),this.loadUserstories()},BacklogController.prototype.loadUserstories=function(){var promise;return this.scope.httpParams=this.getUrlFilters(),this.rs.userstories.storeQueryParams(this.scope.projectId,this.scope.httpParams),promise=this.rs.userstories.listUnassigned(this.scope.projectId,this.scope.httpParams),promise.then(function(_this){return function(userstories){ -return _this.scope.userstories=_.sortBy(userstories,"backlog_order"),_this.setSearchDataFilters(),scopeDefer(_this.scope,function(){return _this.scope.$broadcast("userstories:loaded")}),userstories}}(this))},BacklogController.prototype.loadBacklog=function(){return this.q.all([this.loadProjectStats(),this.loadSprints(),this.loadUserstories()])},BacklogController.prototype.loadProject=function(){return this.rs.projects.getBySlug(this.params.pslug).then(function(_this){return function(project){return project.is_backlog_activated||_this.location.path(_this.navUrls.resolve("permission-denied")),_this.scope.projectId=project.id,_this.scope.project=project,_this.scope.closedMilestones=!!project.total_closed_milestones,_this.scope.$emit("project:loaded",project),_this.scope.points=_.sortBy(project.points,"order"),_this.scope.pointsById=groupBy(project.points,function(x){return x.id}),_this.scope.usStatusById=groupBy(project.us_statuses,function(x){return x.id}),_this.scope.usStatusList=_.sortBy(project.us_statuses,"id"),project}}(this))},BacklogController.prototype.loadInitialData=function(){var promise;return promise=this.loadProject(),promise.then(function(_this){return function(project){return _this.fillUsersAndRoles(project.members,project.roles),_this.initializeSubscription()}}(this)),promise.then(function(_this){return function(){return _this.loadBacklog()}}(this)).then(function(_this){return function(){return _this.generateFilters()}}(this)).then(function(_this){return function(){return _this.scope.$emit("backlog:loaded")}}(this))},BacklogController.prototype.prepareBulkUpdateData=function(uses,field){return null==field&&(field="backlog_order"),_.map(uses,function(x){return{us_id:x.id,order:x[field]}})},BacklogController.prototype.resortUserStories=function(uses,field){var index,item,items,j,len;for(null==field&&(field="backlog_order"),items=[],index=j=0,len=uses.length;len>j;index=++j)item=uses[index],item[field]=index,item.isModified()&&items.push(item);return items},BacklogController.prototype.moveUs=function(ctx,usList,newUsIndex,newSprintId){var data,items,j,l,len,len1,len2,m,movedFromClosedSprint,movedToClosedSprint,newSprint,oldSprintId,project,promise,promises,sprint,us,userstories;if(oldSprintId=usList[0].milestone,project=usList[0].project,movedFromClosedSprint=!1,movedToClosedSprint=!1,sprint=this.scope.sprintsById[oldSprintId],!sprint&&this.scope.closedSprintsById&&(sprint=this.scope.closedSprintsById[oldSprintId],sprint&&(movedFromClosedSprint=!0)),newSprint=this.scope.sprintsById[newSprintId],!newSprint&&newSprintId&&(newSprint=this.scope.closedSprintsById[newSprintId],newSprint&&(movedToClosedSprint=!0)),newSprintId===oldSprintId)return items=null,userstories=null,userstories=null===newSprintId?this.scope.userstories:newSprint.user_stories,this.scope.$apply(function(){var args,j,key,len,r,us;for(key=j=0,len=usList.length;len>j;key=++j)us=usList[key],r=userstories.indexOf(us),userstories.splice(r,1);return args=[newUsIndex,0].concat(usList),Array.prototype.splice.apply(userstories,args)}),null===newSprintId?(items=this.resortUserStories(userstories,"backlog_order"),data=this.prepareBulkUpdateData(items,"backlog_order"),this.rs.userstories.bulkUpdateBacklogOrder(project,data).then(function(_this){return function(){var j,len,results,us;for(results=[],j=0,len=usList.length;len>j;j++)us=usList[j],results.push(_this.rootscope.$broadcast("sprint:us:moved",us,oldSprintId,newSprintId));return results}}(this))):(items=this.resortUserStories(userstories,"sprint_order"),data=this.prepareBulkUpdateData(items,"sprint_order"),this.rs.userstories.bulkUpdateSprintOrder(project,data).then(function(_this){return function(){var j,len,results,us;for(results=[],j=0,len=usList.length;len>j;j++)us=usList[j],results.push(_this.rootscope.$broadcast("sprint:us:moved",us,oldSprintId,newSprintId));return results}}(this))),promise;if(null===newSprintId){for(j=0,len=usList.length;len>j;j++)us=usList[j],us.milestone=null;return this.scope.$apply(function(_this){return function(){var args,key,l,len1,r,results;for(args=[newUsIndex,0].concat(usList),Array.prototype.splice.apply(_this.scope.userstories,args),results=[],key=l=0,len1=usList.length;len1>l;key=++l)us=usList[key],r=sprint.user_stories.indexOf(us),results.push(sprint.user_stories.splice(r,1));return results}}(this)),promise=this.repo.save(us),promise=promise.then(function(_this){return function(){return items=_this.resortUserStories(_this.scope.userstories,"backlog_order"),data=_this.prepareBulkUpdateData(items,"backlog_order"),_this.rs.userstories.bulkUpdateBacklogOrder(us.project,data).then(function(){return _this.rootscope.$broadcast("sprint:us:moved",us,oldSprintId,newSprintId),movedFromClosedSprint?_this.rootscope.$broadcast("backlog:load-closed-sprints"):void 0})}}(this)),promise.then(null,function(){return console.log("FAIL")}),promise}if(null===oldSprintId){for(l=0,len1=usList.length;len1>l;l++)us=usList[l],us.milestone=newSprintId;this.scope.$apply(function(_this){return function(){var args,key,len2,m,r,results;for(args=[newUsIndex,0].concat(usList),Array.prototype.splice.apply(newSprint.user_stories,args),results=[],key=m=0,len2=usList.length;len2>m;key=++m)us=usList[key],r=_this.scope.userstories.indexOf(us),results.push(_this.scope.userstories.splice(r,1));return results}}(this))}else{for(m=0,len2=usList.length;len2>m;m++)us=usList[m],us.milestone=newSprintId;this.scope.$apply(function(_this){return function(){var args,len3,n,r,results;for(args=[newUsIndex,0].concat(usList),Array.prototype.splice.apply(newSprint.user_stories,args),results=[],n=0,len3=usList.length;len3>n;n++)us=usList[n],r=sprint.user_stories.indexOf(us),results.push(sprint.user_stories.splice(r,1));return results}}(this))}return promises=_.map(usList,function(_this){return function(us){return _this.repo.save(us)}}(this)),promise=this.q.all(promises).then(function(_this){return function(){return items=_this.resortUserStories(newSprint.user_stories,"sprint_order"),data=_this.prepareBulkUpdateData(items,"sprint_order"),_this.rs.userstories.bulkUpdateSprintOrder(project,data).then(function(result){return _this.rootscope.$broadcast("sprint:us:moved",us,oldSprintId,newSprintId)}),_this.rs.userstories.bulkUpdateBacklogOrder(project,data).then(function(){var len3,n,results;for(results=[],n=0,len3=usList.length;len3>n;n++)us=usList[n],results.push(_this.rootscope.$broadcast("sprint:us:moved",us,oldSprintId,newSprintId));return results}),movedToClosedSprint||movedFromClosedSprint?_this.scope.$broadcast("backlog:load-closed-sprints"):void 0}}(this)),promise.then(null,function(){return console.log("FAIL")}),promise},BacklogController.prototype.isFilterSelected=function(type,id){return null!=this.searchdata[type]&&this.searchdata[type][id]?!0:!1},BacklogController.prototype.setSearchDataFilters=function(){var name,results,urlfilters,val,value;urlfilters=this.getUrlFilters(),urlfilters.q&&(this.scope.filtersQ=this.scope.filtersQ||urlfilters.q),this.searchdata={},results=[];for(name in urlfilters)value=urlfilters[name],null==this.searchdata[name]&&(this.searchdata[name]={}),results.push(function(){var j,len,ref1,results1;for(ref1=taiga.toString(value).split(","),results1=[],j=0,len=ref1.length;len>j;j++)val=ref1[j],results1.push(this.searchdata[name][val]=!0);return results1}.call(this));return results},BacklogController.prototype.getUrlFilters=function(){return _.pick(this.location.search(),"status","tags","q")},BacklogController.prototype.generateFilters=function(){var loadFilters,urlfilters;return urlfilters=this.getUrlFilters(),this.scope.filters={},loadFilters={},loadFilters.project=this.scope.projectId,loadFilters.tags=urlfilters.tags,loadFilters.status=urlfilters.status,loadFilters.q=urlfilters.q,loadFilters.milestone="null",this.rs.userstories.filtersData(loadFilters).then(function(_this){return function(data){var choicesFiltersFormat,selectedStatuses,selectedTags,tagsFilterFormat;return choicesFiltersFormat=function(choices,type,byIdObject){return _.map(choices,function(t){return t.type=type,t})},tagsFilterFormat=function(tags){return _.map(tags,function(t){return t.id=t.name,t.type="tags",t})},_this.scope.filters.status=choicesFiltersFormat(data.statuses,"status",_this.scope.usStatusById),_this.scope.filters.tags=tagsFilterFormat(data.tags),selectedTags=_.filter(_this.scope.filters.tags,"selected"),selectedTags=_.map(selectedTags,"id"),selectedStatuses=_.filter(_this.scope.filters.status,"selected"),selectedStatuses=_.map(selectedStatuses,"id"),_this.markSelectedFilters(_this.scope.filters,urlfilters),_this.rs.userstories.storeQueryParams(_this.scope.projectId,{status:selectedStatuses,tags:selectedTags,project:_this.scope.projectId,milestone:null})}}(this))},BacklogController.prototype.markSelectedFilters=function(filters,urlfilters){var isSelected,j,key,len,name,obj,ref1,ref2,results,searchdata,val,value;searchdata={},ref1=_.omit(urlfilters,"page","orderBy");for(name in ref1)for(value=ref1[name],null==searchdata[name]&&(searchdata[name]={}),ref2=(""+value).split(","),j=0,len=ref2.length;len>j;j++)val=ref2[j],searchdata[name][val]=!0;isSelected=function(type,id){return null!=searchdata[type]&&searchdata[type][id]?!0:!1},results=[];for(key in filters)value=filters[key],results.push(function(){var l,len1,results1;for(results1=[],l=0,len1=value.length;len1>l;l++)obj=value[l],results1.push(obj.selected=isSelected(obj.type,obj.id)?!0:void 0);return results1}());return results},BacklogController.prototype.updateUserStoryStatus=function(){return this.setSearchDataFilters(),this.generateFilters().then(function(_this){return function(){return _this.rootscope.$broadcast("filters:update"),_this.loadProjectStats()}}(this))},BacklogController.prototype.editUserStory=function(projectId,ref,$event){var currentLoading,target;return target=$($event.target),currentLoading=this.loading().target(target).removeClasses("icon-edit").timeout(200).start(),this.rs.userstories.getByRef(projectId,ref).then(function(_this){return function(us){return _this.rootscope.$broadcast("usform:edit",us),currentLoading.finish()}}(this))},BacklogController.prototype.deleteUserStory=function(us){var message,title;return title=this.translate.instant("US.TITLE_DELETE_ACTION"),message=us.subject,this.confirm.askOnDelete(title,message).then(function(_this){return function(askResponse){var promise;return _this.scope.userstories=_.without(_this.scope.userstories,us),promise=_this.repo.remove(us),promise.then(function(){return askResponse.finish(),_this.loadBacklog()}),promise.then(null,function(){return askResponse.finish(!1),_this.confirm.notify("error")})}}(this))},BacklogController.prototype.addNewUs=function(type){switch(type){case"standard":return this.rootscope.$broadcast("usform:new",this.scope.projectId,this.scope.project.default_us_status,this.scope.usStatusList);case"bulk":return this.rootscope.$broadcast("usform:bulk",this.scope.projectId,this.scope.project.default_us_status)}},BacklogController.prototype.addNewSprint=function(){return this.rootscope.$broadcast("sprintform:create",this.scope.projectId)},BacklogController}(mixOf(taiga.Controller,taiga.PageMixin,taiga.FiltersMixin)),module.controller("BacklogController",BacklogController),BacklogDirective=function($repo,$rootscope,$translate){var doomLineTemplate,link,linkDoomLine,linkFilters,linkToolbar,showHideFilter,showHideTags;return doomLineTemplate=_.template('
<%- text %>
'),linkDoomLine=function($scope,$el,$attrs,$ctrl){var addDoomLineDom,getUsItems,reloadDoomLine,removeDoomlineDom;return reloadDoomLine=function(){var current_sum,domElement,i,j,len,ref1,results,stats,total_points,us;if(null!=$scope.stats&&null!=$scope.stats.total_points&&0!==$scope.stats.total_points){if(removeDoomlineDom(),stats=$scope.stats,total_points=stats.total_points,current_sum=stats.assigned_points,!$scope.userstories)return;for(ref1=$scope.userstories,results=[],i=j=0,len=ref1.length;len>j;i=++j){if(us=ref1[i],current_sum+=us.total_points,current_sum>total_points){domElement=$el.find(".backlog-table-body .us-item-row")[i],addDoomLineDom(domElement);break}results.push(void 0)}return results}},removeDoomlineDom=function(){return $el.find(".doom-line").remove()},addDoomLineDom=function(element){var text;return text=$translate.instant("BACKLOG.DOOMLINE"),$(element).before(doomLineTemplate({text:text}))},getUsItems=function(){var rowElements;return rowElements=$el.find(".backlog-table-body .us-item-row"),_.map(rowElements,function(x){return angular.element(x)})},$scope.$on("userstories:loaded",reloadDoomLine),$scope.$watch("stats",reloadDoomLine)},linkToolbar=function($scope,$el,$attrs,$ctrl){var checkSelected,lastChecked,moveToCurrentSprint,shiftPressed;return moveToCurrentSprint=function(selectedUss){var extraPoints,totalExtraPoints,ussCurrent;return ussCurrent=_($scope.userstories),$scope.userstories=ussCurrent.without.apply(ussCurrent,selectedUss).value(),extraPoints=_.map(selectedUss,function(v,k){return v.total_points}),totalExtraPoints=_.reduce(extraPoints,function(acc,num){return acc+num}),$scope.sprints[0].user_stories=_.union($scope.sprints[0].user_stories,selectedUss),$scope.sprints[0].total_points+=totalExtraPoints,$repo.saveAll(selectedUss).then(function(){return $ctrl.loadSprints(),$ctrl.loadProjectStats()})},shiftPressed=!1,lastChecked=null,checkSelected=function(target){var moveToCurrentSprintDom,selectedUsDom;return lastChecked=target.closest(".us-item-row"),moveToCurrentSprintDom=$el.find("#move-to-current-sprint"),selectedUsDom=$el.find(".backlog-table-body input:checkbox:checked"),selectedUsDom.length>0&&$scope.sprints.length>0?moveToCurrentSprintDom.show():moveToCurrentSprintDom.hide(),target.closest(".us-item-row").toggleClass("ui-multisortable-multiple")},$(window).on("keydown.shift-pressed keyup.shift-pressed",function(event){return shiftPressed=!!event.shiftKey,!0}),$el.on("change",".backlog-table-body input:checkbox",function(event){var current,elements,nextAll,prevAll,target;return lastChecked&&shiftPressed&&(elements=[],current=$(event.currentTarget).closest(".us-item-row"),nextAll=lastChecked.nextAll(),prevAll=lastChecked.prevAll(),_.some(nextAll,function(next){return next===current[0]})?elements=lastChecked.nextUntil(current):_.some(prevAll,function(prev){return prev===current[0]})&&(elements=lastChecked.prevUntil(current)),_.map(elements,function(elm){var input;return input=$(elm).find("input:checkbox"),input.prop("checked",!0),checkSelected(input)})),target=angular.element(event.currentTarget),target.closest(".us-item-row").toggleClass("is-checked"),checkSelected(target)}),$el.on("click","#move-to-current-sprint",function(_this){return function(event){var ussDom,ussToMove;return ussDom=$el.find(".backlog-table-body input:checkbox:checked"),ussToMove=_.map(ussDom,function(item){var itemScope;return item=$(item).closest(".tg-scope"),itemScope=item.scope(),itemScope.us.milestone=$scope.sprints[0].id,itemScope.us}),$scope.$apply(_.partial(moveToCurrentSprint,ussToMove))}}(this)),$el.on("click","#show-tags",function(event){return event.preventDefault(),$ctrl.toggleShowTags(),showHideTags($ctrl)})},showHideTags=function($ctrl){var elm,text;return elm=angular.element("#show-tags"),$ctrl.showTags?(elm.addClass("active"),text=$translate.instant("BACKLOG.TAGS.HIDE"),elm.text(text)):(elm.removeClass("active"),text=$translate.instant("BACKLOG.TAGS.SHOW"),elm.text(text))},showHideFilter=function($scope,$el,$ctrl){var hideText,showText,sidebar,target;return sidebar=$el.find("sidebar.filters-bar"),sidebar.one("transitionend",function(){return timeout(150,function(){return $rootscope.$broadcast("resize"),$(".burndown").css("visibility","visible")})}),target=angular.element("#show-filters-button"),$(".burndown").css("visibility","hidden"),sidebar.toggleClass("active"),target.toggleClass("active"),hideText=$translate.instant("BACKLOG.FILTERS.HIDE"),showText=$translate.instant("BACKLOG.FILTERS.SHOW"),toggleText(target,[hideText,showText]),sidebar.hasClass("active")?$ctrl.restoreFilters():$ctrl.resetFilters(),$ctrl.toggleActiveFilters()},linkFilters=function($scope,$el,$attrs,$ctrl){return $scope.filtersSearch={},$el.on("click","#show-filters-button",function(event){return event.preventDefault(),$scope.$apply(function(){return showHideFilter($scope,$el,$ctrl)})})},link=function($scope,$el,$attrs,$rootscope){var $ctrl,filters;return $ctrl=$el.controller(),linkToolbar($scope,$el,$attrs,$ctrl),linkFilters($scope,$el,$attrs,$ctrl),linkDoomLine($scope,$el,$attrs,$ctrl),$el.find(".backlog-table-body").disableSelection(),filters=$ctrl.getUrlFilters(),(filters.status||filters.tags||filters.q)&&showHideFilter($scope,$el,$ctrl),$scope.$on("showTags",function(){return showHideTags($ctrl)}),$scope.$on("$destroy",function(){return $el.off(),$(window).off(".shift-pressed")})},{link:link}},module.directive("tgBacklog",["$tgRepo","$rootScope","$translate",BacklogDirective]),UsRolePointsSelectorDirective=function($rootscope,$template,$compile,$translate){var link,selectionTemplate;return selectionTemplate=$template.get("backlog/us-role-points-popover.html",!0),link=function($scope,$el,$attrs){return bindOnce($scope,"project",function(project){var numberOfRoles,roles;return roles=_.filter(project.roles,"computable"),numberOfRoles=_.size(roles),numberOfRoles>1?$el.append($compile(selectionTemplate({roles:roles}))($scope)):($el.find(".icon-arrow-bottom").remove(),$el.find(".header-points").addClass("not-clickable"))}),$scope.$on("uspoints:select",function(ctx,roleId,roleName){return $el.find(".popover").popover().close(),$el.find(".header-points").html(roleName+"/Total")}),$scope.$on("uspoints:clear-selection",function(ctx,roleId){var text;return $el.find(".popover").popover().close(),text=$translate.instant("COMMON.FIELDS.POINTS"),$el.find(".header-points").text(text)}),$el.on("click",function(event){var target;return target=angular.element(event.target),(target.is("span")||target.is("div"))&&event.stopPropagation(),$el.find(".popover").popover().open()}),$el.on("click",".clear-selection",function(event){return event.preventDefault(),event.stopPropagation(),$rootscope.$broadcast("uspoints:clear-selection")}),$el.on("click",".role",function(event){var rolScope,target;return event.preventDefault(),event.stopPropagation(),target=angular.element(event.currentTarget),rolScope=target.scope(),$rootscope.$broadcast("uspoints:select",target.data("role-id"),target.text())}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgUsRolePointsSelector",["$rootScope","$tgTemplate","$compile",UsRolePointsSelectorDirective]),UsPointsDirective=function($tgEstimationsService,$repo,$tgTemplate){var link,rolesTemplate;return rolesTemplate=$tgTemplate.get("common/estimation/us-points-roles-popover.html",!0),link=function($scope,$el,$attrs){var $ctrl,bindClickElements,estimationProcess,filteringRoleId,renderRolesSelector,selectedRoleId,updatingSelectedRoleId;return $ctrl=$el.controller(),updatingSelectedRoleId=null,selectedRoleId=null,filteringRoleId=null,estimationProcess=null,$scope.$on("uspoints:select",function(ctx,roleId,roleName){var us;return us=$scope.$eval($attrs.tgBacklogUsPoints),selectedRoleId=roleId,estimationProcess.render()}),$scope.$on("uspoints:clear-selection",function(ctx){var us;return us=$scope.$eval($attrs.tgBacklogUsPoints),selectedRoleId=null,estimationProcess.render()}),$scope.$watch($attrs.tgBacklogUsPoints,function(us){var roles;return us?(estimationProcess=$tgEstimationsService.create($el,us,$scope.project),roles=estimationProcess.calculateRoles(),0===roles.length?($el.find(".icon-arrow-bottom").remove(),$el.find("a.us-points").addClass("not-clickable")):1===roles.length&&(selectedRoleId=_.keys(us.points)[0]),estimationProcess.isEditable&&bindClickElements(),estimationProcess.onSelectedPointForRole=function(roleId,pointId){return this.save(roleId,pointId).then(function(){return $ctrl.loadProjectStats()})},estimationProcess.render=function(){var ctx,html,mainTemplate,pointId,pointObj,template,text,title,totalPoints;return totalPoints=this.calculateTotalPoints(),null==selectedRoleId||1===roles.length?(text=totalPoints,title=totalPoints):(pointId=this.us.points[selectedRoleId],pointObj=this.pointsById[pointId],text=pointObj.name+" / "+totalPoints+"",title=pointObj.name+" / "+totalPoints),ctx={totalPoints:totalPoints,roles:this.calculateRoles(),editable:this.isEditable,text:text,title:title},mainTemplate="common/estimation/us-estimation-total.html",template=$tgTemplate.get(mainTemplate,!0),html=template(ctx),this.$el.html(html)},estimationProcess.render()):void 0}),renderRolesSelector=function(){var html,roles;return roles=estimationProcess.calculateRoles(),html=rolesTemplate({roles:roles}),$el.append(html),$el.find(".pop-role").popover().open(function(){return $(this).remove()})},bindClickElements=function(){return $el.on("click","a.us-points span",function(event){var us;return event.preventDefault(),event.stopPropagation(),us=$scope.$eval($attrs.tgBacklogUsPoints),updatingSelectedRoleId=selectedRoleId,null!=selectedRoleId?estimationProcess.renderPointsSelector(selectedRoleId):renderRolesSelector()}),$el.on("click",".role",function(event){var popRolesDom,target,us;return event.preventDefault(),event.stopPropagation(),target=angular.element(event.currentTarget),us=$scope.$eval($attrs.tgBacklogUsPoints),updatingSelectedRoleId=target.data("role-id"),popRolesDom=$el.find(".pop-role"),popRolesDom.find("a").removeClass("active"),popRolesDom.find("a[data-role-id='"+updatingSelectedRoleId+"']").addClass("active"),estimationProcess.renderPointsSelector(updatingSelectedRoleId)})},$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgBacklogUsPoints",["$tgEstimationsService","$tgRepo","$tgTemplate",UsPointsDirective]),ToggleBurndownVisibility=function($storage){var hide,link,show;return hide=function(){return $(".js-burndown-graph").removeClass("shown"),$(".js-toggle-burndown-visibility-button").removeClass("active"),$(".js-burndown-graph").removeClass("open")},show=function(firstLoad){return $(".js-toggle-burndown-visibility-button").addClass("active"),firstLoad?$(".js-burndown-graph").addClass("shown"):$(".js-burndown-graph").addClass("open")},link=function($scope,$el,$attrs){var firstLoad,hash,toggleGraph;return firstLoad=!0,hash=generateHash(["is-burndown-grpahs-collapsed"]),$scope.isBurndownGraphCollapsed=$storage.get(hash)||!1,toggleGraph=function(){return $scope.isBurndownGraphCollapsed?hide(firstLoad):show(firstLoad),firstLoad=!1},$scope.$watch("showGraphPlaceholder",function(){return null!=$scope.showGraphPlaceholder?($scope.isBurndownGraphCollapsed=$scope.isBurndownGraphCollapsed||$scope.showGraphPlaceholder,toggleGraph()):void 0}),$el.on("click",".js-toggle-burndown-visibility-button",function(){return $scope.isBurndownGraphCollapsed=!$scope.isBurndownGraphCollapsed,$storage.set(hash,$scope.isBurndownGraphCollapsed),toggleGraph()}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgToggleBurndownVisibility",["$tgStorage",ToggleBurndownVisibility]),BurndownBacklogGraphDirective=function($translate){var link,redrawChart;return redrawChart=function(element,dataToDraw){var client_increment_line,colors,data,evolution_line,milestonesRange,optimal_line,options,results,team_increment_line,width,zero_line;return width=element.width(),element.height(width/6),milestonesRange=function(){results=[];for(var j=0,ref1=dataToDraw.milestones.length-1;ref1>=0?ref1>=j:j>=ref1;ref1>=0?j++:j--)results.push(j);return results}.apply(this),data=[],zero_line=_.map(dataToDraw.milestones,function(ml){return 0}),data.push({data:_.zip(milestonesRange,zero_line),lines:{fillColor:"rgba(0,0,0,0)"},points:{show:!1}}),optimal_line=_.map(dataToDraw.milestones,function(ml){return ml.optimal}),data.push({data:_.zip(milestonesRange,optimal_line),lines:{fillColor:"rgba(120,120,120,0.2)"}}),evolution_line=_.filter(_.map(dataToDraw.milestones,function(ml){return ml.evolution}),function(evolution){return null!=evolution}),data.push({data:_.zip(milestonesRange,evolution_line),lines:{fillColor:"rgba(102,153,51,0.3)"}}),client_increment_line=_.map(dataToDraw.milestones,function(ml){return-ml["team-increment"]-ml["client-increment"]}),data.push({data:_.zip(milestonesRange,client_increment_line),lines:{fillColor:"rgba(255,51,51,0.3)"}}),team_increment_line=_.map(dataToDraw.milestones,function(ml){return-ml["team-increment"]}),data.push({data:_.zip(milestonesRange,team_increment_line),lines:{fillColor:"rgba(153,51,51,0.3)"}}),colors=["rgba(0,0,0,1)","rgba(120,120,120,0.2)","rgba(102,153,51,1)","rgba(153,51,51,1)","rgba(255,51,51,1)"],options={grid:{borderWidth:{top:0,right:1,left:0,bottom:0},borderColor:"#ccc",hoverable:!0},xaxis:{ticks:dataToDraw.milestones.length,axisLabel:$translate.instant("BACKLOG.CHART.XAXIS_LABEL"),axisLabelUseCanvas:!0,axisLabelFontSizePixels:12,axisLabelFontFamily:"Verdana, Arial, Helvetica, Tahoma, sans-serif",axisLabelPadding:5,tickFormatter:function(val,axis){return""}},yaxis:{axisLabel:$translate.instant("BACKLOG.CHART.YAXIS_LABEL"),axisLabelUseCanvas:!0,axisLabelFontSizePixels:12,axisLabelFontFamily:"Verdana, Arial, Helvetica, Tahoma, sans-serif",axisLabelPadding:5},series:{shadowSize:0,lines:{show:!0,fill:!0},points:{show:!0,fill:!0,radius:4,lineWidth:2}},colors:colors,tooltip:!0,tooltipOpts:{content:function(label,xval,yval,flotItem){var ctx;return 1===flotItem.seriesIndex?(ctx={sprintName:dataToDraw.milestones[xval].name,value:Math.abs(yval)},$translate.instant("BACKLOG.CHART.OPTIMAL",ctx)):2===flotItem.seriesIndex?(ctx={sprintName:dataToDraw.milestones[xval].name,value:Math.abs(yval)},$translate.instant("BACKLOG.CHART.REAL",ctx)):3===flotItem.seriesIndex?(ctx={sprintName:dataToDraw.milestones[xval].name,value:Math.abs(yval)},$translate.instant("BACKLOG.CHART.INCREMENT_CLIENT",ctx)):(ctx={sprintName:dataToDraw.milestones[xval].name,value:Math.abs(yval)},$translate.instant("BACKLOG.CHART.INCREMENT_TEAM",ctx))}}},element.empty(),element.plot(data,options).data("plot")},link=function($scope,$el,$attrs){var element;return element=angular.element($el),$scope.$watch("stats",function(value){return null!=$scope.stats?(redrawChart(element,$scope.stats),$scope.$on("resize",function(){return redrawChart(element,$scope.stats)})):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgBurndownBacklogGraph",["$translate",BurndownBacklogGraphDirective]),TgBacklogProgressBarDirective=function($template,$compile){var adjustPercentaje,link,render,template;return template=$template.get("backlog/progress-bar.html",!0),render=function(scope,el,projectPointsPercentaje,closedPointsPercentaje){var html;return html=template({projectPointsPercentaje:projectPointsPercentaje,closedPointsPercentaje:closedPointsPercentaje}),html=$compile(html)(scope),el.html(html)},adjustPercentaje=function(percentage){var adjusted;return adjusted=_.max([0,percentage]),adjusted=_.min([100,adjusted]),Math.round(adjusted)},link=function($scope,$el,$attrs){var element;return element=angular.element($el),$scope.$watch($attrs.tgBacklogProgressBar,function(stats){var closedPoints,closedPointsPercentaje,definedPoints,projectPointsPercentaje,totalPoints;return null!=stats?(totalPoints=stats.total_points?stats.total_points:stats.defined_points,definedPoints=stats.defined_points,closedPoints=stats.closed_points,definedPoints>totalPoints?(projectPointsPercentaje=100*totalPoints/definedPoints,closedPointsPercentaje=100*closedPoints/definedPoints):(projectPointsPercentaje=100,closedPointsPercentaje=100*closedPoints/totalPoints),projectPointsPercentaje=adjustPercentaje(projectPointsPercentaje-3),closedPointsPercentaje=adjustPercentaje(closedPointsPercentaje-3),render($scope,$el,projectPointsPercentaje,closedPointsPercentaje)):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgBacklogProgressBar",["$tgTemplate","$compile",TgBacklogProgressBarDirective])}.call(this),function(){var BacklogEmptySortableDirective,BacklogSortableDirective,SprintSortableDirective,bindOnce,deleteElement,groupBy,mixOf,module,scopeDefer,taiga,toggleText;taiga=this.taiga,mixOf=this.taiga.mixOf,toggleText=this.taiga.toggleText,scopeDefer=this.taiga.scopeDefer,bindOnce=this.taiga.bindOnce,groupBy=this.taiga.groupBy,module=angular.module("taigaBacklog"),deleteElement=function(el){return el.scope().$destroy(),el.off(),el.remove()},BacklogSortableDirective=function($repo,$rs,$rootscope,$tgConfirm,$translate){var link;return link=function($scope,$el,$attrs){var getUsIndex;return getUsIndex=function(_this){return function(us){return $(us).index(".backlog-table-body .row")}}(this),bindOnce($scope,"project",function(project){var filterError;if(project.my_permissions.indexOf("modify_us")>-1)return filterError=function(){var text;return text=$translate.instant("BACKLOG.SORTABLE_FILTER_ERROR"),$tgConfirm.notify("error",text)},$el.sortable({items:".us-item-row",cancel:".popover",connectWith:".sprint",dropOnEmpty:!0,placeholder:"row us-item-row us-item-drag sortable-placeholder",scroll:!0,disableHorizontalScroll:!0,tolerance:"pointer",revert:!1,start:function(){return $(document.body).addClass("drag-active")},stop:function(){return $(document.body).removeClass("drag-active"),$el.hasClass("active-filters")?($el.sortable("cancel"),filterError()):void 0}}),$el.on("multiplesortreceive",function(event,ui){var itemIndex,itemUs;return $el.hasClass("active-filters")?(ui.source.sortable("cancel"),void filterError()):(itemUs=ui.item.scope().us,itemIndex=getUsIndex(ui.item),deleteElement(ui.item),$scope.$emit("sprint:us:move",[itemUs],itemIndex,null),ui.item.find("a").removeClass("noclick"))}),$el.on("multiplesortstop",function(event,ui){var index,items,us;if(0!==$(ui.items[0]).parent().length&&!$el.hasClass("active-filters"))return items=_.sortBy(ui.items,function(item){return $(item).index()}),index=_.min(_.map(items,function(item){return getUsIndex(item)})),us=_.map(items,function(item){var itemUs;return item=$(item),itemUs=item.scope().us,setTimeout(function(_this){return function(){return item.find("a").removeClass("noclick")}}(this),300),itemUs}),$scope.$emit("sprint:us:move",us,index,null)}),$el.on("sortstart",function(event,ui){return ui.item.find("a").addClass("noclick")})}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},BacklogEmptySortableDirective=function($repo,$rs,$rootscope){var link;return link=function($scope,$el,$attrs){return bindOnce($scope,"project",function(project){return project.my_permissions.indexOf("modify_us")>-1?($el.sortable({items:".us-item-row",dropOnEmpty:!0}),$el.on("sortreceive",function(event,ui){var itemIndex,itemUs;return itemUs=ui.item.scope().us,itemIndex=ui.item.index(),deleteElement(ui.item),$scope.$emit("sprint:us:move",[itemUs],itemIndex,null),ui.item.find("a").removeClass("noclick")})):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},SprintSortableDirective=function($repo,$rs,$rootscope){var link;return link=function($scope,$el,$attrs){return bindOnce($scope,"project",function(project){return project.my_permissions.indexOf("modify_us")>-1?($el.sortable({scroll:!0,dropOnEmpty:!0,items:".sprint-table .milestone-us-item-row",disableHorizontalScroll:!0,connectWith:".sprint,.backlog-table-body,.empty-backlog",placeholder:"row us-item-row sortable-placeholder",forcePlaceholderSize:!0}),$el.on("multiplesortreceive",function(event,ui){var index,items,us;return items=_.sortBy(ui.items,function(item){return $(item).index()}),index=_.min(_.map(items,function(item){return $(item).index()})),us=_.map(items,function(item){var itemUs;return item=$(item),itemUs=item.scope().us,deleteElement(item),itemUs}),$scope.$emit("sprint:us:move",us,index,$scope.sprint.id)}),$el.on("multiplesortstop",function(event,ui){var itemIndex,itemUs;if(0!==ui.item.parent().length)return itemUs=ui.item.scope().us, -itemIndex=ui.item.index(),setTimeout(function(_this){return function(){return ui.item.find("a").removeClass("noclick")}}(this),300),$scope.$emit("sprint:us:move",[itemUs],itemIndex,$scope.sprint.id)}),$el.on("sortstart",function(event,ui){return ui.item.find("a").addClass("noclick")})):void 0})},{link:link}},module.directive("tgBacklogSortable",["$tgRepo","$tgResources","$rootScope","$tgConfirm","$translate",BacklogSortableDirective]),module.directive("tgBacklogEmptySortable",["$tgRepo","$tgResources","$rootScope",BacklogEmptySortableDirective]),module.directive("tgSprintSortable",["$tgRepo","$tgResources","$rootScope",SprintSortableDirective])}.call(this),function(){var BacklogSprintDirective,BacklogSprintHeaderDirective,ToggleExcludeClosedSprintsVisualization,module,taiga;taiga=this.taiga,module=angular.module("taigaBacklog"),BacklogSprintDirective=function($repo,$rootscope){var link,slideOptions,sprintTableMinHeight,toggleSprint;return sprintTableMinHeight=50,slideOptions={duration:500,easing:"linear"},toggleSprint=function(_this){return function($el){var sprintArrow,sprintTable;return sprintTable=$el.find(".sprint-table"),sprintArrow=$el.find(".icon-arrow-up"),sprintArrow.toggleClass("active"),sprintTable.toggleClass("open")}}(this),link=function($scope,$el,$attrs){return $scope.$watch($attrs.tgBacklogSprint,function(sprint){return sprint=$scope.$eval($attrs.tgBacklogSprint),sprint.closed?$el.addClass("sprint-closed"):toggleSprint($el)}),$el.on("click",".sprint-name > .icon-arrow-up",function(event){return event.preventDefault(),toggleSprint($el),$el.find(".sprint-table").slideToggle(slideOptions)}),$el.on("click",".sprint-name > .icon-edit",function(event){var sprint;return event.preventDefault(),sprint=$scope.$eval($attrs.tgBacklogSprint),$rootscope.$broadcast("sprintform:edit",sprint)}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgBacklogSprint",["$tgRepo","$rootScope",BacklogSprintDirective]),BacklogSprintHeaderDirective=function($navUrls,$template,$compile,$translate){var link,template;return template=$template.get("backlog/sprint-header.html"),link=function($scope,$el,$attrs,$model){var isEditable,isVisible,prettyDate,render;return prettyDate=$translate.instant("BACKLOG.SPRINTS.DATE"),isEditable=function(){return-1!==$scope.project.my_permissions.indexOf("modify_milestone")},isVisible=function(){return-1!==$scope.project.my_permissions.indexOf("view_milestones")},render=function(sprint){var compiledTemplate,ctx,estimatedDateRange,finish,start,taskboardUrl,templateScope;return taskboardUrl=$navUrls.resolve("project-taskboard",{project:$scope.project.slug,sprint:sprint.slug}),start=moment(sprint.estimated_start).format(prettyDate),finish=moment(sprint.estimated_finish).format(prettyDate),estimatedDateRange=start+"-"+finish,ctx={name:sprint.name,taskboardUrl:taskboardUrl,estimatedDateRange:estimatedDateRange,closedPoints:sprint.closed_points||0,totalPoints:sprint.total_points||0,isVisible:isVisible(),isEditable:isEditable()},templateScope=$scope.$new(),_.assign(templateScope,ctx),compiledTemplate=$compile(template)(templateScope),$el.html(compiledTemplate)},$scope.$watch($attrs.ngModel,function(sprint){return render(sprint)}),$scope.$on("sprintform:edit:success",function(){return render($model.$modelValue)}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,restrict:"EA",require:"ngModel"}},module.directive("tgBacklogSprintHeader",["$tgNavUrls","$tgTemplate","$compile","$translate",BacklogSprintHeaderDirective]),ToggleExcludeClosedSprintsVisualization=function($rootscope,$loading,$translate){var excludeClosedSprints,link;return excludeClosedSprints=!0,link=function($scope,$el,$attrs){var currentLoading,loadingElm;return loadingElm=$("
"),$el.after(loadingElm),currentLoading=null,$el.on("click",function(event){return event.preventDefault(),excludeClosedSprints=!excludeClosedSprints,currentLoading=$loading().target(loadingElm).start(),excludeClosedSprints?$rootscope.$broadcast("backlog:unload-closed-sprints"):$rootscope.$broadcast("backlog:load-closed-sprints")}),$scope.$on("$destroy",function(){return $el.off()}),$scope.$on("closed-sprints:reloaded",function(_this){return function(ctx,sprints){var key,text;return currentLoading.finish(),key=sprints.length>0?"BACKLOG.SPRINTS.ACTION_HIDE_CLOSED_SPRINTS":"BACKLOG.SPRINTS.ACTION_SHOW_CLOSED_SPRINTS",text=$translate.instant(key),$el.find(".text").text(text)}}(this))},{link:link}},module.directive("tgBacklogToggleClosedSprintsVisualization",["$rootScope","$tgLoading","$translate",ToggleExcludeClosedSprintsVisualization])}.call(this),function(){var SprintGraphDirective,bindOnce,groupBy,mixOf,module,scopeDefer,taiga,timeout,toggleText;taiga=this.taiga,mixOf=this.taiga.mixOf,toggleText=this.taiga.toggleText,scopeDefer=this.taiga.scopeDefer,bindOnce=this.taiga.bindOnce,groupBy=this.taiga.groupBy,timeout=this.taiga.timeout,module=angular.module("taigaTaskboard"),SprintGraphDirective=function($translate){var link,redrawChart;return redrawChart=function(element,dataToDraw){var data,days,options,width;return width=element.width(),element.height(240),days=_.map(dataToDraw,function(x){return moment(x.day)}),data=[],data.unshift({data:_.zip(days,_.map(dataToDraw,function(d){return d.optimal_points})),lines:{fillColor:"rgba(120,120,120,0.2)"}}),data.unshift({data:_.zip(days,_.map(dataToDraw,function(d){return d.open_points})),lines:{fillColor:"rgba(102,153,51,0.3)"}}),options={grid:{borderWidth:{top:0,right:1,left:0,bottom:0},borderColor:"#ccc",hoverable:!0},xaxis:{tickSize:[1,"day"],min:days[0],max:_.last(days),mode:"time",daysNames:days,axisLabel:$translate.instant("TASKBOARD.CHARTS.XAXIS_LABEL"),axisLabelUseCanvas:!0,axisLabelFontSizePixels:12,axisLabelFontFamily:"Verdana, Arial, Helvetica, Tahoma, sans-serif",axisLabelPadding:5},yaxis:{min:0,axisLabel:$translate.instant("TASKBOARD.CHARTS.YAXIS_LABEL"),axisLabelUseCanvas:!0,axisLabelFontSizePixels:12,axisLabelFontFamily:"Verdana, Arial, Helvetica, Tahoma, sans-serif",axisLabelPadding:5},series:{shadowSize:0,lines:{show:!0,fill:!0},points:{show:!0,fill:!0,radius:4,lineWidth:2}},colors:["rgba(102,153,51,1)","rgba(120,120,120,0.2)"],tooltip:!0,tooltipOpts:{content:function(label,xval,yval,flotItem){var formattedDate,roundedValue;return formattedDate=moment(xval).format($translate.instant("TASKBOARD.CHARTS.DATE")),roundedValue=Math.round(yval),1===flotItem.seriesIndex?$translate.instant("TASKBOARD.CHARTS.OPTIMAL",{formattedDate:formattedDate,roundedValue:roundedValue}):$translate.instant("TASKBOARD.CHARTS.REAL",{formattedDate:formattedDate,roundedValue:roundedValue})}}},element.empty(),element.plot(data,options).data("plot")},link=function($scope,$el,$attrs){var element;return element=angular.element($el),$scope.$on("resize",function(){return $scope.stats?redrawChart(element,$scope.stats.days):void 0}),$scope.$on("taskboard:graph:toggle-visibility",function(){return $el.parent().toggleClass("open"),timeout(100,function(){return $scope.stats?redrawChart(element,$scope.stats.days):void 0})}),$scope.$watch("stats",function(value){return null!=$scope.stats?redrawChart(element,$scope.stats.days):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgSprintGraph",["$translate",SprintGraphDirective])}.call(this),function(){var CreateBulkTasksDirective,CreateEditTaskDirective,bindOnce,debounce,module,taiga;taiga=this.taiga,bindOnce=this.taiga.bindOnce,debounce=this.taiga.debounce,CreateEditTaskDirective=function($repo,$model,$rs,$rootscope,$loading,lightboxService,$translate){var link;return link=function($scope,$el,attrs){var submit,submitButton;return $scope.isNew=!0,$scope.$on("taskform:new",function(ctx,sprintId,usId){var create,newTask;return $scope.task={project:$scope.projectId,milestone:sprintId,user_story:usId,is_archived:!1,status:$scope.project.default_task_status,assigned_to:null,tags:[]},$scope.isNew=!0,create=$translate.instant("COMMON.CREATE"),$el.find(".button-green").html(create),newTask=$translate.instant("LIGHTBOX.CREATE_EDIT_TASK.TITLE"),$el.find(".title").html(newTask+" "),$el.find(".tag-input").val(""),lightboxService.open($el)}),$scope.$on("taskform:edit",function(ctx,task){var edit,save;return $scope.task=task,$scope.isNew=!1,save=$translate.instant("COMMON.SAVE"),edit=$translate.instant("LIGHTBOX.CREATE_EDIT_TASK.ACTION_EDIT"),$el.find(".button-green").html(save),$el.find(".title").html(edit+" "),$el.find(".tag-input").val(""),lightboxService.open($el)}),submitButton=$el.find(".submit-button"),submit=debounce(2e3,function(_this){return function(event){var broadcastEvent,currentLoading,form,promise;return event.preventDefault(),form=$el.find("form").checksley(),form.validate()?($scope.isNew?(promise=$repo.create("tasks",$scope.task),broadcastEvent="taskform:new:success"):(promise=$repo.save($scope.task),broadcastEvent="taskform:edit:success"),currentLoading=$loading().target(submitButton).start(),promise.then(function(data){return currentLoading.finish(),lightboxService.close($el),$rootscope.$broadcast(broadcastEvent,data)})):void 0}}(this)),$el.on("submit","form",submit),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},CreateBulkTasksDirective=function($repo,$rs,$rootscope,$loading,lightboxService){var link;return link=function($scope,$el,attrs){var submit,submitButton;return $scope.form={data:"",usId:null},submit=debounce(2e3,function(_this){return function(event){var currentLoading,data,form,projectId,promise,sprintId,usId;return event.preventDefault(),form=$el.find("form").checksley(),form.validate()?(currentLoading=$loading().target(submitButton).start(),data=$scope.form.data,projectId=$scope.projectId,sprintId=$scope.form.sprintId,usId=$scope.form.usId,promise=$rs.tasks.bulkCreate(projectId,sprintId,usId,data),promise.then(function(result){return currentLoading.finish(),$rootscope.$broadcast("taskform:bulk:success",result),lightboxService.close($el)}),promise.then(null,function(){return currentLoading.finish(),console.log("FAIL")})):void 0}}(this)),$scope.$on("taskform:bulk",function(ctx,sprintId,usId){return lightboxService.open($el),$scope.form={data:"",sprintId:sprintId,usId:usId}}),submitButton=$el.find(".submit-button"),$el.on("submit","form",submit),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module=angular.module("taigaTaskboard"),module.directive("tgLbCreateEditTask",["$tgRepo","$tgModel","$tgResources","$rootScope","$tgLoading","lightboxService","$translate",CreateEditTaskDirective]),module.directive("tgLbCreateBulkTasks",["$tgRepo","$tgResources","$rootScope","$tgLoading","lightboxService",CreateBulkTasksDirective])}.call(this),function(){var TaskboardController,TaskboardDirective,TaskboardSquishColumnDirective,TaskboardTaskDirective,TaskboardUserDirective,bindMethods,bindOnce,groupBy,mixOf,module,scopeDefer,taiga,timeout,toggleText,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,toggleText=this.taiga.toggleText,mixOf=this.taiga.mixOf,groupBy=this.taiga.groupBy,bindOnce=this.taiga.bindOnce,scopeDefer=this.taiga.scopeDefer,timeout=this.taiga.timeout,bindMethods=this.taiga.bindMethods,module=angular.module("taigaTaskboard"),TaskboardController=function(superClass){function TaskboardController(scope,rootscope,repo,confirm,rs1,params1,q,appMetaService,location,navUrls,events,analytics,translate){var promise;this.scope=scope,this.rootscope=rootscope,this.repo=repo,this.confirm=confirm,this.rs=rs1,this.params=params1,this.q=q,this.appMetaService=appMetaService,this.location=location,this.navUrls=navUrls,this.events=events,this.analytics=analytics,this.translate=translate,bindMethods(this),this.scope.sectionName=this.translate.instant("TASKBOARD.SECTION_NAME"),this.initializeEventHandlers(),promise=this.loadInitialData(),promise.then(function(_this){return function(){return _this._setMeta()}}(this)),promise.then(null,this.onInitialDataError.bind(this))}return extend(TaskboardController,superClass),TaskboardController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","tgAppMetaService","$tgLocation","$tgNavUrls","$tgEvents","$tgAnalytics","$translate"],TaskboardController.prototype._setMeta=function(){var description,prettyDate,title;return prettyDate=this.translate.instant("BACKLOG.SPRINTS.DATE"),title=this.translate.instant("TASKBOARD.PAGE_TITLE",{projectName:this.scope.project.name,sprintName:this.scope.sprint.name}),description=this.translate.instant("TASKBOARD.PAGE_DESCRIPTION",{projectName:this.scope.project.name,sprintName:this.scope.sprint.name,startDate:moment(this.scope.sprint.estimated_start).format(prettyDate),endDate:moment(this.scope.sprint.estimated_finish).format(prettyDate),completedPercentage:this.scope.stats.completedPercentage||"0",completedPoints:this.scope.stats.completedPointsSum||"--",totalPoints:this.scope.stats.totalPointsSum||"--",openTasks:this.scope.stats.openTasks||"--",totalTasks:this.scope.stats.total_tasks||"--"}),this.appMetaService.setAll(title,description)},TaskboardController.prototype.initializeEventHandlers=function(){return this.scope.$on("taskform:bulk:success",function(_this){return function(){return _this.loadTaskboard(),_this.analytics.trackEvent("task","create","bulk create task on taskboard",1)}}(this)),this.scope.$on("taskform:new:success",function(_this){return function(){return _this.loadTaskboard(),_this.analytics.trackEvent("task","create","create task on taskboard",1)}}(this)),this.scope.$on("taskform:edit:success",function(_this){return function(){return _this.loadTaskboard()}}(this)),this.scope.$on("taskboard:task:move",this.taskMove),this.scope.$on("assigned-to:added",function(_this){return function(ctx,userId,task){var promise;return task.assigned_to=userId,promise=_this.repo.save(task),promise.then(null,function(){return console.log("FAIL")})}}(this))},TaskboardController.prototype.initializeSubscription=function(){var routingKey,routingKey1;return routingKey="changes.project."+this.scope.projectId+".tasks",this.events.subscribe(this.scope,routingKey,function(_this){return function(message){return _this.loadTaskboard()}}(this)),routingKey1="changes.project."+this.scope.projectId+".userstories",this.events.subscribe(this.scope,routingKey1,function(_this){return function(message){return _this.refreshTagsColors(),_this.loadSprintStats(),_this.loadSprint()}}(this))},TaskboardController.prototype.loadProject=function(){return this.rs.projects.get(this.scope.projectId).then(function(_this){return function(project){return project.is_backlog_activated||_this.location.path(_this.navUrls.resolve("permission-denied")),_this.scope.project=project,_this.scope.pointsList=_.sortBy(project.points,"order"),_this.scope.pointsById=groupBy(project.points,function(e){return e.id}),_this.scope.roleById=groupBy(project.roles,function(e){return e.id}),_this.scope.taskStatusList=_.sortBy(project.task_statuses,"order"),_this.scope.usStatusList=_.sortBy(project.us_statuses,"order"),_this.scope.usStatusById=groupBy(project.us_statuses,function(e){return e.id}),_this.scope.$emit("project:loaded",project),_this.fillUsersAndRoles(project.members,project.roles),project}}(this))},TaskboardController.prototype.loadSprintStats=function(){return this.rs.sprints.stats(this.scope.projectId,this.scope.sprintId).then(function(_this){return function(stats){var completedPointsSum,remainingPointsSum,remainingTasks,totalPointsSum;return totalPointsSum=_.reduce(_.values(stats.total_points),function(res,n){return res+n},0),completedPointsSum=_.reduce(_.values(stats.completed_points),function(res,n){return res+n},0),remainingPointsSum=totalPointsSum-completedPointsSum,remainingTasks=stats.total_tasks-stats.completed_tasks,_this.scope.stats=stats,_this.scope.stats.totalPointsSum=totalPointsSum,_this.scope.stats.completedPointsSum=completedPointsSum,_this.scope.stats.remainingPointsSum=remainingPointsSum,_this.scope.stats.remainingTasks=remainingTasks,stats.totalPointsSum?_this.scope.stats.completedPercentage=Math.round(100*stats.completedPointsSum/stats.totalPointsSum):_this.scope.stats.completedPercentage=0,_this.scope.stats.openTasks=stats.total_tasks-stats.completed_tasks,stats}}(this))},TaskboardController.prototype.refreshTagsColors=function(){return this.rs.projects.tagsColors(this.scope.projectId).then(function(_this){return function(tags_colors){return _this.scope.project.tags_colors=tags_colors}}(this))},TaskboardController.prototype.loadSprint=function(){return this.rs.sprints.get(this.scope.projectId,this.scope.sprintId).then(function(_this){return function(sprint){return _this.scope.sprint=sprint,_this.scope.userstories=_.sortBy(sprint.user_stories,"sprint_order"),sprint}}(this))},TaskboardController.prototype.loadTasks=function(){return this.rs.tasks.list(this.scope.projectId,this.scope.sprintId).then(function(_this){return function(tasks){var i,j,k,len,len1,len2,ref,ref1,ref2,status,task,us,usId;for(_this.scope.tasks=_.sortBy(tasks,"taskboard_order"),_this.scope.usTasks={},ref=_.union(_this.scope.userstories,[{id:null}]),i=0,len=ref.length;len>i;i++)for(us=ref[i],_this.scope.usTasks[us.id]={},ref1=_this.scope.taskStatusList,j=0,len1=ref1.length;len1>j;j++)status=ref1[j],_this.scope.usTasks[us.id][status.id]=[];for(ref2=_this.scope.tasks,k=0,len2=ref2.length;len2>k;k++)task=ref2[k],null!=_this.scope.usTasks[task.user_story]&&null!=_this.scope.usTasks[task.user_story][task.status]&&_this.scope.usTasks[task.user_story][task.status].push(task);return 0===tasks.length&&(usId=_this.scope.userstories.length>0?_this.scope.userstories[0].id:null,_this.scope.usTasks[usId][_this.scope.taskStatusList[0].id].push({isPlaceholder:!0})),tasks}}(this))},TaskboardController.prototype.loadTaskboard=function(){return this.q.all([this.refreshTagsColors(),this.loadSprintStats(),this.loadSprint().then(function(_this){return function(){return _this.loadTasks()}}(this))])},TaskboardController.prototype.loadInitialData=function(){var params,promise;return params={pslug:this.params.pslug,sslug:this.params.sslug},promise=this.repo.resolve(params).then(function(_this){return function(data){return _this.scope.projectId=data.project,_this.scope.sprintId=data.milestone,_this.initializeSubscription(),data}}(this)),promise.then(function(_this){return function(){return _this.loadProject()}}(this)).then(function(_this){return function(){return _this.loadTaskboard()}}(this))},TaskboardController.prototype.refreshTasksOrder=function(tasks){var data,items;return items=this.resortTasks(tasks),data=this.prepareBulkUpdateData(items),this.rs.tasks.bulkUpdateTaskTaskboardOrder(this.scope.project.id,data)},TaskboardController.prototype.resortTasks=function(tasks){var i,index,item,items,len;for(items=[],index=i=0,len=tasks.length;len>i;index=++i)item=tasks[index],item.taskboard_order=index,item.isModified()&&items.push(item);return items},TaskboardController.prototype.prepareBulkUpdateData=function(uses){return _.map(uses,function(x){return{task_id:x.id,order:x.taskboard_order}})},TaskboardController.prototype.taskMove=function(ctx,task,usId,statusId,order){var promise,r,tasks;return r=this.scope.usTasks[task.user_story][task.status].indexOf(task),this.scope.usTasks[task.user_story][task.status].splice(r,1),tasks=this.scope.usTasks[usId][statusId],tasks.splice(order,0,task),task.user_story=usId,task.status=statusId,task.taskboard_order=order,promise=this.repo.save(task),this.rootscope.$broadcast("sprint:task:moved",task),promise.then(function(_this){return function(){return _this.refreshTasksOrder(tasks),_this.loadSprintStats()}}(this)),promise.then(null,function(_this){return function(){return console.log("FAIL TASK SAVE")}}(this))},TaskboardController.prototype.addNewTask=function(type,us){switch(type){case"standard":return this.rootscope.$broadcast("taskform:new",this.scope.sprintId,null!=us?us.id:void 0);case"bulk":return this.rootscope.$broadcast("taskform:bulk",this.scope.sprintId,null!=us?us.id:void 0)}},TaskboardController.prototype.editTaskAssignedTo=function(task){return this.rootscope.$broadcast("assigned-to:add",task)},TaskboardController}(mixOf(taiga.Controller,taiga.PageMixin)),module.controller("TaskboardController",TaskboardController),TaskboardDirective=function($rootscope){var link;return link=function($scope,$el,$attrs){var $ctrl,tableBodyDom;return $ctrl=$el.controller(),$el.on("click",".toggle-analytics-visibility",function(event){var target;return event.preventDefault(),target=angular.element(event.currentTarget),target.toggleClass("active"),$rootscope.$broadcast("taskboard:graph:toggle-visibility")}),tableBodyDom=$el.find(".taskboard-table-body"),tableBodyDom.on("scroll",function(event){var tableHeaderDom,target;return target=angular.element(event.currentTarget),tableHeaderDom=$el.find(".taskboard-table-header .taskboard-table-inner"),tableHeaderDom.css("left",-1*target.scrollLeft())}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgTaskboard",["$rootScope",TaskboardDirective]),TaskboardTaskDirective=function($rootscope,$loading,$rs){var link;return link=function($scope,$el,$attrs,$model){return $el.disableSelection(),$scope.$watch("task",function(task){return task.is_blocked&&!$el.hasClass("blocked")?$el.addClass("blocked"):!task.is_blocked&&$el.hasClass("blocked")?$el.removeClass("blocked"):void 0}),$el.find(".icon-edit").on("click",function(event){return $el.find(".icon-edit").hasClass("noclick")?void 0:$scope.$apply(function(){var currentLoading,target,task;return target=$(event.target),currentLoading=$loading().target(target).timeout(200).removeClasses("icon-edit").start(),task=$scope.task,$rs.tasks.getByRef(task.project,task.ref).then(function(_this){return function(editingTask){return $rootscope.$broadcast("taskform:edit",editingTask),currentLoading.finish()}}(this))})})},{link:link}},module.directive("tgTaskboardTask",["$rootScope","$tgLoading","$tgResources",TaskboardTaskDirective]),TaskboardSquishColumnDirective=function(rs){var avatarWidth,link,maxColumnWidth;return avatarWidth=40,maxColumnWidth=300,link=function($scope,$el,$attrs){var getCeilWidth,recalculateStatusColumnWidth,recalculateTaskboardWidth,refreshTaskboardTableWidth,setStatusColumnWidth;return $scope.$on("sprint:task:moved",function(_this){return function(){return recalculateTaskboardWidth()}}(this)),bindOnce($scope,"usTasks",function(project){return $scope.statusesFolded=rs.tasks.getStatusColumnModes($scope.project.id),$scope.usFolded=rs.tasks.getUsRowModes($scope.project.id,$scope.sprintId),recalculateTaskboardWidth()}),$scope.foldStatus=function(status){return $scope.statusesFolded[status.id]=!$scope.statusesFolded[status.id],rs.tasks.storeStatusColumnModes($scope.projectId,$scope.statusesFolded),recalculateTaskboardWidth()},$scope.foldUs=function(us){return us?$scope.usFolded[us.id]=!$scope.usFolded[us.id]:$scope.usFolded[null]=!$scope.usFolded[null],rs.tasks.storeUsRowModes($scope.projectId,$scope.sprintId,$scope.usFolded),recalculateTaskboardWidth()},getCeilWidth=function(_this){return function(usId,statusId){var tasks,tasksMatrixSize,width;return tasks=$scope.usTasks[usId][statusId].length,$scope.statusesFolded[statusId]?(tasks&&$scope.usFolded[usId]?(tasksMatrixSize=Math.round(Math.sqrt(tasks)),width=avatarWidth*tasksMatrixSize):width=avatarWidth,width):0}}(this),setStatusColumnWidth=function(_this){return function(statusId,width){var column;return column=$el.find(".squish-status-"+statusId),width?column.css("max-width",width):column.css("max-width",maxColumnWidth)}}(this),refreshTaskboardTableWidth=function(_this){return function(){var columnWidths,columns,totalWidth;return columnWidths=[],columns=$el.find(".task-colum-name"),columnWidths=_.map(columns,function(column){return $(column).outerWidth(!0)}),totalWidth=_.reduce(columnWidths,function(total,width){return total+width}),$el.find(".taskboard-table-inner").css("width",totalWidth)}}(this),recalculateStatusColumnWidth=function(_this){return function(statusId){var statusFoldedWidth;return statusFoldedWidth=getCeilWidth(null,statusId),_.forEach($scope.userstories,function(us){var width;return width=getCeilWidth(us.id,statusId),width>statusFoldedWidth?statusFoldedWidth=width:void 0}),setStatusColumnWidth(statusId,statusFoldedWidth)}}(this),recalculateTaskboardWidth=function(_this){return function(){_.forEach($scope.taskStatusList,function(status){return recalculateStatusColumnWidth(status.id)}),refreshTaskboardTableWidth()}}(this)},{link:link}},module.directive("tgTaskboardSquishColumn",["$tgResources",TaskboardSquishColumnDirective]),TaskboardUserDirective=function($log){var clickable,link;return clickable=!1,link=function($scope,$el,$attrs){var username_label;return username_label=$el.parent().find("a.task-assigned"),username_label.addClass("not-clickable"),$scope.$watch("task.assigned_to",function(assigned_to){var user;return user=$scope.usersById[assigned_to],void 0===user?_.assign($scope,{name:"Unassigned",imgurl:"/"+window._version+"/images/unnamed.png",clickable:clickable}):_.assign($scope,{name:user.full_name_display,imgurl:user.photo,clickable:clickable}),username_label.text($scope.name)}),bindOnce($scope,"project",function(project){return project.my_permissions.indexOf("modify_task")>-1?(clickable=!0,$el.find(".avatar-assigned-to").on("click",function(_this){return function(event){var $ctrl;if(!$el.find("a").hasClass("noclick"))return $ctrl=$el.controller(),$ctrl.editTaskAssignedTo($scope.task)}}(this)),username_label.removeClass("not-clickable"),username_label.on("click",function(event){var $ctrl;if(!$el.find("a").hasClass("noclick"))return $ctrl=$el.controller(),$ctrl.editTaskAssignedTo($scope.task)})):void 0})},{link:link,templateUrl:"taskboard/taskboard-user.html",scope:{usersById:"=users",project:"=",task:"="}}},module.directive("tgTaskboardUserAvatar",["$log",TaskboardUserDirective])}.call(this),function(){var TaskboardSortableDirective,bindOnce,groupBy,mixOf,module,scopeDefer,taiga,toggleText;taiga=this.taiga,mixOf=this.taiga.mixOf,toggleText=this.taiga.toggleText,scopeDefer=this.taiga.scopeDefer,bindOnce=this.taiga.bindOnce,groupBy=this.taiga.groupBy,module=angular.module("taigaBacklog"),TaskboardSortableDirective=function($repo,$rs,$rootscope){var link;return link=function($scope,$el,$attrs){return bindOnce($scope,"project",function(project){var deleteElement,itemEl,newParentScope,oldParentScope,tdom;if(project.my_permissions.indexOf("modify_us")>-1)return oldParentScope=null,newParentScope=null,itemEl=null,tdom=$el,deleteElement=function(itemEl){return itemEl.scope().$destroy(),itemEl.off(),itemEl.remove()},tdom.sortable({handle:".taskboard-task-inner",dropOnEmpty:!0,connectWith:".taskboard-tasks-box",revert:400}),tdom.on("sortstop",function(event,ui){var itemIndex,itemTask,newStatusId,newUsId,oldStatusId,oldUsId,parentEl;return parentEl=ui.item.parent(),itemEl=ui.item,itemTask=itemEl.scope().task,itemIndex=itemEl.index(),newParentScope=parentEl.scope(),oldUsId=oldParentScope.us?oldParentScope.us.id:null,oldStatusId=oldParentScope.st.id,newUsId=newParentScope.us?newParentScope.us.id:null,newStatusId=newParentScope.st.id,(newStatusId!==oldStatusId||newUsId!==oldUsId)&&deleteElement(itemEl),$scope.$apply(function(){return $rootscope.$broadcast("taskboard:task:move",itemTask,newUsId,newStatusId,itemIndex)}),ui.item.find("a").removeClass("noclick")}),tdom.on("sortstart",function(event,ui){return oldParentScope=ui.item.parent().scope(),ui.item.find("a").addClass("noclick")})}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgTaskboardSortable",["$tgRepo","$tgResources","$rootScope",TaskboardSortableDirective])}.call(this),function(){var KanbanArchivedStatusHeaderDirective,KanbanArchivedStatusIntroDirective,KanbanController,KanbanDirective,KanbanSquishColumnDirective,KanbanUserDirective,KanbanUserstoryDirective,KanbanWipLimitDirective,bindMethods,bindOnce,defaultViewMode,groupBy,mixOf,module,scopeDefer,taiga,timeout,toggleText,viewModes,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,mixOf=this.taiga.mixOf,toggleText=this.taiga.toggleText,scopeDefer=this.taiga.scopeDefer,bindOnce=this.taiga.bindOnce,groupBy=this.taiga.groupBy,timeout=this.taiga.timeout,bindMethods=this.taiga.bindMethods,module=angular.module("taigaKanban"),defaultViewMode="maximized",viewModes=["maximized","minimized"],KanbanController=function(superClass){function KanbanController(scope,rootscope,repo,confirm,rs1,params1,q,location,appMetaService,navUrls,events,analytics,translate){var promise;this.scope=scope,this.rootscope=rootscope,this.repo=repo,this.confirm=confirm,this.rs=rs1,this.params=params1,this.q=q,this.location=location,this.appMetaService=appMetaService,this.navUrls=navUrls,this.events=events,this.analytics=analytics,this.translate=translate,bindMethods(this),this.scope.sectionName=this.translate.instant("KANBAN.SECTION_NAME"),this.scope.statusViewModes={},this.initializeEventHandlers(),promise=this.loadInitialData(),promise.then(function(_this){return function(){var description,title;return title=_this.translate.instant("KANBAN.PAGE_TITLE",{projectName:_this.scope.project.name}),description=_this.translate.instant("KANBAN.PAGE_DESCRIPTION",{projectName:_this.scope.project.name,projectDescription:_this.scope.project.description}),_this.appMetaService.setAll(title,description)}}(this)),promise.then(null,this.onInitialDataError.bind(this))}return extend(KanbanController,superClass),KanbanController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","tgAppMetaService","$tgNavUrls","$tgEvents","$tgAnalytics","$translate"],KanbanController.prototype.initializeEventHandlers=function(){return this.scope.$on("usform:new:success",function(_this){return function(){return _this.loadUserstories(),_this.refreshTagsColors(),_this.analytics.trackEvent("userstory","create","create userstory on kanban",1)}}(this)),this.scope.$on("usform:bulk:success",function(_this){return function(){return _this.loadUserstories(),_this.analytics.trackEvent("userstory","create","bulk create userstory on kanban",1)}}(this)),this.scope.$on("usform:edit:success",function(_this){return function(){return _this.loadUserstories(),_this.refreshTagsColors()}}(this)),this.scope.$on("assigned-to:added",this.onAssignedToChanged),this.scope.$on("kanban:us:move",this.moveUs),this.scope.$on("kanban:show-userstories-for-status",this.loadUserStoriesForStatus),this.scope.$on("kanban:hide-userstories-for-status",this.hideUserStoriesForStatus)},KanbanController.prototype.addNewUs=function(type,statusId){switch(type){case"standard":return this.rootscope.$broadcast("usform:new",this.scope.projectId,statusId,this.scope.usStatusList);case"bulk":return this.rootscope.$broadcast("usform:bulk",this.scope.projectId,statusId)}},KanbanController.prototype.changeUsAssignedTo=function(us){return this.rootscope.$broadcast("assigned-to:add",us)},KanbanController.prototype.onAssignedToChanged=function(ctx,userid,us){var promise;return us.assigned_to=userid,promise=this.repo.save(us),promise.then(null,function(){return console.log("FAIL")})},KanbanController.prototype.refreshTagsColors=function(){return this.rs.projects.tagsColors(this.scope.projectId).then(function(_this){return function(tags_colors){return _this.scope.project.tags_colors=tags_colors}}(this))},KanbanController.prototype.loadUserstories=function(){var params,promise;return params={status__is_archived:!1},promise=this.rs.userstories.listAll(this.scope.projectId,params).then(function(_this){ -return function(userstories){var i,j,k,len,len1,len2,ref,ref1,ref2,status,us,usByStatus,us_archived;for(_this.scope.userstories=userstories,usByStatus=_.groupBy(userstories,"status"),us_archived=[],ref=_this.scope.usStatusList,i=0,len=ref.length;len>i;i++){if(status=ref[i],null==usByStatus[status.id]&&(usByStatus[status.id]=[]),null!=_this.scope.usByStatus)for(ref1=_this.scope.usByStatus[status.id],j=0,len1=ref1.length;len1>j;j++)us=ref1[j],us.status!==status.id&&us_archived.push(us);if(status.is_archived&&null!=_this.scope.usByStatus&&0!==_this.scope.usByStatus[status.id].length)for(ref2=_this.scope.usByStatus[status.id].concat(us_archived),k=0,len2=ref2.length;len2>k;k++)us=ref2[k],us.status===status.id&&usByStatus[status.id].push(us);usByStatus[status.id]=_.sortBy(usByStatus[status.id],"kanban_order")}return 0===userstories.length&&(status=_this.scope.usStatusList[0],usByStatus[status.id].push({isPlaceholder:!0})),_this.scope.usByStatus=usByStatus,scopeDefer(_this.scope,function(){return _this.scope.$broadcast("userstories:loaded",userstories)}),userstories}}(this)),promise.then(function(_this){return function(){return _this.scope.$broadcast("redraw:wip")}}(this)),promise},KanbanController.prototype.loadUserStoriesForStatus=function(ctx,statusId){var params;return params={status:statusId},this.rs.userstories.listAll(this.scope.projectId,params).then(function(_this){return function(userstories){return _this.scope.usByStatus[statusId]=_.sortBy(userstories,"kanban_order"),_this.scope.$broadcast("kanban:shown-userstories-for-status",statusId,userstories),userstories}}(this))},KanbanController.prototype.hideUserStoriesForStatus=function(ctx,statusId){return this.scope.usByStatus[statusId]=[],this.scope.$broadcast("kanban:hidden-userstories-for-status",statusId)},KanbanController.prototype.loadKanban=function(){return this.q.all([this.refreshTagsColors(),this.loadUserstories()])},KanbanController.prototype.loadProject=function(){return this.rs.projects.getBySlug(this.params.pslug).then(function(_this){return function(project){return project.is_kanban_activated||_this.location.path(_this.navUrls.resolve("permission-denied")),_this.scope.projectId=project.id,_this.scope.project=project,_this.scope.projectId=project.id,_this.scope.points=_.sortBy(project.points,"order"),_this.scope.pointsById=groupBy(project.points,function(x){return x.id}),_this.scope.usStatusById=groupBy(project.us_statuses,function(x){return x.id}),_this.scope.usStatusList=_.sortBy(project.us_statuses,"order"),_this.generateStatusViewModes(),_this.scope.$emit("project:loaded",project),project}}(this))},KanbanController.prototype.initializeSubscription=function(){var routingKey1;return routingKey1="changes.project."+this.scope.projectId+".userstories",this.events.subscribe(this.scope,routingKey1,function(_this){return function(message){return _this.loadUserstories()}}(this))},KanbanController.prototype.loadInitialData=function(){var promise;return promise=this.loadProject(),promise.then(function(_this){return function(project){return _this.fillUsersAndRoles(project.members,project.roles),_this.initializeSubscription(),_this.loadKanban()}}(this))},KanbanController.prototype.generateStatusViewModes=function(){var i,len,mode,ref,status,storedStatusViewModes;for(storedStatusViewModes=this.rs.kanban.getStatusViewModes(this.scope.projectId),this.scope.statusViewModes={},ref=this.scope.usStatusList,i=0,len=ref.length;len>i;i++)status=ref[i],mode=storedStatusViewModes[status.id]||defaultViewMode,this.scope.statusViewModes[status.id]=mode;return this.storeStatusViewModes()},KanbanController.prototype.storeStatusViewModes=function(){return this.rs.kanban.storeStatusViewModes(this.scope.projectId,this.scope.statusViewModes)},KanbanController.prototype.updateStatusViewMode=function(statusId,newViewMode){return this.scope.statusViewModes[statusId]=newViewMode,this.storeStatusViewModes()},KanbanController.prototype.isMaximized=function(statusId){var mode;return mode=this.scope.statusViewModes[statusId]||defaultViewMode,"maximized"===mode},KanbanController.prototype.isMinimized=function(statusId){var mode;return mode=this.scope.statusViewModes[statusId]||defaultViewMode,"minimized"===mode},KanbanController.prototype.prepareBulkUpdateData=function(uses,field){return null==field&&(field="kanban_order"),_.map(uses,function(x){return{us_id:x.id,order:x[field]}})},KanbanController.prototype.resortUserStories=function(uses){var i,index,item,items,len;for(items=[],index=i=0,len=uses.length;len>i;index=++i)item=uses[index],item.kanban_order=index,item.isModified()&&items.push(item);return items},KanbanController.prototype.moveUs=function(ctx,us,oldStatusId,newStatusId,index){var itemsToSave,promise,r;return oldStatusId!==newStatusId?(r=this.scope.usByStatus[oldStatusId].indexOf(us),this.scope.usByStatus[oldStatusId].splice(r,1),this.scope.usByStatus[newStatusId].splice(index,0,us),us.status=newStatusId):(r=this.scope.usByStatus[newStatusId].indexOf(us),this.scope.usByStatus[newStatusId].splice(r,1),this.scope.usByStatus[newStatusId].splice(index,0,us)),itemsToSave=this.resortUserStories(this.scope.usByStatus[newStatusId]),this.scope.usByStatus[newStatusId]=_.sortBy(this.scope.usByStatus[newStatusId],"kanban_order"),promise=this.repo.save(us),promise=promise.then(function(_this){return function(){var data;return itemsToSave=_.reject(itemsToSave,{id:us.id}),data=_this.prepareBulkUpdateData(itemsToSave),_this.rs.userstories.bulkUpdateKanbanOrder(us.project,data).then(function(){return itemsToSave})}}(this))},KanbanController}(mixOf(taiga.Controller,taiga.PageMixin,taiga.FiltersMixin)),module.controller("KanbanController",KanbanController),KanbanDirective=function($repo,$rootscope){var link;return link=function($scope,$el,$attrs){var tableBodyDom;return tableBodyDom=$el.find(".kanban-table-body"),tableBodyDom.on("scroll",function(event){var tableHeaderDom,target;return target=angular.element(event.currentTarget),tableHeaderDom=$el.find(".kanban-table-header .kanban-table-inner"),tableHeaderDom.css("left",-1*target.scrollLeft())}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgKanban",["$tgRepo","$rootScope",KanbanDirective]),KanbanArchivedStatusHeaderDirective=function($rootscope,$translate){var hideArchivedText,link,showArchivedText;return showArchivedText=$translate.instant("KANBAN.ACTION_SHOW_ARCHIVED"),hideArchivedText=$translate.instant("KANBAN.ACTION_HIDE_ARCHIVED"),link=function($scope,$el,$attrs){var hidden,status;return status=$scope.$eval($attrs.tgKanbanArchivedStatusHeader),hidden=!0,$scope["class"]="icon-open-eye",$scope.title=showArchivedText,$el.on("click",function(event){return hidden=!hidden,$scope.$apply(function(){return hidden?($scope["class"]="icon-open-eye",$scope.title=showArchivedText,$rootscope.$broadcast("kanban:hide-userstories-for-status",status.id)):($scope["class"]="icon-closed-eye",$scope.title=hideArchivedText,$rootscope.$broadcast("kanban:show-userstories-for-status",status.id))})}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgKanbanArchivedStatusHeader",["$rootScope","$translate",KanbanArchivedStatusHeaderDirective]),KanbanArchivedStatusIntroDirective=function($translate){var link,userStories;return userStories=[],link=function($scope,$el,$attrs){var hiddenUserStoriexText,status,updateIntroText;return hiddenUserStoriexText=$translate.instant("KANBAN.HIDDEN_USER_STORIES"),status=$scope.$eval($attrs.tgKanbanArchivedStatusIntro),$el.text(hiddenUserStoriexText),updateIntroText=function(){return userStories.length>0?$el.text(""):$el.text(hiddenUserStoriexText)},$scope.$on("kanban:us:move",function(ctx,itemUs,oldStatusId,newStatusId,itemIndex){var r;return status.id===newStatusId?status.id===oldStatusId?(r=userStories.indexOf(itemUs),userStories.splice(r,1),userStories.splice(itemIndex,0,itemUs)):(itemUs.isArchived=!0,userStories.splice(itemIndex,0,itemUs)):status.id===oldStatusId&&(itemUs.isArchived=!1,r=userStories.indexOf(itemUs),userStories.splice(r,1)),updateIntroText()}),$scope.$on("kanban:shown-userstories-for-status",function(ctx,statusId,userStoriesLoaded){return statusId===status.id?(userStories=_.filter(userStoriesLoaded,function(us){return us.status===status.id}),updateIntroText()):void 0}),$scope.$on("kanban:hidden-userstories-for-status",function(ctx,statusId){return statusId===status.id?(userStories=[],updateIntroText()):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgKanbanArchivedStatusIntro",["$translate",KanbanArchivedStatusIntroDirective]),KanbanUserstoryDirective=function($rootscope,$loading,$rs){var link;return link=function($scope,$el,$attrs,$model){return $el.disableSelection(),$scope.$watch("us",function(us){return us.is_blocked&&!$el.hasClass("blocked")?$el.addClass("blocked"):!us.is_blocked&&$el.hasClass("blocked")?$el.removeClass("blocked"):void 0}),$el.on("click",".icon-edit",function(event){var currentLoading,target,us;if(!$el.find(".icon-edit").hasClass("noclick"))return target=$(event.target),currentLoading=$loading().target(target).timeout(200).removeClasses("icon-edit").start(),us=$model.$modelValue,$rs.userstories.getByRef(us.project,us.ref).then(function(_this){return function(editingUserStory){return $rootscope.$broadcast("usform:edit",editingUserStory),currentLoading.finish()}}(this))}),$scope.getTemplateUrl=function(){return $scope.us.isPlaceholder?"common/components/kanban-placeholder.html":"kanban/kanban-task.html"},$scope.$on("$destroy",function(){return $el.off()})},{template:'',link:link,require:"ngModel"}},module.directive("tgKanbanUserstory",["$rootScope","$tgLoading","$tgResources",KanbanUserstoryDirective]),KanbanSquishColumnDirective=function(rs){var link;return link=function($scope,$el,$attrs){var updateTableWidth;return $scope.$on("project:loaded",function(event,project){return $scope.folds=rs.kanban.getStatusColumnModes(project.id),updateTableWidth()}),$scope.foldStatus=function(status){$scope.folds[status.id]=!$scope.folds[status.id],rs.kanban.storeStatusColumnModes($scope.projectId,$scope.folds),updateTableWidth()},updateTableWidth=function(){var columnWidths,totalWidth;return columnWidths=_.map($scope.usStatusList,function(status){return $scope.folds[status.id]?40:310}),totalWidth=_.reduce(columnWidths,function(total,width){return total+width}),$el.find(".kanban-table-inner").css("width",totalWidth)}},{link:link}},module.directive("tgKanbanSquishColumn",["$tgResources",KanbanSquishColumnDirective]),KanbanWipLimitDirective=function(){var link;return link=function($scope,$el,$attrs){var redrawWipLimit,status;return $el.disableSelection(),status=$scope.$eval($attrs.tgKanbanWipLimit),redrawWipLimit=function(_this){return function(){return $el.find(".kanban-wip-limit").remove(),timeout(200,function(){var element;return element=$el.find(".kanban-task")[status.wip_limit],element?angular.element(element).before("
"):void 0})}}(this),status&&!status.is_archived&&($scope.$on("redraw:wip",redrawWipLimit),$scope.$on("kanban:us:move",redrawWipLimit),$scope.$on("usform:new:success",redrawWipLimit),$scope.$on("usform:bulk:success",redrawWipLimit)),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgKanbanWipLimit",KanbanWipLimitDirective),KanbanUserDirective=function($log,$compile){var clickable,link,template;return template=_.template('
\n class="not-clickable"<% } %>>\n <%- name %>\n \n
'),clickable=!1,link=function($scope,$el,$attrs,$model){var render,username_label,wtid;return username_label=$el.parent().find("a.task-assigned"),username_label.addClass("not-clickable"),$attrs.tgKanbanUserAvatar?(wtid=$scope.$watch($attrs.tgKanbanUserAvatar,function(v){var user;return null==$scope.usersById?($log.error("KanbanUserDirective requires userById set in scope."),wtid()):(user=$scope.usersById[v],render(user))}),render=function(user){var ctx,html;return ctx=void 0===user?{name:"Unassigned",imgurl:"/"+window._version+"/images/unnamed.png",clickable:clickable}:{name:user.full_name_display,imgurl:user.photo,clickable:clickable},html=$compile(template(ctx))($scope),$el.html(html),username_label.text(ctx.name)},bindOnce($scope,"project",function(project){return project.my_permissions.indexOf("modify_us")>-1?(clickable=!0,$el.on("click",function(_this){return function(event){var $ctrl,us;if(!$el.find("a").hasClass("noclick"))return us=$model.$modelValue,$ctrl=$el.controller(),$ctrl.changeUsAssignedTo(us)}}(this)),username_label.removeClass("not-clickable"),username_label.on("click",function(event){var $ctrl,us;if(!$el.find("a").hasClass("noclick"))return us=$model.$modelValue,$ctrl=$el.controller(),$ctrl.changeUsAssignedTo(us)})):void 0}),$scope.$on("$destroy",function(){return $el.off()})):$log.error("KanbanUserDirective: no attr is defined")},{link:link,require:"ngModel"}},module.directive("tgKanbanUserAvatar",["$log","$compile",KanbanUserDirective])}.call(this),function(){var KanbanSortableDirective,bindOnce,groupBy,mixOf,module,scopeDefer,taiga,timeout,toggleText;taiga=this.taiga,mixOf=this.taiga.mixOf,toggleText=this.taiga.toggleText,scopeDefer=this.taiga.scopeDefer,bindOnce=this.taiga.bindOnce,groupBy=this.taiga.groupBy,timeout=this.taiga.timeout,module=angular.module("taigaKanban"),KanbanSortableDirective=function($repo,$rs,$rootscope){var link;return link=function($scope,$el,$attrs){return bindOnce($scope,"project",function(project){var deleteElement,itemEl,newParentScope,oldParentScope,tdom;if(project.my_permissions.indexOf("modify_us")>-1)return oldParentScope=null,newParentScope=null,itemEl=null,tdom=$el,deleteElement=function(itemEl){return itemEl.scope().$destroy(),itemEl.off(),itemEl.remove()},tdom.sortable({handle:".kanban-task-inner",dropOnEmpty:!0,connectWith:".kanban-uses-box",revert:400}),tdom.on("sortstop",function(event,ui){var itemIndex,itemUs,newStatusId,oldStatusId,parentEl;return parentEl=ui.item.parent(),itemEl=ui.item,itemUs=itemEl.scope().us,itemIndex=itemEl.index(),newParentScope=parentEl.scope(),newStatusId=newParentScope.s.id,oldStatusId=oldParentScope.s.id,newStatusId!==oldStatusId&&deleteElement(itemEl),$scope.$apply(function(){return $rootscope.$broadcast("kanban:us:move",itemUs,itemUs.status,newStatusId,itemIndex)}),ui.item.find("a").removeClass("noclick")}),tdom.on("sortstart",function(event,ui){return oldParentScope=ui.item.parent().scope(),ui.item.find("a").addClass("noclick")})}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgKanbanSortable",["$tgRepo","$tgResources","$rootScope",KanbanSortableDirective])}.call(this),function(){var IssueDetailController,IssuePriorityButtonDirective,IssueSeverityButtonDirective,IssueStatusButtonDirective,IssueStatusDisplayDirective,IssueTypeButtonDirective,PromoteIssueToUsButtonDirective,bindMethods,bindOnce,groupBy,joinStr,mixOf,module,taiga,toString,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,mixOf=this.taiga.mixOf,toString=this.taiga.toString,joinStr=this.taiga.joinStr,groupBy=this.taiga.groupBy,bindOnce=this.taiga.bindOnce,bindMethods=this.taiga.bindMethods,module=angular.module("taigaIssues"),IssueDetailController=function(superClass){function IssueDetailController(scope,rootscope,repo,confirm,rs,params,q,location,log,appMetaService,analytics,navUrls,translate){var promise;this.scope=scope,this.rootscope=rootscope,this.repo=repo,this.confirm=confirm,this.rs=rs,this.params=params,this.q=q,this.location=location,this.log=log,this.appMetaService=appMetaService,this.analytics=analytics,this.navUrls=navUrls,this.translate=translate,bindMethods(this),this.scope.issueRef=this.params.issueref,this.scope.sectionName=this.translate.instant("ISSUES.SECTION_NAME"),this.initializeEventHandlers(),promise=this.loadInitialData(),promise.then(function(_this){return function(){return _this._setMeta(),_this.initializeOnDeleteGoToUrl()}}(this)),promise.then(null,this.onInitialDataError.bind(this))}return extend(IssueDetailController,superClass),IssueDetailController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","$log","tgAppMetaService","$tgAnalytics","$tgNavUrls","$translate"],IssueDetailController.prototype._setMeta=function(){var description,ref,ref1,ref2,ref3,title;return title=this.translate.instant("ISSUE.PAGE_TITLE",{issueRef:"#"+this.scope.issue.ref,issueSubject:this.scope.issue.subject,projectName:this.scope.project.name}),description=this.translate.instant("ISSUE.PAGE_DESCRIPTION",{issueStatus:(null!=(ref=this.scope.statusById[this.scope.issue.status])?ref.name:void 0)||"--",issueType:(null!=(ref1=this.scope.typeById[this.scope.issue.type])?ref1.name:void 0)||"--",issueSeverity:(null!=(ref2=this.scope.severityById[this.scope.issue.severity])?ref2.name:void 0)||"--",issuePriority:(null!=(ref3=this.scope.priorityById[this.scope.issue.priority])?ref3.name:void 0)||"--",issueDescription:angular.element(this.scope.issue.description_html||"").text()}),this.appMetaService.setAll(title,description)},IssueDetailController.prototype.initializeEventHandlers=function(){return this.scope.$on("attachment:create",function(_this){return function(){return _this.analytics.trackEvent("attachment","create","create attachment on issue",1)}}(this)),this.scope.$on("promote-issue-to-us:success",function(_this){return function(){return _this.analytics.trackEvent("issue","promoteToUserstory","promote issue to userstory",1),_this.rootscope.$broadcast("object:updated"),_this.loadIssue()}}(this)),this.scope.$on("comment:new",function(_this){return function(){return _this.loadIssue()}}(this)),this.scope.$on("custom-attributes-values:edit",function(_this){return function(){return _this.rootscope.$broadcast("object:updated")}}(this))},IssueDetailController.prototype.initializeOnDeleteGoToUrl=function(){var ctx;return ctx={project:this.scope.project.slug},this.scope.project.is_issues_activated?this.scope.onDeleteGoToUrl=this.navUrls.resolve("project-issues",ctx):this.scope.onDeleteGoToUrl=this.navUrls.resolve("project",ctx)},IssueDetailController.prototype.loadProject=function(){return this.rs.projects.getBySlug(this.params.pslug).then(function(_this){return function(project){return _this.scope.projectId=project.id,_this.scope.project=project,_this.scope.$emit("project:loaded",project),_this.scope.statusList=project.issue_statuses,_this.scope.statusById=groupBy(project.issue_statuses,function(x){return x.id}),_this.scope.typeById=groupBy(project.issue_types,function(x){return x.id}),_this.scope.typeList=_.sortBy(project.issue_types,"order"),_this.scope.severityList=project.severities,_this.scope.severityById=groupBy(project.severities,function(x){return x.id}),_this.scope.priorityList=project.priorities,_this.scope.priorityById=groupBy(project.priorities,function(x){return x.id}),project}}(this))},IssueDetailController.prototype.loadIssue=function(){return this.rs.issues.getByRef(this.scope.projectId,this.params.issueref).then(function(_this){return function(issue){var ctx,ref,ref1;return _this.scope.issue=issue,_this.scope.issueId=issue.id,_this.scope.commentModel=issue,null!=(null!=(ref=_this.scope.issue.neighbors.previous)?ref.ref:void 0)&&(ctx={project:_this.scope.project.slug,ref:_this.scope.issue.neighbors.previous.ref},_this.scope.previousUrl=_this.navUrls.resolve("project-issues-detail",ctx)),null!=(null!=(ref1=_this.scope.issue.neighbors.next)?ref1.ref:void 0)?(ctx={project:_this.scope.project.slug,ref:_this.scope.issue.neighbors.next.ref},_this.scope.nextUrl=_this.navUrls.resolve("project-issues-detail",ctx)):void 0}}(this))},IssueDetailController.prototype.loadInitialData=function(){var promise;return promise=this.loadProject(),promise.then(function(_this){return function(project){return _this.fillUsersAndRoles(project.members,project.roles),_this.loadIssue()}}(this))},IssueDetailController.prototype.onUpvote=function(){var onError,onSuccess;return onSuccess=function(_this){return function(){return _this.loadIssue(),_this.rootscope.$broadcast("object:updated")}}(this),onError=function(_this){return function(){return _this.confirm.notify("error")}}(this),this.rs.issues.upvote(this.scope.issueId).then(onSuccess,onError)},IssueDetailController.prototype.onDownvote=function(){var onError,onSuccess;return onSuccess=function(_this){return function(){return _this.loadIssue(),_this.rootscope.$broadcast("object:updated")}}(this),onError=function(_this){return function(){return _this.confirm.notify("error")}}(this),this.rs.issues.downvote(this.scope.issueId).then(onSuccess,onError)},IssueDetailController.prototype.onWatch=function(){var onError,onSuccess;return onSuccess=function(_this){return function(){return _this.loadIssue(),_this.rootscope.$broadcast("object:updated")}}(this),onError=function(_this){return function(){return _this.confirm.notify("error")}}(this),this.rs.issues.watch(this.scope.issueId).then(onSuccess,onError)},IssueDetailController.prototype.onUnwatch=function(){var onError,onSuccess;return onSuccess=function(_this){return function(){return _this.loadIssue(),_this.rootscope.$broadcast("object:updated")}}(this),onError=function(_this){return function(){return _this.confirm.notify("error")}}(this),this.rs.issues.unwatch(this.scope.issueId).then(onSuccess,onError)},IssueDetailController}(mixOf(taiga.Controller,taiga.PageMixin)),module.controller("IssueDetailController",IssueDetailController),IssueStatusDisplayDirective=function($template,$compile){var link,template;return template=$template.get("common/components/status-display.html",!0),link=function($scope,$el,$attrs){var render;return render=function(issue){var html,status;return status=$scope.statusById[issue.status],html=template({is_closed:status.is_closed,status:status}),html=$compile(html)($scope),$el.html(html)},$scope.$watch($attrs.ngModel,function(issue){return null!=issue?render(issue):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,restrict:"EA",require:"ngModel"}},module.directive("tgIssueStatusDisplay",["$tgTemplate","$compile",IssueStatusDisplayDirective]),IssueStatusButtonDirective=function($rootScope,$repo,$confirm,$loading,$qqueue,$template,$compile){var link,template;return template=$template.get("issue/issues-status-button.html",!0),link=function($scope,$el,$attrs,$model){var isEditable,render,save;return isEditable=function(){return-1!==$scope.project.my_permissions.indexOf("modify_issue")},render=function(_this){return function(issue){var html,status;return status=$scope.statusById[issue.status],html=template({status:status,statuses:$scope.statusList,editable:isEditable()}),html=$compile(html)($scope),$el.html(html)}}(this),save=$qqueue.bindAdd(function(_this){return function(statusId){var currentLoading,issue,onError,onSuccess;return $.fn.popover().closeAll(),issue=$model.$modelValue.clone(),issue.status=statusId,currentLoading=$loading().target($el.find(".level-name")).start(),onSuccess=function(){return $confirm.notify("success"),$model.$setViewValue(issue),$rootScope.$broadcast("object:updated"),currentLoading.finish()},onError=function(){return $confirm.notify("error"),issue.revert(),$model.$setViewValue(issue),currentLoading.finish()},$repo.save(issue).then(onSuccess,onError)}}(this)),$el.on("click",".status-data",function(event){return event.preventDefault(),event.stopPropagation(),isEditable()?$el.find(".pop-status").popover().open():void 0}),$el.on("click",".status",function(event){var target;return event.preventDefault(),event.stopPropagation(),isEditable()?(target=angular.element(event.currentTarget),save(target.data("status-id"))):void 0}),$scope.$watch($attrs.ngModel,function(issue){return issue?render(issue):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,restrict:"EA",require:"ngModel"}},module.directive("tgIssueStatusButton",["$rootScope","$tgRepo","$tgConfirm","$tgLoading","$tgQqueue","$tgTemplate","$compile",IssueStatusButtonDirective]),IssueTypeButtonDirective=function($rootScope,$repo,$confirm,$loading,$qqueue,$template,$compile){var link,template;return template=$template.get("issue/issue-type-button.html",!0),link=function($scope,$el,$attrs,$model){var isEditable,render,save;return isEditable=function(){return-1!==$scope.project.my_permissions.indexOf("modify_issue")},render=function(_this){return function(issue){var html,type;return type=$scope.typeById[issue.type],html=template({type:type,typees:$scope.typeList,editable:isEditable()}),html=$compile(html)($scope),$el.html(html)}}(this),save=$qqueue.bindAdd(function(_this){return function(type){var currentLoading,issue,onError,onSuccess;return $.fn.popover().closeAll(),issue=$model.$modelValue.clone(),issue.type=type,currentLoading=$loading().target($el.find(".level-name")).start(),onSuccess=function(){return $confirm.notify("success"),$model.$setViewValue(issue),$rootScope.$broadcast("object:updated"),currentLoading.finish()},onError=function(){return $confirm.notify("error"),issue.revert(),$model.$setViewValue(issue),currentLoading.finish()},$repo.save(issue).then(onSuccess,onError)}}(this)),$el.on("click",".type-data",function(event){return event.preventDefault(),event.stopPropagation(),isEditable()?$el.find(".pop-type").popover().open():void 0}),$el.on("click",".type",function(event){var target,type;return event.preventDefault(),event.stopPropagation(),isEditable()?(target=angular.element(event.currentTarget),type=target.data("type-id"),save(type)):void 0}),$scope.$watch($attrs.ngModel,function(issue){return issue?render(issue):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,restrict:"EA",require:"ngModel"}},module.directive("tgIssueTypeButton",["$rootScope","$tgRepo","$tgConfirm","$tgLoading","$tgQqueue","$tgTemplate","$compile",IssueTypeButtonDirective]),IssueSeverityButtonDirective=function($rootScope,$repo,$confirm,$loading,$qqueue,$template,$compile){var link,template;return template=$template.get("issue/issue-severity-button.html",!0),link=function($scope,$el,$attrs,$model){var isEditable,render,save;return isEditable=function(){return-1!==$scope.project.my_permissions.indexOf("modify_issue")},render=function(_this){return function(issue){var html,severity;return severity=$scope.severityById[issue.severity],html=template({severity:severity,severityes:$scope.severityList,editable:isEditable()}),html=$compile(html)($scope),$el.html(html)}}(this),save=$qqueue.bindAdd(function(_this){return function(severity){var currentLoading,issue,onError,onSuccess;return $.fn.popover().closeAll(),issue=$model.$modelValue.clone(),issue.severity=severity,currentLoading=$loading().target($el.find(".level-name")).start(),onSuccess=function(){return $confirm.notify("success"),$model.$setViewValue(issue),$rootScope.$broadcast("object:updated"),currentLoading.finish()},onError=function(){return $confirm.notify("error"),issue.revert(),$model.$setViewValue(issue),currentLoading.finish()},$repo.save(issue).then(onSuccess,onError)}}(this)),$el.on("click",".severity-data",function(event){return event.preventDefault(),event.stopPropagation(),isEditable()?$el.find(".pop-severity").popover().open():void 0}),$el.on("click",".severity",function(event){var severity,target;return event.preventDefault(),event.stopPropagation(),isEditable()?(target=angular.element(event.currentTarget),severity=target.data("severity-id"),save(severity)):void 0}),$scope.$watch($attrs.ngModel,function(issue){return issue?render(issue):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,restrict:"EA",require:"ngModel"}},module.directive("tgIssueSeverityButton",["$rootScope","$tgRepo","$tgConfirm","$tgLoading","$tgQqueue","$tgTemplate","$compile",IssueSeverityButtonDirective]),IssuePriorityButtonDirective=function($rootScope,$repo,$confirm,$loading,$qqueue,$template,$compile){var link,template;return template=$template.get("issue/issue-priority-button.html",!0),link=function($scope,$el,$attrs,$model){var isEditable,render,save;return isEditable=function(){return-1!==$scope.project.my_permissions.indexOf("modify_issue")},render=function(_this){return function(issue){var html,priority;return priority=$scope.priorityById[issue.priority],html=template({priority:priority,priorityes:$scope.priorityList,editable:isEditable()}),html=$compile(html)($scope),$el.html(html)}}(this),save=$qqueue.bindAdd(function(_this){return function(priority){var currentLoading,issue,onError,onSuccess;return $.fn.popover().closeAll(),issue=$model.$modelValue.clone(),issue.priority=priority,currentLoading=$loading().target($el.find(".level-name")).start(),onSuccess=function(){return $confirm.notify("success"),$model.$setViewValue(issue),$rootScope.$broadcast("object:updated"),currentLoading.finish()},onError=function(){return $confirm.notify("error"),issue.revert(),$model.$setViewValue(issue),currentLoading.finish()},$repo.save(issue).then(onSuccess,onError)}}(this)),$el.on("click",".priority-data",function(event){return event.preventDefault(),event.stopPropagation(),isEditable()?$el.find(".pop-priority").popover().open():void 0}),$el.on("click",".priority",function(event){var priority,target;return event.preventDefault(),event.stopPropagation(),isEditable()?(target=angular.element(event.currentTarget),priority=target.data("priority-id"),save(priority)):void 0}),$scope.$watch($attrs.ngModel,function(issue){return issue?render(issue):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,restrict:"EA",require:"ngModel"}},module.directive("tgIssuePriorityButton",["$rootScope","$tgRepo","$tgConfirm","$tgLoading","$tgQqueue","$tgTemplate","$compile",IssuePriorityButtonDirective]),PromoteIssueToUsButtonDirective=function($rootScope,$repo,$confirm,$qqueue,$translate){var link;return link=function($scope,$el,$attrs,$model){var save;return save=$qqueue.bindAdd(function(_this){return function(issue,askResponse){var data,onError,onSuccess;return data={generated_from_issue:issue.id,project:issue.project,subject:issue.subject,description:issue.description,tags:issue.tags,is_blocked:issue.is_blocked,blocked_note:issue.blocked_note},onSuccess=function(){return askResponse.finish(),$confirm.notify("success"),$rootScope.$broadcast("promote-issue-to-us:success")},onError=function(){return askResponse.finish(),$confirm.notify("error")},$repo.create("userstories",data).then(onSuccess,onError)}}(this)),$el.on("click","a",function(event){var issue,message,subtitle,title;return event.preventDefault(),issue=$model.$modelValue,title=$translate.instant("ISSUES.CONFIRM_PROMOTE.TITLE"),message=$translate.instant("ISSUES.CONFIRM_PROMOTE.MESSAGE"),subtitle=issue.subject,$confirm.ask(title,subtitle,message).then(function(_this){return function(response){return save(issue,response)}}(this))}),$scope.$on("$destroy",function(){return $el.off()})},{restrict:"AE",require:"ngModel",templateUrl:"issue/promote-issue-to-us-button.html",link:link}},module.directive("tgPromoteIssueToUsButton",["$rootScope","$tgRepo","$tgConfirm","$tgQqueue","$translate",PromoteIssueToUsButtonDirective])}.call(this),function(){var CreateBulkIssuesDirective,CreateIssueDirective,bindOnce,debounce,module,taiga;taiga=this.taiga,bindOnce=this.taiga.bindOnce,debounce=this.taiga.debounce,module=angular.module("taigaIssues"),CreateIssueDirective=function($repo,$confirm,$rootscope,lightboxService,$loading){var link;return link=function($scope,$el,$attrs){var form,submit,submitButton;return form=$el.find("form").checksley(),$scope.issue={},$scope.$on("issueform:new",function(ctx,project){return $el.find(".tag-input").val(""), -lightboxService.open($el),$scope.issue={project:project.id,subject:"",status:project.default_issue_status,type:project.default_issue_type,priority:project.default_priority,severity:project.default_severity,tags:[]}}),$scope.$on("$destroy",function(){return $el.off()}),submit=debounce(2e3,function(_this){return function(event){var currentLoading,promise;return event.preventDefault(),form.validate()?(currentLoading=$loading().target(submitButton).start(),promise=$repo.create("issues",$scope.issue),promise.then(function(data){return currentLoading.finish(),$rootscope.$broadcast("issueform:new:success",data),lightboxService.close($el),$confirm.notify("success")}),promise.then(null,function(){return currentLoading.finish(),$confirm.notify("error")})):void 0}}(this)),submitButton=$el.find(".submit-button"),$el.on("submit","form",submit)},{link:link}},module.directive("tgLbCreateIssue",["$tgRepo","$tgConfirm","$rootScope","lightboxService","$tgLoading",CreateIssueDirective]),CreateBulkIssuesDirective=function($repo,$rs,$confirm,$rootscope,$loading,lightboxService){var link;return link=function($scope,$el,attrs){var submit,submitButton;return $scope.$on("issueform:bulk",function(ctx,projectId,status){return lightboxService.open($el),$scope["new"]={projectId:projectId,bulk:""}}),submit=debounce(2e3,function(_this){return function(event){var currentLoading,data,form,projectId,promise;return event.preventDefault(),form=$el.find("form").checksley(),form.validate()?(currentLoading=$loading().target(submitButton).start(),data=$scope["new"].bulk,projectId=$scope["new"].projectId,promise=$rs.issues.bulkCreate(projectId,data),promise.then(function(result){return currentLoading.finish(),$rootscope.$broadcast("issueform:new:success",result),lightboxService.close($el),$confirm.notify("success")}),promise.then(null,function(){return currentLoading.finish(),$confirm.notify("error")})):void 0}}(this)),submitButton=$el.find(".submit-button"),$el.on("submit","form",submit),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgLbCreateBulkIssues",["$tgRepo","$tgResources","$tgConfirm","$rootScope","$tgLoading","lightboxService",CreateBulkIssuesDirective])}.call(this),function(){var IssueAssignedToInlineEditionDirective,IssueStatusInlineEditionDirective,IssuesController,IssuesDirective,IssuesFiltersDirective,bindOnce,debounceLeading,groupBy,joinStr,mixOf,module,startswith,taiga,toString,trim,bind=function(fn,me){return function(){return fn.apply(me,arguments)}},extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,mixOf=this.taiga.mixOf,trim=this.taiga.trim,toString=this.taiga.toString,joinStr=this.taiga.joinStr,groupBy=this.taiga.groupBy,bindOnce=this.taiga.bindOnce,debounceLeading=this.taiga.debounceLeading,startswith=this.taiga.startswith,module=angular.module("taigaIssues"),IssuesController=function(superClass){function IssuesController(scope,rootscope,repo,confirm,rs,urls,params,q,location,appMetaService,navUrls,events,analytics,translate){var filters,promise;return this.scope=scope,this.rootscope=rootscope,this.repo=repo,this.confirm=confirm,this.rs=rs,this.urls=urls,this.params=params,this.q=q,this.location=location,this.appMetaService=appMetaService,this.navUrls=navUrls,this.events=events,this.analytics=analytics,this.translate=translate,this.loadIssues=bind(this.loadIssues,this),this.scope.sectionName="Issues",this.scope.filters={},_.isEmpty(this.location.search())?(filters=this.rs.issues.getFilters(this.params.pslug),filters.page=1,this.location.search(filters),void this.location.replace()):(promise=this.loadInitialData(),promise.then(function(_this){return function(){var description,title;return title=_this.translate.instant("ISSUES.PAGE_TITLE",{projectName:_this.scope.project.name}),description=_this.translate.instant("ISSUES.PAGE_DESCRIPTION",{projectName:_this.scope.project.name,projectDescription:_this.scope.project.description}),_this.appMetaService.setAll(title,description)}}(this)),promise.then(null,this.onInitialDataError.bind(this)),void this.scope.$on("issueform:new:success",function(_this){return function(){return _this.analytics.trackEvent("issue","create","create issue on issues list",1),_this.loadIssues()}}(this)))}return extend(IssuesController,superClass),IssuesController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$tgUrls","$routeParams","$q","$tgLocation","tgAppMetaService","$tgNavUrls","$tgEvents","$tgAnalytics","$translate"],IssuesController.prototype.initializeSubscription=function(){var routingKey;return routingKey="changes.project."+this.scope.projectId+".issues",this.events.subscribe(this.scope,routingKey,function(_this){return function(message){return _this.loadIssues()}}(this))},IssuesController.prototype.storeFilters=function(){return this.rs.issues.storeFilters(this.params.pslug,this.location.search())},IssuesController.prototype.loadProject=function(){return this.rs.projects.getBySlug(this.params.pslug).then(function(_this){return function(project){return project.is_issues_activated||_this.location.path(_this.navUrls.resolve("permission-denied")),_this.scope.projectId=project.id,_this.scope.project=project,_this.scope.$emit("project:loaded",project),_this.scope.issueStatusById=groupBy(project.issue_statuses,function(x){return x.id}),_this.scope.issueStatusList=_.sortBy(project.issue_statuses,"order"),_this.scope.severityById=groupBy(project.severities,function(x){return x.id}),_this.scope.severityList=_.sortBy(project.severities,"order"),_this.scope.priorityById=groupBy(project.priorities,function(x){return x.id}),_this.scope.priorityList=_.sortBy(project.priorities,"order"),_this.scope.issueTypes=_.sortBy(project.issue_types,"order"),_this.scope.issueTypeById=groupBy(project.issue_types,function(x){return x.id}),project}}(this))},IssuesController.prototype.getUrlFilters=function(){var filters;return filters=_.pick(this.location.search(),"page","tags","status","types","q","severities","priorities","assignedTo","createdBy","orderBy"),filters.page||(filters.page=1),filters},IssuesController.prototype.getUrlFilter=function(name){var filters;return filters=_.pick(this.location.search(),name),filters[name]},IssuesController.prototype.loadMyFilters=function(){return this.rs.issues.getMyFilters(this.scope.projectId).then(function(_this){return function(filters){return _.map(filters,function(value,key){return{id:key,name:key,type:"myFilters",selected:!1}})}}(this))},IssuesController.prototype.removeNotExistingFiltersFromUrl=function(){var currentSearch,existingValues,filterName,filterValue,splittedValues,urlfilters;currentSearch=this.location.search(),urlfilters=this.getUrlFilters();for(filterName in urlfilters)filterValue=urlfilters[filterName],"page"!==filterName&&"orderBy"!==filterName&&"q"!==filterName&&(splittedValues="tags"===filterName?_.map((""+filterValue).split(",")):_.map((""+filterValue).split(","),function(x){return"null"===x?null:parseInt(x)}),existingValues=_.intersection(splittedValues,_.map(this.scope.filters[filterName],"id")),splittedValues.length!==existingValues.length&&this.location.search(filterName,existingValues.join()));return currentSearch!==this.location.search()?this.location.replace():void 0},IssuesController.prototype.markSelectedFilters=function(filters,urlfilters){var isSelected,j,key,len,name,obj,ref,ref1,results,searchdata,val,value;searchdata={},ref=_.omit(urlfilters,"page","orderBy");for(name in ref)for(value=ref[name],null==searchdata[name]&&(searchdata[name]={}),ref1=(""+value).split(","),j=0,len=ref1.length;len>j;j++)val=ref1[j],searchdata[name][val]=!0;isSelected=function(type,id){return null!=searchdata[type]&&searchdata[type][id]?!0:!1},results=[];for(key in filters)value=filters[key],results.push(function(){var k,len1,results1;for(results1=[],k=0,len1=value.length;len1>k;k++)obj=value[k],results1.push(obj.selected=isSelected(obj.type,obj.id)?!0:void 0);return results1}());return results},IssuesController.prototype.loadFilters=function(){var loadFilters,promise,urlfilters;return urlfilters=this.getUrlFilters(),urlfilters.q&&(this.scope.filtersQ=urlfilters.q),promise=this.loadMyFilters().then(function(_this){return function(myFilters){return _this.scope.filters.myFilters=myFilters,myFilters}}(this)),loadFilters={},loadFilters.project=this.scope.projectId,loadFilters.tags=urlfilters.tags,loadFilters.status=urlfilters.status,loadFilters.q=urlfilters.q,loadFilters.types=urlfilters.types,loadFilters.severities=urlfilters.severities,loadFilters.priorities=urlfilters.priorities,loadFilters.assigned_to=urlfilters.assignedTo,loadFilters.owner=urlfilters.createdBy,promise=promise.then(function(_this){return function(){return _this.rs.issues.filtersData(loadFilters)}}(this)),promise.then(function(_this){return function(data){var choicesFiltersFormat,tagsFilterFormat,usersFiltersFormat;return usersFiltersFormat=function(users,type,unknownOption){var reformatedUsers,unknownItem;return reformatedUsers=_.map(users,function(t){return t.type=type,t.name=t.full_name?t.full_name:unknownOption,t}),unknownItem=_.remove(reformatedUsers,function(u){return!u.id}),reformatedUsers=_.sortBy(reformatedUsers,function(u){return u.name.toUpperCase()}),unknownItem.length>0&&reformatedUsers.unshift(unknownItem[0]),reformatedUsers},choicesFiltersFormat=function(choices,type,byIdObject){return _.map(choices,function(t){return t.type=type,t})},tagsFilterFormat=function(tags){return _.map(tags,function(t){return t.id=t.name,t.type="tags",t})},_this.scope.filters.status=choicesFiltersFormat(data.statuses,"status",_this.scope.issueStatusById),_this.scope.filters.severities=choicesFiltersFormat(data.severities,"severities",_this.scope.severityById),_this.scope.filters.priorities=choicesFiltersFormat(data.priorities,"priorities",_this.scope.priorityById),_this.scope.filters.assignedTo=usersFiltersFormat(data.assigned_to,"assignedTo","Unassigned"),_this.scope.filters.createdBy=usersFiltersFormat(data.owners,"createdBy","Unknown"),_this.scope.filters.types=choicesFiltersFormat(data.types,"types",_this.scope.issueTypeById),_this.scope.filters.tags=tagsFilterFormat(data.tags),_this.removeNotExistingFiltersFromUrl(),_this.markSelectedFilters(_this.scope.filters,urlfilters),_this.rootscope.$broadcast("filters:loaded",_this.scope.filters)}}(this))},IssuesController.prototype.loadIssuesRequests=0,IssuesController.prototype.loadIssues=function(){var name,promise,ref,values;this.scope.urlFilters=this.getUrlFilters(),this.scope.httpParams={},ref=this.scope.urlFilters;for(name in ref)values=ref[name],"severities"===name?name="severity":"orderBy"===name?name="order_by":"priorities"===name?name="priority":"assignedTo"===name?name="assigned_to":"createdBy"===name?name="owner":"status"===name?name="status":"types"===name&&(name="type"),this.scope.httpParams[name]=values;return promise=this.rs.issues.list(this.scope.projectId,this.scope.httpParams),this.loadIssuesRequests+=1,promise.index=this.loadIssuesRequests,promise.then(function(_this){return function(data){return promise.index===_this.loadIssuesRequests&&(_this.scope.issues=data.models,_this.scope.page=data.current,_this.scope.count=data.count,_this.scope.paginatedBy=data.paginatedBy),data}}(this)),promise},IssuesController.prototype.loadInitialData=function(){var promise;return promise=this.loadProject(),promise.then(function(_this){return function(project){return _this.fillUsersAndRoles(project.members,project.roles),_this.initializeSubscription(),_this.loadFilters(),_this.loadIssues()}}(this))},IssuesController.prototype.saveCurrentFiltersTo=function(newFilter){var deferred;return deferred=this.q.defer(),this.rs.issues.getMyFilters(this.scope.projectId).then(function(_this){return function(filters){return filters[newFilter]=_this.location.search(),_this.rs.issues.storeMyFilters(_this.scope.projectId,filters).then(function(){return deferred.resolve()})}}(this)),deferred.promise},IssuesController.prototype.deleteMyFilter=function(filter){var deferred;return deferred=this.q.defer(),this.rs.issues.getMyFilters(this.scope.projectId).then(function(_this){return function(filters){return delete filters[filter],_this.rs.issues.storeMyFilters(_this.scope.projectId,filters).then(function(){return deferred.resolve()})}}(this)),deferred.promise},IssuesController.prototype.addNewIssue=function(){return this.rootscope.$broadcast("issueform:new",this.scope.project)},IssuesController.prototype.addIssuesInBulk=function(){return this.rootscope.$broadcast("issueform:bulk",this.scope.projectId)},IssuesController}(mixOf(taiga.Controller,taiga.PageMixin,taiga.FiltersMixin)),module.controller("IssuesController",IssuesController),IssuesDirective=function($log,$location,$template,$compile){var link,linkOrdering,linkPagination,template;return template=$template.get("issue/issue-paginator.html",!0),linkPagination=function($scope,$el,$attrs,$ctrl){var $pagEl,afterCurrent,atBegin,atEnd,beforeCurrent,getNumPages,renderPagination;return afterCurrent=2,beforeCurrent=4,atBegin=2,atEnd=2,$pagEl=$el.find(".issues-paginator"),getNumPages=function(){var numPages;return numPages=$scope.count/$scope.paginatedBy,numPages=parseInt(numPages,10)=numPages)return void $pagEl.hide();for($pagEl.show(),pages=[],options={},options.pages=pages,options.showPrevious=$scope.page>1,options.showNext=!($scope.page===numPages),cpage=$scope.page,i=j=1,ref=numPages;ref>=1?ref>=j:j>=ref;i=ref>=1?++j:--j)i===cpage+afterCurrent&&numPages>cpage+afterCurrent+atEnd?pages.push({classes:"dots",type:"dots"}):i===cpage-beforeCurrent&&cpage>atBegin+beforeCurrent?pages.push({classes:"dots",type:"dots"}):i>cpage+afterCurrent&&numPages-atEnd>=i||cpage-beforeCurrent>i&&i>atBegin||(i===cpage?pages.push({classes:"active",num:i,type:"page-active"}):pages.push({classes:"page",num:i,type:"page"}));return html=template(options),html=$compile(html)($scope),$pagEl.html(html)},$scope.$watch("issues",function(value){return value?renderPagination():void 0}),$el.on("click",".issues-paginator a.next",function(event){return event.preventDefault(),$scope.$apply(function(){return $ctrl.selectFilter("page",$scope.page+1),$ctrl.loadIssues()})}),$el.on("click",".issues-paginator a.previous",function(event){return event.preventDefault(),$scope.$apply(function(){return $ctrl.selectFilter("page",$scope.page-1),$ctrl.loadIssues()})}),$el.on("click",".issues-paginator li.page > a",function(event){var pagenum,target;return event.preventDefault(),target=angular.element(event.currentTarget),pagenum=target.data("pagenum"),$scope.$apply(function(){return $ctrl.selectFilter("page",pagenum),$ctrl.loadIssues()})})},linkOrdering=function($scope,$el,$attrs,$ctrl){var colHeadElement,currentOrder,icon;return currentOrder=$ctrl.getUrlFilter("orderBy")||"created_date",currentOrder&&(icon=startswith(currentOrder,"-")?"icon-arrow-up":"icon-arrow-bottom",colHeadElement=$el.find(".row.title > div[data-fieldname='"+trim(currentOrder,"-")+"']"),colHeadElement.html(colHeadElement.html()+"")),$el.on("click",".row.title > div",function(event){var finalOrder,newOrder,target;return target=angular.element(event.currentTarget),currentOrder=$ctrl.getUrlFilter("orderBy"),newOrder=target.data("fieldname"),finalOrder=currentOrder===newOrder?"-"+newOrder:newOrder,$scope.$apply(function(){return $ctrl.replaceFilter("orderBy",finalOrder),$ctrl.storeFilters(),$ctrl.loadIssues().then(function(){return $el.find(".row.title > div > span.icon").remove(),icon=startswith(finalOrder,"-")?"icon-arrow-up":"icon-arrow-bottom",target.html(target.html()+"")})})})},link=function($scope,$el,$attrs){var $ctrl;return $ctrl=$el.controller(),linkOrdering($scope,$el,$attrs,$ctrl),linkPagination($scope,$el,$attrs,$ctrl),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgIssues",["$log","$tgLocation","$tgTemplate","$compile",IssuesDirective]),IssuesFiltersDirective=function($q,$log,$location,$rs,$confirm,$loading,$template,$translate,$compile,$auth){var link,template,templateSelected;return template=$template.get("issue/issues-filters.html",!0),templateSelected=$template.get("issue/issues-filters-selected.html",!0),link=function($scope,$el,$attrs){var $ctrl,getFiltersType,initializeSelectedFilters,reloadIssues,renderFilters,renderSelectedFilters,selectQFilter,selectedFilters,showCategories,showFilters,toggleFilterSelection,unwatchIssues;return $ctrl=$el.closest(".wrapper").controller(),selectedFilters=[],showFilters=function(title,type){return $el.find(".filters-cats").hide(),$el.find(".filter-list").removeClass("hidden"),$el.find("h2.breadcrumb").removeClass("hidden"),$el.find("h2 a.subfilter span.title").html(title),$el.find("h2 a.subfilter span.title").prop("data-type",type)},showCategories=function(){return $el.find(".filters-cats").show(),$el.find(".filter-list").addClass("hidden"),$el.find("h2.breadcrumb").addClass("hidden")},initializeSelectedFilters=function(filters){var j,len,name,val,values;selectedFilters=[];for(name in filters)for(values=filters[name],j=0,len=values.length;len>j;j++)val=values[j],val.selected&&selectedFilters.push(val);return renderSelectedFilters(selectedFilters)},renderSelectedFilters=function(selectedFilters){var html;return _.filter(selectedFilters,function(_this){return function(f){return f.color?f.style="border-left: 3px solid "+f.color:void 0}}(this)),html=templateSelected({filters:selectedFilters}),html=$compile(html)($scope),$el.find(".filters-applied").html(html),$auth.isAuthenticated()&&selectedFilters.length>0?$el.find(".save-filters").show():$el.find(".save-filters").hide()},renderFilters=function(filters){var html;return _.filter(filters,function(_this){return function(f){return f.color?f.style="border-left: 3px solid "+f.color:void 0}}(this)),html=template({filters:filters}),html=$compile(html)($scope),$el.find(".filter-list").html(html)},getFiltersType=function(){return $el.find("h2 a.subfilter span.title").prop("data-type")},reloadIssues=function(){var currentFiltersType;return currentFiltersType=getFiltersType(),$q.all([$ctrl.loadIssues(),$ctrl.loadFilters()]).then(function(){var filters;return filters=$scope.filters[currentFiltersType],renderFilters(_.reject(filters,"selected"))})},toggleFilterSelection=function(type,id){var currentFiltersType,filter,filterId,filters;return"myFilters"===type?($rs.issues.getMyFilters($scope.projectId).then(function(data){var filters,myFilters;return myFilters=data,filters=myFilters[id],filters.page=1,$ctrl.replaceAllFilters(filters),$ctrl.storeFilters(),$ctrl.loadIssues(),$ctrl.markSelectedFilters($scope.filters,filters),initializeSelectedFilters($scope.filters)}),null):(filters=$scope.filters[type],filterId="tags"===type?taiga.toString(id):id,filter=_.find(filters,{id:filterId}),filter.selected=!filter.selected,null===id&&(id="null"),filter.selected?(selectedFilters.push(filter),$ctrl.selectFilter(type,id),$ctrl.selectFilter("page",1),$ctrl.storeFilters()):(selectedFilters=_.reject(selectedFilters,function(f){return f.id===filter.id&&f.type===filter.type}),$ctrl.unselectFilter(type,id),$ctrl.selectFilter("page",1),$ctrl.storeFilters()),reloadIssues(),renderSelectedFilters(selectedFilters),currentFiltersType=getFiltersType(),type===currentFiltersType?renderFilters(_.reject(filters,"selected")):void 0)},$scope.$on("filters:loaded",function(ctx,filters){return initializeSelectedFilters(filters)}),$scope.$on("filters:issueupdate",function(ctx,filters){var html;return html=template({filters:filters.status}),html=$compile(html)($scope),$el.find(".filter-list").html(html)}),selectQFilter=debounceLeading(100,function(value,oldValue){return void 0!==value&&value!==oldValue?($ctrl.replaceFilter("page",null,!0),0===value.length?($ctrl.replaceFilter("q",null),$ctrl.storeFilters()):($ctrl.replaceFilter("q",value),$ctrl.storeFilters()),reloadIssues()):void 0}),unwatchIssues=$scope.$watch("issues",function(newValue){return _.isUndefined(newValue)?void 0:($scope.$watch("filtersQ",selectQFilter),unwatchIssues())}),$el.on("click",".filters-cats > ul > li > a",function(event){var tags,target;return event.preventDefault(),target=angular.element(event.currentTarget),tags=$scope.filters[target.data("type")],renderFilters(_.reject(tags,"selected")),showFilters(target.attr("title"),target.data("type"))}),$el.on("click",".filters-inner > .filters-step-cat > .breadcrumb > .back",function(event){return event.preventDefault(),showCategories($el)}),$el.on("click",".filters-applied a",function(event){var id,target,type;return event.preventDefault(),target=angular.element(event.currentTarget),id=target.data("id")||null,type=target.data("type"),toggleFilterSelection(type,id)}),$el.on("click",".filter-list .single-filter",function(event){var id,target,type;return event.preventDefault(),target=angular.element(event.currentTarget),target.toggleClass("active"),id=target.data("id")||null,type=target.data("type"),"myFilters"===type&&target.removeClass("active"),toggleFilterSelection(type,id)}),$el.on("click",".filter-list .single-filter .icon-delete",function(event){var customFilterName,message,target,title;return event.preventDefault(),event.stopPropagation(),target=angular.element(event.currentTarget),customFilterName=target.parent().data("id"),title=$translate.instant("ISSUES.FILTERS.CONFIRM_DELETE.TITLE"),message=$translate.instant("ISSUES.FILTERS.CONFIRM_DELETE.MESSAGE",{customFilterName:customFilterName}),$confirm.askOnDelete(title,message).then(function(askResponse){var promise;return promise=$ctrl.deleteMyFilter(customFilterName),promise.then(function(){return promise=$ctrl.loadMyFilters(),promise.then(function(filters){return askResponse.finish(),$scope.filters.myFilters=filters,renderFilters($scope.filters.myFilters)}),promise.then(null,function(){return askResponse.finish()})}),promise.then(null,function(){return askResponse.finish(!1),$confirm.notify("error")})})}),$el.on("click",".save-filters",function(event){return event.preventDefault(),renderFilters($scope.filters.myFilters),showFilters("My filters","myFilters"),$el.find(".save-filters").hide(),$el.find(".my-filter-name").removeClass("hidden"),$el.find(".my-filter-name").focus(),$scope.$apply()}),$el.on("keyup",".my-filter-name",function(event){var currentLoading,newFilter,promise,target;return event.preventDefault(),13===event.keyCode?(target=angular.element(event.currentTarget),newFilter=target.val(),currentLoading=$loading().target($el.find(".new")).start(),promise=$ctrl.saveCurrentFiltersTo(newFilter),promise.then(function(){var loadPromise;return loadPromise=$ctrl.loadMyFilters(),loadPromise.then(function(filters){var currentfilterstype;return currentLoading.finish(),$scope.filters.myFilters=filters,currentfilterstype=$el.find("h2 a.subfilter span.title").prop("data-type"),"myFilters"===currentfilterstype&&renderFilters($scope.filters.myFilters),$el.find(".my-filter-name").addClass("hidden"),$el.find(".save-filters").show()}),loadPromise.then(null,function(){return currentLoading.finish(),$confirm.notify("error","Error loading custom filters")})}),promise.then(null,function(){return currentLoading.finish(),$el.find(".my-filter-name").val(newFilter).focus().select(),$confirm.notify("error","Filter not saved")})):27===event.keyCode?($el.find(".my-filter-name").val(""),$el.find(".my-filter-name").addClass("hidden"),$el.find(".save-filters").show()):void 0})},{link:link}},module.directive("tgIssuesFilters",["$q","$log","$tgLocation","$tgResources","$tgConfirm","$tgLoading","$tgTemplate","$translate","$compile","$tgAuth",IssuesFiltersDirective]),IssueStatusInlineEditionDirective=function($repo,$template,$rootscope){var link,selectionTemplate,updateIssueStatus;return selectionTemplate=$template.get("issue/issue-status-inline-edition-selection.html",!0),updateIssueStatus=function($el,issue,issueStatusById){var issueStatusDom,issueStatusDomParent,status;return issueStatusDomParent=$el.find(".issue-status"),issueStatusDom=$el.find(".issue-status .issue-status-bind"),status=issueStatusById[issue.status],status?(issueStatusDom.text(status.name),issueStatusDom.prop("title",status.name),issueStatusDomParent.css("color",status.color)):void 0},link=function($scope,$el,$attrs){var $ctrl,issue;return $ctrl=$el.controller(),issue=$scope.$eval($attrs.tgIssueStatusInlineEdition),$el.on("click",".issue-status",function(event){return event.preventDefault(),event.stopPropagation(),$el.find(".pop-status").popover().open()}),$el.on("click",".status",function(event){var filter,j,len,ref,target;for(event.preventDefault(),event.stopPropagation(),target=angular.element(event.currentTarget),ref=$scope.filters.status,j=0,len=ref.length;len>j;j++)filter=ref[j],filter.id===issue.status&&filter.count--;return issue.status=target.data("status-id"),$el.find(".pop-status").popover().close(),updateIssueStatus($el,issue,$scope.issueStatusById),$scope.$apply(function(){var k,len1,ref1;for($repo.save(issue).then(function(){return $ctrl.loadIssues()}),ref1=$scope.filters.status,k=0,len1=ref1.length;len1>k;k++)filter=ref1[k],filter.id===issue.status&&filter.count++;return $rootscope.$broadcast("filters:issueupdate",$scope.filters)})}),taiga.bindOnce($scope,"project",function(project){return $el.append(selectionTemplate({statuses:project.issue_statuses})),updateIssueStatus($el,issue,$scope.issueStatusById),-1===project.my_permissions.indexOf("modify_issue")?($el.unbind("click"),$el.find("a").addClass("not-clickable")):void 0}),$scope.$watch($attrs.tgIssueStatusInlineEdition,function(_this){return function(val){return updateIssueStatus($el,val,$scope.issueStatusById)}}(this)),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgIssueStatusInlineEdition",["$tgRepo","$tgTemplate","$rootScope",IssueStatusInlineEditionDirective]),IssueAssignedToInlineEditionDirective=function($repo,$rootscope,popoverService){var link,template;return template=_.template('<%- name %>\n
<%- name %>
'),link=function($scope,$el,$attrs){var $ctrl,issue,updateIssue;return updateIssue=function(issue){var ctx,member;return ctx={name:"Unassigned",imgurl:"/"+window._version+"/images/unnamed.png"},member=$scope.usersById[issue.assigned_to],member&&(ctx.imgurl=member.photo,ctx.name=member.full_name_display),$el.find(".avatar").html(template(ctx)),$el.find(".issue-assignedto").attr("title",ctx.name)},$ctrl=$el.controller(),issue=$scope.$eval($attrs.tgIssueAssignedToInlineEdition),updateIssue(issue),$el.on("click",".issue-assignedto",function(event){return $rootscope.$broadcast("assigned-to:add",issue)}),taiga.bindOnce($scope,"project",function(project){return-1===project.my_permissions.indexOf("modify_issue")?($el.unbind("click"),$el.find("a").addClass("not-clickable")):void 0}),$scope.$on("assigned-to:added",function(_this){return function(ctx,userId,updatedIssue){return updatedIssue.id===issue.id?(updatedIssue.assigned_to=userId,$repo.save(updatedIssue),updateIssue(updatedIssue)):void 0}}(this)),$scope.$watch($attrs.tgIssueAssignedToInlineEdition,function(_this){return function(val){return updateIssue(val)}}(this)),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgIssueAssignedToInlineEdition",["$tgRepo","$rootScope",IssueAssignedToInlineEditionDirective])}.call(this),function(){var UsClientRequirementButtonDirective,UsStatusButtonDirective,UsStatusDisplayDirective,UsTasksProgressDisplayDirective,UsTeamRequirementButtonDirective,UserStoryDetailController,bindMethods,bindOnce,groupBy,mixOf,module,taiga,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,mixOf=this.taiga.mixOf,groupBy=this.taiga.groupBy,bindOnce=this.taiga.bindOnce,bindMethods=this.taiga.bindMethods,module=angular.module("taigaUserStories"),UserStoryDetailController=function(superClass){function UserStoryDetailController(scope,rootscope,repo,confirm,rs,params,q,location,log,appMetaService,navUrls,analytics,translate){var promise;this.scope=scope,this.rootscope=rootscope,this.repo=repo,this.confirm=confirm,this.rs=rs,this.params=params,this.q=q,this.location=location,this.log=log,this.appMetaService=appMetaService,this.navUrls=navUrls,this.analytics=analytics,this.translate=translate,bindMethods(this),this.scope.usRef=this.params.usref,this.scope.sectionName=this.translate.instant("US.SECTION_NAME"),this.initializeEventHandlers(),promise=this.loadInitialData(),promise.then(function(_this){return function(){return _this._setMeta(),_this.initializeOnDeleteGoToUrl()}}(this)),promise.then(null,this.onInitialDataError.bind(this))}return extend(UserStoryDetailController,superClass),UserStoryDetailController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","$log","tgAppMetaService","$tgNavUrls","$tgAnalytics","$translate"],UserStoryDetailController.prototype._setMeta=function(){var closedTasks,description,progressPercentage,ref,title,totalTasks;return totalTasks=this.scope.tasks.length,closedTasks=_.filter(this.scope.tasks,function(_this){return function(t){return _this.scope.taskStatusById[t.status].is_closed}}(this)).length,progressPercentage=totalTasks>0?Math.round(100*closedTasks/totalTasks):0,title=this.translate.instant("US.PAGE_TITLE",{userStoryRef:"#"+this.scope.us.ref,userStorySubject:this.scope.us.subject,projectName:this.scope.project.name}),description=this.translate.instant("US.PAGE_DESCRIPTION",{userStoryStatus:(null!=(ref=this.scope.statusById[this.scope.us.status])?ref.name:void 0)||"--",userStoryPoints:this.scope.us.total_points,userStoryDescription:angular.element(this.scope.us.description_html||"").text(),userStoryClosedTasks:closedTasks,userStoryTotalTasks:totalTasks,userStoryProgressPercentage:progressPercentage}),this.appMetaService.setAll(title,description)},UserStoryDetailController.prototype.initializeEventHandlers=function(){return this.scope.$on("related-tasks:update",function(_this){return function(){return _this.scope.tasks=_.clone(_this.scope.tasks,!1)}}(this)),this.scope.$on("attachment:create",function(_this){return function(){return _this.analytics.trackEvent("attachment","create","create attachment on userstory",1)}}(this)),this.scope.$on("comment:new",function(_this){return function(){return _this.loadUs()}}(this))},UserStoryDetailController.prototype.initializeOnDeleteGoToUrl=function(){var ctx;return ctx={project:this.scope.project.slug},this.scope.onDeleteGoToUrl=this.navUrls.resolve("project",ctx),this.scope.project.is_backlog_activated?this.scope.us.milestone?(ctx.sprint=this.scope.sprint.slug,this.scope.onDeleteGoToUrl=this.navUrls.resolve("project-taskboard",ctx)):this.scope.onDeleteGoToUrl=this.navUrls.resolve("project-backlog",ctx):this.scope.project.is_kanban_activated?this.scope.onDeleteGoToUrl=this.navUrls.resolve("project-kanban",ctx):void 0},UserStoryDetailController.prototype.loadProject=function(){return this.rs.projects.getBySlug(this.params.pslug).then(function(_this){return function(project){return _this.scope.projectId=project.id,_this.scope.project=project,_this.scope.$emit("project:loaded",project),_this.scope.statusList=project.us_statuses,_this.scope.statusById=groupBy(project.us_statuses,function(x){return x.id}),_this.scope.taskStatusById=groupBy(project.task_statuses,function(x){return x.id}),_this.scope.pointsList=_.sortBy(project.points,"order"),_this.scope.pointsById=groupBy(_this.scope.pointsList,function(e){ -return e.id}),project}}(this))},UserStoryDetailController.prototype.loadUs=function(){var httpParams,kanbanStaus,milestone,noMilestone;return httpParams=_.pick(this.location.search(),"milestone","no-milestone","kanban-status"),milestone=httpParams.milestone,milestone&&this.rs.userstories.storeQueryParams(this.scope.projectId,{milestone:milestone,order_by:"sprint_order"}),noMilestone=httpParams["no-milestone"],noMilestone&&this.rs.userstories.storeQueryParams(this.scope.projectId,{milestone:"null",order_by:"backlog_order"}),kanbanStaus=httpParams["kanban-status"],kanbanStaus&&this.rs.userstories.storeQueryParams(this.scope.projectId,{status:kanbanStaus,order_by:"kanban_order"}),this.rs.userstories.getByRef(this.scope.projectId,this.params.usref).then(function(_this){return function(us){var ctx,ref,ref1;return _this.scope.us=us,_this.scope.usId=us.id,_this.scope.commentModel=us,null!=(null!=(ref=_this.scope.us.neighbors.previous)?ref.ref:void 0)&&(ctx={project:_this.scope.project.slug,ref:_this.scope.us.neighbors.previous.ref},_this.scope.previousUrl=_this.navUrls.resolve("project-userstories-detail",ctx)),null!=(null!=(ref1=_this.scope.us.neighbors.next)?ref1.ref:void 0)&&(ctx={project:_this.scope.project.slug,ref:_this.scope.us.neighbors.next.ref},_this.scope.nextUrl=_this.navUrls.resolve("project-userstories-detail",ctx)),us}}(this))},UserStoryDetailController.prototype.loadSprint=function(){return this.scope.us.milestone?this.rs.sprints.get(this.scope.us.project,this.scope.us.milestone).then(function(_this){return function(sprint){return _this.scope.sprint=sprint,sprint}}(this)):void 0},UserStoryDetailController.prototype.loadTasks=function(){return this.rs.tasks.list(this.scope.projectId,null,this.scope.usId).then(function(_this){return function(tasks){return _this.scope.tasks=tasks,tasks}}(this))},UserStoryDetailController.prototype.loadInitialData=function(){var promise;return promise=this.loadProject(),promise.then(function(_this){return function(project){return _this.fillUsersAndRoles(project.members,project.roles),_this.loadUs().then(function(){return _this.q.all([_this.loadSprint(),_this.loadTasks()])})}}(this))},UserStoryDetailController.prototype.onUpvote=function(){var onError,onSuccess;return onSuccess=function(_this){return function(){return _this.loadUs(),_this.rootscope.$broadcast("object:updated")}}(this),onError=function(_this){return function(){return _this.confirm.notify("error")}}(this),this.rs.userstories.upvote(this.scope.usId).then(onSuccess,onError)},UserStoryDetailController.prototype.onDownvote=function(){var onError,onSuccess;return onSuccess=function(_this){return function(){return _this.loadUs(),_this.rootscope.$broadcast("object:updated")}}(this),onError=function(_this){return function(){return _this.confirm.notify("error")}}(this),this.rs.userstories.downvote(this.scope.usId).then(onSuccess,onError)},UserStoryDetailController.prototype.onWatch=function(){var onError,onSuccess;return onSuccess=function(_this){return function(){return _this.loadUs(),_this.rootscope.$broadcast("object:updated")}}(this),onError=function(_this){return function(){return _this.confirm.notify("error")}}(this),this.rs.userstories.watch(this.scope.usId).then(onSuccess,onError)},UserStoryDetailController.prototype.onUnwatch=function(){var onError,onSuccess;return onSuccess=function(_this){return function(){return _this.loadUs(),_this.rootscope.$broadcast("object:updated")}}(this),onError=function(_this){return function(){return _this.confirm.notify("error")}}(this),this.rs.userstories.unwatch(this.scope.usId).then(onSuccess,onError)},UserStoryDetailController}(mixOf(taiga.Controller,taiga.PageMixin)),module.controller("UserStoryDetailController",UserStoryDetailController),UsStatusDisplayDirective=function($template,$compile){var link,template;return template=$template.get("common/components/status-display.html",!0),link=function($scope,$el,$attrs){var render;return render=function(us){var html,status;return status=$scope.statusById[us.status],html=template({is_closed:us.is_closed,status:status}),html=$compile(html)($scope),$el.html(html)},$scope.$watch($attrs.ngModel,function(us){return null!=us?render(us):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,restrict:"EA",require:"ngModel"}},module.directive("tgUsStatusDisplay",["$tgTemplate","$compile",UsStatusDisplayDirective]),UsTasksProgressDisplayDirective=function($template,$compile){var link;return link=function($scope,$el,$attrs){var render;return render=function(tasks){var progress,totalClosedTasks,totalTasks;return totalTasks=tasks.length,totalClosedTasks=_.filter(tasks,function(_this){return function(task){return $scope.taskStatusById[task.status].is_closed}}(this)).length,progress=totalTasks>0?100*totalClosedTasks/totalTasks:0,_.assign($scope,{totalTasks:totalTasks,totalClosedTasks:totalClosedTasks,progress:progress,style:{width:progress+"%"}})},$scope.$watch($attrs.ngModel,function(tasks){return null!=tasks?render(tasks):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{templateUrl:"us/us-task-progress.html",link:link,restrict:"EA",require:"ngModel",scope:!0}},module.directive("tgUsTasksProgressDisplay",["$tgTemplate","$compile",UsTasksProgressDisplayDirective]),UsStatusButtonDirective=function($rootScope,$repo,$confirm,$loading,$qqueue,$template){var link,template;return template=$template.get("us/us-status-button.html",!0),link=function($scope,$el,$attrs,$model){var isEditable,render,save;return isEditable=function(){return-1!==$scope.project.my_permissions.indexOf("modify_us")},render=function(_this){return function(us){var html,status;return status=$scope.statusById[us.status],html=template({status:status,statuses:$scope.statusList,editable:isEditable()}),$el.html(html)}}(this),save=$qqueue.bindAdd(function(_this){return function(status){var currentLoading,onError,onSuccess,us;return us=$model.$modelValue.clone(),us.status=status,$.fn.popover().closeAll(),currentLoading=$loading().target($el.find(".level-name")).start(),onSuccess=function(){return $confirm.notify("success"),$model.$setViewValue(us),$rootScope.$broadcast("object:updated"),currentLoading.finish()},onError=function(){return $confirm.notify("error"),currentLoading.finish()},$repo.save(us).then(onSuccess,onError)}}(this)),$el.on("click",".status-data",function(event){return event.preventDefault(),event.stopPropagation(),isEditable()?$el.find(".pop-status").popover().open():void 0}),$el.on("click",".status",function(event){var status,target;return event.preventDefault(),event.stopPropagation(),isEditable()?(target=angular.element(event.currentTarget),status=target.data("status-id"),save(status)):void 0}),$scope.$watch($attrs.ngModel,function(us){return us?render(us):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,restrict:"EA",require:"ngModel"}},module.directive("tgUsStatusButton",["$rootScope","$tgRepo","$tgConfirm","$tgLoading","$tgQqueue","$tgTemplate",UsStatusButtonDirective]),UsTeamRequirementButtonDirective=function($rootscope,$tgrepo,$confirm,$loading,$qqueue,$template,$compile){var link,template;return template=$template.get("us/us-team-requirement-button.html",!0),link=function($scope,$el,$attrs,$model){var canEdit,render,save;return canEdit=function(){return-1!==$scope.project.my_permissions.indexOf("modify_us")},render=function(us){var ctx,html;return canEdit()||us.team_requirement?(ctx={canEdit:canEdit(),isRequired:us.team_requirement},html=template(ctx),html=$compile(html)($scope),$el.html(html)):void $el.html("")},save=$qqueue.bindAdd(function(_this){return function(team_requirement){var currentLoading,promise,us;return us=$model.$modelValue.clone(),us.team_requirement=team_requirement,currentLoading=$loading().target($el.find("label")).start(),promise=$tgrepo.save(us),promise.then(function(){return $model.$setViewValue(us),currentLoading.finish(),$rootscope.$broadcast("object:updated")}),promise.then(null,function(){return currentLoading.finish(),$confirm.notify("error")})}}(this)),$el.on("click",".team-requirement",function(event){var team_requirement;if(canEdit())return team_requirement=!$model.$modelValue.team_requirement,save(team_requirement)}),$scope.$watch($attrs.ngModel,function(us){return us?render(us):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,restrict:"EA",require:"ngModel"}},module.directive("tgUsTeamRequirementButton",["$rootScope","$tgRepo","$tgConfirm","$tgLoading","$tgQqueue","$tgTemplate","$compile",UsTeamRequirementButtonDirective]),UsClientRequirementButtonDirective=function($rootscope,$tgrepo,$confirm,$loading,$qqueue,$template,$compile){var link,template;return template=$template.get("us/us-client-requirement-button.html",!0),link=function($scope,$el,$attrs,$model){var canEdit,render,save;return canEdit=function(){return-1!==$scope.project.my_permissions.indexOf("modify_us")},render=function(us){var ctx,html;return canEdit()||us.client_requirement?(ctx={canEdit:canEdit(),isRequired:us.client_requirement},html=$compile(template(ctx))($scope),$el.html(html)):void $el.html("")},save=$qqueue.bindAdd(function(_this){return function(client_requirement){var currentLoading,promise,us;return us=$model.$modelValue.clone(),us.client_requirement=client_requirement,currentLoading=$loading().target($el.find("label")).start(),promise=$tgrepo.save(us),promise.then(function(){return $model.$setViewValue(us),currentLoading.finish(),$rootscope.$broadcast("object:updated")}),promise.then(null,function(){return $confirm.notify("error")})}}(this)),$el.on("click",".client-requirement",function(event){var client_requirement;if(canEdit())return client_requirement=!$model.$modelValue.client_requirement,save(client_requirement)}),$scope.$watch($attrs.ngModel,function(us){return us?render(us):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,restrict:"EA",require:"ngModel"}},module.directive("tgUsClientRequirementButton",["$rootScope","$tgRepo","$tgConfirm","$tgLoading","$tgQqueue","$tgTemplate","$compile",UsClientRequirementButtonDirective])}.call(this),function(){var TaskDetailController,TaskIsIocaineButtonDirective,TaskStatusButtonDirective,TaskStatusDisplayDirective,bindMethods,groupBy,mixOf,module,taiga,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,mixOf=this.taiga.mixOf,groupBy=this.taiga.groupBy,bindMethods=this.taiga.bindMethods,module=angular.module("taigaTasks"),TaskDetailController=function(superClass){function TaskDetailController(scope,rootscope,repo,confirm,rs,params,q,location,log,appMetaService,navUrls,analytics,translate){var promise;this.scope=scope,this.rootscope=rootscope,this.repo=repo,this.confirm=confirm,this.rs=rs,this.params=params,this.q=q,this.location=location,this.log=log,this.appMetaService=appMetaService,this.navUrls=navUrls,this.analytics=analytics,this.translate=translate,bindMethods(this),this.scope.taskRef=this.params.taskref,this.scope.sectionName=this.translate.instant("TASK.SECTION_NAME"),this.initializeEventHandlers(),promise=this.loadInitialData(),promise.then(function(_this){return function(){return _this._setMeta(),_this.initializeOnDeleteGoToUrl()}}(this)),promise.then(null,this.onInitialDataError.bind(this))}return extend(TaskDetailController,superClass),TaskDetailController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","$log","tgAppMetaService","$tgNavUrls","$tgAnalytics","$translate"],TaskDetailController.prototype._setMeta=function(){var description,ref,title;return title=this.translate.instant("TASK.PAGE_TITLE",{taskRef:"#"+this.scope.task.ref,taskSubject:this.scope.task.subject,projectName:this.scope.project.name}),description=this.translate.instant("TASK.PAGE_DESCRIPTION",{taskStatus:(null!=(ref=this.scope.statusById[this.scope.task.status])?ref.name:void 0)||"--",taskDescription:angular.element(this.scope.task.description_html||"").text()}),this.appMetaService.setAll(title,description)},TaskDetailController.prototype.initializeEventHandlers=function(){return this.scope.$on("attachment:create",function(_this){return function(){return _this.analytics.trackEvent("attachment","create","create attachment on task",1)}}(this)),this.scope.$on("custom-attributes-values:edit",function(_this){return function(){return _this.rootscope.$broadcast("object:updated")}}(this)),this.scope.$on("comment:new",function(_this){return function(){return _this.loadTask()}}(this))},TaskDetailController.prototype.initializeOnDeleteGoToUrl=function(){var ctx;if(ctx={project:this.scope.project.slug},this.scope.onDeleteGoToUrl=this.navUrls.resolve("project",ctx),this.scope.project.is_backlog_activated){if(this.scope.task.milestone)return ctx.sprint=this.scope.sprint.slug,this.scope.onDeleteGoToUrl=this.navUrls.resolve("project-taskboard",ctx);if(this.scope.task.us)return ctx.ref=this.scope.us.ref,this.scope.onDeleteGoToUrl=this.navUrls.resolve("project-userstories-detail",ctx)}else if(this.scope.project.is_kanban_activated&&this.scope.us)return ctx.ref=this.scope.us.ref,this.scope.onDeleteGoToUrl=this.navUrls.resolve("project-userstories-detail",ctx)},TaskDetailController.prototype.loadProject=function(){return this.rs.projects.getBySlug(this.params.pslug).then(function(_this){return function(project){return _this.scope.projectId=project.id,_this.scope.project=project,_this.scope.$emit("project:loaded",project),_this.scope.statusList=project.task_statuses,_this.scope.statusById=groupBy(project.task_statuses,function(x){return x.id}),project}}(this))},TaskDetailController.prototype.loadTask=function(){return this.rs.tasks.getByRef(this.scope.projectId,this.params.taskref).then(function(_this){return function(task){var ctx,ref,ref1;return _this.scope.task=task,_this.scope.taskId=task.id,_this.scope.commentModel=task,null!=(null!=(ref=_this.scope.task.neighbors.previous)?ref.ref:void 0)&&(ctx={project:_this.scope.project.slug,ref:_this.scope.task.neighbors.previous.ref},_this.scope.previousUrl=_this.navUrls.resolve("project-tasks-detail",ctx)),null!=(null!=(ref1=_this.scope.task.neighbors.next)?ref1.ref:void 0)&&(ctx={project:_this.scope.project.slug,ref:_this.scope.task.neighbors.next.ref},_this.scope.nextUrl=_this.navUrls.resolve("project-tasks-detail",ctx)),task}}(this))},TaskDetailController.prototype.loadSprint=function(){return this.scope.task.milestone?this.rs.sprints.get(this.scope.task.project,this.scope.task.milestone).then(function(_this){return function(sprint){return _this.scope.sprint=sprint,sprint}}(this)):void 0},TaskDetailController.prototype.loadUserStory=function(){return this.scope.task.user_story?this.rs.userstories.get(this.scope.task.project,this.scope.task.user_story).then(function(_this){return function(us){return _this.scope.us=us,us}}(this)):void 0},TaskDetailController.prototype.loadInitialData=function(){var promise;return promise=this.loadProject(),promise.then(function(_this){return function(project){return _this.fillUsersAndRoles(project.members,project.roles),_this.loadTask().then(function(){return _this.q.all([_this.loadSprint(),_this.loadUserStory()])})}}(this))},TaskDetailController.prototype.onUpvote=function(){var onError,onSuccess;return onSuccess=function(_this){return function(){return _this.loadTask(),_this.rootscope.$broadcast("object:updated")}}(this),onError=function(_this){return function(){return _this.confirm.notify("error")}}(this),this.rs.tasks.upvote(this.scope.taskId).then(onSuccess,onError)},TaskDetailController.prototype.onDownvote=function(){var onError,onSuccess;return onSuccess=function(_this){return function(){return _this.loadTask(),_this.rootscope.$broadcast("object:updated")}}(this),onError=function(_this){return function(){return _this.confirm.notify("error")}}(this),this.rs.tasks.downvote(this.scope.taskId).then(onSuccess,onError)},TaskDetailController.prototype.onWatch=function(){var onError,onSuccess;return onSuccess=function(_this){return function(){return _this.loadTask(),_this.rootscope.$broadcast("object:updated")}}(this),onError=function(_this){return function(){return _this.confirm.notify("error")}}(this),this.rs.tasks.watch(this.scope.taskId).then(onSuccess,onError)},TaskDetailController.prototype.onUnwatch=function(){var onError,onSuccess;return onSuccess=function(_this){return function(){return _this.loadTask(),_this.rootscope.$broadcast("object:updated")}}(this),onError=function(_this){return function(){return _this.confirm.notify("error")}}(this),this.rs.tasks.unwatch(this.scope.taskId).then(onSuccess,onError)},TaskDetailController}(mixOf(taiga.Controller,taiga.PageMixin)),module.controller("TaskDetailController",TaskDetailController),TaskStatusDisplayDirective=function($template,$compile){var link,template;return template=$template.get("common/components/status-display.html",!0),link=function($scope,$el,$attrs){var render;return render=function(task){var html,status;return status=$scope.statusById[task.status],html=template({is_closed:status.is_closed,status:status}),html=$compile(html)($scope),$el.html(html)},$scope.$watch($attrs.ngModel,function(task){return null!=task?render(task):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,restrict:"EA",require:"ngModel"}},module.directive("tgTaskStatusDisplay",["$tgTemplate","$compile",TaskStatusDisplayDirective]),TaskStatusButtonDirective=function($rootScope,$repo,$confirm,$loading,$qqueue,$compile,$translate,$template){var link,template;return template=$template.get("us/us-status-button.html",!0),link=function($scope,$el,$attrs,$model){var isEditable,render,save;return isEditable=function(){return-1!==$scope.project.my_permissions.indexOf("modify_task")},render=function(_this){return function(task){var html,status;return status=$scope.statusById[task.status],html=$compile(template({status:status,statuses:$scope.statusList,editable:isEditable()}))($scope),$el.html(html)}}(this),save=$qqueue.bindAdd(function(_this){return function(status){var currentLoading,onError,onSuccess,task;return task=$model.$modelValue.clone(),task.status=status,currentLoading=$loading().target($el.find(".level-name")).start(),onSuccess=function(){return $model.$setViewValue(task),$confirm.notify("success"),$rootScope.$broadcast("object:updated"),currentLoading.finish()},onError=function(){return $confirm.notify("error"),currentLoading.finish()},$repo.save(task).then(onSuccess,onError)}}(this)),$el.on("click",".status-data",function(event){return event.preventDefault(),event.stopPropagation(),isEditable()?$el.find(".pop-status").popover().open():void 0}),$el.on("click",".status",function(event){var target;return event.preventDefault(),event.stopPropagation(),isEditable()?(target=angular.element(event.currentTarget),$.fn.popover().closeAll(),save(target.data("status-id"))):void 0}),$scope.$watch($attrs.ngModel,function(task){return task?render(task):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,restrict:"EA",require:"ngModel"}},module.directive("tgTaskStatusButton",["$rootScope","$tgRepo","$tgConfirm","$tgLoading","$tgQqueue","$compile","$translate","$tgTemplate",TaskStatusButtonDirective]),TaskIsIocaineButtonDirective=function($rootscope,$tgrepo,$confirm,$loading,$qqueue,$compile){var link,template;return template=_.template('
\n \n \n
'),link=function($scope,$el,$attrs,$model){var isEditable,render,save;return isEditable=function(){return-1!==$scope.project.my_permissions.indexOf("modify_task")},render=function(task){var ctx,html;return isEditable()||task.is_iocaine?(ctx={isIocaine:task.is_iocaine,isEditable:isEditable()},html=$compile(template(ctx))($scope),$el.html(html)):void $el.html("")},save=$qqueue.bindAdd(function(_this){return function(is_iocaine){var currentLoading,promise,task;return task=$model.$modelValue.clone(),task.is_iocaine=is_iocaine,currentLoading=$loading().target($el.find("label")).start(),promise=$tgrepo.save(task),promise.then(function(){return $model.$setViewValue(task),$confirm.notify("success"),$rootscope.$broadcast("object:updated")}),promise.then(null,function(){return $confirm.notify("error")}),promise["finally"](function(){return currentLoading.finish()})}}(this)),$el.on("click",".is-iocaine",function(event){var is_iocaine;if(isEditable())return is_iocaine=!$model.$modelValue.is_iocaine,save(is_iocaine)}),$scope.$watch($attrs.ngModel,function(task){return task?render(task):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,restrict:"EA",require:"ngModel"}},module.directive("tgTaskIsIocaineButton",["$rootScope","$tgRepo","$tgConfirm","$tgLoading","$tgQqueue","$compile",TaskIsIocaineButtonDirective])}.call(this),function(){var LeaveProjectDirective,TeamController,TeamFiltersDirective,TeamMemberCurrentUserDirective,TeamMemberStatsDirective,TeamMembersDirective,membersFilter,mixOf,module,taiga,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,mixOf=this.taiga.mixOf,module=angular.module("taigaTeam"),TeamController=function(superClass){function TeamController(scope,rootscope,repo,rs,params,q,location,navUrls,appMetaService,auth,translate,projectService){var promise;this.scope=scope,this.rootscope=rootscope,this.repo=repo,this.rs=rs,this.params=params,this.q=q,this.location=location,this.navUrls=navUrls,this.appMetaService=appMetaService,this.auth=auth,this.translate=translate,this.projectService=projectService,this.scope.sectionName="TEAM.SECTION_NAME",promise=this.loadInitialData(),promise.then(function(_this){return function(){var description,title;return title=_this.translate.instant("TEAM.PAGE_TITLE",{projectName:_this.scope.project.name}),description=_this.translate.instant("TEAM.PAGE_DESCRIPTION",{projectName:_this.scope.project.name,projectDescription:_this.scope.project.description}),_this.appMetaService.setAll(title,description)}}(this)),promise.then(null,this.onInitialDataError.bind(this))}return extend(TeamController,superClass),TeamController.$inject=["$scope","$rootScope","$tgRepo","$tgResources","$routeParams","$q","$location","$tgNavUrls","tgAppMetaService","$tgAuth","$translate","tgProjectService"],TeamController.prototype.setRole=function(role){return role?this.scope.filtersRole=role:this.scope.filtersRole=null},TeamController.prototype.loadMembers=function(){var i,len,member,ref,user;for(user=this.auth.getUser(),this.scope.totals={},ref=this.scope.activeUsers,i=0,len=ref.length;len>i;i++)member=ref[i],this.scope.totals[member.id]=0;return this.scope.currentUser=_.find(this.scope.activeUsers,{id:null!=user?user.id:void 0}),this.scope.memberships=_.reject(this.scope.activeUsers,{id:null!=user?user.id:void 0})},TeamController.prototype.loadProject=function(){return this.rs.projects.getBySlug(this.params.pslug).then(function(_this){return function(project){return _this.scope.projectId=project.id,_this.scope.project=project,_this.scope.$emit("project:loaded",project),_this.scope.issuesEnabled=project.is_issues_activated,_this.scope.tasksEnabled=project.is_kanban_activated||project.is_backlog_activated,_this.scope.wikiEnabled=project.is_wiki_activated,project}}(this))},TeamController.prototype.loadMemberStats=function(){return this.rs.projects.memberStats(this.scope.projectId).then(function(_this){return function(stats){var totals;return totals={},_.forEach(_this.scope.totals,function(total,userId){var vals;return vals=_.map(stats,function(memberStats,statsKey){return memberStats[userId]}),total=_.reduce(vals,function(sum,el){return sum+el}),_this.scope.totals[userId]=total}),_this.scope.stats=_this._processStats(stats),_this.scope.stats.totals=_this.scope.totals}}(this))},TeamController.prototype._processStat=function(stat){var max,min,singleStat;return max=_.max(stat),min=_.min(stat),singleStat=_.map(stat,function(value,key){return value===min?[key,.1]:value===max?[key,1]:[key,.5*value/max]}),singleStat=_.object(singleStat)},TeamController.prototype._processStats=function(stats){var key,value;for(key in stats)value=stats[key],stats[key]=this._processStat(value);return stats},TeamController.prototype.loadInitialData=function(){var promise;return promise=this.loadProject(),promise.then(function(_this){return function(project){return _this.fillUsersAndRoles(project.members,project.roles),_this.loadMembers(),_this.loadMemberStats()}}(this))},TeamController}(mixOf(taiga.Controller,taiga.PageMixin)),module.controller("TeamController",TeamController),TeamFiltersDirective=function(){return{templateUrl:"team/team-filter.html"}},module.directive("tgTeamFilters",[TeamFiltersDirective]),TeamMemberStatsDirective=function(){return{templateUrl:"team/team-member-stats.html",scope:{stats:"=",userId:"=user",issuesEnabled:"=issuesenabled",tasksEnabled:"=tasksenabled",wikiEnabled:"=wikienabled"}}},module.directive("tgTeamMemberStats",TeamMemberStatsDirective),TeamMemberCurrentUserDirective=function(){return{templateUrl:"team/team-member-current-user.html",scope:{projectId:"=projectid",currentUser:"=currentuser",stats:"=",issuesEnabled:"=issuesenabled",tasksEnabled:"=tasksenabled",wikiEnabled:"=wikienabled"}}},module.directive("tgTeamCurrentUser",TeamMemberCurrentUserDirective),TeamMembersDirective=function(){var template;return template="team/team-members.html",{templateUrl:template,scope:{memberships:"=",filtersQ:"=filtersq",filtersRole:"=filtersrole",stats:"=",issuesEnabled:"=issuesenabled",tasksEnabled:"=tasksenabled",wikiEnabled:"=wikienabled"}}},module.directive("tgTeamMembers",TeamMembersDirective),LeaveProjectDirective=function($repo,$confirm,$location,$rs,$navurls,$translate){var link;return link=function($scope,$el,$attrs){return $scope.leave=function(){var confirm_leave_project_text,leave_project_text;return leave_project_text=$translate.instant("TEAM.ACTION_LEAVE_PROJECT"),confirm_leave_project_text=$translate.instant("TEAM.CONFIRM_LEAVE_PROJECT"),$confirm.ask(leave_project_text,confirm_leave_project_text).then(function(_this){return function(response){var promise;return promise=$rs.projects.leave($attrs.projectid),promise.then(function(){return response.finish(),$confirm.notify("success"),$location.path($navurls.resolve("home"))}),promise.then(null,function(response){return response.finish(),$confirm.notify("error",response.data._error_message)})}}(this))}},{scope:{},templateUrl:"team/leave-project.html",link:link}},module.directive("tgLeaveProject",["$tgRepo","$tgConfirm","$tgLocation","$tgResources","$tgNavUrls","$translate",LeaveProjectDirective]),membersFilter=function(){return function(members,filtersQ,filtersRole){return _.filter(members,function(m){return(!filtersRole||m.role===filtersRole.id)&&(!filtersQ||m.full_name.search(new RegExp(filtersQ,"i"))>=0)})}},module.filter("membersFilter",membersFilter)}.call(this),function(){var EditableWikiContentDirective,WikiDetailController,WikiSummaryDirective,bindOnce,debounce,groupBy,mixOf,module,taiga,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,mixOf=this.taiga.mixOf,groupBy=this.taiga.groupBy,bindOnce=this.taiga.bindOnce,debounce=this.taiga.debounce,module=angular.module("taigaWiki"),WikiDetailController=function(superClass){function WikiDetailController(scope,rootscope,repo,model,confirm,rs,params,q,location,filter,log,appMetaService,navUrls,analytics,translate){var promise;this.scope=scope,this.rootscope=rootscope,this.repo=repo,this.model=model,this.confirm=confirm,this.rs=rs,this.params=params,this.q=q,this.location=location,this.filter=filter,this.log=log,this.appMetaService=appMetaService,this.navUrls=navUrls,this.analytics=analytics,this.translate=translate,this.scope.projectSlug=this.params.pslug,this.scope.wikiSlug=this.params.slug,this.scope.wikiTitle=this.scope.wikiSlug,this.scope.sectionName="Wiki",promise=this.loadInitialData(),promise.then(function(_this){return function(){return _this._setMeta()}}(this)),promise.then(null,this.onInitialDataError.bind(this))}return extend(WikiDetailController,superClass),WikiDetailController.$inject=["$scope","$rootScope","$tgRepo","$tgModel","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","$filter","$log","tgAppMetaService","$tgNavUrls","$tgAnalytics","$translate"],WikiDetailController.prototype._setMeta=function(){var description,title;return title=this.translate.instant("WIKI.PAGE_TITLE",{wikiPageName:this.scope.wikiTitle,projectName:this.scope.project.name}),description=this.translate.instant("WIKI.PAGE_DESCRIPTION",{wikiPageContent:angular.element(this.scope.wiki.html||"").text(),totalEditions:this.scope.wiki.editions||0,lastModifiedDate:moment(this.scope.wiki.modified_date).format(this.translate.instant("WIKI.DATETIME"))}),this.appMetaService.setAll(title,description)},WikiDetailController.prototype.loadProject=function(){return this.rs.projects.getBySlug(this.params.pslug).then(function(_this){return function(project){return project.is_wiki_activated||_this.location.path(_this.navUrls.resolve("permission-denied")),_this.scope.projectId=project.id,_this.scope.project=project,_this.scope.$emit("project:loaded",project),project}}(this))},WikiDetailController.prototype.loadWiki=function(){var promise;return promise=this.rs.wiki.getBySlug(this.scope.projectId,this.params.slug),promise.then(function(_this){return function(wiki){return _this.scope.wiki=wiki,_this.scope.wikiId=wiki.id,_this.scope.wiki}}(this)),promise.then(null,function(_this){return function(xhr){var data;return _this.scope.wikiId=null,-1===_this.scope.project.my_permissions.indexOf("add_wiki_page")?null:(data={project:_this.scope.projectId,slug:_this.scope.wikiSlug,content:""},_this.scope.wiki=_this.model.make_model("wiki",data),_this.scope.wiki)}}(this))},WikiDetailController.prototype.loadWikiLinks=function(){return this.rs.wiki.listLinks(this.scope.projectId).then(function(_this){return function(wikiLinks){var selectedWikiLink;return _this.scope.wikiLinks=wikiLinks,selectedWikiLink=_.find(wikiLinks,{href:_this.scope.wikiSlug}),null!=selectedWikiLink?_this.scope.wikiTitle=selectedWikiLink.title:void 0}}(this))},WikiDetailController.prototype.loadInitialData=function(){var promise;return promise=this.loadProject(),promise.then(function(_this){return function(project){return _this.fillUsersAndRoles(project.members,project.roles),_this.q.all([_this.loadWikiLinks(),_this.loadWiki()]).then(function(){})}}(this))},WikiDetailController.prototype["delete"]=function(){var message,title;return title=this.translate.instant("WIKI.DELETE_LIGHTBOX_TITLE"),message=this.scope.wikiTitle,this.confirm.askOnDelete(title,message).then(function(_this){return function(askResponse){var onError,onSuccess;return onSuccess=function(){var ctx;return askResponse.finish(),ctx={project:_this.scope.projectSlug},_this.location.path(_this.navUrls.resolve("project-wiki",ctx)),_this.confirm.notify("success")},onError=function(){return askResponse.finish(!1),_this.confirm.notify("error")},_this.repo.remove(_this.scope.wiki).then(onSuccess,onError)}}(this))},WikiDetailController}(mixOf(taiga.Controller,taiga.PageMixin)),module.controller("WikiDetailController",WikiDetailController), -WikiSummaryDirective=function($log,$template,$compile,$translate){var link,template;return template=$template.get("wiki/wiki-summary.html",!0),link=function($scope,$el,$attrs,$model){var render;return render=function(wiki){var ctx,html,user;return null==$scope.usersById?$log.error("WikiSummaryDirective requires userById set in scope."):user=$scope.usersById[wiki.last_modifier],user=void 0===user?{name:"unknown",imgUrl:"/"+window._version+"/images/user-noimage.png"}:{name:user.full_name_display,imgUrl:user.photo},ctx={totalEditions:wiki.editions,lastModifiedDate:moment(wiki.modified_date).format($translate.instant("WIKI.DATETIME")),user:user},html=template(ctx),html=$compile(html)($scope),$el.html(html)},$scope.$watch($attrs.ngModel,function(wikiPage){return wikiPage?render(wikiPage):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,restrict:"EA",require:"ngModel"}},module.directive("tgWikiSummary",["$log","$tgTemplate","$compile","$translate",WikiSummaryDirective]),EditableWikiContentDirective=function($window,$document,$repo,$confirm,$loading,$analytics,$qqueue){var link;return link=function($scope,$el,$attrs,$model){var cancelEdition,disableEdition,getSelectedText,isEditable,save,switchToEditMode,switchToReadMode;return isEditable=function(){return-1!==$scope.project.my_permissions.indexOf("modify_wiki_page")},switchToEditMode=function(){return $el.find(".edit-wiki-content").show(),$el.find(".view-wiki-content").hide(),$el.find("textarea").focus()},switchToReadMode=function(){return $el.find(".edit-wiki-content").hide(),$el.find(".view-wiki-content").show()},disableEdition=function(){return $el.find(".view-wiki-content .edit").remove(),$el.find(".edit-wiki-content").remove()},cancelEdition=function(){return $model.$modelValue.id?($scope.$apply(function(_this){return function(){return $model.$modelValue.revert()}}(this)),switchToReadMode()):void 0},getSelectedText=function(){return $window.getSelection?$window.getSelection().toString():$document.selection?$document.selection.createRange().text:null},save=$qqueue.bindAdd(function(wiki){var currentLoading,onError,onSuccess,promise;return onSuccess=function(wikiPage){return null==wiki.id&&$analytics.trackEvent("wikipage","create","create wiki page",1),$model.$setViewValue(wikiPage.clone()),$confirm.notify("success"),switchToReadMode()},onError=function(){return $confirm.notify("error")},currentLoading=$loading().removeClasses("icon-floppy").target($el.find(".icon-floppy")).start(),promise=null!=wiki.id?$repo.save(wiki).then(onSuccess,onError):$repo.create("wiki",wiki).then(onSuccess,onError),promise["finally"](function(){return currentLoading.finish()})}),$el.on("click","a",function(event){var href,target;return target=angular.element(event.target),href=target.attr("href"),0===href.indexOf("#")?(event.preventDefault(),$("body").scrollTop($(href).offset().top)):void 0}),$el.on("mousedown",".view-wiki-content",function(event){var target;target=angular.element(event.target),isEditable()&&2===event.button}),$el.on("mouseup",".view-wiki-content",function(event){var target;return target=angular.element(event.target),getSelectedText()||!isEditable()||target.is("a")||target.is("pre")?void 0:switchToEditMode()}),$el.on("click",".save",debounce(2e3,function(){return save($scope.wiki)})),$el.on("click",".cancel",function(){return cancelEdition()}),$el.on("keydown","textarea",function(event){return 27===event.keyCode?cancelEdition():void 0}),$scope.$watch($attrs.ngModel,function(wikiPage){return wikiPage?isEditable()?($el.addClass("editable"),null==wikiPage.id||0===$.trim(wikiPage.content).length?switchToEditMode():void 0):disableEdition():void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,restrict:"EA",require:"ngModel",templateUrl:"wiki/editable-wiki-content.html"}},module.directive("tgEditableWikiContent",["$window","$document","$tgRepo","$tgConfirm","$tgLoading","$tgAnalytics","$tgQqueue",EditableWikiContentDirective])}.call(this),function(){var WikiNavDirective,bindOnce,groupBy,mixOf,module,taiga;taiga=this.taiga,mixOf=this.taiga.mixOf,groupBy=this.taiga.groupBy,bindOnce=this.taiga.bindOnce,module=angular.module("taigaWiki"),WikiNavDirective=function($tgrepo,$log,$location,$confirm,$navUrls,$analytics,$loading,$template,$compile,$translate){var link,template;return template=$template.get("wiki/wiki-nav.html",!0),link=function($scope,$el,$attrs){var $ctrl,render;return $ctrl=$el.controller(),null==$attrs.ngModel?$log.error("WikiNavDirective: no ng-model attr is defined"):(render=function(wikiLinks){var addWikiLinkPermission,deleteWikiLinkPermission,html;return addWikiLinkPermission=$scope.project.my_permissions.indexOf("add_wiki_link")>-1,deleteWikiLinkPermission=$scope.project.my_permissions.indexOf("delete_wiki_link")>-1,html=template({wikiLinks:wikiLinks,projectSlug:$scope.projectSlug,addWikiLinkPermission:addWikiLinkPermission,deleteWikiLinkPermission:deleteWikiLinkPermission}),html=$compile(html)($scope),$el.off(),$el.html(html),$el.on("click",".wiki-link .link-title",function(event){var linkId,linkSlug,target;return event.preventDefault(),target=angular.element(event.currentTarget),linkId=target.parents(".wiki-link").data("id"),linkSlug=$scope.wikiLinks[linkId].href,$scope.$apply(function(){var ctx;return ctx={project:$scope.projectSlug,slug:linkSlug},$location.path($navUrls.resolve("project-wiki-page",ctx))})}),$el.on("click",".add-button",function(event){return event.preventDefault(),$el.find(".new").removeClass("hidden"),$el.find(".new input").focus(),$el.find(".add-button").hide()}),$el.on("click",".wiki-link .icon-delete",function(event){var linkId,message,target,title;return event.preventDefault(),event.stopPropagation(),target=angular.element(event.currentTarget),linkId=target.parents(".wiki-link").data("id"),title=$translate.instant("WIKI.DELETE_LIGHTBOX_TITLE"),message=$scope.wikiLinks[linkId].title,$confirm.askOnDelete(title,message).then(function(_this){return function(askResponse){var promise;return promise=$tgrepo.remove($scope.wikiLinks[linkId]),promise.then(function(){return promise=$ctrl.loadWikiLinks(),promise.then(function(){return askResponse.finish(),render($scope.wikiLinks)}),promise.then(null,function(){return askResponse.finish()})}),promise.then(null,function(){return askResponse.finish(!1),$confirm.notify("error")})}}(this))}),$el.on("keyup",".new input",function(event){var currentLoading,newLink,promise,target;return event.preventDefault(),13===event.keyCode?(target=angular.element(event.currentTarget),newLink=target.val(),currentLoading=$loading().target($el.find(".new")).start(),promise=$tgrepo.create("wiki-links",{project:$scope.projectId,title:newLink}),promise.then(function(){var loadPromise;return $analytics.trackEvent("wikilink","create","create wiki link",1),loadPromise=$ctrl.loadWikiLinks(),loadPromise.then(function(){return currentLoading.finish(),$el.find(".new").addClass("hidden"),$el.find(".new input").val(""),$el.find(".add-button").show(),render($scope.wikiLinks)}),loadPromise.then(null,function(){return currentLoading.finish(),$el.find(".new").addClass("hidden"),$el.find(".new input").val(""),$el.find(".add-button").show(),$confirm.notify("error","Error loading wiki links")})}),promise.then(null,function(error){var ref;return currentLoading.finish(),$el.find(".new input").val(newLink),$el.find(".new input").focus().select(),null!=(null!=error&&null!=(ref=error.__all__)?ref[0]:void 0)?$confirm.notify("error","The link already exists"):$confirm.notify("error")})):27===event.keyCode?(target=angular.element(event.currentTarget),$el.find(".new").addClass("hidden"),$el.find(".new input").val(""),$el.find(".add-button").show()):void 0})},bindOnce($scope,$attrs.ngModel,render))},{link:link}},module.directive("tgWikiNav",["$tgRepo","$log","$tgLocation","$tgConfirm","$tgNavUrls","$tgAnalytics","$tgLoading","$tgTemplate","$compile","$translate",WikiNavDirective])}.call(this),function(){var CreateMembersDirective,MAX_MEMBERSHIP_FIELDSETS,debounce,module,taiga;taiga=this.taiga,debounce=this.taiga.debounce,module=angular.module("taigaKanban"),MAX_MEMBERSHIP_FIELDSETS=4,CreateMembersDirective=function($rs,$rootScope,$confirm,$loading,lightboxService,$compile){var extraTextTemplate,link,template;return extraTextTemplate='
\n \n
',template=_.template('
\n
\n data-required="true" <% } %> data-type="email" />\n
\n
\n \n \n
\n
'),link=function($scope,$el,$attrs){var createFieldSet,resetForm,submit,submitButton;return createFieldSet=function(required){var ctx;return null==required&&(required=!0),ctx={roleList:$scope.project.roles,required:required},$compile(template(ctx))($scope)},resetForm=function(){var fieldSet,invitations;return $el.find("form textarea").remove(),$el.find("form .add-member-wrapper").remove(),invitations=$el.find(".add-member-forms"),invitations.html($compile(extraTextTemplate)($scope)),fieldSet=createFieldSet(),invitations.prepend(fieldSet)},$scope.$on("membersform:new",function(){return resetForm(),lightboxService.open($el)}),$scope.$on("$destroy",function(){return $el.off()}),$el.on("click",".delete-fieldset",function(event){var fieldSet,lastActionButton,target;return event.preventDefault(),target=angular.element(event.currentTarget),fieldSet=target.closest(".add-member-wrapper"),fieldSet.remove(),lastActionButton=$el.find(".add-member-wrapper fieldset:last > a"),lastActionButton.hasClass("icon-delete delete-fieldset")?lastActionButton.removeClass("icon-delete delete-fieldset").addClass("icon-plus add-fieldset"):void 0}),$el.on("click",".add-fieldset",function(event){var fieldSet,newFieldSet,target;return event.preventDefault(),target=angular.element(event.currentTarget),fieldSet=target.closest(".add-member-wrapper"),target.removeClass("icon-plus add-fieldset").addClass("icon-delete delete-fieldset"),newFieldSet=createFieldSet(!1),fieldSet.after(newFieldSet),$scope.$digest(),$el.find(".add-member-wrapper").length===MAX_MEMBERSHIP_FIELDSETS?$el.find(".add-member-wrapper fieldset:last > a").removeClass("icon-plus add-fieldset").addClass("icon-delete delete-fieldset"):void 0}),submit=debounce(2e3,function(_this){return function(event){var currentLoading,form,invitation_extra_text,invitations,memberWrappers,onError,onSuccess,promise;return event.preventDefault(),currentLoading=$loading().target(submitButton).start(),onSuccess=function(data){return currentLoading.finish(),lightboxService.close($el),$confirm.notify("success"),$rootScope.$broadcast("membersform:new:success")},onError=function(data){return currentLoading.finish(),lightboxService.close($el),$confirm.notify("error"),$rootScope.$broadcast("membersform:new:error")},form=$el.find("form").checksley(),form.destroy(),form.initialize(),form.validate()?(memberWrappers=$el.find("form .add-member-wrapper"),memberWrappers=_.filter(memberWrappers,function(mw){return angular.element(mw).find("input").hasClass("checksley-ok")}),invitations=_.map(memberWrappers,function(mw){var email,memberWrapper,role;return memberWrapper=angular.element(mw),email=memberWrapper.find("input"),role=memberWrapper.find("select"),{email:email.val(),role_id:role.val()}}),invitations.length?(invitation_extra_text=$el.find("form textarea").val(),promise=$rs.memberships.bulkCreateMemberships($scope.project.id,invitations,invitation_extra_text),promise.then(onSuccess,onError)):void 0):void 0}}(this)),submitButton=$el.find(".submit-button"),$el.on("submit","form",submit)},{link:link}},module.directive("tgLbCreateMembers",["$tgResources","$rootScope","$tgConfirm","$tgLoading","lightboxService","$compile",CreateMembersDirective])}.call(this),function(){var MembershipsController,MembershipsDirective,MembershipsRowActionsDirective,MembershipsRowAdminCheckboxDirective,MembershipsRowAvatarDirective,MembershipsRowRoleSelectorDirective,bindMethods,mixOf,module,taiga,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,mixOf=this.taiga.mixOf,bindMethods=this.taiga.bindMethods,module=angular.module("taigaAdmin"),MembershipsController=function(superClass){function MembershipsController(scope,rootscope,repo,confirm,rs,params,q,location,navUrls,analytics,appMetaService,translate){var promise;this.scope=scope,this.rootscope=rootscope,this.repo=repo,this.confirm=confirm,this.rs=rs,this.params=params,this.q=q,this.location=location,this.navUrls=navUrls,this.analytics=analytics,this.appMetaService=appMetaService,this.translate=translate,bindMethods(this),this.scope.project={},this.scope.filters={},promise=this.loadInitialData(),promise.then(function(_this){return function(){var description,title;return title=_this.translate.instant("ADMIN.MEMBERSHIPS.PAGE_TITLE",{projectName:_this.scope.project.name}),description=_this.scope.project.description,_this.appMetaService.setAll(title,description)}}(this)),promise.then(null,this.onInitialDataError.bind(this)),this.scope.$on("membersform:new:success",function(_this){return function(){return _this.loadMembers(),_this.analytics.trackEvent("membership","create","create memberships on admin",1)}}(this))}return extend(MembershipsController,superClass),MembershipsController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","$tgNavUrls","$tgAnalytics","tgAppMetaService","$translate"],MembershipsController.prototype.loadProject=function(){return this.rs.projects.getBySlug(this.params.pslug).then(function(_this){return function(project){return project.i_am_owner||_this.location.path(_this.navUrls.resolve("permission-denied")),_this.scope.projectId=project.id,_this.scope.project=project,_this.scope.$emit("project:loaded",project),project}}(this))},MembershipsController.prototype.loadMembers=function(){var httpFilters;return httpFilters=this.getUrlFilters(),this.rs.memberships.list(this.scope.projectId,httpFilters).then(function(_this){return function(data){return _this.scope.memberships=_.filter(data.models,function(membership){return null===membership.user||membership.is_user_active}),_this.scope.page=data.current,_this.scope.count=data.count,_this.scope.paginatedBy=data.paginatedBy,data}}(this))},MembershipsController.prototype.loadInitialData=function(){var promise;return promise=this.loadProject(),promise.then(function(_this){return function(){return _this.loadMembers()}}(this)),promise},MembershipsController.prototype.getUrlFilters=function(){var filters;return filters=_.pick(this.location.search(),"page"),filters.page||(filters.page=1),filters},MembershipsController.prototype.addNewMembers=function(){return this.rootscope.$broadcast("membersform:new")},MembershipsController}(mixOf(taiga.Controller,taiga.PageMixin,taiga.FiltersMixin)),module.controller("MembershipsController",MembershipsController),MembershipsDirective=function($template,$compile){var link,linkPagination,template;return template=$template.get("admin/admin-membership-paginator.html",!0),linkPagination=function($scope,$el,$attrs,$ctrl){var $pagEl,afterCurrent,atBegin,atEnd,beforeCurrent,getNumPages,renderPagination;return afterCurrent=2,beforeCurrent=4,atBegin=2,atEnd=2,$pagEl=$el.find(".memberships-paginator"),getNumPages=function(){var numPages;return numPages=$scope.count/$scope.paginatedBy,numPages=parseInt(numPages,10)=numPages)return void $pagEl.hide();for(pages=[],options={},options.pages=pages,options.showPrevious=$scope.page>1,options.showNext=!($scope.page===numPages),cpage=$scope.page,i=j=1,ref=numPages;ref>=1?ref>=j:j>=ref;i=ref>=1?++j:--j)i===cpage+afterCurrent&&numPages>cpage+afterCurrent+atEnd?pages.push({classes:"dots",type:"dots"}):i===cpage-beforeCurrent&&cpage>atBegin+beforeCurrent?pages.push({classes:"dots",type:"dots"}):i>cpage+afterCurrent&&numPages-atEnd>=i||cpage-beforeCurrent>i&&i>atBegin||(i===cpage?pages.push({classes:"active",num:i,type:"page-active"}):pages.push({classes:"page",num:i,type:"page"}));return html=template(options),html=$compile(html)($scope),$pagEl.html(html),$pagEl.show()},$scope.$watch("memberships",function(value){return value?renderPagination():void 0}),$el.on("click",".memberships-paginator a.next",function(event){return event.preventDefault(),$scope.$apply(function(){return $ctrl.selectFilter("page",$scope.page+1),$ctrl.loadMembers()})}),$el.on("click",".memberships-paginator a.previous",function(event){return event.preventDefault(),$scope.$apply(function(){return $ctrl.selectFilter("page",$scope.page-1),$ctrl.loadMembers()})}),$el.on("click",".memberships-paginator li.page > a",function(event){var pagenum,target;return event.preventDefault(),target=angular.element(event.currentTarget),pagenum=target.data("pagenum"),$scope.$apply(function(){return $ctrl.selectFilter("page",pagenum),$ctrl.loadMembers()})})},link=function($scope,$el,$attrs){var $ctrl;return $ctrl=$el.controller(),linkPagination($scope,$el,$attrs,$ctrl),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgMemberships",["$tgTemplate","$compile",MembershipsDirective]),MembershipsRowAvatarDirective=function($log,$template,$translate){var link,template;return template=$template.get("admin/memberships-row-avatar.html",!0),link=function($scope,$el,$attrs){var member,pending,render;return pending=$translate.instant("ADMIN.MEMBERSHIP.STATUS_PENDING"),render=function(member){var ctx,html;return ctx={full_name:member.full_name?member.full_name:"",email:member.user_email?member.user_email:member.email,imgurl:member.photo?member.photo:"/"+window._version+"/images/unnamed.png",pending:member.is_user_active?"":pending},html=template(ctx),$el.html(html)},null==$attrs.tgMembershipsRowAvatar?$log.error("MembershipsRowAvatarDirective: the directive need a member"):(member=$scope.$eval($attrs.tgMembershipsRowAvatar),render(member),$scope.$on("$destroy",function(){return $el.off()}))},{link:link}},module.directive("tgMembershipsRowAvatar",["$log","$tgTemplate","$translate",MembershipsRowAvatarDirective]),MembershipsRowAdminCheckboxDirective=function($log,$repo,$confirm,$template,$compile){var link,template;return template=$template.get("admin/admin-memberships-row-checkbox.html",!0),link=function($scope,$el,$attrs){var html,member,render;return render=function(member){var ctx,html;return ctx={inputId:"is-admin-"+member.id},html=template(ctx),html=$compile(html)($scope),$el.html(html)},null==$attrs.tgMembershipsRowAdminCheckbox?$log.error("MembershipsRowAdminCheckboxDirective: the directive need a member"):(member=$scope.$eval($attrs.tgMembershipsRowAdminCheckbox),html=render(member),member.is_owner&&$el.find(":checkbox").prop("checked",!0),$el.on("click",":checkbox",function(_this){return function(event){var onError,onSuccess,target;return onSuccess=function(){return $confirm.notify("success")},onError=function(data){return member.revert(),$el.find(":checkbox").prop("checked",member.is_owner),$confirm.notify("error",data.is_owner[0])},target=angular.element(event.currentTarget),member.is_owner=target.prop("checked"),$repo.save(member).then(onSuccess,onError)}}(this)),$scope.$on("$destroy",function(){return $el.off()}))},{link:link}},module.directive("tgMembershipsRowAdminCheckbox",["$log","$tgRepo","$tgConfirm","$tgTemplate","$compile",MembershipsRowAdminCheckboxDirective]),MembershipsRowRoleSelectorDirective=function($log,$repo,$confirm){var link,template;return template=_.template(''),link=function($scope,$el,$attrs){var $ctrl,html,member,render;return render=function(member){var ctx,html;return ctx={roleList:$scope.project.roles,selectedRole:member.role},html=template(ctx),$el.html(html)},null==$attrs.tgMembershipsRowRoleSelector?$log.error("MembershipsRowRoleSelectorDirective: the directive need a member"):($ctrl=$el.controller(),member=$scope.$eval($attrs.tgMembershipsRowRoleSelector),html=render(member),$el.on("change","select",function(_this){return function(event){var newRole,onError,onSuccess,target;return onSuccess=function(){return $confirm.notify("success")},onError=function(){return $confirm.notify("error")},target=angular.element(event.currentTarget),newRole=parseInt(target.val(),10),member.role!==newRole?(member.role=newRole,$repo.save(member).then(onSuccess,onError)):void 0}}(this)),$scope.$on("$destroy",function(){return $el.off()}))},{link:link}},module.directive("tgMembershipsRowRoleSelector",["$log","$tgRepo","$tgConfirm",MembershipsRowRoleSelectorDirective]),MembershipsRowActionsDirective=function($log,$repo,$rs,$confirm,$compile,$translate){var activedTemplate,link,pendingTemplate;return activedTemplate='
\n
\n\n \n',pendingTemplate='\n\n\n \n',link=function($scope,$el,$attrs){var $ctrl,member,render;return render=function(member){var html;return html=member.user?$compile(activedTemplate)($scope):$compile(pendingTemplate)($scope),$el.html(html)},null==$attrs.tgMembershipsRowActions?$log.error("MembershipsRowActionsDirective: the directive need a member"):($ctrl=$el.controller(),member=$scope.$eval($attrs.tgMembershipsRowActions),render(member),$el.on("click",".js-resend",function(event){var onError,onSuccess;return event.preventDefault(),onSuccess=function(){var text;return text=$translate.instant("ADMIN.MEMBERSHIP.SUCCESS_SEND_INVITATION",{email:$scope.member.email}),$confirm.notify("success",text)},onError=function(){var text;return text=$translate.instant("ADMIM.MEMBERSHIP.ERROR_SEND_INVITATION"),$confirm.notify("error",text)},$rs.memberships.resendInvitation($scope.member.id).then(onSuccess,onError)}),$el.on("click",".delete",function(event){var defaultMsg,message,title;return event.preventDefault(),title=$translate.instant("ADMIN.MEMBERSHIP.DELETE_MEMBER"),defaultMsg=$translate.instant("ADMIN.MEMBERSHIP.DEFAULT_DELETE_MESSAGE",{email:member.email}),message=member.user?member.full_name:defaultMsg,$confirm.askOnDelete(title,message).then(function(askResponse){var onError,onSuccess;return onSuccess=function(_this){return function(){var text;return askResponse.finish(),$scope.page>1&&$scope.count-1<=$scope.paginatedBy&&$ctrl.selectFilter("page",$scope.page-1),$ctrl.loadMembers(),text=$translate.instant("ADMIN.MEMBERSHIP.SUCCESS_DELETE"),$confirm.notify("success",null,text)}}(this),onError=function(_this){return function(){var text;return askResponse.finish(!1),text=$translate.instant("ADMIN.MEMBERSHIP.ERROR_DELETE",{message:message}),$confirm.notify("error",null,text)}}(this),$repo.remove(member).then(onSuccess,onError)})}),$scope.$on("$destroy",function(){return $el.off()}))},{link:link}},module.directive("tgMembershipsRowActions",["$log","$tgRepo","$tgResources","$tgConfirm","$compile","$translate",MembershipsRowActionsDirective])}.call(this),function(){var AdminNavigationDirective,module;AdminNavigationDirective=function(){var link;return link=function($scope,$el,$attrs){var section;return section=$attrs.tgAdminNavigation,$el.find(".active").removeClass("active"),$el.find("#adminmenu-"+section+" a").addClass("active"),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module=angular.module("taigaAdmin"),module.directive("tgAdminNavigation",AdminNavigationDirective)}.call(this),function(){var CsvExporterController,CsvExporterIssuesController,CsvExporterTasksController,CsvExporterUserstoriesController,CsvIssueDirective,CsvTaskDirective,CsvUsDirective,ProjectDefaultValuesDirective,ProjectExportDirective,ProjectModulesDirective,ProjectProfileController,ProjectProfileDirective,bindOnce,debounce,groupBy,joinStr,mixOf,module,taiga,toString,trim,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty,bind=function(fn,me){return function(){return fn.apply(me,arguments)}};taiga=this.taiga,mixOf=this.taiga.mixOf,trim=this.taiga.trim,toString=this.taiga.toString,joinStr=this.taiga.joinStr,groupBy=this.taiga.groupBy,bindOnce=this.taiga.bindOnce,debounce=this.taiga.debounce,module=angular.module("taigaAdmin"),ProjectProfileController=function(superClass){function ProjectProfileController(scope,rootscope,repo,confirm,rs,params,q,location,navUrls,appMetaService,translate){var promise;this.scope=scope,this.rootscope=rootscope,this.repo=repo,this.confirm=confirm,this.rs=rs,this.params=params,this.q=q,this.location=location,this.navUrls=navUrls,this.appMetaService=appMetaService,this.translate=translate,this.scope.project={},promise=this.loadInitialData(),promise.then(function(_this){return function(){var description,sectionName,title;return sectionName=_this.translate.instant(_this.scope.sectionName),title=_this.translate.instant("ADMIN.PROJECT_PROFILE.PAGE_TITLE",{sectionName:sectionName,projectName:_this.scope.project.name}),description=_this.scope.project.description,_this.appMetaService.setAll(title,description)}}(this)),promise.then(null,this.onInitialDataError.bind(this)),this.scope.$on("project:loaded",function(_this){return function(){var description,sectionName,title;return sectionName=_this.translate.instant(_this.scope.sectionName),title=_this.translate.instant("ADMIN.PROJECT_PROFILE.PAGE_TITLE",{sectionName:sectionName,projectName:_this.scope.project.name}),description=_this.scope.project.description,_this.appMetaService.setAll(title,description)}}(this))}return extend(ProjectProfileController,superClass),ProjectProfileController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","$tgNavUrls","tgAppMetaService","$translate"],ProjectProfileController.prototype.loadProject=function(){return this.rs.projects.getBySlug(this.params.pslug).then(function(_this){return function(project){return project.i_am_owner||_this.location.path(_this.navUrls.resolve("permission-denied")),_this.scope.projectId=project.id,_this.scope.project=project,_this.scope.pointsList=_.sortBy(project.points,"order"),_this.scope.usStatusList=_.sortBy(project.us_statuses,"order"),_this.scope.taskStatusList=_.sortBy(project.task_statuses,"order"),_this.scope.prioritiesList=_.sortBy(project.priorities,"order"),_this.scope.severitiesList=_.sortBy(project.severities,"order"),_this.scope.issueTypesList=_.sortBy(project.issue_types,"order"),_this.scope.issueStatusList=_.sortBy(project.issue_statuses,"order"),_this.scope.$emit("project:loaded",project),project}}(this))},ProjectProfileController.prototype.loadInitialData=function(){var promise;return promise=this.loadProject()},ProjectProfileController.prototype.openDeleteLightbox=function(){return this.rootscope.$broadcast("deletelightbox:new",this.scope.project)},ProjectProfileController}(mixOf(taiga.Controller,taiga.PageMixin)),module.controller("ProjectProfileController",ProjectProfileController),ProjectProfileDirective=function($repo,$confirm,$loading,$navurls,$location,projectService,currentUserService){var link;return link=function($scope,$el,$attrs){var $ctrl,form,submit,submitButton;return $ctrl=$el.controller(),form=$el.find("form").checksley({onlyOneErrorElement:!0}),submit=debounce(2e3,function(_this){return function(event){var currentLoading,promise;return event.preventDefault(),form.validate()?(currentLoading=$loading().target(submitButton).start(),promise=$repo.save($scope.project),promise.then(function(){var newUrl;return currentLoading.finish(),$confirm.notify("success"),newUrl=$navurls.resolve("project-admin-project-profile-details",{project:$scope.project.slug}),$location.path(newUrl),$ctrl.loadInitialData(),projectService.fetchProject(),currentUserService.loadProjects()}),promise.then(null,function(data){return currentLoading.finish(),form.setErrors(data),data._error_message?$confirm.notify("error",data._error_message):void 0})):void 0}}(this)),submitButton=$el.find(".submit-button"),$el.on("submit","form",submit)},{link:link}},module.directive("tgProjectProfile",["$tgRepo","$tgConfirm","$tgLoading","$tgNavUrls","$tgLocation","tgProjectService","tgCurrentUserService",ProjectProfileDirective]),ProjectDefaultValuesDirective=function($repo,$confirm,$loading){var link;return link=function($scope,$el,$attrs){var form,submit,submitButton;return form=$el.find("form").checksley({onlyOneErrorElement:!0}),submit=debounce(2e3,function(_this){return function(event){var currentLoading,promise;return event.preventDefault(),form.validate()?(currentLoading=$loading().target(submitButton).start(),promise=$repo.save($scope.project),promise.then(function(){return currentLoading.finish(),$confirm.notify("success")}),promise.then(null,function(data){return currentLoading.finish(),form.setErrors(data),data._error_message?$confirm.notify("error",data._error_message):void 0})):void 0}}(this)),submitButton=$el.find(".submit-button"),$el.on("submit","form",submit),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgProjectDefaultValues",["$tgRepo","$tgConfirm","$tgLoading",ProjectDefaultValuesDirective]),ProjectModulesDirective=function($repo,$confirm,$loading,projectService){var link;return link=function($scope,$el,$attrs){var submit;return submit=function(_this){return function(){var currentLoading,form,promise,target;return form=$el.find("form").checksley(),form.validate()?(target=angular.element(".admin-functionalities .submit-button"),currentLoading=$loading().target(target).start(),promise=$repo.save($scope.project),promise.then(function(){return currentLoading.finish(),$confirm.notify("success"),$scope.$emit("project:loaded",$scope.project),projectService.fetchProject()}),promise.then(null,function(data){return currentLoading.finish(),$confirm.notify("error",data._error_message)})):void 0}}(this),$el.on("submit","form",function(event){return event.preventDefault(),submit()}),$el.on("click",".admin-functionalities a.button-green",function(event){return event.preventDefault(),submit()}),$scope.$watch("isVideoconferenceActivated",function(isVideoconferenceActivated){return isVideoconferenceActivated?$el.find(".videoconference-attributes").removeClass("hidden"):($el.find(".videoconference-attributes").addClass("hidden"),$scope.project.videoconferences=null,$scope.project.videoconferences_extra_data="")}),$scope.$watch("project",function(project){return null!=project.videoconferences?$scope.isVideoconferenceActivated=!0:$scope.isVideoconferenceActivated=!1; -})},{link:link}},module.directive("tgProjectModules",["$tgRepo","$tgConfirm","$tgLoading","tgProjectService",ProjectModulesDirective]),ProjectExportDirective=function($window,$rs,$confirm,$translate){var link;return link=function($scope,$el,$attrs){var asyn_message,buttonsEl,dump_ready_text,hideButtons,hideResult,hideSpinner,loading_msg,loading_title,resultEl,resultMessageEl,resultTitleEl,setAsyncMessage,setAsyncTitle,setLoadingMessage,setLoadingTitle,setSyncMessage,setSyncTitle,showButtons,showErrorMode,showExportResultAsyncMode,showExportResultSyncMode,showLoadingMode,showResult,showSpinner,spinnerEl,syn_message;return buttonsEl=$el.find(".admin-project-export-buttons"),showButtons=function(){return buttonsEl.removeClass("hidden")},hideButtons=function(){return buttonsEl.addClass("hidden")},resultEl=$el.find(".admin-project-export-result"),showResult=function(){return resultEl.removeClass("hidden")},hideResult=function(){return resultEl.addClass("hidden")},spinnerEl=$el.find(".spin"),showSpinner=function(){return spinnerEl.removeClass("hidden")},hideSpinner=function(){return spinnerEl.addClass("hidden")},resultTitleEl=$el.find(".result-title"),loading_title=$translate.instant("ADMIN.PROJECT_EXPORT.LOADING_TITLE"),loading_msg=$translate.instant("ADMIN.PROJECT_EXPORT.LOADING_MESSAGE"),dump_ready_text=function(){return resultTitleEl.html($translate.instant("ADMIN.PROJECT_EXPORT.DUMP_READY"))},asyn_message=function(){return resultTitleEl.html($translate.instant("ADMIN.PROJECT_EXPORT.ASYNC_MESSAGE"))},syn_message=function(url){return resultTitleEl.html($translate.instant("ADMIN.PROJECT_EXPORT.SYNC_MESSAGE",{url:url}))},setLoadingTitle=function(){return resultTitleEl.html(loading_title)},setAsyncTitle=function(){return resultTitleEl.html(loading_msg)},setSyncTitle=function(){return resultTitleEl.html(dump_ready_text)},resultMessageEl=$el.find(".result-message "),setLoadingMessage=function(){return resultMessageEl.html(loading_msg)},setAsyncMessage=function(){return resultMessageEl.html(asyn_message)},setSyncMessage=function(url){return resultMessageEl.html(syn_message(url))},showLoadingMode=function(){return showSpinner(),setLoadingTitle(),setLoadingMessage(),hideButtons(),showResult()},showExportResultAsyncMode=function(){return hideSpinner(),setAsyncTitle(),setAsyncMessage()},showExportResultSyncMode=function(url){return hideSpinner(),setSyncTitle(),setSyncMessage(url)},showErrorMode=function(){return hideSpinner(),hideResult(),showButtons()},$el.on("click","a.button-export",debounce(2e3,function(_this){return function(event){var onError,onSuccess;return event.preventDefault(),onSuccess=function(result){var dumpUrl;return 202===result.status?showExportResultAsyncMode():(dumpUrl=result.data.url,showExportResultSyncMode(dumpUrl),$window.open(dumpUrl,"_blank"))},onError=function(result){var errorMsg,ref;return showErrorMode(),errorMsg=$translate.instant("ADMIN.PROJECT_EXPORT.ERROR"),429===result.status?errorMsg=$translate.instant("ADMIN.PROJECT_EXPORT.ERROR_BUSY"):(null!=(ref=result.data)?ref._error_message:void 0)&&(errorMsg=$translate.instant("ADMIN.PROJECT_EXPORT.ERROR_BUSY",{message:result.data._error_message})),$confirm.notify("error",errorMsg)},showLoadingMode(),$rs.projects["export"]($scope.projectId).then(onSuccess,onError)}}(this)))},{link:link}},module.directive("tgProjectExport",["$window","$tgResources","$tgConfirm","$translate",ProjectExportDirective]),CsvExporterController=function(superClass){function CsvExporterController(scope,rootscope,urls,confirm,rs,translate){this.scope=scope,this.rootscope=rootscope,this.urls=urls,this.confirm=confirm,this.rs=rs,this.translate=translate,this._generateUuid=bind(this._generateUuid,this),this.setCsvUuid=bind(this.setCsvUuid,this),this.rootscope.$on("project:loaded",this.setCsvUuid),this.scope.$watch("csvUuid",function(_this){return function(value){return value?_this.scope.csvUrl=_this.urls.resolveAbsolute(_this.type+"-csv",value):_this.scope.csvUrl=""}}(this))}return extend(CsvExporterController,superClass),CsvExporterController.$inject=["$scope","$rootScope","$tgUrls","$tgConfirm","$tgResources","$translate"],CsvExporterController.prototype.setCsvUuid=function(){return this.scope.csvUuid=this.scope.project[this.type+"_csv_uuid"]},CsvExporterController.prototype._generateUuid=function(response){var promise;return null==response&&(response=null),promise=this.rs.projects["regenerate_"+this.type+"_csv_uuid"](this.scope.projectId),promise.then(function(_this){return function(data){var ref;return _this.scope.csvUuid=null!=(ref=data.data)?ref.uuid:void 0}}(this)),promise.then(null,function(_this){return function(){return _this.confirm.notify("error")}}(this)),promise["finally"](function(){return response?response.finish():void 0}),promise},CsvExporterController.prototype.regenerateUuid=function(){var subtitle,title;return this.scope.csvUuid?(title=this.translate.instant("ADMIN.REPORTS.REGENERATE_TITLE"),subtitle=this.translate.instant("ADMIN.REPORTS.REGENERATE_SUBTITLE"),this.confirm.ask(title,subtitle).then(this._generateUuid)):this._generateUuid()},CsvExporterController}(taiga.Controller),CsvExporterUserstoriesController=function(superClass){function CsvExporterUserstoriesController(){return CsvExporterUserstoriesController.__super__.constructor.apply(this,arguments)}return extend(CsvExporterUserstoriesController,superClass),CsvExporterUserstoriesController.prototype.type="userstories",CsvExporterUserstoriesController}(CsvExporterController),CsvExporterTasksController=function(superClass){function CsvExporterTasksController(){return CsvExporterTasksController.__super__.constructor.apply(this,arguments)}return extend(CsvExporterTasksController,superClass),CsvExporterTasksController.prototype.type="tasks",CsvExporterTasksController}(CsvExporterController),CsvExporterIssuesController=function(superClass){function CsvExporterIssuesController(){return CsvExporterIssuesController.__super__.constructor.apply(this,arguments)}return extend(CsvExporterIssuesController,superClass),CsvExporterIssuesController.prototype.type="issues",CsvExporterIssuesController}(CsvExporterController),module.controller("CsvExporterUserstoriesController",CsvExporterUserstoriesController),module.controller("CsvExporterTasksController",CsvExporterTasksController),module.controller("CsvExporterIssuesController",CsvExporterIssuesController),CsvUsDirective=function($translate){var link;return link=function($scope){return $scope.sectionTitle="ADMIN.CSV.SECTION_TITLE_US"},{controller:"CsvExporterUserstoriesController",controllerAs:"ctrl",templateUrl:"admin/project-csv.html",link:link,scope:!0}},module.directive("tgCsvUs",["$translate",CsvUsDirective]),CsvTaskDirective=function($translate){var link;return link=function($scope){return $scope.sectionTitle="ADMIN.CSV.SECTION_TITLE_TASK"},{controller:"CsvExporterTasksController",controllerAs:"ctrl",templateUrl:"admin/project-csv.html",link:link,scope:!0}},module.directive("tgCsvTask",["$translate",CsvTaskDirective]),CsvIssueDirective=function($translate){var link;return link=function($scope){return $scope.sectionTitle="ADMIN.CSV.SECTION_TITLE_ISSUE"},{controller:"CsvExporterIssuesController",controllerAs:"ctrl",templateUrl:"admin/project-csv.html",link:link,scope:!0}},module.directive("tgCsvIssue",["$translate",CsvIssueDirective])}.call(this),function(){var ColorSelectionDirective,DATE_TYPE,MULTILINE_TYPE,ProjectCustomAttributesController,ProjectCustomAttributesDirective,ProjectValuesController,ProjectValuesDirective,ProjectValuesSectionController,TEXT_TYPE,TYPE_CHOICES,bindOnce,debounce,groupBy,joinStr,mixOf,module,taiga,toString,trim,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty,bind=function(fn,me){return function(){return fn.apply(me,arguments)}};taiga=this.taiga,mixOf=this.taiga.mixOf,trim=this.taiga.trim,toString=this.taiga.toString,joinStr=this.taiga.joinStr,groupBy=this.taiga.groupBy,bindOnce=this.taiga.bindOnce,debounce=this.taiga.debounce,module=angular.module("taigaAdmin"),ProjectValuesSectionController=function(superClass){function ProjectValuesSectionController(scope,rootscope,repo,confirm,rs,params,q,location,navUrls,appMetaService,translate){var promise;this.scope=scope,this.rootscope=rootscope,this.repo=repo,this.confirm=confirm,this.rs=rs,this.params=params,this.q=q,this.location=location,this.navUrls=navUrls,this.appMetaService=appMetaService,this.translate=translate,this.scope.project={},promise=this.loadInitialData(),promise.then(function(_this){return function(){var description,sectionName,title;return sectionName=_this.translate.instant(_this.scope.sectionName),title=_this.translate.instant("ADMIN.PROJECT_VALUES.PAGE_TITLE",{sectionName:sectionName,projectName:_this.scope.project.name}),description=_this.scope.project.description,_this.appMetaService.setAll(title,description)}}(this)),promise.then(null,this.onInitialDataError.bind(this))}return extend(ProjectValuesSectionController,superClass),ProjectValuesSectionController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","$tgNavUrls","tgAppMetaService","$translate"],ProjectValuesSectionController.prototype.loadProject=function(){return this.rs.projects.getBySlug(this.params.pslug).then(function(_this){return function(project){return project.i_am_owner||_this.location.path(_this.navUrls.resolve("permission-denied")),_this.scope.projectId=project.id,_this.scope.project=project,_this.scope.$emit("project:loaded",project),project}}(this))},ProjectValuesSectionController.prototype.loadInitialData=function(){var promise;return promise=this.loadProject()},ProjectValuesSectionController}(mixOf(taiga.Controller,taiga.PageMixin)),module.controller("ProjectValuesSectionController",ProjectValuesSectionController),ProjectValuesController=function(superClass){function ProjectValuesController(scope,rootscope,repo,confirm,rs){this.scope=scope,this.rootscope=rootscope,this.repo=repo,this.confirm=confirm,this.rs=rs,this.moveValue=bind(this.moveValue,this),this.loadValues=bind(this.loadValues,this),this.scope.$on("admin:project-values:move",this.moveValue),this.rootscope.$on("project:loaded",this.loadValues)}return extend(ProjectValuesController,superClass),ProjectValuesController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources"],ProjectValuesController.prototype.loadValues=function(){return this.rs[this.scope.resource].listValues(this.scope.projectId,this.scope.type).then(function(_this){return function(values){return _this.scope.values=values,_this.scope.maxValueOrder=_.max(values,"order").order,values}}(this))},ProjectValuesController.prototype.moveValue=function(ctx,itemValue,itemIndex){var r,values;return values=this.scope.values,r=values.indexOf(itemValue),values.splice(r,1),values.splice(itemIndex,0,itemValue),_.each(values,function(value,index){return value.order=index}),this.repo.saveAll(values)},ProjectValuesController}(taiga.Controller),module.controller("ProjectValuesController",ProjectValuesController),ProjectValuesDirective=function($log,$repo,$confirm,$location,animationFrame,$translate,$rootscope){var link,linkDragAndDrop,linkValue;return linkDragAndDrop=function($scope,$el,$attrs){var itemEl,newParentScope,oldParentScope,tdom;return oldParentScope=null,newParentScope=null,itemEl=null,tdom=$el.find(".sortable"),tdom.sortable({handle:".row.table-main.visualization",dropOnEmpty:!0,connectWith:".project-values-body",revert:400,axis:"y"}),tdom.on("sortstop",function(event,ui){var itemIndex,itemValue;return itemEl=ui.item,itemValue=itemEl.scope().value,itemIndex=itemEl.index(),$scope.$broadcast("admin:project-values:move",itemValue,itemIndex)}),$scope.$on("$destroy",function(){return $el.off()})},linkValue=function($scope,$el,$attrs){var $ctrl,cancel,goToBottomList,initializeNewValue,initializeTextTranslations,objName,saveNewValue,saveValue,valueType;return $ctrl=$el.controller(),valueType=$attrs.type,objName=$attrs.objname,initializeNewValue=function(){return $scope.newValue={name:"",is_closed:!1,is_archived:!1}},initializeTextTranslations=function(){return $scope.addNewElementText=$translate.instant("ADMIN.PROJECT_VALUES_"+objName.toUpperCase()+".ACTION_ADD")},initializeNewValue(),initializeTextTranslations(),$rootscope.$on("$translateChangeEnd",function(){return $scope.$evalAsync(initializeTextTranslations)}),goToBottomList=function(_this){return function(focus){var table;return null==focus&&(focus=!1),table=$el.find(".table-main"),$(document.body).scrollTop(table.offset().top+table.height()),focus?$el.find(".new-value input:visible").first().focus():void 0}}(this),saveValue=function(target){var form,formEl,promise,value;return formEl=target.parents("form"),form=formEl.checksley(),form.validate()?(value=formEl.scope().value,promise=$repo.save(value),promise.then(function(_this){return function(){var row;return row=target.parents(".row.table-main"),row.addClass("hidden"),row.siblings(".visualization").removeClass("hidden")}}(this)),promise.then(null,function(data){return form.setErrors(data)})):void 0},saveNewValue=function(target){var form,formEl,promise;return formEl=target.parents("form"),form=formEl.checksley(),form.validate()?($scope.newValue.project=$scope.project.id,$scope.newValue.order=$scope.maxValueOrder?$scope.maxValueOrder+1:1,promise=$repo.create(valueType,$scope.newValue),promise.then(function(_this){return function(data){return target.addClass("hidden"),$scope.values.push(data),$scope.maxValueOrder=data.order,initializeNewValue()}}(this)),promise.then(null,function(data){return form.setErrors(data)})):void 0},cancel=function(target){var formEl,row,value;return row=target.parents(".row.table-main"),formEl=target.parents("form"),value=formEl.scope().value,$scope.$apply(function(){return row.addClass("hidden"),value.revert(),row.siblings(".visualization").removeClass("hidden")})},$el.on("click",".show-add-new",function(event){return event.preventDefault(),$el.find(".new-value").removeClass("hidden"),goToBottomList(!0)}),$el.on("click",".add-new",debounce(2e3,function(event){var target;return event.preventDefault(),target=$el.find(".new-value"),saveNewValue(target)})),$el.on("click",".delete-new",function(event){return event.preventDefault(),$el.find(".new-value").addClass("hidden"),initializeNewValue()}),$el.on("click",".edit-value",function(event){var editionRow,row,target;return event.preventDefault(),target=angular.element(event.currentTarget),row=target.parents(".row.table-main"),row.addClass("hidden"),editionRow=row.siblings(".edition"),editionRow.removeClass("hidden"),editionRow.find("input:visible").first().focus().select()}),$el.on("keyup",".edition input",function(event){var target;return 13===event.keyCode?(target=angular.element(event.currentTarget),saveValue(target)):27===event.keyCode?(target=angular.element(event.currentTarget),cancel(target)):void 0}),$el.on("keyup",".new-value input",function(event){var target;return 13===event.keyCode?(target=$el.find(".new-value"),saveNewValue(target)):27===event.keyCode?($el.find(".new-value").addClass("hidden"),initializeNewValue()):void 0}),$el.on("click",".save",function(event){var target;return event.preventDefault(),target=angular.element(event.currentTarget),saveValue(target)}),$el.on("click",".cancel",function(event){var target;return event.preventDefault(),target=angular.element(event.currentTarget),cancel(target)}),$el.on("click",".delete-value",function(event){var choices,formEl,subtitle,target,text,title,value;return event.preventDefault(),target=angular.element(event.currentTarget),formEl=target.parents("form"),value=formEl.scope().value,choices={},_.each($scope.values,function(option){return value.id!==option.id?choices[option.id]=option.name:void 0}),subtitle=value.name,0===_.keys(choices).length?$confirm.error($translate.instant("ADMIN.PROJECT_VALUES.ERROR_DELETE_ALL")):(title=$translate.instant("ADMIN.COMMON.TITLE_ACTION_DELETE_VALUE"),text=$translate.instant("ADMIN.PROJECT_VALUES.REPLACEMENT"),$confirm.askChoice(title,subtitle,choices,text).then(function(response){var onError,onSucces;return onSucces=function(){return $ctrl.loadValues()["finally"](function(){return response.finish()})},onError=function(){return $confirm.notify("error")},$repo.remove(value,{moveTo:response.selected}).then(onSucces,onError)}))})},link=function($scope,$el,$attrs){return linkDragAndDrop($scope,$el,$attrs),linkValue($scope,$el,$attrs),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgProjectValues",["$log","$tgRepo","$tgConfirm","$tgLocation","animationFrame","$translate","$rootScope",ProjectValuesDirective]),ColorSelectionDirective=function(){var link;return link=function($scope,$el,$attrs,$model){var $ctrl;return $ctrl=$el.controller(),$scope.$watch($attrs.ngModel,function(element){return $scope.color=element.color}),$el.on("click",".current-color",function(event){var body,target;return event.preventDefault(),event.stopPropagation(),target=angular.element(event.currentTarget),$el.find(".select-color").hide(),target.siblings(".select-color").show(),body=angular.element("body"),body.on("click",function(_this){return function(event){return 0===angular.element(event.target).parent(".select-color").length?($el.find(".select-color").hide(),body.unbind("click")):void 0}}(this))}),$el.on("click",".select-color .color",function(event){var target;return event.preventDefault(),target=angular.element(event.currentTarget),$scope.$apply(function(){return $model.$modelValue.color=target.data("color")}),$el.find(".select-color").hide()}),$el.on("click",".select-color .selected-color",function(event){return event.preventDefault(),$scope.$apply(function(){return $model.$modelValue.color=$scope.color}),$el.find(".select-color").hide()}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,require:"ngModel"}},module.directive("tgColorSelection",ColorSelectionDirective),TEXT_TYPE="text",MULTILINE_TYPE="multiline",DATE_TYPE="date",TYPE_CHOICES=[{key:TEXT_TYPE,name:"ADMIN.CUSTOM_FIELDS.FIELD_TYPE_TEXT"},{key:MULTILINE_TYPE,name:"ADMIN.CUSTOM_FIELDS.FIELD_TYPE_MULTI"},{key:DATE_TYPE,name:"ADMIN.CUSTOM_FIELDS.FIELD_TYPE_DATE"}],ProjectCustomAttributesController=function(superClass){function ProjectCustomAttributesController(scope,rootscope,repo,rs,params,q,location,navUrls,appMetaService,translate){this.scope=scope,this.rootscope=rootscope,this.repo=repo,this.rs=rs,this.params=params,this.q=q,this.location=location,this.navUrls=navUrls,this.appMetaService=appMetaService,this.translate=translate,this.moveCustomAttributes=bind(this.moveCustomAttributes,this),this.deleteCustomAttribute=bind(this.deleteCustomAttribute,this),this.saveCustomAttribute=bind(this.saveCustomAttribute,this),this.createCustomAttribute=bind(this.createCustomAttribute,this),this.loadCustomAttributes=bind(this.loadCustomAttributes,this),this.scope.TYPE_CHOICES=TYPE_CHOICES,this.scope.project={},this.rootscope.$on("project:loaded",function(_this){return function(){var description,sectionName,title;return _this.loadCustomAttributes(),sectionName=_this.translate.instant(_this.scope.sectionName),title=_this.translate.instant("ADMIN.CUSTOM_ATTRIBUTES.PAGE_TITLE",{sectionName:sectionName,projectName:_this.scope.project.name}),description=_this.scope.project.description,_this.appMetaService.setAll(title,description)}}(this))}return extend(ProjectCustomAttributesController,superClass),ProjectCustomAttributesController.$inject=["$scope","$rootScope","$tgRepo","$tgResources","$routeParams","$q","$tgLocation","$tgNavUrls","tgAppMetaService","$translate"],ProjectCustomAttributesController.prototype.loadCustomAttributes=function(){return this.rs.customAttributes[this.scope.type].list(this.scope.projectId).then(function(_this){return function(customAttributes){return _this.scope.customAttributes=customAttributes,_this.scope.maxOrder=_.max(customAttributes,"order").order,customAttributes}}(this))},ProjectCustomAttributesController.prototype.createCustomAttribute=function(attrValues){return this.repo.create("custom-attributes/"+this.scope.type,attrValues)},ProjectCustomAttributesController.prototype.saveCustomAttribute=function(attrModel){return this.repo.save(attrModel)},ProjectCustomAttributesController.prototype.deleteCustomAttribute=function(attrModel){return this.repo.remove(attrModel)},ProjectCustomAttributesController.prototype.moveCustomAttributes=function(attrModel,newIndex){var customAttributes,r;return customAttributes=this.scope.customAttributes,r=customAttributes.indexOf(attrModel),customAttributes.splice(r,1),customAttributes.splice(newIndex,0,attrModel),_.each(customAttributes,function(val,idx){return val.order=idx}),this.repo.saveAll(customAttributes)},ProjectCustomAttributesController}(mixOf(taiga.Controller,taiga.PageMixin)),module.controller("ProjectCustomAttributesController",ProjectCustomAttributesController),ProjectCustomAttributesDirective=function($log,$confirm,animationFrame,$translate){var link;return link=function($scope,$el,$attrs){var $ctrl,cancelCreate,cancelUpdate,create,deleteCustomAttribute,hideAddButton,hideCancelButton,hideCreateForm,hideEditForm,resetNewAttr,revertChangesInCustomAttribute,showAddButton,showCancelButton,showCreateForm,showEditForm,sortableEl,update;return $ctrl=$el.controller(),$scope.$on("$destroy",function(){return $el.off()}),sortableEl=$el.find(".js-sortable"),sortableEl.sortable({handle:".js-view-custom-field",dropOnEmpty:!0,revert:400,axis:"y"}),sortableEl.on("sortstop",function(event,ui){var itemAttr,itemEl,itemIndex;return itemEl=ui.item,itemAttr=itemEl.scope().attr,itemIndex=itemEl.index(),$ctrl.moveCustomAttributes(itemAttr,itemIndex)}),showCreateForm=function(){return $el.find(".js-new-custom-field").removeClass("hidden"),$el.find(".js-new-custom-field input:visible").first().focus()},hideCreateForm=function(){return $el.find(".js-new-custom-field").addClass("hidden")},showAddButton=function(){return $el.find(".js-add-custom-field-button").removeClass("hidden")},hideAddButton=function(){return $el.find(".js-add-custom-field-button").addClass("hidden")},showCancelButton=function(){return $el.find(".js-cancel-new-custom-field-button").removeClass("hidden")},hideCancelButton=function(){return $el.find(".js-cancel-new-custom-field-button").addClass("hidden")},resetNewAttr=function(){return $scope.newAttr={}},create=function(formEl){var attr,form,onError,onSucces;return form=formEl.checksley(),form.validate()?(onSucces=function(_this){return function(){return $ctrl.loadCustomAttributes(),hideCreateForm(),resetNewAttr(),$confirm.notify("success")}}(this),onError=function(_this){return function(data){return form.setErrors(data)}}(this),attr=$scope.newAttr,attr.project=$scope.projectId,attr.order=$scope.maxOrder?$scope.maxOrder+1:1,$ctrl.createCustomAttribute(attr).then(onSucces,onError)):void 0},cancelCreate=function(){return hideCreateForm(),resetNewAttr()},$scope.$watch("customAttributes",function(customAttributes){return customAttributes?0===customAttributes.length?(hideCancelButton(),hideAddButton(),showCreateForm()):(hideCreateForm(),showAddButton(),showCancelButton()):void 0}),$el.on("click",".js-add-custom-field-button",function(event){return event.preventDefault(),showCreateForm()}),$el.on("click",".js-create-custom-field-button",debounce(2e3,function(event){var formEl,target;return event.preventDefault(),target=angular.element(event.currentTarget),formEl=target.closest("form"),create(formEl)})),$el.on("click",".js-cancel-new-custom-field-button",function(event){return event.preventDefault(),cancelCreate()}),$el.on("keyup",".js-new-custom-field input",function(event){var formEl,target;return 13===event.keyCode?(target=angular.element(event.currentTarget),formEl=target.closest("form"),create(formEl)):27===event.keyCode?cancelCreate():void 0}),showEditForm=function(formEl){return formEl.find(".js-view-custom-field").addClass("hidden"),formEl.find(".js-edit-custom-field").removeClass("hidden"),formEl.find(".js-edit-custom-field input:visible").first().focus().select()},hideEditForm=function(formEl){return formEl.find(".js-edit-custom-field").addClass("hidden"),formEl.find(".js-view-custom-field").removeClass("hidden")},revertChangesInCustomAttribute=function(formEl){return $scope.$apply(function(){return formEl.scope().attr.revert()})},update=function(formEl){var attr,form,onError,onSucces;return form=formEl.checksley(),form.validate()?(onSucces=function(_this){return function(){return $ctrl.loadCustomAttributes(),hideEditForm(formEl),$confirm.notify("success")}}(this),onError=function(_this){return function(data){return form.setErrors(data)}}(this),attr=formEl.scope().attr,$ctrl.saveCustomAttribute(attr).then(onSucces,onError)):void 0},cancelUpdate=function(formEl){return hideEditForm(formEl),revertChangesInCustomAttribute(formEl)},$el.on("click",".js-edit-custom-field-button",function(event){var formEl,target;return event.preventDefault(),target=angular.element(event.currentTarget),formEl=target.closest("form"),showEditForm(formEl)}),$el.on("click",".js-update-custom-field-button",debounce(2e3,function(event){var formEl,target;return event.preventDefault(),target=angular.element(event.currentTarget),formEl=target.closest("form"),update(formEl)})),$el.on("click",".js-cancel-edit-custom-field-button",function(event){var formEl,target;return event.preventDefault(),target=angular.element(event.currentTarget),formEl=target.closest("form"),cancelUpdate(formEl)}),$el.on("keyup",".js-edit-custom-field input",function(event){var formEl,target;return 13===event.keyCode?(target=angular.element(event.currentTarget),formEl=target.closest("form"),update(formEl)):27===event.keyCode?(target=angular.element(event.currentTarget),formEl=target.closest("form"),cancelUpdate(formEl)):void 0}),deleteCustomAttribute=function(formEl){var attr,message,text,title;return attr=formEl.scope().attr,message=attr.name,title=$translate.instant("COMMON.CUSTOM_ATTRIBUTES.DELETE"),text=$translate.instant("COMMON.CUSTOM_ATTRIBUTES.CONFIRM_DELETE"),$confirm.ask(title,text,message).then(function(response){var onError,onSucces;return onSucces=function(){return $ctrl.loadCustomAttributes()["finally"](function(){return response.finish()})},onError=function(){return $confirm.notify("error",null,"We have not been able to delete '"+message+"'.")},$ctrl.deleteCustomAttribute(attr).then(onSucces,onError)})},$el.on("click",".js-delete-custom-field-button",debounce(2e3,function(event){var formEl,target;return event.preventDefault(),target=angular.element(event.currentTarget),formEl=target.closest("form"),deleteCustomAttribute(formEl)}))},{link:link}},module.directive("tgProjectCustomAttributes",["$log","$tgConfirm","animationFrame","$translate",ProjectCustomAttributesDirective])}.call(this),function(){var EditRoleDirective,NewRoleDirective,RolePermissionsDirective,RolesController,RolesDirective,bindMethods,bindOnce,debounce,mixOf,module,taiga,bind=function(fn,me){return function(){return fn.apply(me,arguments)}},extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty,indexOf=[].indexOf||function(item){for(var i=0,l=this.length;l>i;i++)if(i in this&&this[i]===item)return i;return-1};taiga=this.taiga,mixOf=this.taiga.mixOf,bindOnce=this.taiga.bindOnce,debounce=this.taiga.debounce,bindMethods=this.taiga.bindMethods,module=angular.module("taigaAdmin"),RolesController=function(superClass){function RolesController(scope,rootscope,repo,confirm,rs,params,q,location,navUrls,appMetaService,translate){var promise;this.scope=scope,this.rootscope=rootscope,this.repo=repo,this.confirm=confirm,this.rs=rs,this.params=params,this.q=q,this.location=location,this.navUrls=navUrls,this.appMetaService=appMetaService,this.translate=translate,this._disableComputable=bind(this._disableComputable,this),this._enableComputable=bind(this._enableComputable,this),bindMethods(this),this.scope.sectionName="ADMIN.MENU.PERMISSIONS",this.scope.project={},this.scope.anyComputableRole=!0,promise=this.loadInitialData(),promise.then(function(_this){return function(){var description,title;return title=_this.translate.instant("ADMIN.ROLES.PAGE_TITLE",{projectName:_this.scope.project.name}),description=_this.scope.project.description,_this.appMetaService.setAll(title,description)}}(this)),promise.then(null,this.onInitialDataError.bind(this))}return extend(RolesController,superClass),RolesController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","$tgNavUrls","tgAppMetaService","$translate"],RolesController.prototype.loadProject=function(){return this.rs.projects.getBySlug(this.params.pslug).then(function(_this){return function(project){return project.i_am_owner||_this.location.path(_this.navUrls.resolve("permission-denied")),_this.scope.projectId=project.id,_this.scope.project=project,_this.scope.$emit("project:loaded",project),_this.scope.anyComputableRole=_.some(_.map(project.roles,function(point){return point.computable})),project}}(this))},RolesController.prototype.loadRoles=function(){return this.rs.roles.list(this.scope.projectId).then(function(_this){return function(roles){var public_permission;return roles=roles.map(function(role){return role.external_user=!1,role}),public_permission={name:_this.translate.instant("ADMIN.ROLES.EXTERNAL_USER"),permissions:_this.scope.project.public_permissions,external_user:!0},roles.push(public_permission),_this.scope.roles=roles,_this.scope.role=_this.scope.roles[0],roles}}(this))},RolesController.prototype.loadInitialData=function(){var promise;return promise=this.loadProject(),promise.then(function(_this){return function(){return _this.loadRoles()}}(this)),promise},RolesController.prototype.setRole=function(role){return this.scope.role=role,this.scope.$broadcast("role:changed",this.scope.role)},RolesController.prototype["delete"]=function(){var choices,i,len,ref,replacement,role,subtitle,title,warning;for(choices={},ref=this.scope.roles,i=0,len=ref.length;len>i;i++)role=ref[i],role.id!==this.scope.role.id&&(choices[role.id]=role.name);return 0===_.keys(choices).length?this.confirm.error(this.translate.instant("ADMIN.ROLES.ERROR_DELETE_ALL")):(title=this.translate.instant("ADMIN.ROLES.TITLE_DELETE_ROLE"),subtitle=this.scope.role.name,replacement=this.translate.instant("ADMIN.ROLES.REPLACEMENT_ROLE"),warning=this.translate.instant("ADMIN.ROLES.WARNING_DELETE_ROLE"),this.confirm.askChoice(title,subtitle,choices,replacement,warning).then(function(_this){return function(response){var onError,onSuccess;return onSuccess=function(){return _this.loadProject(),_this.loadRoles()["finally"](function(){return response.finish()})},onError=function(){return _this.confirm.notify("error")},_this.repo.remove(_this.scope.role,{moveTo:response.selected}).then(onSuccess,onError)}}(this)))},RolesController.prototype._enableComputable=function(){var onError,onSuccess;return onSuccess=function(_this){return function(){return _this.confirm.notify("success"),_this.loadProject()}}(this),onError=function(_this){return function(){return _this.confirm.notify("error"),_this.scope.role.revert()}}(this),this.repo.save(this.scope.role).then(onSuccess,onError)},RolesController.prototype._disableComputable=function(){var askOnError,askOnSuccess,message,subtitle,title;return askOnSuccess=function(_this){return function(response){var onError,onSuccess;return onSuccess=function(){return response.finish(),_this.confirm.notify("success"),_this.loadProject()},onError=function(){return response.finish(),_this.confirm.notify("error"),_this.scope.role.revert()},_this.repo.save(_this.scope.role).then(onSuccess,onError); -}}(this),askOnError=function(_this){return function(response){return _this.scope.role.revert()}}(this),title=this.translate.instant("ADMIN.ROLES.DISABLE_COMPUTABLE_ALERT_TITLE"),subtitle=this.translate.instant("ADMIN.ROLES.DISABLE_COMPUTABLE_ALERT_SUBTITLE",{roleName:this.scope.role.name}),message=this.translate.instant("ADMIN.ROLES.DISABLE_COMPUTABLE_ALERT_MESSAGE"),this.confirm.ask(title,subtitle,message).then(askOnSuccess,askOnError)},RolesController.prototype.toggleComputable=debounce(2e3,function(){return this.scope.role.computable?this._enableComputable():this._disableComputable()}),RolesController}(mixOf(taiga.Controller,taiga.PageMixin,taiga.FiltersMixin)),module.controller("RolesController",RolesController),EditRoleDirective=function($repo,$confirm){var link;return link=function($scope,$el,$attrs){var submit,toggleView;return toggleView=function(){return $el.find(".total").toggle(),$el.find(".edit-role").toggle()},submit=function(){var promise;return $scope.role.name=$el.find("input").val(),promise=$repo.save($scope.role),promise.then(function(){return $confirm.notify("success")}),promise.then(null,function(data){return $confirm.notify("error")}),toggleView()},$el.on("click","a.icon-edit",function(){return toggleView(),$el.find("input").focus(),$el.find("input").val($scope.role.name)}),$el.on("click","a.save",submit),$el.on("keyup","input",function(event){return 13===event.keyCode?submit():27===event.keyCode?toggleView():void 0}),$scope.$on("role:changed",function(){return $el.find(".edit-role").is(":visible")?toggleView():void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgEditRole",["$tgRepo","$tgConfirm",EditRoleDirective]),RolesDirective=function(){var link;return link=function($scope,$el,$attrs){var $ctrl;return $ctrl=$el.controller(),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgRoles",RolesDirective),NewRoleDirective=function($tgrepo,$confirm){var DEFAULT_PERMISSIONS,link;return DEFAULT_PERMISSIONS=["view_project","view_milestones","view_us","view_tasks","view_issues"],link=function($scope,$el,$attrs){var $ctrl;return $ctrl=$el.controller(),$scope.$on("$destroy",function(){return $el.off()}),$el.on("click","a.add-button",function(event){return event.preventDefault(),$el.find(".new").removeClass("hidden"),$el.find(".new").focus(),$el.find(".add-button").hide()}),$el.on("keyup",".new",function(event){var newRole,onError,onSuccess,target;return event.preventDefault(),13===event.keyCode?(target=angular.element(event.currentTarget),newRole={project:$scope.projectId,name:target.val(),permissions:DEFAULT_PERMISSIONS,order:_.max($scope.roles,function(r){return r.order}).order+1,computable:!1},$el.find(".new").addClass("hidden"),$el.find(".new").val(""),onSuccess=function(role){var insertPosition;return insertPosition=$scope.roles.length-1,$scope.roles.splice(insertPosition,0,role),$ctrl.setRole(role),$el.find(".add-button").show(),$ctrl.loadProject()},onError=function(){return $confirm.notify("error")},$tgrepo.create("roles",newRole).then(onSuccess,onError)):27===event.keyCode?(target=angular.element(event.currentTarget),$el.find(".new").addClass("hidden"),$el.find(".new").val(""),$el.find(".add-button").show()):void 0})},{link:link}},module.directive("tgNewRole",["$tgRepo","$tgConfirm",NewRoleDirective]),RolePermissionsDirective=function($rootscope,$repo,$confirm,$compile){var baseTemplate,categoryTemplate,link,resumeTemplate;return resumeTemplate=_.template('
\n
\n
<%- category.activePermissions %>/<%- category.permissions.length %>
\n <% _.each(category.permissions, function(permission) { %>\n
\n <% }) %>\n
\n
'),categoryTemplate=_.template('
\n
\n
\n
\n
\n <% _.each(category.permissions, function(permission) { %>\n
\n \n
\n disabled="disabled" <% } %>\n <% if(permission.active) { %> checked="checked" <% } %>/>\n
\n \n \n
\n
\n <% }) %>\n
\n
\n
'),baseTemplate=_.template('
'),link=function($scope,$el,$attrs){var $ctrl,generateCategoriesFromRole,renderCategory,renderPermissions,renderResume;return $ctrl=$el.controller(),generateCategoriesFromRole=function(role){var categories,isPermissionEditable,issuePermissions,milestonePermissions,setActivePermissions,setActivePermissionsPerCategory,taskPermissions,userStoryPermissions,wikiPermissions;return setActivePermissions=function(permissions){return _.map(permissions,function(x){var ref;return _.extend({},x,{active:(ref=x.key,indexOf.call(role.permissions,ref)>=0)})})},isPermissionEditable=function(permission,role,project){return role.external_user&&!project.is_private&&0===permission.key.indexOf("view_")?!1:!0},setActivePermissionsPerCategory=function(category){return _.map(category,function(cat){return cat.permissions=cat.permissions.map(function(permission){return permission.editable=isPermissionEditable(permission,role,$scope.project),permission}),_.extend({},cat,{activePermissions:_.filter(cat.permissions,"active").length})})},categories=[],milestonePermissions=[{key:"view_milestones",name:"COMMON.PERMISIONS_CATEGORIES.SPRINTS.VIEW_SPRINTS"},{key:"add_milestone",name:"COMMON.PERMISIONS_CATEGORIES.SPRINTS.ADD_SPRINTS"},{key:"modify_milestone",name:"COMMON.PERMISIONS_CATEGORIES.SPRINTS.MODIFY_SPRINTS"},{key:"delete_milestone",name:"COMMON.PERMISIONS_CATEGORIES.SPRINTS.DELETE_SPRINTS"}],categories.push({name:"COMMON.PERMISIONS_CATEGORIES.SPRINTS.NAME",permissions:setActivePermissions(milestonePermissions)}),userStoryPermissions=[{key:"view_us",name:"COMMON.PERMISIONS_CATEGORIES.USER_STORIES.VIEW_USER_STORIES"},{key:"add_us",name:"COMMON.PERMISIONS_CATEGORIES.USER_STORIES.ADD_USER_STORIES"},{key:"modify_us",name:"COMMON.PERMISIONS_CATEGORIES.USER_STORIES.MODIFY_USER_STORIES"},{key:"delete_us",name:"COMMON.PERMISIONS_CATEGORIES.USER_STORIES.DELETE_USER_STORIES"}],categories.push({name:"COMMON.PERMISIONS_CATEGORIES.USER_STORIES.NAME",permissions:setActivePermissions(userStoryPermissions)}),taskPermissions=[{key:"view_tasks",name:"COMMON.PERMISIONS_CATEGORIES.TASKS.VIEW_TASKS"},{key:"add_task",name:"COMMON.PERMISIONS_CATEGORIES.TASKS.ADD_TASKS"},{key:"modify_task",name:"COMMON.PERMISIONS_CATEGORIES.TASKS.MODIFY_TASKS"},{key:"delete_task",name:"COMMON.PERMISIONS_CATEGORIES.TASKS.DELETE_TASKS"}],categories.push({name:"COMMON.PERMISIONS_CATEGORIES.TASKS.NAME",permissions:setActivePermissions(taskPermissions)}),issuePermissions=[{key:"view_issues",name:"COMMON.PERMISIONS_CATEGORIES.ISSUES.VIEW_ISSUES"},{key:"add_issue",name:"COMMON.PERMISIONS_CATEGORIES.ISSUES.ADD_ISSUES"},{key:"modify_issue",name:"COMMON.PERMISIONS_CATEGORIES.ISSUES.MODIFY_ISSUES"},{key:"delete_issue",name:"COMMON.PERMISIONS_CATEGORIES.ISSUES.DELETE_ISSUES"}],categories.push({name:"COMMON.PERMISIONS_CATEGORIES.ISSUES.NAME",permissions:setActivePermissions(issuePermissions)}),wikiPermissions=[{key:"view_wiki_pages",name:"COMMON.PERMISIONS_CATEGORIES.WIKI.VIEW_WIKI_PAGES"},{key:"add_wiki_page",name:"COMMON.PERMISIONS_CATEGORIES.WIKI.ADD_WIKI_PAGES"},{key:"modify_wiki_page",name:"COMMON.PERMISIONS_CATEGORIES.WIKI.MODIFY_WIKI_PAGES"},{key:"delete_wiki_page",name:"COMMON.PERMISIONS_CATEGORIES.WIKI.DELETE_WIKI_PAGES"},{key:"view_wiki_links",name:"COMMON.PERMISIONS_CATEGORIES.WIKI.VIEW_WIKI_LINKS"},{key:"add_wiki_link",name:"COMMON.PERMISIONS_CATEGORIES.WIKI.ADD_WIKI_LINKS"},{key:"delete_wiki_link",name:"COMMON.PERMISIONS_CATEGORIES.WIKI.DELETE_WIKI_LINKS"}],categories.push({name:"COMMON.PERMISIONS_CATEGORIES.WIKI.NAME",permissions:setActivePermissions(wikiPermissions)}),setActivePermissionsPerCategory(categories)},renderResume=function(element,category){return element.find(".resume").html($compile(resumeTemplate({category:category}))($scope))},renderCategory=function(category,index){var html;return html=categoryTemplate({category:category,index:index}),html=angular.element(html),renderResume(html,category),$compile(html)($scope)},renderPermissions=function(){var html;return $el.off(),html=baseTemplate(),_.each(generateCategoriesFromRole($scope.role),function(category,index){return html=angular.element(html).append(renderCategory(category,index))}),$el.html(html),$el.on("click",".resume",function(event){var target;return event.preventDefault(),target=angular.element(event.currentTarget),target.next().toggleClass("open")}),$el.on("change",".category-item input",function(event){var getActivePermissions,onError,onSuccess,target;return getActivePermissions=function(){var activePermissions;return activePermissions=_.filter($el.find(".category-item input"),function(t){return angular.element(t).is(":checked")}),activePermissions=_.sortBy(_.map(activePermissions,function(t){var permission;return permission=angular.element(t).parents(".category-item").data("id")})),activePermissions.length&&activePermissions.push("view_project"),activePermissions},target=angular.element(event.currentTarget),$scope.role.permissions=getActivePermissions(),onSuccess=function(){var categories,categoryId;return categories=generateCategoriesFromRole($scope.role),categoryId=target.parents(".category-config").data("id"),renderResume(target.parents(".category-config"),categories[categoryId]),$rootscope.$broadcast("projects:reload"),$confirm.notify("success"),$ctrl.loadProject()},onError=function(){return $confirm.notify("error"),target.prop("checked",!target.prop("checked")),$scope.role.permissions=getActivePermissions()},$scope.role.external_user?($scope.project.public_permissions=$scope.role.permissions,$scope.project.anon_permissions=$scope.role.permissions.filter(function(permission){return 0===permission.indexOf("view_")}),$repo.save($scope.project).then(onSuccess,onError)):$repo.save($scope.role).then(onSuccess,onError)})},$scope.$on("$destroy",function(){return $el.off()}),$scope.$on("role:changed",function(){return renderPermissions()}),bindOnce($scope,$attrs.ngModel,renderPermissions)},{link:link}},module.directive("tgRolePermissions",["$rootScope","$tgRepo","$tgConfirm","$compile",RolePermissionsDirective])}.call(this),function(){var BitbucketController,BitbucketWebhooksDirective,GithubController,GithubWebhooksDirective,GitlabController,GitlabWebhooksDirective,NewWebhookDirective,SelectInputText,ValidOriginIpsDirective,WebhookDirective,WebhooksController,bindMethods,debounce,mixOf,module,taiga,timeout,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,mixOf=this.taiga.mixOf,bindMethods=this.taiga.bindMethods,debounce=this.taiga.debounce,timeout=this.taiga.timeout,module=angular.module("taigaAdmin"),WebhooksController=function(superClass){function WebhooksController(scope,repo,rs,params,location,navUrls,appMetaService,translate){var promise;this.scope=scope,this.repo=repo,this.rs=rs,this.params=params,this.location=location,this.navUrls=navUrls,this.appMetaService=appMetaService,this.translate=translate,bindMethods(this),this.scope.sectionName="ADMIN.WEBHOOKS.SECTION_NAME",this.scope.project={},promise=this.loadInitialData(),promise.then(function(_this){return function(){var description,title;return title=_this.translate.instant("ADMIN.WEBHOOKS.PAGE_TITLE",{projectName:_this.scope.project.name}),description=_this.scope.project.description,_this.appMetaService.setAll(title,description)}}(this)),promise.then(null,this.onInitialDataError.bind(this)),this.scope.$on("webhooks:reload",this.loadWebhooks)}return extend(WebhooksController,superClass),WebhooksController.$inject=["$scope","$tgRepo","$tgResources","$routeParams","$tgLocation","$tgNavUrls","tgAppMetaService","$translate"],WebhooksController.prototype.loadWebhooks=function(){return this.rs.webhooks.list(this.scope.projectId).then(function(_this){return function(webhooks){return _this.scope.webhooks=webhooks}}(this))},WebhooksController.prototype.loadProject=function(){return this.rs.projects.getBySlug(this.params.pslug).then(function(_this){return function(project){return project.i_am_owner||_this.location.path(_this.navUrls.resolve("permission-denied")),_this.scope.projectId=project.id,_this.scope.project=project,_this.scope.$emit("project:loaded",project),project}}(this))},WebhooksController.prototype.loadInitialData=function(){var promise;return promise=this.loadProject(),promise.then(function(_this){return function(){return _this.loadWebhooks()}}(this)),promise},WebhooksController}(mixOf(taiga.Controller,taiga.PageMixin,taiga.FiltersMixin)),module.controller("WebhooksController",WebhooksController),WebhookDirective=function($rs,$repo,$confirm,$loading,$translate){var link;return link=function($scope,$el,$attrs){var cancel,openHistory,save,showEditMode,showVisualizationMode,updateLogs,updateShowHideHistoryText,webhook;return webhook=$scope.$eval($attrs.tgWebhook),updateLogs=function(){var prettyDate;return prettyDate=$translate.instant("ADMIN.WEBHOOKS.DATE"),$rs.webhooklogs.list(webhook.id).then(function(_this){return function(webhooklogs){var i,len,log,ref;for(i=0,len=webhooklogs.length;len>i;i++)log=webhooklogs[i],log.validStatus=200<=(ref=log.status)&&300>ref,log.prettySentHeaders=_.map(_.pairs(log.request_headers),function(arg){var header,value;return header=arg[0],value=arg[1],header+": "+value}).join("\n"),log.prettySentData=JSON.stringify(log.request_data),log.prettyDate=moment(log.created).format(prettyDate);return webhook.logs_counter=webhooklogs.length,webhook.logs=webhooklogs,updateShowHideHistoryText()}}(this))},updateShowHideHistoryText=function(){var historyElement,text,textElement,title;return textElement=$el.find(".toggle-history"),historyElement=textElement.parents(".single-webhook-wrapper").find(".webhooks-history"),historyElement.hasClass("open")?(text=$translate.instant("ADMIN.WEBHOOKS.ACTION_HIDE_HISTORY"),title=$translate.instant("ADMIN.WEBHOOKS.ACTION_HIDE_HISTORY_TITLE")):(text=$translate.instant("ADMIN.WEBHOOKS.ACTION_SHOW_HISTORY"),title=$translate.instant("ADMIN.WEBHOOKS.ACTION_SHOW_HISTORY_TITLE")),textElement.text(text),textElement.prop("title",title)},showVisualizationMode=function(){return $el.find(".edition-mode").addClass("hidden"),$el.find(".visualization-mode").removeClass("hidden")},showEditMode=function(){return $el.find(".visualization-mode").addClass("hidden"),$el.find(".edition-mode").removeClass("hidden")},openHistory=function(){return $el.find(".webhooks-history").addClass("open")},cancel=function(){return showVisualizationMode(),$scope.$apply(function(){return webhook.revert()})},save=debounce(2e3,function(target){var form,promise;return form=target.parents("form").checksley(),form.validate()?(promise=$repo.save(webhook),promise.then(function(_this){return function(){return showVisualizationMode()}}(this)),promise.then(null,function(data){return $confirm.notify("error"),form.setErrors(data)})):void 0}),$el.on("click",".test-webhook",function(){return openHistory(),$rs.webhooks.test(webhook.id).then(function(_this){return function(){return updateLogs()}}(this))}),$el.on("click",".edit-webhook",function(){return showEditMode()}),$el.on("click",".cancel-existing",function(){return cancel()}),$el.on("click",".edit-existing",function(event){var target;return event.preventDefault(),target=angular.element(event.currentTarget),save(target)}),$el.on("keyup",".edition-mode input",function(event){var target;return 13===event.keyCode?(target=angular.element(event.currentTarget),save(target)):27===event.keyCode?(target=angular.element(event.currentTarget),cancel(target)):void 0}),$el.on("click",".delete-webhook",function(){var message,title;return title=$translate.instant("ADMIN.WEBHOOKS.DELETE"),message=$translate.instant("ADMIN.WEBHOOKS.WEBHOOK_NAME",{name:webhook.name}),$confirm.askOnDelete(title,message).then(function(_this){return function(askResponse){var onError,onSucces;return onSucces=function(){return askResponse.finish(),$scope.$emit("webhooks:reload")},onError=function(){return askResponse.finish(!1),$confirm.notify("error")},$repo.remove(webhook).then(onSucces,onError)}}(this))}),$el.on("click",".toggle-history",function(event){var target;return target=angular.element(event.currentTarget),null==webhook.logs||0===webhook.logs.length?updateLogs().then(function(){return timeout(0,function(){return $el.find(".webhooks-history").toggleClass("open"),updateShowHideHistoryText()})}):($el.find(".webhooks-history").toggleClass("open"),$scope.$apply(function(){return updateShowHideHistoryText()}))}),$el.on("click",".history-single",function(event){var target;return target=angular.element(event.currentTarget),target.toggleClass("history-single-open"),target.siblings(".history-single-response").toggleClass("open")}),$el.on("click",".resend-request",function(event){var log,target;return target=angular.element(event.currentTarget),log=target.data("log"),$rs.webhooklogs.resend(log).then(function(_this){return function(){return updateLogs()}}(this))})},{link:link}},module.directive("tgWebhook",["$tgResources","$tgRepo","$tgConfirm","$tgLoading","$translate",WebhookDirective]),NewWebhookDirective=function($rs,$repo,$confirm,$loading){var link;return link=function($scope,$el,$attrs){var addWebhookDOMNode,formDOMNode,initializeNewValue,save,webhook;return webhook=$scope.$eval($attrs.tgWebhook),formDOMNode=$el.find(".new-webhook-form"),addWebhookDOMNode=$el.find(".add-webhook"),initializeNewValue=function(){return $scope.newValue={name:"",url:"",key:""}},initializeNewValue(),$scope.$watch("webhooks",function(webhooks){return null!=webhooks?0===webhooks.length?(formDOMNode.removeClass("hidden"),addWebhookDOMNode.addClass("hidden"),formDOMNode.find("input")[0].focus()):(formDOMNode.addClass("hidden"),addWebhookDOMNode.removeClass("hidden")):void 0}),save=debounce(2e3,function(){var form,promise;return form=formDOMNode.checksley(),form.validate()?($scope.newValue.project=$scope.project.id,promise=$repo.create("webhooks",$scope.newValue),promise.then(function(_this){return function(){return $scope.$emit("webhooks:reload"),initializeNewValue()}}(this)),promise.then(null,function(data){return $confirm.notify("error"),form.setErrors(data)})):void 0}),formDOMNode.on("click",".add-new",function(event){return event.preventDefault(),save()}),formDOMNode.on("keyup","input",function(event){return 13===event.keyCode?save():void 0}),formDOMNode.on("click",".cancel-new",function(event){return $scope.$apply(function(){return initializeNewValue()})}),addWebhookDOMNode.on("click",function(event){return formDOMNode.removeClass("hidden"),formDOMNode.find("input")[0].focus()})},{link:link}},module.directive("tgNewWebhook",["$tgResources","$tgRepo","$tgConfirm","$tgLoading",NewWebhookDirective]),GithubController=function(superClass){function GithubController(scope,repo,rs,params,appMetaService,translate){var promise;this.scope=scope,this.repo=repo,this.rs=rs,this.params=params,this.appMetaService=appMetaService,this.translate=translate,bindMethods(this),this.scope.sectionName=this.translate.instant("ADMIN.GITHUB.SECTION_NAME"),this.scope.project={},promise=this.loadInitialData(),promise.then(function(_this){return function(){var description,title;return title=_this.translate.instant("ADMIN.GITHUB.PAGE_TITLE",{projectName:_this.scope.project.name}),description=_this.scope.project.description,_this.appMetaService.setAll(title,description)}}(this)),promise.then(null,this.onInitialDataError.bind(this))}return extend(GithubController,superClass),GithubController.$inject=["$scope","$tgRepo","$tgResources","$routeParams","tgAppMetaService","$translate"],GithubController.prototype.loadModules=function(){return this.rs.modules.list(this.scope.projectId,"github").then(function(_this){return function(github){return _this.scope.github=github}}(this))},GithubController.prototype.loadProject=function(){return this.rs.projects.getBySlug(this.params.pslug).then(function(_this){return function(project){return _this.scope.projectId=project.id,_this.scope.project=project,_this.scope.$emit("project:loaded",project),project}}(this))},GithubController.prototype.loadInitialData=function(){var promise;return promise=this.loadProject(),promise.then(function(_this){return function(){return _this.loadModules()}}(this)),promise},GithubController}(mixOf(taiga.Controller,taiga.PageMixin,taiga.FiltersMixin)),module.controller("GithubController",GithubController),GitlabController=function(superClass){function GitlabController(scope,repo,rs,params,appMetaService,translate){var promise;this.scope=scope,this.repo=repo,this.rs=rs,this.params=params,this.appMetaService=appMetaService,this.translate=translate,bindMethods(this),this.scope.sectionName=this.translate.instant("ADMIN.GITLAB.SECTION_NAME"),this.scope.project={},promise=this.loadInitialData(),promise.then(function(_this){return function(){var description,title;return title=_this.translate.instant("ADMIN.GITLAB.PAGE_TITLE",{projectName:_this.scope.project.name}),description=_this.scope.project.description,_this.appMetaService.setAll(title,description)}}(this)),promise.then(null,this.onInitialDataError.bind(this)),this.scope.$on("project:modules:reload",function(_this){return function(){return _this.loadModules()}}(this))}return extend(GitlabController,superClass),GitlabController.$inject=["$scope","$tgRepo","$tgResources","$routeParams","tgAppMetaService","$translate"],GitlabController.prototype.loadModules=function(){return this.rs.modules.list(this.scope.projectId,"gitlab").then(function(_this){return function(gitlab){return _this.scope.gitlab=gitlab}}(this))},GitlabController.prototype.loadProject=function(){return this.rs.projects.getBySlug(this.params.pslug).then(function(_this){return function(project){return _this.scope.projectId=project.id,_this.scope.project=project,_this.scope.$emit("project:loaded",project),project}}(this))},GitlabController.prototype.loadInitialData=function(){var promise;return promise=this.loadProject(),promise.then(function(_this){return function(){return _this.loadModules()}}(this)),promise},GitlabController}(mixOf(taiga.Controller,taiga.PageMixin,taiga.FiltersMixin)),module.controller("GitlabController",GitlabController),BitbucketController=function(superClass){function BitbucketController(scope,repo,rs,params,appMetaService,translate){var promise;this.scope=scope,this.repo=repo,this.rs=rs,this.params=params,this.appMetaService=appMetaService,this.translate=translate,bindMethods(this),this.scope.sectionName=this.translate.instant("ADMIN.BITBUCKET.SECTION_NAME"),this.scope.project={},promise=this.loadInitialData(),promise.then(function(_this){return function(){var description,title;return title=_this.translate.instant("ADMIN.BITBUCKET.PAGE_TITLE",{projectName:_this.scope.project.name}),description=_this.scope.project.description,_this.appMetaService.setAll(title,description)}}(this)),promise.then(null,this.onInitialDataError.bind(this)),this.scope.$on("project:modules:reload",function(_this){return function(){return _this.loadModules()}}(this))}return extend(BitbucketController,superClass),BitbucketController.$inject=["$scope","$tgRepo","$tgResources","$routeParams","tgAppMetaService","$translate"],BitbucketController.prototype.loadModules=function(){return this.rs.modules.list(this.scope.projectId,"bitbucket").then(function(_this){return function(bitbucket){return _this.scope.bitbucket=bitbucket}}(this))},BitbucketController.prototype.loadProject=function(){return this.rs.projects.getBySlug(this.params.pslug).then(function(_this){return function(project){return _this.scope.projectId=project.id,_this.scope.project=project,_this.scope.$emit("project:loaded",project),project}}(this))},BitbucketController.prototype.loadInitialData=function(){var promise;return promise=this.loadProject(),promise.then(function(_this){return function(){return _this.loadModules()}}(this)),promise},BitbucketController}(mixOf(taiga.Controller,taiga.PageMixin,taiga.FiltersMixin)),module.controller("BitbucketController",BitbucketController),SelectInputText=function(){var link;return link=function($scope,$el,$attrs){return $el.on("click",".select-input-content",function(){return $el.find("input").select(),$el.find(".help-copy").addClass("visible")})},{link:link}},module.directive("tgSelectInputText",SelectInputText),GithubWebhooksDirective=function($repo,$confirm,$loading){var link;return link=function($scope,$el,$attrs){var form,submit,submitButton;return form=$el.find("form").checksley({onlyOneErrorElement:!0}),submit=debounce(2e3,function(_this){return function(event){var currentLoading,promise;return event.preventDefault(),form.validate()?(currentLoading=$loading().target(submitButton).start(),promise=$repo.saveAttribute($scope.github,"github"),promise.then(function(){return currentLoading.finish(),$confirm.notify("success")}),promise.then(null,function(data){return currentLoading.finish(),form.setErrors(data),data._error_message?$confirm.notify("error",data._error_message):void 0})):void 0}}(this)),submitButton=$el.find(".submit-button"),$el.on("submit","form",submit)},{link:link}},module.directive("tgGithubWebhooks",["$tgRepo","$tgConfirm","$tgLoading",GithubWebhooksDirective]),GitlabWebhooksDirective=function($repo,$confirm,$loading){var link;return link=function($scope,$el,$attrs){var form,submit,submitButton;return form=$el.find("form").checksley({onlyOneErrorElement:!0}),submit=debounce(2e3,function(_this){return function(event){var currentLoading,promise;return event.preventDefault(),form.validate()?(currentLoading=$loading().target(submitButton).start(),promise=$repo.saveAttribute($scope.gitlab,"gitlab"),promise.then(function(){return currentLoading.finish(),$confirm.notify("success"),$scope.$emit("project:modules:reload")}),promise.then(null,function(data){return currentLoading.finish(),form.setErrors(data),data._error_message?$confirm.notify("error",data._error_message):void 0})):void 0}}(this)),submitButton=$el.find(".submit-button"),$el.on("submit","form",submit)},{link:link}},module.directive("tgGitlabWebhooks",["$tgRepo","$tgConfirm","$tgLoading",GitlabWebhooksDirective]),BitbucketWebhooksDirective=function($repo,$confirm,$loading){var link;return link=function($scope,$el,$attrs){var form,submit,submitButton;return form=$el.find("form").checksley({onlyOneErrorElement:!0}),submit=debounce(2e3,function(_this){return function(event){var currentLoading,promise;return event.preventDefault(),form.validate()?(currentLoading=$loading().target(submitButton).start(),promise=$repo.saveAttribute($scope.bitbucket,"bitbucket"),promise.then(function(){return currentLoading.finish(),$confirm.notify("success"),$scope.$emit("project:modules:reload")}),promise.then(null,function(data){return currentLoading.finish(),form.setErrors(data),data._error_message?$confirm.notify("error",data._error_message):void 0})):void 0}}(this)),submitButton=$el.find(".submit-button"),$el.on("submit","form",submit)},{link:link}},module.directive("tgBitbucketWebhooks",["$tgRepo","$tgConfirm","$tgLoading",BitbucketWebhooksDirective]),ValidOriginIpsDirective=function(){var link;return link=function($scope,$el,$attrs,$ngModel){return $ngModel.$parsers.push(function(value){return value=$.trim(value),""===value?[]:value.split(",")})},{link:link,restrict:"EA",require:"ngModel"}},module.directive("tgValidOriginIps",ValidOriginIpsDirective)}.call(this),function(){var CreateProject,DeleteProjectDirective,bindOnce,debounce,module,taiga,timeout;taiga=this.taiga,bindOnce=this.taiga.bindOnce,timeout=this.taiga.timeout,debounce=this.taiga.debounce,module=angular.module("taigaProject"),CreateProject=function($rootscope,$repo,$confirm,$location,$navurls,$rs,$projectUrl,$loading,lightboxService,$cacheFactory,$translate,currentUserService){var directive,link;return link=function($scope,$el,attrs){var currentLoading,form,onErrorSubmit,onSuccessSubmit,openLightbox,submit,submitButton;return $scope.data={},$scope.templates=[],currentLoading=null,form=$el.find("form").checksley({onlyOneErrorElement:!0}),onSuccessSubmit=function(response){return $cacheFactory.get("$http").removeAll(),currentLoading.finish(),$rootscope.$broadcast("projects:reload"),$confirm.notify("success",$translate.instant("COMMON.SAVE")),$location.url($projectUrl.get(response)),lightboxService.close($el),currentUserService.loadProjects()},onErrorSubmit=function(response){var error_field,error_step,i,len,ref,selectors;for(currentLoading.finish(),form.setErrors(response),selectors=[],ref=_.keys(response),i=0,len=ref.length;len>i;i++)error_field=ref[i],selectors.push("[name="+error_field+"]");return $el.find(".active").removeClass("active"),error_step=$el.find(selectors.join(",")).first().parents(".wizard-step"),error_step.addClass("active"),$el.find(".progress-bar").removeClass().addClass("progress-bar").addClass(error_step.data("step"))},submit=function(_this){return function(event){var promise;return event.preventDefault(),form.validate()?(currentLoading=$loading().target(submitButton).start(),promise=$repo.create("projects",$scope.data),promise.then(onSuccessSubmit,onErrorSubmit)):void 0}}(this),openLightbox=function(){return $scope.data={},$scope.templates.length?$scope.data.creation_template=_.head(_.filter($scope.templates,function(x){return"scrum"===x.slug})).id:$rs.projects.templates().then(function(_this){return function(result){return $scope.templates=result,$scope.data.creation_template=_.head(_.filter($scope.templates,function(x){return"scrum"===x.slug})).id}}(this)),$el.find(".active").removeClass("active"),$el.find(".create-step1").addClass("active"),lightboxService.open($el),timeout(600,function(){return $el.find(".progress-bar").addClass("step1")})},$el.on("click",".button-next",function(event){var current,field,i,len,next,ref,step,valid;for(event.preventDefault(),current=$el.find(".active"),valid=!0,ref=form.fields,i=0,len=ref.length;len>i;i++)field=ref[i],current.find("[name="+field.element.attr("name")+"]").length&&(valid=field.validate()!==!1&&valid);return valid?(next=current.next(),current.toggleClass("active"),next.toggleClass("active"),step=next.data("step"),$el.find(".progress-bar").removeClass().addClass("progress-bar").addClass(step)):void 0}),$el.on("click",".button-prev",function(event){var current,prev,step;return event.preventDefault(),current=$el.find(".active"),prev=current.prev(),current.toggleClass("active"),prev.toggleClass("active"),step=prev.data("step"),$el.find(".progress-bar").removeClass().addClass("progress-bar").addClass(step)}),submitButton=$el.find(".submit-button"),$el.on("submit","form",submit),$el.on("click",".close",function(event){return event.preventDefault(),lightboxService.close($el)}),$scope.$on("$destroy",function(){return $el.off()}),openLightbox()},directive={link:link,templateUrl:"project/wizard-create-project.html",scope:{}}},module.directive("tgLbCreateProject",["$rootScope","$tgRepo","$tgConfirm","$location","$tgNavUrls","$tgResources","$projectUrl","$tgLoading","lightboxService","$cacheFactory","$translate","tgCurrentUserService",CreateProject]), -DeleteProjectDirective=function($repo,$rootscope,$auth,$location,$navUrls,$confirm,lightboxService,tgLoader,currentUserService){var link;return link=function($scope,$el,$attrs){var projectToDelete,submit;return projectToDelete=null,$scope.$on("deletelightbox:new",function(ctx,project){return lightboxService.open($el),projectToDelete=project}),$scope.$on("$destroy",function(){return $el.off()}),submit=function(){var promise;return tgLoader.start(),lightboxService.close($el),promise=$repo.remove(projectToDelete),promise.then(function(data){return tgLoader.pageLoaded(),$rootscope.$broadcast("projects:reload"),$location.path($navUrls.resolve("home")),$confirm.notify("success"),currentUserService.loadProjects()}),promise.then(null,function(){return $confirm.notify("error"),lightboxService.close($el)})},$el.on("click",".button-red",function(event){return event.preventDefault(),lightboxService.close($el)}),$el.on("click",".button-green",function(event){return event.preventDefault(),submit()})},{link:link}},module.directive("tgLbDeleteProject",["$tgRepo","$rootScope","$tgAuth","$tgLocation","$tgNavUrls","$tgConfirm","lightboxService","tgLoader","tgCurrentUserService",DeleteProjectDirective])}.call(this),function(){var BindHtmlDirective,BindOnceAltDirective,BindOnceBindDirective,BindOnceHrefDirective,BindOnceHtmlDirective,BindOnceRefDirective,BindOnceSrcDirective,BindOnceTitleDirective,BindTitleDirective,bindOnce,module;bindOnce=this.taiga.bindOnce,BindOnceBindDirective=function(){var link;return link=function($scope,$el,$attrs){return bindOnce($scope,$attrs.tgBoBind,function(val){return $el.text(val)})},{link:link}},BindOnceHtmlDirective=function(){var link;return link=function($scope,$el,$attrs){return bindOnce($scope,$attrs.tgBoHtml,function(val){return $el.html(val)})},{link:link}},BindOnceRefDirective=function(){var link;return link=function($scope,$el,$attrs){return bindOnce($scope,$attrs.tgBoRef,function(val){return $el.html("#"+val+" ")})},{link:link}},BindOnceSrcDirective=function(){var link;return link=function($scope,$el,$attrs){return bindOnce($scope,$attrs.tgBoSrc,function(val){return $el.attr("src",val)})},{link:link}},BindOnceHrefDirective=function(){var link;return link=function($scope,$el,$attrs){return bindOnce($scope,$attrs.tgBoHref,function(val){return $el.attr("href",val)})},{link:link}},BindOnceAltDirective=function(){var link;return link=function($scope,$el,$attrs){return bindOnce($scope,$attrs.tgBoAlt,function(val){return $el.attr("alt",val)})},{link:link}},BindOnceTitleDirective=function(){var link;return link=function($scope,$el,$attrs){return bindOnce($scope,$attrs.tgBoTitle,function(val){return $el.attr("title",val)})},{link:link}},BindTitleDirective=function(){var link;return link=function($scope,$el,$attrs){return $scope.$watch($attrs.tgTitleHtml,function(val){return null!=val?$el.attr("title",val):void 0})},{link:link}},BindHtmlDirective=function(){var link;return link=function($scope,$el,$attrs){return $scope.$watch($attrs.tgBindHtml,function(val){return null!=val?$el.html(val):void 0})},{link:link}},module=angular.module("taigaBase"),module.directive("tgBoBind",BindOnceBindDirective),module.directive("tgBoHtml",BindOnceHtmlDirective),module.directive("tgBoRef",BindOnceRefDirective),module.directive("tgBoSrc",BindOnceSrcDirective),module.directive("tgBoHref",BindOnceHrefDirective),module.directive("tgBoAlt",BindOnceAltDirective),module.directive("tgBoTitle",BindOnceTitleDirective),module.directive("tgBindTitle",BindTitleDirective),module.directive("tgBindHtml",BindHtmlDirective)}.call(this),function(){var ConfigurationService,module;ConfigurationService=function(){function ConfigurationService(){this.config=window.taigaConfig}return ConfigurationService.prototype.get=function(key,defaultValue){return null==defaultValue&&(defaultValue=null),_.has(this.config,key)?this.config[key]:defaultValue},ConfigurationService}(),module=angular.module("taigaBase"),module.service("$tgConfig",ConfigurationService)}.call(this),function(){var ContribController,module,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;module=angular.module("taigaBase"),ContribController=function(superClass){function ContribController(rootScope,scope,params,repo,rs,confirm){var promise;this.rootScope=rootScope,this.scope=scope,this.params=params,this.repo=repo,this.rs=rs,this.confirm=confirm,this.scope.currentPlugin=_.first(_.where(this.rootScope.adminPlugins,{slug:this.params.plugin})),this.scope.projectSlug=this.params.pslug,promise=this.loadInitialData(),promise.then(null,function(_this){return function(){return _this.confirm.notify("error")}}(this))}return extend(ContribController,superClass),ContribController.$inject=["$rootScope","$scope","$routeParams","$tgRepo","$tgResources","$tgConfirm"],ContribController.prototype.loadProject=function(){return this.rs.projects.getBySlug(this.params.pslug).then(function(_this){return function(project){return _this.scope.projectId=project.id,_this.scope.project=project,_this.scope.$emit("project:loaded",project),_this.scope.$broadcast("project:loaded",project),project}}(this))},ContribController.prototype.loadInitialData=function(){return this.loadProject()},ContribController}(taiga.Controller),module.controller("ContribController",ContribController)}.call(this),function(){var FiltersStorageService,taiga,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,FiltersStorageService=function(superClass){function FiltersStorageService(storage,params){this.storage=storage,this.params=params}return extend(FiltersStorageService,superClass),FiltersStorageService.$inject=["$tgStorage","$routeParams"],FiltersStorageService.prototype.generateHash=function(components){return null==components&&(components=[]),components=_.map(components,function(x){return JSON.stringify(x)}),hex_sha1(components.join(":"))},FiltersStorageService}(taiga.Service)}.call(this),function(){var HttpService,module,taiga,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,HttpService=function(superClass){function HttpService(http,q,storage,rootScope,cacheFactory,translate){this.http=http,this.q=q,this.storage=storage,this.rootScope=rootScope,this.cacheFactory=cacheFactory,this.translate=translate,HttpService.__super__.constructor.call(this),this.cache=this.cacheFactory("httpget")}return extend(HttpService,superClass),HttpService.$inject=["$http","$q","$tgStorage","$rootScope","$cacheFactory","$translate"],HttpService.prototype.headers=function(){var headers,lang,token;return headers={},token=this.storage.get("token"),token&&(headers.Authorization="Bearer "+token),lang=this.translate.preferredLanguage(),lang&&(headers["Accept-Language"]=lang),headers},HttpService.prototype.request=function(options){return options.headers=_.merge({},options.headers||{},this.headers()),this.http(options)},HttpService.prototype.get=function(url,params,options){return options=_.merge({method:"GET",url:url},options),params&&(options.params=params),options.cache=this.cache,this.request(options)["finally"](function(_this){return function(data){return _this.cache.removeAll()}}(this))},HttpService.prototype.post=function(url,data,params,options){return options=_.merge({method:"POST",url:url},options),data&&(options.data=data),params&&(options.params=params),this.request(options)},HttpService.prototype.put=function(url,data,params,options){return options=_.merge({method:"PUT",url:url},options),data&&(options.data=data),params&&(options.params=params),this.request(options)},HttpService.prototype.patch=function(url,data,params,options){return options=_.merge({method:"PATCH",url:url},options),data&&(options.data=data),params&&(options.params=params),this.request(options)},HttpService.prototype["delete"]=function(url,data,params,options){return options=_.merge({method:"DELETE",url:url},options),data&&(options.data=data),params&&(options.params=params),this.request(options)},HttpService}(taiga.Service),module=angular.module("taigaBase"),module.service("$tgHttp",HttpService)}.call(this),function(){var locationFactory,module;locationFactory=function($location,$route,$rootscope){return $location.noreload=function(scope){var lastRoute,un;return lastRoute=$route.current,un=scope.$on("$locationChangeSuccess",function(){return $route.current=lastRoute,un()}),$location},$location.isInCurrentRouteParams=function(name,value){var params;return params=$location.search()||{},params[name]===value},$location},module=angular.module("taigaBase"),module.factory("$tgLocation",["$location","$route","$rootScope",locationFactory])}.call(this),function(){var Model,ModelService,module,provider,taiga,indexOf=[].indexOf||function(item){for(var i=0,l=this.length;l>i;i++)if(i in this&&this[i]===item)return i;return-1},extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;Model=function(){function Model(name,data,dataTypes){this._attrs=data,this._name=name,this._dataTypes=dataTypes,this.setAttrs(data),this.initialize()}return Model.prototype.clone=function(){var instance;return instance=new Model(this._name,this._attrs,this._dataTypes),instance._modifiedAttrs=this._modifiedAttrs,instance._isModified=this._isModified,instance},Model.prototype.applyCasts=function(){var attrName,castMethod,castName,ref,results;ref=this._dataTypes,results=[];for(attrName in ref)castName=ref[attrName],castMethod=service.casts[castName],castMethod&&results.push(this._attrs[attrName]=castMethod(this._attrs[attrName]));return results},Model.prototype.getIdAttrName=function(){return"id"},Model.prototype.getName=function(){return this._name},Model.prototype.getAttrs=function(patch){return null==patch&&(patch=!1),null!=this._attrs.version&&(this._modifiedAttrs.version=this._attrs.version),patch?_.extend({},this._modifiedAttrs):_.extend({},this._attrs,this._modifiedAttrs)},Model.prototype.setAttrs=function(attrs){return this._attrs=attrs,this._modifiedAttrs={},this.applyCasts(),this._isModified=!1},Model.prototype.setAttr=function(name,value){return this._modifiedAttrs[name]=value,this._isModified=!0},Model.prototype.initialize=function(){var getter,self,setter;return self=this,getter=function(name){return function(){return"string"==typeof name&&"__"===name.substr(0,2)?self[name]:indexOf.call(_.keys(self._modifiedAttrs),name)<0?self._attrs[name]:self._modifiedAttrs[name]}},setter=function(name){return function(value){return"string"==typeof name&&"__"===name.substr(0,2)?void(self[name]=value):void(self._attrs[name]!==value?(self._modifiedAttrs[name]=value,self._isModified=!0):delete self._modifiedAttrs[name])}},_.each(this._attrs,function(value,name){var options;return options={get:getter(name),set:setter(name),enumerable:!0,configurable:!0},Object.defineProperty(self,name,options)})},Model.prototype.serialize=function(){var data;return data={data:_.clone(this._attrs),name:this._name},JSON.stringify(data)},Model.prototype.isModified=function(){return this._isModified},Model.prototype.isAttributeModified=function(attribute){return null!=this._modifiedAttrs[attribute]},Model.prototype.markSaved=function(){return this._isModified=!1,this._attrs=this.getAttrs(),this._modifiedAttrs={}},Model.prototype.revert=function(){return this._modifiedAttrs={},this._isModified=!1},Model.desSerialize=function(sdata){var ddata,model;return ddata=JSON.parse(sdata),model=new Model(ddata.url,ddata.data)},Model}(),taiga=this.taiga,ModelService=function(superClass){function ModelService(q,urls,storage,http){this.q=q,this.urls=urls,this.storage=storage,this.http=http,ModelService.__super__.constructor.call(this)}return extend(ModelService,superClass),ModelService.$inject=["$q","$tgUrls","$tgStorage","$tgHttp"],ModelService}(taiga.Service),provider=function($q,$http,$gmUrls,$gmStorage){var service;return service={},service.make_model=function(name,data,cls,dataTypes){return null==cls&&(cls=Model),null==dataTypes&&(dataTypes={}),new cls(name,data,dataTypes)},service.cls=Model,service.casts={"int":function(value){return parseInt(value,10)},"float":function(value){return parseFloat(value,10)}},service},module=angular.module("taigaBase"),module.factory("$tgModel",["$q","$http","$tgUrls","$tgStorage",provider])}.call(this),function(){var NavigationUrlsDirective,NavigationUrlsService,bindOnce,module,taiga,trim,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,trim=this.taiga.trim,bindOnce=this.taiga.bindOnce,module=angular.module("taigaBase"),NavigationUrlsService=function(superClass){function NavigationUrlsService(){this.urls={}}return extend(NavigationUrlsService,superClass),NavigationUrlsService.prototype.update=function(urls){return this.urls=_.merge({},this.urls,urls||{})},NavigationUrlsService.prototype.formatUrl=function(url,ctx){var replacer;return null==ctx&&(ctx={}),replacer=function(match){return match=trim(match,":"),ctx[match]||"undefined"},url.replace(/(:\w+)/g,replacer)},NavigationUrlsService.prototype.resolve=function(name,ctx){var url;return url=this.urls[name],url?ctx?this.formatUrl(url,ctx):url:""},NavigationUrlsService}(taiga.Service),module.service("$tgNavUrls",NavigationUrlsService),NavigationUrlsDirective=function($navurls,$auth,$q,$location){var bindOnceP,link,parseNav;return bindOnceP=function($scope,attr){var defered;return defered=$q.defer(),bindOnce($scope,attr,function(v){return defered.resolve(v)}),defered.promise},parseNav=function(data,$scope){var index,name,obj,params,promises,ref,result,values;if(ref=_.map(data.split(":"),trim),name=ref[0],params=ref[1],params)for(result=params.split(/(\w+)=/),result=_.filter(result,function(str){return str.length}),result=_.map(result,function(str){return trim(str.replace(/,$/g,""))}),params=[],index=0;indexi;i++)param=params[i],key=Object.keys(param)[0],value=param[key],options[key]=$scope.$eval(value);return[name,options]})},link=function($scope,$el,$attrs){return $el.is("a")&&$el.attr("href","#"),$el.on("mouseenter",function(event){var target;return target=$(event.currentTarget),target.data("fullUrl")?void 0:parseNav($attrs.tgNav,$scope).then(function(result){var fullUrl,getURLParams,getURLParamsStr,name,options,url,user;return name=result[0],options=result[1],user=$auth.getUser(),user&&(options.user=user.username),url=$navurls.resolve(name),fullUrl=$navurls.formatUrl(url,options),$attrs.tgNavGetParams&&(getURLParams=JSON.parse($attrs.tgNavGetParams),getURLParamsStr=$.param(getURLParams),fullUrl=fullUrl+"?"+getURLParamsStr),target.data("fullUrl",fullUrl),target.is("a")&&target.attr("href",fullUrl),$el.on("click",function(event){if(!event.metaKey&&!event.ctrlKey&&(event.preventDefault(),target=$(event.currentTarget),!target.hasClass("noclick")))switch(fullUrl=target.data("fullUrl"),event.which){case 1:return $location.url(fullUrl),$scope.$apply();case 2:return window.open(fullUrl)}})})}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgNav",["$tgNavUrls","$tgAuth","$q","$tgLocation",NavigationUrlsDirective])}.call(this),function(){var RepositoryService,module,taiga,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,RepositoryService=function(superClass){function RepositoryService(q,model1,storage,http,urls){this.q=q,this.model=model1,this.storage=storage,this.http=http,this.urls=urls,RepositoryService.__super__.constructor.call(this)}return extend(RepositoryService,superClass),RepositoryService.$inject=["$q","$tgModel","$tgStorage","$tgHttp","$tgUrls"],RepositoryService.prototype.resolveUrlForModel=function(model){var idAttrName;return idAttrName=model.getIdAttrName(),this.urls.resolve(model.getName())+"/"+model[idAttrName]},RepositoryService.prototype.resolveUrlForAttributeModel=function(model){return this.urls.resolve(model.getName(),model.parent)},RepositoryService.prototype.create=function(name,data,dataTypes,extraParams){var defered,promise,url;return null==dataTypes&&(dataTypes={}),null==extraParams&&(extraParams={}),defered=this.q.defer(),url=this.urls.resolve(name),promise=this.http.post(url,JSON.stringify(data)),promise.success(function(_this){return function(_data,_status){return defered.resolve(_this.model.make_model(name,_data,null,dataTypes))}}(this)),promise.error(function(_this){return function(data,status){return defered.reject(data)}}(this)),defered.promise},RepositoryService.prototype.remove=function(model,params){var defered,promise,url;return null==params&&(params={}),defered=this.q.defer(),url=this.resolveUrlForModel(model),promise=this.http["delete"](url,{},params),promise.success(function(data,status){return defered.resolve(model)}),promise.error(function(data,status){return defered.reject(model)}),defered.promise},RepositoryService.prototype.saveAll=function(models,patch){var promises;return null==patch&&(patch=!0),promises=_.map(models,function(_this){return function(x){return _this.save(x,!0)}}(this)),this.q.all(promises)},RepositoryService.prototype.save=function(model,patch){var data,defered,promise,url;return null==patch&&(patch=!0),defered=this.q.defer(),!model.isModified()&&patch?(defered.resolve(model),defered.promise):(url=this.resolveUrlForModel(model),data=JSON.stringify(model.getAttrs(patch)),promise=patch?this.http.patch(url,data):this.http.put(url,data),promise.success(function(_this){return function(data,status){return model._isModified=!1,model._attrs=_.extend(model.getAttrs(),data),model._modifiedAttrs={},model.applyCasts(),defered.resolve(model)}}(this)),promise.error(function(data,status){return defered.reject(data)}),defered.promise)},RepositoryService.prototype.saveAttribute=function(model,attribute,patch){var data,defered,promise,url;return null==patch&&(patch=!0),defered=this.q.defer(),!model.isModified()&&patch?(defered.resolve(model),defered.promise):(url=this.resolveUrlForAttributeModel(model),data={},data[attribute]=model.getAttrs(),promise=patch?this.http.patch(url,data):this.http.put(url,data),promise.success(function(_this){return function(data,status){return model._isModified=!1,model._attrs=_.extend(model.getAttrs(),data),model._modifiedAttrs={},model.applyCasts(),defered.resolve(model)}}(this)),promise.error(function(data,status){return defered.reject(data)}),defered.promise)},RepositoryService.prototype.refresh=function(model){var defered,promise,url;return defered=this.q.defer(),url=this.resolveUrlForModel(model),promise=this.http.get(url),promise.success(function(data,status){return model._modifiedAttrs={},model._attrs=data,model._isModified=!1,model.applyCasts(),defered.resolve(model)}),promise.error(function(data,status){return defered.reject(data)}),defered.promise},RepositoryService.prototype.queryMany=function(name,params,options,headers){var httpOptions,url;return null==options&&(options={}),null==headers&&(headers=!1),url=this.urls.resolve(name),httpOptions={headers:{}},options.enablePagination||(httpOptions.headers["x-disable-pagination"]="1"),this.http.get(url,params,httpOptions).then(function(_this){return function(data){var result;return result=_.map(data.data,function(x){return _this.model.make_model(name,x)}),headers?[result,data.headers]:result}}(this))},RepositoryService.prototype.queryOneAttribute=function(name,id,attribute,params,options){var httpOptions,url;return null==options&&(options={}),url=this.urls.resolve(name,id),httpOptions={headers:{}},options.enablePagination||(httpOptions.headers["x-disable-pagination"]="1"),this.http.get(url,params,httpOptions).then(function(_this){return function(data){var model;return model=_this.model.make_model(name,data.data[attribute]),model.parent=id,model}}(this))},RepositoryService.prototype.queryOne=function(name,id,params,options){var httpOptions,url;return null==options&&(options={}),url=this.urls.resolve(name),id&&(url=url+"/"+id),httpOptions={headers:{}},options.enablePagination||(httpOptions.headers["x-disable-pagination"]="1"),this.http.get(url,params,httpOptions).then(function(_this){return function(data){return _this.model.make_model(name,data.data)}}(this))},RepositoryService.prototype.queryOneRaw=function(name,id,params,options){var httpOptions,url;return null==options&&(options={}),url=this.urls.resolve(name),id&&(url=url+"/"+id),httpOptions=_.merge({headers:{}},options),options.enablePagination||(httpOptions.headers["x-disable-pagination"]="1"),this.http.get(url,params,httpOptions).then(function(_this){return function(data){return data.data}}(this))},RepositoryService.prototype.queryPaginated=function(name,params,options){var httpOptions,url;return null==options&&(options={}),url=this.urls.resolve(name),httpOptions=_.merge({headers:{}},options),this.http.get(url,params,httpOptions).then(function(_this){return function(data){var headers,result;return headers=data.headers(),result={},result.models=_.map(data.data,function(x){return _this.model.make_model(name,x)}),result.count=parseInt(headers["x-pagination-count"],10),result.current=parseInt(headers["x-pagination-current"]||1,10),result.paginatedBy=parseInt(headers["x-paginated-by"],10),result}}(this))},RepositoryService.prototype.queryOnePaginatedRaw=function(name,id,params,options){var httpOptions,url;return null==options&&(options={}),url=this.urls.resolve(name),id&&(url=url+"/"+id),httpOptions=_.merge({headers:{}},options),this.http.get(url,params,httpOptions).then(function(_this){return function(data){var headers,result;return headers=data.headers(),result={},result.data=data.data,result.count=parseInt(headers["x-pagination-count"],10),result.current=parseInt(headers["x-pagination-current"]||1,10),result.paginatedBy=parseInt(headers["x-paginated-by"],10),result}}(this))},RepositoryService.prototype.resolve=function(options){var cache,params;return params={},null!=options.pslug&&(params.project=options.pslug),null!=options.usref&&(params.us=options.usref),null!=options.taskref&&(params.task=options.taskref),null!=options.issueref&&(params.issue=options.issueref),null!=options.sslug&&(params.milestone=options.sslug),null!=options.wikipage&&(params.wikipage=options.wikipage),cache=!(options.wikipage||options.sslug),this.queryOneRaw("resolver",null,params,{cache:cache})},RepositoryService}(taiga.Service),module=angular.module("taigaBase"),module.service("$tgRepo",RepositoryService)}.call(this),function(){var StorageService,module,taiga,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,StorageService=function(superClass){function StorageService($rootScope){StorageService.__super__.constructor.call(this)}return extend(StorageService,superClass),StorageService.$inject=["$rootScope"],StorageService.prototype.get=function(key,_default){var serializedValue;return serializedValue=localStorage.getItem(key),null===serializedValue?_default||null:JSON.parse(serializedValue)},StorageService.prototype.set=function(key,val){return _.isObject(key)?_.each(key,function(_this){return function(val,key){return _this.set(key,val)}}(this)):localStorage.setItem(key,JSON.stringify(val))},StorageService.prototype.contains=function(key){var value;return value=this.get(key),null!==value},StorageService.prototype.remove=function(key){return localStorage.removeItem(key)},StorageService.prototype.clear=function(){return localStorage.clear()},StorageService}(taiga.Service),module=angular.module("taigaBase"),module.service("$tgStorage",StorageService)}.call(this),function(){var UrlsService,format,module,taiga,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;format=function(fmt,obj){return obj=_.clone(obj),fmt.replace(/%s/g,function(match){return String(obj.shift())})},taiga=this.taiga,UrlsService=function(superClass){function UrlsService(config){this.config=config,this.urls={},this.mainUrl=this.config.get("api")}return extend(UrlsService,superClass),UrlsService.$inject=["$tgConfig"],UrlsService.prototype.update=function(urls){return this.urls=_.merge(this.urls,urls)},UrlsService.prototype.resolve=function(){var args,name,url;if(args=_.toArray(arguments),0===args.length)throw Error("wrong arguments to setUrls");return name=args.slice(0,1)[0],url=format(this.urls[name],args.slice(1)),format("%s/%s",[_.str.rtrim(this.mainUrl,"/"),_.str.ltrim(url,"/")])},UrlsService.prototype.resolveAbsolute=function(){var url;return url=this.resolve.apply(this,arguments),/^https?:\/\//i.test(url)?url:/^\//.test(url)?window.location.protocol+"//"+window.location.host+url:window.location.protocol+"//"+window.location.host+"/"+url},UrlsService}(taiga.Service),module=angular.module("taigaBase"),module.service("$tgUrls",UrlsService)}.call(this),function(){var module,resourceProvider,sizeFormat,taiga;taiga=this.taiga,sizeFormat=this.taiga.sizeFormat,resourceProvider=function($rootScope,$config,$urls,$model,$repo,$auth,$q){var service;return service={},service.list=function(urlName,objectId,projectId){var params;return params={object_id:objectId,project:projectId},$repo.queryMany(urlName,params)},service.create=function(urlName,projectId,objectId,file){var data,defered,maxFileSize,response,uploadComplete,uploadFailed,uploadProgress,xhr;return defered=$q.defer(),void 0===file?(defered.reject(null),defered.promise):(maxFileSize=$config.get("maxUploadFileSize",null),maxFileSize&&file.size>maxFileSize?(response={status:413,data:{_error_message:"'"+file.name+"' ("+sizeFormat(file.size)+") is too heavy for our oompa loompas, try it with a smaller than ("+sizeFormat(maxFileSize)+")"}},defered.reject(response),defered.promise):(uploadProgress=function(_this){return function(evt){return $rootScope.$apply(function(){return file.status="in-progress",file.size=sizeFormat(evt.total),file.progressMessage="upload "+sizeFormat(evt.loaded)+" of "+sizeFormat(evt.total),file.progressPercent=Math.round(evt.loaded/evt.total*100)+"%"})}}(this),uploadComplete=function(_this){return function(evt){return $rootScope.$apply(function(){var data,model,ref,status;file.status="done",status=evt.target.status;try{data=JSON.parse(evt.target.responseText)}catch(error){data={}}return status>=200&&400>status?(model=$model.make_model(urlName,data),defered.resolve(model)):(response={status:status,data:{_error_message:null!=(ref=data.attached_file)?ref[0]:void 0}},defered.reject(response))})}}(this),uploadFailed=function(_this){return function(evt){return $rootScope.$apply(function(){return file.status="error",defered.reject("fail")})}}(this),data=new FormData,data.append("project",projectId),data.append("object_id",objectId),data.append("attached_file",file),xhr=new XMLHttpRequest,xhr.upload.addEventListener("progress",uploadProgress,!1),xhr.addEventListener("load",uploadComplete,!1),xhr.addEventListener("error",uploadFailed,!1),xhr.open("POST",$urls.resolve(urlName)),xhr.setRequestHeader("Authorization","Bearer "+$auth.getToken()),xhr.setRequestHeader("Accept","application/json"),xhr.send(data),defered.promise))},function(instance){return instance.attachments=service}},module=angular.module("taigaResources"),module.factory("$tgAttachmentsResourcesProvider",["$rootScope","$tgConfig","$tgUrls","$tgModel","$tgRepo","$tgAuth","$q",resourceProvider])}.call(this),function(){var module,resourceProvider,taiga;taiga=this.taiga,resourceProvider=function($repo){var _get,service;return _get=function(objectId,resource){return $repo.queryOne(resource,objectId)},service={userstory:{get:function(objectId){return _get(objectId,"custom-attributes-values/userstory")}},task:{get:function(objectId){return _get(objectId,"custom-attributes-values/task")}},issue:{get:function(objectId){return _get(objectId,"custom-attributes-values/issue")}}},function(instance){return instance.customAttributesValues=service}},module=angular.module("taigaResources"),module.factory("$tgCustomAttributesValuesResourcesProvider",["$tgRepo",resourceProvider])}.call(this),function(){var module,resourceProvider,sizeFormat,taiga;taiga=this.taiga,sizeFormat=this.taiga.sizeFormat,resourceProvider=function($repo){var _list,service;return _list=function(projectId,resource){return $repo.queryMany(resource,{project:projectId})},service={userstory:{list:function(projectId){return _list(projectId,"custom-attributes/userstory")}},task:{list:function(projectId){return _list(projectId,"custom-attributes/task")}},issue:{list:function(projectId){return _list(projectId,"custom-attributes/issue")}}},function(instance){return instance.customAttributes=service}},module=angular.module("taigaResources"),module.factory("$tgCustomAttributesResourcesProvider",["$tgRepo",resourceProvider])}.call(this),function(){var module,resourceProvider,taiga;taiga=this.taiga,resourceProvider=function($repo,$http,$urls){var service;return service={},service.get=function(type,objectId){return $repo.queryOneRaw("history/"+type,objectId)},service.deleteComment=function(type,objectId,activityId){var params,url;return url=$urls.resolve("history/"+type),url=url+"/"+objectId+"/delete_comment",params={id:activityId},$http.post(url,null,params).then(function(_this){return function(data){return data.data}}(this))},service.undeleteComment=function(type,objectId,activityId){var params,url;return url=$urls.resolve("history/"+type),url=url+"/"+objectId+"/undelete_comment",params={id:activityId},$http.post(url,null,params).then(function(_this){return function(data){return data.data}}(this))},function(instance){return instance.history=service}},module=angular.module("taigaResources"),module.factory("$tgHistoryResourcesProvider",["$tgRepo","$tgHttp","$tgUrls",resourceProvider])}.call(this),function(){var module,resourceProvider,taiga;taiga=this.taiga,resourceProvider=function($repo){var service;return service={},service.get=function(token){return $repo.queryOne("invitations",token)},function(instance){return instance.invitations=service}},module=angular.module("taigaResources"),module.factory("$tgInvitationsResourcesProvider",["$tgRepo",resourceProvider])}.call(this),function(){var generateHash,module,resourceProvider,taiga;taiga=this.taiga,generateHash=taiga.generateHash,resourceProvider=function($repo,$http,$urls,$storage,$q){var filtersHashSuffix,hashSuffix,myFiltersHashSuffix,service; -return service={},hashSuffix="issues-queryparams",filtersHashSuffix="issues-filters",myFiltersHashSuffix="issues-my-filters",service.get=function(projectId,issueId){var params;return params=service.getQueryParams(projectId),params.project=projectId,$repo.queryOne("issues",issueId,params)},service.getByRef=function(projectId,ref){var params;return params=service.getQueryParams(projectId),params.project=projectId,params.ref=ref,$repo.queryOne("issues","by_ref",params)},service.listInAllProjects=function(filters){return $repo.queryMany("issues",filters)},service.list=function(projectId,filters,options){var params;return params={project:projectId},params=_.extend({},params,filters||{}),service.storeQueryParams(projectId,params),$repo.queryPaginated("issues",params,options)},service.bulkCreate=function(projectId,data){var params,url;return url=$urls.resolve("bulk-create-issues"),params={project_id:projectId,bulk_issues:data},$http.post(url,params)},service.upvote=function(issueId){var url;return url=$urls.resolve("issue-upvote",issueId),$http.post(url)},service.downvote=function(issueId){var url;return url=$urls.resolve("issue-downvote",issueId),$http.post(url)},service.watch=function(issueId){var url;return url=$urls.resolve("issue-watch",issueId),$http.post(url)},service.unwatch=function(issueId){var url;return url=$urls.resolve("issue-unwatch",issueId),$http.post(url)},service.stats=function(projectId){return $repo.queryOneRaw("projects",projectId+"/issues_stats")},service.filtersData=function(params){return $repo.queryOneRaw("issues-filters",null,params)},service.listValues=function(projectId,type){var params;return params={project:projectId},service.storeQueryParams(projectId,params),$repo.queryMany(type,params)},service.storeQueryParams=function(projectId,params){var hash,ns;return ns=projectId+":"+hashSuffix,hash=generateHash([projectId,ns]),$storage.set(hash,params)},service.getQueryParams=function(projectId){var hash,ns;return ns=projectId+":"+hashSuffix,hash=generateHash([projectId,ns]),$storage.get(hash)||{}},service.storeFilters=function(projectSlug,params){var hash,ns;return ns=projectSlug+":"+filtersHashSuffix,hash=generateHash([projectSlug,ns]),$storage.set(hash,params)},service.getFilters=function(projectSlug){var hash,ns;return ns=projectSlug+":"+filtersHashSuffix,hash=generateHash([projectSlug,ns]),$storage.get(hash)||{}},service.storeMyFilters=function(projectId,myFilters){var deferred,hash,ns,promise,url;return deferred=$q.defer(),url=$urls.resolve("user-storage"),ns=projectId+":"+myFiltersHashSuffix,hash=generateHash([projectId,ns]),_.isEmpty(myFilters)?(promise=$http["delete"](url+"/"+hash,{key:hash,value:myFilters}),promise.then(function(){return deferred.resolve()}),promise.then(null,function(){return deferred.reject()})):(promise=$http.put(url+"/"+hash,{key:hash,value:myFilters}),promise.then(function(data){return deferred.resolve()}),promise.then(null,function(data){var innerPromise;return innerPromise=$http.post(""+url,{key:hash,value:myFilters}),innerPromise.then(function(){return deferred.resolve()}),innerPromise.then(null,function(){return deferred.reject()})})),deferred.promise},service.getMyFilters=function(projectId){var deferred,hash,ns,promise,url;return deferred=$q.defer(),url=$urls.resolve("user-storage"),ns=projectId+":"+myFiltersHashSuffix,hash=generateHash([projectId,ns]),promise=$http.get(url+"/"+hash),promise.then(function(data){return deferred.resolve(data.data.value)}),promise.then(null,function(data){return deferred.resolve({})}),deferred.promise},function(instance){return instance.issues=service}},module=angular.module("taigaResources"),module.factory("$tgIssuesResourcesProvider",["$tgRepo","$tgHttp","$tgUrls","$tgStorage","$q",resourceProvider])}.call(this),function(){var generateHash,module,resourceProvider,taiga;taiga=this.taiga,generateHash=taiga.generateHash,resourceProvider=function($storage){var hashSuffixStatusColumnModes,hashSuffixStatusViewModes,service;return service={},hashSuffixStatusViewModes="kanban-statusviewmodels",hashSuffixStatusColumnModes="kanban-statuscolumnmodels",service.storeStatusViewModes=function(projectId,params){var hash,ns;return ns=projectId+":"+hashSuffixStatusViewModes,hash=generateHash([projectId,ns]),$storage.set(hash,params)},service.getStatusViewModes=function(projectId){var hash,ns;return ns=projectId+":"+hashSuffixStatusViewModes,hash=generateHash([projectId,ns]),$storage.get(hash)||{}},service.storeStatusColumnModes=function(projectId,params){var hash,ns;return ns=projectId+":"+hashSuffixStatusColumnModes,hash=generateHash([projectId,ns]),$storage.set(hash,params)},service.getStatusColumnModes=function(projectId){var hash,ns;return ns=projectId+":"+hashSuffixStatusColumnModes,hash=generateHash([projectId,ns]),$storage.get(hash)||{}},function(instance){return instance.kanban=service}},module=angular.module("taigaResources"),module.factory("$tgKanbanResourcesProvider",["$tgStorage",resourceProvider])}.call(this),function(){var module,resourceProvider,sizeFormat,taiga;taiga=this.taiga,sizeFormat=this.taiga.sizeFormat,resourceProvider=function($repo){var service;return service={list:function(){return $repo.queryMany("locales")}},function(instance){return instance.locales=service}},module=angular.module("taigaResources"),module.factory("$tgLocalesResourcesProvider",["$tgRepo",resourceProvider])}.call(this),function(){var module,resourceProvider,taiga;taiga=this.taiga,resourceProvider=function($repo,$urls,$http){var service;return service={},service.render=function(projectId,content){var params,url;return(null==content||""===content)&&(content=" "),params={project_id:projectId,content:content},url=$urls.resolve("wiki"),$http.post(url+"/render",params).then(function(_this){return function(data){return data.data}}(this))},function(instance){return instance.mdrender=service}},module=angular.module("taigaResources"),module.factory("$tgMdRenderResourcesProvider",["$tgRepo","$tgUrls","$tgHttp",resourceProvider])}.call(this),function(){var module,resourceProvider,taiga;taiga=this.taiga,resourceProvider=function($repo,$http,$urls){var service;return service={},service.get=function(id){return $repo.queryOne("memberships",id)},service.list=function(projectId,filters,enablePagination){var options,params;return null==enablePagination&&(enablePagination=!0),params={project:projectId},params=_.extend({},params,filters||{}),enablePagination?$repo.queryPaginated("memberships",params):$repo.queryMany("memberships",params,options={enablePagination:enablePagination})},service.listByUser=function(userId,filters){var params;return params={user:userId},params=_.extend({},params,filters||{}),$repo.queryPaginated("memberships",params)},service.resendInvitation=function(id){var url;return url=$urls.resolve("memberships"),$http.post(url+"/"+id+"/resend_invitation",{})},service.bulkCreateMemberships=function(projectId,data,invitation_extra_text){var params,url;return url=$urls.resolve("bulk-create-memberships"),params={project_id:projectId,bulk_memberships:data,invitation_extra_text:invitation_extra_text},$http.post(url,params)},function(instance){return instance.memberships=service}},module=angular.module("taigaResources"),module.factory("$tgMembershipsResourcesProvider",["$tgRepo","$tgHttp","$tgUrls",resourceProvider])}.call(this),function(){var module,resourceProvider;resourceProvider=function($repo){var service;return service={},service.list=function(projectId,module){return $repo.queryOneAttribute("project-modules",projectId,module)},function(instance){return instance.modules=service}},module=angular.module("taigaResources"),module.factory("$tgModulesResourcesProvider",["$tgRepo",resourceProvider])}.call(this),function(){var module,resourceProvider,taiga;taiga=this.taiga,resourceProvider=function($repo,$http,$urls){var service;return service={},service.get=function(id){return $repo.queryOne("notify-policies",id)},service.list=function(filters){var params;return params=_.extend({},params,filters||{}),$repo.queryMany("notify-policies",params)},function(instance){return instance.notifyPolicies=service}},module=angular.module("taigaResources"),module.factory("$tgNotifyPoliciesResourcesProvider",["$tgRepo","$tgHttp","$tgUrls",resourceProvider])}.call(this),function(){var module,resourceProvider,sizeFormat,taiga;taiga=this.taiga,sizeFormat=this.taiga.sizeFormat,resourceProvider=function($config,$repo,$http,$urls,$auth,$q,$translate){var service;return service={},service.get=function(projectId){return $repo.queryOne("projects",projectId)},service.getBySlug=function(projectSlug){return $repo.queryOne("projects","by_slug?slug="+projectSlug)},service.list=function(){return $repo.queryMany("projects")},service.listByMember=function(memberId){var params;return params={member:memberId,order_by:"memberships__user_order"},$repo.queryMany("projects",params)},service.templates=function(){return $repo.queryMany("project-templates")},service.usersList=function(projectId){var params;return params={project:projectId},$repo.queryMany("users",params)},service.rolesList=function(projectId){var params;return params={project:projectId},$repo.queryMany("roles",params)},service.stats=function(projectId){return $repo.queryOneRaw("projects",projectId+"/stats")},service.bulkUpdateOrder=function(bulkData){var url;return url=$urls.resolve("bulk-update-projects-order"),$http.post(url,bulkData)},service.regenerate_userstories_csv_uuid=function(projectId){var url;return url=$urls.resolve("projects")+"/"+projectId+"/regenerate_userstories_csv_uuid",$http.post(url)},service.regenerate_issues_csv_uuid=function(projectId){var url;return url=$urls.resolve("projects")+"/"+projectId+"/regenerate_issues_csv_uuid",$http.post(url)},service.regenerate_tasks_csv_uuid=function(projectId){var url;return url=$urls.resolve("projects")+"/"+projectId+"/regenerate_tasks_csv_uuid",$http.post(url)},service.leave=function(projectId){var url;return url=$urls.resolve("projects")+"/"+projectId+"/leave",$http.post(url)},service.memberStats=function(projectId){return $repo.queryOneRaw("projects",projectId+"/member_stats")},service.tagsColors=function(projectId){return $repo.queryOne("projects",projectId+"/tags_colors")},service["export"]=function(projectId){var url;return url=$urls.resolve("exporter")+"/"+projectId,$http.get(url)},service["import"]=function(file,statusUpdater){var complete,data,defered,errorMsg,failed,maxFileSize,response,uploadComplete,uploadFailed,uploadProgress,xhr;return defered=$q.defer(),maxFileSize=$config.get("maxUploadFileSize",null),maxFileSize&&file.size>maxFileSize?(errorMsg=$translate.instant("PROJECT.IMPORT.ERROR_MAX_SIZE_EXCEEDED",{fileName:file.name,fileSize:sizeFormat(file.size),maxFileSize:sizeFormat(maxFileSize)}),response={status:413,data:{_error_message:errorMsg}},defered.reject(response),defered.promise):(uploadProgress=function(_this){return function(evt){var message,percent;return percent=Math.round(evt.loaded/evt.total*100),message=$translate.instant("PROJECT.IMPORT.UPLOAD_IN_PROGRESS_MESSAGE",{uploadedSize:sizeFormat(evt.loaded),totalSize:sizeFormat(evt.total)}),statusUpdater("in-progress",null,message,percent)}}(this),uploadComplete=function(_this){return function(evt){return statusUpdater("done",$translate.instant("PROJECT.IMPORT.TITLE"),$translate.instant("PROJECT.IMPORT.DESCRIPTION"))}}(this),uploadFailed=function(_this){return function(evt){return statusUpdater("error")}}(this),complete=function(_this){return function(evt){var ref;response={};try{response.data=JSON.parse(evt.target.responseText)}catch(error){response.data={}}return response.status=evt.target.status,(201===(ref=response.status)||202===ref)&&defered.resolve(response),defered.reject(response)}}(this),failed=function(_this){return function(evt){return defered.reject("fail")}}(this),data=new FormData,data.append("dump",file),xhr=new XMLHttpRequest,xhr.upload.addEventListener("progress",uploadProgress,!1),xhr.upload.addEventListener("load",uploadComplete,!1),xhr.upload.addEventListener("error",uploadFailed,!1),xhr.upload.addEventListener("abort",uploadFailed,!1),xhr.addEventListener("load",complete,!1),xhr.addEventListener("error",failed,!1),xhr.open("POST",$urls.resolve("importer")),xhr.setRequestHeader("Authorization","Bearer "+$auth.getToken()),xhr.setRequestHeader("Accept","application/json"),xhr.send(data),defered.promise)},function(instance){return instance.projects=service}},module=angular.module("taigaResources"),module.factory("$tgProjectsResourcesProvider",["$tgConfig","$tgRepo","$tgHttp","$tgUrls","$tgAuth","$q","$translate",resourceProvider])}.call(this),function(){var module,resourceProvider,taiga;taiga=this.taiga,resourceProvider=function($repo,$http,$urls){var service;return service={},service.get=function(id){return $repo.queryOne("roles",id)},service.list=function(projectId){return $repo.queryMany("roles",{project:projectId})},function(instance){return instance.roles=service}},module=angular.module("taigaResources"),module.factory("$tgRolesResourcesProvider",["$tgRepo","$tgHttp","$tgUrls",resourceProvider])}.call(this),function(){var module,resourceProvider,taiga;taiga=this.taiga,resourceProvider=function($repo,$urls,$http,$q){var service;return service={},service["do"]=function(projectId,term){var deferredAbort,params,request,url;return deferredAbort=$q.defer(),url=$urls.resolve("search"),params={url:url,method:"GET",timeout:deferredAbort.promise,cancelable:!0,params:{project:projectId,text:term,get_all:!1}},request=$http.request(params).then(function(data){return data.data}),request.abort=function(){return deferredAbort.resolve()},request["finally"]=function(){return request.abort=angular.noop,deferredAbort=request=null},request},function(instance){return instance.search=service}},module=angular.module("taigaResources"),module.factory("$tgSearchResourcesProvider",["$tgRepo","$tgUrls","$tgHttp","$q",resourceProvider])}.call(this),function(){var generateHash,module,resourceProvider,taiga;taiga=this.taiga,generateHash=taiga.generateHash,resourceProvider=function($repo,$model,$storage){var service;return service={},service.get=function(projectId,sprintId){return $repo.queryOne("milestones",sprintId).then(function(sprint){var uses;return uses=sprint.user_stories,uses=_.map(uses,function(u){return $model.make_model("userstories",u)}),sprint._attrs.user_stories=uses,sprint})},service.stats=function(projectId,sprintId){return $repo.queryOneRaw("milestones",sprintId+"/stats")},service.list=function(projectId,filters){var params;return params={project:projectId},params=_.extend({},params,filters||{}),$repo.queryMany("milestones",params,{},!0).then(function(_this){return function(result){var headers,i,len,m,milestones,uses;for(milestones=result[0],headers=result[1],i=0,len=milestones.length;len>i;i++)m=milestones[i],uses=m.user_stories,uses=_.map(uses,function(u){return $model.make_model("userstories",u)}),m._attrs.user_stories=uses;return{milestones:milestones,closed:parseInt(headers("Taiga-Info-Total-Closed-Milestones"),10),open:parseInt(headers("Taiga-Info-Total-Opened-Milestones"),10)}}}(this))},function(instance){return instance.sprints=service}},module=angular.module("taigaResources"),module.factory("$tgSprintsResourcesProvider",["$tgRepo","$tgModel","$tgStorage",resourceProvider])}.call(this),function(){var generateHash,module,resourceProvider,taiga;taiga=this.taiga,generateHash=taiga.generateHash,resourceProvider=function($repo,$http,$urls,$storage){var hashSuffix,hashSuffixStatusColumnModes,hashSuffixUsRowModes,service;return service={},hashSuffix="tasks-queryparams",hashSuffixStatusColumnModes="tasks-statuscolumnmodels",hashSuffixUsRowModes="tasks-usrowmodels",service.get=function(projectId,taskId){var params;return params=service.getQueryParams(projectId),params.project=projectId,$repo.queryOne("tasks",taskId,params)},service.getByRef=function(projectId,ref){var params;return params=service.getQueryParams(projectId),params.project=projectId,params.ref=ref,$repo.queryOne("tasks","by_ref",params)},service.listInAllProjects=function(filters){return $repo.queryMany("tasks",filters)},service.list=function(projectId,sprintId,userStoryId){var params;return null==sprintId&&(sprintId=null),null==userStoryId&&(userStoryId=null),params={project:projectId},sprintId&&(params.milestone=sprintId),userStoryId&&(params.user_story=userStoryId),service.storeQueryParams(projectId,params),$repo.queryMany("tasks",params)},service.bulkCreate=function(projectId,sprintId,usId,data){var params,url;return url=$urls.resolve("bulk-create-tasks"),params={project_id:projectId,sprint_id:sprintId,us_id:usId,bulk_tasks:data},$http.post(url,params).then(function(result){return result.data})},service.upvote=function(taskId){var url;return url=$urls.resolve("task-upvote",taskId),$http.post(url)},service.downvote=function(taskId){var url;return url=$urls.resolve("task-downvote",taskId),$http.post(url)},service.watch=function(taskId){var url;return url=$urls.resolve("task-watch",taskId),$http.post(url)},service.unwatch=function(taskId){var url;return url=$urls.resolve("task-unwatch",taskId),$http.post(url)},service.bulkUpdateTaskTaskboardOrder=function(projectId,data){var params,url;return url=$urls.resolve("bulk-update-task-taskboard-order"),params={project_id:projectId,bulk_tasks:data},$http.post(url,params)},service.listValues=function(projectId,type){var params;return params={project:projectId},$repo.queryMany(type,params)},service.storeQueryParams=function(projectId,params){var hash,ns;return ns=projectId+":"+hashSuffix,hash=generateHash([projectId,ns]),$storage.set(hash,params)},service.getQueryParams=function(projectId){var hash,ns;return ns=projectId+":"+hashSuffix,hash=generateHash([projectId,ns]),$storage.get(hash)||{}},service.storeStatusColumnModes=function(projectId,params){var hash,ns;return ns=projectId+":"+hashSuffixStatusColumnModes,hash=generateHash([projectId,ns]),$storage.set(hash,params)},service.getStatusColumnModes=function(projectId){var hash,ns;return ns=projectId+":"+hashSuffixStatusColumnModes,hash=generateHash([projectId,ns]),$storage.get(hash)||{}},service.storeUsRowModes=function(projectId,sprintId,params){var hash,ns;return ns=projectId+":"+hashSuffixUsRowModes,hash=generateHash([projectId,sprintId,ns]),$storage.set(hash,params)},service.getUsRowModes=function(projectId,sprintId){var hash,ns;return ns=projectId+":"+hashSuffixUsRowModes,hash=generateHash([projectId,sprintId,ns]),$storage.get(hash)||{}},function(instance){return instance.tasks=service}},module=angular.module("taigaResources"),module.factory("$tgTasksResourcesProvider",["$tgRepo","$tgHttp","$tgUrls","$tgStorage",resourceProvider])}.call(this),function(){var module,resourceProvider,sizeFormat,taiga;taiga=this.taiga,sizeFormat=this.taiga.sizeFormat,resourceProvider=function($config,$repo,$http,$urls,$q){var service;return service={},service.changeAvatar=function(file){var data,defered,maxFileSize,options,response,url;return maxFileSize=$config.get("maxUploadFileSize",null),maxFileSize&&file.size>maxFileSize?(response={status:413,data:{_error_message:"'"+file.name+"' ("+sizeFormat(file.size)+") is too heavy for our oompa loompas, try it with a smaller than ("+sizeFormat(maxFileSize)+")"}},defered=$q.defer(),defered.reject(response),defered.promise):(data=new FormData,data.append("avatar",file),options={transformRequest:angular.identity,headers:{"Content-Type":void 0}},url=$urls.resolve("users")+"/change_avatar",$http.post(url,data,{},options))},service.removeAvatar=function(){var url;return url=$urls.resolve("users")+"/remove_avatar",$http.post(url)},service.changePassword=function(currentPassword,newPassword){var data,url;return url=$urls.resolve("users")+"/change_password",data={current_password:currentPassword,password:newPassword},$http.post(url,data)},function(instance){return instance.userSettings=service}},module=angular.module("taigaResources"),module.factory("$tgUserSettingsResourcesProvider",["$tgConfig","$tgRepo","$tgHttp","$tgUrls","$q",resourceProvider])}.call(this),function(){var module,resourceProvider,sizeFormat,taiga;taiga=this.taiga,sizeFormat=this.taiga.sizeFormat,resourceProvider=function($http,$urls){var service;return service={},service.contacts=function(userId,options){var httpOptions,url;return null==options&&(options={}),url=$urls.resolve("user-contacts",userId),httpOptions={headers:{}},options.enablePagination||(httpOptions.headers["x-disable-pagination"]="1"),$http.get(url,{},httpOptions).then(function(result){return result.data})},function(instance){return instance.users=service}},module=angular.module("taigaResources"),module.factory("$tgUsersResourcesProvider",["$tgHttp","$tgUrls","$q",resourceProvider])}.call(this),function(){var generateHash,module,resourceProvider,taiga;taiga=this.taiga,generateHash=taiga.generateHash,resourceProvider=function($repo,$http,$urls,$storage){var hashSuffix,service;return service={},hashSuffix="userstories-queryparams",service.get=function(projectId,usId){var params;return params=service.getQueryParams(projectId),params.project=projectId,$repo.queryOne("userstories",usId,params)},service.getByRef=function(projectId,ref){var params;return params=service.getQueryParams(projectId),params.project=projectId,params.ref=ref,$repo.queryOne("userstories","by_ref",params)},service.listInAllProjects=function(filters){return $repo.queryMany("userstories",filters)},service.filtersData=function(params){return $repo.queryOneRaw("userstories-filters",null,params)},service.listUnassigned=function(projectId,filters){var params;return params={project:projectId,milestone:"null"},params=_.extend({},params,filters||{}),service.storeQueryParams(projectId,params),$repo.queryMany("userstories",params)},service.listAll=function(projectId,filters){var params;return params={project:projectId},params=_.extend({},params,filters||{}),service.storeQueryParams(projectId,params),$repo.queryMany("userstories",params)},service.bulkCreate=function(projectId,status,bulk){var data,url;return data={project_id:projectId,status_id:status,bulk_stories:bulk},url=$urls.resolve("bulk-create-us"),$http.post(url,data)},service.upvote=function(userStoryId){var url;return url=$urls.resolve("userstory-upvote",userStoryId),$http.post(url)},service.downvote=function(userStoryId){var url;return url=$urls.resolve("userstory-downvote",userStoryId),$http.post(url)},service.watch=function(userStoryId){var url;return url=$urls.resolve("userstory-watch",userStoryId),$http.post(url)},service.unwatch=function(userStoryId){var url;return url=$urls.resolve("userstory-unwatch",userStoryId),$http.post(url)},service.bulkUpdateBacklogOrder=function(projectId,data){var params,url;return url=$urls.resolve("bulk-update-us-backlog-order"),params={project_id:projectId,bulk_stories:data},$http.post(url,params)},service.bulkUpdateSprintOrder=function(projectId,data){var params,url;return url=$urls.resolve("bulk-update-us-sprint-order"),params={project_id:projectId,bulk_stories:data},$http.post(url,params)},service.bulkUpdateKanbanOrder=function(projectId,data){var params,url;return url=$urls.resolve("bulk-update-us-kanban-order"),params={project_id:projectId,bulk_stories:data},$http.post(url,params)},service.listValues=function(projectId,type){var params;return params={project:projectId},service.storeQueryParams(projectId,params),$repo.queryMany(type,params)},service.storeQueryParams=function(projectId,params){var hash,ns;return ns=projectId+":"+hashSuffix,hash=generateHash([projectId,ns]),$storage.set(hash,params)},service.getQueryParams=function(projectId){var hash,ns;return ns=projectId+":"+hashSuffix,hash=generateHash([projectId,ns]),$storage.get(hash)||{}},service.storeShowTags=function(projectId,showTags){var hash;return hash=generateHash([projectId,"showTags"]),$storage.set(hash,showTags)},service.getShowTags=function(projectId){var hash;return hash=generateHash([projectId,"showTags"]),$storage.get(hash)||null},function(instance){return instance.userstories=service}},module=angular.module("taigaResources"),module.factory("$tgUserstoriesResourcesProvider",["$tgRepo","$tgHttp","$tgUrls","$tgStorage",resourceProvider])}.call(this),function(){var module,resourceProvider;resourceProvider=function($repo,$urls,$http){var service;return service={},service.list=function(webhookId){var params;return params={webhook:webhookId},$repo.queryMany("webhooklogs",params)},service.resend=function(webhooklogId){var url;return url=$urls.resolve("webhooklogs-resend",webhooklogId),$http.post(url)},function(instance){return instance.webhooklogs=service}},module=angular.module("taigaResources"),module.factory("$tgWebhookLogsResourcesProvider",["$tgRepo","$tgUrls","$tgHttp",resourceProvider])}.call(this),function(){var module,resourceProvider;resourceProvider=function($repo,$urls,$http){var service;return service={},service.list=function(projectId){var params;return params={project:projectId},$repo.queryMany("webhooks",params)},service.test=function(webhookId){var url;return url=$urls.resolve("webhooks-test",webhookId),$http.post(url)},function(instance){return instance.webhooks=service}},module=angular.module("taigaResources"),module.factory("$tgWebhooksResourcesProvider",["$tgRepo","$tgUrls","$tgHttp",resourceProvider])}.call(this),function(){var module,resourceProvider,taiga;taiga=this.taiga,resourceProvider=function($repo,$http,$urls){var service;return service={},service.get=function(wikiId){return $repo.queryOne("wiki",wikiId)},service.getBySlug=function(projectId,slug){return $repo.queryOne("wiki","by_slug?project="+projectId+"&slug="+slug)},service.listLinks=function(projectId){return $repo.queryMany("wiki-links",{project:projectId})},function(instance){return instance.wiki=service}},module=angular.module("taigaResources"),module.factory("$tgWikiResourcesProvider",["$tgRepo","$tgHttp","$tgUrls",resourceProvider])}.call(this),function(){var UserChangePasswordController,UserChangePasswordDirective,debounce,mixOf,module,taiga,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,mixOf=this.taiga.mixOf,debounce=this.taiga.debounce,module=angular.module("taigaUserSettings"),UserChangePasswordController=function(superClass){function UserChangePasswordController(scope,rootscope,repo,confirm,rs,params,q,location,navUrls,auth,translate){this.scope=scope,this.rootscope=rootscope,this.repo=repo,this.confirm=confirm,this.rs=rs,this.params=params,this.q=q,this.location=location,this.navUrls=navUrls,this.auth=auth,this.translate=translate,this.scope.sectionName=this.translate.instant("CHANGE_PASSWORD.SECTION_NAME"),this.scope.user=this.auth.getUser()}return extend(UserChangePasswordController,superClass),UserChangePasswordController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","$tgNavUrls","$tgAuth","$translate"],UserChangePasswordController}(mixOf(taiga.Controller,taiga.PageMixin)),module.controller("UserChangePasswordController",UserChangePasswordController),UserChangePasswordDirective=function($rs,$confirm,$loading,$translate){var link;return link=function($scope,$el,$attrs,ctrl){var submit,submitButton;return submit=debounce(2e3,function(_this){return function(event){var currentLoading,promise;return event.preventDefault(),$scope.newPassword1!==$scope.newPassword2?void $confirm.notify("error",$translate.instant("CHANGE_PASSWORD.ERROR_PASSWORD_MATCH")):(currentLoading=$loading().target(submitButton).start(),promise=$rs.userSettings.changePassword($scope.currentPassword,$scope.newPassword1),promise.then(function(){return currentLoading.finish(),$confirm.notify("success")}),promise.then(null,function(response){return currentLoading.finish(),$confirm.notify("error",response.data._error_message)}))}}(this)),submitButton=$el.find(".submit-button"),$el.on("submit","form",submit),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgUserChangePassword",["$tgResources","$tgConfirm","$tgLoading","$translate",UserChangePasswordDirective])}.call(this),function(){var DeleteUserDirective,bindOnce,debounce,module,taiga;taiga=this.taiga,bindOnce=this.taiga.bindOnce,debounce=this.taiga.debounce,module=angular.module("taigaUserSettings"),DeleteUserDirective=function($repo,$rootscope,$auth,$location,$navUrls,lightboxService){var link;return link=function($scope,$el,$attrs){var submit;return $scope.$on("deletelightbox:new",function(ctx,user){return lightboxService.open($el)}),$scope.$on("$destroy",function(){return $el.off()}),submit=function(){var promise;return promise=$repo.remove($scope.user),promise.then(function(data){return lightboxService.close($el),$auth.logout(),$location.path($navUrls.resolve("login"))}),promise.then(null,function(){return console.log("FAIL")})},$el.on("click",".button-red",function(event){return event.preventDefault(),lightboxService.close($el)}),$el.on("click",".button-green",debounce(2e3,function(event){return event.preventDefault(),submit()}))},{link:link,templateUrl:"user/lightbox/lightbox-delete-account.html"}},module.directive("tgLbDeleteUser",["$tgRepo","$rootScope","$tgAuth","$tgLocation","$tgNavUrls","lightboxService",DeleteUserDirective])}.call(this),function(){var TaigaAvatarModelDirective,UserAvatarDirective,UserProfileDirective,UserSettingsController,debounce,mixOf,module,sizeFormat,taiga,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,mixOf=this.taiga.mixOf,sizeFormat=this.taiga.sizeFormat,module=angular.module("taigaUserSettings"),debounce=this.taiga.debounce,UserSettingsController=function(superClass){function UserSettingsController(scope,rootscope,config,repo,confirm,rs,params,q,location,navUrls,auth,translate){var maxFileSize,promise,text;this.scope=scope,this.rootscope=rootscope,this.config=config,this.repo=repo,this.confirm=confirm,this.rs=rs,this.params=params,this.q=q,this.location=location,this.navUrls=navUrls,this.auth=auth,this.translate=translate,this.scope.sectionName="USER_SETTINGS.MENU.SECTION_TITLE",this.scope.project={},this.scope.user=this.auth.getUser(),this.scope.user||(this.location.path(this.navUrls.resolve("permission-denied")),this.location.replace()),this.scope.lang=this.getLan(),this.scope.theme=this.getTheme(),maxFileSize=this.config.get("maxUploadFileSize",null),maxFileSize&&(text=this.translate.instant("USER_SETTINGS.AVATAR_MAX_SIZE",{maxFileSize:sizeFormat(maxFileSize)}),this.scope.maxFileSizeMsg=text),promise=this.loadInitialData(),promise.then(null,this.onInitialDataError.bind(this))}return extend(UserSettingsController,superClass),UserSettingsController.$inject=["$scope","$rootScope","$tgConfig","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","$tgNavUrls","$tgAuth","$translate"],UserSettingsController.prototype.loadInitialData=function(){return this.scope.availableThemes=this.config.get("themes",[]),this.rs.locales.list().then(function(_this){return function(locales){return _this.scope.locales=locales,locales}}(this))},UserSettingsController.prototype.openDeleteLightbox=function(){return this.rootscope.$broadcast("deletelightbox:new",this.scope.user)},UserSettingsController.prototype.getLan=function(){return this.scope.user.lang||this.translate.preferredLanguage()},UserSettingsController.prototype.getTheme=function(){return this.scope.user.theme||this.config.get("defaultTheme")||"taiga"},UserSettingsController}(mixOf(taiga.Controller,taiga.PageMixin)),module.controller("UserSettingsController",UserSettingsController),UserProfileDirective=function($confirm,$auth,$repo,$translate){var link;return link=function($scope,$el,$attrs){ -var submit;return submit=debounce(2e3,function(_this){return function(event){var changeEmail,form,onError,onSuccess;return event.preventDefault(),form=$el.find("form").checksley(),form.validate()?(changeEmail=$scope.user.isAttributeModified("email"),$scope.user.lang=$scope.lang,$scope.user.theme=$scope.theme,onSuccess=function(data){var text;return $auth.setUser(data),changeEmail?(text=$translate.instant("USER_PROFILE.CHANGE_EMAIL_SUCCESS"),$confirm.success(text)):$confirm.notify("success")},onError=function(data){return form.setErrors(data),$confirm.notify("error",data._error_message)},$repo.save($scope.user).then(onSuccess,onError)):void 0}}(this)),$el.on("submit","form",submit),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgUserProfile",["$tgConfirm","$tgAuth","$tgRepo","$translate",UserProfileDirective]),UserAvatarDirective=function($auth,$model,$rs,$confirm){var link;return link=function($scope,$el,$attrs){var onError,onSuccess,showSizeInfo;return showSizeInfo=function(){return $el.find(".size-info").removeClass("hidden")},onSuccess=function(response){var user;return user=$model.make_model("users",response.data),$auth.setUser(user),$scope.user=user,$el.find(".overlay").addClass("hidden"),$confirm.notify("success")},onError=function(response){return 413===response.status&&showSizeInfo(),$el.find(".overlay").addClass("hidden"),$confirm.notify("error",response.data._error_message)},$el.on("click",".js-change-avatar",function(){return $el.find("#avatar-field").click()}),$el.on("change","#avatar-field",function(event){return $scope.avatarAttachment?($el.find(".overlay").removeClass("hidden"),$rs.userSettings.changeAvatar($scope.avatarAttachment).then(onSuccess,onError)):void 0}),$el.on("click","a.use-gravatar",function(event){return $el.find(".overlay").removeClass("hidden"),$rs.userSettings.removeAvatar().then(onSuccess,onError)}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgUserAvatar",["$tgAuth","$tgModel","$tgResources","$tgConfirm",UserAvatarDirective]),TaigaAvatarModelDirective=function($parse){var link;return link=function($scope,$el,$attrs){var model,modelSetter;return model=$parse($attrs.tgAvatarModel),modelSetter=model.assign,$el.bind("change",function(){return $scope.$apply(function(){return modelSetter($scope,$el[0].files[0])})})},{link:link}},module.directive("tgAvatarModel",["$parse",TaigaAvatarModelDirective])}.call(this),function(){var UserSettingsNavigationDirective,module;UserSettingsNavigationDirective=function(){var link;return link=function($scope,$el,$attrs){var section;return section=$attrs.tgUserSettingsNavigation,$el.find(".active").removeClass("active"),$el.find("#usersettingsmenu-"+section+" a").addClass("active"),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module=angular.module("taigaUserSettings"),module.directive("tgUserSettingsNavigation",UserSettingsNavigationDirective)}.call(this),function(){var UserNotificationsController,UserNotificationsDirective,UserNotificationsListDirective,bindOnce,mixOf,module,taiga,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,mixOf=this.taiga.mixOf,bindOnce=this.taiga.bindOnce,module=angular.module("taigaUserSettings"),UserNotificationsController=function(superClass){function UserNotificationsController(scope,rootscope,repo,confirm,rs,params,q,location,navUrls,auth){var promise;this.scope=scope,this.rootscope=rootscope,this.repo=repo,this.confirm=confirm,this.rs=rs,this.params=params,this.q=q,this.location=location,this.navUrls=navUrls,this.auth=auth,this.scope.sectionName="USER_SETTINGS.NOTIFICATIONS.SECTION_NAME",this.scope.user=this.auth.getUser(),promise=this.loadInitialData(),promise.then(null,this.onInitialDataError.bind(this))}return extend(UserNotificationsController,superClass),UserNotificationsController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","$tgNavUrls","$tgAuth"],UserNotificationsController.prototype.loadInitialData=function(){return this.rs.notifyPolicies.list().then(function(_this){return function(notifyPolicies){return _this.scope.notifyPolicies=notifyPolicies,notifyPolicies}}(this))},UserNotificationsController}(mixOf(taiga.Controller,taiga.PageMixin)),module.controller("UserNotificationsController",UserNotificationsController),UserNotificationsDirective=function(){var link;return link=function($scope,$el,$attrs){return $scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgUserNotifications",UserNotificationsDirective),UserNotificationsListDirective=function($repo,$confirm,$compile){var link,template;return template=_.template('<% _.each(notifyPolicies, function (notifyPolicy, index) { %>\n
\n
<%- notifyPolicy.project_name %>
\n
\n
\n checked="checked"<% } %>/>\n \n
\n
\n
\n
\n checked="checked"<% } %> />\n \n
\n
\n
\n
\n checked="checked"<% } %> />\n \n
\n
\n
\n<% }) %>'),link=function($scope,$el,$attrs){var render;return render=function(){var ctx,html;return $el.off(),ctx={notifyPolicies:$scope.notifyPolicies},html=template(ctx),$el.html($compile(html)($scope)),$el.on("change","input[type=radio]",function(event){var onError,onSuccess,policy,policyIndex,prev_level,target;return target=angular.element(event.currentTarget),policyIndex=target.parents(".policy-table-row").data("index"),policy=$scope.notifyPolicies[policyIndex],prev_level=policy.notify_level,policy.notify_level=parseInt(target.val(),10),onSuccess=function(){return $confirm.notify("success")},onError=function(){return $confirm.notify("error"),target.parents(".policy-table-row").find("input[value="+prev_level+"]").prop("checked",!0)},$repo.save(policy).then(onSuccess,onError)})},$scope.$on("$destroy",function(){return $el.off()}),bindOnce($scope,$attrs.ngModel,render)},{link:link}},module.directive("tgUserNotificationsList",["$tgRepo","$tgConfirm","$compile",UserNotificationsListDirective])}.call(this),function(){angular.module("taigaComponents",[])}.call(this),function(){var module;module=angular.module("taigaExternalApps",[])}.call(this),function(){var module;module=angular.module("taigaHome",[])}.call(this),function(){angular.module("taigaNavigationBar",[])}.call(this),function(){var module;module=angular.module("taigaProfile",[])}.call(this),function(){angular.module("taigaProjects",[])}.call(this),function(){angular.module("taigaResources2",[])}.call(this),function(){angular.module("taigaUserTimeline",[])}.call(this),function(){var JoyRideDirective,taiga;taiga=this.taiga,JoyRideDirective=function($rootScope,currentUserService,joyRideService,$location,$translate){var link;return link=function(scope,el,attrs,ctrl){var initJoyrRide,intro,unsuscribe;return unsuscribe=null,intro=introJs(),intro.oncomplete(function(){return $("html,body").scrollTop(0)}),intro.onexit(function(){return currentUserService.disableJoyRide()}),initJoyrRide=function(next,config){return config[next.joyride]?(intro.setOptions({exitOnEsc:!1,exitOnOverlayClick:!1,showStepNumbers:!1,nextLabel:$translate.instant("JOYRIDE.NAV.NEXT")+" →",prevLabel:"← "+$translate.instant("JOYRIDE.NAV.BACK"),skipLabel:$translate.instant("JOYRIDE.NAV.SKIP"),doneLabel:$translate.instant("JOYRIDE.NAV.DONE"),disableInteraction:!0}),intro.setOption("steps",joyRideService.get(next.joyride)),intro.start()):void 0},$rootScope.$on("$routeChangeSuccess",function(event,next){return next.joyride&¤tUserService.isAuthenticated()?(intro.oncomplete(function(){return currentUserService.disableJoyRide(next.joyride)}),next.loader?unsuscribe=$rootScope.$on("loader:end",function(){return currentUserService.loadJoyRideConfig().then(function(config){return initJoyrRide(next,config)}),unsuscribe()}):currentUserService.loadJoyRideConfig().then(function(config){return initJoyrRide(next,config)})):(intro.exit(),void(unsuscribe&&unsuscribe()))})},{scope:{},link:link}},JoyRideDirective.$inject=["$rootScope","tgCurrentUserService","tgJoyRideService","$location","$translate"],angular.module("taigaComponents").directive("tgJoyRide",JoyRideDirective)}.call(this),function(){var JoyRideService,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;JoyRideService=function(superClass){function JoyRideService(translate,checkPermissionsService){this.translate=translate,this.checkPermissionsService=checkPermissionsService}return extend(JoyRideService,superClass),JoyRideService.$inject=["$translate","tgCheckPermissionsService"],JoyRideService.prototype.getConfig=function(){return{dashboard:function(_this){return function(){var steps;return steps=[{element:".project-list > section:not(.ng-hide)",position:"left",joyride:{title:_this.translate.instant("JOYRIDE.DASHBOARD.STEP1.TITLE"),text:_this.translate.instant("JOYRIDE.DASHBOARD.STEP1.TEXT")}},{element:".working-on-container",position:"right",joyride:{title:_this.translate.instant("JOYRIDE.DASHBOARD.STEP2.TITLE"),text:_this.translate.instant("JOYRIDE.DASHBOARD.STEP2.TEXT")}},{element:".watching-container",position:"right",joyride:{title:_this.translate.instant("JOYRIDE.DASHBOARD.STEP3.TITLE"),text:[_this.translate.instant("JOYRIDE.DASHBOARD.STEP3.TEXT1"),_this.translate.instant("JOYRIDE.DASHBOARD.STEP3.TEXT2")]}}],$(".project-list .create-project-button").is(":hidden")||steps.push({element:".project-list .create-project-button",position:"bottom",joyride:{title:_this.translate.instant("JOYRIDE.DASHBOARD.STEP4.TITLE"),text:[_this.translate.instant("JOYRIDE.DASHBOARD.STEP4.TEXT1"),_this.translate.instant("JOYRIDE.DASHBOARD.STEP4.TEXT2")]}}),steps}}(this),backlog:function(_this){return function(){var steps;return steps=[{element:".summary",position:"bottom",joyride:{title:_this.translate.instant("JOYRIDE.BACKLOG.STEP1.TITLE"),text:[_this.translate.instant("JOYRIDE.BACKLOG.STEP1.TEXT1"),_this.translate.instant("JOYRIDE.BACKLOG.STEP1.TEXT2")]}},{element:".backlog-table-empty",position:"bottom",joyride:{title:_this.translate.instant("JOYRIDE.BACKLOG.STEP2.TITLE"),text:_this.translate.instant("JOYRIDE.BACKLOG.STEP2.TEXT")}},{element:".sprints",position:"left",joyride:{title:_this.translate.instant("JOYRIDE.BACKLOG.STEP3.TITLE"),text:_this.translate.instant("JOYRIDE.BACKLOG.STEP3.TEXT")}}],_this.checkPermissionsService.check("add_us")&&steps.push({element:".new-us",position:"rigth",joyride:{title:_this.translate.instant("JOYRIDE.BACKLOG.STEP4.TITLE"),text:_this.translate.instant("JOYRIDE.BACKLOG.STEP4.TEXT")}}),steps}}(this),kanban:function(_this){return function(){var steps;return steps=[{element:".kanban-table-inner",position:"bottom",joyride:{title:_this.translate.instant("JOYRIDE.KANBAN.STEP1.TITLE"),text:_this.translate.instant("JOYRIDE.KANBAN.STEP1.TEXT")}},{element:".card-placeholder",position:"right",joyride:{title:_this.translate.instant("JOYRIDE.KANBAN.STEP2.TITLE"),text:_this.translate.instant("JOYRIDE.KANBAN.STEP2.TEXT")}}],_this.checkPermissionsService.check("add_us")&&steps.push({element:".icon-plus",position:"bottom",joyride:{title:_this.translate.instant("JOYRIDE.KANBAN.STEP3.TITLE"),text:[_this.translate.instant("JOYRIDE.KANBAN.STEP3.TEXT1"),_this.translate.instant("JOYRIDE.KANBAN.STEP3.TEXT2")]}}),steps}}(this)}},JoyRideService.prototype.get=function(name){var joyRide,joyRides;return joyRides=this.getConfig(),joyRide=joyRides[name].call(this),_.map(joyRide,function(item){var html;return html="",item.joyride.title&&(html+="

"+item.joyride.title+"

"),_.isArray(item.joyride.text)?_.forEach(item.joyride.text,function(text){return html+="

"+text+"

"}):html+="

"+item.joyride.text+"

",item.intro=html,item})},JoyRideService}(taiga.Service),angular.module("taigaComponents").service("tgJoyRideService",JoyRideService)}.call(this),function(){var LiveAnnouncementDirective;LiveAnnouncementDirective=function(liveAnnouncementService){var link;return link=function(scope,el,attrs){},{restrict:"AE",scope:{},controllerAs:"vm",controller:function(){return this.close=function(){return liveAnnouncementService.open=!1},Object.defineProperties(this,{open:{get:function(){return liveAnnouncementService.open}},title:{get:function(){return liveAnnouncementService.title}},desc:{get:function(){return liveAnnouncementService.desc}}})},link:link,templateUrl:"components/live-announcement/live-announcement.html"}},LiveAnnouncementDirective.$inject=["tgLiveAnnouncementService"],angular.module("taigaComponents").directive("tgLiveAnnouncement",LiveAnnouncementDirective)}.call(this),function(){var LiveAnnouncementService,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;LiveAnnouncementService=function(superClass){function LiveAnnouncementService(){this.open=!1,this.title="",this.desc=""}return extend(LiveAnnouncementService,superClass),LiveAnnouncementService.prototype.show=function(title,desc){return this.open=!0,this.title=title,this.desc=desc},LiveAnnouncementService}(taiga.Service),angular.module("taigaComponents").service("tgLiveAnnouncementService",LiveAnnouncementService)}.call(this),function(){var ProjectMenuController;ProjectMenuController=function(){function ProjectMenuController(projectService,lightboxFactory){this.projectService=projectService,this.lightboxFactory=lightboxFactory,this.project=null,this.menu=Immutable.Map()}return ProjectMenuController.$inject=["tgProjectService","tgLightboxFactory"],ProjectMenuController.prototype.show=function(){return this.project=this.projectService.project,this.active=this._getActiveSection(),this._setVideoConference(),this._setMenuPermissions()},ProjectMenuController.prototype.hide=function(){return this.project=null,this.menu={}},ProjectMenuController.prototype.search=function(){return this.lightboxFactory.create("tg-search-box",{"class":"lightbox lightbox-search"})},ProjectMenuController.prototype._setVideoConference=function(){var videoconferenceUrl;return videoconferenceUrl=this._videoConferenceUrl(),videoconferenceUrl?this.project=this.project.set("videoconferenceUrl",videoconferenceUrl):void 0},ProjectMenuController.prototype._setMenuPermissions=function(){return this.menu=Immutable.Map({backlog:!1,kanban:!1,issues:!1,wiki:!1}),this.project.get("is_backlog_activated")&&-1!==this.project.get("my_permissions").indexOf("view_us")&&(this.menu=this.menu.set("backlog",!0)),this.project.get("is_kanban_activated")&&-1!==this.project.get("my_permissions").indexOf("view_us")&&(this.menu=this.menu.set("kanban",!0)),this.project.get("is_issues_activated")&&-1!==this.project.get("my_permissions").indexOf("view_issues")&&(this.menu=this.menu.set("issues",!0)),this.project.get("is_wiki_activated")&&-1!==this.project.get("my_permissions").indexOf("view_wiki_pages")?this.menu=this.menu.set("wiki",!0):void 0},ProjectMenuController.prototype._getActiveSection=function(){var indexBacklog,indexKanban,oldSectionName,sectionName,sectionsBreadcrumb;return sectionName=this.projectService.section,sectionsBreadcrumb=this.projectService.sectionsBreadcrumb,indexBacklog=sectionsBreadcrumb.lastIndexOf("backlog"),indexKanban=sectionsBreadcrumb.lastIndexOf("kanban"),(-1!==indexBacklog||-1!==indexKanban)&&(oldSectionName=-1===indexKanban||indexKanban>indexBacklog?"backlog":"kanban"),"backlog-kanban"===sectionName&&("backlog"===oldSectionName||"kanban"===oldSectionName?sectionName=oldSectionName:this.project.get("is_backlog_activated")&&!this.project.get("is_kanban_activated")?sectionName="backlog":!this.project.get("is_backlog_activated")&&this.project.get("is_kanban_activated")&&(sectionName="kanban")),sectionName},ProjectMenuController.prototype._videoConferenceUrl=function(){var baseUrl,url;if("appear-in"===this.project.get("videoconferences"))baseUrl="https://appear.in/";else{if("talky"!==this.project.get("videoconferences"))return"jitsi"===this.project.get("videoconferences")?(baseUrl="https://meet.jit.si/",url=this.project.get("slug")+"-"+taiga.slugify(this.project.get("videoconferences_extra_data")),url=url.replace(/-/g,""),baseUrl+url):"custom"===this.project.get("videoconferences")?this.project.get("videoconferences_extra_data"):"";baseUrl="https://talky.io/"}return url=this.project.get("videoconferences_extra_data")?this.project.get("slug")+"-"+this.project.get("videoconferences_extra_data"):this.project.get("slug"),baseUrl+url},ProjectMenuController}(),angular.module("taigaComponents").controller("ProjectMenu",ProjectMenuController)}.call(this),function(){var ProjectMenuDirective,taiga;taiga=this.taiga,ProjectMenuDirective=function(projectService,lightboxFactory){var link;return link=function(scope,el,attrs,ctrl){var projectChange;return projectChange=function(){return projectService.project?ctrl.show():ctrl.hide()},scope.$watch(function(){return projectService.project},projectChange)},{scope:{},controller:"ProjectMenu",controllerAs:"vm",templateUrl:"components/project-menu/project-menu.html",link:link}},ProjectMenuDirective.$inject=["tgProjectService","tgLightboxFactory"],angular.module("taigaComponents").directive("tgProjectMenu",ProjectMenuDirective)}.call(this),function(){var TermsOfServiceAndPrivacyPolicyNoticeDirective;TermsOfServiceAndPrivacyPolicyNoticeDirective=function($config){var link;return link=function(scope,el,attrs){return scope.privacyPolicyUrl=$config.get("privacyPolicyUrl"),scope.termsOfServiceUrl=$config.get("termsOfServiceUrl")},{restrict:"AE",scope:{},link:link,templateUrl:"components/terms-of-service-and-privacy-policy-notice/terms-of-service-and-privacy-policy-notice.html"}},angular.module("taigaComponents").directive("tgTermsOfServiceAndPrivacyPolicyNotice",["$tgConfig",TermsOfServiceAndPrivacyPolicyNoticeDirective])}.call(this),function(){var VoteButtonController;VoteButtonController=function(){function VoteButtonController(currentUserService){this.currentUserService=currentUserService,this.user=this.currentUserService.getUser(),this.isMouseOver=!1,this.loading=!1}return VoteButtonController.$inject=["tgCurrentUserService"],VoteButtonController.prototype.showTextWhenMouseIsOver=function(){return this.isMouseOver=!0},VoteButtonController.prototype.showTextWhenMouseIsLeave=function(){return this.isMouseOver=!1},VoteButtonController.prototype.toggleVote=function(){var promise;return this.loading=!0,promise=this.item.is_voter?this._downvote():this._upvote(),promise["finally"](function(_this){return function(){return _this.loading=!1}}(this)),promise},VoteButtonController.prototype._upvote=function(){return this.onUpvote().then(function(_this){return function(){return _this.showTextWhenMouseIsLeave()}}(this))},VoteButtonController.prototype._downvote=function(){return this.onDownvote()},VoteButtonController}(),angular.module("taigaComponents").controller("VoteButton",VoteButtonController)}.call(this),function(){var VoteButtonDirective;VoteButtonDirective=function(){return{scope:{},controller:"VoteButton",bindToController:{item:"=",onUpvote:"=",onDownvote:"="},controllerAs:"vm",templateUrl:"components/vote-button/vote-button.html"}},angular.module("taigaComponents").directive("tgVoteButton",VoteButtonDirective)}.call(this),function(){var WatchButtonController;WatchButtonController=function(){function WatchButtonController(currentUserService){this.currentUserService=currentUserService,this.user=this.currentUserService.getUser(),this.isMouseOver=!1,this.loading=!1}return WatchButtonController.$inject=["tgCurrentUserService"],WatchButtonController.prototype.showTextWhenMouseIsOver=function(){return this.isMouseOver=!0},WatchButtonController.prototype.showTextWhenMouseIsLeave=function(){return this.isMouseOver=!1},WatchButtonController.prototype.toggleWatch=function(){var promise;return this.loading=!0,promise=this.item.is_watcher?this._unwatch():this._watch(),promise["finally"](function(_this){return function(){return _this.loading=!1}}(this)),promise},WatchButtonController.prototype._watch=function(){return this.onWatch().then(function(_this){return function(){return _this.showTextWhenMouseIsLeave()}}(this))},WatchButtonController.prototype._unwatch=function(){return this.onUnwatch()},WatchButtonController}(),angular.module("taigaComponents").controller("WatchButton",WatchButtonController)}.call(this),function(){var WatchButtonDirective;WatchButtonDirective=function(){return{scope:{},controller:"WatchButton",bindToController:{item:"=",onWatch:"=",onUnwatch:"="},controllerAs:"vm",templateUrl:"components/watch-button/watch-button.html"}},angular.module("taigaComponents").directive("tgWatchButton",WatchButtonDirective)}.call(this),function(){var ExternalAppController,taiga,bind=function(fn,me){return function(){return fn.apply(me,arguments)}},extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,ExternalAppController=function(superClass){function ExternalAppController(routeParams,externalAppsService,window,currentUserService,location,navUrls,xhrError,loader){var loginUrl,nextUrl;this.routeParams=routeParams,this.externalAppsService=externalAppsService,this.window=window,this.currentUserService=currentUserService,this.location=location,this.navUrls=navUrls,this.xhrError=xhrError,this.loader=loader,this.createApplicationToken=bind(this.createApplicationToken,this),this._getApplicationToken=bind(this._getApplicationToken,this),this._redirect=bind(this._redirect,this),this.loader.start(!1),this._applicationId=this.routeParams.application,this._state=this.routeParams.state,this._getApplicationToken(),this._user=this.currentUserService.getUser(),this._application=null,nextUrl=encodeURIComponent(this.location.url()),loginUrl=this.navUrls.resolve("login"),this.loginWithAnotherUserUrl=loginUrl+"?next="+nextUrl,taiga.defineImmutableProperty(this,"user",function(_this){return function(){return _this._user}}(this)),taiga.defineImmutableProperty(this,"application",function(_this){return function(){return _this._application}}(this))}return extend(ExternalAppController,superClass),ExternalAppController.$inject=["$routeParams","tgExternalAppsService","$window","tgCurrentUserService","$location","$tgNavUrls","tgXhrErrorService","tgLoader"],ExternalAppController.prototype._redirect=function(applicationToken){var nextUrl;return nextUrl=applicationToken.get("next_url"),this.window.open(nextUrl,"_self")},ExternalAppController.prototype._getApplicationToken=function(){return this.externalAppsService.getApplicationToken(this._applicationId,this._state).then(function(_this){return function(data){return _this._application=data.get("application"),data.get("auth_code")?_this._redirect(data):_this.loader.pageLoaded()}}(this))["catch"](function(_this){return function(xhr){return _this.loader.pageLoaded(),_this.xhrError.response(xhr)}}(this))},ExternalAppController.prototype.cancel=function(){return this.window.history.back()},ExternalAppController.prototype.createApplicationToken=function(){return this.externalAppsService.authorizeApplicationToken(this._applicationId,this._state).then(function(_this){return function(data){return _this._redirect(data)}}(this))["catch"](function(_this){return function(xhr){return _this.xhrError.response(xhr)}}(this))},ExternalAppController}(taiga.Controller),angular.module("taigaExternalApps").controller("ExternalApp",ExternalAppController)}.call(this),function(){var ExternalAppsService,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;ExternalAppsService=function(superClass){function ExternalAppsService(rs){this.rs=rs}return extend(ExternalAppsService,superClass),ExternalAppsService.$inject=["tgResources"],ExternalAppsService.prototype.getApplicationToken=function(applicationId,state){return this.rs.externalapps.getApplicationToken(applicationId,state)},ExternalAppsService.prototype.authorizeApplicationToken=function(applicationId,state){return this.rs.externalapps.authorizeApplicationToken(applicationId,state)},ExternalAppsService}(taiga.Service),angular.module("taigaExternalApps").service("tgExternalAppsService",ExternalAppsService)}.call(this),function(){var FeedbackService,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;FeedbackService=function(superClass){function FeedbackService(lightboxFactory){this.lightboxFactory=lightboxFactory}return extend(FeedbackService,superClass),FeedbackService.$inject=["tgLightboxFactory"],FeedbackService.prototype.sendFeedback=function(){return this.lightboxFactory.create("tg-lb-feedback",{"class":"lightbox lightbox-feedback lightbox-generic-form"})},FeedbackService}(taiga.Service),angular.module("taigaFeedback").service("tgFeedbackService",FeedbackService)}.call(this),function(){var DutyDirective;DutyDirective=function(navurls,$translate){var link;return link=function(scope,el,attrs,ctrl){return scope.vm={},scope.vm.duty=scope.duty,scope.vm.getDutyType=function(){if(scope.vm.duty){if("userstories"===scope.vm.duty.get("_name"))return $translate.instant("COMMON.USER_STORY");if("tasks"===scope.vm.duty.get("_name"))return $translate.instant("COMMON.TASK");if("issues"===scope.vm.duty.get("_name"))return $translate.instant("COMMON.ISSUE")}}},{templateUrl:"home/duties/duty.html",scope:{duty:"=tgDuty"},link:link}},DutyDirective.$inject=["$tgNavUrls","$translate"],angular.module("taigaHome").directive("tgDuty",DutyDirective)}.call(this),function(){var HomeService,groupBy,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;groupBy=this.taiga.groupBy,HomeService=function(superClass){function HomeService(navurls,rs,projectsService){this.navurls=navurls,this.rs=rs,this.projectsService=projectsService}return extend(HomeService,superClass),HomeService.$inject=["$tgNavUrls","tgResources","tgProjectsService"],HomeService.prototype._attachProjectInfoToWorkInProgress=function(workInProgress,projectsById){var _attachProjectInfoToDuty,_duties,assignedTo,watching;return _attachProjectInfoToDuty=function(_this){return function(duty,objType){var ctx,project,url;return project=projectsById.get(String(duty.get("project"))),ctx={project:project.get("slug"),ref:duty.get("ref")},url=_this.navurls.resolve("project-"+objType+"-detail",ctx),duty=duty.set("url",url),duty=duty.set("projectName",project.get("name")),duty=duty.set("_name",objType)}}(this),assignedTo=workInProgress.get("assignedTo"),assignedTo.get("userStories")&&(_duties=assignedTo.get("userStories").map(function(duty){return _attachProjectInfoToDuty(duty,"userstories")}),assignedTo=assignedTo.set("userStories",_duties)),assignedTo.get("tasks")&&(_duties=assignedTo.get("tasks").map(function(duty){return _attachProjectInfoToDuty(duty,"tasks")}),assignedTo=assignedTo.set("tasks",_duties)),assignedTo.get("issues")&&(_duties=assignedTo.get("issues").map(function(duty){return _attachProjectInfoToDuty(duty,"issues")}),assignedTo=assignedTo.set("issues",_duties)),watching=workInProgress.get("watching"),watching.get("userStories")&&(_duties=watching.get("userStories").map(function(duty){return _attachProjectInfoToDuty(duty,"userstories")}),watching=watching.set("userStories",_duties)),watching.get("tasks")&&(_duties=watching.get("tasks").map(function(duty){return _attachProjectInfoToDuty(duty,"tasks")}),watching=watching.set("tasks",_duties)),watching.get("issues")&&(_duties=watching.get("issues").map(function(duty){return _attachProjectInfoToDuty(duty,"issues")}),watching=watching.set("issues",_duties)),workInProgress=workInProgress.set("assignedTo",assignedTo),workInProgress=workInProgress.set("watching",watching)},HomeService.prototype.getWorkInProgress=function(userId){var assignedIssuesPromise,assignedTasksPromise,assignedTo,assignedUserStoriesPromise,params,params_us,projectsById,projectsPromise,watching,watchingIssuesPromise,watchingTasksPromise,watchingUserStoriesPromise,workInProgress;return projectsById=Immutable.Map(),projectsPromise=this.projectsService.getProjectsByUserId(userId).then(function(projects){return projectsById=Immutable.fromJS(groupBy(projects.toJS(),function(p){return p.id}))}),assignedTo=Immutable.Map(),params={status__is_closed:!1,assigned_to:userId},params_us={is_closed:!1,assigned_to:userId},assignedUserStoriesPromise=this.rs.userstories.listInAllProjects(params_us).then(function(userstories){return assignedTo=assignedTo.set("userStories",userstories)}),assignedTasksPromise=this.rs.tasks.listInAllProjects(params).then(function(tasks){return assignedTo=assignedTo.set("tasks",tasks)}),assignedIssuesPromise=this.rs.issues.listInAllProjects(params).then(function(issues){return assignedTo=assignedTo.set("issues",issues)}),params={status__is_closed:!1,watchers:userId},params_us={is_closed:!1,watchers:userId},watching=Immutable.Map(),watchingUserStoriesPromise=this.rs.userstories.listInAllProjects(params_us).then(function(userstories){return watching=watching.set("userStories",userstories)}),watchingTasksPromise=this.rs.tasks.listInAllProjects(params).then(function(tasks){return watching=watching.set("tasks",tasks)}),watchingIssuesPromise=this.rs.issues.listInAllProjects(params).then(function(issues){return watching=watching.set("issues",issues)}),workInProgress=Immutable.Map(),Promise.all([projectsPromise,assignedUserStoriesPromise,assignedTasksPromise,assignedIssuesPromise,watchingUserStoriesPromise,watchingTasksPromise,watchingIssuesPromise]).then(function(_this){return function(){return workInProgress=workInProgress.set("assignedTo",assignedTo),workInProgress=workInProgress.set("watching",watching),workInProgress=_this._attachProjectInfoToWorkInProgress(workInProgress,projectsById); -}}(this))},HomeService}(taiga.Service),angular.module("taigaHome").service("tgHomeService",HomeService)}.call(this),function(){var HomeProjectListDirective;HomeProjectListDirective=function(currentUserService,projectsService){var directive,link;return link=function(scope,el,attrs,ctrl){return scope.vm={},taiga.defineImmutableProperty(scope.vm,"projects",function(){return currentUserService.projects.get("recents")}),scope.vm.newProject=function(){return projectsService.newProject()}},directive={templateUrl:"home/projects/home-project-list.html",scope:{},link:link}},HomeProjectListDirective.$inject=["tgCurrentUserService","tgProjectsService"],angular.module("taigaHome").directive("tgHomeProjectList",HomeProjectListDirective)}.call(this),function(){var WorkingOnController;WorkingOnController=function(){function WorkingOnController(homeService){this.homeService=homeService,this.assignedTo=Immutable.Map(),this.watching=Immutable.Map()}return WorkingOnController.$inject=["tgHomeService"],WorkingOnController.prototype._setAssignedTo=function(workInProgress){var issues,tasks,userStories;return userStories=workInProgress.get("assignedTo").get("userStories"),tasks=workInProgress.get("assignedTo").get("tasks"),issues=workInProgress.get("assignedTo").get("issues"),this.assignedTo=userStories.concat(tasks).concat(issues),this.assignedTo.size>0?this.assignedTo=this.assignedTo.sortBy(function(elem){return elem.get("modified_date")}).reverse():void 0},WorkingOnController.prototype._setWatching=function(workInProgress){var issues,tasks,userStories;return userStories=workInProgress.get("watching").get("userStories"),tasks=workInProgress.get("watching").get("tasks"),issues=workInProgress.get("watching").get("issues"),this.watching=userStories.concat(tasks).concat(issues),this.watching.size>0?this.watching=this.watching.sortBy(function(elem){return elem.get("modified_date")}).reverse():void 0},WorkingOnController.prototype.getWorkInProgress=function(userId){return this.homeService.getWorkInProgress(userId).then(function(_this){return function(workInProgress){return _this._setAssignedTo(workInProgress),_this._setWatching(workInProgress)}}(this))},WorkingOnController}(),angular.module("taigaHome").controller("WorkingOn",WorkingOnController)}.call(this),function(){var WorkingOnDirective;WorkingOnDirective=function(homeService,currentUserService){var link;return link=function(scope,el,attrs,ctrl){var user,userId;return user=currentUserService.getUser(),user?(userId=user.get("id"),ctrl.getWorkInProgress(userId)):void 0},{controller:"WorkingOn",controllerAs:"vm",templateUrl:"home/working-on/working-on.html",scope:{},link:link}},WorkingOnDirective.$inject=["tgHomeService","tgCurrentUserService"],angular.module("taigaHome").directive("tgWorkingOn",WorkingOnDirective)}.call(this),function(){var DropdownProjectListDirective;DropdownProjectListDirective=function(currentUserService,projectsService){var directive,link;return link=function(scope,el,attrs,ctrl){return scope.vm={},taiga.defineImmutableProperty(scope.vm,"projects",function(){return currentUserService.projects.get("recents")}),scope.vm.newProject=function(){return projectsService.newProject()}},directive={templateUrl:"navigation-bar/dropdown-project-list/dropdown-project-list.html",scope:{},link:link}},DropdownProjectListDirective.$inject=["tgCurrentUserService","tgProjectsService"],angular.module("taigaNavigationBar").directive("tgDropdownProjectList",DropdownProjectListDirective)}.call(this),function(){var DropdownUserDirective;DropdownUserDirective=function(authService,configService,locationService,navUrlsService,feedbackService){var directive,link;return link=function(scope,el,attrs,ctrl){return scope.vm={},scope.vm.isFeedbackEnabled=configService.get("feedbackEnabled"),taiga.defineImmutableProperty(scope.vm,"user",function(){return authService.userData}),scope.vm.logout=function(){return authService.logout(),locationService.path(navUrlsService.resolve("login"))},scope.vm.sendFeedback=function(){return feedbackService.sendFeedback()}},directive={templateUrl:"navigation-bar/dropdown-user/dropdown-user.html",scope:{},link:link}},DropdownUserDirective.$inject=["$tgAuth","$tgConfig","$tgLocation","$tgNavUrls","tgFeedbackService"],angular.module("taigaNavigationBar").directive("tgDropdownUser",DropdownUserDirective)}.call(this),function(){var NavigationBarDirective;NavigationBarDirective=function(currentUserService,navigationBarService,$location){var directive,link;return link=function(scope,el,attrs,ctrl){return scope.vm={},scope.$on("$routeChangeSuccess",function(){return"/"===$location.path()?scope.vm.active=!0:scope.vm.active=!1}),taiga.defineImmutableProperty(scope.vm,"projects",function(){return currentUserService.projects.get("recents")}),taiga.defineImmutableProperty(scope.vm,"isAuthenticated",function(){return currentUserService.isAuthenticated()}),taiga.defineImmutableProperty(scope.vm,"isEnabledHeader",function(){return navigationBarService.isEnabledHeader()})},directive={templateUrl:"navigation-bar/navigation-bar.html",scope:{},link:link}},NavigationBarDirective.$inject=["tgCurrentUserService","tgNavigationBarService","$location"],angular.module("taigaNavigationBar").directive("tgNavigationBar",NavigationBarDirective)}.call(this),function(){var NavigationBarService,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;NavigationBarService=function(superClass){function NavigationBarService(){this.disableHeader()}return extend(NavigationBarService,superClass),NavigationBarService.prototype.enableHeader=function(){return this.enabledHeader=!0},NavigationBarService.prototype.disableHeader=function(){return this.enabledHeader=!1},NavigationBarService.prototype.isEnabledHeader=function(){return this.enabledHeader},NavigationBarService}(taiga.Service),angular.module("taigaNavigationBar").service("tgNavigationBarService",NavigationBarService)}.call(this),function(){var ProfileBarController;ProfileBarController=function(){function ProfileBarController(userService){this.userService=userService,this.loadStats()}return ProfileBarController.$inject=["tgUserService"],ProfileBarController.prototype.loadStats=function(){return this.userService.getStats(this.user.get("id")).then(function(_this){return function(stats){return _this.stats=stats}}(this))},ProfileBarController}(),angular.module("taigaProfile").controller("ProfileBar",ProfileBarController)}.call(this),function(){var ProfileBarDirective;ProfileBarDirective=function(){return{templateUrl:"profile/profile-bar/profile-bar.html",controller:"ProfileBar",controllerAs:"vm",scope:{user:"=user",isCurrentUser:"=iscurrentuser"},bindToController:!0}},angular.module("taigaProfile").directive("tgProfileBar",ProfileBarDirective)}.call(this),function(){var ProfileContactsController;ProfileContactsController=function(){function ProfileContactsController(userService,currentUserService){this.userService=userService,this.currentUserService=currentUserService,this.currentUser=this.currentUserService.getUser(),this.isCurrentUser=!1,this.currentUser&&this.currentUser.get("id")===this.user.get("id")&&(this.isCurrentUser=!0)}return ProfileContactsController.$inject=["tgUserService","tgCurrentUserService"],ProfileContactsController.prototype.loadContacts=function(){return this.userService.getContacts(this.user.get("id")).then(function(_this){return function(contacts){return _this.contacts=contacts}}(this))},ProfileContactsController}(),angular.module("taigaProfile").controller("ProfileContacts",ProfileContactsController)}.call(this),function(){var ProfileContactsDirective;ProfileContactsDirective=function(){var link;return link=function(scope,elm,attrs,ctrl){return ctrl.loadContacts()},{templateUrl:"profile/profile-contacts/profile-contacts.html",scope:{user:"="},controllerAs:"vm",controller:"ProfileContacts",link:link,bindToController:!0}},angular.module("taigaProfile").directive("tgProfileContacts",ProfileContactsDirective)}.call(this),function(){var FavItemDirective;FavItemDirective=function(){var link,templateUrl;return link=function(scope,el,attrs,ctrl){return scope.vm={item:scope.item}},templateUrl=function(el,attrs){return"project"===attrs.itemType?"profile/profile-favs/items/project.html":"profile/profile-favs/items/ticket.html"},{scope:{item:"=tgFavItem"},link:link,templateUrl:templateUrl}},angular.module("taigaProfile").directive("tgFavItem",FavItemDirective)}.call(this),function(){var FavsBaseController,ProfileLikedController,ProfileVotedController,ProfileWatchedController,debounceLeading,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;debounceLeading=this.taiga.debounceLeading,FavsBaseController=function(){function FavsBaseController(){this._init()}return FavsBaseController.prototype._init=function(){return this.enableFilterByAll=!0,this.enableFilterByProjects=!0,this.enableFilterByUserStories=!0,this.enableFilterByTasks=!0,this.enableFilterByIssues=!0,this.enableFilterByTextQuery=!0,this._resetList(),this.q=null,this.type=null},FavsBaseController.prototype._resetList=function(){return this.items=Immutable.List(),this.scrollDisabled=!1,this._page=1},FavsBaseController.prototype._enableLoadingSpinner=function(){return this.isLoading=!0},FavsBaseController.prototype._disableLoadingSpinner=function(){return this.isLoading=!1},FavsBaseController.prototype._enableScroll=function(){return this.scrollDisabled=!1},FavsBaseController.prototype._disableScroll=function(){return this.scrollDisabled=!0},FavsBaseController.prototype._checkIfHasMorePages=function(hasNext){return hasNext?(this._page+=1,this._enableScroll()):this._disableScroll()},FavsBaseController.prototype._checkIfHasNoResults=function(){return this.hasNoResults=0===this.items.size},FavsBaseController.prototype.loadItems=function(){return this._enableLoadingSpinner(),this._disableScroll(),this._getItems(this.user.get("id"),this._page,this.type,this.q).then(function(_this){return function(response){return _this.items=_this.items.concat(response.get("data")),_this._checkIfHasMorePages(response.get("next")),_this._checkIfHasNoResults(),_this._disableLoadingSpinner(),_this.items}}(this))["catch"](function(_this){return function(){return _this._disableLoadingSpinner(),_this.items}}(this))},FavsBaseController.prototype.filterByTextQuery=debounceLeading(500,function(){return this._resetList(),this.loadItems()}),FavsBaseController.prototype.showAll=function(){return null!==this.type?(this.type=null,this._resetList(),this.loadItems()):void 0},FavsBaseController.prototype.showProjectsOnly=function(){return"project"!==this.type?(this.type="project",this._resetList(),this.loadItems()):void 0},FavsBaseController.prototype.showUserStoriesOnly=function(){return"userstory"!==this.type?(this.type="userstory",this._resetList(),this.loadItems()):void 0},FavsBaseController.prototype.showTasksOnly=function(){return"task"!==this.type?(this.type="task",this._resetList(),this.loadItems()):void 0},FavsBaseController.prototype.showIssuesOnly=function(){return"issue"!==this.type?(this.type="issue",this._resetList(),this.loadItems()):void 0},FavsBaseController}(),ProfileLikedController=function(superClass){function ProfileLikedController(userService){this.userService=userService,ProfileLikedController.__super__.constructor.call(this),this.enableFilterByAll=!1,this.enableFilterByProjects=!1,this.enableFilterByUserStories=!1,this.enableFilterByTasks=!1,this.enableFilterByIssues=!1,this.enableFilterByTextQuery=!0,this._getItems=this.userService.getLiked}return extend(ProfileLikedController,superClass),ProfileLikedController.$inject=["tgUserService"],ProfileLikedController}(FavsBaseController),angular.module("taigaProfile").controller("ProfileLiked",ProfileLikedController),ProfileVotedController=function(superClass){function ProfileVotedController(userService){this.userService=userService,ProfileVotedController.__super__.constructor.call(this),this.enableFilterByAll=!0,this.enableFilterByProjects=!1,this.enableFilterByUserStories=!0,this.enableFilterByTasks=!0,this.enableFilterByIssues=!0,this.enableFilterByTextQuery=!0,this._getItems=this.userService.getVoted}return extend(ProfileVotedController,superClass),ProfileVotedController.$inject=["tgUserService"],ProfileVotedController}(FavsBaseController),angular.module("taigaProfile").controller("ProfileVoted",ProfileVotedController),ProfileWatchedController=function(superClass){function ProfileWatchedController(userService){this.userService=userService,ProfileWatchedController.__super__.constructor.call(this),this._getItems=this.userService.getWatched}return extend(ProfileWatchedController,superClass),ProfileWatchedController.$inject=["tgUserService"],ProfileWatchedController}(FavsBaseController),angular.module("taigaProfile").controller("ProfileWatched",ProfileWatchedController)}.call(this),function(){var ProfileLikedDirective,ProfileVotedDirective,ProfileWatchedDirective,base;base={scope:{},bindToController:{user:"=",type:"@",q:"@",scrollDisabled:"@",isLoading:"@",hasNoResults:"@"},controller:null,controllerAs:"vm",templateUrl:"profile/profile-favs/profile-favs.html"},ProfileLikedDirective=function(){return _.extend({},base,{controller:"ProfileLiked"})},angular.module("taigaProfile").directive("tgProfileLiked",ProfileLikedDirective),ProfileVotedDirective=function(){return _.extend({},base,{controller:"ProfileVoted"})},angular.module("taigaProfile").directive("tgProfileVoted",ProfileVotedDirective),ProfileWatchedDirective=function(){return _.extend({},base,{controller:"ProfileWatched"})},angular.module("taigaProfile").directive("tgProfileWatched",ProfileWatchedDirective)}.call(this),function(){var ProfileHints;ProfileHints=function(){function ProfileHints(translate){var hintKey;this.translate=translate,hintKey=Math.floor(Math.random()*this.HINTS.length)+1,this.hint=this.HINTS[hintKey-1],this.hint.linkText=this.hint.linkText||"HINTS.LINK",this.hint.title=this.translate.instant("HINTS.HINT"+hintKey+"_TITLE"),this.hint.text=this.translate.instant("HINTS.HINT"+hintKey+"_TEXT")}return ProfileHints.prototype.HINTS=[{url:"https://taiga.io/support/import-export-projects/"},{url:"https://taiga.io/support/custom-fields/"},{},{}],ProfileHints}(),ProfileHints.$inject=["$translate"],angular.module("taigaProfile").controller("ProfileHints",ProfileHints)}.call(this),function(){var ProfileHints;ProfileHints=function($translate){return{scope:{},controller:"ProfileHints",controllerAs:"vm",templateUrl:"profile/profile-hints/profile-hints.html"}},ProfileHints.$inject=["$translate"],angular.module("taigaProfile").directive("tgProfileHints",ProfileHints)}.call(this),function(){var ProfileProjectsController;ProfileProjectsController=function(){function ProfileProjectsController(projectsService,userService){this.projectsService=projectsService,this.userService=userService}return ProfileProjectsController.$inject=["tgProjectsService","tgUserService"],ProfileProjectsController.prototype.loadProjects=function(){return this.projectsService.getProjectsByUserId(this.user.get("id")).then(function(_this){return function(projects){return _this.userService.attachUserContactsToProjects(_this.user.get("id"),projects)}}(this)).then(function(_this){return function(projects){return _this.projects=projects}}(this))},ProfileProjectsController}(),angular.module("taigaProfile").controller("ProfileProjects",ProfileProjectsController)}.call(this),function(){var ProfileProjectsDirective;ProfileProjectsDirective=function(){var link;return link=function(scope,elm,attr,ctrl){return ctrl.loadProjects()},{templateUrl:"profile/profile-projects/profile-projects.html",scope:{user:"="},link:link,bindToController:!0,controllerAs:"vm",controller:"ProfileProjects"}},angular.module("taigaProfile").directive("tgProfileProjects",ProfileProjectsDirective)}.call(this),function(){var ProfileTabDirective;ProfileTabDirective=function(){var link;return link=function(scope,element,attrs,ctrl,transclude){return scope.tab={},attrs.$observe("tgProfileTab",function(name){return scope.tab.name=name}),attrs.$observe("tabTitle",function(title){return scope.tab.title=title}),scope.tab.icon=attrs.tabIcon,scope.tab.active=!!attrs.tabActive,scope.$eval(attrs.tabDisabled)!==!0?ctrl.addTab(scope.tab):void 0},{templateUrl:"profile/profile-tab/profile-tab.html",scope:{},require:"^tgProfileTabs",link:link,transclude:!0}},angular.module("taigaProfile").directive("tgProfileTab",ProfileTabDirective)}.call(this),function(){var ProfileTabsController;ProfileTabsController=function(){function ProfileTabsController(){this.tabs=[]}return ProfileTabsController.prototype.addTab=function(tab){return this.tabs.push(tab)},ProfileTabsController.prototype.toggleTab=function(tab){return _.map(this.tabs,function(tab){return tab.active=!1}),tab.active=!0},ProfileTabsController}(),angular.module("taigaProfile").controller("ProfileTabs",ProfileTabsController)}.call(this),function(){var ProfileTabsDirective;ProfileTabsDirective=function(){return{scope:{},controller:"ProfileTabs",controllerAs:"vm",templateUrl:"profile/profile-tabs/profile-tabs.html",transclude:!0}},angular.module("taigaProfile").directive("tgProfileTabs",ProfileTabsDirective)}.call(this),function(){var ProfileController;ProfileController=function(){function ProfileController(appMetaService,currentUserService,routeParams,userService,xhrError,translate){this.appMetaService=appMetaService,this.currentUserService=currentUserService,this.routeParams=routeParams,this.userService=userService,this.xhrError=xhrError,this.translate=translate,this.isCurrentUser=!1,this.routeParams.slug?this.userService.getUserByUserName(this.routeParams.slug).then(function(_this){return function(user){return user.get("is_active")?(_this.user=user,_this.isCurrentUser=!1,_this._setMeta(_this.user),user):_this.xhrError.notFound()}}(this))["catch"](function(_this){return function(xhr){return _this.xhrError.response(xhr)}}(this)):(this.user=this.currentUserService.getUser(),this.isCurrentUser=!0,this._setMeta(this.user))}return ProfileController.$inject=["tgAppMetaService","tgCurrentUserService","$routeParams","tgUserService","tgXhrErrorService","$translate"],ProfileController.prototype._setMeta=function(user){var ctx,description,title;return ctx={userFullName:user.get("full_name_display"),userUsername:user.get("username")},title=this.translate.instant("USER.PROFILE.PAGE_TITLE",ctx),description=user.get("bio"),this.appMetaService.setAll(title,description)},ProfileController}(),angular.module("taigaProfile").controller("Profile",ProfileController)}.call(this),function(){var LikeProjectButtonController;LikeProjectButtonController=function(){function LikeProjectButtonController(confirm,likeButtonService){this.confirm=confirm,this.likeButtonService=likeButtonService,this.isMouseOver=!1,this.loading=!1}return LikeProjectButtonController.$inject=["$tgConfirm","tgLikeProjectButtonService"],LikeProjectButtonController.prototype.showTextWhenMouseIsOver=function(){return this.isMouseOver=!0},LikeProjectButtonController.prototype.showTextWhenMouseIsLeave=function(){return this.isMouseOver=!1},LikeProjectButtonController.prototype.toggleLike=function(){var promise;return this.loading=!0,promise=this.project.get("is_fan")?this._unlike():this._like(),promise["finally"](function(_this){return function(){return _this.loading=!1}}(this)),promise},LikeProjectButtonController.prototype._like=function(){return this.likeButtonService.like(this.project.get("id")).then(function(_this){return function(){return _this.showTextWhenMouseIsLeave()}}(this))["catch"](function(_this){return function(){return _this.confirm.notify("error")}}(this))},LikeProjectButtonController.prototype._unlike=function(){return this.likeButtonService.unlike(this.project.get("id"))["catch"](function(_this){return function(){return _this.confirm.notify("error")}}(this))},LikeProjectButtonController}(),angular.module("taigaProjects").controller("LikeProjectButton",LikeProjectButtonController)}.call(this),function(){var LikeProjectButtonDirective;LikeProjectButtonDirective=function(){return{scope:{},controller:"LikeProjectButton",bindToController:{project:"="},controllerAs:"vm",templateUrl:"projects/components/like-project-button/like-project-button.html"}},angular.module("taigaProjects").directive("tgLikeProjectButton",LikeProjectButtonDirective)}.call(this),function(){var LikeProjectButtonService,taiga,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,LikeProjectButtonService=function(superClass){function LikeProjectButtonService(rs,currentUserService,projectService){this.rs=rs,this.currentUserService=currentUserService,this.projectService=projectService}return extend(LikeProjectButtonService,superClass),LikeProjectButtonService.$inject=["tgResources","tgCurrentUserService","tgProjectService"],LikeProjectButtonService.prototype._getProjectIndex=function(projectId){return this.currentUserService.projects.get("all").findIndex(function(project){return project.get("id")===projectId})},LikeProjectButtonService.prototype._updateProjects=function(projectId,isFan){var projectIndex,projects;return projectIndex=this._getProjectIndex(projectId),-1!==projectIndex?(projects=this.currentUserService.projects.get("all").update(projectIndex,function(project){var totalFans;return totalFans=project.get("total_fans"),isFan?totalFans++:totalFans--,project.merge({is_fan:isFan,total_fans:totalFans})}),this.currentUserService.setProjects(projects)):void 0},LikeProjectButtonService.prototype._updateCurrentProject=function(isFan){var project,totalFans;return totalFans=this.projectService.project.get("total_fans"),isFan?totalFans++:totalFans--,project=this.projectService.project.merge({is_fan:isFan,total_fans:totalFans}),this.projectService.setProject(project)},LikeProjectButtonService.prototype.like=function(projectId){return this.rs.projects.likeProject(projectId).then(function(_this){return function(){return _this._updateProjects(projectId,!0),_this._updateCurrentProject(!0)}}(this))},LikeProjectButtonService.prototype.unlike=function(projectId){return this.rs.projects.unlikeProject(projectId).then(function(_this){return function(){return _this._updateProjects(projectId,!1),_this._updateCurrentProject(!1)}}(this))},LikeProjectButtonService}(taiga.Service),angular.module("taigaProjects").service("tgLikeProjectButtonService",LikeProjectButtonService)}.call(this),function(){var SortProjectsDirective;SortProjectsDirective=function(currentUserService){var directive,link;return link=function(scope,el,attrs,ctrl){var itemEl;return itemEl=null,el.sortable({dropOnEmpty:!0,revert:200,axis:"y",opacity:.95,placeholder:"placeholder",cancel:".project-name"}),el.on("sortstop",function(event,ui){var i,index,len,project,sortData,sorted_project_ids,value;for(itemEl=ui.item,project=itemEl.scope().project,index=itemEl.index(),sorted_project_ids=_.map(scope.projects.toJS(),function(p){return p.id}),sorted_project_ids=_.without(sorted_project_ids,project.get("id")),sorted_project_ids.splice(index,0,project.get("id")),sortData=[],index=i=0,len=sorted_project_ids.length;len>i;index=++i)value=sorted_project_ids[index],sortData.push({project_id:value,order:index});return currentUserService.bulkUpdateProjectsOrder(sortData)})},directive={scope:{projects:"=tgSortProjects"},link:link}},angular.module("taigaProjects").directive("tgSortProjects",["tgCurrentUserService",SortProjectsDirective])}.call(this),function(){var WatchProjectButtonController;WatchProjectButtonController=function(){function WatchProjectButtonController(confirm,watchButtonService){this.confirm=confirm,this.watchButtonService=watchButtonService,this.showWatchOptions=!1,this.loading=!1}return WatchProjectButtonController.$inject=["$tgConfirm","tgWatchProjectButtonService"],WatchProjectButtonController.prototype.toggleWatcherOptions=function(){return this.showWatchOptions=!this.showWatchOptions},WatchProjectButtonController.prototype.closeWatcherOptions=function(){return this.showWatchOptions=!1},WatchProjectButtonController.prototype.watch=function(notifyLevel){return notifyLevel!==this.project.get("notify_level")?(this.loading=!0,this.closeWatcherOptions(),this.watchButtonService.watch(this.project.get("id"),notifyLevel)["catch"](function(_this){return function(){return _this.confirm.notify("error")}}(this))["finally"](function(_this){return function(){return _this.loading=!1}}(this))):void 0},WatchProjectButtonController.prototype.unwatch=function(){return this.loading=!0,this.closeWatcherOptions(),this.watchButtonService.unwatch(this.project.get("id"))["catch"](function(_this){return function(){return _this.confirm.notify("error")}}(this))["finally"](function(_this){return function(){return _this.loading=!1}}(this))},WatchProjectButtonController}(),angular.module("taigaProjects").controller("WatchProjectButton",WatchProjectButtonController)}.call(this),function(){var WatchProjectButtonDirective;WatchProjectButtonDirective=function(){return{scope:{},controller:"WatchProjectButton",bindToController:{project:"="},controllerAs:"vm",templateUrl:"projects/components/watch-project-button/watch-project-button.html"}},angular.module("taigaProjects").directive("tgWatchProjectButton",WatchProjectButtonDirective)}.call(this),function(){var WatchProjectButtonService,taiga,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,WatchProjectButtonService=function(superClass){function WatchProjectButtonService(rs,currentUserService,projectService){this.rs=rs,this.currentUserService=currentUserService,this.projectService=projectService}return extend(WatchProjectButtonService,superClass),WatchProjectButtonService.$inject=["tgResources","tgCurrentUserService","tgProjectService"],WatchProjectButtonService.prototype._getProjectIndex=function(projectId){return this.currentUserService.projects.get("all").findIndex(function(project){return project.get("id")===projectId})},WatchProjectButtonService.prototype._updateProjects=function(projectId,notifyLevel,isWatcher){var projectIndex,projects;return projectIndex=this._getProjectIndex(projectId),-1!==projectIndex?(projects=this.currentUserService.projects.get("all").update(projectIndex,function(_this){return function(project){var totalWatchers;return totalWatchers=project.get("total_watchers"),!_this.projectService.project.get("is_watcher")&&isWatcher?totalWatchers++:_this.projectService.project.get("is_watcher")&&!isWatcher&&totalWatchers--,project.merge({is_watcher:isWatcher,total_watchers:totalWatchers,notify_level:notifyLevel})}}(this)),this.currentUserService.setProjects(projects)):void 0},WatchProjectButtonService.prototype._updateCurrentProject=function(notifyLevel,isWatcher){var project,totalWatchers;return totalWatchers=this.projectService.project.get("total_watchers"),!this.projectService.project.get("is_watcher")&&isWatcher?totalWatchers++:this.projectService.project.get("is_watcher")&&!isWatcher&&totalWatchers--,project=this.projectService.project.merge({is_watcher:isWatcher,notify_level:notifyLevel,total_watchers:totalWatchers}),this.projectService.setProject(project)},WatchProjectButtonService.prototype.watch=function(projectId,notifyLevel){return this.rs.projects.watchProject(projectId,notifyLevel).then(function(_this){return function(){return _this._updateProjects(projectId,notifyLevel,!0),_this._updateCurrentProject(notifyLevel,!0)}}(this))},WatchProjectButtonService.prototype.unwatch=function(projectId){return this.rs.projects.unwatchProject(projectId).then(function(_this){return function(){return _this._updateProjects(projectId,null,!1),_this._updateCurrentProject(null,!1)}}(this))},WatchProjectButtonService}(taiga.Service),angular.module("taigaProjects").service("tgWatchProjectButtonService",WatchProjectButtonService)}.call(this),function(){var ProjectsListingController;ProjectsListingController=function(){function ProjectsListingController(currentUserService,projectsService){this.currentUserService=currentUserService,this.projectsService=projectsService,taiga.defineImmutableProperty(this,"projects",function(_this){return function(){return _this.currentUserService.projects.get("all")}}(this))}return ProjectsListingController.$inject=["tgCurrentUserService","tgProjectsService"],ProjectsListingController.prototype.newProject=function(){return this.projectsService.newProject()},ProjectsListingController}(),angular.module("taigaProjects").controller("ProjectsListing",ProjectsListingController)}.call(this),function(){var ProjectController;ProjectController=function(){function ProjectController(routeParams,appMetaService,auth,translate,projectService){var projectSlug;this.routeParams=routeParams,this.appMetaService=appMetaService,this.auth=auth,this.translate=translate,this.projectService=projectService,projectSlug=this.routeParams.pslug,this.user=this.auth.userData,taiga.defineImmutableProperty(this,"project",function(_this){return function(){return _this.projectService.project}}(this)),taiga.defineImmutableProperty(this,"members",function(_this){return function(){return _this.projectService.activeMembers}}(this)),this.appMetaService.setfn(this._setMeta.bind(this))}return ProjectController.$inject=["$routeParams","tgAppMetaService","$tgAuth","$translate","tgProjectService"],ProjectController.prototype._setMeta=function(project){var ctx,metas;return this.project?(metas={},ctx={projectName:this.project.get("name")},metas.title=this.translate.instant("PROJECT.PAGE_TITLE",ctx),metas.description=this.project.get("description"),metas):null},ProjectController}(),angular.module("taigaProjects").controller("Project",ProjectController)}.call(this),function(){var ProjectsService,groupBy,taiga,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,groupBy=this.taiga.groupBy,ProjectsService=function(superClass){function ProjectsService(rs,projectUrl,lightboxFactory){this.rs=rs,this.projectUrl=projectUrl,this.lightboxFactory=lightboxFactory}return extend(ProjectsService,superClass),ProjectsService.$inject=["tgResources","$projectUrl","tgLightboxFactory"],ProjectsService.prototype.getProjectBySlug=function(projectSlug){return this.rs.projects.getProjectBySlug(projectSlug).then(function(_this){return function(project){return _this._decorate(project)}}(this))},ProjectsService.prototype.getProjectStats=function(projectId){return this.rs.projects.getProjectStats(projectId)},ProjectsService.prototype.getProjectsByUserId=function(userId,paginate){return this.rs.projects.getProjectsByUserId(userId,paginate).then(function(_this){return function(projects){return projects.map(_this._decorate.bind(_this))}}(this))},ProjectsService.prototype._decorate=function(project){var colorized_tags,tags,url;return url=this.projectUrl.get(project.toJS()),project=project.set("url",url),colorized_tags=[],project.get("tags")&&(tags=project.get("tags").sort(),colorized_tags=tags.map(function(tag){var color;return color=project.get("tags_colors").get(tag),Immutable.fromJS({name:tag,color:color})}),project=project.set("colorized_tags",colorized_tags)), -project},ProjectsService.prototype.newProject=function(){return this.lightboxFactory.create("tg-lb-create-project",{"class":"wizard-create-project"})},ProjectsService.prototype.bulkUpdateProjectsOrder=function(sortData){return this.rs.projects.bulkUpdateOrder(sortData)},ProjectsService}(taiga.Service),angular.module("taigaProjects").service("tgProjectsService",ProjectsService)}.call(this),function(){var Resource,module;Resource=function(urlsService,http){var service;return service={},service.getApplicationToken=function(applicationId,state){var url;return url=urlsService.resolve("applications"),url=url+"/"+applicationId+"/token?state="+state,http.get(url).then(function(result){return Immutable.fromJS(result.data)})},service.authorizeApplicationToken=function(applicationId,state){var data,url;return url=urlsService.resolve("application-tokens"),url+="/authorize",data={state:state,application:applicationId},http.post(url,data).then(function(result){return Immutable.fromJS(result.data)})},function(){return{externalapps:service}}},Resource.$inject=["$tgUrls","$tgHttp"],module=angular.module("taigaResources2"),module.factory("tgExternalAppsResource",Resource)}.call(this),function(){var Resource,module;Resource=function(urlsService,http){var service;return service={},service.listInAllProjects=function(params){var httpOptions,url;return url=urlsService.resolve("issues"),httpOptions={headers:{"x-disable-pagination":"1"}},http.get(url,params,httpOptions).then(function(result){return Immutable.fromJS(result.data)})},function(){return{issues:service}}},Resource.$inject=["$tgUrls","$tgHttp"],module=angular.module("taigaResources2"),module.factory("tgIssuesResource",Resource)}.call(this),function(){var Resource,module,pagination;pagination=function(){},Resource=function(urlsService,http,paginateResponseService){var service;return service={},service.getProjectBySlug=function(projectSlug){var url;return url=urlsService.resolve("projects"),url=url+"/by_slug?slug="+projectSlug,http.get(url).then(function(result){return Immutable.fromJS(result.data)})},service.getProjectsByUserId=function(userId,paginate){var httpOptions,params,url;return null==paginate&&(paginate=!1),url=urlsService.resolve("projects"),httpOptions={},paginate||(httpOptions.headers={"x-disable-pagination":"1"}),params={member:userId,order_by:"memberships__user_order"},http.get(url,params,httpOptions).then(function(result){return Immutable.fromJS(result.data)})},service.getProjectStats=function(projectId){var url;return url=urlsService.resolve("projects"),url=url+"/"+projectId,http.get(url).then(function(result){return Immutable.fromJS(result.data)})},service.bulkUpdateOrder=function(bulkData){var url;return url=urlsService.resolve("bulk-update-projects-order"),http.post(url,bulkData)},service.getTimeline=function(projectId,page){var params,url;return params={page:page,only_relevant:!0},url=urlsService.resolve("timeline-project"),url=url+"/"+projectId,http.get(url,params,{headers:{"x-lazy-pagination":!0}}).then(function(result){return result=Immutable.fromJS(result),paginateResponseService(result)})},service.likeProject=function(projectId){var url;return url=urlsService.resolve("project-like",projectId),http.post(url)},service.unlikeProject=function(projectId){var url;return url=urlsService.resolve("project-unlike",projectId),http.post(url)},service.watchProject=function(projectId,notifyLevel){var data,url;return data={notify_level:notifyLevel},url=urlsService.resolve("project-watch",projectId),http.post(url,data)},service.unwatchProject=function(projectId){var url;return url=urlsService.resolve("project-unwatch",projectId),http.post(url)},function(){return{projects:service}}},Resource.$inject=["$tgUrls","$tgHttp","tgPaginateResponseService"],module=angular.module("taigaResources2"),module.factory("tgProjectsResources",Resource)}.call(this),function(){var Resources,services;services=["tgProjectsResources","tgUserResources","tgUsersResources","tgUserstoriesResource","tgTasksResource","tgIssuesResource","tgExternalAppsResource"],Resources=function($injector){var i,j,len,len1,ref,service,serviceFn,serviceName,serviceProperty;for(i=0,len=services.length;len>i;i++)for(serviceName=services[i],serviceFn=$injector.get(serviceName),service=$injector.invoke(serviceFn),ref=Object.keys(service),j=0,len1=ref.length;len1>j;j++)serviceProperty=ref[j],this[serviceProperty]&&console.warm("repeated resource "+serviceProperty),this[serviceProperty]=service[serviceProperty];return this},Resources.$inject=["$injector"],angular.module("taigaResources2").service("tgResources",Resources)}.call(this),function(){var Resource,module;Resource=function(urlsService,http){var service;return service={},service.listInAllProjects=function(params){var httpOptions,url;return url=urlsService.resolve("tasks"),httpOptions={headers:{"x-disable-pagination":"1"}},http.get(url,params,httpOptions).then(function(result){return Immutable.fromJS(result.data)})},function(){return{tasks:service}}},Resource.$inject=["$tgUrls","$tgHttp"],module=angular.module("taigaResources2"),module.factory("tgTasksResource",Resource)}.call(this),function(){var Resource,module;Resource=function(urlsService,http,paginateResponseService){var service;return service={},service.getUserStorage=function(key){var httpOptions,url;return url=urlsService.resolve("user-storage"),key&&(url+="/"+key),httpOptions={},http.get(url,{}).then(function(response){return response.data.value})},service.setUserStorage=function(key,value){var params,url;return url=urlsService.resolve("user-storage")+"/"+key,params={key:key,value:value},http.put(url,params)},service.createUserStorage=function(key,value){var params,url;return url=urlsService.resolve("user-storage"),params={key:key,value:value},http.post(url,params)},function(){return{user:service}}},Resource.$inject=["$tgUrls","$tgHttp"],module=angular.module("taigaResources2"),module.factory("tgUserResources",Resource)}.call(this),function(){var Resource,module;Resource=function(urlsService,http,paginateResponseService){var service;return service={},service.getUserByUsername=function(username){var httpOptions,params,url;return url=urlsService.resolve("by_username"),httpOptions={headers:{"x-disable-pagination":"1"}},params={username:username},http.get(url,params,httpOptions).then(function(result){return Immutable.fromJS(result.data)})},service.getStats=function(userId){var httpOptions,url;return url=urlsService.resolve("user-stats",userId),httpOptions={headers:{"x-disable-pagination":"1"}},http.get(url,{},httpOptions).then(function(result){return Immutable.fromJS(result.data)})},service.getContacts=function(userId){var httpOptions,url;return url=urlsService.resolve("user-contacts",userId),httpOptions={headers:{"x-disable-pagination":"1"}},http.get(url,{},httpOptions).then(function(result){return Immutable.fromJS(result.data)})},service.getLiked=function(userId,page,type,q){var params,url;return url=urlsService.resolve("user-liked",userId),params={},null!=page&&(params.page=page),null!=type&&(params.type=type),null!=q&&(params.q=q),params.only_relevant=!0,http.get(url,params,{headers:{"x-lazy-pagination":!0}}).then(function(result){return result=Immutable.fromJS(result),paginateResponseService(result)})},service.getVoted=function(userId,page,type,q){var params,url;return url=urlsService.resolve("user-voted",userId),params={},null!=page&&(params.page=page),null!=type&&(params.type=type),null!=q&&(params.q=q),http.get(url,params,{headers:{"x-lazy-pagination":!0}}).then(function(result){return result=Immutable.fromJS(result),paginateResponseService(result)})},service.getWatched=function(userId,page,type,q){var params,url;return url=urlsService.resolve("user-watched",userId),params={},null!=page&&(params.page=page),null!=type&&(params.type=type),null!=q&&(params.q=q),http.get(url,params,{headers:{"x-lazy-pagination":!0}}).then(function(result){return result=Immutable.fromJS(result),paginateResponseService(result)})},service.getProfileTimeline=function(userId,page){var params,url;return params={page:page},url=urlsService.resolve("timeline-profile"),url=url+"/"+userId,http.get(url,params,{headers:{"x-lazy-pagination":!0}}).then(function(result){return result=Immutable.fromJS(result),paginateResponseService(result)})},service.getUserTimeline=function(userId,page){var params,url;return params={page:page,only_relevant:!0},url=urlsService.resolve("timeline-user"),url=url+"/"+userId,http.get(url,params,{headers:{"x-lazy-pagination":!0}}).then(function(result){return result=Immutable.fromJS(result),paginateResponseService(result)})},function(){return{users:service}}},Resource.$inject=["$tgUrls","$tgHttp","tgPaginateResponseService"],module=angular.module("taigaResources2"),module.factory("tgUsersResources",Resource)}.call(this),function(){var Resource,module;Resource=function(urlsService,http){var service;return service={},service.listInAllProjects=function(params){var httpOptions,url;return url=urlsService.resolve("userstories"),httpOptions={headers:{"x-disable-pagination":"1"}},http.get(url,params,httpOptions).then(function(result){return Immutable.fromJS(result.data)})},function(){return{userstories:service}}},Resource.$inject=["$tgUrls","$tgHttp"],module=angular.module("taigaResources2"),module.factory("tgUserstoriesResource",Resource)}.call(this),function(){var AppMetaService,taiga,truncate;taiga=this.taiga,truncate=taiga.truncate,AppMetaService=function(){function AppMetaService(rootScope){this.rootScope=rootScope}return AppMetaService.$inject=["$rootScope"],AppMetaService.prototype._set=function(key,value){var meta;if(key)return"title"===key?(meta=$("title"),0===meta.length&&(meta=$(""),$("head").append(meta)),meta.text(value||"")):0===key.indexOf("og:")?(meta=$("meta[property='"+key+"']"),0===meta.length&&(meta=$(""),$("head").append(meta)),meta.attr("content",value||"")):(meta=$("meta[name='"+key+"']"),0===meta.length&&(meta=$(""),$("head").append(meta)),meta.attr("content",value||""))},AppMetaService.prototype.setTitle=function(title){return this._set("title",title)},AppMetaService.prototype.setDescription=function(description){return this._set("description",truncate(description,250))},AppMetaService.prototype.setTwitterMetas=function(title,description){return this._set("twitter:card","summary"),this._set("twitter:site","@taigaio"),this._set("twitter:title",title),this._set("twitter:description",truncate(description,300)),this._set("twitter:image",window.location.origin+"/"+window._version+"/images/logo-color.png")},AppMetaService.prototype.setOpenGraphMetas=function(title,description){return this._set("og:type","object"),this._set("og:site_name","Taiga - Love your projects"),this._set("og:title",title),this._set("og:description",truncate(description,300)),this._set("og:image",window.location.origin+"/"+window._version+"/images/logo-color.png"),this._set("og:url",window.location.href)},AppMetaService.prototype.setAll=function(title,description){return this.setTitle(title),this.setDescription(description),this.setTwitterMetas(title,description),this.setOpenGraphMetas(title,description)},AppMetaService.prototype.addMobileViewport=function(){return $("head").append('')},AppMetaService.prototype.removeMobileViewport=function(){return $('meta[name="viewport"]').remove()},AppMetaService.prototype.setfn=function(fn){return this.listener&&this._listener(),this._listener=this.rootScope.$watchCollection(fn,function(_this){return function(metas){return metas?(_this.setAll(metas.title,metas.description),_this._listener()):void 0}}(this))},AppMetaService}(),angular.module("taigaCommon").service("tgAppMetaService",AppMetaService)}.call(this),function(){var ChekcPermissionsService,taiga;taiga=this.taiga,ChekcPermissionsService=function(){function ChekcPermissionsService(projectService){this.projectService=projectService}return ChekcPermissionsService.$inject=["tgProjectService"],ChekcPermissionsService.prototype.check=function(permission){return-1!==this.projectService.project.get("my_permissions").indexOf(permission)},ChekcPermissionsService}(),angular.module("taigaCommon").service("tgCheckPermissionsService",ChekcPermissionsService)}.call(this),function(){var CurrentUserService,groupBy,taiga;taiga=this.taiga,groupBy=this.taiga.groupBy,CurrentUserService=function(){function CurrentUserService(projectsService,storageService,rs){this.projectsService=projectsService,this.storageService=storageService,this.rs=rs,this._user=null,this._projects=Immutable.Map(),this._projectsById=Immutable.Map(),this._joyride=null,taiga.defineImmutableProperty(this,"projects",function(_this){return function(){return _this._projects}}(this)),taiga.defineImmutableProperty(this,"projectsById",function(_this){return function(){return _this._projectsById}}(this))}return CurrentUserService.$inject=["tgProjectsService","$tgStorage","tgResources"],CurrentUserService.prototype.isAuthenticated=function(){return null!==this.getUser()?!0:!1},CurrentUserService.prototype.getUser=function(){var userData;return this._user||(userData=this.storageService.get("userInfo"),userData&&(userData=Immutable.fromJS(userData),this.setUser(userData))),this._user},CurrentUserService.prototype.removeUser=function(){return this._user=null,this._projects=Immutable.Map(),this._projectsById=Immutable.Map(),this._joyride=null},CurrentUserService.prototype.setUser=function(user){return this._user=user,this._loadUserInfo()},CurrentUserService.prototype.bulkUpdateProjectsOrder=function(sortData){return this.projectsService.bulkUpdateProjectsOrder(sortData).then(function(_this){return function(){return _this.loadProjects()}}(this))},CurrentUserService.prototype.loadProjects=function(){return this.projectsService.getProjectsByUserId(this._user.get("id")).then(function(_this){return function(projects){return _this.setProjects(projects)}}(this))},CurrentUserService.prototype.disableJoyRide=function(section){return section?this._joyride[section]=!1:this._joyride={backlog:!1,kanban:!1,dashboard:!1},this.rs.user.setUserStorage("joyride",this._joyride)},CurrentUserService.prototype.loadJoyRideConfig=function(){return new Promise(function(_this){return function(resolve){return null!==_this._joyride?void resolve(_this._joyride):_this.rs.user.getUserStorage("joyride").then(function(config){return _this._joyride=config,resolve(_this._joyride)})["catch"](function(){return _this._joyride={backlog:!0,kanban:!0,dashboard:!0},_this.rs.user.createUserStorage("joyride",_this._joyride),resolve(_this._joyride)})}}(this))},CurrentUserService.prototype._loadUserInfo=function(){return Promise.all([this.loadProjects()])},CurrentUserService.prototype.setProjects=function(projects){return this._projects=this._projects.set("all",projects),this._projects=this._projects.set("recents",projects.slice(0,10)),this._projectsById=Immutable.fromJS(groupBy(projects.toJS(),function(p){return p.id})),this.projects},CurrentUserService}(),angular.module("taigaCommon").service("tgCurrentUserService",CurrentUserService)}.call(this),function(){var LightboxFactory;LightboxFactory=function(){function LightboxFactory(rootScope,compile){this.rootScope=rootScope,this.compile=compile}return LightboxFactory.$inject=["$rootScope","$compile"],LightboxFactory.prototype.create=function(name,attrs){var elm,html,scope;scope=this.rootScope.$new(),elm=$("
").attr(name,!0).attr("tg-bind-scope",!0),attrs&&elm.attr(attrs),elm.addClass("remove-on-close"),html=this.compile(elm)(scope),$(document.body).append(html)},LightboxFactory}(),angular.module("taigaCommon").service("tgLightboxFactory",LightboxFactory)}.call(this),function(){var PaginateResponse;PaginateResponse=function(){return function(result){var paginateResponse;return paginateResponse=Immutable.Map({data:result.get("data"),next:!!result.get("headers")("x-pagination-next"),prev:!!result.get("headers")("x-pagination-prev"),current:result.get("headers")("x-pagination-current"),count:result.get("headers")("x-pagination-count")})}},angular.module("taigaCommon").factory("tgPaginateResponseService",PaginateResponse)}.call(this),function(){var ProjectService,taiga;taiga=this.taiga,ProjectService=function(){function ProjectService(projectsService,xhrError){this.projectsService=projectsService,this.xhrError=xhrError,this._project=null,this._section=null,this._sectionsBreadcrumb=Immutable.List(),this._activeMembers=Immutable.List(),taiga.defineImmutableProperty(this,"project",function(_this){return function(){return _this._project}}(this)),taiga.defineImmutableProperty(this,"section",function(_this){return function(){return _this._section}}(this)),taiga.defineImmutableProperty(this,"sectionsBreadcrumb",function(_this){return function(){return _this._sectionsBreadcrumb}}(this)),taiga.defineImmutableProperty(this,"activeMembers",function(_this){return function(){return _this._activeMembers}}(this))}return ProjectService.$inject=["tgProjectsService","tgXhrErrorService"],ProjectService.prototype.setSection=function(section){return this._section=section,section?this._sectionsBreadcrumb=this._sectionsBreadcrumb.push(this._section):this._sectionsBreadcrumb=Immutable.List()},ProjectService.prototype.setProjectBySlug=function(pslug){return new Promise(function(_this){return function(resolve,reject){return _this.project&&_this.project.get("slug")===pslug?resolve():_this.projectsService.getProjectBySlug(pslug).then(function(project){return _this.setProject(project),resolve()})["catch"](function(xhr){return _this.xhrError.response(xhr)})}}(this))},ProjectService.prototype.setProject=function(project){return this._project=project,this._activeMembers=this._project.get("members").filter(function(member){return member.get("is_active")})},ProjectService.prototype.cleanProject=function(){return this._project=null,this._activeMembers=Immutable.List(),this._section=null,this._sectionsBreadcrumb=Immutable.List()},ProjectService.prototype.fetchProject=function(){var pslug;return pslug=this.project.get("slug"),this.projectsService.getProjectBySlug(pslug).then(function(_this){return function(project){return _this.setProject(project)}}(this))},ProjectService}(),angular.module("taigaCommon").service("tgProjectService",ProjectService)}.call(this),function(){var ScopeEvent;ScopeEvent=function(){function ScopeEvent(){}return ScopeEvent.prototype.scopes={},ScopeEvent.prototype._searchDuplicatedScopes=function(id){return _.find(Object.keys(this.scopes),function(_this){return function(key){return _this.scopes[key].$id===id}}(this))},ScopeEvent.prototype._create=function(name,scope){var duplicatedScopeName;if(duplicatedScopeName=this._searchDuplicatedScopes(scope.$id))throw new Error('scopeEvent: this scope is already register with the name "'+duplicatedScopeName+'"');if(this.scopes[name])throw new Error('scopeEvent: "'+name+'" already in use');return scope._tgEmitter=new EventEmitter2,scope.$on("$destroy",function(_this){return function(){return scope._tgEmitter.removeAllListeners(),delete _this.scopes[name]}}(this)),this.scopes[name]=scope},ScopeEvent.prototype.emitter=function(name,scope){if(scope)scope=this._create(name,scope);else{if(!this.scopes[name])throw new Error('scopeEvent: "'+name+"\" scope doesn't exist'");scope=this.scopes[name]}return scope._tgEmitter},ScopeEvent}(),angular.module("taigaCommon").service("tgScopeEvent",ScopeEvent)}.call(this),function(){var ThemeService,taiga,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,ThemeService=function(superClass){function ThemeService(){return ThemeService.__super__.constructor.apply(this,arguments)}return extend(ThemeService,superClass),ThemeService}(taiga.Service=function(){return{use:function(themeName){var stylesheetEl;return stylesheetEl=$("link[rel='stylesheet']:first"),0===stylesheetEl.length&&(stylesheetEl=$(""),$("head").append(stylesheetEl)),stylesheetEl.attr("href","/"+window._version+"/styles/theme-"+themeName+".css")}}}),angular.module("taigaCommon").service("tgThemeService",ThemeService)}.call(this),function(){var UserService,bindMethods,taiga,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;taiga=this.taiga,bindMethods=taiga.bindMethods,UserService=function(superClass){function UserService(rs){this.rs=rs,bindMethods(this)}return extend(UserService,superClass),UserService.$inject=["tgResources"],UserService.prototype.getUserByUserName=function(username){return this.rs.users.getUserByUsername(username)},UserService.prototype.getContacts=function(userId){return this.rs.users.getContacts(userId)},UserService.prototype.getLiked=function(userId,pageNumber,objectType,textQuery){return this.rs.users.getLiked(userId,pageNumber,objectType,textQuery)},UserService.prototype.getVoted=function(userId,pageNumber,objectType,textQuery){return this.rs.users.getVoted(userId,pageNumber,objectType,textQuery)},UserService.prototype.getWatched=function(userId,pageNumber,objectType,textQuery){return this.rs.users.getWatched(userId,pageNumber,objectType,textQuery)},UserService.prototype.getStats=function(userId){return this.rs.users.getStats(userId)},UserService.prototype.attachUserContactsToProjects=function(userId,projects){return this.getContacts(userId).then(function(contacts){return projects=projects.map(function(project){var contactsFiltered;return contactsFiltered=contacts.filter(function(contact){var contactId;return contactId=contact.get("id"),-1!==project.get("members").indexOf(contactId)}),project=project.set("contacts",contactsFiltered)})})},UserService}(taiga.Service),angular.module("taigaCommon").service("tgUserService",UserService)}.call(this),function(){var xhrError,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;xhrError=function(superClass){function xhrError(q,location,navUrls){this.q=q,this.location=location,this.navUrls=navUrls}return extend(xhrError,superClass),xhrError.$inject=["$q","$location","$tgNavUrls"],xhrError.prototype.notFound=function(){return this.location.path(this.navUrls.resolve("not-found")),this.location.replace()},xhrError.prototype.permissionDenied=function(){return this.location.path(this.navUrls.resolve("permission-denied")),this.location.replace()},xhrError.prototype.response=function(xhr){return xhr&&(404===xhr.status?this.notFound():403===xhr.status&&this.permissionDenied()),this.q.reject(xhr)},xhrError}(taiga.Service),angular.module("taigaCommon").service("tgXhrErrorService",xhrError)}.call(this),function(){var UserTimelineAttachmentDirective;UserTimelineAttachmentDirective=function(template,$compile){var isImage,link,validFileExtensions;return validFileExtensions=[".jpg",".jpeg",".bmp",".gif",".png"],isImage=function(url){return url=url.toLowerCase(),_.some(validFileExtensions,function(extension){return-1!==url.indexOf(extension,url-extension.length)})},link=function(scope,el){var is_image,templateHtml;return is_image=isImage(scope.attachment.get("url")),templateHtml=is_image?template.get("user-timeline/user-timeline-attachment/user-timeline-attachment-image.html"):template.get("user-timeline/user-timeline-attachment/user-timeline-attachment.html"),el.html(templateHtml),$compile(el.contents())(scope),el.find("img").error(function(){return this.remove()})},{link:link,scope:{attachment:"=tgUserTimelineAttachment"}}},UserTimelineAttachmentDirective.$inject=["$tgTemplate","$compile"],angular.module("taigaUserTimeline").directive("tgUserTimelineAttachment",UserTimelineAttachmentDirective)}.call(this),function(){var UserTimelineItemTitle,unslugify;unslugify=this.taiga.unslugify,UserTimelineItemTitle=function(){function UserTimelineItemTitle(translate,sce){this.translate=translate,this.sce=sce}return UserTimelineItemTitle.$inject=["$translate","$sce"],UserTimelineItemTitle.prototype._fieldTranslationKey={status:"COMMON.FIELDS.STATUS",subject:"COMMON.FIELDS.SUBJECT",description_diff:"COMMON.FIELDS.DESCRIPTION",points:"COMMON.FIELDS.POINTS",assigned_to:"COMMON.FIELDS.ASSIGNED_TO",severity:"ISSUES.FIELDS.SEVERITY",priority:"ISSUES.FIELDS.PRIORITY",type:"ISSUES.FIELDS.TYPE",is_iocaine:"TASK.FIELDS.IS_IOCAINE",is_blocked:"COMMON.FIELDS.IS_BLOCKED"},UserTimelineItemTitle.prototype._params={username:function(timeline,event){var title_attr,url,user;return user=timeline.getIn(["data","user"]),user.get("is_profile_visible")?(title_attr=this.translate.instant("COMMON.SEE_USER_PROFILE",{username:user.get("username")}),url="user-profile:username=timeline.getIn(['data', 'user', 'username'])",this._getLink(url,user.get("name"),title_attr)):this._getUsernameSpan(user.get("name"))},field_name:function(timeline,event){var field_name;return field_name=timeline.getIn(["data","value_diff","key"]),this.translate.instant(this._fieldTranslationKey[field_name])},project_name:function(timeline,event){var url;return url="project:project=timeline.getIn(['data', 'project', 'slug'])",this._getLink(url,timeline.getIn(["data","project","name"]))},new_value:function(timeline,event){var new_value,value;return _.isArray(timeline.getIn(["data","value_diff","value"]).toJS())?(value=timeline.getIn(["data","value_diff","value"]).get(1),null===value&&"assigned_to"===timeline.getIn(["data","value_diff","key"])&&(value=this.translate.instant("ACTIVITY.VALUES.UNASSIGNED")),new_value=value):new_value=timeline.getIn(["data","value_diff","value"]).first().get(1),_.escape(new_value)},sprint_name:function(timeline,event){var url;return url="project-taskboard:project=timeline.getIn(['data', 'project', 'slug']),sprint=timeline.getIn(['data', 'milestone', 'slug'])",this._getLink(url,timeline.getIn(["data","milestone","name"]))},us_name:function(timeline,event){var event_us,obj,text,url;return obj=this._getTimelineObj(timeline,event).get("userstory"),event_us={obj:"parent_userstory"},url=this._getDetailObjUrl(event_us),text="#"+obj.get("ref")+" "+obj.get("subject"),this._getLink(url,text)},obj_name:function(timeline,event){var obj,text,url;return obj=this._getTimelineObj(timeline,event),url=this._getDetailObjUrl(event),text="wikipage"===event.obj?unslugify(obj.get("slug")):"milestone"===event.obj?obj.get("name"):"#"+obj.get("ref")+" "+obj.get("subject"),this._getLink(url,text)},role_name:function(timeline,event){return _.escape(timeline.getIn(["data","value_diff","value"]).keySeq().first())}},UserTimelineItemTitle.prototype._translateTitleParams=function(param,timeline,event){return this._params[param].call(this,timeline,event)},UserTimelineItemTitle.prototype._getTimelineObj=function(timeline,event){return timeline.getIn(["data",event.obj])},UserTimelineItemTitle.prototype._getDetailObjUrl=function(event){var url;return url={issue:["project-issues-detail",":project=timeline.getIn(['data', 'project', 'slug']),ref=timeline.getIn(['obj', 'ref'])"],wikipage:["project-wiki-page",":project=timeline.getIn(['data', 'project', 'slug']),slug=timeline.getIn(['obj', 'slug'])"],task:["project-tasks-detail",":project=timeline.getIn(['data', 'project', 'slug']),ref=timeline.getIn(['obj', 'ref'])"],userstory:["project-userstories-detail",":project=timeline.getIn(['data', 'project', 'slug']),ref=timeline.getIn(['obj', 'ref'])"],parent_userstory:["project-userstories-detail",":project=timeline.getIn(['data', 'project', 'slug']),ref=timeline.getIn(['obj', 'userstory', 'ref'])"],milestone:["project-taskboard",":project=timeline.getIn(['data', 'project', 'slug']),sprint=timeline.getIn(['obj', 'slug'])"]},url[event.obj][0]+url[event.obj][1]},UserTimelineItemTitle.prototype._getLink=function(url,text,title){return title=title||text,$("").attr("tg-nav",url).text(text).attr("title",title).prop("outerHTML")},UserTimelineItemTitle.prototype._getUsernameSpan=function(text){var title;return title=title||text,$("").addClass("username").text(text).prop("outerHTML")},UserTimelineItemTitle.prototype._getParams=function(timeline,event,timeline_type){var params;return params={},timeline_type.translate_params.forEach(function(_this){return function(param){return params[param]=_this._translateTitleParams(param,timeline,event)}}(this)),params},UserTimelineItemTitle.prototype.getTitle=function(timeline,event,type){var params,paramsKeys,translation;return params=this._getParams(timeline,event,type),paramsKeys={},Object.keys(params).forEach(function(key){return paramsKeys[key]="{{"+key+"}}"}),translation=this.translate.instant(type.key,paramsKeys),Object.keys(params).forEach(function(key){var find;return find="{{"+key+"}}",translation=translation.replace(new RegExp(find,"g"),params[key])}),translation},UserTimelineItemTitle}(),angular.module("taigaUserTimeline").service("tgUserTimelineItemTitle",UserTimelineItemTitle)}.call(this),function(){var UserTimelineType,timelineType;timelineType=function(timeline,event){var types;return types=[{check:function(timeline,event){return"membership"===event.obj},key:"TIMELINE.NEW_MEMBER",translate_params:["project_name"],member:function(timeline){return Immutable.Map({user:timeline.getIn(["data","user"]),role:timeline.getIn(["data","role"])})}},{check:function(timeline,event){return"project"===event.obj&&"create"===event.type},key:"TIMELINE.NEW_PROJECT",translate_params:["username","project_name"],description:function(timeline){return timeline.getIn(["data","project","description"])}},{check:function(timeline,event){return"change"===event.type&&timeline.hasIn(["data","value_diff"])&&"attachments"===timeline.getIn(["data","value_diff","key"])},key:"TIMELINE.UPLOAD_ATTACHMENT",translate_params:["username","obj_name"]},{check:function(timeline,event){return"userstory"===event.obj&&"create"===event.type},key:"TIMELINE.US_CREATED",translate_params:["username","project_name","obj_name"]},{check:function(timeline,event){return"issue"===event.obj&&"create"===event.type},key:"TIMELINE.ISSUE_CREATED",translate_params:["username","project_name","obj_name"]},{check:function(timeline,event){return"wikipage"===event.obj&&"create"===event.type},key:"TIMELINE.WIKI_CREATED",translate_params:["username","project_name","obj_name"]},{check:function(timeline,event){return"task"===event.obj&&"create"===event.type&&!timeline.getIn(["data","task","userstory"])},key:"TIMELINE.TASK_CREATED",translate_params:["username","project_name","obj_name"]},{check:function(timeline,event){return"task"===event.obj&&"create"===event.type&&timeline.getIn(["data","task","userstory"])},key:"TIMELINE.TASK_CREATED_WITH_US",translate_params:["username","project_name","obj_name","us_name"]},{check:function(timeline,event){return"milestone"===event.obj&&"create"===event.type},key:"TIMELINE.MILESTONE_CREATED",translate_params:["username","project_name","obj_name"]},{check:function(timeline,event){return timeline.getIn(["data","comment"])&&"userstory"===event.obj},key:"TIMELINE.NEW_COMMENT_US",translate_params:["username","obj_name"],description:function(timeline){return $(timeline.getIn(["data","comment_html"])).text()}},{check:function(timeline,event){return timeline.getIn(["data","comment"])&&"issue"===event.obj},key:"TIMELINE.NEW_COMMENT_ISSUE",translate_params:["username","obj_name"],description:function(timeline){return $(timeline.getIn(["data","comment_html"])).text()}},{check:function(timeline,event){return timeline.getIn(["data","comment"])&&"task"===event.obj},key:"TIMELINE.NEW_COMMENT_TASK",translate_params:["username","obj_name"], -description:function(timeline){return $(timeline.getIn(["data","comment_html"])).text()}},{check:function(timeline,event){return timeline.hasIn(["data","value_diff"])&&"moveInBacklog"===timeline.getIn(["data","value_diff","key"])&&timeline.hasIn(["data","value_diff","value","backlog_order"])&&"change"===event.type},key:"TIMELINE.US_MOVED",translate_params:["username","obj_name"]},{check:function(timeline,event){return timeline.hasIn(["data","value_diff"])&&"moveInBacklog"===timeline.getIn(["data","value_diff","key"])&&"change"===event.type?null===timeline.getIn(["data","value_diff","value","milestone"]).get(1):!1},key:"TIMELINE.US_REMOVED_FROM_MILESTONE",translate_params:["username","obj_name"]},{check:function(timeline,event){return timeline.hasIn(["data","value_diff"])&&"moveInBacklog"===timeline.getIn(["data","value_diff","key"])&&"change"===event.type},key:"TIMELINE.US_ADDED_MILESTONE",translate_params:["username","obj_name","sprint_name"]},{check:function(timeline,event){return timeline.hasIn(["data","value_diff"])&&"blocked"===timeline.getIn(["data","value_diff","key"])&&"change"===event.type?timeline.getIn(["data","value_diff","value","is_blocked"]).get(1)===!0:!1},key:"TIMELINE.BLOCKED",translate_params:["username","obj_name"],description:function(timeline){return timeline.hasIn(["data","value_diff","value","blocked_note_html"])?$(timeline.getIn(["data","value_diff","value","blocked_note_html"]).get(1)).text():!1}},{check:function(timeline,event){return timeline.hasIn(["data","value_diff"])&&"blocked"===timeline.getIn(["data","value_diff","key"])&&"change"===event.type?timeline.getIn(["data","value_diff","value","is_blocked"]).get(1)===!1:!1},key:"TIMELINE.UNBLOCKED",translate_params:["username","obj_name"]},{check:function(timeline,event){return"milestone"===event.obj&&"change"===event.type},key:"TIMELINE.MILESTONE_UPDATED",translate_params:["username","obj_name"]},{check:function(timeline,event){return"wikipage"===event.obj&&"change"===event.type},key:"TIMELINE.WIKI_UPDATED",translate_params:["username","obj_name"]},{check:function(timeline,event){return"userstory"===event.obj&&"change"===event.type&&timeline.hasIn(["data","value_diff"])&&"points"===timeline.getIn(["data","value_diff","key"])},key:"TIMELINE.US_UPDATED_POINTS",translate_params:["username","field_name","obj_name","new_value","role_name"]},{check:function(timeline,event){return"userstory"===event.obj&&"change"===event.type&&timeline.hasIn(["data","value_diff"])&&"description_diff"===timeline.getIn(["data","value_diff","key"])},key:"TIMELINE.US_UPDATED",translate_params:["username","field_name","obj_name"]},{check:function(timeline,event){return"userstory"===event.obj&&"change"===event.type},key:"TIMELINE.US_UPDATED_WITH_NEW_VALUE",translate_params:["username","field_name","obj_name","new_value"]},{check:function(timeline,event){return"issue"===event.obj&&"change"===event.type&&timeline.hasIn(["data","value_diff"])&&"description_diff"===timeline.getIn(["data","value_diff","key"])},key:"TIMELINE.ISSUE_UPDATED",translate_params:["username","field_name","obj_name"]},{check:function(timeline,event){return"issue"===event.obj&&"change"===event.type},key:"TIMELINE.ISSUE_UPDATED_WITH_NEW_VALUE",translate_params:["username","field_name","obj_name","new_value"]},{check:function(timeline,event){return"task"===event.obj&&"change"===event.type&&!timeline.getIn(["data","task","userstory"])&&timeline.hasIn(["data","value_diff"])&&"description_diff"===timeline.getIn(["data","value_diff","key"])},key:"TIMELINE.TASK_UPDATED",translate_params:["username","field_name","obj_name"]},{check:function(timeline,event){return"task"===event.obj&&"change"===event.type&&timeline.getIn(["data","task","userstory"])&&timeline.hasIn(["data","value_diff"])&&"description_diff"===timeline.getIn(["data","value_diff","key"])},key:"TIMELINE.TASK_UPDATED_WITH_US",translate_params:["username","field_name","obj_name","us_name"]},{check:function(timeline,event){return"task"===event.obj&&"change"===event.type&&!timeline.getIn(["data","task","userstory"])},key:"TIMELINE.TASK_UPDATED_WITH_NEW_VALUE",translate_params:["username","field_name","obj_name","new_value"]},{check:function(timeline,event){return"task"===event.obj&&"change"===event.type&&timeline.getIn(["data","task","userstory"])},key:"TIMELINE.TASK_UPDATED_WITH_US_NEW_VALUE",translate_params:["username","field_name","obj_name","us_name","new_value"]},{check:function(timeline,event){return"user"===event.obj&&"create"===event.type},key:"TIMELINE.NEW_USER",translate_params:["username"]}],_.find(types,function(obj){return obj.check(timeline,event)})},UserTimelineType=function(){function UserTimelineType(){}return UserTimelineType.prototype.getType=function(timeline,event){return timelineType(timeline,event)},UserTimelineType}(),angular.module("taigaUserTimeline").service("tgUserTimelineItemType",UserTimelineType)}.call(this),function(){var UserTimelineItemDirective;UserTimelineItemDirective=function(){return{templateUrl:"user-timeline/user-timeline-item/user-timeline-item.html",scope:{timeline:"=tgUserTimelineItem"}}},angular.module("taigaUserTimeline").directive("tgUserTimelineItem",UserTimelineItemDirective)}.call(this),function(){var UserTimelinePaginationSequence;UserTimelinePaginationSequence=function(){var obj;return obj={},obj.generate=function(config){var getContent,items,next,page;return page=1,items=Immutable.List(),config.minItems=config.minItems||20,next=function(){return items=Immutable.List(),getContent()},getContent=function(){return config.fetch(page).then(function(response){var data;return page++,data=response.get("data"),config.filter&&(data=config.filter(data)),config.map&&(data=data.map(config.map)),items=items.concat(data),items.size>5]|=128<<24-len%32,x[(len+64>>9<<4)+15]=len;for(var w=Array(80),a=1732584193,b=-271733879,c=-1732584194,d=271733878,e=-1009589776,i=0;ij;j++){16>j?w[j]=x[i+j]:w[j]=rol(w[j-3]^w[j-8]^w[j-14]^w[j-16],1);var t=safe_add(safe_add(rol(a,5),sha1_ft(j,b,c,d)),safe_add(safe_add(e,w[j]),sha1_kt(j)));e=d,d=c,c=rol(b,30),b=a,a=t}a=safe_add(a,olda),b=safe_add(b,oldb),c=safe_add(c,oldc),d=safe_add(d,oldd),e=safe_add(e,olde)}return Array(a,b,c,d,e)}function sha1_ft(t,b,c,d){return 20>t?b&c|~b&d:40>t?b^c^d:60>t?b&c|b&d|c&d:b^c^d}function sha1_kt(t){return 20>t?1518500249:40>t?1859775393:60>t?-1894007588:-899497514}function core_hmac_sha1(key,data){var bkey=str2binb(key);bkey.length>16&&(bkey=core_sha1(bkey,key.length*chrsz));for(var ipad=Array(16),opad=Array(16),i=0;16>i;i++)ipad[i]=909522486^bkey[i],opad[i]=1549556828^bkey[i];var hash=core_sha1(ipad.concat(str2binb(data)),512+data.length*chrsz);return core_sha1(opad.concat(hash),672)}function safe_add(x,y){var lsw=(65535&x)+(65535&y),msw=(x>>16)+(y>>16)+(lsw>>16);return msw<<16|65535&lsw}function rol(num,cnt){return num<>>32-cnt}function str2binb(str){for(var bin=Array(),mask=(1<>5]|=(str.charCodeAt(i/chrsz)&mask)<<32-chrsz-i%32;return bin}function binb2str(bin){for(var str="",mask=(1<>5]>>>32-chrsz-i%32&mask);return str}function binb2hex(binarray){for(var hex_tab=hexcase?"0123456789ABCDEF":"0123456789abcdef",str="",i=0;i<4*binarray.length;i++)str+=hex_tab.charAt(binarray[i>>2]>>8*(3-i%4)+4&15)+hex_tab.charAt(binarray[i>>2]>>8*(3-i%4)&15);return str}function binb2b64(binarray){for(var tab="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",str="",i=0;i<4*binarray.length;i+=3)for(var triplet=(binarray[i>>2]>>8*(3-i%4)&255)<<16|(binarray[i+1>>2]>>8*(3-(i+1)%4)&255)<<8|binarray[i+2>>2]>>8*(3-(i+2)%4)&255,j=0;4>j;j++)str+=8*i+6*j>32*binarray.length?b64pad:tab.charAt(triplet>>6*(3-j)&63);return str}!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof _dereq_&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof _dereq_&&_dereq_,o=0;o0},Async.prototype.throwLater=function(fn,arg){if(1===arguments.length&&(arg=fn,fn=function(){throw arg}),"undefined"!=typeof setTimeout)setTimeout(function(){fn(arg)},0);else try{this._schedule(function(){fn(arg)})}catch(e){throw new Error("No async scheduler available\n\n See http://goo.gl/m3OTXk\n")}},util.hasDevTools?(schedule.isStatic&&(schedule=function(fn){setTimeout(fn,0)}),Async.prototype.invokeLater=function(fn,receiver,arg){this._trampolineEnabled?AsyncInvokeLater.call(this,fn,receiver,arg):this._schedule(function(){setTimeout(function(){fn.call(receiver,arg)},100)})},Async.prototype.invoke=function(fn,receiver,arg){this._trampolineEnabled?AsyncInvoke.call(this,fn,receiver,arg):this._schedule(function(){fn.call(receiver,arg)})},Async.prototype.settlePromises=function(promise){this._trampolineEnabled?AsyncSettlePromises.call(this,promise):this._schedule(function(){promise._settlePromises()})}):(Async.prototype.invokeLater=AsyncInvokeLater,Async.prototype.invoke=AsyncInvoke,Async.prototype.settlePromises=AsyncSettlePromises),Async.prototype.invokeFirst=function(fn,receiver,arg){this._normalQueue.unshift(fn,receiver,arg),this._queueTick()},Async.prototype._drainQueue=function(queue){for(;queue.length()>0;){var fn=queue.shift();if("function"==typeof fn){var receiver=queue.shift(),arg=queue.shift();fn.call(receiver,arg)}else fn._settlePromises()}},Async.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._drainQueue(this._lateQueue)},Async.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},Async.prototype._reset=function(){this._isTickUsed=!1},module.exports=new Async,module.exports.firstLineError=firstLineError},{"./queue.js":28,"./schedule.js":31,"./util.js":38}],3:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,tryConvertToPromise){var rejectThis=function(_,e){this._reject(e)},targetRejected=function(e,context){context.promiseRejectionQueued=!0,context.bindingPromise._then(rejectThis,rejectThis,null,this,e)},bindingResolved=function(thisArg,context){this._isPending()&&this._resolveCallback(context.target)},bindingRejected=function(e,context){context.promiseRejectionQueued||this._reject(e)};Promise.prototype.bind=function(thisArg){var maybePromise=tryConvertToPromise(thisArg),ret=new Promise(INTERNAL);ret._propagateFrom(this,1);var target=this._target();if(ret._setBoundTo(maybePromise),maybePromise instanceof Promise){var context={promiseRejectionQueued:!1,promise:ret,target:target,bindingPromise:maybePromise};target._then(INTERNAL,targetRejected,ret._progress,ret,context),maybePromise._then(bindingResolved,bindingRejected,ret._progress,ret,context)}else ret._resolveCallback(target);return ret},Promise.prototype._setBoundTo=function(obj){void 0!==obj?(this._bitField=131072|this._bitField,this._boundTo=obj):this._bitField=-131073&this._bitField},Promise.prototype._isBound=function(){return 131072===(131072&this._bitField)},Promise.bind=function(thisArg,value){var maybePromise=tryConvertToPromise(thisArg),ret=new Promise(INTERNAL);return ret._setBoundTo(maybePromise),maybePromise instanceof Promise?maybePromise._then(function(){ret._resolveCallback(value)},ret._reject,ret._progress,ret,null):ret._resolveCallback(value),ret}}},{}],4:[function(_dereq_,module,exports){"use strict";function noConflict(){try{Promise===bluebird&&(Promise=old)}catch(e){}return bluebird}var old;"undefined"!=typeof Promise&&(old=Promise);var bluebird=_dereq_("./promise.js")();bluebird.noConflict=noConflict,module.exports=bluebird},{"./promise.js":23}],5:[function(_dereq_,module,exports){"use strict";var cr=Object.create;if(cr){var callerCache=cr(null),getterCache=cr(null);callerCache[" size"]=getterCache[" size"]=0}module.exports=function(Promise){function ensureMethod(obj,methodName){var fn;if(null!=obj&&(fn=obj[methodName]),"function"!=typeof fn){var message="Object "+util.classString(obj)+" has no method '"+util.toString(methodName)+"'";throw new Promise.TypeError(message)}return fn}function caller(obj){var methodName=this.pop(),fn=ensureMethod(obj,methodName);return fn.apply(obj,this)}function namedGetter(obj){return obj[this]}function indexedGetter(obj){var index=+this;return 0>index&&(index=Math.max(0,index+obj.length)),obj[index]}var getGetter,util=_dereq_("./util.js"),canEvaluate=util.canEvaluate;util.isIdentifier;Promise.prototype.call=function(methodName){for(var $_len=arguments.length,args=new Array($_len-1),$_i=1;$_len>$_i;++$_i)args[$_i-1]=arguments[$_i];return args.push(methodName),this._then(caller,void 0,void 0,args,void 0)},Promise.prototype.get=function(propertyName){var getter,isIndex="number"==typeof propertyName;if(isIndex)getter=indexedGetter;else if(canEvaluate){var maybeGetter=getGetter(propertyName);getter=null!==maybeGetter?maybeGetter:namedGetter}else getter=namedGetter;return this._then(getter,void 0,void 0,propertyName,void 0)}}},{"./util.js":38}],6:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){var errors=_dereq_("./errors.js"),async=_dereq_("./async.js"),CancellationError=errors.CancellationError;Promise.prototype._cancel=function(reason){if(!this.isCancellable())return this;for(var parent,promiseToReject=this;void 0!==(parent=promiseToReject._cancellationParent)&&parent.isCancellable();)promiseToReject=parent;this._unsetCancellable(),promiseToReject._target()._rejectCallback(reason,!1,!0)},Promise.prototype.cancel=function(reason){return this.isCancellable()?(void 0===reason&&(reason=new CancellationError),async.invokeLater(this._cancel,this,reason),this):this},Promise.prototype.cancellable=function(){return this._cancellable()?this:(async.enableTrampoline(),this._setCancellable(),this._cancellationParent=void 0,this)},Promise.prototype.uncancellable=function(){var ret=this.then();return ret._unsetCancellable(),ret},Promise.prototype.fork=function(didFulfill,didReject,didProgress){var ret=this._then(didFulfill,didReject,didProgress,void 0,void 0);return ret._setCancellable(),ret._cancellationParent=void 0,ret}}},{"./async.js":2,"./errors.js":13}],7:[function(_dereq_,module,exports){"use strict";module.exports=function(){function CapturedTrace(parent){this._parent=parent;var length=this._length=1+(void 0===parent?0:parent._length);captureStackTrace(this,CapturedTrace),length>32&&this.uncycle()}function reconstructStack(message,stacks){for(var i=0;i=0;--j)if(prev[j]===currentLastLine){commonRootMeetPoint=j;break}for(var j=commonRootMeetPoint;j>=0;--j){var line=prev[j];if(current[currentLastIndex]!==line)break;current.pop(),currentLastIndex--}current=prev}}function cleanStack(stack){for(var ret=[],i=0;i0&&(stack=stack.slice(i)),stack}function formatNonError(obj){var str;if("function"==typeof obj)str="[function "+(obj.name||"anonymous")+"]";else{str=obj.toString();var ruselessToString=/\[object [a-zA-Z0-9$_]+\]/;if(ruselessToString.test(str))try{var newStr=JSON.stringify(obj);str=newStr}catch(e){}0===str.length&&(str="(empty array)")}return"(<"+snip(str)+">, no stack trace)"}function snip(str){var maxChars=41;return str.lengthlength)){for(var nodes=[],stackToIndex={},i=0,node=this;void 0!==node;++i)nodes.push(node),node=node._parent;length=this._length=i;for(var i=length-1;i>=0;--i){var stack=nodes[i].stack;void 0===stackToIndex[stack]&&(stackToIndex[stack]=i)}for(var i=0;length>i;++i){var currentStack=nodes[i].stack,index=stackToIndex[currentStack];if(void 0!==index&&index!==i){index>0&&(nodes[index-1]._parent=void 0,nodes[index-1]._length=1),nodes[i]._parent=void 0,nodes[i]._length=1;var cycleEdgeNode=i>0?nodes[i-1]:this;length-1>index?(cycleEdgeNode._parent=nodes[index+1],cycleEdgeNode._parent.uncycle(),cycleEdgeNode._length=cycleEdgeNode._parent._length+1):(cycleEdgeNode._parent=void 0,cycleEdgeNode._length=1);for(var currentChildLength=cycleEdgeNode._length+1,j=i-2;j>=0;--j)nodes[j]._length=currentChildLength,currentChildLength++;return}}}},CapturedTrace.prototype.parent=function(){return this._parent},CapturedTrace.prototype.hasParent=function(){return void 0!==this._parent},CapturedTrace.prototype.attachExtraTrace=function(error){if(!error.__stackCleaned__){this.uncycle();for(var parsed=CapturedTrace.parseStackAndMessage(error),message=parsed.message,stacks=[parsed.stack],trace=this;void 0!==trace;)stacks.push(cleanStack(trace.stack.split("\n"))),trace=trace._parent;removeCommonRoots(stacks),removeDuplicateOrEmptyJumps(stacks),util.notEnumerableProp(error,"stack",reconstructStack(message,stacks)),util.notEnumerableProp(error,"__stackCleaned__",!0)}},CapturedTrace.parseStackAndMessage=function(error){var stack=error.stack,message=error.toString();return stack="string"==typeof stack&&stack.length>0?stackFramesAsArray(error):[" (No stack trace)"],{message:message,stack:cleanStack(stack)}},CapturedTrace.formatAndLogError=function(error,title){if("undefined"!=typeof console){var message;if("object"==typeof error||"function"==typeof error){var stack=error.stack;message=title+formatStack(stack,error)}else message=title+String(error);"function"==typeof warn?warn(message):("function"==typeof console.log||"object"==typeof console.log)&&console.log(message)}},CapturedTrace.unhandledRejection=function(reason){CapturedTrace.formatAndLogError(reason,"^--- With additional stack trace: ")},CapturedTrace.isSupported=function(){return"function"==typeof captureStackTrace},CapturedTrace.fireRejectionEvent=function(name,localHandler,reason,promise){var localEventFired=!1;try{"function"==typeof localHandler&&(localEventFired=!0,"rejectionHandled"===name?localHandler(promise):localHandler(reason,promise))}catch(e){async.throwLater(e)}var globalEventFired=!1;try{globalEventFired=fireGlobalEvent(name,reason,promise)}catch(e){globalEventFired=!0,async.throwLater(e)}var domEventFired=!1;if(fireDomEvent)try{domEventFired=fireDomEvent(name.toLowerCase(),{reason:reason,promise:promise})}catch(e){domEventFired=!0,async.throwLater(e)}globalEventFired||localEventFired||domEventFired||"unhandledRejection"!==name||CapturedTrace.formatAndLogError(reason,"Unhandled rejection ")};var shouldIgnore=function(){return!1},parseLineInfoRegex=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;CapturedTrace.setBounds=function(firstLineError,lastLineError){if(CapturedTrace.isSupported()){for(var firstFileName,lastFileName,firstStackLines=firstLineError.stack.split("\n"),lastStackLines=lastLineError.stack.split("\n"),firstIndex=-1,lastIndex=-1,i=0;ifirstIndex||0>lastIndex||!firstFileName||!lastFileName||firstFileName!==lastFileName||firstIndex>=lastIndex||(shouldIgnore=function(line){if(bluebirdFramePattern.test(line))return!0;var info=parseLineInfo(line);return info&&info.fileName===firstFileName&&firstIndex<=info.line&&info.line<=lastIndex?!0:!1})}};var fireDomEvent,captureStackTrace=function(){var v8stackFramePattern=/^\s*at\s*/,v8stackFormatter=function(stack,error){return"string"==typeof stack?stack:void 0!==error.name&&void 0!==error.message?error.toString():formatNonError(error)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit=Error.stackTraceLimit+6,stackFramePattern=v8stackFramePattern,formatStack=v8stackFormatter;var captureStackTrace=Error.captureStackTrace;return shouldIgnore=function(line){return bluebirdFramePattern.test(line)},function(receiver,ignoreUntil){Error.stackTraceLimit=Error.stackTraceLimit+6,captureStackTrace(receiver,ignoreUntil),Error.stackTraceLimit=Error.stackTraceLimit-6}}var err=new Error;if("string"==typeof err.stack&&err.stack.split("\n")[0].indexOf("stackDetection@")>=0)return stackFramePattern=/@/,formatStack=v8stackFormatter,indentStackFrames=!0,function(o){o.stack=(new Error).stack};var hasStackAfterThrow;try{throw new Error}catch(e){hasStackAfterThrow="stack"in e}return"stack"in err||!hasStackAfterThrow||"number"!=typeof Error.stackTraceLimit?(formatStack=function(stack,error){return"string"==typeof stack?stack:"object"!=typeof error&&"function"!=typeof error||void 0===error.name||void 0===error.message?formatNonError(error):error.toString()},null):(stackFramePattern=v8stackFramePattern,formatStack=v8stackFormatter,function(o){Error.stackTraceLimit=Error.stackTraceLimit+6;try{throw new Error}catch(e){o.stack=e.stack}Error.stackTraceLimit=Error.stackTraceLimit-6})}([]),fireGlobalEvent=function(){if(util.isNode)return function(name,reason,promise){return"rejectionHandled"===name?process.emit(name,promise):process.emit(name,reason,promise)};var customEventWorks=!1,anyEventWorks=!0;try{var ev=new self.CustomEvent("test");customEventWorks=ev instanceof CustomEvent}catch(e){}if(!customEventWorks)try{var event=document.createEvent("CustomEvent");event.initCustomEvent("testingtheevent",!1,!0,{}),self.dispatchEvent(event)}catch(e){anyEventWorks=!1}anyEventWorks&&(fireDomEvent=function(type,detail){var event;return customEventWorks?event=new self.CustomEvent(type,{detail:detail,bubbles:!1,cancelable:!0}):self.dispatchEvent&&(event=document.createEvent("CustomEvent"),event.initCustomEvent(type,!1,!0,detail)),event?!self.dispatchEvent(event):!1});var toWindowMethodNameMap={};return toWindowMethodNameMap.unhandledRejection="onunhandledRejection".toLowerCase(),toWindowMethodNameMap.rejectionHandled="onrejectionHandled".toLowerCase(),function(name,reason,promise){var methodName=toWindowMethodNameMap[name],method=self[methodName];return method?("rejectionHandled"===name?method.call(self,promise):method.call(self,reason,promise),!0):!1}}();return"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(warn=function(message){console.warn(message)},util.isNode&&process.stderr.isTTY?warn=function(message){process.stderr.write(""+message+"\n")}:util.isNode||"string"!=typeof(new Error).stack||(warn=function(message){console.warn("%c"+message,"color: red")})),CapturedTrace}},{"./async.js":2,"./util.js":38}],8:[function(_dereq_,module,exports){"use strict";module.exports=function(NEXT_FILTER){function CatchFilter(instances,callback,promise){this._instances=instances,this._callback=callback,this._promise=promise}function safePredicate(predicate,e){var safeObject={},retfilter=tryCatch(predicate).call(safeObject,e);if(retfilter===errorObj)return retfilter;var safeKeys=keys(safeObject);return safeKeys.length?(errorObj.e=new TypeError("Catch filter must inherit from Error or be a simple predicate function\n\n See http://goo.gl/o84o68\n"),errorObj):retfilter}var util=_dereq_("./util.js"),errors=_dereq_("./errors.js"),tryCatch=util.tryCatch,errorObj=util.errorObj,keys=_dereq_("./es5.js").keys,TypeError=errors.TypeError;return CatchFilter.prototype.doFilter=function(e){for(var cb=this._callback,promise=this._promise,boundTo=promise._boundValue(),i=0,len=this._instances.length;len>i;++i){var item=this._instances[i],itemIsErrorType=item===Error||null!=item&&item.prototype instanceof Error;if(itemIsErrorType&&e instanceof item){var ret=tryCatch(cb).call(boundTo,e);return ret===errorObj?(NEXT_FILTER.e=ret.e,NEXT_FILTER):ret}if("function"==typeof item&&!itemIsErrorType){var shouldHandle=safePredicate(item,e);if(shouldHandle===errorObj){e=errorObj.e;break}if(shouldHandle){var ret=tryCatch(cb).call(boundTo,e);return ret===errorObj?(NEXT_FILTER.e=ret.e,NEXT_FILTER):ret}}}return NEXT_FILTER.e=e,NEXT_FILTER},CatchFilter}},{"./errors.js":13,"./es5.js":14,"./util.js":38}],9:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,CapturedTrace,isDebugging){function Context(){this._trace=new CapturedTrace(peekContext())}function createContext(){return isDebugging()?new Context:void 0}function peekContext(){var lastIndex=contextStack.length-1;return lastIndex>=0?contextStack[lastIndex]:void 0}var contextStack=[];return Context.prototype._pushContext=function(){isDebugging()&&void 0!==this._trace&&contextStack.push(this._trace)},Context.prototype._popContext=function(){isDebugging()&&void 0!==this._trace&&contextStack.pop()},Promise.prototype._peekContext=peekContext,Promise.prototype._pushContext=Context.prototype._pushContext,Promise.prototype._popContext=Context.prototype._popContext,createContext}},{}],10:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,CapturedTrace){var unhandledRejectionHandled,possiblyUnhandledRejection,getDomain=Promise._getDomain,async=_dereq_("./async.js"),Warning=_dereq_("./errors.js").Warning,util=_dereq_("./util.js"),canAttachTrace=util.canAttachTrace,debugging=util.isNode&&(!!process.env.BLUEBIRD_DEBUG||"development"===process.env.NODE_ENV);return util.isNode&&0==process.env.BLUEBIRD_DEBUG&&(debugging=!1),debugging&&async.disableTrampolineIfNecessary(),Promise.prototype._ignoreRejections=function(){this._unsetRejectionIsUnhandled(),this._bitField=16777216|this._bitField},Promise.prototype._ensurePossibleRejectionHandled=function(){0===(16777216&this._bitField)&&(this._setRejectionIsUnhandled(),async.invokeLater(this._notifyUnhandledRejection,this,void 0))},Promise.prototype._notifyUnhandledRejectionIsHandled=function(){CapturedTrace.fireRejectionEvent("rejectionHandled",unhandledRejectionHandled,void 0,this)},Promise.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var reason=this._getCarriedStackTrace()||this._settledValue;this._setUnhandledRejectionIsNotified(),CapturedTrace.fireRejectionEvent("unhandledRejection",possiblyUnhandledRejection,reason,this)}},Promise.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=524288|this._bitField},Promise.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-524289&this._bitField},Promise.prototype._isUnhandledRejectionNotified=function(){return(524288&this._bitField)>0},Promise.prototype._setRejectionIsUnhandled=function(){this._bitField=2097152|this._bitField},Promise.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-2097153&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},Promise.prototype._isRejectionUnhandled=function(){return(2097152&this._bitField)>0},Promise.prototype._setCarriedStackTrace=function(capturedTrace){this._bitField=1048576|this._bitField,this._fulfillmentHandler0=capturedTrace},Promise.prototype._isCarryingStackTrace=function(){return(1048576&this._bitField)>0},Promise.prototype._getCarriedStackTrace=function(){return this._isCarryingStackTrace()?this._fulfillmentHandler0:void 0},Promise.prototype._captureStackTrace=function(){return debugging&&(this._trace=new CapturedTrace(this._peekContext())),this},Promise.prototype._attachExtraTrace=function(error,ignoreSelf){if(debugging&&canAttachTrace(error)){var trace=this._trace;if(void 0!==trace&&ignoreSelf&&(trace=trace._parent),void 0!==trace)trace.attachExtraTrace(error);else if(!error.__stackCleaned__){var parsed=CapturedTrace.parseStackAndMessage(error);util.notEnumerableProp(error,"stack",parsed.message+"\n"+parsed.stack.join("\n")),util.notEnumerableProp(error,"__stackCleaned__",!0)}}},Promise.prototype._warn=function(message){var warning=new Warning(message),ctx=this._peekContext();if(ctx)ctx.attachExtraTrace(warning);else{var parsed=CapturedTrace.parseStackAndMessage(warning);warning.stack=parsed.message+"\n"+parsed.stack.join("\n")}CapturedTrace.formatAndLogError(warning,"")},Promise.onPossiblyUnhandledRejection=function(fn){var domain=getDomain();possiblyUnhandledRejection="function"==typeof fn?null===domain?fn:domain.bind(fn):void 0},Promise.onUnhandledRejectionHandled=function(fn){var domain=getDomain();unhandledRejectionHandled="function"==typeof fn?null===domain?fn:domain.bind(fn):void 0},Promise.longStackTraces=function(){if(async.haveItemsQueued()&&debugging===!1)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/DT1qyG\n");debugging=CapturedTrace.isSupported(),debugging&&async.disableTrampolineIfNecessary()},Promise.hasLongStackTraces=function(){return debugging&&CapturedTrace.isSupported()},CapturedTrace.isSupported()||(Promise.longStackTraces=function(){},debugging=!1),function(){return debugging}}},{"./async.js":2,"./errors.js":13,"./util.js":38}],11:[function(_dereq_,module,exports){"use strict";var util=_dereq_("./util.js"),isPrimitive=util.isPrimitive;module.exports=function(Promise){var returner=function(){return this},thrower=function(){throw this},returnUndefined=function(){},throwUndefined=function(){throw void 0},wrapper=function(value,action){return 1===action?function(){throw value}:2===action?function(){return value}:void 0};Promise.prototype["return"]=Promise.prototype.thenReturn=function(value){return void 0===value?this.then(returnUndefined):isPrimitive(value)?this._then(wrapper(value,2),void 0,void 0,void 0,void 0):(value instanceof Promise&&value._ignoreRejections(),this._then(returner,void 0,void 0,value,void 0))},Promise.prototype["throw"]=Promise.prototype.thenThrow=function(reason){return void 0===reason?this.then(throwUndefined):isPrimitive(reason)?this._then(wrapper(reason,1),void 0,void 0,void 0,void 0):this._then(thrower,void 0,void 0,reason,void 0)}}},{"./util.js":38}],12:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var PromiseReduce=Promise.reduce;Promise.prototype.each=function(fn){return PromiseReduce(this,fn,null,INTERNAL)},Promise.each=function(promises,fn){return PromiseReduce(promises,fn,null,INTERNAL)}}},{}],13:[function(_dereq_,module,exports){"use strict";function subError(nameProperty,defaultMessage){function SubError(message){return this instanceof SubError?(notEnumerableProp(this,"message","string"==typeof message?message:defaultMessage),notEnumerableProp(this,"name",nameProperty),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new SubError(message)}return inherits(SubError,Error),SubError}function OperationalError(message){return this instanceof OperationalError?(notEnumerableProp(this,"name","OperationalError"),notEnumerableProp(this,"message",message),this.cause=message,this.isOperational=!0,void(message instanceof Error?(notEnumerableProp(this,"message",message.message),notEnumerableProp(this,"stack",message.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new OperationalError(message)}var _TypeError,_RangeError,es5=_dereq_("./es5.js"),Objectfreeze=es5.freeze,util=_dereq_("./util.js"),inherits=util.inherits,notEnumerableProp=util.notEnumerableProp,Warning=subError("Warning","warning"),CancellationError=subError("CancellationError","cancellation error"),TimeoutError=subError("TimeoutError","timeout error"),AggregateError=subError("AggregateError","aggregate error");try{_TypeError=TypeError,_RangeError=RangeError}catch(e){_TypeError=subError("TypeError","type error"),_RangeError=subError("RangeError","range error")}for(var methods="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),i=0;i0&&"function"==typeof arguments[last]){fn=arguments[last];var ret}for(var $_len=arguments.length,args=new Array($_len),$_i=0;$_len>$_i;++$_i)args[$_i]=arguments[$_i];fn&&args.pop();var ret=new PromiseArray(args).promise();return void 0!==fn?ret.spread(fn):ret}}},{"./util.js":38}],19:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL){function MappingPromiseArray(promises,fn,limit,_filter){this.constructor$(promises),this._promise._captureStackTrace();var domain=getDomain();this._callback=null===domain?fn:domain.bind(fn),this._preservedValues=_filter===INTERNAL?new Array(this.length()):null,this._limit=limit,this._inFlight=0,this._queue=limit>=1?[]:EMPTY_ARRAY,async.invoke(init,this,void 0)}function init(){this._init$(void 0,-2)}function map(promises,fn,options,_filter){var limit="object"==typeof options&&null!==options?options.concurrency:0;return limit="number"==typeof limit&&isFinite(limit)&&limit>=1?limit:0,new MappingPromiseArray(promises,fn,limit,_filter)}var getDomain=Promise._getDomain,async=_dereq_("./async.js"),util=_dereq_("./util.js"),tryCatch=util.tryCatch,errorObj=util.errorObj,PENDING={},EMPTY_ARRAY=[];util.inherits(MappingPromiseArray,PromiseArray),MappingPromiseArray.prototype._init=function(){},MappingPromiseArray.prototype._promiseFulfilled=function(value,index){var values=this._values,length=this.length(),preservedValues=this._preservedValues,limit=this._limit;if(values[index]===PENDING){if(values[index]=value,limit>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return}else{if(limit>=1&&this._inFlight>=limit)return values[index]=value,void this._queue.push(index);null!==preservedValues&&(preservedValues[index]=value);var callback=this._callback,receiver=this._promise._boundValue();this._promise._pushContext();var ret=tryCatch(callback).call(receiver,value,index,length);if(this._promise._popContext(),ret===errorObj)return this._reject(ret.e);var maybePromise=tryConvertToPromise(ret,this._promise);if(maybePromise instanceof Promise){if(maybePromise=maybePromise._target(),maybePromise._isPending())return limit>=1&&this._inFlight++,values[index]=PENDING,maybePromise._proxyPromiseArray(this,index);if(!maybePromise._isFulfilled())return this._reject(maybePromise._reason());ret=maybePromise._value()}values[index]=ret}var totalResolved=++this._totalResolved;totalResolved>=length&&(null!==preservedValues?this._filter(values,preservedValues):this._resolve(values))},MappingPromiseArray.prototype._drainQueue=function(){for(var queue=this._queue,limit=this._limit,values=this._values;queue.length>0&&this._inFlighti;++i)booleans[i]&&(ret[j++]=values[i]);ret.length=j,this._resolve(ret)},MappingPromiseArray.prototype.preservedValues=function(){return this._preservedValues},Promise.prototype.map=function(fn,options){return"function"!=typeof fn?apiRejection("fn must be a function\n\n See http://goo.gl/916lJJ\n"):map(this,fn,options,null).promise()},Promise.map=function(promises,fn,options,_filter){return"function"!=typeof fn?apiRejection("fn must be a function\n\n See http://goo.gl/916lJJ\n"):map(promises,fn,options,_filter).promise()}}},{"./async.js":2,"./util.js":38}],20:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,tryConvertToPromise,apiRejection){var util=_dereq_("./util.js"),tryCatch=util.tryCatch;Promise.method=function(fn){if("function"!=typeof fn)throw new Promise.TypeError("fn must be a function\n\n See http://goo.gl/916lJJ\n");return function(){var ret=new Promise(INTERNAL);ret._captureStackTrace(),ret._pushContext();var value=tryCatch(fn).apply(this,arguments);return ret._popContext(),ret._resolveFromSyncValue(value),ret}},Promise.attempt=Promise["try"]=function(fn,args,ctx){if("function"!=typeof fn)return apiRejection("fn must be a function\n\n See http://goo.gl/916lJJ\n");var ret=new Promise(INTERNAL);ret._captureStackTrace(),ret._pushContext();var value=util.isArray(args)?tryCatch(fn).apply(ctx,args):tryCatch(fn).call(ctx,args);return ret._popContext(),ret._resolveFromSyncValue(value),ret},Promise.prototype._resolveFromSyncValue=function(value){value===util.errorObj?this._rejectCallback(value.e,!1,!0):this._resolveCallback(value,!0)}}},{"./util.js":38}],21:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){function spreadAdapter(val,nodeback){var promise=this;if(!util.isArray(val))return successAdapter.call(promise,val,nodeback);var ret=tryCatch(nodeback).apply(promise._boundValue(),[null].concat(val));ret===errorObj&&async.throwLater(ret.e)}function successAdapter(val,nodeback){var promise=this,receiver=promise._boundValue(),ret=void 0===val?tryCatch(nodeback).call(receiver,null):tryCatch(nodeback).call(receiver,null,val);ret===errorObj&&async.throwLater(ret.e)}function errorAdapter(reason,nodeback){var promise=this;if(!reason){var target=promise._target(),newReason=target._getCarriedStackTrace();newReason.cause=reason,reason=newReason}var ret=tryCatch(nodeback).call(promise._boundValue(),reason);ret===errorObj&&async.throwLater(ret.e)}var util=_dereq_("./util.js"),async=_dereq_("./async.js"),tryCatch=util.tryCatch,errorObj=util.errorObj;Promise.prototype.asCallback=Promise.prototype.nodeify=function(nodeback,options){if("function"==typeof nodeback){var adapter=successAdapter;void 0!==options&&Object(options).spread&&(adapter=spreadAdapter),this._then(adapter,errorAdapter,void 0,this,nodeback)}return this}}},{"./async.js":2,"./util.js":38}],22:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray){var util=_dereq_("./util.js"),async=_dereq_("./async.js"),tryCatch=util.tryCatch,errorObj=util.errorObj;Promise.prototype.progressed=function(handler){return this._then(void 0,void 0,handler,void 0,void 0)},Promise.prototype._progress=function(progressValue){this._isFollowingOrFulfilledOrRejected()||this._target()._progressUnchecked(progressValue)},Promise.prototype._progressHandlerAt=function(index){return 0===index?this._progressHandler0:this[(index<<2)+index-5+2]},Promise.prototype._doProgressWith=function(progression){var progressValue=progression.value,handler=progression.handler,promise=progression.promise,receiver=progression.receiver,ret=tryCatch(handler).call(receiver,progressValue);if(ret===errorObj){if(null!=ret.e&&"StopProgressPropagation"!==ret.e.name){var trace=util.canAttachTrace(ret.e)?ret.e:new Error(util.toString(ret.e));promise._attachExtraTrace(trace),promise._progress(ret.e)}}else ret instanceof Promise?ret._then(promise._progress,null,null,promise,void 0):promise._progress(ret)},Promise.prototype._progressUnchecked=function(progressValue){for(var len=this._length(),progress=this._progress,i=0;len>i;i++){var handler=this._progressHandlerAt(i),promise=this._promiseAt(i);if(promise instanceof Promise)"function"==typeof handler?async.invoke(this._doProgressWith,this,{handler:handler,promise:promise,receiver:this._receiverAt(i),value:progressValue}):async.invoke(progress,promise,progressValue);else{var receiver=this._receiverAt(i);"function"==typeof handler?handler.call(receiver,progressValue,promise):receiver instanceof PromiseArray&&!receiver._isResolved()&&receiver._promiseProgressed(progressValue,promise)}}}}},{"./async.js":2,"./util.js":38}],23:[function(_dereq_,module,exports){"use strict";module.exports=function(){function Promise(resolver){if("function"!=typeof resolver)throw new TypeError("the promise constructor requires a resolver function\n\n See http://goo.gl/EC22Yn\n");if(this.constructor!==Promise)throw new TypeError("the promise constructor cannot be invoked directly\n\n See http://goo.gl/KsIlge\n");this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._progressHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,this._settledValue=void 0,resolver!==INTERNAL&&this._resolveFromResolver(resolver)}function fillTypes(value){var p=new Promise(INTERNAL);p._fulfillmentHandler0=value,p._rejectionHandler0=value,p._progressHandler0=value,p._promise0=value,p._receiver0=value,p._settledValue=value}var getDomain,makeSelfResolutionError=function(){return new TypeError("circular promise resolution chain\n\n See http://goo.gl/LhFpo0\n")},reflect=function(){return new Promise.PromiseInspection(this._target())},apiRejection=function(msg){return Promise.reject(new TypeError(msg))},util=_dereq_("./util.js");getDomain=util.isNode?function(){var ret=process.domain;return void 0===ret&&(ret=null),ret}:function(){return null},util.notEnumerableProp(Promise,"_getDomain",getDomain);var UNDEFINED_BINDING={},async=_dereq_("./async.js"),errors=_dereq_("./errors.js"),TypeError=Promise.TypeError=errors.TypeError;Promise.RangeError=errors.RangeError,Promise.CancellationError=errors.CancellationError,Promise.TimeoutError=errors.TimeoutError,Promise.OperationalError=errors.OperationalError,Promise.RejectionError=errors.OperationalError,Promise.AggregateError=errors.AggregateError;var INTERNAL=function(){},APPLY={},NEXT_FILTER={e:null},tryConvertToPromise=_dereq_("./thenables.js")(Promise,INTERNAL),PromiseArray=_dereq_("./promise_array.js")(Promise,INTERNAL,tryConvertToPromise,apiRejection),CapturedTrace=_dereq_("./captured_trace.js")(),isDebugging=_dereq_("./debuggability.js")(Promise,CapturedTrace),createContext=_dereq_("./context.js")(Promise,CapturedTrace,isDebugging),CatchFilter=_dereq_("./catch_filter.js")(NEXT_FILTER),PromiseResolver=_dereq_("./promise_resolver.js"),nodebackForPromise=PromiseResolver._nodebackForPromise,errorObj=util.errorObj,tryCatch=util.tryCatch;return Promise.prototype.toString=function(){return"[object Promise]"},Promise.prototype.caught=Promise.prototype["catch"]=function(fn){var len=arguments.length;if(len>1){var i,catchInstances=new Array(len-1),j=0;for(i=0;len-1>i;++i){var item=arguments[i];if("function"!=typeof item)return Promise.reject(new TypeError("Catch filter must inherit from Error or be a simple predicate function\n\n See http://goo.gl/o84o68\n"));catchInstances[j++]=item}catchInstances.length=j,fn=arguments[i];var catchFilter=new CatchFilter(catchInstances,fn,this);return this._then(void 0,catchFilter.doFilter,void 0,catchFilter,void 0)}return this._then(void 0,fn,void 0,void 0,void 0)},Promise.prototype.reflect=function(){return this._then(reflect,reflect,void 0,this,void 0)},Promise.prototype.then=function(didFulfill,didReject,didProgress){if(isDebugging()&&arguments.length>0&&"function"!=typeof didFulfill&&"function"!=typeof didReject){var msg=".then() only accepts functions but was passed: "+util.classString(didFulfill);arguments.length>1&&(msg+=", "+util.classString(didReject)),this._warn(msg)}return this._then(didFulfill,didReject,didProgress,void 0,void 0)},Promise.prototype.done=function(didFulfill,didReject,didProgress){var promise=this._then(didFulfill,didReject,didProgress,void 0,void 0);promise._setIsFinal()},Promise.prototype.spread=function(didFulfill,didReject){return this.all()._then(didFulfill,didReject,void 0,APPLY,void 0)},Promise.prototype.isCancellable=function(){return!this.isResolved()&&this._cancellable()},Promise.prototype.toJSON=function(){var ret={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(ret.fulfillmentValue=this.value(),ret.isFulfilled=!0):this.isRejected()&&(ret.rejectionReason=this.reason(),ret.isRejected=!0),ret},Promise.prototype.all=function(){return new PromiseArray(this).promise()},Promise.prototype.error=function(fn){return this.caught(util.originatesFromRejection,fn)},Promise.is=function(val){return val instanceof Promise},Promise.fromNode=function(fn){var ret=new Promise(INTERNAL),result=tryCatch(fn)(nodebackForPromise(ret));return result===errorObj&&ret._rejectCallback(result.e,!0,!0),ret},Promise.all=function(promises){return new PromiseArray(promises).promise()},Promise.defer=Promise.pending=function(){var promise=new Promise(INTERNAL);return new PromiseResolver(promise)},Promise.cast=function(obj){var ret=tryConvertToPromise(obj);if(!(ret instanceof Promise)){var val=ret;ret=new Promise(INTERNAL),ret._fulfillUnchecked(val)}return ret},Promise.resolve=Promise.fulfilled=Promise.cast,Promise.reject=Promise.rejected=function(reason){var ret=new Promise(INTERNAL);return ret._captureStackTrace(),ret._rejectCallback(reason,!0),ret},Promise.setScheduler=function(fn){if("function"!=typeof fn)throw new TypeError("fn must be a function\n\n See http://goo.gl/916lJJ\n");var prev=async._schedule;return async._schedule=fn,prev},Promise.prototype._then=function(didFulfill,didReject,didProgress,receiver,internalData){var haveInternalData=void 0!==internalData,ret=haveInternalData?internalData:new Promise(INTERNAL);haveInternalData||(ret._propagateFrom(this,5),ret._captureStackTrace());var target=this._target();target!==this&&(void 0===receiver&&(receiver=this._boundTo),haveInternalData||ret._setIsMigrated());var callbackIndex=target._addCallbacks(didFulfill,didReject,didProgress,ret,receiver,getDomain());return target._isResolved()&&!target._isSettlePromisesQueued()&&async.invoke(target._settlePromiseAtPostResolution,target,callbackIndex),ret},Promise.prototype._settlePromiseAtPostResolution=function(index){this._isRejectionUnhandled()&&this._unsetRejectionIsUnhandled(),this._settlePromiseAt(index)},Promise.prototype._length=function(){return 131071&this._bitField},Promise.prototype._isFollowingOrFulfilledOrRejected=function(){return(939524096&this._bitField)>0},Promise.prototype._isFollowing=function(){return 536870912===(536870912&this._bitField)},Promise.prototype._setLength=function(len){this._bitField=-131072&this._bitField|131071&len},Promise.prototype._setFulfilled=function(){this._bitField=268435456|this._bitField},Promise.prototype._setRejected=function(){this._bitField=134217728|this._bitField},Promise.prototype._setFollowing=function(){this._bitField=536870912|this._bitField},Promise.prototype._setIsFinal=function(){this._bitField=33554432|this._bitField},Promise.prototype._isFinal=function(){return(33554432&this._bitField)>0},Promise.prototype._cancellable=function(){return(67108864&this._bitField)>0},Promise.prototype._setCancellable=function(){this._bitField=67108864|this._bitField},Promise.prototype._unsetCancellable=function(){this._bitField=-67108865&this._bitField},Promise.prototype._setIsMigrated=function(){this._bitField=4194304|this._bitField},Promise.prototype._unsetIsMigrated=function(){this._bitField=-4194305&this._bitField},Promise.prototype._isMigrated=function(){return(4194304&this._bitField)>0},Promise.prototype._receiverAt=function(index){var ret=0===index?this._receiver0:this[5*index-5+4];return ret===UNDEFINED_BINDING?void 0:void 0===ret&&this._isBound()?this._boundValue():ret},Promise.prototype._promiseAt=function(index){return 0===index?this._promise0:this[5*index-5+3]},Promise.prototype._fulfillmentHandlerAt=function(index){return 0===index?this._fulfillmentHandler0:this[5*index-5+0]},Promise.prototype._rejectionHandlerAt=function(index){return 0===index?this._rejectionHandler0:this[5*index-5+1]},Promise.prototype._boundValue=function(){var ret=this._boundTo;return void 0!==ret&&ret instanceof Promise?ret.isFulfilled()?ret.value():void 0:ret},Promise.prototype._migrateCallbacks=function(follower,index){var fulfill=follower._fulfillmentHandlerAt(index),reject=follower._rejectionHandlerAt(index),progress=follower._progressHandlerAt(index),promise=follower._promiseAt(index),receiver=follower._receiverAt(index);promise instanceof Promise&&promise._setIsMigrated(),void 0===receiver&&(receiver=UNDEFINED_BINDING),this._addCallbacks(fulfill,reject,progress,promise,receiver,null)},Promise.prototype._addCallbacks=function(fulfill,reject,progress,promise,receiver,domain){var index=this._length();if(index>=131066&&(index=0,this._setLength(0)),0===index)this._promise0=promise,void 0!==receiver&&(this._receiver0=receiver),"function"!=typeof fulfill||this._isCarryingStackTrace()||(this._fulfillmentHandler0=null===domain?fulfill:domain.bind(fulfill)),"function"==typeof reject&&(this._rejectionHandler0=null===domain?reject:domain.bind(reject)),"function"==typeof progress&&(this._progressHandler0=null===domain?progress:domain.bind(progress));else{var base=5*index-5;this[base+3]=promise,this[base+4]=receiver,"function"==typeof fulfill&&(this[base+0]=null===domain?fulfill:domain.bind(fulfill)),"function"==typeof reject&&(this[base+1]=null===domain?reject:domain.bind(reject)),"function"==typeof progress&&(this[base+2]=null===domain?progress:domain.bind(progress))}return this._setLength(index+1),index},Promise.prototype._setProxyHandlers=function(receiver,promiseSlotValue){var index=this._length();if(index>=131066&&(index=0,this._setLength(0)),0===index)this._promise0=promiseSlotValue,this._receiver0=receiver;else{var base=5*index-5;this[base+3]=promiseSlotValue,this[base+4]=receiver}this._setLength(index+1)},Promise.prototype._proxyPromiseArray=function(promiseArray,index){this._setProxyHandlers(promiseArray,index)},Promise.prototype._resolveCallback=function(value,shouldBind){if(!this._isFollowingOrFulfilledOrRejected()){if(value===this)return this._rejectCallback(makeSelfResolutionError(),!1,!0);var maybePromise=tryConvertToPromise(value,this);if(!(maybePromise instanceof Promise))return this._fulfill(value);var propagationFlags=1|(shouldBind?4:0);this._propagateFrom(maybePromise,propagationFlags);var promise=maybePromise._target();if(promise._isPending()){for(var len=this._length(),i=0;len>i;++i)promise._migrateCallbacks(this,i);this._setFollowing(),this._setLength(0),this._setFollowee(promise)}else promise._isFulfilled()?this._fulfillUnchecked(promise._value()):this._rejectUnchecked(promise._reason(),promise._getCarriedStackTrace())}},Promise.prototype._rejectCallback=function(reason,synchronous,shouldNotMarkOriginatingFromRejection){shouldNotMarkOriginatingFromRejection||util.markAsOriginatingFromRejection(reason);var trace=util.ensureErrorObject(reason),hasStack=trace===reason;this._attachExtraTrace(trace,synchronous?hasStack:!1),this._reject(reason,hasStack?void 0:trace)},Promise.prototype._resolveFromResolver=function(resolver){var promise=this;this._captureStackTrace(),this._pushContext();var synchronous=!0,r=tryCatch(resolver)(function(value){null!==promise&&(promise._resolveCallback(value),promise=null)},function(reason){null!==promise&&(promise._rejectCallback(reason,synchronous),promise=null)});synchronous=!1,this._popContext(),void 0!==r&&r===errorObj&&null!==promise&&(promise._rejectCallback(r.e,!0,!0),promise=null)},Promise.prototype._settlePromiseFromHandler=function(handler,receiver,value,promise){if(!promise._isRejected()){promise._pushContext();var x;if(x=receiver!==APPLY||this._isRejected()?tryCatch(handler).call(receiver,value):tryCatch(handler).apply(this._boundValue(),value),promise._popContext(),x===errorObj||x===promise||x===NEXT_FILTER){var err=x===promise?makeSelfResolutionError():x.e;promise._rejectCallback(err,!1,!0)}else promise._resolveCallback(x)}},Promise.prototype._target=function(){for(var ret=this;ret._isFollowing();)ret=ret._followee();return ret},Promise.prototype._followee=function(){return this._rejectionHandler0},Promise.prototype._setFollowee=function(promise){this._rejectionHandler0=promise},Promise.prototype._cleanValues=function(){this._cancellable()&&(this._cancellationParent=void 0)},Promise.prototype._propagateFrom=function(parent,flags){(1&flags)>0&&parent._cancellable()&&(this._setCancellable(),this._cancellationParent=parent),(4&flags)>0&&parent._isBound()&&this._setBoundTo(parent._boundTo)},Promise.prototype._fulfill=function(value){this._isFollowingOrFulfilledOrRejected()||this._fulfillUnchecked(value)},Promise.prototype._reject=function(reason,carriedStackTrace){this._isFollowingOrFulfilledOrRejected()||this._rejectUnchecked(reason,carriedStackTrace)},Promise.prototype._settlePromiseAt=function(index){var promise=this._promiseAt(index),isPromise=promise instanceof Promise;if(isPromise&&promise._isMigrated())return promise._unsetIsMigrated(),async.invoke(this._settlePromiseAt,this,index);var handler=this._isFulfilled()?this._fulfillmentHandlerAt(index):this._rejectionHandlerAt(index),carriedStackTrace=this._isCarryingStackTrace()?this._getCarriedStackTrace():void 0,value=this._settledValue,receiver=this._receiverAt(index);this._clearCallbackDataAtIndex(index),"function"==typeof handler?isPromise?this._settlePromiseFromHandler(handler,receiver,value,promise):handler.call(receiver,value,promise):receiver instanceof PromiseArray?receiver._isResolved()||(this._isFulfilled()?receiver._promiseFulfilled(value,promise):receiver._promiseRejected(value,promise)):isPromise&&(this._isFulfilled()?promise._fulfill(value):promise._reject(value,carriedStackTrace)),index>=4&&4===(31&index)&&async.invokeLater(this._setLength,this,0)},Promise.prototype._clearCallbackDataAtIndex=function(index){if(0===index)this._isCarryingStackTrace()||(this._fulfillmentHandler0=void 0),this._rejectionHandler0=this._progressHandler0=this._receiver0=this._promise0=void 0;else{var base=5*index-5;this[base+3]=this[base+4]=this[base+0]=this[base+1]=this[base+2]=void 0}},Promise.prototype._isSettlePromisesQueued=function(){return-1073741824===(-1073741824&this._bitField)},Promise.prototype._setSettlePromisesQueued=function(){this._bitField=-1073741824|this._bitField},Promise.prototype._unsetSettlePromisesQueued=function(){this._bitField=1073741823&this._bitField},Promise.prototype._queueSettlePromises=function(){async.settlePromises(this),this._setSettlePromisesQueued()},Promise.prototype._fulfillUnchecked=function(value){if(value===this){var err=makeSelfResolutionError();return this._attachExtraTrace(err),this._rejectUnchecked(err,void 0)}this._setFulfilled(),this._settledValue=value,this._cleanValues(),this._length()>0&&this._queueSettlePromises()},Promise.prototype._rejectUncheckedCheckError=function(reason){var trace=util.ensureErrorObject(reason);this._rejectUnchecked(reason,trace===reason?void 0:trace)},Promise.prototype._rejectUnchecked=function(reason,trace){if(reason===this){var err=makeSelfResolutionError();return this._attachExtraTrace(err),this._rejectUnchecked(err)}return this._setRejected(),this._settledValue=reason,this._cleanValues(),this._isFinal()?void async.throwLater(function(e){throw"stack"in e&&async.invokeFirst(CapturedTrace.unhandledRejection,void 0,e),e},void 0===trace?reason:trace):(void 0!==trace&&trace!==reason&&this._setCarriedStackTrace(trace),void(this._length()>0?this._queueSettlePromises():this._ensurePossibleRejectionHandled()))},Promise.prototype._settlePromises=function(){this._unsetSettlePromisesQueued();for(var len=this._length(),i=0;len>i;i++)this._settlePromiseAt(i)},util.notEnumerableProp(Promise,"_makeSelfResolutionError",makeSelfResolutionError),_dereq_("./progress.js")(Promise,PromiseArray),_dereq_("./method.js")(Promise,INTERNAL,tryConvertToPromise,apiRejection),_dereq_("./bind.js")(Promise,INTERNAL,tryConvertToPromise),_dereq_("./finally.js")(Promise,NEXT_FILTER,tryConvertToPromise),_dereq_("./direct_resolve.js")(Promise),_dereq_("./synchronous_inspection.js")(Promise),_dereq_("./join.js")(Promise,PromiseArray,tryConvertToPromise,INTERNAL),Promise.Promise=Promise,_dereq_("./map.js")(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL),_dereq_("./cancel.js")(Promise),_dereq_("./using.js")(Promise,apiRejection,tryConvertToPromise,createContext),_dereq_("./generators.js")(Promise,apiRejection,INTERNAL,tryConvertToPromise),_dereq_("./nodeify.js")(Promise),_dereq_("./call_get.js")(Promise),_dereq_("./props.js")(Promise,PromiseArray,tryConvertToPromise,apiRejection),_dereq_("./race.js")(Promise,INTERNAL,tryConvertToPromise,apiRejection),_dereq_("./reduce.js")(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL),_dereq_("./settle.js")(Promise,PromiseArray),_dereq_("./some.js")(Promise,PromiseArray,apiRejection),_dereq_("./promisify.js")(Promise,INTERNAL),_dereq_("./any.js")(Promise),_dereq_("./each.js")(Promise,INTERNAL),_dereq_("./timers.js")(Promise,INTERNAL),_dereq_("./filter.js")(Promise,INTERNAL),util.toFastProperties(Promise),util.toFastProperties(Promise.prototype),fillTypes({a:1}),fillTypes({b:2}),fillTypes({c:3}),fillTypes(1),fillTypes(function(){}),fillTypes(void 0),fillTypes(!1),fillTypes(new Promise(INTERNAL)),CapturedTrace.setBounds(async.firstLineError,util.lastLineError),Promise}},{"./any.js":1,"./async.js":2,"./bind.js":3,"./call_get.js":5,"./cancel.js":6,"./captured_trace.js":7,"./catch_filter.js":8,"./context.js":9,"./debuggability.js":10,"./direct_resolve.js":11,"./each.js":12,"./errors.js":13,"./filter.js":15,"./finally.js":16,"./generators.js":17,"./join.js":18,"./map.js":19,"./method.js":20,"./nodeify.js":21,"./progress.js":22,"./promise_array.js":24,"./promise_resolver.js":25,"./promisify.js":26,"./props.js":27,"./race.js":29,"./reduce.js":30,"./settle.js":32,"./some.js":33,"./synchronous_inspection.js":34,"./thenables.js":35,"./timers.js":36,"./using.js":37,"./util.js":38}],24:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,tryConvertToPromise,apiRejection){function toResolutionValue(val){switch(val){case-2:return[];case-3:return{}}}function PromiseArray(values){var parent,promise=this._promise=new Promise(INTERNAL);values instanceof Promise&&(parent=values,promise._propagateFrom(parent,5)),this._values=values,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var util=_dereq_("./util.js"),isArray=util.isArray; -return PromiseArray.prototype.length=function(){return this._length},PromiseArray.prototype.promise=function(){return this._promise},PromiseArray.prototype._init=function init(_,resolveValueIfEmpty){var values=tryConvertToPromise(this._values,this._promise);if(values instanceof Promise){if(values=values._target(),this._values=values,!values._isFulfilled())return values._isPending()?void values._then(init,this._reject,void 0,this,resolveValueIfEmpty):void this._reject(values._reason());if(values=values._value(),!isArray(values)){var err=new Promise.TypeError("expecting an array, a promise or a thenable\n\n See http://goo.gl/s8MMhc\n");return void this.__hardReject__(err)}}else if(!isArray(values))return void this._promise._reject(apiRejection("expecting an array, a promise or a thenable\n\n See http://goo.gl/s8MMhc\n")._reason());if(0===values.length)return void(-5===resolveValueIfEmpty?this._resolveEmptyArray():this._resolve(toResolutionValue(resolveValueIfEmpty)));var len=this.getActualLength(values.length);this._length=len,this._values=this.shouldCopyValues()?new Array(len):this._values;for(var promise=this._promise,i=0;len>i;++i){var isResolved=this._isResolved(),maybePromise=tryConvertToPromise(values[i],promise);maybePromise instanceof Promise?(maybePromise=maybePromise._target(),isResolved?maybePromise._ignoreRejections():maybePromise._isPending()?maybePromise._proxyPromiseArray(this,i):maybePromise._isFulfilled()?this._promiseFulfilled(maybePromise._value(),i):this._promiseRejected(maybePromise._reason(),i)):isResolved||this._promiseFulfilled(maybePromise,i)}},PromiseArray.prototype._isResolved=function(){return null===this._values},PromiseArray.prototype._resolve=function(value){this._values=null,this._promise._fulfill(value)},PromiseArray.prototype.__hardReject__=PromiseArray.prototype._reject=function(reason){this._values=null,this._promise._rejectCallback(reason,!1,!0)},PromiseArray.prototype._promiseProgressed=function(progressValue,index){this._promise._progress({index:index,value:progressValue})},PromiseArray.prototype._promiseFulfilled=function(value,index){this._values[index]=value;var totalResolved=++this._totalResolved;totalResolved>=this._length&&this._resolve(this._values)},PromiseArray.prototype._promiseRejected=function(reason,index){this._totalResolved++,this._reject(reason)},PromiseArray.prototype.shouldCopyValues=function(){return!0},PromiseArray.prototype.getActualLength=function(len){return len},PromiseArray}},{"./util.js":38}],25:[function(_dereq_,module,exports){"use strict";function isUntypedError(obj){return obj instanceof Error&&es5.getPrototypeOf(obj)===Error.prototype}function wrapAsOperationalError(obj){var ret;if(isUntypedError(obj)){ret=new OperationalError(obj),ret.name=obj.name,ret.message=obj.message,ret.stack=obj.stack;for(var keys=es5.keys(obj),i=0;i2){for(var $_len=arguments.length,args=new Array($_len-1),$_i=1;$_len>$_i;++$_i)args[$_i-1]=arguments[$_i];promise._fulfill(args)}else promise._fulfill(value);promise=null}}}var PromiseResolver,util=_dereq_("./util.js"),maybeWrapAsError=util.maybeWrapAsError,errors=_dereq_("./errors.js"),TimeoutError=errors.TimeoutError,OperationalError=errors.OperationalError,haveGetters=util.haveGetters,es5=_dereq_("./es5.js"),rErrorKey=/^(?:name|message|stack|cause)$/;if(PromiseResolver=haveGetters?function(promise){this.promise=promise}:function(promise){this.promise=promise,this.asCallback=nodebackForPromise(promise),this.callback=this.asCallback},haveGetters){var prop={get:function(){return nodebackForPromise(this.promise)}};es5.defineProperty(PromiseResolver.prototype,"asCallback",prop),es5.defineProperty(PromiseResolver.prototype,"callback",prop)}PromiseResolver._nodebackForPromise=nodebackForPromise,PromiseResolver.prototype.toString=function(){return"[object PromiseResolver]"},PromiseResolver.prototype.resolve=PromiseResolver.prototype.fulfill=function(value){if(!(this instanceof PromiseResolver))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._resolveCallback(value)},PromiseResolver.prototype.reject=function(reason){if(!(this instanceof PromiseResolver))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._rejectCallback(reason)},PromiseResolver.prototype.progress=function(value){if(!(this instanceof PromiseResolver))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._progress(value)},PromiseResolver.prototype.cancel=function(err){this.promise.cancel(err)},PromiseResolver.prototype.timeout=function(){this.reject(new TimeoutError("timeout"))},PromiseResolver.prototype.isResolved=function(){return this.promise.isResolved()},PromiseResolver.prototype.toJSON=function(){return this.promise.toJSON()},module.exports=PromiseResolver},{"./errors.js":13,"./es5.js":14,"./util.js":38}],26:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){function propsFilter(key){return!noCopyPropsPattern.test(key)}function isPromisified(fn){try{return fn.__isPromisified__===!0}catch(e){return!1}}function hasPromisified(obj,key,suffix){var val=util.getDataPropertyOrDefault(obj,key+suffix,defaultPromisified);return val?isPromisified(val):!1}function checkValid(ret,suffix,suffixRegexp){for(var i=0;ii;i+=2){var key=methods[i],fn=methods[i+1],promisifiedKey=key+suffix;if(promisifier===makeNodePromisified)obj[promisifiedKey]=makeNodePromisified(key,THIS,key,fn,suffix);else{var promisified=promisifier(fn,function(){return makeNodePromisified(key,THIS,key,fn,suffix)});util.notEnumerableProp(promisified,"__isPromisified__",!0),obj[promisifiedKey]=promisified}}return util.toFastProperties(obj),obj}function promisify(callback,receiver){return makeNodePromisified(callback,receiver,void 0,callback)}var makeNodePromisifiedEval,THIS={},util=_dereq_("./util.js"),nodebackForPromise=_dereq_("./promise_resolver.js")._nodebackForPromise,withAppended=util.withAppended,maybeWrapAsError=util.maybeWrapAsError,canEvaluate=util.canEvaluate,TypeError=_dereq_("./errors").TypeError,defaultSuffix="Async",defaultPromisified={__isPromisified__:!0},noCopyProps=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],noCopyPropsPattern=new RegExp("^(?:"+noCopyProps.join("|")+")$"),defaultFilter=function(name){return util.isIdentifier(name)&&"_"!==name.charAt(0)&&"constructor"!==name},escapeIdentRegex=function(str){return str.replace(/([$])/,"\\$")},makeNodePromisified=canEvaluate?makeNodePromisifiedEval:makeNodePromisifiedClosure;Promise.promisify=function(fn,receiver){if("function"!=typeof fn)throw new TypeError("fn must be a function\n\n See http://goo.gl/916lJJ\n");if(isPromisified(fn))return fn;var ret=promisify(fn,arguments.length<2?THIS:receiver);return util.copyDescriptors(fn,ret,propsFilter),ret},Promise.promisifyAll=function(target,options){if("function"!=typeof target&&"object"!=typeof target)throw new TypeError("the target of promisifyAll must be an object or a function\n\n See http://goo.gl/9ITlV0\n");options=Object(options);var suffix=options.suffix;"string"!=typeof suffix&&(suffix=defaultSuffix);var filter=options.filter;"function"!=typeof filter&&(filter=defaultFilter);var promisifier=options.promisifier;if("function"!=typeof promisifier&&(promisifier=makeNodePromisified),!util.isIdentifier(suffix))throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/8FZo5V\n");for(var keys=util.inheritedDataKeys(target),i=0;ii;++i){var key=keys[i];values[i]=obj[key],values[i+len]=key}this.constructor$(values)}function props(promises){var ret,castValue=tryConvertToPromise(promises);return isObject(castValue)?(ret=castValue instanceof Promise?castValue._then(Promise.props,void 0,void 0,void 0,void 0):new PropertiesPromiseArray(castValue).promise(),castValue instanceof Promise&&ret._propagateFrom(castValue,4),ret):apiRejection("cannot await properties of a non-object\n\n See http://goo.gl/OsFKC8\n")}var util=_dereq_("./util.js"),isObject=util.isObject,es5=_dereq_("./es5.js");util.inherits(PropertiesPromiseArray,PromiseArray),PropertiesPromiseArray.prototype._init=function(){this._init$(void 0,-3)},PropertiesPromiseArray.prototype._promiseFulfilled=function(value,index){this._values[index]=value;var totalResolved=++this._totalResolved;if(totalResolved>=this._length){for(var val={},keyOffset=this.length(),i=0,len=this.length();len>i;++i)val[this._values[i+keyOffset]]=this._values[i];this._resolve(val)}},PropertiesPromiseArray.prototype._promiseProgressed=function(value,index){this._promise._progress({key:this._values[index+this.length()],value:value})},PropertiesPromiseArray.prototype.shouldCopyValues=function(){return!1},PropertiesPromiseArray.prototype.getActualLength=function(len){return len>>1},Promise.prototype.props=function(){return props(this)},Promise.props=function(promises){return props(promises)}}},{"./es5.js":14,"./util.js":38}],28:[function(_dereq_,module,exports){"use strict";function arrayMove(src,srcIndex,dst,dstIndex,len){for(var j=0;len>j;++j)dst[j+dstIndex]=src[j+srcIndex],src[j+srcIndex]=void 0}function Queue(capacity){this._capacity=capacity,this._length=0,this._front=0}Queue.prototype._willBeOverCapacity=function(size){return this._capacityi;++i){var val=promises[i];(void 0!==val||i in promises)&&Promise.cast(val)._then(fulfill,reject,void 0,ret,null)}return ret}var isArray=_dereq_("./util.js").isArray,raceLater=function(promise){return promise.then(function(array){return race(array,promise)})};Promise.race=function(promises){return race(promises,void 0)},Promise.prototype.race=function(){return race(this,void 0)}}},{"./util.js":38}],30:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL){function ReductionPromiseArray(promises,fn,accum,_each){this.constructor$(promises),this._promise._captureStackTrace(),this._preservedValues=_each===INTERNAL?[]:null,this._zerothIsAccum=void 0===accum,this._gotAccum=!1,this._reducingIndex=this._zerothIsAccum?1:0,this._valuesPhase=void 0;var maybePromise=tryConvertToPromise(accum,this._promise),rejected=!1,isPromise=maybePromise instanceof Promise;isPromise&&(maybePromise=maybePromise._target(),maybePromise._isPending()?maybePromise._proxyPromiseArray(this,-1):maybePromise._isFulfilled()?(accum=maybePromise._value(),this._gotAccum=!0):(this._reject(maybePromise._reason()),rejected=!0)),isPromise||this._zerothIsAccum||(this._gotAccum=!0);var domain=getDomain();this._callback=null===domain?fn:domain.bind(fn),this._accum=accum,rejected||async.invoke(init,this,void 0)}function init(){this._init$(void 0,-5)}function reduce(promises,fn,initialValue,_each){if("function"!=typeof fn)return apiRejection("fn must be a function\n\n See http://goo.gl/916lJJ\n");var array=new ReductionPromiseArray(promises,fn,initialValue,_each);return array.promise()}var getDomain=Promise._getDomain,async=_dereq_("./async.js"),util=_dereq_("./util.js"),tryCatch=util.tryCatch,errorObj=util.errorObj;util.inherits(ReductionPromiseArray,PromiseArray),ReductionPromiseArray.prototype._init=function(){},ReductionPromiseArray.prototype._resolveEmptyArray=function(){(this._gotAccum||this._zerothIsAccum)&&this._resolve(null!==this._preservedValues?[]:this._accum)},ReductionPromiseArray.prototype._promiseFulfilled=function(value,index){var values=this._values;values[index]=value;var valuesPhaseIndex,length=this.length(),preservedValues=this._preservedValues,isEach=null!==preservedValues,gotAccum=this._gotAccum,valuesPhase=this._valuesPhase;if(!valuesPhase)for(valuesPhase=this._valuesPhase=new Array(length),valuesPhaseIndex=0;length>valuesPhaseIndex;++valuesPhaseIndex)valuesPhase[valuesPhaseIndex]=0;if(valuesPhaseIndex=valuesPhase[index],0===index&&this._zerothIsAccum?(this._accum=value,this._gotAccum=gotAccum=!0,valuesPhase[index]=0===valuesPhaseIndex?1:2):-1===index?(this._accum=value,this._gotAccum=gotAccum=!0):0===valuesPhaseIndex?valuesPhase[index]=1:(valuesPhase[index]=2,this._accum=value),gotAccum){for(var ret,callback=this._callback,receiver=this._promise._boundValue(),i=this._reducingIndex;length>i;++i)if(valuesPhaseIndex=valuesPhase[i],2!==valuesPhaseIndex){if(1!==valuesPhaseIndex)return;if(value=values[i],this._promise._pushContext(),isEach?(preservedValues.push(value),ret=tryCatch(callback).call(receiver,value,i,length)):ret=tryCatch(callback).call(receiver,this._accum,value,i,length),this._promise._popContext(),ret===errorObj)return this._reject(ret.e);var maybePromise=tryConvertToPromise(ret,this._promise);if(maybePromise instanceof Promise){if(maybePromise=maybePromise._target(),maybePromise._isPending())return valuesPhase[i]=4,maybePromise._proxyPromiseArray(this,i);if(!maybePromise._isFulfilled())return this._reject(maybePromise._reason());ret=maybePromise._value()}this._reducingIndex=i+1,this._accum=ret}else this._reducingIndex=i+1;this._resolve(isEach?preservedValues:this._accum)}},Promise.prototype.reduce=function(fn,initialValue){return reduce(this,fn,initialValue,null)},Promise.reduce=function(promises,fn,initialValue,_each){return reduce(promises,fn,initialValue,_each)}}},{"./async.js":2,"./util.js":38}],31:[function(_dereq_,module,exports){"use strict";var schedule,util=_dereq_("./util"),noAsyncScheduler=function(){throw new Error("No async scheduler available\n\n See http://goo.gl/m3OTXk\n")};if(util.isNode&&"undefined"==typeof MutationObserver){var GlobalSetImmediate=global.setImmediate,ProcessNextTick=process.nextTick;schedule=util.isRecentNode?function(fn){GlobalSetImmediate.call(global,fn)}:function(fn){ProcessNextTick.call(process,fn)}}else"undefined"==typeof MutationObserver||"undefined"!=typeof window&&window.navigator&&window.navigator.standalone?schedule="undefined"!=typeof setImmediate?function(fn){setImmediate(fn)}:"undefined"!=typeof setTimeout?function(fn){setTimeout(fn,0)}:noAsyncScheduler:(schedule=function(fn){var div=document.createElement("div"),observer=new MutationObserver(fn);return observer.observe(div,{attributes:!0}),function(){div.classList.toggle("foo")}},schedule.isStatic=!0);module.exports=schedule},{"./util":38}],32:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray){function SettledPromiseArray(values){this.constructor$(values)}var PromiseInspection=Promise.PromiseInspection,util=_dereq_("./util.js");util.inherits(SettledPromiseArray,PromiseArray),SettledPromiseArray.prototype._promiseResolved=function(index,inspection){this._values[index]=inspection;var totalResolved=++this._totalResolved;totalResolved>=this._length&&this._resolve(this._values)},SettledPromiseArray.prototype._promiseFulfilled=function(value,index){var ret=new PromiseInspection;ret._bitField=268435456,ret._settledValue=value,this._promiseResolved(index,ret)},SettledPromiseArray.prototype._promiseRejected=function(reason,index){var ret=new PromiseInspection;ret._bitField=134217728,ret._settledValue=reason,this._promiseResolved(index,ret)},Promise.settle=function(promises){return new SettledPromiseArray(promises).promise()},Promise.prototype.settle=function(){return new SettledPromiseArray(this).promise()}}},{"./util.js":38}],33:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,apiRejection){function SomePromiseArray(values){this.constructor$(values),this._howMany=0,this._unwrap=!1,this._initialized=!1}function some(promises,howMany){if((0|howMany)!==howMany||0>howMany)return apiRejection("expecting a positive integer\n\n See http://goo.gl/1wAmHx\n");var ret=new SomePromiseArray(promises),promise=ret.promise();return ret.setHowMany(howMany),ret.init(),promise}var util=_dereq_("./util.js"),RangeError=_dereq_("./errors.js").RangeError,AggregateError=_dereq_("./errors.js").AggregateError,isArray=util.isArray;util.inherits(SomePromiseArray,PromiseArray),SomePromiseArray.prototype._init=function(){if(this._initialized){if(0===this._howMany)return void this._resolve([]);this._init$(void 0,-5);var isArrayResolved=isArray(this._values);!this._isResolved()&&isArrayResolved&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}},SomePromiseArray.prototype.init=function(){this._initialized=!0,this._init()},SomePromiseArray.prototype.setUnwrap=function(){this._unwrap=!0},SomePromiseArray.prototype.howMany=function(){return this._howMany},SomePromiseArray.prototype.setHowMany=function(count){this._howMany=count},SomePromiseArray.prototype._promiseFulfilled=function(value){this._addFulfilled(value),this._fulfilled()===this.howMany()&&(this._values.length=this.howMany(),1===this.howMany()&&this._unwrap?this._resolve(this._values[0]):this._resolve(this._values))},SomePromiseArray.prototype._promiseRejected=function(reason){if(this._addRejected(reason),this.howMany()>this._canPossiblyFulfill()){for(var e=new AggregateError,i=this.length();i0},PromiseInspection.prototype.isRejected=Promise.prototype._isRejected=function(){return(134217728&this._bitField)>0},PromiseInspection.prototype.isPending=Promise.prototype._isPending=function(){return 0===(402653184&this._bitField)},PromiseInspection.prototype.isResolved=Promise.prototype._isResolved=function(){return(402653184&this._bitField)>0},Promise.prototype.isPending=function(){return this._target()._isPending()},Promise.prototype.isRejected=function(){return this._target()._isRejected()},Promise.prototype.isFulfilled=function(){return this._target()._isFulfilled()},Promise.prototype.isResolved=function(){return this._target()._isResolved()},Promise.prototype._value=function(){return this._settledValue},Promise.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue},Promise.prototype.value=function(){var target=this._target();if(!target.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/hc1DLj\n");return target._settledValue},Promise.prototype.reason=function(){var target=this._target();if(!target.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/hPuiwB\n");return target._unsetRejectionIsUnhandled(),target._settledValue},Promise.PromiseInspection=PromiseInspection}},{}],35:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){function tryConvertToPromise(obj,context){if(isObject(obj)){if(obj instanceof Promise)return obj;if(isAnyBluebirdPromise(obj)){var ret=new Promise(INTERNAL);return obj._then(ret._fulfillUnchecked,ret._rejectUncheckedCheckError,ret._progressUnchecked,ret,null),ret}var then=util.tryCatch(getThen)(obj);if(then===errorObj){context&&context._pushContext();var ret=Promise.reject(then.e);return context&&context._popContext(),ret}if("function"==typeof then)return doThenable(obj,then,context)}return obj}function getThen(obj){return obj.then}function isAnyBluebirdPromise(obj){return hasProp.call(obj,"_promise0")}function doThenable(x,then,context){function resolveFromThenable(value){promise&&(promise._resolveCallback(value),promise=null)}function rejectFromThenable(reason){promise&&(promise._rejectCallback(reason,synchronous,!0),promise=null)}function progressFromThenable(value){promise&&"function"==typeof promise._progress&&promise._progress(value)}var promise=new Promise(INTERNAL),ret=promise;context&&context._pushContext(),promise._captureStackTrace(),context&&context._popContext();var synchronous=!0,result=util.tryCatch(then).call(x,resolveFromThenable,rejectFromThenable,progressFromThenable);return synchronous=!1,promise&&result===errorObj&&(promise._rejectCallback(result.e,!0,!0),promise=null),ret}var util=_dereq_("./util.js"),errorObj=util.errorObj,isObject=util.isObject,hasProp={}.hasOwnProperty;return tryConvertToPromise}},{"./util.js":38}],36:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){function successClear(value){var handle=this;return handle instanceof Number&&(handle=+handle),clearTimeout(handle),value}function failureClear(reason){var handle=this;throw handle instanceof Number&&(handle=+handle),clearTimeout(handle),reason}var util=_dereq_("./util.js"),TimeoutError=Promise.TimeoutError,afterTimeout=function(promise,message){if(promise.isPending()){var err;!util.isPrimitive(message)&&message instanceof Error?err=message:("string"!=typeof message&&(message="operation timed out"),err=new TimeoutError(message)),util.markAsOriginatingFromRejection(err),promise._attachExtraTrace(err),promise._cancel(err)}},afterValue=function(value){return delay(+this).thenReturn(value)},delay=Promise.delay=function(value,ms){if(void 0===ms){ms=value,value=void 0;var ret=new Promise(INTERNAL);return setTimeout(function(){ret._fulfill()},ms),ret}return ms=+ms,Promise.resolve(value)._then(afterValue,null,null,ms,void 0)};Promise.prototype.delay=function(ms){return delay(this,ms)},Promise.prototype.timeout=function(ms,message){ms=+ms;var ret=this.then().cancellable();ret._cancellationParent=this;var handle=setTimeout(function(){afterTimeout(ret,message)},ms);return ret._then(successClear,failureClear,void 0,handle,void 0)}}},{"./util.js":38}],37:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,apiRejection,tryConvertToPromise,createContext){function inspectionMapper(inspections){for(var len=inspections.length,i=0;len>i;++i){var inspection=inspections[i];if(inspection.isRejected())return Promise.reject(inspection.error());inspections[i]=inspection._settledValue}return inspections}function thrower(e){setTimeout(function(){throw e},0)}function castPreservingDisposable(thenable){var maybePromise=tryConvertToPromise(thenable);return maybePromise!==thenable&&"function"==typeof thenable._isDisposable&&"function"==typeof thenable._getDisposer&&thenable._isDisposable()&&maybePromise._setDisposable(thenable._getDisposer()),maybePromise}function dispose(resources,inspection){function iterator(){if(i>=len)return ret.resolve();var maybePromise=castPreservingDisposable(resources[i++]);if(maybePromise instanceof Promise&&maybePromise._isDisposable()){try{maybePromise=tryConvertToPromise(maybePromise._getDisposer().tryDispose(inspection),resources.promise)}catch(e){return thrower(e)}if(maybePromise instanceof Promise)return maybePromise._then(iterator,thrower,null,null,null)}iterator()}var i=0,len=resources.length,ret=Promise.defer();return iterator(),ret.promise}function disposerSuccess(value){var inspection=new PromiseInspection;return inspection._settledValue=value,inspection._bitField=268435456,dispose(this,inspection).thenReturn(value)}function disposerFail(reason){var inspection=new PromiseInspection;return inspection._settledValue=reason,inspection._bitField=134217728,dispose(this,inspection).thenThrow(reason)}function Disposer(data,promise,context){this._data=data,this._promise=promise,this._context=context}function FunctionDisposer(fn,promise,context){this.constructor$(fn,promise,context)}function maybeUnwrapDisposer(value){return Disposer.isDisposer(value)?(this.resources[this.index]._setDisposable(value),value.promise()):value}var TypeError=_dereq_("./errors.js").TypeError,inherits=_dereq_("./util.js").inherits,PromiseInspection=Promise.PromiseInspection;Disposer.prototype.data=function(){return this._data},Disposer.prototype.promise=function(){return this._promise},Disposer.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():null},Disposer.prototype.tryDispose=function(inspection){var resource=this.resource(),context=this._context;void 0!==context&&context._pushContext();var ret=null!==resource?this.doDispose(resource,inspection):null;return void 0!==context&&context._popContext(),this._promise._unsetDisposable(),this._data=null,ret},Disposer.isDisposer=function(d){return null!=d&&"function"==typeof d.resource&&"function"==typeof d.tryDispose},inherits(FunctionDisposer,Disposer),FunctionDisposer.prototype.doDispose=function(resource,inspection){var fn=this.data();return fn.call(resource,resource,inspection)},Promise.using=function(){var len=arguments.length;if(2>len)return apiRejection("you must pass at least 2 arguments to Promise.using");var fn=arguments[len-1];if("function"!=typeof fn)return apiRejection("fn must be a function\n\n See http://goo.gl/916lJJ\n");var input,spreadArgs=!0;2===len&&Array.isArray(arguments[0])?(input=arguments[0],len=input.length,spreadArgs=!1):(input=arguments,len--);for(var resources=new Array(len),i=0;len>i;++i){var resource=input[i];if(Disposer.isDisposer(resource)){var disposer=resource;resource=resource.promise(),resource._setDisposable(disposer)}else{var maybePromise=tryConvertToPromise(resource);maybePromise instanceof Promise&&(resource=maybePromise._then(maybeUnwrapDisposer,null,null,{resources:resources,index:i},void 0))}resources[i]=resource}var promise=Promise.settle(resources).then(inspectionMapper).then(function(vals){promise._pushContext();var ret;try{ret=spreadArgs?fn.apply(void 0,vals):fn.call(void 0,vals)}finally{promise._popContext()}return ret})._then(disposerSuccess,disposerFail,void 0,resources,void 0);return resources.promise=promise,promise},Promise.prototype._setDisposable=function(disposer){this._bitField=262144|this._bitField,this._disposer=disposer; -},Promise.prototype._isDisposable=function(){return(262144&this._bitField)>0},Promise.prototype._getDisposer=function(){return this._disposer},Promise.prototype._unsetDisposable=function(){this._bitField=-262145&this._bitField,this._disposer=void 0},Promise.prototype.disposer=function(fn){if("function"==typeof fn)return new FunctionDisposer(fn,this,createContext());throw new TypeError}}},{"./errors.js":13,"./util.js":38}],38:[function(_dereq_,module,exports){"use strict";function tryCatcher(){try{var target=tryCatchTarget;return tryCatchTarget=null,target.apply(this,arguments)}catch(e){return errorObj.e=e,errorObj}}function tryCatch(fn){return tryCatchTarget=fn,tryCatcher}function isPrimitive(val){return null==val||val===!0||val===!1||"string"==typeof val||"number"==typeof val}function isObject(value){return!isPrimitive(value)}function maybeWrapAsError(maybeError){return isPrimitive(maybeError)?new Error(safeToString(maybeError)):maybeError}function withAppended(target,appendee){var i,len=target.length,ret=new Array(len+1);for(i=0;len>i;++i)ret[i]=target[i];return ret[i]=appendee,ret}function getDataPropertyOrDefault(obj,key,defaultValue){if(!es5.isES5)return{}.hasOwnProperty.call(obj,key)?obj[key]:void 0;var desc=Object.getOwnPropertyDescriptor(obj,key);return null!=desc?null==desc.get&&null==desc.set?desc.value:defaultValue:void 0}function notEnumerableProp(obj,name,value){if(isPrimitive(obj))return obj;var descriptor={value:value,configurable:!0,enumerable:!1,writable:!0};return es5.defineProperty(obj,name,descriptor),obj}function thrower(r){throw r}function isClass(fn){try{if("function"==typeof fn){var keys=es5.names(fn.prototype),hasMethods=es5.isES5&&keys.length>1,hasMethodsOtherThanConstructor=keys.length>0&&!(1===keys.length&&"constructor"===keys[0]),hasThisAssignmentAndStaticMethods=thisAssignmentPattern.test(fn+"")&&es5.names(fn).length>0;if(hasMethods||hasMethodsOtherThanConstructor||hasThisAssignmentAndStaticMethods)return!0}return!1}catch(e){return!1}}function toFastProperties(obj){function f(){}f.prototype=obj;for(var l=8;l--;)new f;return obj}function isIdentifier(str){return rident.test(str)}function filledRange(count,prefix,suffix){for(var ret=new Array(count),i=0;count>i;++i)ret[i]=prefix+i+suffix;return ret}function safeToString(obj){try{return obj+""}catch(e){return"[no string representation]"}}function markAsOriginatingFromRejection(e){try{notEnumerableProp(e,"isOperational",!0)}catch(ignore){}}function originatesFromRejection(e){return null==e?!1:e instanceof Error.__BluebirdErrorTypes__.OperationalError||e.isOperational===!0}function canAttachTrace(obj){return obj instanceof Error&&es5.propertyIsWritable(obj,"stack")}function classString(obj){return{}.toString.call(obj)}function copyDescriptors(from,to,filter){for(var keys=es5.names(from),i=0;i10||version[0]>0}(),ret.isNode&&ret.toFastProperties(process);try{throw new Error}catch(e){ret.lastLineError=e}module.exports=ret},{"./es5.js":14}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise),function(global,factory){"object"==typeof module&&"object"==typeof module.exports?module.exports=global.document?factory(global,!0):function(w){if(!w.document)throw new Error("jQuery requires a window with a document");return factory(w)}:factory(global)}("undefined"!=typeof window?window:this,function(window,noGlobal){function isArraylike(obj){var length="length"in obj&&obj.length,type=jQuery.type(obj);return"function"===type||jQuery.isWindow(obj)?!1:1===obj.nodeType&&length?!0:"array"===type||0===length||"number"==typeof length&&length>0&&length-1 in obj}function winnow(elements,qualifier,not){if(jQuery.isFunction(qualifier))return jQuery.grep(elements,function(elem,i){return!!qualifier.call(elem,i,elem)!==not});if(qualifier.nodeType)return jQuery.grep(elements,function(elem){return elem===qualifier!==not});if("string"==typeof qualifier){if(risSimple.test(qualifier))return jQuery.filter(qualifier,elements,not);qualifier=jQuery.filter(qualifier,elements)}return jQuery.grep(elements,function(elem){return indexOf.call(qualifier,elem)>=0!==not})}function sibling(cur,dir){for(;(cur=cur[dir])&&1!==cur.nodeType;);return cur}function createOptions(options){var object=optionsCache[options]={};return jQuery.each(options.match(rnotwhite)||[],function(_,flag){object[flag]=!0}),object}function completed(){document.removeEventListener("DOMContentLoaded",completed,!1),window.removeEventListener("load",completed,!1),jQuery.ready()}function Data(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=jQuery.expando+Data.uid++}function dataAttr(elem,key,data){var name;if(void 0===data&&1===elem.nodeType)if(name="data-"+key.replace(rmultiDash,"-$1").toLowerCase(),data=elem.getAttribute(name),"string"==typeof data){try{data="true"===data?!0:"false"===data?!1:"null"===data?null:+data+""===data?+data:rbrace.test(data)?jQuery.parseJSON(data):data}catch(e){}data_user.set(elem,key,data)}else data=void 0;return data}function returnTrue(){return!0}function returnFalse(){return!1}function safeActiveElement(){try{return document.activeElement}catch(err){}}function manipulationTarget(elem,content){return jQuery.nodeName(elem,"table")&&jQuery.nodeName(11!==content.nodeType?content:content.firstChild,"tr")?elem.getElementsByTagName("tbody")[0]||elem.appendChild(elem.ownerDocument.createElement("tbody")):elem}function disableScript(elem){return elem.type=(null!==elem.getAttribute("type"))+"/"+elem.type,elem}function restoreScript(elem){var match=rscriptTypeMasked.exec(elem.type);return match?elem.type=match[1]:elem.removeAttribute("type"),elem}function setGlobalEval(elems,refElements){for(var i=0,l=elems.length;l>i;i++)data_priv.set(elems[i],"globalEval",!refElements||data_priv.get(refElements[i],"globalEval"))}function cloneCopyEvent(src,dest){var i,l,type,pdataOld,pdataCur,udataOld,udataCur,events;if(1===dest.nodeType){if(data_priv.hasData(src)&&(pdataOld=data_priv.access(src),pdataCur=data_priv.set(dest,pdataOld),events=pdataOld.events)){delete pdataCur.handle,pdataCur.events={};for(type in events)for(i=0,l=events[type].length;l>i;i++)jQuery.event.add(dest,type,events[type][i])}data_user.hasData(src)&&(udataOld=data_user.access(src),udataCur=jQuery.extend({},udataOld),data_user.set(dest,udataCur))}}function getAll(context,tag){var ret=context.getElementsByTagName?context.getElementsByTagName(tag||"*"):context.querySelectorAll?context.querySelectorAll(tag||"*"):[];return void 0===tag||tag&&jQuery.nodeName(context,tag)?jQuery.merge([context],ret):ret}function fixInput(src,dest){var nodeName=dest.nodeName.toLowerCase();"input"===nodeName&&rcheckableType.test(src.type)?dest.checked=src.checked:("input"===nodeName||"textarea"===nodeName)&&(dest.defaultValue=src.defaultValue)}function actualDisplay(name,doc){var style,elem=jQuery(doc.createElement(name)).appendTo(doc.body),display=window.getDefaultComputedStyle&&(style=window.getDefaultComputedStyle(elem[0]))?style.display:jQuery.css(elem[0],"display");return elem.detach(),display}function defaultDisplay(nodeName){var doc=document,display=elemdisplay[nodeName];return display||(display=actualDisplay(nodeName,doc),"none"!==display&&display||(iframe=(iframe||jQuery("'),"after"==options.previewPosition?iFrame.insertAfter(footer):iFrame.insertBefore(header),previewWindow=iFrame[iFrame.length-1].contentWindow||frame[iFrame.length-1]):altKey===!0&&(iFrame?iFrame.remove():previewWindow.close(),previewWindow=iFrame=!1),options.previewAutoRefresh||refreshPreview(),options.previewInWindow&&previewWindow.focus()}function refreshPreview(){renderPreview()}function renderPreview(){if(options.previewHandler&&"function"==typeof options.previewHandler)options.previewHandler($$.val());else if(options.previewParser&&"function"==typeof options.previewParser){var data=options.previewParser($$.val());writeInPreview(localize(data,1))}else""!==options.previewParserPath?$.ajax({type:"POST",dataType:"text",global:!1,url:options.previewParserPath,data:options.previewParserVar+"="+encodeURIComponent($$.val()),success:function(data){writeInPreview(localize(data,1))}}):template||$.ajax({url:options.previewTemplatePath,dataType:"text",global:!1,success:function(data){writeInPreview(localize(data,1).replace(//g,$$.val()))}});return!1}function writeInPreview(data){if(options.previewInElement)$(options.previewInElement).html(data);else if(previewWindow&&previewWindow.document){try{sp=previewWindow.document.documentElement.scrollTop}catch(e){sp=0}previewWindow.document.open(),previewWindow.document.write(data),previewWindow.document.close(),previewWindow.document.documentElement.scrollTop=sp}}function keyPressed(e){if(shiftKey=e.shiftKey,altKey=e.altKey,ctrlKey=e.altKey&&e.ctrlKey?!1:e.ctrlKey||e.metaKey,"keydown"===e.type){if(ctrlKey===!0&&(li=$('a[accesskey="'+(13==e.keyCode?"\\n":String.fromCharCode(e.keyCode))+'"]',header).parent("li"),0!==li.length))return ctrlKey=!1,setTimeout(function(){li.triggerHandler("mouseup")},1),!1;if(13===e.keyCode||10===e.keyCode)return ctrlKey===!0?(ctrlKey=!1,markup(options.onCtrlEnter),options.onCtrlEnter.keepDefault):shiftKey===!0?(shiftKey=!1,markup(options.onShiftEnter),options.onShiftEnter.keepDefault):(markup(options.onEnter),options.onEnter.keepDefault);if(9===e.keyCode)return 1==shiftKey||1==ctrlKey||1==altKey?!1:-1!==caretOffset?(get(),caretOffset=$$.val().length-caretOffset,set(caretOffset,0),caretOffset=-1,!1):(markup(options.onTab),options.onTab.keepDefault)}}function remove(){$$.unbind(".markItUp").removeClass("markItUpEditor"),$$.parent("div").parent("div.markItUp").parent("div").replaceWith($$),$$.data("markItUp",null)}var $$,textarea,levels,scrollPosition,caretPosition,caretOffset,clicked,hash,header,footer,previewWindow,template,iFrame,abort;if($$=$(this),textarea=this,levels=[],abort=!1,scrollPosition=caretPosition=0,caretOffset=-1,options.previewParserPath=localize(options.previewParserPath),options.previewTemplatePath=localize(options.previewTemplatePath),method)switch(method){case"remove":remove();break;case"insert":markup(params);break;default:$.error("Method "+method+" does not exist on jQuery.markItUp")}else init()})},$.fn.markItUpRemove=function(){return this.each(function(){$(this).markItUp("remove")})},$.markItUp=function(settings){var options={target:!1};return $.extend(options,settings),options.target?$(options.target).each(function(){$(this).focus(),$(this).trigger("insertion",[options])}):void $("textarea").trigger("insertion",[options])}}(jQuery),!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?module.exports=a:a(jQuery)}(function(a){function b(b){var g=b||window.event,h=i.call(arguments,1),j=0,l=0,m=0,n=0,o=0,p=0;if(b=a.event.fix(g),b.type="mousewheel","detail"in g&&(m=-1*g.detail),"wheelDelta"in g&&(m=g.wheelDelta),"wheelDeltaY"in g&&(m=g.wheelDeltaY),"wheelDeltaX"in g&&(l=-1*g.wheelDeltaX),"axis"in g&&g.axis===g.HORIZONTAL_AXIS&&(l=-1*m,m=0),j=0===m?l:m,"deltaY"in g&&(m=-1*g.deltaY,j=m),"deltaX"in g&&(l=g.deltaX,0===m&&(j=-1*l)),0!==m||0!==l){if(1===g.deltaMode){var q=a.data(this,"mousewheel-line-height");j*=q,m*=q,l*=q}else if(2===g.deltaMode){var r=a.data(this,"mousewheel-page-height");j*=r,m*=r,l*=r}if(n=Math.max(Math.abs(m),Math.abs(l)),(!f||f>n)&&(f=n,d(g,n)&&(f/=40)),d(g,n)&&(j/=40,l/=40,m/=40),j=Math[j>=1?"floor":"ceil"](j/f),l=Math[l>=1?"floor":"ceil"](l/f),m=Math[m>=1?"floor":"ceil"](m/f),k.settings.normalizeOffset&&this.getBoundingClientRect){var s=this.getBoundingClientRect();o=b.clientX-s.left,p=b.clientY-s.top}return b.deltaX=l,b.deltaY=m,b.deltaFactor=f,b.offsetX=o,b.offsetY=p,b.deltaMode=0,h.unshift(b,j,l,m),e&&clearTimeout(e),e=setTimeout(c,200),(a.event.dispatch||a.event.handle).apply(this,h)}}function c(){f=null}function d(a,b){return k.settings.adjustOldDeltas&&"mousewheel"===a.type&&b%120===0}var e,f,g=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],h="onwheel"in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"],i=Array.prototype.slice;if(a.event.fixHooks)for(var j=g.length;j;)a.event.fixHooks[g[--j]]=a.event.mouseHooks;var k=a.event.special.mousewheel={version:"3.1.12",setup:function(){if(this.addEventListener)for(var c=h.length;c;)this.addEventListener(h[--c],b,!1);else this.onmousewheel=b;a.data(this,"mousewheel-line-height",k.getLineHeight(this)),a.data(this,"mousewheel-page-height",k.getPageHeight(this))},teardown:function(){if(this.removeEventListener)for(var c=h.length;c;)this.removeEventListener(h[--c],b,!1);else this.onmousewheel=null;a.removeData(this,"mousewheel-line-height"),a.removeData(this,"mousewheel-page-height")},getLineHeight:function(b){var c=a(b),d=c["offsetParent"in a.fn?"offsetParent":"parent"]();return d.length||(d=a("body")),parseInt(d.css("fontSize"),10)||parseInt(c.css("fontSize"),10)||16},getPageHeight:function(b){return a(b).height()},settings:{adjustOldDeltas:!0,normalizeOffset:!0}};a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})}),!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?module.exports=a:a(jQuery)}(function(a){function b(b){var g=b||window.event,h=i.call(arguments,1),j=0,l=0,m=0,n=0,o=0,p=0;if(b=a.event.fix(g),b.type="mousewheel","detail"in g&&(m=-1*g.detail),"wheelDelta"in g&&(m=g.wheelDelta),"wheelDeltaY"in g&&(m=g.wheelDeltaY),"wheelDeltaX"in g&&(l=-1*g.wheelDeltaX),"axis"in g&&g.axis===g.HORIZONTAL_AXIS&&(l=-1*m,m=0),j=0===m?l:m,"deltaY"in g&&(m=-1*g.deltaY,j=m),"deltaX"in g&&(l=g.deltaX,0===m&&(j=-1*l)),0!==m||0!==l){if(1===g.deltaMode){var q=a.data(this,"mousewheel-line-height");j*=q,m*=q,l*=q}else if(2===g.deltaMode){var r=a.data(this,"mousewheel-page-height");j*=r,m*=r,l*=r}if(n=Math.max(Math.abs(m),Math.abs(l)),(!f||f>n)&&(f=n,d(g,n)&&(f/=40)),d(g,n)&&(j/=40,l/=40,m/=40),j=Math[j>=1?"floor":"ceil"](j/f),l=Math[l>=1?"floor":"ceil"](l/f),m=Math[m>=1?"floor":"ceil"](m/f),k.settings.normalizeOffset&&this.getBoundingClientRect){var s=this.getBoundingClientRect();o=b.clientX-s.left,p=b.clientY-s.top}return b.deltaX=l,b.deltaY=m,b.deltaFactor=f,b.offsetX=o,b.offsetY=p,b.deltaMode=0,h.unshift(b,j,l,m),e&&clearTimeout(e),e=setTimeout(c,200),(a.event.dispatch||a.event.handle).apply(this,h)}}function c(){f=null}function d(a,b){return k.settings.adjustOldDeltas&&"mousewheel"===a.type&&b%120===0}var e,f,g=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],h="onwheel"in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"],i=Array.prototype.slice;if(a.event.fixHooks)for(var j=g.length;j;)a.event.fixHooks[g[--j]]=a.event.mouseHooks;var k=a.event.special.mousewheel={version:"3.1.12",setup:function(){if(this.addEventListener)for(var c=h.length;c;)this.addEventListener(h[--c],b,!1);else this.onmousewheel=b;a.data(this,"mousewheel-line-height",k.getLineHeight(this)),a.data(this,"mousewheel-page-height",k.getPageHeight(this))},teardown:function(){if(this.removeEventListener)for(var c=h.length;c;)this.removeEventListener(h[--c],b,!1);else this.onmousewheel=null;a.removeData(this,"mousewheel-line-height"),a.removeData(this,"mousewheel-page-height")},getLineHeight:function(b){var c=a(b),d=c["offsetParent"in a.fn?"offsetParent":"parent"]();return d.length||(d=a("body")),parseInt(d.css("fontSize"),10)||parseInt(c.css("fontSize"),10)||16},getPageHeight:function(b){return a(b).height()},settings:{adjustOldDeltas:!0,normalizeOffset:!0}};a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})}),!function(e){"undefined"!=typeof module&&module.exports?module.exports=e:e(jQuery,window,document)}(function(e){!function(t){var o="function"==typeof define&&define.amd,a="undefined"!=typeof module&&module.exports,n="https:"==document.location.protocol?"https:":"http:",i="cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.min.js";o||(a?require("jquery-mousewheel")(e):e.event.special.mousewheel||e("head").append(decodeURI("%3Cscript src="+n+"//"+i+"%3E%3C/script%3E"))),t()}(function(){var t,o="mCustomScrollbar",a="mCS",n=".mCustomScrollbar",i={setTop:0,setLeft:0,axis:"y",scrollbarPosition:"inside",scrollInertia:950,autoDraggerLength:!0,alwaysShowScrollbar:0,snapOffset:0,mouseWheel:{enable:!0,scrollAmount:"auto",axis:"y",deltaFactor:"auto",disableOver:["select","option","keygen","datalist","textarea"]},scrollButtons:{scrollType:"stepless",scrollAmount:"auto"},keyboard:{enable:!0,scrollType:"stepless",scrollAmount:"auto"},contentTouchScroll:25,documentTouchScroll:!0,advanced:{autoScrollOnFocus:"input,textarea,select,button,datalist,keygen,a[tabindex],area,object,[contenteditable='true']",updateOnContentResize:!0,updateOnImageLoad:"auto",autoUpdateTimeout:60},theme:"light",callbacks:{onTotalScrollOffset:0,onTotalScrollBackOffset:0,alwaysTriggerOffsets:!0}},r=0,l={},s=window.attachEvent&&!window.addEventListener?1:0,c=!1,d=["mCSB_dragger_onDrag","mCSB_scrollTools_onDrag","mCS_img_loaded","mCS_disabled","mCS_destroyed","mCS_no_scrollbar","mCS-autoHide","mCS-dir-rtl","mCS_no_scrollbar_y","mCS_no_scrollbar_x","mCS_y_hidden","mCS_x_hidden","mCSB_draggerContainer","mCSB_buttonUp","mCSB_buttonDown","mCSB_buttonLeft","mCSB_buttonRight"],u={init:function(t){var t=e.extend(!0,{},i,t),o=f.call(this);if(t.live){var s=t.liveSelector||this.selector||n,c=e(s);if("off"===t.live)return void m(s);l[s]=setTimeout(function(){c.mCustomScrollbar(t),"once"===t.live&&c.length&&m(s)},500)}else m(s);return t.setWidth=t.set_width?t.set_width:t.setWidth,t.setHeight=t.set_height?t.set_height:t.setHeight,t.axis=t.horizontalScroll?"x":p(t.axis),t.scrollInertia=t.scrollInertia>0&&t.scrollInertia<17?17:t.scrollInertia,"object"!=typeof t.mouseWheel&&1==t.mouseWheel&&(t.mouseWheel={enable:!0,scrollAmount:"auto",axis:"y",preventDefault:!1,deltaFactor:"auto",normalizeDelta:!1,invert:!1}),t.mouseWheel.scrollAmount=t.mouseWheelPixels?t.mouseWheelPixels:t.mouseWheel.scrollAmount,t.mouseWheel.normalizeDelta=t.advanced.normalizeMouseWheelDelta?t.advanced.normalizeMouseWheelDelta:t.mouseWheel.normalizeDelta,t.scrollButtons.scrollType=g(t.scrollButtons.scrollType),h(t),e(o).each(function(){var o=e(this);if(!o.data(a)){o.data(a,{idx:++r,opt:t,scrollRatio:{y:null,x:null},overflowed:null,contentReset:{y:null,x:null},bindEvents:!1,tweenRunning:!1,sequential:{},langDir:o.css("direction"),cbOffsets:null,trigger:null,poll:{size:{o:0,n:0},img:{o:0,n:0},change:{o:0,n:0}}});var n=o.data(a),i=n.opt,l=o.data("mcs-axis"),s=o.data("mcs-scrollbar-position"),c=o.data("mcs-theme");l&&(i.axis=l),s&&(i.scrollbarPosition=s),c&&(i.theme=c,h(i)),v.call(this),n&&i.callbacks.onCreate&&"function"==typeof i.callbacks.onCreate&&i.callbacks.onCreate.call(this),e("#mCSB_"+n.idx+"_container img:not(."+d[2]+")").addClass(d[2]),u.update.call(null,o)}})},update:function(t,o){var n=t||f.call(this);return e(n).each(function(){var t=e(this);if(t.data(a)){var n=t.data(a),i=n.opt,r=e("#mCSB_"+n.idx+"_container"),l=e("#mCSB_"+n.idx),s=[e("#mCSB_"+n.idx+"_dragger_vertical"),e("#mCSB_"+n.idx+"_dragger_horizontal")];if(!r.length)return;n.tweenRunning&&N(t),o&&n&&i.callbacks.onBeforeUpdate&&"function"==typeof i.callbacks.onBeforeUpdate&&i.callbacks.onBeforeUpdate.call(this),t.hasClass(d[3])&&t.removeClass(d[3]),t.hasClass(d[4])&&t.removeClass(d[4]),l.css("max-height","none"),l.height()!==t.height()&&l.css("max-height",t.height()),_.call(this),"y"===i.axis||i.advanced.autoExpandHorizontalScroll||r.css("width",x(r)),n.overflowed=y.call(this),M.call(this),i.autoDraggerLength&&S.call(this),b.call(this),T.call(this);var c=[Math.abs(r[0].offsetTop),Math.abs(r[0].offsetLeft)];"x"!==i.axis&&(n.overflowed[0]?s[0].height()>s[0].parent().height()?B.call(this):(V(t,c[0].toString(),{dir:"y",dur:0,overwrite:"none"}),n.contentReset.y=null):(B.call(this),"y"===i.axis?k.call(this):"yx"===i.axis&&n.overflowed[1]&&V(t,c[1].toString(),{dir:"x",dur:0,overwrite:"none"}))),"y"!==i.axis&&(n.overflowed[1]?s[1].width()>s[1].parent().width()?B.call(this):(V(t,c[1].toString(),{dir:"x",dur:0,overwrite:"none"}),n.contentReset.x=null):(B.call(this),"x"===i.axis?k.call(this):"yx"===i.axis&&n.overflowed[0]&&V(t,c[0].toString(),{dir:"y",dur:0,overwrite:"none"}))),o&&n&&(2===o&&i.callbacks.onImageLoad&&"function"==typeof i.callbacks.onImageLoad?i.callbacks.onImageLoad.call(this):3===o&&i.callbacks.onSelectorChange&&"function"==typeof i.callbacks.onSelectorChange?i.callbacks.onSelectorChange.call(this):i.callbacks.onUpdate&&"function"==typeof i.callbacks.onUpdate&&i.callbacks.onUpdate.call(this)),j.call(this)}})},scrollTo:function(t,o){if("undefined"!=typeof t&&null!=t){var n=f.call(this);return e(n).each(function(){var n=e(this);if(n.data(a)){var i=n.data(a),r=i.opt,l={trigger:"external",scrollInertia:r.scrollInertia,scrollEasing:"mcsEaseInOut",moveDragger:!1,timeout:60,callbacks:!0,onStart:!0,onUpdate:!0,onComplete:!0},s=e.extend(!0,{},l,o),c=q.call(this,t),d=s.scrollInertia>0&&s.scrollInertia<17?17:s.scrollInertia;c[0]=Y.call(this,c[0],"y"),c[1]=Y.call(this,c[1],"x"),s.moveDragger&&(c[0]*=i.scrollRatio.y,c[1]*=i.scrollRatio.x),s.dur=d,setTimeout(function(){null!==c[0]&&"undefined"!=typeof c[0]&&"x"!==r.axis&&i.overflowed[0]&&(s.dir="y",s.overwrite="all",V(n,c[0].toString(),s)),null!==c[1]&&"undefined"!=typeof c[1]&&"y"!==r.axis&&i.overflowed[1]&&(s.dir="x",s.overwrite="none",V(n,c[1].toString(),s))},s.timeout)}})}},stop:function(){var t=f.call(this);return e(t).each(function(){var t=e(this);t.data(a)&&N(t)})},disable:function(t){var o=f.call(this);return e(o).each(function(){var o=e(this);o.data(a)&&(o.data(a),j.call(this,"remove"),k.call(this),t&&B.call(this),M.call(this,!0),o.addClass(d[3]))})},destroy:function(){var t=f.call(this);return e(t).each(function(){var n=e(this);if(n.data(a)){var i=n.data(a),r=i.opt,l=e("#mCSB_"+i.idx),s=e("#mCSB_"+i.idx+"_container"),c=e(".mCSB_"+i.idx+"_scrollbar");r.live&&m(r.liveSelector||e(t).selector),j.call(this,"remove"),k.call(this),B.call(this),n.removeData(a),K(this,"mcs"),c.remove(),s.find("img."+d[2]).removeClass(d[2]),l.replaceWith(s.contents()),n.removeClass(o+" _"+a+"_"+i.idx+" "+d[6]+" "+d[7]+" "+d[5]+" "+d[3]).addClass(d[4])}})}},f=function(){return"object"!=typeof e(this)||e(this).length<1?n:this},h=function(t){var o=["rounded","rounded-dark","rounded-dots","rounded-dots-dark"],a=["rounded-dots","rounded-dots-dark","3d","3d-dark","3d-thick","3d-thick-dark","inset","inset-dark","inset-2","inset-2-dark","inset-3","inset-3-dark"],n=["minimal","minimal-dark"],i=["minimal","minimal-dark"],r=["minimal","minimal-dark"];t.autoDraggerLength=e.inArray(t.theme,o)>-1?!1:t.autoDraggerLength,t.autoExpandScrollbar=e.inArray(t.theme,a)>-1?!1:t.autoExpandScrollbar,t.scrollButtons.enable=e.inArray(t.theme,n)>-1?!1:t.scrollButtons.enable,t.autoHideScrollbar=e.inArray(t.theme,i)>-1?!0:t.autoHideScrollbar,t.scrollbarPosition=e.inArray(t.theme,r)>-1?"outside":t.scrollbarPosition},m=function(e){l[e]&&(clearTimeout(l[e]),K(l,e))},p=function(e){return"yx"===e||"xy"===e||"auto"===e?"yx":"x"===e||"horizontal"===e?"x":"y"},g=function(e){return"stepped"===e||"pixels"===e||"step"===e||"click"===e?"stepped":"stepless"},v=function(){var t=e(this),n=t.data(a),i=n.opt,r=i.autoExpandScrollbar?" "+d[1]+"_expand":"",l=["
","
"],s="yx"===i.axis?"mCSB_vertical_horizontal":"x"===i.axis?"mCSB_horizontal":"mCSB_vertical",c="yx"===i.axis?l[0]+l[1]:"x"===i.axis?l[1]:l[0],u="yx"===i.axis?"
":"",f=i.autoHideScrollbar?" "+d[6]:"",h="x"!==i.axis&&"rtl"===n.langDir?" "+d[7]:"";i.setWidth&&t.css("width",i.setWidth),i.setHeight&&t.css("height",i.setHeight),i.setLeft="y"!==i.axis&&"rtl"===n.langDir?"989999px":i.setLeft,t.addClass(o+" _"+a+"_"+n.idx+f+h).wrapInner("
");var m=e("#mCSB_"+n.idx),p=e("#mCSB_"+n.idx+"_container");"y"===i.axis||i.advanced.autoExpandHorizontalScroll||p.css("width",x(p)),"outside"===i.scrollbarPosition?("static"===t.css("position")&&t.css("position","relative"),t.css("overflow","visible"),m.addClass("mCSB_outside").after(c)):(m.addClass("mCSB_inside").append(c),p.wrap(u)),w.call(this);var g=[e("#mCSB_"+n.idx+"_dragger_vertical"),e("#mCSB_"+n.idx+"_dragger_horizontal")];g[0].css("min-height",g[0].height()),g[1].css("min-width",g[1].width())},x=function(t){var o=[t[0].scrollWidth,Math.max.apply(Math,t.children().map(function(){return e(this).outerWidth(!0)}).get())],a=t.parent().width();return o[0]>a?o[0]:o[1]>a?o[1]:"100%"},_=function(){var t=e(this),o=t.data(a),n=o.opt,i=e("#mCSB_"+o.idx+"_container");if(n.advanced.autoExpandHorizontalScroll&&"y"!==n.axis){i.css({width:"auto","min-width":0,"overflow-x":"scroll"});var r=Math.ceil(i[0].scrollWidth);3===n.advanced.autoExpandHorizontalScroll||2!==n.advanced.autoExpandHorizontalScroll&&r>i.parent().width()?i.css({width:r,"min-width":"100%","overflow-x":"inherit"}):i.css({"overflow-x":"inherit",position:"absolute"}).wrap("
").css({width:Math.ceil(i[0].getBoundingClientRect().right+.4)-Math.floor(i[0].getBoundingClientRect().left),"min-width":"100%",position:"relative"}).unwrap()}},w=function(){var t=e(this),o=t.data(a),n=o.opt,i=e(".mCSB_"+o.idx+"_scrollbar:first"),r=ee(n.scrollButtons.tabindex)?"tabindex='"+n.scrollButtons.tabindex+"'":"",l=["","","",""],s=["x"===n.axis?l[2]:l[0],"x"===n.axis?l[3]:l[1],l[2],l[3]];n.scrollButtons.enable&&i.prepend(s[0]).append(s[1]).next(".mCSB_scrollTools").prepend(s[2]).append(s[3])},S=function(){var t=e(this),o=t.data(a),n=e("#mCSB_"+o.idx),i=e("#mCSB_"+o.idx+"_container"),r=[e("#mCSB_"+o.idx+"_dragger_vertical"),e("#mCSB_"+o.idx+"_dragger_horizontal")],l=[n.height()/i.outerHeight(!1),n.width()/i.outerWidth(!1)],c=[parseInt(r[0].css("min-height")),Math.round(l[0]*r[0].parent().height()),parseInt(r[1].css("min-width")),Math.round(l[1]*r[1].parent().width())],d=s&&c[1]r&&(r=s),c>l&&(l=c),[r>n.height(),l>n.width()]},B=function(){var t=e(this),o=t.data(a),n=o.opt,i=e("#mCSB_"+o.idx),r=e("#mCSB_"+o.idx+"_container"),l=[e("#mCSB_"+o.idx+"_dragger_vertical"),e("#mCSB_"+o.idx+"_dragger_horizontal")];if(N(t),("x"!==n.axis&&!o.overflowed[0]||"y"===n.axis&&o.overflowed[0])&&(l[0].add(r).css("top",0),V(t,"_resetY")),"y"!==n.axis&&!o.overflowed[1]||"x"===n.axis&&o.overflowed[1]){var s=dx=0;"rtl"===o.langDir&&(s=i.width()-r.outerWidth(!1),dx=Math.abs(s/o.scrollRatio.x)),r.css("left",s),l[1].css("left",dx),V(t,"_resetX")}},T=function(){function t(){r=setTimeout(function(){e.event.special.mousewheel?(clearTimeout(r),E.call(o[0])):t()},100)}var o=e(this),n=o.data(a),i=n.opt;if(!n.bindEvents){if(I.call(this),i.contentTouchScroll&&D.call(this),R.call(this),i.mouseWheel.enable){var r;t()}z.call(this),P.call(this),i.advanced.autoScrollOnFocus&&A.call(this),i.scrollButtons.enable&&H.call(this),i.keyboard.enable&&U.call(this),n.bindEvents=!0}},k=function(){var t=e(this),o=t.data(a),n=o.opt,i=a+"_"+o.idx,r=".mCSB_"+o.idx+"_scrollbar",l=e("#mCSB_"+o.idx+",#mCSB_"+o.idx+"_container,#mCSB_"+o.idx+"_container_wrapper,"+r+" ."+d[12]+",#mCSB_"+o.idx+"_dragger_vertical,#mCSB_"+o.idx+"_dragger_horizontal,"+r+">a"),s=e("#mCSB_"+o.idx+"_container");n.advanced.releaseDraggableSelectors&&l.add(e(n.advanced.releaseDraggableSelectors)),o.bindEvents&&(e(document).unbind("."+i),l.each(function(){e(this).unbind("."+i)}),clearTimeout(t[0]._focusTimeout),K(t[0],"_focusTimeout"),clearTimeout(o.sequential.step),K(o.sequential,"step"),clearTimeout(s[0].onCompleteTimeout),K(s[0],"onCompleteTimeout"),o.bindEvents=!1)},M=function(t){var o=e(this),n=o.data(a),i=n.opt,r=e("#mCSB_"+n.idx+"_container_wrapper"),l=r.length?r:e("#mCSB_"+n.idx+"_container"),s=[e("#mCSB_"+n.idx+"_scrollbar_vertical"),e("#mCSB_"+n.idx+"_scrollbar_horizontal")],c=[s[0].find(".mCSB_dragger"),s[1].find(".mCSB_dragger")];"x"!==i.axis&&(n.overflowed[0]&&!t?(s[0].add(c[0]).add(s[0].children("a")).css("display","block"),l.removeClass(d[8]+" "+d[10])):(i.alwaysShowScrollbar?(2!==i.alwaysShowScrollbar&&c[0].css("display","none"),l.removeClass(d[10])):(s[0].css("display","none"),l.addClass(d[10])),l.addClass(d[8]))),"y"!==i.axis&&(n.overflowed[1]&&!t?(s[1].add(c[1]).add(s[1].children("a")).css("display","block"),l.removeClass(d[9]+" "+d[11])):(i.alwaysShowScrollbar?(2!==i.alwaysShowScrollbar&&c[1].css("display","none"),l.removeClass(d[11])):(s[1].css("display","none"),l.addClass(d[11])),l.addClass(d[9]))),n.overflowed[0]||n.overflowed[1]?o.removeClass(d[5]):o.addClass(d[5])},O=function(e){var t=e.type;switch(t){case"pointerdown":case"MSPointerDown":case"pointermove":case"MSPointerMove":case"pointerup":case"MSPointerUp":return e.target.ownerDocument!==document?[e.originalEvent.screenY,e.originalEvent.screenX,!1]:[e.originalEvent.pageY,e.originalEvent.pageX,!1];case"touchstart":case"touchmove":case"touchend":var o=e.originalEvent.touches[0]||e.originalEvent.changedTouches[0],a=e.originalEvent.touches.length||e.originalEvent.changedTouches.length;return e.target.ownerDocument!==document?[o.screenY,o.screenX,a>1]:[o.pageY,o.pageX,a>1];default:return[e.pageY,e.pageX,!1]}},I=function(){function t(e){var t=m.find("iframe");if(t.length){var o=e?"auto":"none";t.css("pointer-events",o)}}function o(e,t,o,a){if(m[0].idleTimer=u.scrollInertia<233?250:0,n.attr("id")===h[1])var i="x",r=(n[0].offsetLeft-t+a)*d.scrollRatio.x;else var i="y",r=(n[0].offsetTop-e+o)*d.scrollRatio.y;V(l,r.toString(),{dir:i,drag:!0})}var n,i,r,l=e(this),d=l.data(a),u=d.opt,f=a+"_"+d.idx,h=["mCSB_"+d.idx+"_dragger_vertical","mCSB_"+d.idx+"_dragger_horizontal"],m=e("#mCSB_"+d.idx+"_container"),p=e("#"+h[0]+",#"+h[1]),g=u.advanced.releaseDraggableSelectors?p.add(e(u.advanced.releaseDraggableSelectors)):p;p.bind("mousedown."+f+" touchstart."+f+" pointerdown."+f+" MSPointerDown."+f,function(o){if(o.stopImmediatePropagation(),o.preventDefault(), -Z(o)){c=!0,s&&(document.onselectstart=function(){return!1}),t(!1),N(l),n=e(this);var a=n.offset(),d=O(o)[0]-a.top,f=O(o)[1]-a.left,h=n.height()+a.top,m=n.width()+a.left;h>d&&d>0&&m>f&&f>0&&(i=d,r=f),C(n,"active",u.autoExpandScrollbar)}}).bind("touchmove."+f,function(e){e.stopImmediatePropagation(),e.preventDefault();var t=n.offset(),a=O(e)[0]-t.top,l=O(e)[1]-t.left;o(i,r,a,l)}),e(document).bind("mousemove."+f+" pointermove."+f+" MSPointerMove."+f,function(e){if(n){var t=n.offset(),a=O(e)[0]-t.top,l=O(e)[1]-t.left;if(i===a&&r===l)return;o(i,r,a,l)}}).add(g).bind("mouseup."+f+" touchend."+f+" pointerup."+f+" MSPointerUp."+f,function(e){n&&(C(n,"active",u.autoExpandScrollbar),n=null),c=!1,s&&(document.onselectstart=null),t(!0)})},D=function(){function o(e){if(!$(e)||c||O(e)[2])return void(t=0);t=1,b=0,C=0,d=1,y.removeClass("mCS_touch_action");var o=I.offset();u=O(e)[0]-o.top,f=O(e)[1]-o.left,A=[O(e)[0],O(e)[1]]}function n(e){if($(e)&&!c&&!O(e)[2]&&(T.documentTouchScroll||e.preventDefault(),e.stopImmediatePropagation(),(!C||b)&&d)){g=G();var t=M.offset(),o=O(e)[0]-t.top,a=O(e)[1]-t.left,n="mcsLinearOut";if(R.push(o),E.push(a),A[2]=Math.abs(O(e)[0]-A[0]),A[3]=Math.abs(O(e)[1]-A[1]),B.overflowed[0])var i=D[0].parent().height()-D[0].height(),r=u-o>0&&o-u>-(i*B.scrollRatio.y)&&(2*A[3]0&&a-f>-(l*B.scrollRatio.x)&&(2*A[2]30)){_=1e3/(v-p);var n="mcsEaseOut",i=2.5>_,r=i?[R[R.length-2],E[E.length-2]]:[0,0];x=i?[o-r[0],a-r[1]]:[o-h,a-m];var u=[Math.abs(x[0]),Math.abs(x[1])];_=i?[Math.abs(x[0]/4),Math.abs(x[1]/4)]:[_,_];var f=[Math.abs(I[0].offsetTop)-x[0]*l(u[0]/_[0],_[0]),Math.abs(I[0].offsetLeft)-x[1]*l(u[1]/_[1],_[1])];w="yx"===T.axis?[f[0],f[1]]:"x"===T.axis?[null,f[1]]:[f[0],null],S=[4*u[0]+T.scrollInertia,4*u[1]+T.scrollInertia];var y=parseInt(T.contentTouchScroll)||0;w[0]=u[0]>y?w[0]:0,w[1]=u[1]>y?w[1]:0,B.overflowed[0]&&s(w[0],S[0],n,"y",z,!1),B.overflowed[1]&&s(w[1],S[1],n,"x",z,!1)}}}function l(e,t){var o=[1.5*t,2*t,t/1.5,t/2];return e>90?t>4?o[0]:o[3]:e>60?t>3?o[3]:o[2]:e>30?t>8?o[1]:t>6?o[0]:t>4?t:o[2]:t>8?t:o[3]}function s(e,t,o,a,n,i){e&&V(y,e.toString(),{dur:t,scrollEasing:o,dir:a,overwrite:n,drag:i})}var d,u,f,h,m,p,g,v,x,_,w,S,b,C,y=e(this),B=y.data(a),T=B.opt,k=a+"_"+B.idx,M=e("#mCSB_"+B.idx),I=e("#mCSB_"+B.idx+"_container"),D=[e("#mCSB_"+B.idx+"_dragger_vertical"),e("#mCSB_"+B.idx+"_dragger_horizontal")],R=[],E=[],L=0,z="yx"===T.axis?"none":"all",A=[],P=I.find("iframe"),H=["touchstart."+k+" pointerdown."+k+" MSPointerDown."+k,"touchmove."+k+" pointermove."+k+" MSPointerMove."+k,"touchend."+k+" pointerup."+k+" MSPointerUp."+k],U=void 0!==document.body.style.touchAction;I.bind(H[0],function(e){o(e)}).bind(H[1],function(e){n(e)}),M.bind(H[0],function(e){i(e)}).bind(H[2],function(e){r(e)}),P.length&&P.each(function(){e(this).load(function(){W(this)&&e(this.contentDocument||this.contentWindow.document).bind(H[0],function(e){o(e),i(e)}).bind(H[1],function(e){n(e)}).bind(H[2],function(e){r(e)})})})},R=function(){function o(){return window.getSelection?window.getSelection().toString():document.selection&&"Control"!=document.selection.type?document.selection.createRange().text:0}function n(e,t,o){d.type=o&&i?"stepped":"stepless",d.scrollAmount=10,F(r,e,t,"mcsLinearOut",o?60:null)}var i,r=e(this),l=r.data(a),s=l.opt,d=l.sequential,u=a+"_"+l.idx,f=e("#mCSB_"+l.idx+"_container"),h=f.parent();f.bind("mousedown."+u,function(e){t||i||(i=1,c=!0)}).add(document).bind("mousemove."+u,function(e){if(!t&&i&&o()){var a=f.offset(),r=O(e)[0]-a.top+f[0].offsetTop,c=O(e)[1]-a.left+f[0].offsetLeft;r>0&&r0&&cr?n("on",38):r>h.height()&&n("on",40)),"y"!==s.axis&&l.overflowed[1]&&(0>c?n("on",37):c>h.width()&&n("on",39)))}}).bind("mouseup."+u+" dragend."+u,function(e){t||(i&&(i=0,n("off",null)),c=!1)})},E=function(){function t(t,a){if(N(o),!L(o,t.target)){var r="auto"!==i.mouseWheel.deltaFactor?parseInt(i.mouseWheel.deltaFactor):s&&t.deltaFactor<100?100:t.deltaFactor||100,d=i.scrollInertia;if("x"===i.axis||"x"===i.mouseWheel.axis)var u="x",f=[Math.round(r*n.scrollRatio.x),parseInt(i.mouseWheel.scrollAmount)],h="auto"!==i.mouseWheel.scrollAmount?f[1]:f[0]>=l.width()?.9*l.width():f[0],m=Math.abs(e("#mCSB_"+n.idx+"_container")[0].offsetLeft),p=c[1][0].offsetLeft,g=c[1].parent().width()-c[1].width(),v=t.deltaX||t.deltaY||a;else var u="y",f=[Math.round(r*n.scrollRatio.y),parseInt(i.mouseWheel.scrollAmount)],h="auto"!==i.mouseWheel.scrollAmount?f[1]:f[0]>=l.height()?.9*l.height():f[0],m=Math.abs(e("#mCSB_"+n.idx+"_container")[0].offsetTop),p=c[0][0].offsetTop,g=c[0].parent().height()-c[0].height(),v=t.deltaY||a;"y"===u&&!n.overflowed[0]||"x"===u&&!n.overflowed[1]||((i.mouseWheel.invert||t.webkitDirectionInvertedFromDevice)&&(v=-v),i.mouseWheel.normalizeDelta&&(v=0>v?-1:1),(v>0&&0!==p||0>v&&p!==g||i.mouseWheel.preventDefault)&&(t.stopImmediatePropagation(),t.preventDefault()),t.deltaFactor<2&&!i.mouseWheel.normalizeDelta&&(h=t.deltaFactor,d=17),V(o,(m-v*h).toString(),{dir:u,dur:d}))}}if(e(this).data(a)){var o=e(this),n=o.data(a),i=n.opt,r=a+"_"+n.idx,l=e("#mCSB_"+n.idx),c=[e("#mCSB_"+n.idx+"_dragger_vertical"),e("#mCSB_"+n.idx+"_dragger_horizontal")],d=e("#mCSB_"+n.idx+"_container").find("iframe");d.length&&d.each(function(){e(this).load(function(){W(this)&&e(this.contentDocument||this.contentWindow.document).bind("mousewheel."+r,function(e,o){t(e,o)})})}),l.bind("mousewheel."+r,function(e,o){t(e,o)})}},W=function(e){var t=null;try{var o=e.contentDocument||e.contentWindow.document;t=o.body.innerHTML}catch(a){}return null!==t},L=function(t,o){var n=o.nodeName.toLowerCase(),i=t.data(a).opt.mouseWheel.disableOver,r=["select","textarea"];return e.inArray(n,i)>-1&&!(e.inArray(n,r)>-1&&!e(o).is(":focus"))},z=function(){var t,o=e(this),n=o.data(a),i=a+"_"+n.idx,r=e("#mCSB_"+n.idx+"_container"),l=r.parent(),s=e(".mCSB_"+n.idx+"_scrollbar ."+d[12]);s.bind("mousedown."+i+" touchstart."+i+" pointerdown."+i+" MSPointerDown."+i,function(o){c=!0,e(o.target).hasClass("mCSB_dragger")||(t=1)}).bind("touchend."+i+" pointerup."+i+" MSPointerUp."+i,function(e){c=!1}).bind("click."+i,function(a){if(t&&(t=0,e(a.target).hasClass(d[12])||e(a.target).hasClass("mCSB_draggerRail"))){N(o);var i=e(this),s=i.find(".mCSB_dragger");if(i.parent(".mCSB_scrollTools_horizontal").length>0){if(!n.overflowed[1])return;var c="x",u=a.pageX>s.offset().left?-1:1,f=Math.abs(r[0].offsetLeft)-.9*u*l.width()}else{if(!n.overflowed[0])return;var c="y",u=a.pageY>s.offset().top?-1:1,f=Math.abs(r[0].offsetTop)-.9*u*l.height()}V(o,f.toString(),{dir:c,scrollEasing:"mcsEaseInOut"})}})},A=function(){var t=e(this),o=t.data(a),n=o.opt,i=a+"_"+o.idx,r=e("#mCSB_"+o.idx+"_container"),l=r.parent();r.bind("focusin."+i,function(o){var a=e(document.activeElement),i=r.find(".mCustomScrollBox").length,s=0;a.is(n.advanced.autoScrollOnFocus)&&(N(t),clearTimeout(t[0]._focusTimeout),t[0]._focusTimer=i?(s+17)*i:0,t[0]._focusTimeout=setTimeout(function(){var e=[te(a)[0],te(a)[1]],o=[r[0].offsetTop,r[0].offsetLeft],i=[o[0]+e[0]>=0&&o[0]+e[0]=0&&o[0]+e[1]a");s.bind("mousedown."+r+" touchstart."+r+" pointerdown."+r+" MSPointerDown."+r+" mouseup."+r+" touchend."+r+" pointerup."+r+" MSPointerUp."+r+" mouseout."+r+" pointerout."+r+" MSPointerOut."+r+" click."+r,function(a){function r(e,o){i.scrollAmount=n.snapAmount||n.scrollButtons.scrollAmount,F(t,e,o)}if(a.preventDefault(),Z(a)){var l=e(this).attr("class");switch(i.type=n.scrollButtons.scrollType,a.type){case"mousedown":case"touchstart":case"pointerdown":case"MSPointerDown":if("stepped"===i.type)return;c=!0,o.tweenRunning=!1,r("on",l);break;case"mouseup":case"touchend":case"pointerup":case"MSPointerUp":case"mouseout":case"pointerout":case"MSPointerOut":if("stepped"===i.type)return;c=!1,i.dir&&r("off",l);break;case"click":if("stepped"!==i.type||o.tweenRunning)return;r("on",l)}}})},U=function(){function t(t){function a(e,t){r.type=i.keyboard.scrollType,r.scrollAmount=i.snapAmount||i.keyboard.scrollAmount,"stepped"===r.type&&n.tweenRunning||F(o,e,t)}switch(t.type){case"blur":n.tweenRunning&&r.dir&&a("off",null);break;case"keydown":case"keyup":var l=t.keyCode?t.keyCode:t.which,s="on";if("x"!==i.axis&&(38===l||40===l)||"y"!==i.axis&&(37===l||39===l)){if((38===l||40===l)&&!n.overflowed[0]||(37===l||39===l)&&!n.overflowed[1])return;"keyup"===t.type&&(s="off"),e(document.activeElement).is(u)||(t.preventDefault(),t.stopImmediatePropagation(),a(s,l))}else if(33===l||34===l){if((n.overflowed[0]||n.overflowed[1])&&(t.preventDefault(),t.stopImmediatePropagation()),"keyup"===t.type){N(o);var f=34===l?-1:1;if("x"===i.axis||"yx"===i.axis&&n.overflowed[1]&&!n.overflowed[0])var h="x",m=Math.abs(c[0].offsetLeft)-.9*f*d.width();else var h="y",m=Math.abs(c[0].offsetTop)-.9*f*d.height();V(o,m.toString(),{dir:h,scrollEasing:"mcsEaseInOut"})}}else if((35===l||36===l)&&!e(document.activeElement).is(u)&&((n.overflowed[0]||n.overflowed[1])&&(t.preventDefault(),t.stopImmediatePropagation()),"keyup"===t.type)){if("x"===i.axis||"yx"===i.axis&&n.overflowed[1]&&!n.overflowed[0])var h="x",m=35===l?Math.abs(d.width()-c.outerWidth(!1)):0;else var h="y",m=35===l?Math.abs(d.height()-c.outerHeight(!1)):0;V(o,m.toString(),{dir:h,scrollEasing:"mcsEaseInOut"})}}}var o=e(this),n=o.data(a),i=n.opt,r=n.sequential,l=a+"_"+n.idx,s=e("#mCSB_"+n.idx),c=e("#mCSB_"+n.idx+"_container"),d=c.parent(),u="input,textarea,select,datalist,keygen,[contenteditable='true']",f=c.find("iframe"),h=["blur."+l+" keydown."+l+" keyup."+l];f.length&&f.each(function(){e(this).load(function(){W(this)&&e(this.contentDocument||this.contentWindow.document).bind(h[0],function(e){t(e)})})}),s.attr("tabindex","0").bind(h[0],function(e){t(e)})},F=function(t,o,n,i,r){function l(e){var o="stepped"!==f.type,a=r?r:e?o?p/1.5:g:1e3/60,n=e?o?7.5:40:2.5,s=[Math.abs(h[0].offsetTop),Math.abs(h[0].offsetLeft)],d=[c.scrollRatio.y>10?10:c.scrollRatio.y,c.scrollRatio.x>10?10:c.scrollRatio.x],u="x"===f.dir[0]?s[1]+f.dir[1]*d[1]*n:s[0]+f.dir[1]*d[0]*n,m="x"===f.dir[0]?s[1]+f.dir[1]*parseInt(f.scrollAmount):s[0]+f.dir[1]*parseInt(f.scrollAmount),v="auto"!==f.scrollAmount?m:u,x=i?i:e?o?"mcsLinearOut":"mcsEaseInOut":"mcsLinear",_=e?!0:!1;return e&&17>a&&(v="x"===f.dir[0]?s[1]:s[0]),V(t,v.toString(),{dir:f.dir[0],scrollEasing:x,dur:a,onComplete:_}),e?void(f.dir=!1):(clearTimeout(f.step),void(f.step=setTimeout(function(){l()},a)))}function s(){clearTimeout(f.step),K(f,"step"),N(t)}var c=t.data(a),u=c.opt,f=c.sequential,h=e("#mCSB_"+c.idx+"_container"),m="stepped"===f.type?!0:!1,p=u.scrollInertia<26?26:u.scrollInertia,g=u.scrollInertia<1?17:u.scrollInertia;switch(o){case"on":if(f.dir=[n===d[16]||n===d[15]||39===n||37===n?"x":"y",n===d[13]||n===d[15]||38===n||37===n?-1:1],N(t),ee(n)&&"stepped"===f.type)return;l(m);break;case"off":s(),(m||c.tweenRunning&&f.dir)&&l(!0)}},q=function(t){var o=e(this).data(a).opt,n=[];return"function"==typeof t&&(t=t()),t instanceof Array?n=t.length>1?[t[0],t[1]]:"x"===o.axis?[null,t[0]]:[t[0],null]:(n[0]=t.y?t.y:t.x||"x"===o.axis?null:t,n[1]=t.x?t.x:t.y||"y"===o.axis?null:t),"function"==typeof n[0]&&(n[0]=n[0]()),"function"==typeof n[1]&&(n[1]=n[1]()),n},Y=function(t,o){if(null!=t&&"undefined"!=typeof t){var n=e(this),i=n.data(a),r=i.opt,l=e("#mCSB_"+i.idx+"_container"),s=l.parent(),c=typeof t;o||(o="x"===r.axis?"x":"y");var d="x"===o?l.outerWidth(!1):l.outerHeight(!1),f="x"===o?l[0].offsetLeft:l[0].offsetTop,h="x"===o?"left":"top";switch(c){case"function":return t();case"object":var m=t.jquery?t:e(t);if(!m.length)return;return"x"===o?te(m)[1]:te(m)[0];case"string":case"number":if(ee(t))return Math.abs(t);if(-1!==t.indexOf("%"))return Math.abs(d*parseInt(t)/100);if(-1!==t.indexOf("-="))return Math.abs(f-parseInt(t.split("-=")[1]));if(-1!==t.indexOf("+=")){var p=f+parseInt(t.split("+=")[1]);return p>=0?0:Math.abs(p)}if(-1!==t.indexOf("px")&&ee(t.split("px")[0]))return Math.abs(t.split("px")[0]);if("top"===t||"left"===t)return 0;if("bottom"===t)return Math.abs(s.height()-l.outerHeight(!1));if("right"===t)return Math.abs(s.width()-l.outerWidth(!1));if("first"===t||"last"===t){var m=l.find(":"+t);return"x"===o?te(m)[1]:te(m)[0]}return e(t).length?"x"===o?te(e(t))[1]:te(e(t))[0]:(l.css(h,t),void u.update.call(null,n[0]))}}},j=function(t){function o(){return clearTimeout(f[0].autoUpdate),0===l.parents("html").length?void(l=null):void(f[0].autoUpdate=setTimeout(function(){return c.advanced.updateOnSelectorChange&&(s.poll.change.n=i(),s.poll.change.n!==s.poll.change.o)?(s.poll.change.o=s.poll.change.n,void r(3)):c.advanced.updateOnContentResize&&(s.poll.size.n=l[0].scrollHeight+l[0].scrollWidth+f[0].offsetHeight+l[0].offsetHeight,s.poll.size.n!==s.poll.size.o)?(s.poll.size.o=s.poll.size.n,void r(1)):!c.advanced.updateOnImageLoad||"auto"===c.advanced.updateOnImageLoad&&"y"===c.axis||(s.poll.img.n=f.find("img").length,s.poll.img.n===s.poll.img.o)?void((c.advanced.updateOnSelectorChange||c.advanced.updateOnContentResize||c.advanced.updateOnImageLoad)&&o()):(s.poll.img.o=s.poll.img.n,void f.find("img").each(function(){n(this)}))},c.advanced.autoUpdateTimeout))}function n(t){function o(e,t){return function(){return t.apply(e,arguments)}}function a(){this.onload=null,e(t).addClass(d[2]),r(2)}if(e(t).hasClass(d[2]))return void r();var n=new Image;n.onload=o(n,a),n.src=t.src}function i(){c.advanced.updateOnSelectorChange===!0&&(c.advanced.updateOnSelectorChange="*");var e=0,t=f.find(c.advanced.updateOnSelectorChange);return c.advanced.updateOnSelectorChange&&t.length>0&&t.each(function(){e+=this.offsetHeight+this.offsetWidth}),e}function r(e){clearTimeout(f[0].autoUpdate),u.update.call(null,l[0],e)}var l=e(this),s=l.data(a),c=s.opt,f=e("#mCSB_"+s.idx+"_container");return t?(clearTimeout(f[0].autoUpdate),void K(f[0],"autoUpdate")):void o()},X=function(e,t,o){return Math.round(e/t)*t-o},N=function(t){var o=t.data(a),n=e("#mCSB_"+o.idx+"_container,#mCSB_"+o.idx+"_container_wrapper,#mCSB_"+o.idx+"_dragger_vertical,#mCSB_"+o.idx+"_dragger_horizontal");n.each(function(){J.call(this)})},V=function(t,o,n){function i(e){return s&&c.callbacks[e]&&"function"==typeof c.callbacks[e]}function r(){return[c.callbacks.alwaysTriggerOffsets||_>=w[0]+b,c.callbacks.alwaysTriggerOffsets||-y>=_]}function l(){var e=[h[0].offsetTop,h[0].offsetLeft],o=[v[0].offsetTop,v[0].offsetLeft],a=[h.outerHeight(!1),h.outerWidth(!1)],i=[f.height(),f.width()];t[0].mcs={content:h,top:e[0],left:e[1],draggerTop:o[0],draggerLeft:o[1],topPct:Math.round(100*Math.abs(e[0])/(Math.abs(a[0])-i[0])),leftPct:Math.round(100*Math.abs(e[1])/(Math.abs(a[1])-i[1])),direction:n.dir}}var s=t.data(a),c=s.opt,d={trigger:"internal",dir:"y",scrollEasing:"mcsEaseOut",drag:!1,dur:c.scrollInertia,overwrite:"all",callbacks:!0,onStart:!0,onUpdate:!0,onComplete:!0},n=e.extend(d,n),u=[n.dur,n.drag?0:n.dur],f=e("#mCSB_"+s.idx),h=e("#mCSB_"+s.idx+"_container"),m=h.parent(),p=c.callbacks.onTotalScrollOffset?q.call(t,c.callbacks.onTotalScrollOffset):[0,0],g=c.callbacks.onTotalScrollBackOffset?q.call(t,c.callbacks.onTotalScrollBackOffset):[0,0];if(s.trigger=n.trigger,(0!==m.scrollTop()||0!==m.scrollLeft())&&(e(".mCSB_"+s.idx+"_scrollbar").css("visibility","visible"),m.scrollTop(0).scrollLeft(0)),"_resetY"!==o||s.contentReset.y||(i("onOverflowYNone")&&c.callbacks.onOverflowYNone.call(t[0]),s.contentReset.y=1),"_resetX"!==o||s.contentReset.x||(i("onOverflowXNone")&&c.callbacks.onOverflowXNone.call(t[0]),s.contentReset.x=1),"_resetY"!==o&&"_resetX"!==o){switch(!s.contentReset.y&&t[0].mcs||!s.overflowed[0]||(i("onOverflowY")&&c.callbacks.onOverflowY.call(t[0]),s.contentReset.x=null),!s.contentReset.x&&t[0].mcs||!s.overflowed[1]||(i("onOverflowX")&&c.callbacks.onOverflowX.call(t[0]),s.contentReset.x=null),c.snapAmount&&(o=X(o,c.snapAmount,c.snapOffset)),n.dir){case"x":var v=e("#mCSB_"+s.idx+"_dragger_horizontal"),x="left",_=h[0].offsetLeft,w=[f.width()-h.outerWidth(!1),v.parent().width()-v.width()],S=[o,0===o?0:o/s.scrollRatio.x],b=p[1],y=g[1],B=b>0?b/s.scrollRatio.x:0,T=y>0?y/s.scrollRatio.x:0;break;case"y":var v=e("#mCSB_"+s.idx+"_dragger_vertical"),x="top",_=h[0].offsetTop,w=[f.height()-h.outerHeight(!1),v.parent().height()-v.height()],S=[o,0===o?0:o/s.scrollRatio.y],b=p[0],y=g[0],B=b>0?b/s.scrollRatio.y:0,T=y>0?y/s.scrollRatio.y:0}S[1]<0||0===S[0]&&0===S[1]?S=[0,0]:S[1]>=w[1]?S=[w[0],w[1]]:S[0]=-S[0],t[0].mcs||(l(),i("onInit")&&c.callbacks.onInit.call(t[0])),clearTimeout(h[0].onCompleteTimeout),(s.tweenRunning||!(0===_&&S[0]>=0||_===w[0]&&S[0]<=w[0]))&&(Q(v[0],x,Math.round(S[1]),u[1],n.scrollEasing),Q(h[0],x,Math.round(S[0]),u[0],n.scrollEasing,n.overwrite,{onStart:function(){n.callbacks&&n.onStart&&!s.tweenRunning&&(i("onScrollStart")&&(l(),c.callbacks.onScrollStart.call(t[0])),s.tweenRunning=!0,C(v),s.cbOffsets=r())},onUpdate:function(){n.callbacks&&n.onUpdate&&i("whileScrolling")&&(l(),c.callbacks.whileScrolling.call(t[0]))},onComplete:function(){if(n.callbacks&&n.onComplete){"yx"===c.axis&&clearTimeout(h[0].onCompleteTimeout);var e=h[0].idleTimer||0;h[0].onCompleteTimeout=setTimeout(function(){i("onScroll")&&(l(),c.callbacks.onScroll.call(t[0])),i("onTotalScroll")&&S[1]>=w[1]-B&&s.cbOffsets[0]&&(l(),c.callbacks.onTotalScroll.call(t[0])),i("onTotalScrollBack")&&S[1]<=T&&s.cbOffsets[1]&&(l(),c.callbacks.onTotalScrollBack.call(t[0])),s.tweenRunning=!1,h[0].idleTimer=0,C(v,"hide")},e)}}}))}},Q=function(e,t,o,a,n,i,r){function l(){S.stop||(x||m.call(),x=G()-v,s(),x>=S.time&&(S.time=x>S.time?x+f-(x-S.time):x+f-1,S.time0?(S.currVal=u(S.time,_,b,a,n),w[t]=Math.round(S.currVal)+"px"):w[t]=o+"px",p.call()}function c(){f=1e3/60,S.time=x+f,h=window.requestAnimationFrame?window.requestAnimationFrame:function(e){return s(),setTimeout(e,.01)},S.id=h(l)}function d(){null!=S.id&&(window.requestAnimationFrame?window.cancelAnimationFrame(S.id):clearTimeout(S.id),S.id=null)}function u(e,t,o,a,n){switch(n){case"linear":case"mcsLinear":return o*e/a+t;case"mcsLinearOut":return e/=a,e--,o*Math.sqrt(1-e*e)+t;case"easeInOutSmooth":return e/=a/2,1>e?o/2*e*e+t:(e--,-o/2*(e*(e-2)-1)+t);case"easeInOutStrong":return e/=a/2,1>e?o/2*Math.pow(2,10*(e-1))+t:(e--,o/2*(-Math.pow(2,-10*e)+2)+t);case"easeInOut":case"mcsEaseInOut":return e/=a/2,1>e?o/2*e*e*e+t:(e-=2,o/2*(e*e*e+2)+t);case"easeOutSmooth":return e/=a,e--,-o*(e*e*e*e-1)+t;case"easeOutStrong":return o*(-Math.pow(2,-10*e/a)+1)+t;case"easeOut":case"mcsEaseOut":default:var i=(e/=a)*e,r=i*e;return t+o*(.499999999999997*r*i+-2.5*i*i+5.5*r+-6.5*i+4*e)}}e._mTween||(e._mTween={top:{},left:{}});var f,h,r=r||{},m=r.onStart||function(){},p=r.onUpdate||function(){},g=r.onComplete||function(){},v=G(),x=0,_=e.offsetTop,w=e.style,S=e._mTween[t];"left"===t&&(_=e.offsetLeft);var b=o-_;S.stop=0,"none"!==i&&d(),c()},G=function(){return window.performance&&window.performance.now?window.performance.now():window.performance&&window.performance.webkitNow?window.performance.webkitNow():Date.now?Date.now():(new Date).getTime()},J=function(){var e=this;e._mTween||(e._mTween={top:{},left:{}});for(var t=["top","left"],o=0;o=0&&a[0]+te(n)[0]=0&&a[1]+te(n)[1]i;i++)callback.call(null,i,obj[i])}function handleStackInfo(stackInfo,options){var frames=[];stackInfo.stack&&stackInfo.stack.length&&each(stackInfo.stack,function(i,stack){var frame=normalizeFrame(stack);frame&&frames.push(frame)}),triggerEvent("handle",{stackInfo:stackInfo,options:options}),processException(stackInfo.name,stackInfo.message,stackInfo.url,stackInfo.lineno,frames,options)}function normalizeFrame(frame){if(frame.url){var i,normalized={filename:frame.url,lineno:frame.line,colno:frame.column,"function":frame.func||"?"},context=extractContextFromFrame(frame);if(context){var keys=["pre_context","context_line","post_context"];for(i=3;i--;)normalized[keys[i]]=context[i]}return normalized.in_app=!(globalOptions.includePaths.test&&!globalOptions.includePaths.test(normalized.filename)||/(Raven|TraceKit)\./.test(normalized["function"])||/raven\.(min\.)?js$/.test(normalized.filename)),normalized}}function extractContextFromFrame(frame){if(frame.context&&globalOptions.fetchContext){for(var context=frame.context,pivot=~~(context.length/2),i=context.length,isMinified=!1;i--;)if(context[i].length>300){isMinified=!0;break}if(isMinified){if(isUndefined(frame.column))return;return[[],context[pivot].substr(frame.column,50),[]]}return[context.slice(0,pivot),context[pivot],context.slice(pivot+1)]}}function processException(type,message,fileurl,lineno,frames,options){var stacktrace,fullMessage;globalOptions.ignoreErrors.test&&globalOptions.ignoreErrors.test(message)||(message+="",message=truncate(message,globalOptions.maxMessageLength),fullMessage=type+": "+message,fullMessage=truncate(fullMessage,globalOptions.maxMessageLength),frames&&frames.length?(fileurl=frames[0].filename||fileurl,frames.reverse(),stacktrace={frames:frames}):fileurl&&(stacktrace={frames:[{filename:fileurl,lineno:lineno,in_app:!0}]}),globalOptions.ignoreUrls.test&&globalOptions.ignoreUrls.test(fileurl)||(!globalOptions.whitelistUrls.test||globalOptions.whitelistUrls.test(fileurl))&&send(objectMerge({exception:{type:type,value:message},stacktrace:stacktrace,culprit:fileurl,message:fullMessage},options)))}function objectMerge(obj1,obj2){return obj2?(each(obj2,function(key,value){obj1[key]=value}),obj1):obj1}function truncate(str,max){return str.length<=max?str:str.substr(0,max)+"…"}function now(){return+new Date}function getHttpData(){if(document.location&&document.location.href){var http={headers:{"User-Agent":navigator.userAgent}};return http.url=document.location.href,document.referrer&&(http.headers.Referer=document.referrer),http}}function send(data){var baseData={project:globalProject,logger:globalOptions.logger,platform:"javascript"},http=getHttpData();http&&(baseData.request=http),data=objectMerge(baseData,data),data.tags=objectMerge(objectMerge({},globalOptions.tags),data.tags),data.extra=objectMerge(objectMerge({},globalOptions.extra),data.extra),data.extra=objectMerge({"session:duration":now()-startTime},data.extra),isEmptyObject(data.tags)&&delete data.tags,globalUser&&(data.user=globalUser),globalOptions.release&&(data.release=globalOptions.release),isFunction(globalOptions.dataCallback)&&(data=globalOptions.dataCallback(data)||data),data&&!isEmptyObject(data)&&(!isFunction(globalOptions.shouldSendCallback)||globalOptions.shouldSendCallback(data))&&(lastEventId=data.event_id||(data.event_id=uuid4()),logDebug("debug","Raven about to send:",data),isSetup()&&(globalOptions.transport||makeRequest)({url:globalServer,auth:{sentry_version:"4",sentry_client:"raven-js/"+Raven.VERSION,sentry_key:globalKey},data:data,options:globalOptions,onSuccess:function(){triggerEvent("success",{data:data,src:globalServer})},onError:function(){triggerEvent("failure",{data:data,src:globalServer})}}))}function makeRequest(opts){opts.auth.sentry_data=JSON.stringify(opts.data);var img=newImage(),src=opts.url+"?"+urlencode(opts.auth);(opts.options.crossOrigin||""===opts.options.crossOrigin)&&(img.crossOrigin=opts.options.crossOrigin),img.onload=opts.onSuccess,img.onerror=img.onabort=opts.onError,img.src=src}function newImage(){return document.createElement("img")}function isSetup(){return hasJSON?globalServer?!0:(ravenNotConfiguredError||logDebug("error","Error: Raven has not been configured."),ravenNotConfiguredError=!0,!1):!1}function joinRegExp(patterns){for(var pattern,sources=[],i=0,len=patterns.length;len>i;i++)pattern=patterns[i],isString(pattern)?sources.push(pattern.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1")):pattern&&pattern.source&&sources.push(pattern.source);return new RegExp(sources.join("|"),"i")}function uuid4(){var crypto=window.crypto||window.msCrypto;if(!isUndefined(crypto)&&crypto.getRandomValues){var arr=new Uint16Array(8);crypto.getRandomValues(arr),arr[3]=4095&arr[3]|16384,arr[4]=16383&arr[4]|32768;var pad=function(num){for(var v=num.toString(16);v.length<4;)v="0"+v;return v};return pad(arr[0])+pad(arr[1])+pad(arr[2])+pad(arr[3])+pad(arr[4])+pad(arr[5])+pad(arr[6])+pad(arr[7])}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=16*Math.random()|0,v="x"==c?r:3&r|8;return v.toString(16)})}function logDebug(level){originalConsoleMethods[level]&&Raven.debug&&originalConsoleMethods[level].apply(originalConsole,_slice.call(arguments,1))}function afterLoad(){var RavenConfig=window.RavenConfig;RavenConfig&&Raven.config(RavenConfig.dsn,RavenConfig.config).install()}function urlencode(o){var pairs=[];return each(o,function(key,value){pairs.push(encodeURIComponent(key)+"="+encodeURIComponent(value))}),pairs.join("&")}var TraceKit={remoteFetching:!1,collectWindowErrors:!0,linesOfContext:7,debug:!1},_slice=[].slice,UNKNOWN_FUNCTION="?";TraceKit.wrap=function(func){function wrapped(){try{return func.apply(this,arguments)}catch(e){throw TraceKit.report(e),e}}return wrapped},TraceKit.report=function(){function subscribe(handler){installGlobalHandler(),handlers.push(handler)}function unsubscribe(handler){for(var i=handlers.length-1;i>=0;--i)handlers[i]===handler&&handlers.splice(i,1)}function unsubscribeAll(){uninstallGlobalHandler(),handlers=[]}function notifyHandlers(stack,isWindowError){var exception=null;if(!isWindowError||TraceKit.collectWindowErrors){for(var i in handlers)if(hasKey(handlers,i))try{handlers[i].apply(null,[stack].concat(_slice.call(arguments,2)))}catch(inner){exception=inner}if(exception)throw exception}}function traceKitWindowOnError(message,url,lineNo,colNo,ex){var stack=null;if(lastExceptionStack)TraceKit.computeStackTrace.augmentStackTraceWithInitialElement(lastExceptionStack,url,lineNo,message),processLastException();else if(ex)stack=TraceKit.computeStackTrace(ex),notifyHandlers(stack,!0);else{var location={url:url,line:lineNo,column:colNo};location.func=TraceKit.computeStackTrace.guessFunctionName(location.url,location.line),location.context=TraceKit.computeStackTrace.gatherContext(location.url,location.line),stack={message:message,url:document.location.href,stack:[location]},notifyHandlers(stack,!0)}return _oldOnerrorHandler?_oldOnerrorHandler.apply(this,arguments):!1}function installGlobalHandler(){_onErrorHandlerInstalled||(_oldOnerrorHandler=window.onerror,window.onerror=traceKitWindowOnError,_onErrorHandlerInstalled=!0)}function uninstallGlobalHandler(){_onErrorHandlerInstalled&&(window.onerror=_oldOnerrorHandler,_onErrorHandlerInstalled=!1,_oldOnerrorHandler=undefined)}function processLastException(){var _lastExceptionStack=lastExceptionStack,_lastArgs=lastArgs;lastArgs=null,lastExceptionStack=null,lastException=null,notifyHandlers.apply(null,[_lastExceptionStack,!1].concat(_lastArgs))}function report(ex,rethrow){var args=_slice.call(arguments,1);if(lastExceptionStack){if(lastException===ex)return;processLastException()}var stack=TraceKit.computeStackTrace(ex);if(lastExceptionStack=stack,lastException=ex,lastArgs=args,window.setTimeout(function(){lastException===ex&&processLastException()},stack.incomplete?2e3:0),rethrow!==!1)throw ex}var _oldOnerrorHandler,_onErrorHandlerInstalled,handlers=[],lastArgs=null,lastException=null,lastExceptionStack=null;return report.subscribe=subscribe,report.unsubscribe=unsubscribe,report.uninstall=unsubscribeAll,report}(),TraceKit.computeStackTrace=function(){function loadSource(url){if(!TraceKit.remoteFetching)return"";try{var getXHR=function(){try{return new window.XMLHttpRequest}catch(e){return new window.ActiveXObject("Microsoft.XMLHTTP")}},request=getXHR();return request.open("GET",url,!1),request.send(""),request.responseText}catch(e){return""}}function getSource(url){if(!isString(url))return[];if(!hasKey(sourceCache,url)){var source="",domain="";try{domain=document.domain}catch(e){}-1!==url.indexOf(domain)&&(source=loadSource(url)),sourceCache[url]=source?source.split("\n"):[]; -}return sourceCache[url]}function guessFunctionName(url,lineNo){var m,reFunctionArgNames=/function ([^(]*)\(([^)]*)\)/,reGuessFunction=/['"]?([0-9A-Za-z$_]+)['"]?\s*[:=]\s*(function|eval|new Function)/,line="",maxLines=10,source=getSource(url);if(!source.length)return UNKNOWN_FUNCTION;for(var i=0;maxLines>i;++i)if(line=source[lineNo-i]+line,!isUndefined(line)){if(m=reGuessFunction.exec(line))return m[1];if(m=reFunctionArgNames.exec(line))return m[1]}return UNKNOWN_FUNCTION}function gatherContext(url,line){var source=getSource(url);if(!source.length)return null;var context=[],linesBefore=Math.floor(TraceKit.linesOfContext/2),linesAfter=linesBefore+TraceKit.linesOfContext%2,start=Math.max(0,line-linesBefore-1),end=Math.min(source.length,line+linesAfter-1);line-=1;for(var i=start;end>i;++i)isUndefined(source[i])||context.push(source[i]);return context.length>0?context:null}function escapeRegExp(text){return text.replace(/[\-\[\]{}()*+?.,\\\^$|#]/g,"\\$&")}function escapeCodeAsRegExpForMatchingInsideHTML(body){return escapeRegExp(body).replace("<","(?:<|<)").replace(">","(?:>|>)").replace("&","(?:&|&)").replace('"','(?:"|")').replace(/\s+/g,"\\s+")}function findSourceInUrls(re,urls){for(var source,m,i=0,j=urls.length;j>i;++i)if((source=getSource(urls[i])).length&&(source=source.join("\n"),m=re.exec(source)))return{url:urls[i],line:source.substring(0,m.index).split("\n").length,column:m.index-source.lastIndexOf("\n",m.index)-1};return null}function findSourceInLine(fragment,url,line){var m,source=getSource(url),re=new RegExp("\\b"+escapeRegExp(fragment)+"\\b");return line-=1,source&&source.length>line&&(m=re.exec(source[line]))?m.index:null}function findSourceByFunctionBody(func){for(var body,re,parts,result,urls=[window.location.href],scripts=document.getElementsByTagName("script"),code=""+func,codeRE=/^function(?:\s+([\w$]+))?\s*\(([\w\s,]*)\)\s*\{\s*(\S[\s\S]*\S)\s*\}\s*$/,eventRE=/^function on([\w$]+)\s*\(event\)\s*\{\s*(\S[\s\S]*\S)\s*\}\s*$/,i=0;i):(\d+)(?::(\d+))?\)?\s*$/i,gecko=/^\s*(.*?)(?:\((.*?)\))?@((?:file|https?|chrome).*?):(\d+)(?::(\d+))?\s*$/i,winjs=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:ms-appx|http|https):.*?):(\d+)(?::(\d+))?\)?\s*$/i,lines=ex.stack.split("\n"),stack=[],reference=/^(.*) is undefined$/.exec(ex.message),i=0,j=lines.length;j>i;++i){if(parts=gecko.exec(lines[i]))element={url:parts[3],func:parts[1]||UNKNOWN_FUNCTION,args:parts[2]?parts[2].split(","):"",line:+parts[4],column:parts[5]?+parts[5]:null};else if(parts=chrome.exec(lines[i]))element={url:parts[2],func:parts[1]||UNKNOWN_FUNCTION,line:+parts[3],column:parts[4]?+parts[4]:null};else{if(!(parts=winjs.exec(lines[i])))continue;element={url:parts[2],func:parts[1]||UNKNOWN_FUNCTION,line:+parts[3],column:parts[4]?+parts[4]:null}}!element.func&&element.line&&(element.func=guessFunctionName(element.url,element.line)),element.line&&(element.context=gatherContext(element.url,element.line)),stack.push(element)}return stack.length?(stack[0].line&&!stack[0].column&&reference?stack[0].column=findSourceInLine(reference[1],stack[0].url,stack[0].line):stack[0].column||isUndefined(ex.columnNumber)||(stack[0].column=ex.columnNumber+1),{name:ex.name,message:ex.message,url:document.location.href,stack:stack}):null}}function computeStackTraceFromStacktraceProp(ex){var stacktrace=ex.stacktrace;if(!isUndefined(ex.stacktrace)&&ex.stacktrace){for(var parts,testRE=/ line (\d+), column (\d+) in (?:]+)>|([^\)]+))\((.*)\) in (.*):\s*$/i,lines=stacktrace.split("\n"),stack=[],i=0,j=lines.length;j>i;i+=2)if(parts=testRE.exec(lines[i])){var element={line:+parts[1],column:+parts[2],func:parts[3]||parts[4],args:parts[5]?parts[5].split(","):[],url:parts[6]};if(!element.func&&element.line&&(element.func=guessFunctionName(element.url,element.line)),element.line)try{element.context=gatherContext(element.url,element.line)}catch(exc){}element.context||(element.context=[lines[i+1]]),stack.push(element)}return stack.length?{name:ex.name,message:ex.message,url:document.location.href,stack:stack}:null}}function computeStackTraceFromOperaMultiLineMessage(ex){var lines=ex.message.split("\n");if(lines.length<4)return null;var parts,i,len,source,lineRE1=/^\s*Line (\d+) of linked script ((?:file|https?)\S+)(?:: in function (\S+))?\s*$/i,lineRE2=/^\s*Line (\d+) of inline#(\d+) script in ((?:file|https?)\S+)(?:: in function (\S+))?\s*$/i,lineRE3=/^\s*Line (\d+) of function script\s*$/i,stack=[],scripts=document.getElementsByTagName("script"),inlineScriptBlocks=[];for(i in scripts)hasKey(scripts,i)&&!scripts[i].src&&inlineScriptBlocks.push(scripts[i]);for(i=2,len=lines.length;len>i;i+=2){var item=null;if(parts=lineRE1.exec(lines[i]))item={url:parts[2],func:parts[3],line:+parts[1]};else if(parts=lineRE2.exec(lines[i])){item={url:parts[3],func:parts[4]};var relativeLine=+parts[1],script=inlineScriptBlocks[parts[2]-1];if(script&&(source=getSource(item.url))){source=source.join("\n");var pos=source.indexOf(script.innerText);pos>=0&&(item.line=relativeLine+source.substring(0,pos).split("\n").length)}}else if(parts=lineRE3.exec(lines[i])){var url=window.location.href.replace(/#.*$/,""),line=parts[1],re=new RegExp(escapeCodeAsRegExpForMatchingInsideHTML(lines[i+1]));source=findSourceInUrls(re,[url]),item={url:url,line:source?source.line:line,func:""}}if(item){item.func||(item.func=guessFunctionName(item.url,item.line));var context=gatherContext(item.url,item.line),midline=context?context[Math.floor(context.length/2)]:null;context&&midline.replace(/^\s*/,"")===lines[i+1].replace(/^\s*/,"")?item.context=context:item.context=[lines[i+1]],stack.push(item)}}return stack.length?{name:ex.name,message:lines[0],url:document.location.href,stack:stack}:null}function augmentStackTraceWithInitialElement(stackInfo,url,lineNo,message){var initial={url:url,line:lineNo};if(initial.url&&initial.line){stackInfo.incomplete=!1,initial.func||(initial.func=guessFunctionName(initial.url,initial.line)),initial.context||(initial.context=gatherContext(initial.url,initial.line));var reference=/ '([^']+)' /.exec(message);if(reference&&(initial.column=findSourceInLine(reference[1],initial.url,initial.line)),stackInfo.stack.length>0&&stackInfo.stack[0].url===initial.url){if(stackInfo.stack[0].line===initial.line)return!1;if(!stackInfo.stack[0].line&&stackInfo.stack[0].func===initial.func)return stackInfo.stack[0].line=initial.line,stackInfo.stack[0].context=initial.context,!1}return stackInfo.stack.unshift(initial),stackInfo.partial=!0,!0}return stackInfo.incomplete=!0,!1}function computeStackTraceByWalkingCallerChain(ex,depth){for(var parts,item,source,functionName=/function\s+([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*)?\s*\(/i,stack=[],funcs={},recursion=!1,curr=computeStackTraceByWalkingCallerChain.caller;curr&&!recursion;curr=curr.caller)if(curr!==computeStackTrace&&curr!==TraceKit.report){if(item={url:null,func:UNKNOWN_FUNCTION,line:null,column:null},curr.name?item.func=curr.name:(parts=functionName.exec(curr.toString()))&&(item.func=parts[1]),"undefined"==typeof item.func)try{item.func=parts.input.substring(0,parts.input.indexOf("{"))}catch(e){}if(source=findSourceByFunctionBody(curr)){item.url=source.url,item.line=source.line,item.func===UNKNOWN_FUNCTION&&(item.func=guessFunctionName(item.url,item.line));var reference=/ '([^']+)' /.exec(ex.message||ex.description);reference&&(item.column=findSourceInLine(reference[1],source.url,source.line))}funcs[""+curr]?recursion=!0:funcs[""+curr]=!0,stack.push(item)}depth&&stack.splice(0,depth);var result={name:ex.name,message:ex.message,url:document.location.href,stack:stack};return augmentStackTraceWithInitialElement(result,ex.sourceURL||ex.fileName,ex.line||ex.lineNumber,ex.message||ex.description),result}function computeStackTrace(ex,depth){var stack=null;depth=null==depth?0:+depth;try{if(stack=computeStackTraceFromStacktraceProp(ex))return stack}catch(e){if(TraceKit.debug)throw e}try{if(stack=computeStackTraceFromStackProp(ex))return stack}catch(e){if(TraceKit.debug)throw e}try{if(stack=computeStackTraceFromOperaMultiLineMessage(ex))return stack}catch(e){if(TraceKit.debug)throw e}try{if(stack=computeStackTraceByWalkingCallerChain(ex,depth+1))return stack}catch(e){if(TraceKit.debug)throw e}return{name:ex.name,message:ex.message,url:document.location.href}}var sourceCache={};return computeStackTrace.augmentStackTraceWithInitialElement=augmentStackTraceWithInitialElement,computeStackTrace.computeStackTraceFromStackProp=computeStackTraceFromStackProp,computeStackTrace.guessFunctionName=guessFunctionName,computeStackTrace.gatherContext=gatherContext,computeStackTrace}();var lastCapturedException,lastEventId,globalServer,globalUser,globalKey,globalProject,_Raven=window.Raven,hasJSON=!("object"!=typeof JSON||!JSON.stringify),globalOptions={logger:"javascript",ignoreErrors:[],ignoreUrls:[],whitelistUrls:[],includePaths:[],crossOrigin:"anonymous",collectWindowErrors:!0,tags:{},maxMessageLength:100,extra:{}},isRavenInstalled=!1,objectPrototype=Object.prototype,originalConsole=window.console||{},originalConsoleMethods={},startTime=now();for(var method in originalConsole)originalConsoleMethods[method]=originalConsole[method];var Raven={VERSION:"1.1.22",debug:!0,noConflict:function(){return window.Raven=_Raven,Raven},config:function(dsn,options){if(globalServer)return logDebug("error","Error: Raven has already been configured"),Raven;if(!dsn)return Raven;var uri=parseDSN(dsn),lastSlash=uri.path.lastIndexOf("/"),path=uri.path.substr(1,lastSlash);return options&&each(options,function(key,value){globalOptions[key]=value}),globalOptions.ignoreErrors.push(/^Script error\.?$/),globalOptions.ignoreErrors.push(/^Javascript error: Script error\.? on line 0$/),globalOptions.ignoreErrors=joinRegExp(globalOptions.ignoreErrors),globalOptions.ignoreUrls=globalOptions.ignoreUrls.length?joinRegExp(globalOptions.ignoreUrls):!1,globalOptions.whitelistUrls=globalOptions.whitelistUrls.length?joinRegExp(globalOptions.whitelistUrls):!1,globalOptions.includePaths=joinRegExp(globalOptions.includePaths),globalKey=uri.user,globalProject=uri.path.substr(lastSlash+1),globalServer="//"+uri.host+(uri.port?":"+uri.port:"")+"/"+path+"api/"+globalProject+"/store/",uri.protocol&&(globalServer=uri.protocol+":"+globalServer),globalOptions.fetchContext&&(TraceKit.remoteFetching=!0),globalOptions.linesOfContext&&(TraceKit.linesOfContext=globalOptions.linesOfContext),TraceKit.collectWindowErrors=!!globalOptions.collectWindowErrors,Raven},install:function(){return isSetup()&&!isRavenInstalled&&(TraceKit.report.subscribe(handleStackInfo),isRavenInstalled=!0),Raven},context:function(options,func,args){return isFunction(options)&&(args=func||[],func=options,options=undefined),Raven.wrap(options,func).apply(this,args)},wrap:function(options,func){function wrapped(){for(var args=[],i=arguments.length,deep=!options||options&&options.deep!==!1;i--;)args[i]=deep?Raven.wrap(options,arguments[i]):arguments[i];try{return func.apply(this,args)}catch(e){throw Raven.captureException(e,options),e}}if(isUndefined(func)&&!isFunction(options))return options;if(isFunction(options)&&(func=options,options=undefined),!isFunction(func))return func;if(func.__raven__)return func;for(var property in func)hasKey(func,property)&&(wrapped[property]=func[property]);return wrapped.__raven__=!0,wrapped.__inner__=func,wrapped},uninstall:function(){return TraceKit.report.uninstall(),isRavenInstalled=!1,Raven},captureException:function(ex,options){if(!isError(ex))return Raven.captureMessage(ex,options);lastCapturedException=ex;try{var stack=TraceKit.computeStackTrace(ex);handleStackInfo(stack,options)}catch(ex1){if(ex!==ex1)throw ex1}return Raven},captureMessage:function(msg,options){return globalOptions.ignoreErrors.test&&globalOptions.ignoreErrors.test(msg)?void 0:(send(objectMerge({message:msg+""},options)),Raven)},setUserContext:function(user){return globalUser=user,Raven},setExtraContext:function(extra){return globalOptions.extra=extra||{},Raven},setTagsContext:function(tags){return globalOptions.tags=tags||{},Raven},setReleaseContext:function(release){return globalOptions.release=release,Raven},setDataCallback:function(callback){return globalOptions.dataCallback=callback,Raven},setShouldSendCallback:function(callback){return globalOptions.shouldSendCallback=callback,Raven},lastException:function(){return lastCapturedException},lastEventId:function(){return lastEventId},isSetup:function(){return isSetup()}};Raven.setUser=Raven.setUserContext;var dsnKeys="source protocol user pass host port path".split(" "),dsnPattern=/^(?:(\w+):)?\/\/(?:(\w+)(:\w+)?@)?([\w\.-]+)(?::(\d+))?(\/.*)/;RavenConfigError.prototype=new Error,RavenConfigError.prototype.constructor=RavenConfigError;var ravenNotConfiguredError;afterLoad(),"function"==typeof define&&define.amd?(window.Raven=Raven,define("raven",[],function(){return Raven})):"object"==typeof module?module.exports=Raven:"object"==typeof exports?exports=Raven:window.Raven=Raven}("undefined"!=typeof window?window:this),function(window,undefined){var gEval=function(js){(window.execScript||function(js){window.eval.call(window,js)})(js)},isA=function(a,b){return a instanceof(b||Array)},D=document,getElementsByTagName="getElementsByTagName",length="length",readyState="readyState",onreadystatechange="onreadystatechange",scripts=D[getElementsByTagName]("script"),scriptTag=scripts[scripts[length]-1],script=scriptTag.innerHTML.replace(/^\s+|\s+$/g,"");if(!window.ljs){var checkLoaded=scriptTag.src.match(/checkLoaded/)?1:0,header=D[getElementsByTagName]("head")[0]||D.documentElement,urlParse=function(url){var parts={};return parts.u=url.replace(/#(=)?([^#]*)?/g,function(m,a,b){return parts[a?"f":"i"]=b,""}),parts},appendElmt=function(type,attrs,cb){var i,e=D.createElement(type);cb&&(e[readyState]?e[onreadystatechange]=function(){("loaded"===e[readyState]||"complete"===e[readyState])&&(e[onreadystatechange]=null,cb())}:e.onload=cb);for(i in attrs)attrs[i]&&(e[i]=attrs[i]);header.appendChild(e)},load=function(url,cb){if(this.aliases&&this.aliases[url]){var args=this.aliases[url].slice(0);return isA(args)||(args=[args]),cb&&args.push(cb),this.load.apply(this,args)}if(isA(url)){for(var l=url[length];l--;)this.load(url[l]);return cb&&url.push(cb),this.load.apply(this,url)}return url.match(/\.css\b/)?this.loadcss(url,cb):this.loadjs(url,cb)},loaded={},loader={aliases:{},loadjs:function(url,cb){var parts=urlParse(url);return url=parts.u,loaded[url]===!0?(cb&&cb(),this):loaded[url]!==undefined?(cb&&(loaded[url]=function(ocb,cb){return function(){ocb&&ocb(),cb&&cb()}}(loaded[url],cb)),this):(loaded[url]=function(cb){return function(){loaded[url]=!0,cb&&cb()}}(cb),cb=function(){loaded[url]()},appendElmt("script",{type:"text/javascript",src:url,id:parts.i,onerror:function(error){if(parts.f){var c=error.currentTarget;c.parentNode.removeChild(c),appendElmt("script",{type:"text/javascript",src:parts.f,id:parts.i},cb)}}},cb),this)},loadcss:function(url,cb){var parts=urlParse(url);return url=parts.u,loaded[url]||appendElmt("link",{type:"text/css",rel:"stylesheet",href:url,id:parts.i}),loaded[url]=!0,cb&&cb(),this},load:function(){var argv=arguments,argc=argv[length];return 1===argc&&isA(argv[0],Function)?(argv[0](),this):(load.call(this,argv[0],1>=argc?undefined:function(){loader.load.apply(loader,[].slice.call(argv,1))}),this)},addAliases:function(aliases){for(var i in aliases)this.aliases[i]=isA(aliases[i])?aliases[i].slice(0):aliases[i];return this}};if(checkLoaded){var i,l,links,url;for(i=0,l=scripts[length];l>i;i++)(url=scripts[i].getAttribute("src"))&&(loaded[url.replace(/#.*$/,"")]=!0);for(links=D[getElementsByTagName]("link"),i=0,l=links[length];l>i;i++)("stylesheet"===links[i].rel||"text/css"===links[i].type)&&(loaded[links[i].getAttribute("href").replace(/#.*$/,"")]=!0)}window.ljs=loader}script&&gEval(script)}(window),MessageFormat.locale.af=function(n){return 1===n?"one":"other"},MessageFormat.locale.am=function(n){return 0===n||1==n?"one":"other"},MessageFormat.locale.ar=function(n){return 0===n?"zero":1==n?"one":2==n?"two":n%100>=3&&10>=n%100&&n==Math.floor(n)?"few":n%100>=11&&99>=n%100&&n==Math.floor(n)?"many":"other"},MessageFormat.locale.bg=function(n){return 1===n?"one":"other"},MessageFormat.locale.bn=function(n){return 1===n?"one":"other"},MessageFormat.locale.br=function(n){return 0===n?"zero":1==n?"one":2==n?"two":3==n?"few":6==n?"many":"other"},MessageFormat.locale.ca=function(n){return 1===n?"one":"other"},MessageFormat.locale.cs=function(n){return 1==n?"one":2==n||3==n||4==n?"few":"other"},MessageFormat.locale.cy=function(n){return 0===n?"zero":1==n?"one":2==n?"two":3==n?"few":6==n?"many":"other"},MessageFormat.locale.da=function(n){return 1===n?"one":"other"},MessageFormat.locale.de=function(n){return 1===n?"one":"other"},MessageFormat.locale.el=function(n){return 1===n?"one":"other"},MessageFormat.locale.en=function(n){return 1===n?"one":"other"},MessageFormat.locale.es=function(n){return 1===n?"one":"other"},MessageFormat.locale.et=function(n){return 1===n?"one":"other"},MessageFormat.locale.eu=function(n){return 1===n?"one":"other"},MessageFormat.locale.fa=function(n){return"other"},MessageFormat.locale.fi=function(n){return 1===n?"one":"other"},MessageFormat.locale.fil=function(n){return 0===n||1==n?"one":"other"},MessageFormat.locale.fr=function(n){return 0===n||1==n?"one":"other"},MessageFormat.locale.ga=function(n){return 1==n?"one":2==n?"two":"other"},MessageFormat.locale.gl=function(n){return 1===n?"one":"other"},MessageFormat.locale.gsw=function(n){return 1===n?"one":"other"},MessageFormat.locale.gu=function(n){return 1===n?"one":"other"},MessageFormat.locale.he=function(n){return 1===n?"one":"other"},MessageFormat.locale.hi=function(n){return 0===n||1==n?"one":"other"},MessageFormat.locale.hr=function(n){return n%10==1&&n%100!=11?"one":n%10>=2&&4>=n%10&&(12>n%100||n%100>14)&&n==Math.floor(n)?"few":n%10===0||n%10>=5&&9>=n%10||n%100>=11&&14>=n%100&&n==Math.floor(n)?"many":"other"},MessageFormat.locale.hu=function(n){return"other"},MessageFormat.locale.id=function(n){return"other"},MessageFormat.locale["in"]=function(n){return"other"},MessageFormat.locale.is=function(n){return 1===n?"one":"other"},MessageFormat.locale.it=function(n){return 1===n?"one":"other"},MessageFormat.locale.iw=function(n){return 1===n?"one":"other"},MessageFormat.locale.ja=function(n){return"other"},MessageFormat.locale.kn=function(n){return"other"},MessageFormat.locale.ko=function(n){return"other"},MessageFormat.locale.lag=function(n){return 0===n?"zero":n>0&&2>n?"one":"other"},MessageFormat.locale.ln=function(n){return 0===n||1==n?"one":"other"},MessageFormat.locale.lt=function(n){return n%10==1&&(11>n%100||n%100>19)?"one":n%10>=2&&9>=n%10&&(11>n%100||n%100>19)&&n==Math.floor(n)?"few":"other"},MessageFormat.locale.lv=function(n){return 0===n?"zero":n%10==1&&n%100!=11?"one":"other"},MessageFormat.locale.mk=function(n){return n%10==1&&11!=n?"one":"other"},MessageFormat.locale.ml=function(n){return 1===n?"one":"other"},MessageFormat.locale.mo=function(n){return 1==n?"one":0===n||1!=n&&n%100>=1&&19>=n%100&&n==Math.floor(n)?"few":"other"},MessageFormat.locale.mr=function(n){return 1===n?"one":"other"},MessageFormat.locale.ms=function(n){return"other"},MessageFormat.locale.mt=function(n){return 1==n?"one":0===n||n%100>=2&&4>=n%100&&n==Math.floor(n)?"few":n%100>=11&&19>=n%100&&n==Math.floor(n)?"many":"other"},MessageFormat.locale.nl=function(n){return 1===n?"one":"other"},MessageFormat.locale.no=function(n){return 1===n?"one":"other"},MessageFormat.locale.or=function(n){return 1===n?"one":"other"},MessageFormat.locale.pl=function(n){return 1==n?"one":n%10>=2&&4>=n%10&&(12>n%100||n%100>14)&&n==Math.floor(n)?"few":n%10===0||1!=n&&n%10==1||(n%10>=5&&9>=n%10||n%100>=12&&14>=n%100)&&n==Math.floor(n)?"many":"other"},MessageFormat.locale.pt=function(n){return 1===n?"one":"other"},MessageFormat.locale.ro=function(n){return 1==n?"one":0===n||1!=n&&n%100>=1&&19>=n%100&&n==Math.floor(n)?"few":"other"},MessageFormat.locale.ru=function(n){return n%10==1&&n%100!=11?"one":n%10>=2&&4>=n%10&&(12>n%100||n%100>14)&&n==Math.floor(n)?"few":n%10===0||n%10>=5&&9>=n%10||n%100>=11&&14>=n%100&&n==Math.floor(n)?"many":"other"},MessageFormat.locale.shi=function(n){return n>=0&&1>=n?"one":n>=2&&10>=n&&n==Math.floor(n)?"few":"other"},MessageFormat.locale.sk=function(n){return 1==n?"one":2==n||3==n||4==n?"few":"other"},MessageFormat.locale.sl=function(n){return n%100==1?"one":n%100==2?"two":n%100==3||n%100==4?"few":"other"},MessageFormat.locale.sq=function(n){return 1===n?"one":"other"},MessageFormat.locale.sr=function(n){return n%10==1&&n%100!=11?"one":n%10>=2&&4>=n%10&&(12>n%100||n%100>14)&&n==Math.floor(n)?"few":n%10===0||n%10>=5&&9>=n%10||n%100>=11&&14>=n%100&&n==Math.floor(n)?"many":"other"},MessageFormat.locale.sv=function(n){return 1===n?"one":"other"},MessageFormat.locale.sw=function(n){return 1===n?"one":"other"},MessageFormat.locale.ta=function(n){return 1===n?"one":"other"},MessageFormat.locale.te=function(n){return 1===n?"one":"other"},MessageFormat.locale.th=function(n){return"other"},MessageFormat.locale.tl=function(n){return 0===n||1==n?"one":"other"},MessageFormat.locale.tr=function(n){return"other"},MessageFormat.locale.uk=function(n){return n%10==1&&n%100!=11?"one":n%10>=2&&4>=n%10&&(12>n%100||n%100>14)&&n==Math.floor(n)?"few":n%10===0||n%10>=5&&9>=n%10||n%100>=11&&14>=n%100&&n==Math.floor(n)?"many":"other"},MessageFormat.locale.ur=function(n){return 1===n?"one":"other"},MessageFormat.locale.vi=function(n){return"other"},MessageFormat.locale.zh=function(n){return"other"};var mod;mod=angular.module("infinite-scroll",[]),mod.value("THROTTLE_MILLISECONDS",null),mod.directive("infiniteScroll",["$rootScope","$window","$interval","THROTTLE_MILLISECONDS",function($rootScope,$window,$interval,THROTTLE_MILLISECONDS){return{scope:{infiniteScroll:"&",infiniteScrollContainer:"=",infiniteScrollDistance:"=",infiniteScrollDisabled:"=",infiniteScrollUseDocumentBottom:"=",infiniteScrollListenForEvent:"@"},link:function(scope,elem,attrs){var changeContainer,checkWhenEnabled,container,handleInfiniteScrollContainer,handleInfiniteScrollDisabled,handleInfiniteScrollDistance,handleInfiniteScrollUseDocumentBottom,handler,height,immediateCheck,offsetTop,pageYOffset,scrollDistance,scrollEnabled,throttle,unregisterEventListener,useDocumentBottom,windowElement;return windowElement=angular.element($window),scrollDistance=null,scrollEnabled=null,checkWhenEnabled=null,container=null,immediateCheck=!0,useDocumentBottom=!1,unregisterEventListener=null,height=function(elem){return elem=elem[0]||elem,isNaN(elem.offsetHeight)?elem.document.documentElement.clientHeight:elem.offsetHeight},offsetTop=function(elem){return elem[0].getBoundingClientRect&&!elem.css("none")?elem[0].getBoundingClientRect().top+pageYOffset(elem):void 0},pageYOffset=function(elem){return elem=elem[0]||elem,isNaN(window.pageYOffset)?elem.document.documentElement.scrollTop:elem.ownerDocument.defaultView.pageYOffset},handler=function(){var containerBottom,containerTopOffset,elementBottom,remaining,shouldScroll;return container===windowElement?(containerBottom=height(container)+pageYOffset(container[0].document.documentElement),elementBottom=offsetTop(elem)+height(elem)):(containerBottom=height(container),containerTopOffset=0,void 0!==offsetTop(container)&&(containerTopOffset=offsetTop(container)),elementBottom=offsetTop(elem)-containerTopOffset+height(elem)),useDocumentBottom&&(elementBottom=height((elem[0].ownerDocument||elem[0].document).documentElement)),remaining=elementBottom-containerBottom,shouldScroll=remaining<=height(container)*scrollDistance+1,shouldScroll?(checkWhenEnabled=!0,scrollEnabled?scope.$$phase||$rootScope.$$phase?scope.infiniteScroll():scope.$apply(scope.infiniteScroll):void 0):checkWhenEnabled=!1},throttle=function(func,wait){var later,previous,timeout;return timeout=null,previous=0,later=function(){var context;return previous=(new Date).getTime(),$interval.cancel(timeout),timeout=null,func.call(),context=null},function(){var now,remaining;return now=(new Date).getTime(),remaining=wait-(now-previous),0>=remaining?(clearTimeout(timeout),$interval.cancel(timeout),timeout=null,previous=now,func.call()):timeout?void 0:timeout=$interval(later,remaining,1)}},null!=THROTTLE_MILLISECONDS&&(handler=throttle(handler,THROTTLE_MILLISECONDS)),scope.$on("$destroy",function(){return container.unbind("scroll",handler),null!=unregisterEventListener?(unregisterEventListener(),unregisterEventListener=null):void 0}),handleInfiniteScrollDistance=function(v){return scrollDistance=parseFloat(v)||0},scope.$watch("infiniteScrollDistance",handleInfiniteScrollDistance),handleInfiniteScrollDistance(scope.infiniteScrollDistance),handleInfiniteScrollDisabled=function(v){return scrollEnabled=!v,scrollEnabled&&checkWhenEnabled?(checkWhenEnabled=!1,handler()):void 0},scope.$watch("infiniteScrollDisabled",handleInfiniteScrollDisabled),handleInfiniteScrollDisabled(scope.infiniteScrollDisabled),handleInfiniteScrollUseDocumentBottom=function(v){return useDocumentBottom=v},scope.$watch("infiniteScrollUseDocumentBottom",handleInfiniteScrollUseDocumentBottom),handleInfiniteScrollUseDocumentBottom(scope.infiniteScrollUseDocumentBottom),changeContainer=function(newContainer){return null!=container&&container.unbind("scroll",handler),container=newContainer,null!=newContainer?container.bind("scroll",handler):void 0},changeContainer(windowElement),scope.infiniteScrollListenForEvent&&(unregisterEventListener=$rootScope.$on(scope.infiniteScrollListenForEvent,handler)),handleInfiniteScrollContainer=function(newContainer){if(null!=newContainer&&0!==newContainer.length){if(newContainer instanceof HTMLElement?newContainer=angular.element(newContainer):"function"==typeof newContainer.append?newContainer=angular.element(newContainer[newContainer.length-1]):"string"==typeof newContainer&&(newContainer=angular.element(document.querySelector(newContainer))),null!=newContainer)return changeContainer(newContainer);throw new Exception("invalid infinite-scroll-container attribute.")}},scope.$watch("infiniteScrollContainer",handleInfiniteScrollContainer),handleInfiniteScrollContainer(scope.infiniteScrollContainer||[]),null!=attrs.infiniteScrollParent&&changeContainer(angular.element(elem.parent())),null!=attrs.infiniteScrollImmediateCheck&&(immediateCheck=scope.$eval(attrs.infiniteScrollImmediateCheck)),$interval(function(){return immediateCheck?handler():void 0},0,1)}}}]),!function(undefined){function init(){this._events={},this._conf&&configure.call(this,this._conf)}function configure(conf){conf&&(this._conf=conf,conf.delimiter&&(this.delimiter=conf.delimiter),conf.maxListeners&&(this._events.maxListeners=conf.maxListeners),conf.wildcard&&(this.wildcard=conf.wildcard),conf.newListener&&(this.newListener=conf.newListener),this.wildcard&&(this.listenerTree={}))}function EventEmitter(conf){this._events={},this.newListener=!1,configure.call(this,conf)}function searchListenerTree(handlers,type,tree,i){if(!tree)return[];var leaf,len,branch,xTree,xxTree,isolatedBranch,endReached,listeners=[],typeLength=type.length,currentType=type[i],nextType=type[i+1];if(i===typeLength&&tree._listeners){if("function"==typeof tree._listeners)return handlers&&handlers.push(tree._listeners),[tree];for(leaf=0,len=tree._listeners.length;len>leaf;leaf++)handlers&&handlers.push(tree._listeners[leaf]);return[tree]}if("*"===currentType||"**"===currentType||tree[currentType]){if("*"===currentType){for(branch in tree)"_listeners"!==branch&&tree.hasOwnProperty(branch)&&(listeners=listeners.concat(searchListenerTree(handlers,type,tree[branch],i+1)));return listeners}if("**"===currentType){endReached=i+1===typeLength||i+2===typeLength&&"*"===nextType,endReached&&tree._listeners&&(listeners=listeners.concat(searchListenerTree(handlers,type,tree,typeLength)));for(branch in tree)"_listeners"!==branch&&tree.hasOwnProperty(branch)&&("*"===branch||"**"===branch?(tree[branch]._listeners&&!endReached&&(listeners=listeners.concat(searchListenerTree(handlers,type,tree[branch],typeLength))),listeners=listeners.concat(searchListenerTree(handlers,type,tree[branch],i))):listeners=branch===nextType?listeners.concat(searchListenerTree(handlers,type,tree[branch],i+2)):listeners.concat(searchListenerTree(handlers,type,tree[branch],i)));return listeners}listeners=listeners.concat(searchListenerTree(handlers,type,tree[currentType],i+1))}if(xTree=tree["*"],xTree&&searchListenerTree(handlers,type,xTree,i+1),xxTree=tree["**"])if(typeLength>i){xxTree._listeners&&searchListenerTree(handlers,type,xxTree,typeLength);for(branch in xxTree)"_listeners"!==branch&&xxTree.hasOwnProperty(branch)&&(branch===nextType?searchListenerTree(handlers,type,xxTree[branch],i+2):branch===currentType?searchListenerTree(handlers,type,xxTree[branch],i+1):(isolatedBranch={},isolatedBranch[branch]=xxTree[branch],searchListenerTree(handlers,type,{"**":isolatedBranch},i+1)))}else xxTree._listeners?searchListenerTree(handlers,type,xxTree,typeLength):xxTree["*"]&&xxTree["*"]._listeners&&searchListenerTree(handlers,type,xxTree["*"],typeLength);return listeners}function growListenerTree(type,listener){type="string"==typeof type?type.split(this.delimiter):type.slice();for(var i=0,len=type.length;len>i+1;i++)if("**"===type[i]&&"**"===type[i+1])return;for(var tree=this.listenerTree,name=type.shift();name;){if(tree[name]||(tree[name]={}),tree=tree[name],0===type.length){if(tree._listeners){if("function"==typeof tree._listeners)tree._listeners=[tree._listeners,listener];else if(isArray(tree._listeners)&&(tree._listeners.push(listener),!tree._listeners.warned)){var m=defaultMaxListeners;"undefined"!=typeof this._events.maxListeners&&(m=this._events.maxListeners),m>0&&tree._listeners.length>m&&(tree._listeners.warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",tree._listeners.length),console.trace())}}else tree._listeners=listener;return!0}name=type.shift()}return!0}var isArray=Array.isArray?Array.isArray:function(obj){return"[object Array]"===Object.prototype.toString.call(obj)},defaultMaxListeners=10;EventEmitter.prototype.delimiter=".",EventEmitter.prototype.setMaxListeners=function(n){this._events||init.call(this),this._events.maxListeners=n,this._conf||(this._conf={}),this._conf.maxListeners=n},EventEmitter.prototype.event="",EventEmitter.prototype.once=function(event,fn){return this.many(event,1,fn),this},EventEmitter.prototype.many=function(event,ttl,fn){function listener(){0===--ttl&&self.off(event,listener),fn.apply(this,arguments)}var self=this;if("function"!=typeof fn)throw new Error("many only accepts instances of Function");return listener._origin=fn,this.on(event,listener),self},EventEmitter.prototype.emit=function(){this._events||init.call(this);var type=arguments[0];if("newListener"===type&&!this.newListener&&!this._events.newListener)return!1;if(this._all){for(var l=arguments.length,args=new Array(l-1),i=1;l>i;i++)args[i-1]=arguments[i];for(i=0,l=this._all.length;l>i;i++)this.event=type, -this._all[i].apply(this,args)}if("error"===type&&!(this._all||this._events.error||this.wildcard&&this.listenerTree.error))throw arguments[1]instanceof Error?arguments[1]:new Error("Uncaught, unspecified 'error' event.");var handler;if(this.wildcard){handler=[];var ns="string"==typeof type?type.split(this.delimiter):type.slice();searchListenerTree.call(this,handler,ns,this.listenerTree,0)}else handler=this._events[type];if("function"==typeof handler){if(this.event=type,1===arguments.length)handler.call(this);else if(arguments.length>1)switch(arguments.length){case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:for(var l=arguments.length,args=new Array(l-1),i=1;l>i;i++)args[i-1]=arguments[i];handler.apply(this,args)}return!0}if(handler){for(var l=arguments.length,args=new Array(l-1),i=1;l>i;i++)args[i-1]=arguments[i];for(var listeners=handler.slice(),i=0,l=listeners.length;l>i;i++)this.event=type,listeners[i].apply(this,args);return listeners.length>0||!!this._all}return!!this._all},EventEmitter.prototype.on=function(type,listener){if("function"==typeof type)return this.onAny(type),this;if("function"!=typeof listener)throw new Error("on only accepts instances of Function");if(this._events||init.call(this),this.emit("newListener",type,listener),this.wildcard)return growListenerTree.call(this,type,listener),this;if(this._events[type]){if("function"==typeof this._events[type])this._events[type]=[this._events[type],listener];else if(isArray(this._events[type])&&(this._events[type].push(listener),!this._events[type].warned)){var m=defaultMaxListeners;"undefined"!=typeof this._events.maxListeners&&(m=this._events.maxListeners),m>0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length),console.trace())}}else this._events[type]=listener;return this},EventEmitter.prototype.onAny=function(fn){if("function"!=typeof fn)throw new Error("onAny only accepts instances of Function");return this._all||(this._all=[]),this._all.push(fn),this},EventEmitter.prototype.addListener=EventEmitter.prototype.on,EventEmitter.prototype.off=function(type,listener){if("function"!=typeof listener)throw new Error("removeListener only takes instances of Function");var handlers,leafs=[];if(this.wildcard){var ns="string"==typeof type?type.split(this.delimiter):type.slice();leafs=searchListenerTree.call(this,null,ns,this.listenerTree,0)}else{if(!this._events[type])return this;handlers=this._events[type],leafs.push({_listeners:handlers})}for(var iLeaf=0;iLeafi;i++)if(handlers[i]===listener||handlers[i].listener&&handlers[i].listener===listener||handlers[i]._origin&&handlers[i]._origin===listener){position=i;break}if(0>position)continue;return this.wildcard?leaf._listeners.splice(position,1):this._events[type].splice(position,1),0===handlers.length&&(this.wildcard?delete leaf._listeners:delete this._events[type]),this}(handlers===listener||handlers.listener&&handlers.listener===listener||handlers._origin&&handlers._origin===listener)&&(this.wildcard?delete leaf._listeners:delete this._events[type])}return this},EventEmitter.prototype.offAny=function(fn){var fns,i=0,l=0;if(fn&&this._all&&this._all.length>0){for(fns=this._all,i=0,l=fns.length;l>i;i++)if(fn===fns[i])return fns.splice(i,1),this}else this._all=[];return this},EventEmitter.prototype.removeListener=EventEmitter.prototype.off,EventEmitter.prototype.removeAllListeners=function(type){if(0===arguments.length)return!this._events||init.call(this),this;if(this.wildcard)for(var ns="string"==typeof type?type.split(this.delimiter):type.slice(),leafs=searchListenerTree.call(this,null,ns,this.listenerTree,0),iLeaf=0;iLeafii;ii++)newArr[ii]=arr[ii+offset];return newArr}function ensureSize(iter){return void 0===iter.size&&(iter.size=iter.__iterate(returnTrue)),iter.size}function wrapIndex(iter,index){if("number"!=typeof index){var numIndex=+index;if(""+numIndex!==index)return NaN;index=numIndex}return 0>index?ensureSize(iter)+index:index}function returnTrue(){return!0}function wholeSlice(begin,end,size){return(0===begin||void 0!==size&&-size>=begin)&&(void 0===end||void 0!==size&&end>=size)}function resolveBegin(begin,size){return resolveIndex(begin,size,0)}function resolveEnd(end,size){return resolveIndex(end,size,size)}function resolveIndex(index,size,defaultIndex){return void 0===index?defaultIndex:0>index?Math.max(0,size+index):void 0===size?index:Math.min(size,index)}function Iterable(value){return isIterable(value)?value:Seq(value)}function KeyedIterable(value){return isKeyed(value)?value:KeyedSeq(value)}function IndexedIterable(value){return isIndexed(value)?value:IndexedSeq(value)}function SetIterable(value){return isIterable(value)&&!isAssociative(value)?value:SetSeq(value)}function isIterable(maybeIterable){return!(!maybeIterable||!maybeIterable[IS_ITERABLE_SENTINEL])}function isKeyed(maybeKeyed){return!(!maybeKeyed||!maybeKeyed[IS_KEYED_SENTINEL])}function isIndexed(maybeIndexed){return!(!maybeIndexed||!maybeIndexed[IS_INDEXED_SENTINEL])}function isAssociative(maybeAssociative){return isKeyed(maybeAssociative)||isIndexed(maybeAssociative)}function isOrdered(maybeOrdered){return!(!maybeOrdered||!maybeOrdered[IS_ORDERED_SENTINEL])}function src_Iterator__Iterator(next){this.next=next}function iteratorValue(type,k,v,iteratorResult){var value=0===type?k:1===type?v:[k,v];return iteratorResult?iteratorResult.value=value:iteratorResult={value:value,done:!1},iteratorResult}function iteratorDone(){return{value:void 0,done:!0}}function hasIterator(maybeIterable){return!!getIteratorFn(maybeIterable)}function isIterator(maybeIterator){return maybeIterator&&"function"==typeof maybeIterator.next}function getIterator(iterable){var iteratorFn=getIteratorFn(iterable);return iteratorFn&&iteratorFn.call(iterable)}function getIteratorFn(iterable){var iteratorFn=iterable&&(REAL_ITERATOR_SYMBOL&&iterable[REAL_ITERATOR_SYMBOL]||iterable[FAUX_ITERATOR_SYMBOL]);return"function"==typeof iteratorFn?iteratorFn:void 0}function isArrayLike(value){return value&&"number"==typeof value.length}function Seq(value){return null===value||void 0===value?emptySequence():isIterable(value)?value.toSeq():seqFromValue(value)}function KeyedSeq(value){return null===value||void 0===value?emptySequence().toKeyedSeq():isIterable(value)?isKeyed(value)?value.toSeq():value.fromEntrySeq():keyedSeqFromValue(value)}function IndexedSeq(value){return null===value||void 0===value?emptySequence():isIterable(value)?isKeyed(value)?value.entrySeq():value.toIndexedSeq():indexedSeqFromValue(value)}function SetSeq(value){return(null===value||void 0===value?emptySequence():isIterable(value)?isKeyed(value)?value.entrySeq():value:indexedSeqFromValue(value)).toSetSeq()}function ArraySeq(array){this._array=array,this.size=array.length}function ObjectSeq(object){var keys=Object.keys(object);this._object=object,this._keys=keys,this.size=keys.length}function IterableSeq(iterable){this._iterable=iterable,this.size=iterable.length||iterable.size}function IteratorSeq(iterator){this._iterator=iterator,this._iteratorCache=[]}function isSeq(maybeSeq){return!(!maybeSeq||!maybeSeq[IS_SEQ_SENTINEL])}function emptySequence(){return EMPTY_SEQ||(EMPTY_SEQ=new ArraySeq([]))}function keyedSeqFromValue(value){var seq=Array.isArray(value)?new ArraySeq(value).fromEntrySeq():isIterator(value)?new IteratorSeq(value).fromEntrySeq():hasIterator(value)?new IterableSeq(value).fromEntrySeq():"object"==typeof value?new ObjectSeq(value):void 0;if(!seq)throw new TypeError("Expected Array or iterable object of [k, v] entries, or keyed object: "+value);return seq}function indexedSeqFromValue(value){var seq=maybeIndexedSeqFromValue(value);if(!seq)throw new TypeError("Expected Array or iterable object of values: "+value);return seq}function seqFromValue(value){var seq=maybeIndexedSeqFromValue(value)||"object"==typeof value&&new ObjectSeq(value);if(!seq)throw new TypeError("Expected Array or iterable object of values, or keyed object: "+value);return seq}function maybeIndexedSeqFromValue(value){return isArrayLike(value)?new ArraySeq(value):isIterator(value)?new IteratorSeq(value):hasIterator(value)?new IterableSeq(value):void 0}function seqIterate(seq,fn,reverse,useKeys){var cache=seq._cache;if(cache){for(var maxIndex=cache.length-1,ii=0;maxIndex>=ii;ii++){var entry=cache[reverse?maxIndex-ii:ii];if(fn(entry[1],useKeys?entry[0]:ii,seq)===!1)return ii+1}return ii}return seq.__iterateUncached(fn,reverse)}function seqIterator(seq,type,reverse,useKeys){var cache=seq._cache;if(cache){var maxIndex=cache.length-1,ii=0;return new src_Iterator__Iterator(function(){var entry=cache[reverse?maxIndex-ii:ii];return ii++>maxIndex?iteratorDone():iteratorValue(type,useKeys?entry[0]:ii-1,entry[1])})}return seq.__iteratorUncached(type,reverse)}function Collection(){throw TypeError("Abstract")}function KeyedCollection(){}function IndexedCollection(){}function SetCollection(){}function is(valueA,valueB){if(valueA===valueB||valueA!==valueA&&valueB!==valueB)return!0;if(!valueA||!valueB)return!1;if("function"==typeof valueA.valueOf&&"function"==typeof valueB.valueOf){if(valueA=valueA.valueOf(),valueB=valueB.valueOf(),valueA===valueB||valueA!==valueA&&valueB!==valueB)return!0;if(!valueA||!valueB)return!1}return"function"==typeof valueA.equals&&"function"==typeof valueB.equals&&valueA.equals(valueB)?!0:!1}function fromJS(json,converter){return converter?fromJSWith(converter,json,"",{"":json}):fromJSDefault(json)}function fromJSWith(converter,json,key,parentJSON){return Array.isArray(json)?converter.call(parentJSON,key,IndexedSeq(json).map(function(v,k){return fromJSWith(converter,v,k,json)})):isPlainObj(json)?converter.call(parentJSON,key,KeyedSeq(json).map(function(v,k){return fromJSWith(converter,v,k,json)})):json}function fromJSDefault(json){return Array.isArray(json)?IndexedSeq(json).map(fromJSDefault).toList():isPlainObj(json)?KeyedSeq(json).map(fromJSDefault).toMap():json}function isPlainObj(value){return value&&(value.constructor===Object||void 0===value.constructor)}function smi(i32){return i32>>>1&1073741824|3221225471&i32}function hash(o){if(o===!1||null===o||void 0===o)return 0;if("function"==typeof o.valueOf&&(o=o.valueOf(),o===!1||null===o||void 0===o))return 0;if(o===!0)return 1;var type=typeof o;if("number"===type){var h=0|o;for(h!==o&&(h^=4294967295*o);o>4294967295;)o/=4294967295,h^=o;return smi(h)}return"string"===type?o.length>STRING_HASH_CACHE_MIN_STRLEN?cachedHashString(o):hashString(o):"function"==typeof o.hashCode?o.hashCode():hashJSObj(o)}function cachedHashString(string){var hash=stringHashCache[string];return void 0===hash&&(hash=hashString(string),STRING_HASH_CACHE_SIZE===STRING_HASH_CACHE_MAX_SIZE&&(STRING_HASH_CACHE_SIZE=0,stringHashCache={}),STRING_HASH_CACHE_SIZE++,stringHashCache[string]=hash),hash}function hashString(string){for(var hash=0,ii=0;ii0)switch(node.nodeType){case 1:return node.uniqueID;case 9:return node.documentElement&&node.documentElement.uniqueID}}function invariant(condition,error){if(!condition)throw new Error(error)}function assertNotInfinite(size){invariant(size!==1/0,"Cannot perform this action with an infinite size.")}function ToKeyedSequence(indexed,useKeys){this._iter=indexed,this._useKeys=useKeys,this.size=indexed.size}function ToIndexedSequence(iter){this._iter=iter,this.size=iter.size}function ToSetSequence(iter){this._iter=iter,this.size=iter.size}function FromEntriesSequence(entries){this._iter=entries,this.size=entries.size}function flipFactory(iterable){var flipSequence=makeSequence(iterable);return flipSequence._iter=iterable,flipSequence.size=iterable.size,flipSequence.flip=function(){return iterable},flipSequence.reverse=function(){var reversedSequence=iterable.reverse.apply(this);return reversedSequence.flip=function(){return iterable.reverse()},reversedSequence},flipSequence.has=function(key){return iterable.includes(key)},flipSequence.includes=function(key){return iterable.has(key)},flipSequence.cacheResult=cacheResultThrough,flipSequence.__iterateUncached=function(fn,reverse){var this$0=this;return iterable.__iterate(function(v,k){return fn(k,v,this$0)!==!1},reverse)},flipSequence.__iteratorUncached=function(type,reverse){if(type===ITERATE_ENTRIES){var iterator=iterable.__iterator(type,reverse);return new src_Iterator__Iterator(function(){var step=iterator.next();if(!step.done){var k=step.value[0];step.value[0]=step.value[1],step.value[1]=k}return step})}return iterable.__iterator(type===ITERATE_VALUES?ITERATE_KEYS:ITERATE_VALUES,reverse)},flipSequence}function mapFactory(iterable,mapper,context){var mappedSequence=makeSequence(iterable);return mappedSequence.size=iterable.size,mappedSequence.has=function(key){return iterable.has(key)},mappedSequence.get=function(key,notSetValue){var v=iterable.get(key,NOT_SET);return v===NOT_SET?notSetValue:mapper.call(context,v,key,iterable)},mappedSequence.__iterateUncached=function(fn,reverse){var this$0=this;return iterable.__iterate(function(v,k,c){return fn(mapper.call(context,v,k,c),k,this$0)!==!1},reverse)},mappedSequence.__iteratorUncached=function(type,reverse){var iterator=iterable.__iterator(ITERATE_ENTRIES,reverse);return new src_Iterator__Iterator(function(){var step=iterator.next();if(step.done)return step;var entry=step.value,key=entry[0];return iteratorValue(type,key,mapper.call(context,entry[1],key,iterable),step)})},mappedSequence}function reverseFactory(iterable,useKeys){var reversedSequence=makeSequence(iterable);return reversedSequence._iter=iterable,reversedSequence.size=iterable.size,reversedSequence.reverse=function(){return iterable},iterable.flip&&(reversedSequence.flip=function(){var flipSequence=flipFactory(iterable);return flipSequence.reverse=function(){return iterable.flip()},flipSequence}),reversedSequence.get=function(key,notSetValue){return iterable.get(useKeys?key:-1-key,notSetValue)},reversedSequence.has=function(key){return iterable.has(useKeys?key:-1-key)},reversedSequence.includes=function(value){return iterable.includes(value)},reversedSequence.cacheResult=cacheResultThrough,reversedSequence.__iterate=function(fn,reverse){var this$0=this;return iterable.__iterate(function(v,k){return fn(v,k,this$0)},!reverse)},reversedSequence.__iterator=function(type,reverse){return iterable.__iterator(type,!reverse)},reversedSequence}function filterFactory(iterable,predicate,context,useKeys){var filterSequence=makeSequence(iterable);return useKeys&&(filterSequence.has=function(key){var v=iterable.get(key,NOT_SET);return v!==NOT_SET&&!!predicate.call(context,v,key,iterable)},filterSequence.get=function(key,notSetValue){var v=iterable.get(key,NOT_SET);return v!==NOT_SET&&predicate.call(context,v,key,iterable)?v:notSetValue}),filterSequence.__iterateUncached=function(fn,reverse){var this$0=this,iterations=0;return iterable.__iterate(function(v,k,c){return predicate.call(context,v,k,c)?(iterations++,fn(v,useKeys?k:iterations-1,this$0)):void 0},reverse),iterations},filterSequence.__iteratorUncached=function(type,reverse){var iterator=iterable.__iterator(ITERATE_ENTRIES,reverse),iterations=0;return new src_Iterator__Iterator(function(){for(;;){var step=iterator.next();if(step.done)return step;var entry=step.value,key=entry[0],value=entry[1];if(predicate.call(context,value,key,iterable))return iteratorValue(type,useKeys?key:iterations++,value,step)}})},filterSequence}function countByFactory(iterable,grouper,context){var groups=src_Map__Map().asMutable();return iterable.__iterate(function(v,k){groups.update(grouper.call(context,v,k,iterable),0,function(a){return a+1})}),groups.asImmutable()}function groupByFactory(iterable,grouper,context){var isKeyedIter=isKeyed(iterable),groups=(isOrdered(iterable)?OrderedMap():src_Map__Map()).asMutable();iterable.__iterate(function(v,k){groups.update(grouper.call(context,v,k,iterable),function(a){return a=a||[],a.push(isKeyedIter?[k,v]:v),a})});var coerce=iterableClass(iterable);return groups.map(function(arr){return reify(iterable,coerce(arr))})}function sliceFactory(iterable,begin,end,useKeys){var originalSize=iterable.size;if(void 0!==begin&&(begin=0|begin),void 0!==end&&(end=0|end),wholeSlice(begin,end,originalSize))return iterable;var resolvedBegin=resolveBegin(begin,originalSize),resolvedEnd=resolveEnd(end,originalSize);if(resolvedBegin!==resolvedBegin||resolvedEnd!==resolvedEnd)return sliceFactory(iterable.toSeq().cacheResult(),begin,end,useKeys);var sliceSize,resolvedSize=resolvedEnd-resolvedBegin;resolvedSize===resolvedSize&&(sliceSize=0>resolvedSize?0:resolvedSize);var sliceSeq=makeSequence(iterable);return sliceSeq.size=0===sliceSize?sliceSize:iterable.size&&sliceSize||void 0,!useKeys&&isSeq(iterable)&&sliceSize>=0&&(sliceSeq.get=function(index,notSetValue){return index=wrapIndex(this,index),index>=0&&sliceSize>index?iterable.get(index+resolvedBegin,notSetValue):notSetValue}),sliceSeq.__iterateUncached=function(fn,reverse){var this$0=this;if(0===sliceSize)return 0;if(reverse)return this.cacheResult().__iterate(fn,reverse);var skipped=0,isSkipping=!0,iterations=0;return iterable.__iterate(function(v,k){return isSkipping&&(isSkipping=skipped++sliceSize)return iteratorDone();var step=iterator.next();return useKeys||type===ITERATE_VALUES?step:type===ITERATE_KEYS?iteratorValue(type,iterations-1,void 0,step):iteratorValue(type,iterations-1,step.value[1],step)})},sliceSeq}function takeWhileFactory(iterable,predicate,context){var takeSequence=makeSequence(iterable);return takeSequence.__iterateUncached=function(fn,reverse){var this$0=this;if(reverse)return this.cacheResult().__iterate(fn,reverse);var iterations=0;return iterable.__iterate(function(v,k,c){return predicate.call(context,v,k,c)&&++iterations&&fn(v,k,this$0)}),iterations},takeSequence.__iteratorUncached=function(type,reverse){var this$0=this;if(reverse)return this.cacheResult().__iterator(type,reverse);var iterator=iterable.__iterator(ITERATE_ENTRIES,reverse),iterating=!0;return new src_Iterator__Iterator(function(){if(!iterating)return iteratorDone();var step=iterator.next();if(step.done)return step;var entry=step.value,k=entry[0],v=entry[1];return predicate.call(context,v,k,this$0)?type===ITERATE_ENTRIES?step:iteratorValue(type,k,v,step):(iterating=!1,iteratorDone())})},takeSequence}function skipWhileFactory(iterable,predicate,context,useKeys){var skipSequence=makeSequence(iterable);return skipSequence.__iterateUncached=function(fn,reverse){var this$0=this;if(reverse)return this.cacheResult().__iterate(fn,reverse);var isSkipping=!0,iterations=0;return iterable.__iterate(function(v,k,c){return isSkipping&&(isSkipping=predicate.call(context,v,k,c))?void 0:(iterations++,fn(v,useKeys?k:iterations-1,this$0))}),iterations},skipSequence.__iteratorUncached=function(type,reverse){var this$0=this;if(reverse)return this.cacheResult().__iterator(type,reverse);var iterator=iterable.__iterator(ITERATE_ENTRIES,reverse),skipping=!0,iterations=0;return new src_Iterator__Iterator(function(){var step,k,v;do{if(step=iterator.next(),step.done)return useKeys||type===ITERATE_VALUES?step:type===ITERATE_KEYS?iteratorValue(type,iterations++,void 0,step):iteratorValue(type,iterations++,step.value[1],step);var entry=step.value;k=entry[0],v=entry[1],skipping&&(skipping=predicate.call(context,v,k,this$0))}while(skipping);return type===ITERATE_ENTRIES?step:iteratorValue(type,k,v,step)})},skipSequence}function concatFactory(iterable,values){var isKeyedIterable=isKeyed(iterable),iters=[iterable].concat(values).map(function(v){return isIterable(v)?isKeyedIterable&&(v=KeyedIterable(v)):v=isKeyedIterable?keyedSeqFromValue(v):indexedSeqFromValue(Array.isArray(v)?v:[v]),v}).filter(function(v){return 0!==v.size});if(0===iters.length)return iterable;if(1===iters.length){var singleton=iters[0];if(singleton===iterable||isKeyedIterable&&isKeyed(singleton)||isIndexed(iterable)&&isIndexed(singleton))return singleton}var concatSeq=new ArraySeq(iters);return isKeyedIterable?concatSeq=concatSeq.toKeyedSeq():isIndexed(iterable)||(concatSeq=concatSeq.toSetSeq()),concatSeq=concatSeq.flatten(!0),concatSeq.size=iters.reduce(function(sum,seq){if(void 0!==sum){var size=seq.size;if(void 0!==size)return sum+size}},0),concatSeq}function flattenFactory(iterable,depth,useKeys){var flatSequence=makeSequence(iterable);return flatSequence.__iterateUncached=function(fn,reverse){function flatDeep(iter,currentDepth){var this$0=this;iter.__iterate(function(v,k){return(!depth||depth>currentDepth)&&isIterable(v)?flatDeep(v,currentDepth+1):fn(v,useKeys?k:iterations++,this$0)===!1&&(stopped=!0),!stopped},reverse)}var iterations=0,stopped=!1;return flatDeep(iterable,0),iterations},flatSequence.__iteratorUncached=function(type,reverse){var iterator=iterable.__iterator(type,reverse),stack=[],iterations=0;return new src_Iterator__Iterator(function(){for(;iterator;){var step=iterator.next();if(step.done===!1){var v=step.value;if(type===ITERATE_ENTRIES&&(v=v[1]),depth&&!(stack.length0}function zipWithFactory(keyIter,zipper,iters){var zipSequence=makeSequence(keyIter);return zipSequence.size=new ArraySeq(iters).map(function(i){return i.size}).min(),zipSequence.__iterate=function(fn,reverse){for(var step,iterator=this.__iterator(ITERATE_VALUES,reverse),iterations=0;!(step=iterator.next()).done&&fn(step.value,iterations++,this)!==!1;);return iterations},zipSequence.__iteratorUncached=function(type,reverse){var iterators=iters.map(function(i){return i=Iterable(i),getIterator(reverse?i.reverse():i)}),iterations=0,isDone=!1;return new src_Iterator__Iterator(function(){var steps;return isDone||(steps=iterators.map(function(i){return i.next()}),isDone=steps.some(function(s){return s.done})),isDone?iteratorDone():iteratorValue(type,iterations++,zipper.apply(null,steps.map(function(s){return s.value})))})},zipSequence}function reify(iter,seq){return isSeq(iter)?seq:iter.constructor(seq)}function validateEntry(entry){if(entry!==Object(entry))throw new TypeError("Expected [K, V] tuple: "+entry)}function resolveSize(iter){return assertNotInfinite(iter.size),ensureSize(iter)}function iterableClass(iterable){return isKeyed(iterable)?KeyedIterable:isIndexed(iterable)?IndexedIterable:SetIterable}function makeSequence(iterable){return Object.create((isKeyed(iterable)?KeyedSeq:isIndexed(iterable)?IndexedSeq:SetSeq).prototype)}function cacheResultThrough(){return this._iter.cacheResult?(this._iter.cacheResult(),this.size=this._iter.size,this):Seq.prototype.cacheResult.call(this)}function defaultComparator(a,b){return a>b?1:b>a?-1:0}function forceIterator(keyPath){var iter=getIterator(keyPath);if(!iter){if(!isArrayLike(keyPath))throw new TypeError("Expected iterable or array-like: "+keyPath);iter=getIterator(Iterable(keyPath))}return iter}function src_Map__Map(value){return null===value||void 0===value?emptyMap():isMap(value)&&!isOrdered(value)?value:emptyMap().withMutations(function(map){var iter=KeyedIterable(value);assertNotInfinite(iter.size),iter.forEach(function(v,k){return map.set(k,v)})})}function isMap(maybeMap){return!(!maybeMap||!maybeMap[IS_MAP_SENTINEL])}function ArrayMapNode(ownerID,entries){this.ownerID=ownerID,this.entries=entries}function BitmapIndexedNode(ownerID,bitmap,nodes){this.ownerID=ownerID,this.bitmap=bitmap,this.nodes=nodes}function HashArrayMapNode(ownerID,count,nodes){this.ownerID=ownerID,this.count=count,this.nodes=nodes}function HashCollisionNode(ownerID,keyHash,entries){this.ownerID=ownerID,this.keyHash=keyHash,this.entries=entries}function ValueNode(ownerID,keyHash,entry){this.ownerID=ownerID,this.keyHash=keyHash,this.entry=entry}function MapIterator(map,type,reverse){this._type=type,this._reverse=reverse,this._stack=map._root&&mapIteratorFrame(map._root)}function mapIteratorValue(type,entry){return iteratorValue(type,entry[0],entry[1])}function mapIteratorFrame(node,prev){return{node:node,index:0,__prev:prev}}function makeMap(size,root,ownerID,hash){var map=Object.create(MapPrototype);return map.size=size,map._root=root,map.__ownerID=ownerID,map.__hash=hash,map.__altered=!1,map}function emptyMap(){return EMPTY_MAP||(EMPTY_MAP=makeMap(0))}function updateMap(map,k,v){var newRoot,newSize;if(map._root){var didChangeSize=MakeRef(CHANGE_LENGTH),didAlter=MakeRef(DID_ALTER);if(newRoot=updateNode(map._root,map.__ownerID,0,void 0,k,v,didChangeSize,didAlter),!didAlter.value)return map;newSize=map.size+(didChangeSize.value?v===NOT_SET?-1:1:0)}else{if(v===NOT_SET)return map;newSize=1,newRoot=new ArrayMapNode(map.__ownerID,[[k,v]])}return map.__ownerID?(map.size=newSize,map._root=newRoot,map.__hash=void 0,map.__altered=!0,map):newRoot?makeMap(newSize,newRoot):emptyMap()}function updateNode(node,ownerID,shift,keyHash,key,value,didChangeSize,didAlter){return node?node.update(ownerID,shift,keyHash,key,value,didChangeSize,didAlter):value===NOT_SET?node:(SetRef(didAlter),SetRef(didChangeSize),new ValueNode(ownerID,keyHash,[key,value]))}function isLeafNode(node){return node.constructor===ValueNode||node.constructor===HashCollisionNode}function mergeIntoNode(node,ownerID,shift,keyHash,entry){if(node.keyHash===keyHash)return new HashCollisionNode(ownerID,keyHash,[node.entry,entry]);var newNode,idx1=(0===shift?node.keyHash:node.keyHash>>>shift)&MASK,idx2=(0===shift?keyHash:keyHash>>>shift)&MASK,nodes=idx1===idx2?[mergeIntoNode(node,ownerID,shift+SHIFT,keyHash,entry)]:(newNode=new ValueNode(ownerID,keyHash,entry),idx2>idx1?[node,newNode]:[newNode,node]);return new BitmapIndexedNode(ownerID,1<ii;ii++,bit<<=1){var node=nodes[ii];void 0!==node&&ii!==excluding&&(bitmap|=bit,packedNodes[packedII++]=node)}return new BitmapIndexedNode(ownerID,bitmap,packedNodes)}function expandNodes(ownerID,nodes,bitmap,including,node){for(var count=0,expandedNodes=new Array(SIZE),ii=0;0!==bitmap;ii++,bitmap>>>=1)expandedNodes[ii]=1&bitmap?nodes[count++]:void 0;return expandedNodes[including]=node,new HashArrayMapNode(ownerID,count+1,expandedNodes)}function mergeIntoMapWith(map,merger,iterables){for(var iters=[],ii=0;ii>1&1431655765,x=(858993459&x)+(x>>2&858993459),x=x+(x>>4)&252645135,x+=x>>8,x+=x>>16,127&x}function setIn(array,idx,val,canEdit){var newArray=canEdit?array:arrCopy(array);return newArray[idx]=val,newArray}function spliceIn(array,idx,val,canEdit){var newLen=array.length+1;if(canEdit&&idx+1===newLen)return array[idx]=val,array;for(var newArray=new Array(newLen),after=0,ii=0;newLen>ii;ii++)ii===idx?(newArray[ii]=val,after=-1):newArray[ii]=array[ii+after];return newArray}function spliceOut(array,idx,canEdit){var newLen=array.length-1;if(canEdit&&idx===newLen)return array.pop(),array;for(var newArray=new Array(newLen),after=0,ii=0;newLen>ii;ii++)ii===idx&&(after=1),newArray[ii]=array[ii+after];return newArray}function List(value){var empty=emptyList();if(null===value||void 0===value)return empty;if(isList(value))return value;var iter=IndexedIterable(value),size=iter.size;return 0===size?empty:(assertNotInfinite(size),size>0&&SIZE>size?makeList(0,size,SHIFT,null,new VNode(iter.toArray())):empty.withMutations(function(list){list.setSize(size),iter.forEach(function(v,i){return list.set(i,v)})}))}function isList(maybeList){return!(!maybeList||!maybeList[IS_LIST_SENTINEL])}function VNode(array,ownerID){this.array=array,this.ownerID=ownerID}function iterateList(list,reverse){function iterateNodeOrLeaf(node,level,offset){return 0===level?iterateLeaf(node,offset):iterateNode(node,level,offset)}function iterateLeaf(node,offset){var array=offset===tailPos?tail&&tail.array:node&&node.array,from=offset>left?0:left-offset,to=right-offset;return to>SIZE&&(to=SIZE),function(){if(from===to)return DONE;var idx=reverse?--to:from++;return array&&array[idx]}}function iterateNode(node,level,offset){var values,array=node&&node.array,from=offset>left?0:left-offset>>level,to=(right-offset>>level)+1;return to>SIZE&&(to=SIZE),function(){for(;;){if(values){var value=values();if(value!==DONE)return value;values=null}if(from===to)return DONE;var idx=reverse?--to:from++;values=iterateNodeOrLeaf(array&&array[idx],level-SHIFT,offset+(idx<=list.size||0>index)return list.withMutations(function(list){0>index?setListBounds(list,index).set(0,value):setListBounds(list,0,index+1).set(index,value)});index+=list._origin;var newTail=list._tail,newRoot=list._root,didAlter=MakeRef(DID_ALTER);return index>=getTailOffset(list._capacity)?newTail=updateVNode(newTail,list.__ownerID,0,index,value,didAlter):newRoot=updateVNode(newRoot,list.__ownerID,list._level,index,value,didAlter),didAlter.value?list.__ownerID?(list._root=newRoot,list._tail=newTail,list.__hash=void 0,list.__altered=!0,list):makeList(list._origin,list._capacity,list._level,newRoot,newTail):list}function updateVNode(node,ownerID,level,index,value,didAlter){var idx=index>>>level&MASK,nodeHas=node&&idx0){var lowerNode=node&&node.array[idx],newLowerNode=updateVNode(lowerNode,ownerID,level-SHIFT,index,value,didAlter);return newLowerNode===lowerNode?node:(newNode=editableVNode(node,ownerID),newNode.array[idx]=newLowerNode,newNode)}return nodeHas&&node.array[idx]===value?node:(SetRef(didAlter),newNode=editableVNode(node,ownerID),void 0===value&&idx===newNode.array.length-1?newNode.array.pop():newNode.array[idx]=value,newNode)}function editableVNode(node,ownerID){return ownerID&&node&&ownerID===node.ownerID?node:new VNode(node?node.array.slice():[],ownerID)}function listNodeFor(list,rawIndex){if(rawIndex>=getTailOffset(list._capacity))return list._tail;if(rawIndex<1<0;)node=node.array[rawIndex>>>level&MASK],level-=SHIFT;return node}}function setListBounds(list,begin,end){void 0!==begin&&(begin=0|begin),void 0!==end&&(end=0|end);var owner=list.__ownerID||new OwnerID,oldOrigin=list._origin,oldCapacity=list._capacity,newOrigin=oldOrigin+begin,newCapacity=void 0===end?oldCapacity:0>end?oldCapacity+end:oldOrigin+end;if(newOrigin===oldOrigin&&newCapacity===oldCapacity)return list;if(newOrigin>=newCapacity)return list.clear();for(var newLevel=list._level,newRoot=list._root,offsetShift=0;0>newOrigin+offsetShift;)newRoot=new VNode(newRoot&&newRoot.array.length?[void 0,newRoot]:[],owner),newLevel+=SHIFT,offsetShift+=1<=1<newTailOffset?listNodeFor(list,newCapacity-1):newTailOffset>oldTailOffset?new VNode([],owner):oldTail;if(oldTail&&newTailOffset>oldTailOffset&&oldCapacity>newOrigin&&oldTail.array.length){newRoot=editableVNode(newRoot,owner);for(var node=newRoot,level=newLevel;level>SHIFT;level-=SHIFT){var idx=oldTailOffset>>>level&MASK;node=node.array[idx]=editableVNode(node.array[idx],owner)}node.array[oldTailOffset>>>SHIFT&MASK]=oldTail}if(oldCapacity>newCapacity&&(newTail=newTail&&newTail.removeAfter(owner,0,newCapacity)),newOrigin>=newTailOffset)newOrigin-=newTailOffset,newCapacity-=newTailOffset,newLevel=SHIFT,newRoot=null,newTail=newTail&&newTail.removeBefore(owner,0,newOrigin);else if(newOrigin>oldOrigin||oldTailOffset>newTailOffset){for(offsetShift=0;newRoot;){var beginIndex=newOrigin>>>newLevel&MASK;if(beginIndex!==newTailOffset>>>newLevel&MASK)break;beginIndex&&(offsetShift+=(1<oldOrigin&&(newRoot=newRoot.removeBefore(owner,newLevel,newOrigin-offsetShift)),newRoot&&oldTailOffset>newTailOffset&&(newRoot=newRoot.removeAfter(owner,newLevel,newTailOffset-offsetShift)),offsetShift&&(newOrigin-=offsetShift,newCapacity-=offsetShift)}return list.__ownerID?(list.size=newCapacity-newOrigin,list._origin=newOrigin,list._capacity=newCapacity,list._level=newLevel,list._root=newRoot,list._tail=newTail,list.__hash=void 0,list.__altered=!0,list):makeList(newOrigin,newCapacity,newLevel,newRoot,newTail)}function mergeIntoListWith(list,merger,iterables){for(var iters=[],maxSize=0,ii=0;iimaxSize&&(maxSize=iter.size),isIterable(value)||(iter=iter.map(function(v){return fromJS(v)})),iters.push(iter)}return maxSize>list.size&&(list=list.setSize(maxSize)),mergeIntoCollectionWith(list,merger,iters)}function getTailOffset(size){return SIZE>size?0:size-1>>>SHIFT<=SIZE&&list.size>=2*map.size?(newList=list.filter(function(entry,idx){return void 0!==entry&&i!==idx}),newMap=newList.toKeyedSeq().map(function(entry){return entry[0]}).flip().toMap(),omap.__ownerID&&(newMap.__ownerID=newList.__ownerID=omap.__ownerID)):(newMap=map.remove(k),newList=i===list.size-1?list.pop():list.set(i,void 0))}else if(has){if(v===list.get(i)[1])return omap;newMap=map,newList=list.set(i,[k,v])}else newMap=map.set(k,list.size),newList=list.set(list.size,[k,v]);return omap.__ownerID?(omap.size=newMap.size,omap._map=newMap,omap._list=newList,omap.__hash=void 0,omap):makeOrderedMap(newMap,newList)}function Stack(value){return null===value||void 0===value?emptyStack():isStack(value)?value:emptyStack().unshiftAll(value)}function isStack(maybeStack){return!(!maybeStack||!maybeStack[IS_STACK_SENTINEL])}function makeStack(size,head,ownerID,hash){var map=Object.create(StackPrototype);return map.size=size,map._head=head,map.__ownerID=ownerID,map.__hash=hash,map.__altered=!1,map}function emptyStack(){return EMPTY_STACK||(EMPTY_STACK=makeStack(0))}function src_Set__Set(value){return null===value||void 0===value?emptySet():isSet(value)&&!isOrdered(value)?value:emptySet().withMutations(function(set){var iter=SetIterable(value);assertNotInfinite(iter.size),iter.forEach(function(v){return set.add(v)})})}function isSet(maybeSet){return!(!maybeSet||!maybeSet[IS_SET_SENTINEL])}function updateSet(set,newMap){return set.__ownerID?(set.size=newMap.size,set._map=newMap,set):newMap===set._map?set:0===newMap.size?set.__empty():set.__make(newMap)}function makeSet(map,ownerID){var set=Object.create(SetPrototype);return set.size=map?map.size:0,set._map=map,set.__ownerID=ownerID,set}function emptySet(){return EMPTY_SET||(EMPTY_SET=makeSet(emptyMap()))}function OrderedSet(value){return null===value||void 0===value?emptyOrderedSet():isOrderedSet(value)?value:emptyOrderedSet().withMutations(function(set){var iter=SetIterable(value);assertNotInfinite(iter.size),iter.forEach(function(v){return set.add(v)})})}function isOrderedSet(maybeOrderedSet){return isSet(maybeOrderedSet)&&isOrdered(maybeOrderedSet)}function makeOrderedSet(map,ownerID){var set=Object.create(OrderedSetPrototype);return set.size=map?map.size:0,set._map=map,set.__ownerID=ownerID,set}function emptyOrderedSet(){return EMPTY_ORDERED_SET||(EMPTY_ORDERED_SET=makeOrderedSet(emptyOrderedMap()))}function Record(defaultValues,name){var hasInitialized,RecordType=function(values){if(values instanceof RecordType)return values;if(!(this instanceof RecordType))return new RecordType(values);if(!hasInitialized){hasInitialized=!0;var keys=Object.keys(defaultValues);setProps(RecordTypePrototype,keys),RecordTypePrototype.size=keys.length,RecordTypePrototype._name=name,RecordTypePrototype._keys=keys,RecordTypePrototype._defaultValues=defaultValues}this._map=src_Map__Map(values)},RecordTypePrototype=RecordType.prototype=Object.create(RecordPrototype);return RecordTypePrototype.constructor=RecordType,RecordType}function makeRecord(likeRecord,map,ownerID){var record=Object.create(Object.getPrototypeOf(likeRecord));return record._map=map,record.__ownerID=ownerID,record}function recordName(record){return record._name||record.constructor.name||"Record"}function setProps(prototype,names){try{names.forEach(setProp.bind(void 0,prototype))}catch(error){}}function setProp(prototype,name){Object.defineProperty(prototype,name,{get:function(){return this.get(name)},set:function(value){invariant(this.__ownerID,"Cannot set on an immutable record."),this.set(name,value)}})}function deepEqual(a,b){if(a===b)return!0;if(!isIterable(b)||void 0!==a.size&&void 0!==b.size&&a.size!==b.size||void 0!==a.__hash&&void 0!==b.__hash&&a.__hash!==b.__hash||isKeyed(a)!==isKeyed(b)||isIndexed(a)!==isIndexed(b)||isOrdered(a)!==isOrdered(b))return!1;if(0===a.size&&0===b.size)return!0;var notAssociative=!isAssociative(a);if(isOrdered(a)){var entries=a.entries();return b.every(function(v,k){var entry=entries.next().value;return entry&&is(entry[1],v)&&(notAssociative||is(entry[0],k))})&&entries.next().done}var flipped=!1;if(void 0===a.size)if(void 0===b.size)"function"==typeof a.cacheResult&&a.cacheResult();else{flipped=!0;var _=a;a=b,b=_}var allEqual=!0,bSize=b.__iterate(function(v,k){return(notAssociative?a.has(v):flipped?is(v,a.get(k,NOT_SET)):is(a.get(k,NOT_SET),v))?void 0:(allEqual=!1,!1)});return allEqual&&a.size===bSize}function Range(start,end,step){if(!(this instanceof Range))return new Range(start,end,step);if(invariant(0!==step,"Cannot step a Range by 0"),start=start||0,void 0===end&&(end=1/0),step=void 0===step?1:Math.abs(step),start>end&&(step=-step),this._start=start,this._end=end,this._step=step,this.size=Math.max(0,Math.ceil((end-start)/step-1)+1),0===this.size){if(EMPTY_RANGE)return EMPTY_RANGE;EMPTY_RANGE=this}}function Repeat(value,times){if(!(this instanceof Repeat))return new Repeat(value,times);if(this._value=value,this.size=void 0===times?1/0:Math.max(0,times),0===this.size){if(EMPTY_REPEAT)return EMPTY_REPEAT;EMPTY_REPEAT=this}}function mixin(ctor,methods){var keyCopier=function(key){ctor.prototype[key]=methods[key]};return Object.keys(methods).forEach(keyCopier),Object.getOwnPropertySymbols&&Object.getOwnPropertySymbols(methods).forEach(keyCopier),ctor}function keyMapper(v,k){return k}function entryMapper(v,k){return[k,v]}function not(predicate){return function(){return!predicate.apply(this,arguments)}}function neg(predicate){return function(){return-predicate.apply(this,arguments)}}function quoteString(value){return"string"==typeof value?JSON.stringify(value):value}function defaultZipper(){return arrCopy(arguments)}function defaultNegComparator(a,b){return b>a?1:a>b?-1:0}function hashIterable(iterable){if(iterable.size===1/0)return 0;var ordered=isOrdered(iterable),keyed=isKeyed(iterable),h=ordered?1:0,size=iterable.__iterate(keyed?ordered?function(v,k){h=31*h+hashMerge(hash(v),hash(k))|0}:function(v,k){h=h+hashMerge(hash(v),hash(k))|0}:ordered?function(v){h=31*h+hash(v)|0}:function(v){h=h+hash(v)|0});return murmurHashOfSize(size,h)}function murmurHashOfSize(size,h){return h=src_Math__imul(h,3432918353),h=src_Math__imul(h<<15|h>>>-15,461845907),h=src_Math__imul(h<<13|h>>>-13,5),h=(h+3864292196|0)^size,h=src_Math__imul(h^h>>>16,2246822507),h=src_Math__imul(h^h>>>13,3266489909),h=smi(h^h>>>16)}function hashMerge(a,b){return a^b+2654435769+(a<<6)+(a>>2)|0}var SLICE$0=Array.prototype.slice,DELETE="delete",SHIFT=5,SIZE=1<=ii;ii++)if(fn(array[reverse?maxIndex-ii:ii],ii,this)===!1)return ii+1;return ii},ArraySeq.prototype.__iterator=function(type,reverse){var array=this._array,maxIndex=array.length-1,ii=0;return new src_Iterator__Iterator(function(){return ii>maxIndex?iteratorDone():iteratorValue(type,ii,array[reverse?maxIndex-ii++:ii++])})},createClass(ObjectSeq,KeyedSeq),ObjectSeq.prototype.get=function(key,notSetValue){return void 0===notSetValue||this.has(key)?this._object[key]:notSetValue},ObjectSeq.prototype.has=function(key){return this._object.hasOwnProperty(key)},ObjectSeq.prototype.__iterate=function(fn,reverse){for(var object=this._object,keys=this._keys,maxIndex=keys.length-1,ii=0;maxIndex>=ii;ii++){var key=keys[reverse?maxIndex-ii:ii];if(fn(object[key],key,this)===!1)return ii+1}return ii},ObjectSeq.prototype.__iterator=function(type,reverse){var object=this._object,keys=this._keys,maxIndex=keys.length-1,ii=0;return new src_Iterator__Iterator(function(){var key=keys[reverse?maxIndex-ii:ii];return ii++>maxIndex?iteratorDone():iteratorValue(type,key,object[key])})},ObjectSeq.prototype[IS_ORDERED_SENTINEL]=!0,createClass(IterableSeq,IndexedSeq),IterableSeq.prototype.__iterateUncached=function(fn,reverse){if(reverse)return this.cacheResult().__iterate(fn,reverse);var iterable=this._iterable,iterator=getIterator(iterable),iterations=0;if(isIterator(iterator))for(var step;!(step=iterator.next()).done&&fn(step.value,iterations++,this)!==!1;);return iterations},IterableSeq.prototype.__iteratorUncached=function(type,reverse){if(reverse)return this.cacheResult().__iterator(type,reverse);var iterable=this._iterable,iterator=getIterator(iterable);if(!isIterator(iterator))return new src_Iterator__Iterator(iteratorDone);var iterations=0;return new src_Iterator__Iterator(function(){var step=iterator.next();return step.done?step:iteratorValue(type,iterations++,step.value)})},createClass(IteratorSeq,IndexedSeq),IteratorSeq.prototype.__iterateUncached=function(fn,reverse){if(reverse)return this.cacheResult().__iterate(fn,reverse);for(var iterator=this._iterator,cache=this._iteratorCache,iterations=0;iterations=cache.length){var step=iterator.next();if(step.done)return step;cache[iterations]=step.value}return iteratorValue(type,iterations,cache[iterations++])})};var EMPTY_SEQ;createClass(Collection,Iterable),createClass(KeyedCollection,Collection),createClass(IndexedCollection,Collection),createClass(SetCollection,Collection),Collection.Keyed=KeyedCollection,Collection.Indexed=IndexedCollection,Collection.Set=SetCollection;var weakMap,src_Math__imul="function"==typeof Math.imul&&-2===Math.imul(4294967295,2)?Math.imul:function(a,b){a=0|a,b=0|b;var c=65535&a,d=65535&b;return c*d+((a>>>16)*d+c*(b>>>16)<<16>>>0)|0},isExtensible=Object.isExtensible,canDefineProperty=function(){try{return Object.defineProperty({},"@",{}),!0}catch(e){return!1}}(),usingWeakMap="function"==typeof WeakMap;usingWeakMap&&(weakMap=new WeakMap);var objHashUID=0,UID_HASH_KEY="__immutablehash__";"function"==typeof Symbol&&(UID_HASH_KEY=Symbol(UID_HASH_KEY));var STRING_HASH_CACHE_MIN_STRLEN=16,STRING_HASH_CACHE_MAX_SIZE=255,STRING_HASH_CACHE_SIZE=0,stringHashCache={};createClass(ToKeyedSequence,KeyedSeq),ToKeyedSequence.prototype.get=function(key,notSetValue){return this._iter.get(key,notSetValue)},ToKeyedSequence.prototype.has=function(key){return this._iter.has(key)},ToKeyedSequence.prototype.valueSeq=function(){return this._iter.valueSeq()},ToKeyedSequence.prototype.reverse=function(){var this$0=this,reversedSequence=reverseFactory(this,!0);return this._useKeys||(reversedSequence.valueSeq=function(){return this$0._iter.toSeq().reverse()}),reversedSequence},ToKeyedSequence.prototype.map=function(mapper,context){var this$0=this,mappedSequence=mapFactory(this,mapper,context);return this._useKeys||(mappedSequence.valueSeq=function(){return this$0._iter.toSeq().map(mapper,context)}),mappedSequence},ToKeyedSequence.prototype.__iterate=function(fn,reverse){var ii,this$0=this;return this._iter.__iterate(this._useKeys?function(v,k){return fn(v,k,this$0)}:(ii=reverse?resolveSize(this):0,function(v){return fn(v,reverse?--ii:ii++,this$0)}),reverse)},ToKeyedSequence.prototype.__iterator=function(type,reverse){if(this._useKeys)return this._iter.__iterator(type,reverse);var iterator=this._iter.__iterator(ITERATE_VALUES,reverse),ii=reverse?resolveSize(this):0;return new src_Iterator__Iterator(function(){var step=iterator.next();return step.done?step:iteratorValue(type,reverse?--ii:ii++,step.value,step)})},ToKeyedSequence.prototype[IS_ORDERED_SENTINEL]=!0,createClass(ToIndexedSequence,IndexedSeq),ToIndexedSequence.prototype.includes=function(value){return this._iter.includes(value)},ToIndexedSequence.prototype.__iterate=function(fn,reverse){var this$0=this,iterations=0;return this._iter.__iterate(function(v){return fn(v,iterations++,this$0)},reverse)},ToIndexedSequence.prototype.__iterator=function(type,reverse){var iterator=this._iter.__iterator(ITERATE_VALUES,reverse),iterations=0;return new src_Iterator__Iterator(function(){var step=iterator.next();return step.done?step:iteratorValue(type,iterations++,step.value,step)})},createClass(ToSetSequence,SetSeq),ToSetSequence.prototype.has=function(key){return this._iter.includes(key)},ToSetSequence.prototype.__iterate=function(fn,reverse){var this$0=this;return this._iter.__iterate(function(v){return fn(v,v,this$0)},reverse)},ToSetSequence.prototype.__iterator=function(type,reverse){var iterator=this._iter.__iterator(ITERATE_VALUES,reverse);return new src_Iterator__Iterator(function(){var step=iterator.next();return step.done?step:iteratorValue(type,step.value,step.value,step)})},createClass(FromEntriesSequence,KeyedSeq),FromEntriesSequence.prototype.entrySeq=function(){return this._iter.toSeq()},FromEntriesSequence.prototype.__iterate=function(fn,reverse){var this$0=this;return this._iter.__iterate(function(entry){if(entry){validateEntry(entry);var indexedIterable=isIterable(entry);return fn(indexedIterable?entry.get(1):entry[1],indexedIterable?entry.get(0):entry[0],this$0)}},reverse)},FromEntriesSequence.prototype.__iterator=function(type,reverse){var iterator=this._iter.__iterator(ITERATE_VALUES,reverse);return new src_Iterator__Iterator(function(){for(;;){var step=iterator.next();if(step.done)return step;var entry=step.value;if(entry){validateEntry(entry);var indexedIterable=isIterable(entry);return iteratorValue(type,indexedIterable?entry.get(0):entry[0],indexedIterable?entry.get(1):entry[1],step)}}})},ToIndexedSequence.prototype.cacheResult=ToKeyedSequence.prototype.cacheResult=ToSetSequence.prototype.cacheResult=FromEntriesSequence.prototype.cacheResult=cacheResultThrough,createClass(src_Map__Map,KeyedCollection),src_Map__Map.prototype.toString=function(){return this.__toString("Map {","}")},src_Map__Map.prototype.get=function(k,notSetValue){return this._root?this._root.get(0,void 0,k,notSetValue):notSetValue},src_Map__Map.prototype.set=function(k,v){return updateMap(this,k,v)},src_Map__Map.prototype.setIn=function(keyPath,v){return this.updateIn(keyPath,NOT_SET,function(){return v})},src_Map__Map.prototype.remove=function(k){return updateMap(this,k,NOT_SET)},src_Map__Map.prototype.deleteIn=function(keyPath){return this.updateIn(keyPath,function(){return NOT_SET})},src_Map__Map.prototype.update=function(k,notSetValue,updater){return 1===arguments.length?k(this):this.updateIn([k],notSetValue,updater)},src_Map__Map.prototype.updateIn=function(keyPath,notSetValue,updater){updater||(updater=notSetValue,notSetValue=void 0);var updatedValue=updateInDeepMap(this,forceIterator(keyPath),notSetValue,updater);return updatedValue===NOT_SET?void 0:updatedValue},src_Map__Map.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):emptyMap()},src_Map__Map.prototype.merge=function(){return mergeIntoMapWith(this,void 0,arguments)},src_Map__Map.prototype.mergeWith=function(merger){var iters=SLICE$0.call(arguments,1);return mergeIntoMapWith(this,merger,iters)},src_Map__Map.prototype.mergeIn=function(keyPath){var iters=SLICE$0.call(arguments,1);return this.updateIn(keyPath,emptyMap(),function(m){return"function"==typeof m.merge?m.merge.apply(m,iters):iters[iters.length-1]})},src_Map__Map.prototype.mergeDeep=function(){return mergeIntoMapWith(this,deepMerger(void 0),arguments)},src_Map__Map.prototype.mergeDeepWith=function(merger){var iters=SLICE$0.call(arguments,1);return mergeIntoMapWith(this,deepMerger(merger),iters)},src_Map__Map.prototype.mergeDeepIn=function(keyPath){var iters=SLICE$0.call(arguments,1);return this.updateIn(keyPath,emptyMap(),function(m){return"function"==typeof m.mergeDeep?m.mergeDeep.apply(m,iters):iters[iters.length-1]})},src_Map__Map.prototype.sort=function(comparator){return OrderedMap(sortFactory(this,comparator))},src_Map__Map.prototype.sortBy=function(mapper,comparator){return OrderedMap(sortFactory(this,comparator,mapper))},src_Map__Map.prototype.withMutations=function(fn){var mutable=this.asMutable();return fn(mutable),mutable.wasAltered()?mutable.__ensureOwner(this.__ownerID):this},src_Map__Map.prototype.asMutable=function(){return this.__ownerID?this:this.__ensureOwner(new OwnerID)},src_Map__Map.prototype.asImmutable=function(){return this.__ensureOwner()},src_Map__Map.prototype.wasAltered=function(){return this.__altered},src_Map__Map.prototype.__iterator=function(type,reverse){return new MapIterator(this,type,reverse)},src_Map__Map.prototype.__iterate=function(fn,reverse){var this$0=this,iterations=0;return this._root&&this._root.iterate(function(entry){return iterations++,fn(entry[1],entry[0],this$0)},reverse),iterations},src_Map__Map.prototype.__ensureOwner=function(ownerID){return ownerID===this.__ownerID?this:ownerID?makeMap(this.size,this._root,ownerID,this.__hash):(this.__ownerID=ownerID,this.__altered=!1,this)},src_Map__Map.isMap=isMap;var IS_MAP_SENTINEL="@@__IMMUTABLE_MAP__@@",MapPrototype=src_Map__Map.prototype;MapPrototype[IS_MAP_SENTINEL]=!0,MapPrototype[DELETE]=MapPrototype.remove,MapPrototype.removeIn=MapPrototype.deleteIn,ArrayMapNode.prototype.get=function(shift,keyHash,key,notSetValue){for(var entries=this.entries,ii=0,len=entries.length;len>ii;ii++)if(is(key,entries[ii][0]))return entries[ii][1];return notSetValue},ArrayMapNode.prototype.update=function(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){for(var removed=value===NOT_SET,entries=this.entries,idx=0,len=entries.length;len>idx&&!is(key,entries[idx][0]);idx++);var exists=len>idx;if(exists?entries[idx][1]===value:removed)return this;if(SetRef(didAlter),(removed||!exists)&&SetRef(didChangeSize),!removed||1!==entries.length){if(!exists&&!removed&&entries.length>=MAX_ARRAY_MAP_SIZE)return createNodes(ownerID,entries,key,value);var isEditable=ownerID&&ownerID===this.ownerID,newEntries=isEditable?entries:arrCopy(entries);return exists?removed?idx===len-1?newEntries.pop():newEntries[idx]=newEntries.pop():newEntries[idx]=[key,value]:newEntries.push([key,value]),isEditable?(this.entries=newEntries,this):new ArrayMapNode(ownerID,newEntries)}},BitmapIndexedNode.prototype.get=function(shift,keyHash,key,notSetValue){void 0===keyHash&&(keyHash=hash(key));var bit=1<<((0===shift?keyHash:keyHash>>>shift)&MASK),bitmap=this.bitmap;return 0===(bitmap&bit)?notSetValue:this.nodes[popCount(bitmap&bit-1)].get(shift+SHIFT,keyHash,key,notSetValue)},BitmapIndexedNode.prototype.update=function(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){void 0===keyHash&&(keyHash=hash(key));var keyHashFrag=(0===shift?keyHash:keyHash>>>shift)&MASK,bit=1<=MAX_BITMAP_INDEXED_SIZE)return expandNodes(ownerID,nodes,bitmap,keyHashFrag,newNode);if(exists&&!newNode&&2===nodes.length&&isLeafNode(nodes[1^idx]))return nodes[1^idx];if(exists&&newNode&&1===nodes.length&&isLeafNode(newNode))return newNode;var isEditable=ownerID&&ownerID===this.ownerID,newBitmap=exists?newNode?bitmap:bitmap^bit:bitmap|bit,newNodes=exists?newNode?setIn(nodes,idx,newNode,isEditable):spliceOut(nodes,idx,isEditable):spliceIn(nodes,idx,newNode,isEditable);return isEditable?(this.bitmap=newBitmap,this.nodes=newNodes,this):new BitmapIndexedNode(ownerID,newBitmap,newNodes)},HashArrayMapNode.prototype.get=function(shift,keyHash,key,notSetValue){void 0===keyHash&&(keyHash=hash(key));var idx=(0===shift?keyHash:keyHash>>>shift)&MASK,node=this.nodes[idx];return node?node.get(shift+SHIFT,keyHash,key,notSetValue):notSetValue},HashArrayMapNode.prototype.update=function(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){void 0===keyHash&&(keyHash=hash(key));var idx=(0===shift?keyHash:keyHash>>>shift)&MASK,removed=value===NOT_SET,nodes=this.nodes,node=nodes[idx]; -if(removed&&!node)return this;var newNode=updateNode(node,ownerID,shift+SHIFT,keyHash,key,value,didChangeSize,didAlter);if(newNode===node)return this;var newCount=this.count;if(node){if(!newNode&&(newCount--,MIN_HASH_ARRAY_MAP_SIZE>newCount))return packNodes(ownerID,nodes,newCount,idx)}else newCount++;var isEditable=ownerID&&ownerID===this.ownerID,newNodes=setIn(nodes,idx,newNode,isEditable);return isEditable?(this.count=newCount,this.nodes=newNodes,this):new HashArrayMapNode(ownerID,newCount,newNodes)},HashCollisionNode.prototype.get=function(shift,keyHash,key,notSetValue){for(var entries=this.entries,ii=0,len=entries.length;len>ii;ii++)if(is(key,entries[ii][0]))return entries[ii][1];return notSetValue},HashCollisionNode.prototype.update=function(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){void 0===keyHash&&(keyHash=hash(key));var removed=value===NOT_SET;if(keyHash!==this.keyHash)return removed?this:(SetRef(didAlter),SetRef(didChangeSize),mergeIntoNode(this,ownerID,shift,keyHash,[key,value]));for(var entries=this.entries,idx=0,len=entries.length;len>idx&&!is(key,entries[idx][0]);idx++);var exists=len>idx;if(exists?entries[idx][1]===value:removed)return this;if(SetRef(didAlter),(removed||!exists)&&SetRef(didChangeSize),removed&&2===len)return new ValueNode(ownerID,this.keyHash,entries[1^idx]);var isEditable=ownerID&&ownerID===this.ownerID,newEntries=isEditable?entries:arrCopy(entries);return exists?removed?idx===len-1?newEntries.pop():newEntries[idx]=newEntries.pop():newEntries[idx]=[key,value]:newEntries.push([key,value]),isEditable?(this.entries=newEntries,this):new HashCollisionNode(ownerID,this.keyHash,newEntries)},ValueNode.prototype.get=function(shift,keyHash,key,notSetValue){return is(key,this.entry[0])?this.entry[1]:notSetValue},ValueNode.prototype.update=function(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){var removed=value===NOT_SET,keyMatch=is(key,this.entry[0]);return(keyMatch?value===this.entry[1]:removed)?this:(SetRef(didAlter),removed?void SetRef(didChangeSize):keyMatch?ownerID&&ownerID===this.ownerID?(this.entry[1]=value,this):new ValueNode(ownerID,this.keyHash,[key,value]):(SetRef(didChangeSize),mergeIntoNode(this,ownerID,shift,hash(key),[key,value])))},ArrayMapNode.prototype.iterate=HashCollisionNode.prototype.iterate=function(fn,reverse){for(var entries=this.entries,ii=0,maxIndex=entries.length-1;maxIndex>=ii;ii++)if(fn(entries[reverse?maxIndex-ii:ii])===!1)return!1},BitmapIndexedNode.prototype.iterate=HashArrayMapNode.prototype.iterate=function(fn,reverse){for(var nodes=this.nodes,ii=0,maxIndex=nodes.length-1;maxIndex>=ii;ii++){var node=nodes[reverse?maxIndex-ii:ii];if(node&&node.iterate(fn,reverse)===!1)return!1}},ValueNode.prototype.iterate=function(fn,reverse){return fn(this.entry)},createClass(MapIterator,src_Iterator__Iterator),MapIterator.prototype.next=function(){for(var type=this._type,stack=this._stack;stack;){var maxIndex,node=stack.node,index=stack.index++;if(node.entry){if(0===index)return mapIteratorValue(type,node.entry)}else if(node.entries){if(maxIndex=node.entries.length-1,maxIndex>=index)return mapIteratorValue(type,node.entries[this._reverse?maxIndex-index:index])}else if(maxIndex=node.nodes.length-1,maxIndex>=index){var subNode=node.nodes[this._reverse?maxIndex-index:index];if(subNode){if(subNode.entry)return mapIteratorValue(type,subNode.entry);stack=this._stack=mapIteratorFrame(subNode,stack)}continue}stack=this._stack=this._stack.__prev}return iteratorDone()};var EMPTY_MAP,MAX_ARRAY_MAP_SIZE=SIZE/4,MAX_BITMAP_INDEXED_SIZE=SIZE/2,MIN_HASH_ARRAY_MAP_SIZE=SIZE/4;createClass(List,IndexedCollection),List.of=function(){return this(arguments)},List.prototype.toString=function(){return this.__toString("List [","]")},List.prototype.get=function(index,notSetValue){if(index=wrapIndex(this,index),index>=0&&index>>level&MASK;if(originIndex>=this.array.length)return new VNode([],ownerID);var newChild,removingFirst=0===originIndex;if(level>0){var oldChild=this.array[originIndex];if(newChild=oldChild&&oldChild.removeBefore(ownerID,level-SHIFT,index),newChild===oldChild&&removingFirst)return this}if(removingFirst&&!newChild)return this;var editable=editableVNode(this,ownerID);if(!removingFirst)for(var ii=0;originIndex>ii;ii++)editable.array[ii]=void 0;return newChild&&(editable.array[originIndex]=newChild),editable},VNode.prototype.removeAfter=function(ownerID,level,index){if(index===(level?1<>>level&MASK;if(sizeIndex>=this.array.length)return this;var newChild;if(level>0){var oldChild=this.array[sizeIndex];if(newChild=oldChild&&oldChild.removeAfter(ownerID,level-SHIFT,index),newChild===oldChild&&sizeIndex===this.array.length-1)return this}var editable=editableVNode(this,ownerID);return editable.array.splice(sizeIndex+1),newChild&&(editable.array[sizeIndex]=newChild),editable};var EMPTY_LIST,DONE={};createClass(OrderedMap,src_Map__Map),OrderedMap.of=function(){return this(arguments)},OrderedMap.prototype.toString=function(){return this.__toString("OrderedMap {","}")},OrderedMap.prototype.get=function(k,notSetValue){var index=this._map.get(k);return void 0!==index?this._list.get(index)[1]:notSetValue},OrderedMap.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._map.clear(),this._list.clear(),this):emptyOrderedMap()},OrderedMap.prototype.set=function(k,v){return updateOrderedMap(this,k,v)},OrderedMap.prototype.remove=function(k){return updateOrderedMap(this,k,NOT_SET)},OrderedMap.prototype.wasAltered=function(){return this._map.wasAltered()||this._list.wasAltered()},OrderedMap.prototype.__iterate=function(fn,reverse){var this$0=this;return this._list.__iterate(function(entry){return entry&&fn(entry[1],entry[0],this$0)},reverse)},OrderedMap.prototype.__iterator=function(type,reverse){return this._list.fromEntrySeq().__iterator(type,reverse)},OrderedMap.prototype.__ensureOwner=function(ownerID){if(ownerID===this.__ownerID)return this;var newMap=this._map.__ensureOwner(ownerID),newList=this._list.__ensureOwner(ownerID);return ownerID?makeOrderedMap(newMap,newList,ownerID,this.__hash):(this.__ownerID=ownerID,this._map=newMap,this._list=newList,this)},OrderedMap.isOrderedMap=isOrderedMap,OrderedMap.prototype[IS_ORDERED_SENTINEL]=!0,OrderedMap.prototype[DELETE]=OrderedMap.prototype.remove;var EMPTY_ORDERED_MAP;createClass(Stack,IndexedCollection),Stack.of=function(){return this(arguments)},Stack.prototype.toString=function(){return this.__toString("Stack [","]")},Stack.prototype.get=function(index,notSetValue){var head=this._head;for(index=wrapIndex(this,index);head&&index--;)head=head.next;return head?head.value:notSetValue},Stack.prototype.peek=function(){return this._head&&this._head.value},Stack.prototype.push=function(){if(0===arguments.length)return this;for(var newSize=this.size+arguments.length,head=this._head,ii=arguments.length-1;ii>=0;ii--)head={value:arguments[ii],next:head};return this.__ownerID?(this.size=newSize,this._head=head,this.__hash=void 0,this.__altered=!0,this):makeStack(newSize,head)},Stack.prototype.pushAll=function(iter){if(iter=IndexedIterable(iter),0===iter.size)return this;assertNotInfinite(iter.size);var newSize=this.size,head=this._head;return iter.reverse().forEach(function(value){newSize++,head={value:value,next:head}}),this.__ownerID?(this.size=newSize,this._head=head,this.__hash=void 0,this.__altered=!0,this):makeStack(newSize,head)},Stack.prototype.pop=function(){return this.slice(1)},Stack.prototype.unshift=function(){return this.push.apply(this,arguments)},Stack.prototype.unshiftAll=function(iter){return this.pushAll(iter)},Stack.prototype.shift=function(){return this.pop.apply(this,arguments)},Stack.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._head=void 0,this.__hash=void 0,this.__altered=!0,this):emptyStack()},Stack.prototype.slice=function(begin,end){if(wholeSlice(begin,end,this.size))return this;var resolvedBegin=resolveBegin(begin,this.size),resolvedEnd=resolveEnd(end,this.size);if(resolvedEnd!==this.size)return IndexedCollection.prototype.slice.call(this,begin,end);for(var newSize=this.size-resolvedBegin,head=this._head;resolvedBegin--;)head=head.next;return this.__ownerID?(this.size=newSize,this._head=head,this.__hash=void 0,this.__altered=!0,this):makeStack(newSize,head)},Stack.prototype.__ensureOwner=function(ownerID){return ownerID===this.__ownerID?this:ownerID?makeStack(this.size,this._head,ownerID,this.__hash):(this.__ownerID=ownerID,this.__altered=!1,this)},Stack.prototype.__iterate=function(fn,reverse){if(reverse)return this.reverse().__iterate(fn);for(var iterations=0,node=this._head;node&&fn(node.value,iterations++,this)!==!1;)node=node.next;return iterations},Stack.prototype.__iterator=function(type,reverse){if(reverse)return this.reverse().__iterator(type);var iterations=0,node=this._head;return new src_Iterator__Iterator(function(){if(node){var value=node.value;return node=node.next,iteratorValue(type,iterations++,value)}return iteratorDone()})},Stack.isStack=isStack;var IS_STACK_SENTINEL="@@__IMMUTABLE_STACK__@@",StackPrototype=Stack.prototype;StackPrototype[IS_STACK_SENTINEL]=!0,StackPrototype.withMutations=MapPrototype.withMutations,StackPrototype.asMutable=MapPrototype.asMutable,StackPrototype.asImmutable=MapPrototype.asImmutable,StackPrototype.wasAltered=MapPrototype.wasAltered;var EMPTY_STACK;createClass(src_Set__Set,SetCollection),src_Set__Set.of=function(){return this(arguments)},src_Set__Set.fromKeys=function(value){return this(KeyedIterable(value).keySeq())},src_Set__Set.prototype.toString=function(){return this.__toString("Set {","}")},src_Set__Set.prototype.has=function(value){return this._map.has(value)},src_Set__Set.prototype.add=function(value){return updateSet(this,this._map.set(value,!0))},src_Set__Set.prototype.remove=function(value){return updateSet(this,this._map.remove(value))},src_Set__Set.prototype.clear=function(){return updateSet(this,this._map.clear())},src_Set__Set.prototype.union=function(){var iters=SLICE$0.call(arguments,0);return iters=iters.filter(function(x){return 0!==x.size}),0===iters.length?this:0!==this.size||this.__ownerID||1!==iters.length?this.withMutations(function(set){for(var ii=0;ii1?" by "+this._step:"")+" ]"},Range.prototype.get=function(index,notSetValue){return this.has(index)?this._start+wrapIndex(this,index)*this._step:notSetValue},Range.prototype.includes=function(searchValue){var possibleIndex=(searchValue-this._start)/this._step;return possibleIndex>=0&&possibleIndex=end?new Range(0,0):new Range(this.get(begin,this._end),this.get(end,this._end),this._step))},Range.prototype.indexOf=function(searchValue){var offsetValue=searchValue-this._start;if(offsetValue%this._step===0){var index=offsetValue/this._step;if(index>=0&&index=ii;ii++){if(fn(value,ii,this)===!1)return ii+1;value+=reverse?-step:step}return ii},Range.prototype.__iterator=function(type,reverse){var maxIndex=this.size-1,step=this._step,value=reverse?this._start+maxIndex*step:this._start,ii=0;return new src_Iterator__Iterator(function(){var v=value;return value+=reverse?-step:step,ii>maxIndex?iteratorDone():iteratorValue(type,ii++,v)})},Range.prototype.equals=function(other){return other instanceof Range?this._start===other._start&&this._end===other._end&&this._step===other._step:deepEqual(this,other)};var EMPTY_RANGE;createClass(Repeat,IndexedSeq),Repeat.prototype.toString=function(){return 0===this.size?"Repeat []":"Repeat [ "+this._value+" "+this.size+" times ]"},Repeat.prototype.get=function(index,notSetValue){return this.has(index)?this._value:notSetValue},Repeat.prototype.includes=function(searchValue){return is(this._value,searchValue)},Repeat.prototype.slice=function(begin,end){var size=this.size;return wholeSlice(begin,end,size)?this:new Repeat(this._value,resolveEnd(end,size)-resolveBegin(begin,size))},Repeat.prototype.reverse=function(){return this},Repeat.prototype.indexOf=function(searchValue){return is(this._value,searchValue)?0:-1},Repeat.prototype.lastIndexOf=function(searchValue){return is(this._value,searchValue)?this.size:-1},Repeat.prototype.__iterate=function(fn,reverse){for(var ii=0;iiindex?this.count():this.size);var spliced=this.slice(0,index);return reify(this,1===numArgs?spliced:spliced.concat(arrCopy(arguments,2),this.slice(index+removeNum)))},findLastIndex:function(predicate,context){var key=this.toKeyedSeq().findLastKey(predicate,context);return void 0===key?-1:key},first:function(){return this.get(0)},flatten:function(depth){return reify(this,flattenFactory(this,depth,!1))},get:function(index,notSetValue){return index=wrapIndex(this,index),0>index||this.size===1/0||void 0!==this.size&&index>this.size?notSetValue:this.find(function(_,key){ -return key===index},void 0,notSetValue)},has:function(index){return index=wrapIndex(this,index),index>=0&&(void 0!==this.size?this.size===1/0||indexi;i++){var currentItem=_cloneObject(this._options.steps[i]);if(currentItem.step=introItems.length+1,"string"==typeof currentItem.element&&(currentItem.element=document.querySelector(currentItem.element)),"undefined"==typeof currentItem.element||null==currentItem.element){var floatingElementQuery=document.querySelector(".introjsFloatingElement");null==floatingElementQuery&&(floatingElementQuery=document.createElement("div"),floatingElementQuery.className="introjsFloatingElement",document.body.appendChild(floatingElementQuery)),currentItem.element=floatingElementQuery,currentItem.position="floating"}null!=currentItem.element&&introItems.push(currentItem)}else{var allIntroSteps=targetElm.querySelectorAll("*[data-intro]");if(allIntroSteps.length<1)return!1;for(var i=0,elmsLength=allIntroSteps.length;elmsLength>i;i++){var currentElement=allIntroSteps[i],step=parseInt(currentElement.getAttribute("data-step"),10);step>0&&(introItems[step-1]={element:currentElement,intro:currentElement.getAttribute("data-intro"),step:parseInt(currentElement.getAttribute("data-step"),10),tooltipClass:currentElement.getAttribute("data-tooltipClass"),highlightClass:currentElement.getAttribute("data-highlightClass"),position:currentElement.getAttribute("data-position")||this._options.tooltipPosition})}for(var nextStep=0,i=0,elmsLength=allIntroSteps.length;elmsLength>i;i++){var currentElement=allIntroSteps[i];if(null==currentElement.getAttribute("data-step")){for(;;){if("undefined"==typeof introItems[nextStep])break;nextStep++}introItems[nextStep]={element:currentElement,intro:currentElement.getAttribute("data-intro"),step:nextStep+1,tooltipClass:currentElement.getAttribute("data-tooltipClass"),highlightClass:currentElement.getAttribute("data-highlightClass"),position:currentElement.getAttribute("data-position")||this._options.tooltipPosition}}}}for(var tempIntroItems=[],z=0;z0?_previousStep.call(self):target&&target.className.indexOf("introjs-skipbutton")>0?(self._introItems.length-1==self._currentStep&&"function"==typeof self._introCompleteCallback&&self._introCompleteCallback.call(self),void 0!=self._introExitCallback&&self._introExitCallback.call(self),_exitIntro.call(self,targetElm)):_nextStep.call(self),e.preventDefault?e.preventDefault():e.returnValue=!1}},self._onResize=function(e){_setHelperLayerPosition.call(self,document.querySelector(".introjs-helperLayer")),_setHelperLayerPosition.call(self,document.querySelector(".introjs-tooltipReferenceLayer"))},window.addEventListener?(this._options.keyboardNavigation&&window.addEventListener("keydown",self._onKeyDown,!0),window.addEventListener("resize",self._onResize,!0)):document.attachEvent&&(this._options.keyboardNavigation&&document.attachEvent("onkeydown",self._onKeyDown),document.attachEvent("onresize",self._onResize))}return!1}function _cloneObject(object){if(null==object||"object"!=typeof object||"undefined"!=typeof object.nodeType)return object;var temp={};for(var key in object)"undefined"!=typeof jQuery&&object[key]instanceof jQuery?temp[key]=object[key]:temp[key]=_cloneObject(object[key]);return temp}function _goToStep(step){this._currentStep=step-2,"undefined"!=typeof this._introItems&&_nextStep.call(this)}function _nextStep(){if(this._direction="forward","undefined"==typeof this._currentStep?this._currentStep=0:++this._currentStep,this._introItems.length<=this._currentStep)return"function"==typeof this._introCompleteCallback&&this._introCompleteCallback.call(this),void _exitIntro.call(this,this._targetElement);var nextStep=this._introItems[this._currentStep];"undefined"!=typeof this._introBeforeChangeCallback&&this._introBeforeChangeCallback.call(this,nextStep.element),_showElement.call(this,nextStep)}function _previousStep(){if(this._direction="backward",0===this._currentStep)return!1;var nextStep=this._introItems[--this._currentStep];"undefined"!=typeof this._introBeforeChangeCallback&&this._introBeforeChangeCallback.call(this,nextStep.element),_showElement.call(this,nextStep)}function _exitIntro(targetElement){var overlayLayer=targetElement.querySelector(".introjs-overlay");if(null!=overlayLayer){overlayLayer.style.opacity=0,setTimeout(function(){overlayLayer.parentNode&&overlayLayer.parentNode.removeChild(overlayLayer)},500);var helperLayer=targetElement.querySelector(".introjs-helperLayer");helperLayer&&helperLayer.parentNode.removeChild(helperLayer);var referenceLayer=targetElement.querySelector(".introjs-tooltipReferenceLayer");referenceLayer&&referenceLayer.parentNode.removeChild(referenceLayer);var disableInteractionLayer=targetElement.querySelector(".introjs-disableInteraction");disableInteractionLayer&&disableInteractionLayer.parentNode.removeChild(disableInteractionLayer);var floatingElement=document.querySelector(".introjsFloatingElement");floatingElement&&floatingElement.parentNode.removeChild(floatingElement);var showElement=document.querySelector(".introjs-showElement");showElement&&(showElement.className=showElement.className.replace(/introjs-[a-zA-Z]+/g,"").replace(/^\s+|\s+$/g,""));var fixParents=document.querySelectorAll(".introjs-fixParent");if(fixParents&&fixParents.length>0)for(var i=fixParents.length-1;i>=0;i--)fixParents[i].className=fixParents[i].className.replace(/introjs-fixParent/g,"").replace(/^\s+|\s+$/g,"");window.removeEventListener?window.removeEventListener("keydown",this._onKeyDown,!0):document.detachEvent&&document.detachEvent("onkeydown",this._onKeyDown),this._currentStep=void 0}}function _placeTooltip(targetElement,tooltipLayer,arrowLayer,helperNumberLayer){var currentStepObj,tooltipOffset,targetOffset,windowSize,currentTooltipPosition,tooltipCssClass="";if(tooltipLayer.style.top=null,tooltipLayer.style.right=null,tooltipLayer.style.bottom=null,tooltipLayer.style.left=null,tooltipLayer.style.marginLeft=null,tooltipLayer.style.marginTop=null,arrowLayer.style.display="inherit","undefined"!=typeof helperNumberLayer&&null!=helperNumberLayer&&(helperNumberLayer.style.top=null,helperNumberLayer.style.left=null),this._introItems[this._currentStep])switch(currentStepObj=this._introItems[this._currentStep],tooltipCssClass="string"==typeof currentStepObj.tooltipClass?currentStepObj.tooltipClass:this._options.tooltipClass,tooltipLayer.className=("introjs-tooltip "+tooltipCssClass).replace(/^\s+|\s+$/g,""),currentTooltipPosition=this._introItems[this._currentStep].position,("auto"==currentTooltipPosition||"auto"==this._options.tooltipPosition)&&"floating"!=currentTooltipPosition&&(currentTooltipPosition=_determineAutoPosition.call(this,targetElement,tooltipLayer,currentTooltipPosition)),targetOffset=_getOffset(targetElement),tooltipOffset=_getOffset(tooltipLayer),windowSize=_getWinSize(),currentTooltipPosition){case"top":arrowLayer.className="introjs-arrow bottom";var tooltipLayerStyleLeft=15;_checkRight(targetOffset,tooltipLayerStyleLeft,tooltipOffset,windowSize,tooltipLayer),tooltipLayer.style.bottom=targetOffset.height+20+"px";break;case"right":tooltipLayer.style.left=targetOffset.width+20+"px",targetOffset.top+tooltipOffset.height>windowSize.height?(arrowLayer.className="introjs-arrow left-bottom",tooltipLayer.style.top="-"+(tooltipOffset.height-targetOffset.height-20)+"px"):arrowLayer.className="introjs-arrow left";break;case"left":1==this._options.showStepNumbers&&(tooltipLayer.style.top="15px"),targetOffset.top+tooltipOffset.height>windowSize.height?(tooltipLayer.style.top="-"+(tooltipOffset.height-targetOffset.height-20)+"px",arrowLayer.className="introjs-arrow right-bottom"):arrowLayer.className="introjs-arrow right",tooltipLayer.style.right=targetOffset.width+20+"px";break;case"floating":arrowLayer.style.display="none",tooltipLayer.style.left="50%",tooltipLayer.style.top="50%",tooltipLayer.style.marginLeft="-"+tooltipOffset.width/2+"px",tooltipLayer.style.marginTop="-"+tooltipOffset.height/2+"px","undefined"!=typeof helperNumberLayer&&null!=helperNumberLayer&&(helperNumberLayer.style.left="-"+(tooltipOffset.width/2+18)+"px",helperNumberLayer.style.top="-"+(tooltipOffset.height/2+18)+"px");break;case"bottom-right-aligned":arrowLayer.className="introjs-arrow top-right";var tooltipLayerStyleRight=0;_checkLeft(targetOffset,tooltipLayerStyleRight,tooltipOffset,tooltipLayer),tooltipLayer.style.top=targetOffset.height+20+"px";break;case"bottom-middle-aligned":arrowLayer.className="introjs-arrow top-middle";var tooltipLayerStyleLeftRight=targetOffset.width/2-tooltipOffset.width/2;_checkLeft(targetOffset,tooltipLayerStyleLeftRight,tooltipOffset,tooltipLayer)&&(tooltipLayer.style.right=null,_checkRight(targetOffset,tooltipLayerStyleLeftRight,tooltipOffset,windowSize,tooltipLayer)),tooltipLayer.style.top=targetOffset.height+20+"px";break;case"bottom-left-aligned":case"bottom":default:arrowLayer.className="introjs-arrow top";var tooltipLayerStyleLeft=0;_checkRight(targetOffset,tooltipLayerStyleLeft,tooltipOffset,windowSize,tooltipLayer),tooltipLayer.style.top=targetOffset.height+20+"px"}}function _checkRight(targetOffset,tooltipLayerStyleLeft,tooltipOffset,windowSize,tooltipLayer){return targetOffset.left+tooltipLayerStyleLeft+tooltipOffset.width>windowSize.width?(tooltipLayer.style.left=windowSize.width-tooltipOffset.width-targetOffset.left+"px",!1):(tooltipLayer.style.left=tooltipLayerStyleLeft+"px",!0)}function _checkLeft(targetOffset,tooltipLayerStyleRight,tooltipOffset,tooltipLayer){return targetOffset.left+targetOffset.width-tooltipLayerStyleRight-tooltipOffset.width<0?(tooltipLayer.style.left=-targetOffset.left+"px",!1):(tooltipLayer.style.right=tooltipLayerStyleRight+"px",!0)}function _determineAutoPosition(targetElement,tooltipLayer,desiredTooltipPosition){var possiblePositions=this._options.positionPrecedence.slice(),windowSize=_getWinSize(),tooltipHeight=_getOffset(tooltipLayer).height+10,tooltipWidth=_getOffset(tooltipLayer).width+20,targetOffset=_getOffset(targetElement),calculatedPosition="floating";return targetOffset.left+tooltipWidth>windowSize.width||targetOffset.left+targetOffset.width/2-tooltipWidth<0?(_removeEntry(possiblePositions,"bottom"),_removeEntry(possiblePositions,"top")):(targetOffset.height+targetOffset.top+tooltipHeight>windowSize.height&&_removeEntry(possiblePositions,"bottom"),targetOffset.top-tooltipHeight<0&&_removeEntry(possiblePositions,"top")),targetOffset.width+targetOffset.left+tooltipWidth>windowSize.width&&_removeEntry(possiblePositions,"right"),targetOffset.left-tooltipWidth<0&&_removeEntry(possiblePositions,"left"),possiblePositions.length>0&&(calculatedPosition=possiblePositions[0]),desiredTooltipPosition&&"auto"!=desiredTooltipPosition&&possiblePositions.indexOf(desiredTooltipPosition)>-1&&(calculatedPosition=desiredTooltipPosition),calculatedPosition}function _removeEntry(stringArray,stringToRemove){stringArray.indexOf(stringToRemove)>-1&&stringArray.splice(stringArray.indexOf(stringToRemove),1)}function _setHelperLayerPosition(helperLayer){if(helperLayer){if(!this._introItems[this._currentStep])return;var currentElement=this._introItems[this._currentStep],elementPosition=_getOffset(currentElement.element),widthHeightPadding=10;"floating"==currentElement.position&&(widthHeightPadding=0),helperLayer.setAttribute("style","width: "+(elementPosition.width+widthHeightPadding)+"px; height:"+(elementPosition.height+widthHeightPadding)+"px; top:"+(elementPosition.top-5)+"px;left: "+(elementPosition.left-5)+"px;")}}function _disableInteraction(){var disableInteractionLayer=document.querySelector(".introjs-disableInteraction");null===disableInteractionLayer&&(disableInteractionLayer=document.createElement("div"),disableInteractionLayer.className="introjs-disableInteraction",this._targetElement.appendChild(disableInteractionLayer)),_setHelperLayerPosition.call(this,disableInteractionLayer)}function _showElement(targetElement){"undefined"!=typeof this._introChangeCallback&&this._introChangeCallback.call(this,targetElement.element);var self=this,oldHelperLayer=document.querySelector(".introjs-helperLayer"),oldReferenceLayer=document.querySelector(".introjs-tooltipReferenceLayer"),highlightClass="introjs-helperLayer";_getOffset(targetElement.element);if("string"==typeof targetElement.highlightClass&&(highlightClass+=" "+targetElement.highlightClass),"string"==typeof this._options.highlightClass&&(highlightClass+=" "+this._options.highlightClass),null!=oldHelperLayer){var oldHelperNumberLayer=oldReferenceLayer.querySelector(".introjs-helperNumberLayer"),oldtooltipLayer=oldReferenceLayer.querySelector(".introjs-tooltiptext"),oldArrowLayer=oldReferenceLayer.querySelector(".introjs-arrow"),oldtooltipContainer=oldReferenceLayer.querySelector(".introjs-tooltip"),skipTooltipButton=oldReferenceLayer.querySelector(".introjs-skipbutton"),prevTooltipButton=oldReferenceLayer.querySelector(".introjs-prevbutton"),nextTooltipButton=oldReferenceLayer.querySelector(".introjs-nextbutton");if(oldHelperLayer.className=highlightClass,oldtooltipContainer.style.opacity=0,oldtooltipContainer.style.display="none",null!=oldHelperNumberLayer){var lastIntroItem=this._introItems[targetElement.step-2>=0?targetElement.step-2:0];(null!=lastIntroItem&&"forward"==this._direction&&"floating"==lastIntroItem.position||"backward"==this._direction&&"floating"==targetElement.position)&&(oldHelperNumberLayer.style.opacity=0)}_setHelperLayerPosition.call(self,oldHelperLayer),_setHelperLayerPosition.call(self,oldReferenceLayer);var fixParents=document.querySelectorAll(".introjs-fixParent");if(fixParents&&fixParents.length>0)for(var i=fixParents.length-1;i>=0;i--)fixParents[i].className=fixParents[i].className.replace(/introjs-fixParent/g,"").replace(/^\s+|\s+$/g,"");var oldShowElement=document.querySelector(".introjs-showElement");oldShowElement.className=oldShowElement.className.replace(/introjs-[a-zA-Z]+/g,"").replace(/^\s+|\s+$/g,""),self._lastShowElementTimer&&clearTimeout(self._lastShowElementTimer),self._lastShowElementTimer=setTimeout(function(){null!=oldHelperNumberLayer&&(oldHelperNumberLayer.innerHTML=targetElement.step),oldtooltipLayer.innerHTML=targetElement.intro,oldtooltipContainer.style.display="block",_placeTooltip.call(self,targetElement.element,oldtooltipContainer,oldArrowLayer,oldHelperNumberLayer),oldReferenceLayer.querySelector(".introjs-bullets li > a.active").className="",oldReferenceLayer.querySelector('.introjs-bullets li > a[data-stepnumber="'+targetElement.step+'"]').className="active",oldReferenceLayer.querySelector(".introjs-progress .introjs-progressbar").setAttribute("style","width:"+_getProgress.call(self)+"%;"),oldtooltipContainer.style.opacity=1,oldHelperNumberLayer&&(oldHelperNumberLayer.style.opacity=1),-1===nextTooltipButton.tabIndex?skipTooltipButton.focus():nextTooltipButton.focus()},350)}else{var helperLayer=document.createElement("div"),referenceLayer=document.createElement("div"),arrowLayer=document.createElement("div"),tooltipLayer=document.createElement("div"),tooltipTextLayer=document.createElement("div"),bulletsLayer=document.createElement("div"),progressLayer=document.createElement("div"),buttonsLayer=document.createElement("div");helperLayer.className=highlightClass,referenceLayer.className="introjs-tooltipReferenceLayer",_setHelperLayerPosition.call(self,helperLayer),_setHelperLayerPosition.call(self,referenceLayer),this._targetElement.appendChild(helperLayer),this._targetElement.appendChild(referenceLayer),arrowLayer.className="introjs-arrow",tooltipTextLayer.className="introjs-tooltiptext",tooltipTextLayer.innerHTML=targetElement.intro,bulletsLayer.className="introjs-bullets",this._options.showBullets===!1&&(bulletsLayer.style.display="none");for(var ulContainer=document.createElement("ul"),i=0,stepsLength=this._introItems.length;stepsLength>i;i++){var innerLi=document.createElement("li"),anchorLink=document.createElement("a");anchorLink.onclick=function(){self.goToStep(this.getAttribute("data-stepnumber"))},i===targetElement.step-1&&(anchorLink.className="active"),anchorLink.href="javascript:void(0);",anchorLink.innerHTML=" ",anchorLink.setAttribute("data-stepnumber",this._introItems[i].step),innerLi.appendChild(anchorLink),ulContainer.appendChild(innerLi)}bulletsLayer.appendChild(ulContainer),progressLayer.className="introjs-progress",this._options.showProgress===!1&&(progressLayer.style.display="none");var progressBar=document.createElement("div");if(progressBar.className="introjs-progressbar",progressBar.setAttribute("style","width:"+_getProgress.call(this)+"%;"),progressLayer.appendChild(progressBar),buttonsLayer.className="introjs-tooltipbuttons",this._options.showButtons===!1&&(buttonsLayer.style.display="none"),tooltipLayer.className="introjs-tooltip",tooltipLayer.appendChild(tooltipTextLayer),tooltipLayer.appendChild(bulletsLayer),tooltipLayer.appendChild(progressLayer),1==this._options.showStepNumbers){var helperNumberLayer=document.createElement("span");helperNumberLayer.className="introjs-helperNumberLayer",helperNumberLayer.innerHTML=targetElement.step,referenceLayer.appendChild(helperNumberLayer)}tooltipLayer.appendChild(arrowLayer),referenceLayer.appendChild(tooltipLayer);var nextTooltipButton=document.createElement("a");nextTooltipButton.onclick=function(){self._introItems.length-1!=self._currentStep&&_nextStep.call(self)},nextTooltipButton.href="javascript:void(0);",nextTooltipButton.innerHTML=this._options.nextLabel;var prevTooltipButton=document.createElement("a");prevTooltipButton.onclick=function(){0!=self._currentStep&&_previousStep.call(self)},prevTooltipButton.href="javascript:void(0);",prevTooltipButton.innerHTML=this._options.prevLabel;var skipTooltipButton=document.createElement("a");skipTooltipButton.className="introjs-button introjs-skipbutton",skipTooltipButton.href="javascript:void(0);",skipTooltipButton.innerHTML=this._options.skipLabel,skipTooltipButton.onclick=function(){self._introItems.length-1==self._currentStep&&"function"==typeof self._introCompleteCallback&&self._introCompleteCallback.call(self),self._introItems.length-1!=self._currentStep&&"function"==typeof self._introExitCallback&&self._introExitCallback.call(self),_exitIntro.call(self,self._targetElement)},buttonsLayer.appendChild(skipTooltipButton),this._introItems.length>1&&(buttonsLayer.appendChild(prevTooltipButton),buttonsLayer.appendChild(nextTooltipButton)),tooltipLayer.appendChild(buttonsLayer),_placeTooltip.call(self,targetElement.element,tooltipLayer,arrowLayer,helperNumberLayer)}this._options.disableInteraction===!0&&_disableInteraction.call(self),prevTooltipButton.removeAttribute("tabIndex"),nextTooltipButton.removeAttribute("tabIndex"),0==this._currentStep&&this._introItems.length>1?(prevTooltipButton.className="introjs-button introjs-prevbutton introjs-disabled",prevTooltipButton.tabIndex="-1",nextTooltipButton.className="introjs-button introjs-nextbutton",skipTooltipButton.innerHTML=this._options.skipLabel):this._introItems.length-1==this._currentStep||1==this._introItems.length?(skipTooltipButton.innerHTML=this._options.doneLabel,prevTooltipButton.className="introjs-button introjs-prevbutton",nextTooltipButton.className="introjs-button introjs-nextbutton introjs-disabled",nextTooltipButton.tabIndex="-1"):(prevTooltipButton.className="introjs-button introjs-prevbutton",nextTooltipButton.className="introjs-button introjs-nextbutton",skipTooltipButton.innerHTML=this._options.skipLabel),nextTooltipButton.focus(),targetElement.element.className+=" introjs-showElement";var currentElementPosition=_getPropValue(targetElement.element,"position");"absolute"!==currentElementPosition&&"relative"!==currentElementPosition&&(targetElement.element.className+=" introjs-relativePosition");for(var parentElm=targetElement.element.parentNode;null!=parentElm&&"body"!==parentElm.tagName.toLowerCase();){var zIndex=_getPropValue(parentElm,"z-index"),opacity=parseFloat(_getPropValue(parentElm,"opacity")),transform=_getPropValue(parentElm,"transform")||_getPropValue(parentElm,"-webkit-transform")||_getPropValue(parentElm,"-moz-transform")||_getPropValue(parentElm,"-ms-transform")||_getPropValue(parentElm,"-o-transform");(/[0-9]+/.test(zIndex)||1>opacity||"none"!==transform&&void 0!==transform)&&(parentElm.className+=" introjs-fixParent"),parentElm=parentElm.parentNode}if(!_elementInViewport(targetElement.element)&&this._options.scrollToElement===!0){var rect=targetElement.element.getBoundingClientRect(),winHeight=_getWinSize().height,top=rect.bottom-(rect.bottom-rect.top),bottom=rect.bottom-winHeight;0>top||targetElement.element.clientHeight>winHeight?window.scrollBy(0,top-30):window.scrollBy(0,bottom+100)}"undefined"!=typeof this._introAfterChangeCallback&&this._introAfterChangeCallback.call(this,targetElement.element)}function _getPropValue(element,propName){var propValue="";return element.currentStyle?propValue=element.currentStyle[propName]:document.defaultView&&document.defaultView.getComputedStyle&&(propValue=document.defaultView.getComputedStyle(element,null).getPropertyValue(propName)),propValue&&propValue.toLowerCase?propValue.toLowerCase():propValue}function _getWinSize(){if(void 0!=window.innerWidth)return{width:window.innerWidth,height:window.innerHeight};var D=document.documentElement;return{width:D.clientWidth,height:D.clientHeight}}function _elementInViewport(el){var rect=el.getBoundingClientRect();return rect.top>=0&&rect.left>=0&&rect.bottom+80<=window.innerHeight&&rect.right<=window.innerWidth}function _addOverlayLayer(targetElm){var overlayLayer=document.createElement("div"),styleText="",self=this;if(overlayLayer.className="introjs-overlay","body"===targetElm.tagName.toLowerCase())styleText+="top: 0;bottom: 0; left: 0;right: 0;position: fixed;",overlayLayer.setAttribute("style",styleText);else{var elementPosition=_getOffset(targetElm);elementPosition&&(styleText+="width: "+elementPosition.width+"px; height:"+elementPosition.height+"px; top:"+elementPosition.top+"px;left: "+elementPosition.left+"px;",overlayLayer.setAttribute("style",styleText))}return targetElm.appendChild(overlayLayer),overlayLayer.onclick=function(){1==self._options.exitOnOverlayClick&&(void 0!=self._introExitCallback&&self._introExitCallback.call(self),_exitIntro.call(self,targetElm))},setTimeout(function(){styleText+="opacity: "+self._options.overlayOpacity.toString()+";",overlayLayer.setAttribute("style",styleText)},10),!0}function _getOffset(element){var elementPosition={};elementPosition.width=element.offsetWidth,elementPosition.height=element.offsetHeight;for(var _x=0,_y=0;element&&!isNaN(element.offsetLeft)&&!isNaN(element.offsetTop);)_x+=element.offsetLeft,_y+=element.offsetTop,element=element.offsetParent;return elementPosition.top=_y,elementPosition.left=_x,elementPosition}function _getProgress(){var currentStep=parseInt(this._currentStep+1,10);return currentStep/this._introItems.length*100}function _mergeOptions(obj1,obj2){var obj3={};for(var attrname in obj1)obj3[attrname]=obj1[attrname];for(var attrname in obj2)obj3[attrname]=obj2[attrname];return obj3}var VERSION="1.1.1",introJs=function(targetElm){if("object"==typeof targetElm)return new IntroJs(targetElm);if("string"==typeof targetElm){var targetElement=document.querySelector(targetElm);if(targetElement)return new IntroJs(targetElement);throw new Error("There is no element with given selector.")}return new IntroJs(document.body)};return introJs.version=VERSION,introJs.fn=IntroJs.prototype={clone:function(){return new IntroJs(this)},setOption:function(option,value){return this._options[option]=value,this},setOptions:function(options){return this._options=_mergeOptions(this._options,options),this},start:function(){return _introForElement.call(this,this._targetElement),this},goToStep:function(step){return _goToStep.call(this,step),this},nextStep:function(){return _nextStep.call(this),this},previousStep:function(){return _previousStep.call(this),this},exit:function(){return _exitIntro.call(this,this._targetElement),this},refresh:function(){return _setHelperLayerPosition.call(this,document.querySelector(".introjs-helperLayer")),_setHelperLayerPosition.call(this,document.querySelector(".introjs-tooltipReferenceLayer")),this},onbeforechange:function(providedCallback){if("function"!=typeof providedCallback)throw new Error("Provided callback for onbeforechange was not a function");return this._introBeforeChangeCallback=providedCallback,this},onchange:function(providedCallback){if("function"!=typeof providedCallback)throw new Error("Provided callback for onchange was not a function.");return this._introChangeCallback=providedCallback,this},onafterchange:function(providedCallback){if("function"!=typeof providedCallback)throw new Error("Provided callback for onafterchange was not a function");return this._introAfterChangeCallback=providedCallback,this},oncomplete:function(providedCallback){if("function"!=typeof providedCallback)throw new Error("Provided callback for oncomplete was not a function.");return this._introCompleteCallback=providedCallback,this},onexit:function(providedCallback){if("function"!=typeof providedCallback)throw new Error("Provided callback for onexit was not a function.");return this._introExitCallback=providedCallback,this}},exports.introJs=introJs,introJs}),function(factory){"function"==typeof define&&define.amd?define(["jquery"],factory):factory(jQuery)}(function($){function focusable(element,isTabIndexNotNaN){var map,mapName,img,nodeName=element.nodeName.toLowerCase();return"area"===nodeName?(map=element.parentNode,mapName=map.name,element.href&&mapName&&"map"===map.nodeName.toLowerCase()?(img=$("img[usemap='#"+mapName+"']")[0],!!img&&visible(img)):!1):(/^(input|select|textarea|button|object)$/.test(nodeName)?!element.disabled:"a"===nodeName?element.href||isTabIndexNotNaN:isTabIndexNotNaN)&&visible(element)}function visible(element){return $.expr.filters.visible(element)&&!$(element).parents().addBack().filter(function(){return"hidden"===$.css(this,"visibility")}).length}$.ui=$.ui||{},$.extend($.ui,{version:"1.11.4",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),$.fn.extend({scrollParent:function(includeHidden){var position=this.css("position"),excludeStaticParent="absolute"===position,overflowRegex=includeHidden?/(auto|scroll|hidden)/:/(auto|scroll)/,scrollParent=this.parents().filter(function(){var parent=$(this);return excludeStaticParent&&"static"===parent.css("position")?!1:overflowRegex.test(parent.css("overflow")+parent.css("overflow-y")+parent.css("overflow-x"))}).eq(0);return"fixed"!==position&&scrollParent.length?scrollParent:$(this[0].ownerDocument||document)},uniqueId:function(){var uuid=0;return function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++uuid)})}}(),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&$(this).removeAttr("id")})}}),$.extend($.expr[":"],{data:$.expr.createPseudo?$.expr.createPseudo(function(dataName){return function(elem){return!!$.data(elem,dataName)}}):function(elem,i,match){return!!$.data(elem,match[3])},focusable:function(element){return focusable(element,!isNaN($.attr(element,"tabindex")))},tabbable:function(element){var tabIndex=$.attr(element,"tabindex"),isTabIndexNaN=isNaN(tabIndex);return(isTabIndexNaN||tabIndex>=0)&&focusable(element,!isTabIndexNaN)}}),$("").outerWidth(1).jquery||$.each(["Width","Height"],function(i,name){function reduce(elem,size,border,margin){return $.each(side,function(){size-=parseFloat($.css(elem,"padding"+this))||0,border&&(size-=parseFloat($.css(elem,"border"+this+"Width"))||0),margin&&(size-=parseFloat($.css(elem,"margin"+this))||0)}),size}var side="Width"===name?["Left","Right"]:["Top","Bottom"],type=name.toLowerCase(),orig={innerWidth:$.fn.innerWidth,innerHeight:$.fn.innerHeight,outerWidth:$.fn.outerWidth,outerHeight:$.fn.outerHeight};$.fn["inner"+name]=function(size){return void 0===size?orig["inner"+name].call(this):this.each(function(){$(this).css(type,reduce(this,size)+"px")})},$.fn["outer"+name]=function(size,margin){return"number"!=typeof size?orig["outer"+name].call(this,size):this.each(function(){$(this).css(type,reduce(this,size,!0,margin)+"px")})}}),$.fn.addBack||($.fn.addBack=function(selector){return this.add(null==selector?this.prevObject:this.prevObject.filter(selector))}),$("").data("a-b","a").removeData("a-b").data("a-b")&&($.fn.removeData=function(removeData){return function(key){return arguments.length?removeData.call(this,$.camelCase(key)):removeData.call(this)}}($.fn.removeData)),$.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),$.fn.extend({focus:function(orig){return function(delay,fn){return"number"==typeof delay?this.each(function(){var elem=this;setTimeout(function(){$(elem).focus(),fn&&fn.call(elem)},delay)}):orig.apply(this,arguments)}}($.fn.focus),disableSelection:function(){ -var eventType="onselectstart"in document.createElement("div")?"selectstart":"mousedown";return function(){return this.bind(eventType+".ui-disableSelection",function(event){event.preventDefault()})}}(),enableSelection:function(){return this.unbind(".ui-disableSelection")},zIndex:function(zIndex){if(void 0!==zIndex)return this.css("zIndex",zIndex);if(this.length)for(var position,value,elem=$(this[0]);elem.length&&elem[0]!==document;){if(position=elem.css("position"),("absolute"===position||"relative"===position||"fixed"===position)&&(value=parseInt(elem.css("zIndex"),10),!isNaN(value)&&0!==value))return value;elem=elem.parent()}return 0}}),$.ui.plugin={add:function(module,option,set){var i,proto=$.ui[module].prototype;for(i in set)proto.plugins[i]=proto.plugins[i]||[],proto.plugins[i].push([option,set[i]])},call:function(instance,name,args,allowDisconnected){var i,set=instance.plugins[name];if(set&&(allowDisconnected||instance.element[0].parentNode&&11!==instance.element[0].parentNode.nodeType))for(i=0;iinputIndex;inputIndex++)for(key in input[inputIndex])value=input[inputIndex][key],input[inputIndex].hasOwnProperty(key)&&void 0!==value&&($.isPlainObject(value)?target[key]=$.isPlainObject(target[key])?$.widget.extend({},target[key],value):$.widget.extend({},value):target[key]=value);return target},$.widget.bridge=function(name,object){var fullName=object.prototype.widgetFullName||name;$.fn[name]=function(options){var isMethodCall="string"==typeof options,args=widget_slice.call(arguments,1),returnValue=this;return isMethodCall?this.each(function(){var methodValue,instance=$.data(this,fullName);return"instance"===options?(returnValue=instance,!1):instance?$.isFunction(instance[options])&&"_"!==options.charAt(0)?(methodValue=instance[options].apply(instance,args),methodValue!==instance&&void 0!==methodValue?(returnValue=methodValue&&methodValue.jquery?returnValue.pushStack(methodValue.get()):methodValue,!1):void 0):$.error("no such method '"+options+"' for "+name+" widget instance"):$.error("cannot call methods on "+name+" prior to initialization; attempted to call method '"+options+"'")}):(args.length&&(options=$.widget.extend.apply(null,[options].concat(args))),this.each(function(){var instance=$.data(this,fullName);instance?(instance.option(options||{}),instance._init&&instance._init()):$.data(this,fullName,new object(options,this))})),returnValue}},$.Widget=function(){},$.Widget._childConstructors=[],$.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"
",options:{disabled:!1,create:null},_createWidget:function(options,element){element=$(element||this.defaultElement||this)[0],this.element=$(element),this.uuid=widget_uuid++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=$(),this.hoverable=$(),this.focusable=$(),element!==this&&($.data(element,this.widgetFullName,this),this._on(!0,this.element,{remove:function(event){event.target===element&&this.destroy()}}),this.document=$(element.style?element.ownerDocument:element.document||element),this.window=$(this.document[0].defaultView||this.document[0].parentWindow)),this.options=$.widget.extend({},this.options,this._getCreateOptions(),options),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:$.noop,_getCreateEventData:$.noop,_create:$.noop,_init:$.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetFullName).removeData($.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:$.noop,widget:function(){return this.element},option:function(key,value){var parts,curOption,i,options=key;if(0===arguments.length)return $.widget.extend({},this.options);if("string"==typeof key)if(options={},parts=key.split("."),key=parts.shift(),parts.length){for(curOption=options[key]=$.widget.extend({},this.options[key]),i=0;i=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}});!function(){function getOffsets(offsets,width,height){return[parseFloat(offsets[0])*(rpercent.test(offsets[0])?width/100:1),parseFloat(offsets[1])*(rpercent.test(offsets[1])?height/100:1)]}function parseCss(element,property){return parseInt($.css(element,property),10)||0}function getDimensions(elem){var raw=elem[0];return 9===raw.nodeType?{width:elem.width(),height:elem.height(),offset:{top:0,left:0}}:$.isWindow(raw)?{width:elem.width(),height:elem.height(),offset:{top:elem.scrollTop(),left:elem.scrollLeft()}}:raw.preventDefault?{width:0,height:0,offset:{top:raw.pageY,left:raw.pageX}}:{width:elem.outerWidth(),height:elem.outerHeight(),offset:elem.offset()}}$.ui=$.ui||{};var cachedScrollbarWidth,supportsOffsetFractions,max=Math.max,abs=Math.abs,round=Math.round,rhorizontal=/left|center|right/,rvertical=/top|center|bottom/,roffset=/[\+\-]\d+(\.[\d]+)?%?/,rposition=/^\w+/,rpercent=/%$/,_position=$.fn.position;$.position={scrollbarWidth:function(){if(void 0!==cachedScrollbarWidth)return cachedScrollbarWidth;var w1,w2,div=$("
"),innerDiv=div.children()[0];return $("body").append(div),w1=innerDiv.offsetWidth,div.css("overflow","scroll"),w2=innerDiv.offsetWidth,w1===w2&&(w2=div[0].clientWidth),div.remove(),cachedScrollbarWidth=w1-w2},getScrollInfo:function(within){var overflowX=within.isWindow||within.isDocument?"":within.element.css("overflow-x"),overflowY=within.isWindow||within.isDocument?"":within.element.css("overflow-y"),hasOverflowX="scroll"===overflowX||"auto"===overflowX&&within.widthright?"left":left>0?"right":"center",vertical:0>bottom?"top":top>0?"bottom":"middle"};elemWidth>targetWidth&&abs(left+right)targetHeight&&abs(top+bottom)max(abs(top),abs(bottom))?feedback.important="horizontal":feedback.important="vertical",options.using.call(this,props,feedback)}),elem.offset($.extend(position,{using:using}))})},$.ui.position={fit:{left:function(position,data){var newOverRight,within=data.within,withinOffset=within.isWindow?within.scrollLeft:within.offset.left,outerWidth=within.width,collisionPosLeft=position.left-data.collisionPosition.marginLeft,overLeft=withinOffset-collisionPosLeft,overRight=collisionPosLeft+data.collisionWidth-outerWidth-withinOffset;data.collisionWidth>outerWidth?overLeft>0&&0>=overRight?(newOverRight=position.left+overLeft+data.collisionWidth-outerWidth-withinOffset,position.left+=overLeft-newOverRight):overRight>0&&0>=overLeft?position.left=withinOffset:overLeft>overRight?position.left=withinOffset+outerWidth-data.collisionWidth:position.left=withinOffset:overLeft>0?position.left+=overLeft:overRight>0?position.left-=overRight:position.left=max(position.left-collisionPosLeft,position.left)},top:function(position,data){var newOverBottom,within=data.within,withinOffset=within.isWindow?within.scrollTop:within.offset.top,outerHeight=data.within.height,collisionPosTop=position.top-data.collisionPosition.marginTop,overTop=withinOffset-collisionPosTop,overBottom=collisionPosTop+data.collisionHeight-outerHeight-withinOffset;data.collisionHeight>outerHeight?overTop>0&&0>=overBottom?(newOverBottom=position.top+overTop+data.collisionHeight-outerHeight-withinOffset,position.top+=overTop-newOverBottom):overBottom>0&&0>=overTop?position.top=withinOffset:overTop>overBottom?position.top=withinOffset+outerHeight-data.collisionHeight:position.top=withinOffset:overTop>0?position.top+=overTop:overBottom>0?position.top-=overBottom:position.top=max(position.top-collisionPosTop,position.top)}},flip:{left:function(position,data){var newOverRight,newOverLeft,within=data.within,withinOffset=within.offset.left+within.scrollLeft,outerWidth=within.width,offsetLeft=within.isWindow?within.scrollLeft:within.offset.left,collisionPosLeft=position.left-data.collisionPosition.marginLeft,overLeft=collisionPosLeft-offsetLeft,overRight=collisionPosLeft+data.collisionWidth-outerWidth-offsetLeft,myOffset="left"===data.my[0]?-data.elemWidth:"right"===data.my[0]?data.elemWidth:0,atOffset="left"===data.at[0]?data.targetWidth:"right"===data.at[0]?-data.targetWidth:0,offset=-2*data.offset[0];0>overLeft?(newOverRight=position.left+myOffset+atOffset+offset+data.collisionWidth-outerWidth-withinOffset,(0>newOverRight||newOverRight0&&(newOverLeft=position.left-data.collisionPosition.marginLeft+myOffset+atOffset+offset-offsetLeft,(newOverLeft>0||abs(newOverLeft)overTop?(newOverBottom=position.top+myOffset+atOffset+offset+data.collisionHeight-outerHeight-withinOffset,(0>newOverBottom||newOverBottom0&&(newOverTop=position.top-data.collisionPosition.marginTop+myOffset+atOffset+offset-offsetTop,(newOverTop>0||abs(newOverTop)10&&11>offsetLeft,testElement.innerHTML="",testElementParent.removeChild(testElement)}()}();$.ui.position;$.widget("ui.draggable",$.ui.mouse,{version:"1.11.4",widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1,drag:null,start:null,stop:null},_create:function(){"original"===this.options.helper&&this._setPositionRelative(),this.options.addClasses&&this.element.addClass("ui-draggable"),this.options.disabled&&this.element.addClass("ui-draggable-disabled"),this._setHandleClassName(),this._mouseInit()},_setOption:function(key,value){this._super(key,value),"handle"===key&&(this._removeHandleClassName(),this._setHandleClassName())},_destroy:function(){return(this.helper||this.element).is(".ui-draggable-dragging")?void(this.destroyOnClear=!0):(this.element.removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._removeHandleClassName(),void this._mouseDestroy())},_mouseCapture:function(event){var o=this.options;return this._blurActiveElement(event),this.helper||o.disabled||$(event.target).closest(".ui-resizable-handle").length>0?!1:(this.handle=this._getHandle(event),this.handle?(this._blockFrames(o.iframeFix===!0?"iframe":o.iframeFix),!0):!1)},_blockFrames:function(selector){this.iframeBlocks=this.document.find(selector).map(function(){var iframe=$(this);return $("
").css("position","absolute").appendTo(iframe.parent()).outerWidth(iframe.outerWidth()).outerHeight(iframe.outerHeight()).offset(iframe.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_blurActiveElement:function(event){var document=this.document[0];if(this.handleElement.is(event.target))try{document.activeElement&&"body"!==document.activeElement.nodeName.toLowerCase()&&$(document.activeElement).blur()}catch(error){}},_mouseStart:function(event){var o=this.options;return this.helper=this._createHelper(event),this.helper.addClass("ui-draggable-dragging"),this._cacheHelperProportions(),$.ui.ddmanager&&($.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(!0),this.offsetParent=this.helper.offsetParent(),this.hasFixedAncestor=this.helper.parents().filter(function(){return"fixed"===$(this).css("position")}).length>0,this.positionAbs=this.element.offset(),this._refreshOffsets(event),this.originalPosition=this.position=this._generatePosition(event,!1),this.originalPageX=event.pageX,this.originalPageY=event.pageY,o.cursorAt&&this._adjustOffsetFromHelper(o.cursorAt),this._setContainment(),this._trigger("start",event)===!1?(this._clear(),!1):(this._cacheHelperProportions(),$.ui.ddmanager&&!o.dropBehaviour&&$.ui.ddmanager.prepareOffsets(this,event),this._normalizeRightBottom(),this._mouseDrag(event,!0),$.ui.ddmanager&&$.ui.ddmanager.dragStart(this,event),!0)},_refreshOffsets:function(event){this.offset={top:this.positionAbs.top-this.margins.top,left:this.positionAbs.left-this.margins.left,scroll:!1,parent:this._getParentOffset(),relative:this._getRelativeOffset()},this.offset.click={left:event.pageX-this.offset.left,top:event.pageY-this.offset.top}},_mouseDrag:function(event,noPropagation){if(this.hasFixedAncestor&&(this.offset.parent=this._getParentOffset()),this.position=this._generatePosition(event,!0),this.positionAbs=this._convertPositionTo("absolute"),!noPropagation){var ui=this._uiHash();if(this._trigger("drag",event,ui)===!1)return this._mouseUp({}),!1;this.position=ui.position}return this.helper[0].style.left=this.position.left+"px",this.helper[0].style.top=this.position.top+"px",$.ui.ddmanager&&$.ui.ddmanager.drag(this,event),!1},_mouseStop:function(event){var that=this,dropped=!1;return $.ui.ddmanager&&!this.options.dropBehaviour&&(dropped=$.ui.ddmanager.drop(this,event)),this.dropped&&(dropped=this.dropped,this.dropped=!1),"invalid"===this.options.revert&&!dropped||"valid"===this.options.revert&&dropped||this.options.revert===!0||$.isFunction(this.options.revert)&&this.options.revert.call(this.element,dropped)?$(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){that._trigger("stop",event)!==!1&&that._clear()}):this._trigger("stop",event)!==!1&&this._clear(),!1},_mouseUp:function(event){return this._unblockFrames(),$.ui.ddmanager&&$.ui.ddmanager.dragStop(this,event),this.handleElement.is(event.target)&&this.element.focus(),$.ui.mouse.prototype._mouseUp.call(this,event)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear(),this},_getHandle:function(event){return this.options.handle?!!$(event.target).closest(this.element.find(this.options.handle)).length:!0},_setHandleClassName:function(){this.handleElement=this.options.handle?this.element.find(this.options.handle):this.element,this.handleElement.addClass("ui-draggable-handle")},_removeHandleClassName:function(){this.handleElement.removeClass("ui-draggable-handle")},_createHelper:function(event){var o=this.options,helperIsFunction=$.isFunction(o.helper),helper=helperIsFunction?$(o.helper.apply(this.element[0],[event])):"clone"===o.helper?this.element.clone().removeAttr("id"):this.element;return helper.parents("body").length||helper.appendTo("parent"===o.appendTo?this.element[0].parentNode:o.appendTo),helperIsFunction&&helper[0]===this.element[0]&&this._setPositionRelative(),helper[0]===this.element[0]||/(fixed|absolute)/.test(helper.css("position"))||helper.css("position","absolute"),helper},_setPositionRelative:function(){/^(?:r|a|f)/.test(this.element.css("position"))||(this.element[0].style.position="relative")},_adjustOffsetFromHelper:function(obj){"string"==typeof obj&&(obj=obj.split(" ")),$.isArray(obj)&&(obj={left:+obj[0],top:+obj[1]||0}),"left"in obj&&(this.offset.click.left=obj.left+this.margins.left),"right"in obj&&(this.offset.click.left=this.helperProportions.width-obj.right+this.margins.left),"top"in obj&&(this.offset.click.top=obj.top+this.margins.top),"bottom"in obj&&(this.offset.click.top=this.helperProportions.height-obj.bottom+this.margins.top)},_isRootNode:function(element){return/(html|body)/i.test(element.tagName)||element===this.document[0]},_getParentOffset:function(){var po=this.offsetParent.offset(),document=this.document[0];return"absolute"===this.cssPosition&&this.scrollParent[0]!==document&&$.contains(this.scrollParent[0],this.offsetParent[0])&&(po.left+=this.scrollParent.scrollLeft(),po.top+=this.scrollParent.scrollTop()),this._isRootNode(this.offsetParent[0])&&(po={top:0,left:0}),{top:po.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:po.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"!==this.cssPosition)return{top:0,left:0};var p=this.element.position(),scrollIsRootNode=this._isRootNode(this.scrollParent[0]);return{top:p.top-(parseInt(this.helper.css("top"),10)||0)+(scrollIsRootNode?0:this.scrollParent.scrollTop()),left:p.left-(parseInt(this.helper.css("left"),10)||0)+(scrollIsRootNode?0:this.scrollParent.scrollLeft())}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight() -}},_setContainment:function(){var isUserScrollable,c,ce,o=this.options,document=this.document[0];return this.relativeContainer=null,o.containment?"window"===o.containment?void(this.containment=[$(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,$(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,$(window).scrollLeft()+$(window).width()-this.helperProportions.width-this.margins.left,$(window).scrollTop()+($(window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]):"document"===o.containment?void(this.containment=[0,0,$(document).width()-this.helperProportions.width-this.margins.left,($(document).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]):o.containment.constructor===Array?void(this.containment=o.containment):("parent"===o.containment&&(o.containment=this.helper[0].parentNode),c=$(o.containment),ce=c[0],void(ce&&(isUserScrollable=/(scroll|auto)/.test(c.css("overflow")),this.containment=[(parseInt(c.css("borderLeftWidth"),10)||0)+(parseInt(c.css("paddingLeft"),10)||0),(parseInt(c.css("borderTopWidth"),10)||0)+(parseInt(c.css("paddingTop"),10)||0),(isUserScrollable?Math.max(ce.scrollWidth,ce.offsetWidth):ce.offsetWidth)-(parseInt(c.css("borderRightWidth"),10)||0)-(parseInt(c.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(isUserScrollable?Math.max(ce.scrollHeight,ce.offsetHeight):ce.offsetHeight)-(parseInt(c.css("borderBottomWidth"),10)||0)-(parseInt(c.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relativeContainer=c))):void(this.containment=null)},_convertPositionTo:function(d,pos){pos||(pos=this.position);var mod="absolute"===d?1:-1,scrollIsRootNode=this._isRootNode(this.scrollParent[0]);return{top:pos.top+this.offset.relative.top*mod+this.offset.parent.top*mod-("fixed"===this.cssPosition?-this.offset.scroll.top:scrollIsRootNode?0:this.offset.scroll.top)*mod,left:pos.left+this.offset.relative.left*mod+this.offset.parent.left*mod-("fixed"===this.cssPosition?-this.offset.scroll.left:scrollIsRootNode?0:this.offset.scroll.left)*mod}},_generatePosition:function(event,constrainPosition){var containment,co,top,left,o=this.options,scrollIsRootNode=this._isRootNode(this.scrollParent[0]),pageX=event.pageX,pageY=event.pageY;return scrollIsRootNode&&this.offset.scroll||(this.offset.scroll={top:this.scrollParent.scrollTop(),left:this.scrollParent.scrollLeft()}),constrainPosition&&(this.containment&&(this.relativeContainer?(co=this.relativeContainer.offset(),containment=[this.containment[0]+co.left,this.containment[1]+co.top,this.containment[2]+co.left,this.containment[3]+co.top]):containment=this.containment,event.pageX-this.offset.click.leftcontainment[2]&&(pageX=containment[2]+this.offset.click.left),event.pageY-this.offset.click.top>containment[3]&&(pageY=containment[3]+this.offset.click.top)),o.grid&&(top=o.grid[1]?this.originalPageY+Math.round((pageY-this.originalPageY)/o.grid[1])*o.grid[1]:this.originalPageY,pageY=containment?top-this.offset.click.top>=containment[1]||top-this.offset.click.top>containment[3]?top:top-this.offset.click.top>=containment[1]?top-o.grid[1]:top+o.grid[1]:top,left=o.grid[0]?this.originalPageX+Math.round((pageX-this.originalPageX)/o.grid[0])*o.grid[0]:this.originalPageX,pageX=containment?left-this.offset.click.left>=containment[0]||left-this.offset.click.left>containment[2]?left:left-this.offset.click.left>=containment[0]?left-o.grid[0]:left+o.grid[0]:left),"y"===o.axis&&(pageX=this.originalPageX),"x"===o.axis&&(pageY=this.originalPageY)),{top:pageY-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.offset.scroll.top:scrollIsRootNode?0:this.offset.scroll.top),left:pageX-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.offset.scroll.left:scrollIsRootNode?0:this.offset.scroll.left)}},_clear:function(){this.helper.removeClass("ui-draggable-dragging"),this.helper[0]===this.element[0]||this.cancelHelperRemoval||this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1,this.destroyOnClear&&this.destroy()},_normalizeRightBottom:function(){"y"!==this.options.axis&&"auto"!==this.helper.css("right")&&(this.helper.width(this.helper.width()),this.helper.css("right","auto")),"x"!==this.options.axis&&"auto"!==this.helper.css("bottom")&&(this.helper.height(this.helper.height()),this.helper.css("bottom","auto"))},_trigger:function(type,event,ui){return ui=ui||this._uiHash(),$.ui.plugin.call(this,type,[event,ui,this],!0),/^(drag|start|stop)/.test(type)&&(this.positionAbs=this._convertPositionTo("absolute"),ui.offset=this.positionAbs),$.Widget.prototype._trigger.call(this,type,event,ui)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),$.ui.plugin.add("draggable","connectToSortable",{start:function(event,ui,draggable){var uiSortable=$.extend({},ui,{item:draggable.element});draggable.sortables=[],$(draggable.options.connectToSortable).each(function(){var sortable=$(this).sortable("instance");sortable&&!sortable.options.disabled&&(draggable.sortables.push(sortable),sortable.refreshPositions(),sortable._trigger("activate",event,uiSortable))})},stop:function(event,ui,draggable){var uiSortable=$.extend({},ui,{item:draggable.element});draggable.cancelHelperRemoval=!1,$.each(draggable.sortables,function(){var sortable=this;sortable.isOver?(sortable.isOver=0,draggable.cancelHelperRemoval=!0,sortable.cancelHelperRemoval=!1,sortable._storedCSS={position:sortable.placeholder.css("position"),top:sortable.placeholder.css("top"),left:sortable.placeholder.css("left")},sortable._mouseStop(event),sortable.options.helper=sortable.options._helper):(sortable.cancelHelperRemoval=!0,sortable._trigger("deactivate",event,uiSortable))})},drag:function(event,ui,draggable){$.each(draggable.sortables,function(){var innermostIntersecting=!1,sortable=this;sortable.positionAbs=draggable.positionAbs,sortable.helperProportions=draggable.helperProportions,sortable.offset.click=draggable.offset.click,sortable._intersectsWith(sortable.containerCache)&&(innermostIntersecting=!0,$.each(draggable.sortables,function(){return this.positionAbs=draggable.positionAbs,this.helperProportions=draggable.helperProportions,this.offset.click=draggable.offset.click,this!==sortable&&this._intersectsWith(this.containerCache)&&$.contains(sortable.element[0],this.element[0])&&(innermostIntersecting=!1),innermostIntersecting})),innermostIntersecting?(sortable.isOver||(sortable.isOver=1,draggable._parent=ui.helper.parent(),sortable.currentItem=ui.helper.appendTo(sortable.element).data("ui-sortable-item",!0),sortable.options._helper=sortable.options.helper,sortable.options.helper=function(){return ui.helper[0]},event.target=sortable.currentItem[0],sortable._mouseCapture(event,!0),sortable._mouseStart(event,!0,!0),sortable.offset.click.top=draggable.offset.click.top,sortable.offset.click.left=draggable.offset.click.left,sortable.offset.parent.left-=draggable.offset.parent.left-sortable.offset.parent.left,sortable.offset.parent.top-=draggable.offset.parent.top-sortable.offset.parent.top,draggable._trigger("toSortable",event),draggable.dropped=sortable.element,$.each(draggable.sortables,function(){this.refreshPositions()}),draggable.currentItem=draggable.element,sortable.fromOutside=draggable),sortable.currentItem&&(sortable._mouseDrag(event),ui.position=sortable.position)):sortable.isOver&&(sortable.isOver=0,sortable.cancelHelperRemoval=!0,sortable.options._revert=sortable.options.revert,sortable.options.revert=!1,sortable._trigger("out",event,sortable._uiHash(sortable)),sortable._mouseStop(event,!0),sortable.options.revert=sortable.options._revert,sortable.options.helper=sortable.options._helper,sortable.placeholder&&sortable.placeholder.remove(),ui.helper.appendTo(draggable._parent),draggable._refreshOffsets(event),ui.position=draggable._generatePosition(event,!0),draggable._trigger("fromSortable",event),draggable.dropped=!1,$.each(draggable.sortables,function(){this.refreshPositions()}))})}}),$.ui.plugin.add("draggable","cursor",{start:function(event,ui,instance){var t=$("body"),o=instance.options;t.css("cursor")&&(o._cursor=t.css("cursor")),t.css("cursor",o.cursor)},stop:function(event,ui,instance){var o=instance.options;o._cursor&&$("body").css("cursor",o._cursor)}}),$.ui.plugin.add("draggable","opacity",{start:function(event,ui,instance){var t=$(ui.helper),o=instance.options;t.css("opacity")&&(o._opacity=t.css("opacity")),t.css("opacity",o.opacity)},stop:function(event,ui,instance){var o=instance.options;o._opacity&&$(ui.helper).css("opacity",o._opacity)}}),$.ui.plugin.add("draggable","scroll",{start:function(event,ui,i){i.scrollParentNotHidden||(i.scrollParentNotHidden=i.helper.scrollParent(!1)),i.scrollParentNotHidden[0]!==i.document[0]&&"HTML"!==i.scrollParentNotHidden[0].tagName&&(i.overflowOffset=i.scrollParentNotHidden.offset())},drag:function(event,ui,i){var o=i.options,scrolled=!1,scrollParent=i.scrollParentNotHidden[0],document=i.document[0];scrollParent!==document&&"HTML"!==scrollParent.tagName?(o.axis&&"x"===o.axis||(i.overflowOffset.top+scrollParent.offsetHeight-event.pageY=0;i--)l=inst.snapElements[i].left-inst.margins.left,r=l+inst.snapElements[i].width,t=inst.snapElements[i].top-inst.margins.top,b=t+inst.snapElements[i].height,l-d>x2||x1>r+d||t-d>y2||y1>b+d||!$.contains(inst.snapElements[i].item.ownerDocument,inst.snapElements[i].item)?(inst.snapElements[i].snapping&&inst.options.snap.release&&inst.options.snap.release.call(inst.element,event,$.extend(inst._uiHash(),{snapItem:inst.snapElements[i].item})),inst.snapElements[i].snapping=!1):("inner"!==o.snapMode&&(ts=Math.abs(t-y2)<=d,bs=Math.abs(b-y1)<=d,ls=Math.abs(l-x2)<=d,rs=Math.abs(r-x1)<=d,ts&&(ui.position.top=inst._convertPositionTo("relative",{top:t-inst.helperProportions.height,left:0}).top),bs&&(ui.position.top=inst._convertPositionTo("relative",{top:b,left:0}).top),ls&&(ui.position.left=inst._convertPositionTo("relative",{top:0,left:l-inst.helperProportions.width}).left),rs&&(ui.position.left=inst._convertPositionTo("relative",{top:0,left:r}).left)),first=ts||bs||ls||rs,"outer"!==o.snapMode&&(ts=Math.abs(t-y1)<=d,bs=Math.abs(b-y2)<=d,ls=Math.abs(l-x1)<=d,rs=Math.abs(r-x2)<=d,ts&&(ui.position.top=inst._convertPositionTo("relative",{top:t,left:0}).top),bs&&(ui.position.top=inst._convertPositionTo("relative",{top:b-inst.helperProportions.height,left:0}).top),ls&&(ui.position.left=inst._convertPositionTo("relative",{top:0,left:l}).left),rs&&(ui.position.left=inst._convertPositionTo("relative",{top:0,left:r-inst.helperProportions.width}).left)),!inst.snapElements[i].snapping&&(ts||bs||ls||rs||first)&&inst.options.snap.snap&&inst.options.snap.snap.call(inst.element,event,$.extend(inst._uiHash(),{snapItem:inst.snapElements[i].item})),inst.snapElements[i].snapping=ts||bs||ls||rs||first)}}),$.ui.plugin.add("draggable","stack",{start:function(event,ui,instance){var min,o=instance.options,group=$.makeArray($(o.stack)).sort(function(a,b){return(parseInt($(a).css("zIndex"),10)||0)-(parseInt($(b).css("zIndex"),10)||0)});group.length&&(min=parseInt($(group[0]).css("zIndex"),10)||0,$(group).each(function(i){$(this).css("zIndex",min+i)}),this.css("zIndex",min+group.length))}}),$.ui.plugin.add("draggable","zIndex",{start:function(event,ui,instance){var t=$(ui.helper),o=instance.options;t.css("zIndex")&&(o._zIndex=t.css("zIndex")),t.css("zIndex",o.zIndex)},stop:function(event,ui,instance){var o=instance.options;o._zIndex&&$(ui.helper).css("zIndex",o._zIndex)}});$.ui.draggable;$.widget("ui.droppable",{version:"1.11.4",widgetEventPrefix:"drop",options:{accept:"*",activeClass:!1,addClasses:!0,greedy:!1,hoverClass:!1,scope:"default",tolerance:"intersect",activate:null,deactivate:null,drop:null,out:null,over:null},_create:function(){var proportions,o=this.options,accept=o.accept;this.isover=!1,this.isout=!0,this.accept=$.isFunction(accept)?accept:function(d){return d.is(accept)},this.proportions=function(){return arguments.length?void(proportions=arguments[0]):proportions?proportions:proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight}},this._addToManager(o.scope),o.addClasses&&this.element.addClass("ui-droppable")},_addToManager:function(scope){$.ui.ddmanager.droppables[scope]=$.ui.ddmanager.droppables[scope]||[],$.ui.ddmanager.droppables[scope].push(this)},_splice:function(drop){for(var i=0;i=reference&&reference+size>x}return function(draggable,droppable,toleranceMode,event){if(!droppable.offset)return!1;var x1=(draggable.positionAbs||draggable.position.absolute).left+draggable.margins.left,y1=(draggable.positionAbs||draggable.position.absolute).top+draggable.margins.top,x2=x1+draggable.helperProportions.width,y2=y1+draggable.helperProportions.height,l=droppable.offset.left,t=droppable.offset.top,r=l+droppable.proportions().width,b=t+droppable.proportions().height;switch(toleranceMode){case"fit":return x1>=l&&r>=x2&&y1>=t&&b>=y2;case"intersect":return l=t&&b>=y1||y2>=t&&b>=y2||t>y1&&y2>b)&&(x1>=l&&r>=x1||x2>=l&&r>=x2||l>x1&&x2>r);default:return!1}}}(),$.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(t,event){var i,j,m=$.ui.ddmanager.droppables[t.options.scope]||[],type=event?event.type:null,list=(t.currentItem||t.element).find(":data(ui-droppable)").addBack();droppablesLoop:for(i=0;i0?!0:(el[scroll]=1,has=el[scroll]>0,el[scroll]=0,has)},_create:function(){var n,i,handle,axis,hname,that=this,o=this.options;if(this.element.addClass("ui-resizable"),$.extend(this,{_aspectRatio:!!o.aspectRatio,aspectRatio:o.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:o.helper||o.ghost||o.animate?o.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/^(canvas|textarea|input|select|button|img)$/i)&&(this.element.wrap($("
").css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("ui-resizable",this.element.resizable("instance")),this.elementIsWrapper=!0,this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")}),this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0}),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css({margin:this.originalElement.css("margin")}),this._proportionallyResize()),this.handles=o.handles||($(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se"),this._handles=$(),this.handles.constructor===String)for("all"===this.handles&&(this.handles="n,e,s,w,se,sw,ne,nw"),n=this.handles.split(","),this.handles={},i=0;i
"),axis.css({zIndex:o.zIndex}),"se"===handle&&axis.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[handle]=".ui-resizable-"+handle,this.element.append(axis);this._renderAxis=function(target){var i,axis,padPos,padWrapper;target=target||this.element;for(i in this.handles)this.handles[i].constructor===String?this.handles[i]=this.element.children(this.handles[i]).first().show():(this.handles[i].jquery||this.handles[i].nodeType)&&(this.handles[i]=$(this.handles[i]),this._on(this.handles[i],{mousedown:that._mouseDown})),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/^(textarea|input|select|button)$/i)&&(axis=$(this.handles[i],this.element),padWrapper=/sw|ne|nw|se|n|s/.test(i)?axis.outerHeight():axis.outerWidth(),padPos=["padding",/ne|nw|n/.test(i)?"Top":/se|sw|s/.test(i)?"Bottom":/^e$/.test(i)?"Right":"Left"].join(""),target.css(padPos,padWrapper),this._proportionallyResize()),this._handles=this._handles.add(this.handles[i])},this._renderAxis(this.element),this._handles=this._handles.add(this.element.find(".ui-resizable-handle")),this._handles.disableSelection(),this._handles.mouseover(function(){that.resizing||(this.className&&(axis=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),that.axis=axis&&axis[1]?axis[1]:"se")}),o.autoHide&&(this._handles.hide(),$(this.element).addClass("ui-resizable-autohide").mouseenter(function(){o.disabled||($(this).removeClass("ui-resizable-autohide"),that._handles.show())}).mouseleave(function(){o.disabled||that.resizing||($(this).addClass("ui-resizable-autohide"),that._handles.hide())})),this._mouseInit()},_destroy:function(){this._mouseDestroy();var wrapper,_destroy=function(exp){$(exp).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};return this.elementIsWrapper&&(_destroy(this.element),wrapper=this.element,this.originalElement.css({position:wrapper.css("position"),width:wrapper.outerWidth(),height:wrapper.outerHeight(),top:wrapper.css("top"),left:wrapper.css("left")}).insertAfter(wrapper),wrapper.remove()),this.originalElement.css("resize",this.originalResizeStyle),_destroy(this.originalElement),this},_mouseCapture:function(event){var i,handle,capture=!1;for(i in this.handles)handle=$(this.handles[i])[0],(handle===event.target||$.contains(handle,event.target))&&(capture=!0);return!this.options.disabled&&capture},_mouseStart:function(event){var curleft,curtop,cursor,o=this.options,el=this.element;return this.resizing=!0,this._renderProxy(),curleft=this._num(this.helper.css("left")),curtop=this._num(this.helper.css("top")),o.containment&&(curleft+=$(o.containment).scrollLeft()||0,curtop+=$(o.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:curleft,top:curtop},this.size=this._helper?{width:this.helper.width(),height:this.helper.height()}:{width:el.width(),height:el.height()},this.originalSize=this._helper?{width:el.outerWidth(),height:el.outerHeight()}:{width:el.width(),height:el.height()},this.sizeDiff={width:el.outerWidth()-el.width(),height:el.outerHeight()-el.height()},this.originalPosition={left:curleft,top:curtop},this.originalMousePosition={left:event.pageX,top:event.pageY},this.aspectRatio="number"==typeof o.aspectRatio?o.aspectRatio:this.originalSize.width/this.originalSize.height||1,cursor=$(".ui-resizable-"+this.axis).css("cursor"),$("body").css("cursor","auto"===cursor?this.axis+"-resize":cursor),el.addClass("ui-resizable-resizing"),this._propagate("start",event),!0},_mouseDrag:function(event){var data,props,smp=this.originalMousePosition,a=this.axis,dx=event.pageX-smp.left||0,dy=event.pageY-smp.top||0,trigger=this._change[a];return this._updatePrevProperties(),trigger?(data=trigger.apply(this,[event,dx,dy]),this._updateVirtualBoundaries(event.shiftKey),(this._aspectRatio||event.shiftKey)&&(data=this._updateRatio(data,event)),data=this._respectSize(data,event),this._updateCache(data),this._propagate("resize",event),props=this._applyChanges(),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),$.isEmptyObject(props)||(this._updatePrevProperties(),this._trigger("resize",event,this.ui()),this._applyChanges()),!1):!1},_mouseStop:function(event){this.resizing=!1;var pr,ista,soffseth,soffsetw,s,left,top,o=this.options,that=this;return this._helper&&(pr=this._proportionallyResizeElements,ista=pr.length&&/textarea/i.test(pr[0].nodeName),soffseth=ista&&this._hasScroll(pr[0],"left")?0:that.sizeDiff.height,soffsetw=ista?0:that.sizeDiff.width,s={width:that.helper.width()-soffsetw,height:that.helper.height()-soffseth},left=parseInt(that.element.css("left"),10)+(that.position.left-that.originalPosition.left)||null,top=parseInt(that.element.css("top"),10)+(that.position.top-that.originalPosition.top)||null,o.animate||this.element.css($.extend(s,{top:top,left:left})),that.helper.height(that.size.height),that.helper.width(that.size.width),this._helper&&!o.animate&&this._proportionallyResize()),$("body").css("cursor","auto"),this.element.removeClass("ui-resizable-resizing"),this._propagate("stop",event),this._helper&&this.helper.remove(),!1},_updatePrevProperties:function(){this.prevPosition={top:this.position.top,left:this.position.left},this.prevSize={width:this.size.width,height:this.size.height}},_applyChanges:function(){var props={};return this.position.top!==this.prevPosition.top&&(props.top=this.position.top+"px"),this.position.left!==this.prevPosition.left&&(props.left=this.position.left+"px"),this.size.width!==this.prevSize.width&&(props.width=this.size.width+"px"),this.size.height!==this.prevSize.height&&(props.height=this.size.height+"px"),this.helper.css(props),props},_updateVirtualBoundaries:function(forceAspectRatio){var pMinWidth,pMaxWidth,pMinHeight,pMaxHeight,b,o=this.options;b={minWidth:this._isNumber(o.minWidth)?o.minWidth:0,maxWidth:this._isNumber(o.maxWidth)?o.maxWidth:1/0,minHeight:this._isNumber(o.minHeight)?o.minHeight:0,maxHeight:this._isNumber(o.maxHeight)?o.maxHeight:1/0},(this._aspectRatio||forceAspectRatio)&&(pMinWidth=b.minHeight*this.aspectRatio,pMinHeight=b.minWidth/this.aspectRatio,pMaxWidth=b.maxHeight*this.aspectRatio,pMaxHeight=b.maxWidth/this.aspectRatio,pMinWidth>b.minWidth&&(b.minWidth=pMinWidth),pMinHeight>b.minHeight&&(b.minHeight=pMinHeight),pMaxWidthdata.width,isminh=this._isNumber(data.height)&&o.minHeight&&o.minHeight>data.height,dw=this.originalPosition.left+this.originalSize.width,dh=this.position.top+this.size.height,cw=/sw|nw|w/.test(a),ch=/nw|ne|n/.test(a);return isminw&&(data.width=o.minWidth),isminh&&(data.height=o.minHeight),ismaxw&&(data.width=o.maxWidth),ismaxh&&(data.height=o.maxHeight),isminw&&cw&&(data.left=dw-o.minWidth),ismaxw&&cw&&(data.left=dw-o.maxWidth),isminh&&ch&&(data.top=dh-o.minHeight),ismaxh&&ch&&(data.top=dh-o.maxHeight),data.width||data.height||data.left||!data.top?data.width||data.height||data.top||!data.left||(data.left=null):data.top=null,data},_getPaddingPlusBorderDimensions:function(element){for(var i=0,widths=[],borders=[element.css("borderTopWidth"),element.css("borderRightWidth"),element.css("borderBottomWidth"),element.css("borderLeftWidth")],paddings=[element.css("paddingTop"),element.css("paddingRight"),element.css("paddingBottom"),element.css("paddingLeft")];4>i;i++)widths[i]=parseInt(borders[i],10)||0, -widths[i]+=parseInt(paddings[i],10)||0;return{height:widths[0]+widths[2],width:widths[1]+widths[3]}},_proportionallyResize:function(){if(this._proportionallyResizeElements.length)for(var prel,i=0,element=this.helper||this.element;i
"),this.helper.addClass(this._helper).css({width:this.element.outerWidth()-1,height:this.element.outerHeight()-1,position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++o.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(event,dx){return{width:this.originalSize.width+dx}},w:function(event,dx){var cs=this.originalSize,sp=this.originalPosition;return{left:sp.left+dx,width:cs.width-dx}},n:function(event,dx,dy){var cs=this.originalSize,sp=this.originalPosition;return{top:sp.top+dy,height:cs.height-dy}},s:function(event,dx,dy){return{height:this.originalSize.height+dy}},se:function(event,dx,dy){return $.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[event,dx,dy]))},sw:function(event,dx,dy){return $.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[event,dx,dy]))},ne:function(event,dx,dy){return $.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[event,dx,dy]))},nw:function(event,dx,dy){return $.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[event,dx,dy]))}},_propagate:function(n,event){$.ui.plugin.call(this,n,[event,this.ui()]),"resize"!==n&&this._trigger(n,event,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),$.ui.plugin.add("resizable","animate",{stop:function(event){var that=$(this).resizable("instance"),o=that.options,pr=that._proportionallyResizeElements,ista=pr.length&&/textarea/i.test(pr[0].nodeName),soffseth=ista&&that._hasScroll(pr[0],"left")?0:that.sizeDiff.height,soffsetw=ista?0:that.sizeDiff.width,style={width:that.size.width-soffsetw,height:that.size.height-soffseth},left=parseInt(that.element.css("left"),10)+(that.position.left-that.originalPosition.left)||null,top=parseInt(that.element.css("top"),10)+(that.position.top-that.originalPosition.top)||null;that.element.animate($.extend(style,top&&left?{top:top,left:left}:{}),{duration:o.animateDuration,easing:o.animateEasing,step:function(){var data={width:parseInt(that.element.css("width"),10),height:parseInt(that.element.css("height"),10),top:parseInt(that.element.css("top"),10),left:parseInt(that.element.css("left"),10)};pr&&pr.length&&$(pr[0]).css({width:data.width,height:data.height}),that._updateCache(data),that._propagate("resize",event)}})}}),$.ui.plugin.add("resizable","containment",{start:function(){var element,p,co,ch,cw,width,height,that=$(this).resizable("instance"),o=that.options,el=that.element,oc=o.containment,ce=oc instanceof $?oc.get(0):/parent/.test(oc)?el.parent().get(0):oc;ce&&(that.containerElement=$(ce),/document/.test(oc)||oc===document?(that.containerOffset={left:0,top:0},that.containerPosition={left:0,top:0},that.parentData={element:$(document),left:0,top:0,width:$(document).width(),height:$(document).height()||document.body.parentNode.scrollHeight}):(element=$(ce),p=[],$(["Top","Right","Left","Bottom"]).each(function(i,name){p[i]=that._num(element.css("padding"+name))}),that.containerOffset=element.offset(),that.containerPosition=element.position(),that.containerSize={height:element.innerHeight()-p[3],width:element.innerWidth()-p[1]},co=that.containerOffset,ch=that.containerSize.height,cw=that.containerSize.width,width=that._hasScroll(ce,"left")?ce.scrollWidth:cw,height=that._hasScroll(ce)?ce.scrollHeight:ch,that.parentData={element:ce,left:co.left,top:co.top,width:width,height:height}))},resize:function(event){var woset,hoset,isParent,isOffsetRelative,that=$(this).resizable("instance"),o=that.options,co=that.containerOffset,cp=that.position,pRatio=that._aspectRatio||event.shiftKey,cop={top:0,left:0},ce=that.containerElement,continueResize=!0;ce[0]!==document&&/static/.test(ce.css("position"))&&(cop=co),cp.left<(that._helper?co.left:0)&&(that.size.width=that.size.width+(that._helper?that.position.left-co.left:that.position.left-cop.left),pRatio&&(that.size.height=that.size.width/that.aspectRatio,continueResize=!1),that.position.left=o.helper?co.left:0),cp.top<(that._helper?co.top:0)&&(that.size.height=that.size.height+(that._helper?that.position.top-co.top:that.position.top),pRatio&&(that.size.width=that.size.height*that.aspectRatio,continueResize=!1),that.position.top=that._helper?co.top:0),isParent=that.containerElement.get(0)===that.element.parent().get(0),isOffsetRelative=/relative|absolute/.test(that.containerElement.css("position")),isParent&&isOffsetRelative?(that.offset.left=that.parentData.left+that.position.left,that.offset.top=that.parentData.top+that.position.top):(that.offset.left=that.element.offset().left,that.offset.top=that.element.offset().top),woset=Math.abs(that.sizeDiff.width+(that._helper?that.offset.left-cop.left:that.offset.left-co.left)),hoset=Math.abs(that.sizeDiff.height+(that._helper?that.offset.top-cop.top:that.offset.top-co.top)),woset+that.size.width>=that.parentData.width&&(that.size.width=that.parentData.width-woset,pRatio&&(that.size.height=that.size.width/that.aspectRatio,continueResize=!1)),hoset+that.size.height>=that.parentData.height&&(that.size.height=that.parentData.height-hoset,pRatio&&(that.size.width=that.size.height*that.aspectRatio,continueResize=!1)),continueResize||(that.position.left=that.prevPosition.left,that.position.top=that.prevPosition.top,that.size.width=that.prevSize.width,that.size.height=that.prevSize.height)},stop:function(){var that=$(this).resizable("instance"),o=that.options,co=that.containerOffset,cop=that.containerPosition,ce=that.containerElement,helper=$(that.helper),ho=helper.offset(),w=helper.outerWidth()-that.sizeDiff.width,h=helper.outerHeight()-that.sizeDiff.height;that._helper&&!o.animate&&/relative/.test(ce.css("position"))&&$(this).css({left:ho.left-cop.left-co.left,width:w,height:h}),that._helper&&!o.animate&&/static/.test(ce.css("position"))&&$(this).css({left:ho.left-cop.left-co.left,width:w,height:h})}}),$.ui.plugin.add("resizable","alsoResize",{start:function(){var that=$(this).resizable("instance"),o=that.options;$(o.alsoResize).each(function(){var el=$(this);el.data("ui-resizable-alsoresize",{width:parseInt(el.width(),10),height:parseInt(el.height(),10),left:parseInt(el.css("left"),10),top:parseInt(el.css("top"),10)})})},resize:function(event,ui){var that=$(this).resizable("instance"),o=that.options,os=that.originalSize,op=that.originalPosition,delta={height:that.size.height-os.height||0,width:that.size.width-os.width||0,top:that.position.top-op.top||0,left:that.position.left-op.left||0};$(o.alsoResize).each(function(){var el=$(this),start=$(this).data("ui-resizable-alsoresize"),style={},css=el.parents(ui.originalElement[0]).length?["width","height"]:["width","height","top","left"];$.each(css,function(i,prop){var sum=(start[prop]||0)+(delta[prop]||0);sum&&sum>=0&&(style[prop]=sum||null)}),el.css(style)})},stop:function(){$(this).removeData("resizable-alsoresize")}}),$.ui.plugin.add("resizable","ghost",{start:function(){var that=$(this).resizable("instance"),o=that.options,cs=that.size;that.ghost=that.originalElement.clone(),that.ghost.css({opacity:.25,display:"block",position:"relative",height:cs.height,width:cs.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass("string"==typeof o.ghost?o.ghost:""),that.ghost.appendTo(that.helper)},resize:function(){var that=$(this).resizable("instance");that.ghost&&that.ghost.css({position:"relative",height:that.size.height,width:that.size.width})},stop:function(){var that=$(this).resizable("instance");that.ghost&&that.helper&&that.helper.get(0).removeChild(that.ghost.get(0))}}),$.ui.plugin.add("resizable","grid",{resize:function(){var outerDimensions,that=$(this).resizable("instance"),o=that.options,cs=that.size,os=that.originalSize,op=that.originalPosition,a=that.axis,grid="number"==typeof o.grid?[o.grid,o.grid]:o.grid,gridX=grid[0]||1,gridY=grid[1]||1,ox=Math.round((cs.width-os.width)/gridX)*gridX,oy=Math.round((cs.height-os.height)/gridY)*gridY,newWidth=os.width+ox,newHeight=os.height+oy,isMaxWidth=o.maxWidth&&o.maxWidthnewWidth,isMinHeight=o.minHeight&&o.minHeight>newHeight;o.grid=grid,isMinWidth&&(newWidth+=gridX),isMinHeight&&(newHeight+=gridY),isMaxWidth&&(newWidth-=gridX),isMaxHeight&&(newHeight-=gridY),/^(se|s|e)$/.test(a)?(that.size.width=newWidth,that.size.height=newHeight):/^(ne)$/.test(a)?(that.size.width=newWidth,that.size.height=newHeight,that.position.top=op.top-oy):/^(sw)$/.test(a)?(that.size.width=newWidth,that.size.height=newHeight,that.position.left=op.left-ox):((0>=newHeight-gridY||0>=newWidth-gridX)&&(outerDimensions=that._getPaddingPlusBorderDimensions(this)),newHeight-gridY>0?(that.size.height=newHeight,that.position.top=op.top-oy):(newHeight=gridY-outerDimensions.height,that.size.height=newHeight,that.position.top=op.top+os.height-newHeight),newWidth-gridX>0?(that.size.width=newWidth,that.position.left=op.left-ox):(newWidth=gridX-outerDimensions.width,that.size.width=newWidth,that.position.left=op.left+os.width-newWidth))}});$.ui.resizable,$.widget("ui.selectable",$.ui.mouse,{version:"1.11.4",options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch",selected:null,selecting:null,start:null,stop:null,unselected:null,unselecting:null},_create:function(){var selectees,that=this;this.element.addClass("ui-selectable"),this.dragged=!1,this.refresh=function(){selectees=$(that.options.filter,that.element[0]),selectees.addClass("ui-selectee"),selectees.each(function(){var $this=$(this),pos=$this.offset();$.data(this,"selectable-item",{element:this,$element:$this,left:pos.left,top:pos.top,right:pos.left+$this.outerWidth(),bottom:pos.top+$this.outerHeight(),startselected:!1,selected:$this.hasClass("ui-selected"),selecting:$this.hasClass("ui-selecting"),unselecting:$this.hasClass("ui-unselecting")})})},this.refresh(),this.selectees=selectees.addClass("ui-selectee"),this._mouseInit(),this.helper=$("
")},_destroy:function(){this.selectees.removeClass("ui-selectee").removeData("selectable-item"),this.element.removeClass("ui-selectable ui-selectable-disabled"),this._mouseDestroy()},_mouseStart:function(event){var that=this,options=this.options;this.opos=[event.pageX,event.pageY],this.options.disabled||(this.selectees=$(options.filter,this.element[0]),this._trigger("start",event),$(options.appendTo).append(this.helper),this.helper.css({left:event.pageX,top:event.pageY,width:0,height:0}),options.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var selectee=$.data(this,"selectable-item");selectee.startselected=!0,event.metaKey||event.ctrlKey||(selectee.$element.removeClass("ui-selected"),selectee.selected=!1,selectee.$element.addClass("ui-unselecting"),selectee.unselecting=!0,that._trigger("unselecting",event,{unselecting:selectee.element}))}),$(event.target).parents().addBack().each(function(){var doSelect,selectee=$.data(this,"selectable-item");return selectee?(doSelect=!event.metaKey&&!event.ctrlKey||!selectee.$element.hasClass("ui-selected"),selectee.$element.removeClass(doSelect?"ui-unselecting":"ui-selected").addClass(doSelect?"ui-selecting":"ui-unselecting"),selectee.unselecting=!doSelect,selectee.selecting=doSelect,selectee.selected=doSelect,doSelect?that._trigger("selecting",event,{selecting:selectee.element}):that._trigger("unselecting",event,{unselecting:selectee.element}),!1):void 0}))},_mouseDrag:function(event){if(this.dragged=!0,!this.options.disabled){var tmp,that=this,options=this.options,x1=this.opos[0],y1=this.opos[1],x2=event.pageX,y2=event.pageY;return x1>x2&&(tmp=x2,x2=x1,x1=tmp),y1>y2&&(tmp=y2,y2=y1,y1=tmp),this.helper.css({left:x1,top:y1,width:x2-x1,height:y2-y1}),this.selectees.each(function(){var selectee=$.data(this,"selectable-item"),hit=!1;selectee&&selectee.element!==that.element[0]&&("touch"===options.tolerance?hit=!(selectee.left>x2||selectee.righty2||selectee.bottomx1&&selectee.righty1&&selectee.bottom *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,disableHorizontalScroll:!1,scope:"default",tolerance:"intersect",zIndex:1e3,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_isOverAxis:function(x,reference,size){return x>=reference&&reference+size>x},_isFloating:function(item){return/left|right/.test(item.css("float"))||/inline|table-cell/.test(item.css("display"))},_create:function(){this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.offset=this.element.offset(),this._mouseInit(),this._setHandleClassName(),this.ready=!0},_setOption:function(key,value){this._super(key,value),"handle"===key&&this._setHandleClassName()},_setHandleClassName:function(){this.element.find(".ui-sortable-handle").removeClass("ui-sortable-handle"),$.each(this.items,function(){(this.instance.options.handle?this.item.find(this.instance.options.handle):this.item).addClass("ui-sortable-handle")})},_destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled").find(".ui-sortable-handle").removeClass("ui-sortable-handle"),this._mouseDestroy();for(var i=this.items.length-1;i>=0;i--)this.items[i].item.removeData(this.widgetName+"-item");return this},_mouseCapture:function(event,overrideHandle){var currentItem=null,validHandle=!1,that=this;return this.reverting?!1:this.options.disabled||"static"===this.options.type?!1:(this._refreshItems(event),$(event.target).parents().each(function(){return $.data(this,that.widgetName+"-item")===that?(currentItem=$(this),!1):void 0}),$.data(event.target,that.widgetName+"-item")===that&&(currentItem=$(event.target)),currentItem&&(!this.options.handle||overrideHandle||($(this.options.handle,currentItem).find("*").addBack().each(function(){this===event.target&&(validHandle=!0)}),validHandle))?(this.currentItem=currentItem,this._removeCurrentsFromItems(),!0):!1)},_mouseStart:function(event,overrideHandle,noActivation){var i,body,o=this.options;if(this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(event),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},$.extend(this.offset,{click:{left:event.pageX-this.offset.left,top:event.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(event),this.originalPageX=event.pageX,this.originalPageY=event.pageY,o.cursorAt&&this._adjustOffsetFromHelper(o.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),o.containment&&this._setContainment(),o.cursor&&"auto"!==o.cursor&&(body=this.document.find("body"),this.storedCursor=body.css("cursor"),body.css("cursor",o.cursor),this.storedStylesheet=$("").appendTo(body)),o.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",o.opacity)),o.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",o.zIndex)),this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",event,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!noActivation)for(i=this.containers.length-1;i>=0;i--)this.containers[i]._trigger("activate",event,this._uiHash(this));return $.ui.ddmanager&&($.ui.ddmanager.current=this),$.ui.ddmanager&&!o.dropBehaviour&&$.ui.ddmanager.prepareOffsets(this,event),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(event),!0},_mouseDrag:function(event){var i,item,itemElement,intersection,o=this.options,scrolled=!1;for(this.position=this._generatePosition(event),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll&&(this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-event.pageY=0;i--)if(item=this.items[i],itemElement=item.item[0],intersection=this._intersectsWithPointer(item),intersection&&!(item.item.data("dragMultipleActive")||item.instance!==this.currentContainer||itemElement===this.currentItem[0]||this.placeholder[1===intersection?"next":"prev"]()[0]===itemElement||$.contains(this.placeholder[0],itemElement)||("semi-dynamic"===this.options.type?$.contains(this.element[0],itemElement):0))){if(this.direction=1===intersection?"down":"up","pointer"!==this.options.tolerance&&!this._intersectsWithSides(item))break;this._rearrange(event,item),this._trigger("change",event,this._uiHash());break}return this._contactContainers(event),$.ui.ddmanager&&$.ui.ddmanager.drag(this,event),this._trigger("sort",event,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(event,noPropagation){if(event){if($.ui.ddmanager&&!this.options.dropBehaviour&&$.ui.ddmanager.drop(this,event),this.options.revert){var that=this,cur=this.placeholder.offset(),axis=this.options.axis,animation={};axis&&"x"!==axis||(animation.left=cur.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollLeft)),axis&&"y"!==axis||(animation.top=cur.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollTop)),this.reverting=!0,$(this.helper).animate(animation,parseInt(this.options.revert,10)||500,function(){that._clear(event)})}else this._clear(event,noPropagation);return!1}},cancel:function(){if(this.dragging){this._mouseUp({target:null}),"original"===this.options.helper?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var i=this.containers.length-1;i>=0;i--)this.containers[i]._trigger("deactivate",null,this._uiHash(this)),this.containers[i].containerCache.over&&(this.containers[i]._trigger("out",null,this._uiHash(this)),this.containers[i].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),"original"!==this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),$.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?$(this.domPosition.prev).after(this.currentItem):$(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(o){var items=this._getItemsAsjQuery(o&&o.connected),str=[];return o=o||{},$(items).each(function(){var res=($(o.item||this).attr(o.attribute||"id")||"").match(o.expression||/(.+)[\-=_](.+)/);res&&str.push((o.key||res[1]+"[]")+"="+(o.key&&o.expression?res[1]:res[2]))}),!str.length&&o.key&&str.push(o.key+"="),str.join("&")},toArray:function(o){var items=this._getItemsAsjQuery(o&&o.connected),ret=[];return o=o||{},items.each(function(){ret.push($(o.item||this).attr(o.attribute||"id")||"")}),ret},_intersectsWith:function(item){var x1=this.positionAbs.left,x2=x1+this.helperProportions.width,y1=this.positionAbs.top,y2=y1+this.helperProportions.height,l=item.left,r=l+item.width,t=item.top,b=t+item.height,dyClick=this.offset.click.top,dxClick=this.offset.click.left,isOverElementHeight="x"===this.options.axis||y1+dyClick>t&&b>y1+dyClick,isOverElementWidth="y"===this.options.axis||x1+dxClick>l&&r>x1+dxClick,isOverElement=isOverElementHeight&&isOverElementWidth;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>item[this.floating?"width":"height"]?isOverElement:l0?"down":"up")},_getDragHorizontalDirection:function(){var delta=this.positionAbs.left-this.lastPositionAbs.left;return 0!==delta&&(delta>0?"right":"left")},refresh:function(event){return this._refreshItems(event),this._setHandleClassName(),this.refreshPositions(),this},_connectWith:function(){var options=this.options;return options.connectWith.constructor===String?[options.connectWith]:options.connectWith},_getItemsAsjQuery:function(connected){function addItems(){items.push(this)}var i,j,cur,inst,items=[],queries=[],connectWith=this._connectWith();if(connectWith&&connected)for(i=connectWith.length-1;i>=0;i--)for(cur=$(connectWith[i],this.document[0]),j=cur.length-1;j>=0;j--)inst=$.data(cur[j],this.widgetFullName),inst&&inst!==this&&!inst.options.disabled&&queries.push([$.isFunction(inst.options.items)?inst.options.items.call(inst.element):$(inst.options.items,inst.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),inst]);for(queries.push([$.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):$(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]),i=queries.length-1;i>=0;i--)queries[i][0].each(addItems);return $(items)},_removeCurrentsFromItems:function(){var list=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=$.grep(this.items,function(item){for(var j=0;j=0;i--)for(cur=$(connectWith[i],this.document[0]),j=cur.length-1;j>=0;j--)inst=$.data(cur[j],this.widgetFullName),inst&&inst!==this&&!inst.options.disabled&&(queries.push([$.isFunction(inst.options.items)?inst.options.items.call(inst.element[0],event,{item:this.currentItem}):$(inst.options.items,inst.element),inst]),this.containers.push(inst));for(i=queries.length-1;i>=0;i--)for(targetData=queries[i][1],_queries=queries[i][0],j=0,queriesLength=_queries.length;queriesLength>j;j++)item=$(_queries[j]),item.data(this.widgetName+"-item",targetData),items.push({item:item,instance:targetData,width:0,height:0,left:0,top:0})},refreshPositions:function(fast){this.floating=this.items.length?"x"===this.options.axis||this._isFloating(this.items[0].item):!1,this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var i,item,t,p;for(i=this.items.length-1;i>=0;i--)item=this.items[i],$(item.item).data("dragMultipleActive")||item.instance!==this.currentContainer&&this.currentContainer&&item.item[0]!==this.currentItem[0]||(t=this.options.toleranceElement?$(this.options.toleranceElement,item.item):item.item,fast||(item.width=t.outerWidth(),item.height=t.outerHeight()),p=t.offset(),item.left=p.left,item.top=p.top);if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(i=this.containers.length-1;i>=0;i--)p=this.containers[i].element.offset(),this.containers[i].containerCache.left=p.left,this.containers[i].containerCache.top=p.top,this.containers[i].containerCache.width=this.containers[i].element.outerWidth(),this.containers[i].containerCache.height=this.containers[i].element.outerHeight();return this},_createPlaceholder:function(that){that=that||this;var className,o=that.options;o.placeholder&&o.placeholder.constructor!==String||(className=o.placeholder,o.placeholder={element:function(){var nodeName=that.currentItem[0].nodeName.toLowerCase(),element=$("<"+nodeName+">",that.document[0]).addClass(className||that.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper");return"tbody"===nodeName?that._createTrPlaceholder(that.currentItem.find("tr").eq(0),$("",that.document[0]).appendTo(element)):"tr"===nodeName?that._createTrPlaceholder(that.currentItem,element):"img"===nodeName&&element.attr("src",that.currentItem.attr("src")),className||element.css("visibility","hidden"),element},update:function(container,p){(!className||o.forcePlaceholderSize)&&(p.height()||p.height(that.currentItem.innerHeight()-parseInt(that.currentItem.css("paddingTop")||0,10)-parseInt(that.currentItem.css("paddingBottom")||0,10)),p.width()||p.width(that.currentItem.innerWidth()-parseInt(that.currentItem.css("paddingLeft")||0,10)-parseInt(that.currentItem.css("paddingRight")||0,10)))}}),that.placeholder=$(o.placeholder.element.call(that.element,that.currentItem)),that.currentItem.after(that.placeholder),o.placeholder.update(that,that.placeholder)},_createTrPlaceholder:function(sourceTr,targetTr){var that=this;sourceTr.children().each(function(){$(" ",that.document[0]).attr("colspan",$(this).attr("colspan")||1).appendTo(targetTr)})},_contactContainers:function(event){var i,j,dist,itemWithLeastDistance,posProperty,sizeProperty,cur,nearBottom,floating,axis,innermostContainer=null,innermostIndex=null;for(i=this.containers.length-1;i>=0;i--)if(!$.contains(this.currentItem[0],this.containers[i].element[0]))if(this._intersectsWith(this.containers[i].containerCache)){if(innermostContainer&&$.contains(this.containers[i].element[0],innermostContainer.element[0]))continue;innermostContainer=this.containers[i],innermostIndex=i}else this.containers[i].containerCache.over&&(this.containers[i]._trigger("out",event,this._uiHash(this)),this.containers[i].containerCache.over=0);if(innermostContainer)if(1===this.containers.length)this.containers[innermostIndex].containerCache.over||(this.containers[innermostIndex]._trigger("over",event,this._uiHash(this)),this.containers[innermostIndex].containerCache.over=1);else{ -for(dist=1e4,itemWithLeastDistance=null,floating=innermostContainer.floating||this._isFloating(this.currentItem),posProperty=floating?"left":"top",sizeProperty=floating?"width":"height",axis=floating?"clientX":"clientY",j=this.items.length-1;j>=0;j--)$.contains(this.containers[innermostIndex].element[0],this.items[j].item[0])&&this.items[j].item[0]!==this.currentItem[0]&&(cur=this.items[j].item.offset()[posProperty],nearBottom=!1,event[axis]-cur>this.items[j][sizeProperty]/2&&(nearBottom=!0),Math.abs(event[axis]-cur)this.containment[2]&&(pageX=this.containment[2]+this.offset.click.left),event.pageY-this.offset.click.top>this.containment[3]&&(pageY=this.containment[3]+this.offset.click.top)),o.grid&&(top=this.originalPageY+Math.round((pageY-this.originalPageY)/o.grid[1])*o.grid[1],pageY=this.containment?top-this.offset.click.top>=this.containment[1]&&top-this.offset.click.top<=this.containment[3]?top:top-this.offset.click.top>=this.containment[1]?top-o.grid[1]:top+o.grid[1]:top,left=this.originalPageX+Math.round((pageX-this.originalPageX)/o.grid[0])*o.grid[0],pageX=this.containment?left-this.offset.click.left>=this.containment[0]&&left-this.offset.click.left<=this.containment[2]?left:left-this.offset.click.left>=this.containment[0]?left-o.grid[0]:left+o.grid[0]:left)),{top:pageY-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():scrollIsRootNode?0:scroll.scrollTop()),left:pageX-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():scrollIsRootNode?0:scroll.scrollLeft())}},_rearrange:function(event,i,a,hardRefresh){a?a[0].appendChild(this.placeholder[0]):i.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?i.item[0]:i.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var counter=this.counter;this._delay(function(){counter===this.counter&&this.refreshPositions(!hardRefresh)})},_clear:function(event,noPropagation){function delayEvent(type,instance,container){return function(event){container._trigger(type,event,instance._uiHash(instance))}}this.reverting=!1;var i,delayedTriggers=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(i in this._storedCSS)("auto"===this._storedCSS[i]||"static"===this._storedCSS[i])&&(this._storedCSS[i]="");this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();for(this.fromOutside&&!noPropagation&&delayedTriggers.push(function(event){this._trigger("receive",event,this._uiHash(this.fromOutside))}),!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||noPropagation||delayedTriggers.push(function(event){this._trigger("update",event,this._uiHash())}),this!==this.currentContainer&&(noPropagation||(delayedTriggers.push(function(event){this._trigger("remove",event,this._uiHash())}),delayedTriggers.push(function(c){return function(event){c._trigger("receive",event,this._uiHash(this))}}.call(this,this.currentContainer)),delayedTriggers.push(function(c){return function(event){c._trigger("update",event,this._uiHash(this))}}.call(this,this.currentContainer)))),i=this.containers.length-1;i>=0;i--)noPropagation||delayedTriggers.push(delayEvent("deactivate",this,this.containers[i])),this.containers[i].containerCache.over&&(delayedTriggers.push(delayEvent("out",this,this.containers[i])),this.containers[i].containerCache.over=0);if(this.storedCursor&&(this.document.find("body").css("cursor",this.storedCursor),this.storedStylesheet.remove()),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,noPropagation||this._trigger("beforeStop",event,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.cancelHelperRemoval||(this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null),!noPropagation){for(i=0;i",delay:300,options:{icons:{submenu:"ui-icon-carat-1-e"},items:"> *",menus:"ul",position:{my:"left-1 top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.element.uniqueId().addClass("ui-menu ui-widget ui-widget-content").toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length).attr({role:this.options.role,tabIndex:0}),this.options.disabled&&this.element.addClass("ui-state-disabled").attr("aria-disabled","true"),this._on({"mousedown .ui-menu-item":function(event){event.preventDefault()},"click .ui-menu-item":function(event){var target=$(event.target);!this.mouseHandled&&target.not(".ui-state-disabled").length&&(this.select(event),event.isPropagationStopped()||(this.mouseHandled=!0),target.has(".ui-menu").length?this.expand(event):!this.element.is(":focus")&&$(this.document[0].activeElement).closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":function(event){if(!this.previousFilter){var target=$(event.currentTarget);target.siblings(".ui-state-active").removeClass("ui-state-active"),this.focus(event,target)}},mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(event,keepActiveItem){var item=this.active||this.element.find(this.options.items).eq(0);keepActiveItem||this.focus(event,item)},blur:function(event){this._delay(function(){$.contains(this.element[0],this.document[0].activeElement)||this.collapseAll(event)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(event){this._closeOnDocumentClick(event)&&this.collapseAll(event),this.mouseHandled=!1}})},_destroy:function(){this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeClass("ui-menu ui-widget ui-widget-content ui-menu-icons ui-front").removeAttr("role").removeAttr("tabIndex").removeAttr("aria-labelledby").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-disabled").removeUniqueId().show(),this.element.find(".ui-menu-item").removeClass("ui-menu-item").removeAttr("role").removeAttr("aria-disabled").removeUniqueId().removeClass("ui-state-hover").removeAttr("tabIndex").removeAttr("role").removeAttr("aria-haspopup").children().each(function(){var elem=$(this);elem.data("ui-menu-submenu-carat")&&elem.remove()}),this.element.find(".ui-menu-divider").removeClass("ui-menu-divider ui-widget-content")},_keydown:function(event){var match,prev,character,skip,preventDefault=!0;switch(event.keyCode){case $.ui.keyCode.PAGE_UP:this.previousPage(event);break;case $.ui.keyCode.PAGE_DOWN:this.nextPage(event);break;case $.ui.keyCode.HOME:this._move("first","first",event);break;case $.ui.keyCode.END:this._move("last","last",event);break;case $.ui.keyCode.UP:this.previous(event);break;case $.ui.keyCode.DOWN:this.next(event);break;case $.ui.keyCode.LEFT:this.collapse(event);break;case $.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(event);break;case $.ui.keyCode.ENTER:case $.ui.keyCode.SPACE:this._activate(event);break;case $.ui.keyCode.ESCAPE:this.collapse(event);break;default:preventDefault=!1,prev=this.previousFilter||"",character=String.fromCharCode(event.keyCode),skip=!1,clearTimeout(this.filterTimer),character===prev?skip=!0:character=prev+character,match=this._filterMenuItems(character),match=skip&&-1!==match.index(this.active.next())?this.active.nextAll(".ui-menu-item"):match,match.length||(character=String.fromCharCode(event.keyCode),match=this._filterMenuItems(character)),match.length?(this.focus(event,match),this.previousFilter=character,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter}preventDefault&&event.preventDefault()},_activate:function(event){this.active.is(".ui-state-disabled")||(this.active.is("[aria-haspopup='true']")?this.expand(event):this.select(event))},refresh:function(){var menus,items,that=this,icon=this.options.icons.submenu,submenus=this.element.find(this.options.menus);this.element.toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length),submenus.filter(":not(.ui-menu)").addClass("ui-menu ui-widget ui-widget-content ui-front").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var menu=$(this),item=menu.parent(),submenuCarat=$("").addClass("ui-menu-icon ui-icon "+icon).data("ui-menu-submenu-carat",!0);item.attr("aria-haspopup","true").prepend(submenuCarat),menu.attr("aria-labelledby",item.attr("id"))}),menus=submenus.add(this.element),items=menus.find(this.options.items),items.not(".ui-menu-item").each(function(){var item=$(this);that._isDivider(item)&&item.addClass("ui-widget-content ui-menu-divider")}),items.not(".ui-menu-item, .ui-menu-divider").addClass("ui-menu-item").uniqueId().attr({tabIndex:-1,role:this._itemRole()}),items.filter(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!$.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(key,value){"icons"===key&&this.element.find(".ui-menu-icon").removeClass(this.options.icons.submenu).addClass(value.submenu),"disabled"===key&&this.element.toggleClass("ui-state-disabled",!!value).attr("aria-disabled",value),this._super(key,value)},focus:function(event,item){var nested,focused;this.blur(event,event&&"focus"===event.type),this._scrollIntoView(item),this.active=item.first(),focused=this.active.addClass("ui-state-focus").removeClass("ui-state-active"),this.options.role&&this.element.attr("aria-activedescendant",focused.attr("id")),this.active.parent().closest(".ui-menu-item").addClass("ui-state-active"),event&&"keydown"===event.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),nested=item.children(".ui-menu"),nested.length&&event&&/^mouse/.test(event.type)&&this._startOpening(nested),this.activeMenu=item.parent(),this._trigger("focus",event,{item:item})},_scrollIntoView:function(item){var borderTop,paddingTop,offset,scroll,elementHeight,itemHeight;this._hasScroll()&&(borderTop=parseFloat($.css(this.activeMenu[0],"borderTopWidth"))||0,paddingTop=parseFloat($.css(this.activeMenu[0],"paddingTop"))||0,offset=item.offset().top-this.activeMenu.offset().top-borderTop-paddingTop,scroll=this.activeMenu.scrollTop(),elementHeight=this.activeMenu.height(),itemHeight=item.outerHeight(),0>offset?this.activeMenu.scrollTop(scroll+offset):offset+itemHeight>elementHeight&&this.activeMenu.scrollTop(scroll+offset-elementHeight+itemHeight))},blur:function(event,fromFocus){fromFocus||clearTimeout(this.timer),this.active&&(this.active.removeClass("ui-state-focus"),this.active=null,this._trigger("blur",event,{item:this.active}))},_startOpening:function(submenu){clearTimeout(this.timer),"true"===submenu.attr("aria-hidden")&&(this.timer=this._delay(function(){this._close(),this._open(submenu)},this.delay))},_open:function(submenu){var position=$.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(submenu.parents(".ui-menu")).hide().attr("aria-hidden","true"),submenu.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(position)},collapseAll:function(event,all){clearTimeout(this.timer),this.timer=this._delay(function(){var currentMenu=all?this.element:$(event&&event.target).closest(this.element.find(".ui-menu"));currentMenu.length||(currentMenu=this.element),this._close(currentMenu),this.blur(event),this.activeMenu=currentMenu},this.delay)},_close:function(startMenu){startMenu||(startMenu=this.active?this.active.parent():this.element),startMenu.find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false").end().find(".ui-state-active").not(".ui-state-focus").removeClass("ui-state-active")},_closeOnDocumentClick:function(event){return!$(event.target).closest(".ui-menu").length},_isDivider:function(item){return!/[^\-\u2014\u2013\s]/.test(item.text())},collapse:function(event){var newItem=this.active&&this.active.parent().closest(".ui-menu-item",this.element);newItem&&newItem.length&&(this._close(),this.focus(event,newItem))},expand:function(event){var newItem=this.active&&this.active.children(".ui-menu ").find(this.options.items).first();newItem&&newItem.length&&(this._open(newItem.parent()),this._delay(function(){this.focus(event,newItem)}))},next:function(event){this._move("next","first",event)},previous:function(event){this._move("prev","last",event)},isFirstItem:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_move:function(direction,filter,event){var next;this.active&&(next="first"===direction||"last"===direction?this.active["first"===direction?"prevAll":"nextAll"](".ui-menu-item").eq(-1):this.active[direction+"All"](".ui-menu-item").eq(0)),next&&next.length&&this.active||(next=this.activeMenu.find(this.options.items)[filter]()),this.focus(event,next)},nextPage:function(event){var item,base,height;return this.active?void(this.isLastItem()||(this._hasScroll()?(base=this.active.offset().top,height=this.element.height(),this.active.nextAll(".ui-menu-item").each(function(){return item=$(this),item.offset().top-base-height<0}),this.focus(event,item)):this.focus(event,this.activeMenu.find(this.options.items)[this.active?"last":"first"]()))):void this.next(event)},previousPage:function(event){var item,base,height;return this.active?void(this.isFirstItem()||(this._hasScroll()?(base=this.active.offset().top,height=this.element.height(),this.active.prevAll(".ui-menu-item").each(function(){return item=$(this),item.offset().top-base+height>0}),this.focus(event,item)):this.focus(event,this.activeMenu.find(this.options.items).first()))):void this.next(event)},_hasScroll:function(){return this.element.outerHeight()",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},requestIndex:0,pending:0,_create:function(){var suppressKeyPress,suppressKeyPressRepeat,suppressInput,nodeName=this.element[0].nodeName.toLowerCase(),isTextarea="textarea"===nodeName,isInput="input"===nodeName;this.isMultiLine=isTextarea?!0:isInput?!1:this.element.prop("isContentEditable"),this.valueMethod=this.element[isTextarea||isInput?"val":"text"],this.isNewMenu=!0,this.element.addClass("ui-autocomplete-input").attr("autocomplete","off"),this._on(this.element,{keydown:function(event){if(this.element.prop("readOnly"))return suppressKeyPress=!0,suppressInput=!0,void(suppressKeyPressRepeat=!0);suppressKeyPress=!1,suppressInput=!1,suppressKeyPressRepeat=!1;var keyCode=$.ui.keyCode;switch(event.keyCode){case keyCode.PAGE_UP:suppressKeyPress=!0,this._move("previousPage",event);break;case keyCode.PAGE_DOWN:suppressKeyPress=!0,this._move("nextPage",event);break;case keyCode.UP:suppressKeyPress=!0,this._keyEvent("previous",event);break;case keyCode.DOWN:suppressKeyPress=!0,this._keyEvent("next",event);break;case keyCode.ENTER:this.menu.active&&(suppressKeyPress=!0,event.preventDefault(),this.menu.select(event));break;case keyCode.TAB:this.menu.active&&this.menu.select(event);break;case keyCode.ESCAPE:this.menu.element.is(":visible")&&(this.isMultiLine||this._value(this.term),this.close(event),event.preventDefault());break;default:suppressKeyPressRepeat=!0,this._searchTimeout(event)}},keypress:function(event){if(suppressKeyPress)return suppressKeyPress=!1,void((!this.isMultiLine||this.menu.element.is(":visible"))&&event.preventDefault());if(!suppressKeyPressRepeat){var keyCode=$.ui.keyCode;switch(event.keyCode){case keyCode.PAGE_UP:this._move("previousPage",event);break;case keyCode.PAGE_DOWN:this._move("nextPage",event);break;case keyCode.UP:this._keyEvent("previous",event);break;case keyCode.DOWN:this._keyEvent("next",event)}}},input:function(event){return suppressInput?(suppressInput=!1,void event.preventDefault()):void this._searchTimeout(event)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(event){return this.cancelBlur?void delete this.cancelBlur:(clearTimeout(this.searching),this.close(event),void this._change(event))}}),this._initSource(),this.menu=$("