taiga-front-dist/dist/js/app.js

17 lines
475 KiB
JavaScript

(function(){var configure,init,module,modules,taiga;this.taiga=taiga={},this.taigaContribPlugins=this.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,tgLoaderProvider){var authHttpIntercept,defaultHeaders,versionCheckHttpIntercept;return $routeProvider.when("/",{templateUrl:"project/projects.html",resolve:{loader:tgLoaderProvider.add()}}),$routeProvider.when("/project/:pslug/",{templateUrl:"project/project.html"}),$routeProvider.when("/project/:pslug/backlog",{templateUrl:"backlog/backlog.html",resolve:{loader:tgLoaderProvider.add()}}),$routeProvider.when("/project/:pslug/taskboard/:sslug",{templateUrl:"taskboard/taskboard.html",resolve:{loader:tgLoaderProvider.add()}}),$routeProvider.when("/project/:pslug/search",{templateUrl:"search/search.html",reloadOnSearch:!1}),$routeProvider.when("/project/:pslug/kanban",{templateUrl:"kanban/kanban.html",resolve:{loader:tgLoaderProvider.add()}}),$routeProvider.when("/project/:pslug/us/:usref",{templateUrl:"us/us-detail.html",resolve:{loader:tgLoaderProvider.add()}}),$routeProvider.when("/project/:pslug/task/:taskref",{templateUrl:"task/task-detail.html",resolve:{loader:tgLoaderProvider.add()}}),$routeProvider.when("/project/:pslug/wiki",{redirectTo:function(params){return"/project/"+params.pslug+"/wiki/home"}}),$routeProvider.when("/project/:pslug/wiki/:slug",{templateUrl:"wiki/wiki.html",resolve:{loader:tgLoaderProvider.add()}}),$routeProvider.when("/project/:pslug/team",{templateUrl:"team/team.html",resolve:{loader:tgLoaderProvider.add()}}),$routeProvider.when("/project/:pslug/issues",{templateUrl:"issue/issues.html",resolve:{loader:tgLoaderProvider.add()}}),$routeProvider.when("/project/:pslug/issue/:issueref",{templateUrl:"issue/issues-detail.html",resolve:{loader:tgLoaderProvider.add()}}),$routeProvider.when("/project/:pslug/admin/project-profile/details",{templateUrl:"admin/admin-project-profile.html"}),$routeProvider.when("/project/:pslug/admin/project-profile/default-values",{templateUrl:"admin/admin-project-default-values.html"}),$routeProvider.when("/project/:pslug/admin/project-profile/modules",{templateUrl:"admin/admin-project-modules.html"}),$routeProvider.when("/project/:pslug/admin/project-profile/export",{templateUrl:"admin/admin-project-export.html"}),$routeProvider.when("/project/:pslug/admin/project-values/us-status",{templateUrl:"admin/admin-project-values-us-status.html"}),$routeProvider.when("/project/:pslug/admin/project-values/us-points",{templateUrl:"admin/admin-project-values-us-points.html"}),$routeProvider.when("/project/:pslug/admin/project-values/task-status",{templateUrl:"admin/admin-project-values-task-status.html"}),$routeProvider.when("/project/:pslug/admin/project-values/issue-status",{templateUrl:"admin/admin-project-values-issue-status.html"}),$routeProvider.when("/project/:pslug/admin/project-values/issue-types",{templateUrl:"admin/admin-project-values-issue-types.html"}),$routeProvider.when("/project/:pslug/admin/project-values/issue-priorities",{templateUrl:"admin/admin-project-values-issue-priorities.html"}),$routeProvider.when("/project/:pslug/admin/project-values/issue-severities",{templateUrl:"admin/admin-project-values-issue-severities.html"}),$routeProvider.when("/project/:pslug/admin/memberships",{templateUrl:"admin/admin-memberships.html"}),$routeProvider.when("/project/:pslug/admin/roles",{templateUrl:"admin/admin-roles.html"}),$routeProvider.when("/project/:pslug/admin/third-parties/webhooks",{templateUrl:"admin/admin-third-parties-webhooks.html"}),$routeProvider.when("/project/:pslug/admin/third-parties/github",{templateUrl:"admin/admin-third-parties-github.html"}),$routeProvider.when("/project/:pslug/admin/third-parties/gitlab",{templateUrl:"admin/admin-third-parties-gitlab.html"}),$routeProvider.when("/project/:pslug/admin/third-parties/bitbucket",{templateUrl:"admin/admin-third-parties-bitbucket.html"}),$routeProvider.when("/project/:pslug/admin/contrib/:plugin",{templateUrl:"contrib/main.html"}),$routeProvider.when("/project/:pslug/user-settings/user-profile",{templateUrl:"user/user-profile.html"}),$routeProvider.when("/project/:pslug/user-settings/user-change-password",{templateUrl:"user/user-change-password.html"}),$routeProvider.when("/project/:pslug/user-settings/user-avatar",{templateUrl:"user/user-avatar.html"}),$routeProvider.when("/project/:pslug/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("/login",{templateUrl:"auth/login.html"}),$routeProvider.when("/register",{templateUrl:"auth/register.html"}),$routeProvider.when("/forgot-password",{templateUrl:"auth/forgot-password.html"}),$routeProvider.when("/change-password",{templateUrl:"auth/change-password-from-recovery.html"}),$routeProvider.when("/change-password/:token",{templateUrl:"auth/change-password-from-recovery.html"}),$routeProvider.when("/invitation/:token",{templateUrl:"auth/invitation.html"}),$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":"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},$tgEventsProvider.setSessionId(taiga.sessionId),authHttpIntercept=function($q,$location,$navUrls,$lightboxService){var httpResponseError;return httpResponseError=function(response){var nextPath;return 0===response.status?($lightboxService.closeAll(),$location.path($navUrls.resolve("error")),$location.replace()):401===response.status&&(nextPath=$location.path(),$location.url($navUrls.resolve("login")).search("next="+nextPath)),$q.reject(response)},{responseError:httpResponseError}},$provide.factory("authHttpIntercept",["$q","$location","$tgNavUrls","lightboxService",authHttpIntercept]),$httpProvider.interceptors.push("authHttpIntercept"),versionCheckHttpIntercept=function($q,$confirm){var httpResponseError,versionErrorMsg;return versionErrorMsg="Someone inside Taiga has changed this before and our Oompa Loompas cannot apply your changes. Please reload and apply your changes again (they will be lost).",httpResponseError=function(response){return 400===response.status&&response.data.version?($confirm.notify("error",versionErrorMsg,null,1e4),$q.reject(response)):$q.reject(response)},{responseError:httpResponseError}},$provide.factory("versionCheckHttpIntercept",["$q","$tgConfirm",versionCheckHttpIntercept]),$httpProvider.interceptors.push("versionCheckHttpIntercept"),window.checksley.updateValidators({linewidth:function(val,width){var lines,valid;return lines=taiga.nl2br(val).split("<br />"),valid=_.every(lines,function(line){return line.length<width})}}),window.checksley.updateMessages("default",{linewidth:"The subject must have a maximum size of %s"})},init=function($log,$i18n,$config,$rootscope,$auth,$events,$analytics){return $i18n.initialize($config.get("defaultLanguage")),$log.debug("Initialize application"),$rootscope.contribPlugins=this.taigaContribPlugins,$auth.isAuthenticated()&&$events.setupConnection(),$analytics.initialize()},modules=["taigaBase","taigaCommon","taigaResources","taigaLocales","taigaAuth","taigaEvents","taigaRelatedTasks","taigaBacklog","taigaTaskboard","taigaKanban","taigaIssues","taigaUserStories","taigaTasks","taigaTeam","taigaWiki","taigaSearch","taigaAdmin","taigaNavMenu","taigaProject","taigaUserSettings","taigaFeedback","taigaPlugins","taigaIntegrations","templates","ngRoute","ngAnimate"].concat(_.map(this.taigaContribPlugins,function(plugin){return plugin.module})),module=angular.module("taiga",modules),module.config(["$routeProvider","$locationProvider","$httpProvider","$provide","$tgEventsProvider","tgLoaderProvider",configure]),module.run(["$log","$tgI18n","$tgConfig","$rootScope","$tgAuth","$tgEvents","$tgAnalytics",init])}).call(this),function(){var TaigaBase,TaigaController,TaigaService,__hasProp={}.hasOwnProperty,__extends=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},__bind=function(fn,me){return function(){return fn.apply(me,arguments)}};TaigaBase=function(){function TaigaBase(){}return TaigaBase}(),TaigaService=function(_super){function TaigaService(){return TaigaService.__super__.constructor.apply(this,arguments)}return __extends(TaigaService,_super),TaigaService}(TaigaBase),TaigaController=function(_super){function TaigaController(){return this.onInitialDataError=__bind(this.onInitialDataError,this),TaigaController.__super__.constructor.apply(this,arguments)}return __extends(TaigaController,_super),TaigaController.prototype.onInitialDataError=function(xhr){return xhr&&(404===xhr.status?(this.location.path(this.navUrls.resolve("not-found")),this.location.replace()):403===xhr.status&&(this.location.path(this.navUrls.resolve("permission-denied")),this.location.replace())),this.q.reject(xhr)},TaigaController}(TaigaBase),this.taiga.Base=TaigaBase,this.taiga.Service=TaigaService,this.taiga.Controller=TaigaController}.call(this),function(){var bindMethods,bindOnce,cancelTimeout,debounce,debounceLeading,groupBy,joinStr,mixOf,nl2br,scopeDefer,sizeFormat,slugify,startswith,taiga,timeout,toString,toggleText,trim,unslugify,__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},__slice=[].slice,__hasProp={}.hasOwnProperty,__extends=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};nl2br=function(){return function(str){var breakTag;return breakTag="<br />",(str+"").replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g,"$1"+breakTag+"$2")}}(this),bindMethods=function(){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(){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,method,mixin,mixins,name,_i,_ref;for(base=arguments[0],mixins=2<=arguments.length?__slice.call(arguments,1):[],Mixed=function(_super){function Mixed(){return Mixed.__super__.constructor.apply(this,arguments)}return __extends(Mixed,_super),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 item,result,_i,_len;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(){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)},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])},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.debounce=debounce,taiga.debounceLeading=debounceLeading,taiga.startswith=startswith,taiga.sizeFormat=sizeFormat}.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,availableRoles;return activeUsers=_.filter(users,function(){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"),availableRoles=_(this.scope.project.memberships).map("role").uniq().value(),this.scope.computableRoles=_(roles).filter("computable").filter(function(x){return _.contains(availableRoles,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))),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),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,__hasProp={}.hasOwnProperty,__extends=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};taiga=this.taiga,debounce=this.taiga.debounce,module=angular.module("taigaAuth",["taigaResources"]),AuthService=function(_super){function AuthService(rootscope,storage,model,rs,http,urls){this.rootscope=rootscope,this.storage=storage,this.model=model,this.rs=rs,this.http=http,this.urls=urls,AuthService.__super__.constructor.call(this)}return __extends(AuthService,_super),AuthService.$inject=["$rootScope","$tgStorage","$tgModel","$tgResources","$tgHttp","$tgUrls"],AuthService.prototype.getUser=function(){var user,userData;return this.rootscope.user?this.rootscope.user:(userData=this.storage.get("userInfo"),userData?(user=this.model.make_model("users",userData),this.rootscope.user=user,user):null)},AuthService.prototype.setUser=function(user){return this.rootscope.auth=user,this.rootscope.$broadcast("i18n:change",user.default_language),this.storage.set("userInfo",user.getAttrs()),this.rootscope.user=user},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){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()},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){var link;return link=function($scope,$el){var onError,onSuccess,submit;return onSuccess=function(){var nextUrl;return nextUrl=$routeParams.next&&$routeParams.next!==$navUrls.resolve("login")?$routeParams.next:$navUrls.resolve("home"),$events.setupConnection(),$location.path(nextUrl)},onError=function(){return $confirm.notify("light-error","According to our Oompa Loompas, your username/email or password are incorrect.")},submit=debounce(2e3,function(){return function(event){var data,form,promise;return event.preventDefault(),form=new checksley.Form($el.find("form.login-form")),form.validate()?(data={username:$el.find("form.login-form input[name=username]").val(),password:$el.find("form.login-form input[name=password]").val()},promise=$auth.login(data),promise.then(onSuccess,onError)):void 0}}(this)),$el.on("submit","form",submit),$el.on("click",".submit-button",submit)},{link:link}},module.directive("tgLogin",["$tgAuth","$tgConfirm","$tgLocation","$tgConfig","$routeParams","$tgNavUrls","$tgEvents",LoginDirective]),RegisterDirective=function($auth,$confirm,$location,$navUrls,$config,$analytics){var link;return link=function($scope,$el){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(){return $analytics.trackEvent("auth","register","user registration",1),$confirm.notify("success","Our Oompa Loompas are happy, welcome to Taiga."),$location.path($navUrls.resolve("home"))},onErrorSubmit=function(response){return null!=response.data._error_message&&$confirm.notify("light-error","According to our Oompa Loompas there was an error. "+response.data._error_message),form.setErrors(response.data)},submit=debounce(2e3,function(){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),$el.on("click",".submit-button",submit)},{link:link}},module.directive("tgRegister",["$tgAuth","$tgConfirm","$tgLocation","$tgNavUrls","$tgConfig","$tgAnalytics",RegisterDirective]),ForgotPasswordDirective=function($auth,$confirm,$location,$navUrls){var link;return link=function($scope,$el){var form,onErrorSubmit,onSuccessSubmit,submit;return $scope.data={},form=$el.find("form").checksley(),onSuccessSubmit=function(response){return $location.path($navUrls.resolve("login")),$confirm.success("<strong>Check your inbox!</strong><br /> We have sent a mail to<br /> <strong>"+response.data.email+"</strong><br /> with the instructions to set a new password")},onErrorSubmit=function(){return $confirm.notify("light-error","According to our Oompa Loompas, your are not registered yet.")},submit=debounce(2e3,function(){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),$el.on("click",".submit-button",submit)},{link:link}},module.directive("tgForgotPassword",["$tgAuth","$tgConfirm","$tgLocation","$tgNavUrls",ForgotPasswordDirective]),ChangePasswordFromRecoveryDirective=function($auth,$confirm,$location,$params,$navUrls){var link;return link=function($scope,$el){var form,onErrorSubmit,onSuccessSubmit,submit;return $scope.data={},null!=$params.token?($scope.tokenInParams=!0,$scope.data.token=$params.token):$scope.tokenInParams=!1,form=$el.find("form").checksley(),onSuccessSubmit=function(){return $location.path($navUrls.resolve("login")),$confirm.success("Our Oompa Loompas saved your new password.<br /> Try to <strong>sign in</strong> with it.")},onErrorSubmit=function(response){return $confirm.notify("light-error","One of our Oompa Loompas say '"+response.data._error_message+"'.")},submit=debounce(2e3,function(){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),$el.on("click",".submit-button",submit)},{link:link}},module.directive("tgChangePasswordFromRecovery",["$tgAuth","$tgConfirm","$tgLocation","$routeParams","$tgNavUrls",ChangePasswordFromRecoveryDirective]),InvitationDirective=function($auth,$confirm,$location,$params,$navUrls,$analytics){var link;return link=function($scope,$el){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(){return $location.path($navUrls.resolve("login")),$confirm.success("<strong>Ooops, we have a problem</strong><br /> Our Oompa Loompas can't find your invitation.")}),$scope.dataLogin={token:token},loginForm=$el.find("form.login-form").checksley({onlyOneErrorElement:!0}),onSuccessSubmitLogin=function(){return $analytics.trackEvent("auth","invitationAccept","invitation accept with existing 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))},onErrorSubmitLogin=function(){return $confirm.notify("light-error","According to our Oompa Loompas, your are not registered yet or typed an invalid password.")},submitLogin=debounce(2e3,function(){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(),onSuccessSubmitRegister=function(){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(){return $confirm.notify("light-error","According to our Oompa Loompas, that username or email is already in use.")},submitRegister=debounce(2e3,function(){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)},{link:link}},module.directive("tgInvitation",["$tgAuth","$tgConfirm","$tgLocation","$routeParams","$tgNavUrls","$tgAnalytics",InvitationDirective]),ChangeEmailDirective=function($repo,$model,$auth,$confirm,$location,$params,$navUrls){var link;return link=function($scope,$el){var form,onErrorSubmit,onSuccessSubmit,submit;return $scope.data={},$scope.data.email_token=$params.email_token,form=$el.find("form").checksley(),onSuccessSubmit=function(){return $repo.queryOne("users",$auth.getUser().id).then(function(){return function(data){return $auth.setUser(data),$location.path($navUrls.resolve("home")),$confirm.success("Our Oompa Loompas updated your email")}}(this))},onErrorSubmit=function(response){return $confirm.notify("error","One of our Oompa Loompas says '"+response.data._error_message+"'.")},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()})},{link:link}},module.directive("tgChangeEmail",["$tgRepo","$tgModel","$tgAuth","$tgConfirm","$tgLocation","$routeParams","$tgNavUrls",ChangeEmailDirective]),CancelAccountDirective=function($repo,$model,$auth,$confirm,$location,$params,$navUrls){var link;return link=function($scope,$el){var form,onErrorSubmit,onSuccessSubmit,submit;return $scope.data={},$scope.data.cancel_token=$params.cancel_token,form=$el.find("form").checksley(),onSuccessSubmit=function(){return $auth.logout(),$location.path($navUrls.resolve("home")),$confirm.success("Our Oompa Loompas removed your account")},onErrorSubmit=function(response){return $confirm.notify("error","One of our Oompa Loompas says '"+response.data._error_message+"'.")},submit=debounce(2e3,function(){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),$el.on("click",".submit-button",submit)},{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",["taigaLocales"]),TaigaMainDirective=function($rootscope,$window){var link;return link=function(){return $window.onresize=function(){return $rootscope.$broadcast("resize")}},{link:link}},module.directive("tgMain",["$rootScope","$window",TaigaMainDirective]),urls={home:"/",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:"/:user",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-values-us-status":"/project/:project/admin/project-values/us-status","project-admin-project-values-us-points":"/project/:project/admin/project-values/us-points","project-admin-project-values-task-status":"/project/:project/admin/project-values/task-status","project-admin-project-values-issue-status":"/project/:project/admin/project-values/issue-status","project-admin-project-values-issue-types":"/project/:project/admin/project-values/issue-types","project-admin-project-values-issue-priorities":"/project/:project/admin/project-values/issue-priorities","project-admin-project-values-issue-severities":"/project/:project/admin/project-values/issue-severities","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":"/project/:project/user-settings/user-profile","user-settings-user-change-password":"/project/:project/user-settings/user-change-password","user-settings-user-avatar":"/project/:project/user-settings/user-avatar","user-settings-mail-notifications":"/project/:project/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,AppTitle,CheckPermissionDirective,LimitLineLengthDirective,ProjectUrl,Qqueue,SelectedText,Template,ToggleCommentDirective,module,taiga,__slice=[].slice;taiga=this.taiga,module=angular.module("taigaCommon",[]),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),AnimationFrame=function(){var add,animationFrame,performAnimation,tail;return animationFrame=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame,performAnimation=function(){return function(){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),_results.push(1===tail.length?animationFrame(performAnimation):void 0);return _results},{add:add}},module.factory("animationFrame",AnimationFrame),ToggleCommentDirective=function(){var link;return link=function($scope,$el){return $el.find("textarea").on("focus",function(){return $el.addClass("active")})},{link:link}},module.directive("tgToggleComment",ToggleCommentDirective),AppTitle=function(){var set;return set=function(text){return $("title").text(text)},{set:set}},module.factory("$appTitle",AppTitle),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){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(){return function(fn){return lastPromise=lastPromise?lastPromise.then(fn):fn(),qqueue}}(this)}},module.factory("$tgQqueue",["$q",Qqueue]),Template=function($templateCache){return{get:function(){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])}.call(this),function(){var EventsProvider,EventsService,bindMethods,module,startswith,taiga;taiga=this.taiga,startswith=this.taiga.startswith,bindMethods=this.taiga.bindMethods,module=angular.module("taigaEvents",[]),EventsService=function(){function EventsService(win,log,config,auth){this.win=win,this.log=log,this.config=config,this.auth=auth,bindMethods(this)}return EventsService.prototype.initialize=function(sessionId){return this.sessionId=sessionId,this.subscriptions={},this.connected=!1,this.error=!1,this.pendingMessages=[],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.ws.close(),delete this.ws):void 0},EventsService.prototype.serialize=function(message){return _.isObject(message)?JSON.stringify(message):message},EventsService.prototype.sendMessage=function(message){var messages,msg,_i,_len,_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.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.$on("$destroy",function(_this){return function(){return _this.unsubscribe(routingKey)}}(this))},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.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,routingKey,subscription;return this.log.debug("WebSocket message received: "+event.data),data=JSON.parse(event.data),routingKey=data.routing_key,null!=this.subscriptions[routingKey]?(subscription=this.subscriptions[routingKey],subscription.scope.$apply(function(){return subscription.callback(data.data)})):void 0},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},EventsService}(),EventsProvider=function(){function EventsProvider(){}return EventsProvider.prototype.setSessionId=function(sessionId){return this.sessionId=sessionId},EventsProvider.prototype.$get=function($win,$log,$conf,$auth){var service;return service=new EventsService($win,$log,$conf,$auth),service.initialize(this.sessionId),service},EventsProvider.prototype.$get.$inject=["$window","$log","$tgConfig","$tgAuth"],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){var link;return link=function($scope,$el){var form,submit,submitButton;return form=$el.find("form").checksley(),submit=debounce(2e3,function(){return function(event){var promise;return event.preventDefault(),form.validate()?($loading.start(submitButton),promise=$repo.create("feedback",$scope.feedback),promise.then(function(){return $loading.finish(submitButton),$lightboxService.close($el),$confirm.notify("success","\\o/ we'll be happy to read your")}),promise.then(null,function(){return $loading.finish(submitButton),$confirm.notify("error")})):void 0}}(this)),submitButton=$el.find(".submit-button"),$el.on("submit","form",submit),$el.on("click",".submit-button",submit),$scope.$on("feedback:show",function(){return $scope.$apply(function(){return $scope.feedback={}}),$lightboxService.open($el),$el.find("textarea").focus()}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgLbFeedback",["lightboxService","$tgRepo","$tgConfirm","$tgLoading",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("taigaLocales",[])}.call(this),function(){var ProjectMenuDirective,ProjectsNavigationController,ProjectsNavigationDirective,bindOnce,groupBy,module,taiga,timeout,__hasProp={}.hasOwnProperty,__extends=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};taiga=this.taiga,groupBy=this.taiga.groupBy,bindOnce=this.taiga.bindOnce,timeout=this.taiga.timeout,module=angular.module("taigaNavMenu",[]),ProjectsNavigationController=function(_super){function ProjectsNavigationController(scope,rootscope,rs,navurls,projectUrl){var promise;this.scope=scope,this.rootscope=rootscope,this.rs=rs,this.navurls=navurls,this.projectUrl=projectUrl,promise=this.loadInitialData(),promise.then(null,function(){return console.log("FAIL")}),this.scope.$on("projects:reload",function(_this){return function(){return _this.loadInitialData()}}(this)),this.scope.$on("project:loaded",function(_this){return function(){return _this.loadInitialData()}}(this))}return __extends(ProjectsNavigationController,_super),ProjectsNavigationController.$inject=["$scope","$rootScope","$tgResources","$tgNavUrls","$projectUrl"],ProjectsNavigationController.prototype.loadInitialData=function(){return this.rs.projects.list().then(function(_this){return function(projects){var project,_i,_len;for(_i=0,_len=projects.length;_len>_i;_i++)project=projects[_i],project.url=_this.projectUrl.get(project);return _this.scope.projects=projects,_this.scope.filteredProjects=projects,_this.scope.filterText="",projects}}(this))},ProjectsNavigationController.prototype.newProject=function(){return this.scope.$apply(function(_this){return function(){return _this.rootscope.$broadcast("projects:create")}}(this))},ProjectsNavigationController.prototype.filterProjects=function(text){return this.scope.filteredProjects=_.filter(this.scope.projects,function(project){return project.name.toLowerCase().indexOf(text)>-1}),this.scope.filterText=text,this.rootscope.$broadcast("projects:filtered")},ProjectsNavigationController}(taiga.Controller),module.controller("ProjectsNavigationController",ProjectsNavigationController),ProjectsNavigationDirective=function($rootscope,animationFrame,$timeout,tgLoader,$location,$compile,$template){var baseTemplate,hideMenu,link,loadingStart,overlay,projectsTemplate;return baseTemplate=$template.get("project/project-navigation-base.html",!0),projectsTemplate=$template.get("project/project-navigation-list.html",!0),overlay=$(".projects-nav-overlay"),loadingStart=0,hideMenu=function(){var difftime,timeoutValue;return overlay.is(":visible")?(difftime=(new Date).getTime()-loadingStart,timeoutValue=0,1e3>difftime&&(timeoutValue=1e3-timeoutValue),timeout(timeoutValue,function(){return overlay.one("transitionend",function(){return $(document.body).removeClass("loading-project open-projects-nav closed-projects-nav").css("overflow-x","visible"),overlay.hide()}),$(document.body).addClass("closed-projects-nav"),tgLoader.disablePreventLoading()})):void 0},link=function($scope,$el,$attrs,$ctrls){var $ctrl,render,renderProjects;return $ctrl=$ctrls[0],$rootscope.$on("project:loaded",hideMenu),renderProjects=function(projects){var html;return html=projectsTemplate({projects:projects}),$el.find(".projects-list").html(html),$scope.$emit("regenerate:project-pagination")},render=function(projects){return $el.html($compile(baseTemplate())($scope)),renderProjects(projects)},overlay.on("click",function(){return hideMenu()}),$(document).on("keydown",function(){return function(e){var code;return code=e.keyCode?e.keyCode:e.which,27===code?hideMenu():void 0}}(this)),$scope.$on("nav:projects-list:open",function(){return $(document.body).hasClass("open-projects-nav")||animationFrame.add(function(){return function(){return overlay.show()}}(this)),animationFrame.add(function(){return function(){return $(document.body).css("overflow-x","hidden")}}(this),function(){return function(){return $(document.body).toggleClass("open-projects-nav")}}(this))}),$el.on("click",".projects-list > li > a",function(event){var currentUrl,nextUrl,target;return target=angular.element(event.currentTarget),nextUrl=target.prop("href"),currentUrl=$location.absUrl(),nextUrl===currentUrl?void hideMenu():($(document.body).addClass("loading-project"),tgLoader.preventLoading(),loadingStart=(new Date).getTime())}),$el.on("click",".create-project-button",function(event){return event.preventDefault(),$ctrl.newProject()}),$el.on("keyup",".search-project",function(event){var target;return target=angular.element(event.currentTarget),$ctrl.filterProjects(target.val())}),$scope.$on("projects:filtered",function(){return renderProjects($scope.filteredProjects)}),$scope.$watch("projects",function(projects){return null!=projects?render(projects):void 0})},{require:["tgProjectsNav"],controller:ProjectsNavigationController,link:link}},module.directive("tgProjectsNav",["$rootScope","animationFrame","$timeout","tgLoader","$tgLocation","$compile","$tgTemplate",ProjectsNavigationDirective]),ProjectMenuDirective=function($log,$compile,$auth,$rootscope,$tgAuth,$location,$navUrls,$config,$template){var getSectionName,link,mainTemplate,menuEntriesTemplate,renderMainMenu,renderMenuEntries,videoConferenceUrl;return menuEntriesTemplate=$template.get("project/project-menu.html",!0),mainTemplate=_.template('<div class="logo-container logo">\n <svg xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 134.2 134.3" version="1.1" preserveAspectRatio="xMidYMid meet">\n <style>\n path {\n fill:#f5f5f5;\n opacity:0.7;\n }\n </style>\n <g transform="translate(-307.87667,-465.22863)">\n <g class="bottom">\n <path transform="matrix(-0.14066483,0.99005727,-0.99005727,0.14066483,0,0)" d="m561.8-506.6 42 0 0 42-42 0z" />\n <path transform="matrix(0.14066483,-0.99005727,0.99005727,-0.14066483,0,0)" d="m-645.7 422.6 42 0 0 42-42 0z" />\n <path transform="matrix(0.99005727,0.14066483,0.14066483,0.99005727,0,0)" d="m266.6 451.9 42 0 0 42-42 0z" />\n <path transform="matrix(-0.99005727,-0.14066483,-0.14066483,-0.99005727,0,0)" d="m-350.6-535.9 42 0 0 42-42 0z" />\n </g>\n <g class="top">\n <path transform="matrix(-0.60061118,-0.79954125,0.60061118,-0.79954125,0,0)" d="m-687.1-62.7 42 0 0 42-42 0z" />\n <path transform="matrix(-0.79954125,0.60061118,-0.79954125,-0.60061118,0,0)" d="m166.6-719.6 42 0 0 42-42 0z" />\n <path transform="matrix(0.60061118,0.79954125,-0.60061118,0.79954125,0,0)" d="m603.1-21.3 42 0 0 42-42 0z" />\n <path transform="matrix(0.79954125,-0.60061118,0.79954125,0.60061118,0,0)" d="m-250.7 635.8 42 0 0 42-42 0z" />\n <path transform="matrix(0.70710678,0.70710678,-0.70710678,0.70710678,0,0)" d="m630.3 100 22.6 0 0 22.6-22.6 0z" />\n </g>\n </g>\n </svg>\n <span class="item">taiga<sup>[beta]</sup></span>\n</div>\n<div class="menu-container"></div>'),getSectionName=function($el,sectionName,project){var oldSectionName,_ref;return oldSectionName=null!=(_ref=$el.find("a.active").parent().attr("id"))?_ref.replace("nav-",""):void 0,"backlog-kanban"===sectionName&&("backlog"===oldSectionName||"kanban"===oldSectionName?sectionName=oldSectionName:project.is_backlog_activated&&!project.is_kanban_activated?sectionName="backlog":!project.is_backlog_activated&&project.is_kanban_activated&&(sectionName="kanban")),sectionName},renderMainMenu=function($el){var html;return html=mainTemplate({}),$el.html(html)},renderMenuEntries=function($el,targetScope,project){var container,ctx,dom,sectionName;return null==project&&(project={}),container=$el.find(".menu-container"),sectionName=getSectionName($el,targetScope.section,project),ctx={user:$auth.getUser(),project:project,feedbackEnabled:$config.get("feedbackEnabled")},dom=$compile(menuEntriesTemplate(ctx))(targetScope),dom.find("a.active").removeClass("active"),dom.find("#nav-"+sectionName+" > a").addClass("active"),container.replaceWith(dom)},videoConferenceUrl=function(project){var baseUrl,url;if("appear-in"===project.videoconferences)baseUrl="https://appear.in/";else{if("talky"!==project.videoconferences)return"";baseUrl="https://talky.io/"}return url=project.videoconferences_salt?""+project.slug+"-"+project.videoconferences_salt:""+project.slug,baseUrl+url},link=function($scope,$el){var project;return renderMainMenu($el),project=null,$el.on("click",".logo",function(event){var target;return event.preventDefault(),target=angular.element(event.currentTarget),$rootscope.$broadcast("nav:projects-list:open")}),$el.on("click",".user-settings .avatar",function(event){return event.preventDefault(),$el.find(".user-settings .popover").popover().open()}),$el.on("click",".logout",function(event){return event.preventDefault(),$auth.logout(),$scope.$apply(function(){return $location.path($navUrls.resolve("login"))})}),$el.on("click","#nav-search > a",function(event){return event.preventDefault(),$rootscope.$broadcast("search-box:show",project)}),$el.on("click",".feedback",function(event){return event.preventDefault(),$rootscope.$broadcast("feedback:show")}),$scope.$on("projects:loaded",function(listener){return $el.addClass("hidden"),listener.stopPropagation()}),$scope.$on("project:loaded",function(ctx,newProject){return project=newProject,$el.hasClass("hidden")&&$el.removeClass("hidden"),project.videoconferenceUrl=videoConferenceUrl(project),renderMenuEntries($el,ctx.targetScope,project)})},{link:link}},module.directive("tgProjectMenu",["$log","$compile","$tgAuth","$rootScope","$tgAuth","$tgLocation","$tgNavUrls","$tgConfig","$tgTemplate",ProjectMenuDirective])}.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){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 promise;return task.subject=$el.find("input").val(),$loading.start($el.find(".task-name")),promise=$repo.save(task),promise.then(function(){return function(){return $loading.finish($el.find(".task-name")),$confirm.notify("success"),$rootscope.$broadcast("related-tasks:update")}}(this)),promise.then(null,function(){return function(){return $loading.finish($el.find(".task-name")),$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(){return saveTask($model.$modelValue).then(function(){return renderView($model.$modelValue)})}),$el.on("click",".cancel-edit",function(){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(){var message,title;return task=$model.$modelValue,title="Delete Task",message=task.subject,$confirm.askOnDelete(title,message).then(function(finish){var promise;return promise=$repo.remove(task),promise.then(function(){return finish(),$confirm.notify("success"),$scope.$emit("related-tasks:delete")}),promise.then(null,function(){return $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",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){var createTask,render;return createTask=debounce(2e3,function(task){var 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,$loading.start($el.find(".task-name")),promise=$repo.create("tasks",task),promise.then(function(){return $analytics.trackEvent("task","create","create task on userstory",1),$loading.finish($el.find(".task-name")),$scope.$emit("related-tasks:add"),$confirm.notify("success")}),promise.then(null,function(){return $el.find("input").val(task.subject),$loading.finish($el.find(".task-name")),$confirm.notify("error")}),promise}),render=function(){return $el.off(),$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?$el.html(""):void 0}),$el.on("click",".icon-delete",function(){return $el.html("")}),$el.on("click",".icon-floppy",function(){return createTask(newTask).then(function(){return $el.html("")})})},taiga.bindOnce($scope,"us",function(){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(){var link,template;return template=_.template('<a class="icon icon-plus related-tasks-buttons"></a>'),link=function($scope,$el){return $scope.$watch("project",function(val){return val?($el.off(),$el.html(-1!==$scope.project.my_permissions.indexOf("add_task")?template():""),$el.on("click",".icon",function(){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){var loadTasks;return loadTasks=function(){return $rs.tasks.list($scope.projectId,null,$scope.usId).then(function(){return function(tasks){return $scope.tasks=tasks,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(){return loadTasks()}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgRelatedTasks",["$tgRepo","$tgResources","$rootScope",RelatedTasksDirective]),RelatedTaskAssignedToInlineEditionDirective=function($repo,$rootscope){var link,template;return template=_.template('<img src="<%- imgurl %>" alt="<%- name %>"/>\n<figcaption><%- name %></figcaption>'),link=function($scope,$el,$attrs){var $ctrl,autoSave,notAutoSave,task,updateRelatedTask;return updateRelatedTask=function(task){var ctx,member;return ctx={name:"Unassigned",imgurl:"/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(){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(){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,__hasProp={}.hasOwnProperty,__extends=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};taiga=this.taiga,ResourcesService=function(_super){function ResourcesService(){return ResourcesService.__super__.constructor.apply(this,arguments)}return __extends(ResourcesService,_super),ResourcesService}(taiga.Service),urls={auth:"/auth","auth-register":"/auth/register",invitations:"/invitations",permissions:"/permissions",roles:"/roles",projects:"/projects",memberships:"/memberships","notify-policies":"/notify-policies","bulk-create-memberships":"/memberships/bulk_create",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-restore":"/userstories/%s/restore",tasks:"/tasks","bulk-create-tasks":"/tasks/bulk_create","bulk-update-task-taskboard-order":"/tasks/bulk_update_taskboard_order","tasks-restore":"/tasks/%s/restore",issues:"/issues","bulk-create-issues":"/issues/bulk_create","issues-restore":"/issues/%s/restore",wiki:"/wiki","wiki-restore":"/wiki/%s/restore","wiki-links":"/wiki-links","choices/userstory-statuses":"/userstory-statuses","choices/userstory-statuses/bulk-update-order":"/userstory-statuses/bulk_update_order","choices/points":"/points","choices/points/bulk-update-order":"/points/bulk_update_order","choices/task-statuses":"/task-statuses","choices/task-statuses/bulk-update-order":"/task-statuses/bulk_update_order","choices/issue-statuses":"/issue-statuses","choices/issue-statuses/bulk-update-order":"/issue-statuses/bulk_update_order","choices/issue-types":"/issue-types","choices/issue-types/bulk-update-order":"/issue-types/bulk_update_order","choices/priorities":"/priorities","choices/priorities/bulk-update-order":"/priorities/bulk_update_order","choices/severities":"/severities","choices/severities/bulk-update-order":"/severities/bulk_update_order",search:"/search",sites:"/sites","project-templates":"/project-templates","site-members":"/site-members","site-projects":"/site-projects",users:"/users","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-storage":"/user-storage",resolver:"/resolver","userstory-statuses":"/userstory-statuses",points:"/points","task-statuses":"/task-statuses","issue-statuses":"/issue-statuses","issue-types":"/issue-types",priorities:"/priorities",severities:"/severities","project-modules":"/projects/%s/modules",webhooks:"/webhooks","webhooks-test":"/webhooks/%s/test",webhooklogs:"/webhooklogs","webhooklogs-resend":"/webhooklogs/%s/resend","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",feedback:"/feedback",exporter:"/exporter",importer:"/importer/load_dump"},initUrls=function($log,$urls){return $log.debug("Initialize api urls"),$urls.update(urls)},initResources=function($log,$rs){var provider,providers,_i,_len,_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","$tgMembershipsResourcesProvider","$tgNotifyPoliciesResourcesProvider","$tgInvitationsResourcesProvider","$tgRolesResourcesProvider","$tgUserSettingsResourcesProvider","$tgSprintsResourcesProvider","$tgUserstoriesResourcesProvider","$tgTasksResourcesProvider","$tgIssuesResourcesProvider","$tgWikiResourcesProvider","$tgSearchResourcesProvider","$tgAttachmentsResourcesProvider","$tgMdRenderResourcesProvider","$tgHistoryResourcesProvider","$tgKanbanResourcesProvider","$tgModulesResourcesProvider","$tgWebhooksResourcesProvider","$tgWebhookLogsResourcesProvider",initResources])
}.call(this),function(){var SearchBoxDirective,SearchController,SearchDirective,bindOnce,debounce,debounceLeading,groupBy,mixOf,module,taiga,trim,__hasProp={}.hasOwnProperty,__extends=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};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(_super){function SearchController(scope,repo,rs,params,q,location,appTitle,navUrls,tgLoader){var loadSearchData,promise;this.scope=scope,this.repo=repo,this.rs=rs,this.params=params,this.q=q,this.location=location,this.appTitle=appTitle,this.navUrls=navUrls,this.tgLoader=tgLoader,this.scope.sectionName="Search",promise=this.loadInitialData(),promise.then(function(_this){return function(){return _this.appTitle.set("Search")}}(this)),promise.then(null,this.onInitialDataError.bind(this)),this.scope.searchTerm="",loadSearchData=debounceLeading(100,function(_this){return function(t){return _this.loadSearchData(t)}}(this)),this.scope.$watch("searchTerm",function(_this){return function(term){return term?loadSearchData(term):_this.tgLoader.pageLoaded()}}(this))}return __extends(SearchController,_super),SearchController.$inject=["$scope","$tgRepo","$tgResources","$routeParams","$q","$tgLocation","$appTitle","$tgNavUrls","tgLoader"],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.membersById=groupBy(project.memberships,function(x){return x.user}),_this.scope.usStatusById=groupBy(project.us_statuses,function(x){return x.id}),project}}(this))},SearchController.prototype.loadSearchData=function(term){var promise;return promise=this.rs.search["do"](this.scope.projectId,term).then(function(_this){return function(data){return _this.scope.searchResults=data,data}}(this)),promise["finally"](function(_this){return function(){return _this.tgLoader.pageLoaded()}}(this)),promise},SearchController.prototype.loadInitialData=function(){return this.loadProject().then(function(_this){return function(project){return _this.scope.projectId=project.id,_this.fillUsersAndRoles(project.users,project.roles)}}(this))},SearchController}(mixOf(taiga.Controller,taiga.PageMixin)),module.controller("SearchController",SearchController),SearchBoxDirective=function($lightboxService,$navurls,$location,$route){var link;return link=function($scope,$el){var project,submit;return project=null,submit=debounce(2e3,function(){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.slug}),$lightboxService.close($el),$scope.$apply(function(){return $location.path(url),$location.search("text",text).path(url),$route.reload()})):void 0}}(this)),$scope.$on("search-box:show",function(ctx,newProject){return project=newProject,$lightboxService.open($el),$el.find("#search-text").val("")}),$el.on("submit","form",submit),$el.on("click",".submit-button",submit)},{link:link}},module.directive("tgSearchBox",["lightboxService","$tgNavUrls","$tgLocation","$route",SearchBoxDirective]),SearchDirective=function($log,$compile,$templatecache,$routeparams,$location){var link,linkTable;return linkTable=function($scope,$el){var getActiveSection,lastSeatchResults,markSectionTabActive,renderFilterTabs,renderTableContent,tabsDom,templates;return tabsDom=$el.find("section.search-filter"),lastSeatchResults=null,getActiveSection=function(data){var maxVal,name,selectedSectionData,selectedSectionName,value;maxVal=0,selectedSectionName=null,selectedSectionData=null;for(name in data)value=data[name],"count"!==name&&value.length>maxVal&&(maxVal=value.length,selectedSectionName=name,selectedSectionData=value);return 0===maxVal?{name:"userstories",value:[]}:{name:selectedSectionName,value:selectedSectionData}},renderFilterTabs=function(data){var name,value,_results;_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")},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 lastSeatchResults=data,activeSection=getActiveSection(data),renderFilterTabs(data),renderTableContent(activeSection),markSectionTabActive(activeSection)}),$scope.$watch("searchTerm",function(searchTerm){return 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=lastSeatchResults[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,__hasProp={}.hasOwnProperty,__extends=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};taiga=this.taiga,module=angular.module("taigaCommon"),AnalyticsService=function(_super){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 __extends(AnalyticsService,_super),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,__hasProp={}.hasOwnProperty,__extends=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};taiga=this.taiga,sizeFormat=this.taiga.sizeFormat,bindOnce=this.taiga.bindOnce,bindMethods=this.taiga.bindMethods,module=angular.module("taigaCommon"),AttachmentsController=function(_super){function AttachmentsController(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.uploadingAttachments=[],this.attachments=[],this.attachmentsCount=0,this.deprecatedAttachmentsCount=0,this.showDeprecated=!1}return __extends(AttachmentsController,_super),AttachmentsController.$inject=["$scope","$rootScope","$tgRepo","$tgResources","$tgConfirm","$q"],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;return 413===data.status&&_this.scope.$emit("attachments:size-error"),index=_this.uploadingAttachments.indexOf(attachment),_this.uploadingAttachments.splice(index,1),_this.confirm.notify("error","We have not been able to upload '"+attachment.name+"'. "+data.data._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,_i,_len,_ref;for(_ref=_this.attachments,_i=0,_len=_ref.length;_len>_i;_i++)item=_ref[_i],item.revert();return _this.attachments=_.sorBy(_this.attachments,"order")}}(this))},AttachmentsController.prototype.removeAttachment=function(attachment){var message,title;return title="Delete attachment",message="the attachment '"+attachment.name+"'",this.confirm.askOnDelete(title,message).then(function(_this){return function(finish){var onError,onSuccess;return onSuccess=function(){var index;return finish(),index=_this.attachments.indexOf(attachment),_this.attachments.splice(index,1),_this.updateCounters(),_this.rootscope.$broadcast("attachment:delete")},onError=function(){return finish(!1),_this.confirm.notify("error",null,"We have not been able to delete "+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){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()}),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?"Maximum upload size is "+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",AttachmentsDirective]),AttachmentDirective=function($template){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,created_date:moment(attachment.created_date).format("DD MMM YYYY [at] hh:mm"),url:attachment.url,size:sizeFormat(attachment.size),description:attachment.description,isDeprecated:attachment.is_deprecated,modifyPermission:modifyPermission},html=edit?templateEdit(ctx):template(ctx),$el.html(html),attachment.is_deprecated?($el.addClass("deprecated"),$el.find("input:checkbox").prop("checked",!0)):void 0},saveAttachment=function(){return attachment.description=$el.find("input[name='description']").val(),attachment.is_deprecated=$el.find("input[name='is-deprecated']").prop("checked"),$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?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)})}),$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",AttachmentDirective])}.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(){var link,renderRange;return renderRange=function($el,first,second){var endDate,initDate;return initDate=moment(first).format("DD MMM YYYY"),endDate=moment(second).format("DD MMM YYYY"),$el.html(""+initDate+"-"+endDate)},link=function($scope,$el,$attrs){var first,second,_ref;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",DateRangeDirective),DateSelectorDirective=function(){var link;return link=function($scope,$el,$attrs){var selectedDate;return selectedDate=null,$el.picker=new Pikaday({field:$el[0],format:"DD MMM YYYY",onSelect:function(){return function(date){return selectedDate=date}}(this),onOpen:function(){return function(){return null!=selectedDate?$el.picker.setDate(selectedDate):void 0}}(this)}),$scope.$watch($attrs.ngModel,function(val){return null!=val?$el.picker.setDate(val):void 0})},{link:link,require:"ngModel"}},module.directive("tgDateSelector",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)})},{link:link}},module.directive("tgSprintProgressbar",SprintProgressBarDirective),CreatedByDisplayDirective=function($template){var link,template;return template=$template.get("common/components/created-by.html",!0),link=function($scope,$el,$attrs){var render;return render=function(model){var html,owner,_ref;return owner=(null!=(_ref=$scope.usersById)?_ref[model.owner]:void 0)||{full_name_display:"external user",photo:"/images/unnamed.png"},html=template({owner:owner,date:moment(model.created_date).format("DD MMM YYYY HH:mm")}),$el.html(html)},bindOnce($scope,$attrs.ngModel,function(model){return null!=model?render(model):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,restrict:"EA",require:"ngModel"}},module.directive("tgCreatedByDisplay",["$tgTemplate",CreatedByDisplayDirective]),WatchersDirective=function($rootscope,$confirm,$repo,$qqueue,$template){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(){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("history:reload")}),promise.then(null,function(){return $model.$modelValue.revert()})}}(this)),deleteWatcher=$qqueue.bindAdd(function(){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("history:reload")}),promise.then(null,function(){return item.revert(),$confirm.notify("error")})}}(this)),renderWatchers=function(watchers){var ctx,html;return ctx={watchers:watchers,isEditable:isEditable()},html=template(ctx),$el.html(html),isEditable()&&0===watchers.length?($el.find(".title").text("Add watchers"),$el.find(".watchers-header").addClass("no-watchers")):void 0},$el.on("click",".icon-delete",function(event){var message,target,title,watcherId;return event.preventDefault(),isEditable()?(target=angular.element(event.currentTarget),watcherId=target.data("watcher-id"),title="Delete watcher",message=$scope.usersById[watcherId].full_name_display,$confirm.askOnDelete(title,message).then(function(){return function(finish){var watcherIds;return finish(),watcherIds=_.clone($model.$modelValue.watchers,!1),watcherIds=_.pull(watcherIds,watcherId),deleteWatcher(watcherIds)}}(this))):void 0}),$el.on("click",".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",WatchersDirective]),AssignedToDirective=function($rootscope,$confirm,$repo,$loading,$qqueue,$template){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(){return function(userId){var promise;return $model.$modelValue.assigned_to=userId,$loading.start($el),promise=$repo.save($model.$modelValue),promise.then(function(){return $loading.finish($el),$confirm.notify("success"),renderAssignedTo($model.$modelValue),$rootscope.$broadcast("history:reload")}),promise.then(null,function(){return $model.$modelValue.revert(),$confirm.notify("error"),$loading.finish($el)}),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=template(ctx),$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="Are you sure you want to leave it unassigned?",$confirm.ask(title).then(function(){return function(finish){return 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",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 finish;return event.preventDefault(),$loading.start($el.find(".item-unblock")),finish=function(){return $loading.finish($el.find(".item-unblock"))},$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",function(){var subtitle,title;return title=$scope.$eval($attrs.onDeleteTitle),subtitle=$model.$modelValue.subject,$confirm.askOnDelete(title,subtitle).then(function(){return function(finish){var promise;return promise=$repo.remove($model.$modelValue),promise.then(function(){var url;return finish(),url=$scope.$eval($attrs.onDeleteGoToUrl),$location.path(url)}),promise.then(null,function(){return 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 isEditable=function(){return-1!==$scope.project.my_permissions.indexOf($attrs.requiredPerm)},save=$qqueue.bindAdd(function(){return function(subject){var promise;return $model.$modelValue.subject=subject,$loading.start($el.find(".save-container")),promise=$repo.save($model.$modelValue),promise.then(function(){return $confirm.notify("success"),$rootscope.$broadcast("history:reload"),$el.find(".edit-subject").hide(),$el.find(".view-subject").show()}),promise.then(null,function(){return $confirm.notify("error")}),promise["finally"](function(){return $loading.finish($el.find(".save-container"))}),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(){var subject;return 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(){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(),isEditable=function(){return-1!==$scope.project.my_permissions.indexOf($attrs.requiredPerm)},save=$qqueue.bindAdd(function(){return function(description){var promise;return $model.$modelValue.description=description,$loading.start($el.find(".save-container")),promise=$repo.save($model.$modelValue),promise.then(function(){return $confirm.notify("success"),$rootscope.$broadcast("history:reload"),$el.find(".edit-description").hide(),$el.find(".view-description").show()}),promise.then(null,function(){return $confirm.notify("error")}),promise["finally"](function(){return $loading.finish($el.find(".save-container"))})}}(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",".save",function(){var description;return description=$scope.item.description,save(description)}),$el.on("keydown","textarea",function(event){return 27===event.keyCode?($scope.$apply(function(){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=noDescriptionMegEditMode):$scope.noDescriptionMsg=noDescriptionMegReadMode):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]),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}},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}},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}},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,"membersById",function(membersById){var ctx,item,member;return item=$scope.$eval($attrs.tgListitemAssignedto),ctx={name:"Unassigned",imgurl:"/images/unnamed.png"},member=membersById[item.assigned_to],member&&(ctx.imgurl=member.photo,ctx.name=member.full_name),$el.html(template(ctx))})},{link:link}},module.directive("tgListitemAssignedto",["$tgTemplate",ListItemAssignedtoDirective]),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"}},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"}},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($template){var link,render,template;return template=$template.get("common/components/main-title.html",!0),render=function(el,projectName,sectionName){return el.html(template({projectName:projectName,sectionName:sectionName}))},link=function($scope,$el){var element;return element=angular.element($el),$scope.$watch("project",function(project){return project?render($el,project.name,$scope.sectionName):void 0}),$scope.$on("project:loaded",function(){return function(ctx,project){return render($el,project.name,$scope.sectionName)}}(this)),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgMainTitle",["$tgTemplate",TgMainTitleDirective]),module.directive("tgListitemType",ListItemTypeDirective),module.directive("tgListitemIssueStatus",ListItemIssueStatusDirective),module.directive("tgListitemSeverity",ListItemSeverityDirective),module.directive("tgListitemTaskStatus",ListItemTaskStatusDirective),module.directive("tgListitemUsStatus",ListItemUsStatusDirective)}.call(this),function(){var ConfirmService,NOTIFICATION_MSG,bindMethods,cancelTimeout,debounce,module,taiga,timeout,__hasProp={}.hasOwnProperty,__extends=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};taiga=this.taiga,timeout=this.taiga.timeout,cancelTimeout=this.taiga.cancelTimeout,debounce=this.taiga.debounce,bindMethods=this.taiga.bindMethods,NOTIFICATION_MSG={success:{title:"Everything is ok",message:"Our Oompa Loompas saved all your changes!"},error:{title:"Oops, something happened...",message:"Our Oompa Loompas are sad, your changes were not saved!"},"light-error":{title:"Oops, something happened...",message:"Our Oompa Loompas are sad, your changes were not saved!"}},ConfirmService=function(_super){function ConfirmService(q,lightboxService,loading){this.q=q,this.lightboxService=lightboxService,this.loading=loading,bindMethods(this)}return __extends(ConfirmService,_super),ConfirmService.$inject=["$q","lightboxService","$tgLoading"],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"),el=angular.element(lightboxSelector),el.find("h2.title").html(title),el.find("span.subtitle").html(subtitle),el.find("span.message").html(message),defered=this.q.defer(),el.on("click.confirm-dialog","a.button-green",debounce(2e3,function(_this){return function(event){var target;return event.preventDefault(),target=angular.element(event.currentTarget),_this.loading.start(target),defered.resolve(function(ok){return null==ok&&(ok=!0),_this.loading.finish(target),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,"Are you sure you want to delete?",message)},ConfirmService.prototype.askChoice=function(title,subtitle,choices,replacement,warning,lightboxSelector){var choicesField,defered,el;return null==lightboxSelector&&(lightboxSelector=".lightbox-ask-choice"),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("<option value='"+key+"'>"+value+"</option>"))}),defered=this.q.defer(),el.on("click.confirm-dialog","a.button-green",debounce(2e3,function(_this){return function(event){var target;return event.preventDefault(),target=angular.element(event.currentTarget),_this.loading.start(target),defered.resolve({selected:choicesField.val(),finish:function(){return _this.loading.finish(target),_this.hide(el)}})}}(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 el=angular.element(".lightbox-generic-error"),el.find("h2.title").html(message),defered=this.q.defer(),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 el=angular.element(".lightbox-generic-success"),title&&el.find("h2.title").html(title),message&&el.find("p.message").html(message),defered=this.q.defer(),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(){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:(el.find("h4").html(title?title:NOTIFICATION_MSG[type].title),el.find("p").html(message?message: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",function(){return function(){return body.find(selector).removeClass("active").addClass("inactive")}}(this)))},ConfirmService}(taiga.Service),module=angular.module("taigaCommon"),module.service("$tgConfirm",ConfirmService)}.call(this),function(){var LbUsEstimationDirective,UsEstimationDirective,module,taiga;taiga=this.taiga,module=angular.module("taigaCommon"),LbUsEstimationDirective=function($rootScope,$repo,$confirm,$template){var link,mainTemplate,pointsTemplate;return mainTemplate=$template.get("common/estimation/lb-us-estimation-points-per-role.html",!0),pointsTemplate=$template.get("common/estimation/lb-us-estimation-points.html",!0),link=function($scope,$el,$attrs,$model){var calculateTotalPoints,render,renderPoints;return render=function(points){var computableRoles,ctx,html,roles,totalPoints;return totalPoints=calculateTotalPoints(points)||0,computableRoles=_.filter($scope.project.roles,"computable"),roles=_.map(computableRoles,function(role){var pointId,pointObj;return pointId=points[role.id],pointObj=$scope.pointsById[pointId],role=_.clone(role,!0),role.points=null!=pointObj&&null!=pointObj.name?pointObj.name:"?",role}),ctx={totalPoints:totalPoints,roles:roles},html=mainTemplate(ctx),$el.html(html)},renderPoints=function(target,usPoints,roleId){var html,points;return points=_.map($scope.project.points,function(point){return point=_.clone(point,!0),point.selected=usPoints[roleId]===point.id?!1:!0,point}),html=pointsTemplate({points:points,roleId:roleId}),$el.find(".popover").popover().close(),$el.find(".pop-points-open").remove(),null==$el.find(".pop-role:visible").css("left")&&$el.find(".pop-points-open").css("left","110px"),$el.find(".pop-points-open").remove(),$el.find(target).append(html),$el.find(".pop-points-open").popover().open(function(){return $(this).removeClass("active")}),$el.find(".pop-points-open").show()},calculateTotalPoints=function(points){var values;return values=_.map(points,function(v){var _ref;return(null!=(_ref=$scope.pointsById[v])?_ref.value:void 0)||0}),0===values.length?"0":_.reduce(values,function(acc,num){return acc+num})},$el.on("click",".total.clickable",function(event){var points,roleId,target;return event.preventDefault(),event.stopPropagation(),target=angular.element(event.currentTarget),roleId=target.data("role-id"),points=$model.$modelValue,renderPoints(target,points,roleId),target.siblings().removeClass("active"),target.addClass("active")}),$el.on("click",".point",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"),$el.find(".popover").popover().close(),points=_.clone($model.$modelValue,!0),points[roleId]=pointId,$scope.$apply(function(){return $model.$setViewValue(points)})}),$scope.$watch($attrs.ngModel,function(points){return points?render(points):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,restrict:"EA",require:"ngModel"}},module.directive("tgLbUsEstimation",["$rootScope","$tgRepo","$tgConfirm","$tgTemplate",LbUsEstimationDirective]),UsEstimationDirective=function($rootScope,$repo,$confirm,$qqueue,$template){var link,mainTemplate,pointsTemplate;return mainTemplate=$template.get("common/estimation/us-estimation-points-per-role.html",!0),pointsTemplate=$template.get("common/estimation/us-estimation-points.html",!0),link=function($scope,$el,$attrs,$model){var calculateTotalPoints,isEditable,render,renderPoints,save;return isEditable=function(){return-1!==$scope.project.my_permissions.indexOf("modify_us")},render=function(us){var computableRoles,ctx,html,roles,totalPoints;return totalPoints=null!=us.total_points?us.total_points:"?",computableRoles=_.filter($scope.project.roles,"computable"),roles=_.map(computableRoles,function(role){var pointId,pointObj;return pointId=us.points[role.id],pointObj=$scope.pointsById[pointId],role=_.clone(role,!0),role.points=null!=pointObj&&null!=pointObj.name?pointObj.name:"?",role}),ctx={totalPoints:totalPoints,roles:roles,editable:isEditable()},html=mainTemplate(ctx),$el.html(html)},renderPoints=function(target,us,roleId){var html,points;return points=_.map($scope.project.points,function(point){return point=_.clone(point,!0),point.selected=us.points[roleId]===point.id?!1:!0,point}),html=pointsTemplate({points:points,roleId:roleId}),$el.find(".popover").popover().close(),$el.find(".pop-points-open").remove(),null==$el.find(".pop-role:visible").css("left")&&$el.find(".pop-points-open").css("left","110px"),$el.find(".pop-points-open").remove(),$el.find(target).append(html),$el.find(".pop-points-open").popover().open(function(){return $(this).removeClass("active").closest("li").removeClass("active")}),$el.find(".pop-points-open").show()},calculateTotalPoints=function(us){var notNullValues,values;return values=_.map(us.points,function(v){var _ref;return null!=(_ref=$scope.pointsById[v])?_ref.value:void 0}),0===values.length?"0":(notNullValues=_.filter(values,function(v){return null!=v}),0===notNullValues.length?"?":_.reduce(notNullValues,function(acc,num){return acc+num}))},save=$qqueue.bindAdd(function(){return function(roleId,pointId){var onError,onSuccess,points,us;return $el.find(".popover").popover().close(),us=angular.copy($model.$modelValue),points=_.clone($model.$modelValue.points,!0),points[roleId]=pointId,us.setAttr("points",points),us.points=points,us.total_points=calculateTotalPoints(us),$model.$setViewValue(us),onSuccess=function(){return $confirm.notify("success"),$rootScope.$broadcast("history:reload")},onError=function(){return $confirm.notify("error"),us.revert(),$model.$setViewValue(us)},$repo.save($model.$modelValue).then(onSuccess,onError)}}(this)),$el.on("click",".total.clickable",function(event){var roleId,target,us;return event.preventDefault(),event.stopPropagation(),isEditable()?(target=angular.element(event.currentTarget),roleId=target.data("role-id"),us=$model.$modelValue,renderPoints(target,us,roleId),target.siblings().removeClass("active"),target.addClass("active")):void 0}),$el.on("click",".point",function(event){var pointId,roleId,target;return event.preventDefault(),event.stopPropagation(),isEditable()?(target=angular.element(event.currentTarget),roleId=target.data("role-id"),pointId=target.data("point-id"),save(roleId,pointId)):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("tgUsEstimation",["$rootScope","$tgRepo","$tgConfirm","$tgQqueue","$tgTemplate",UsEstimationDirective])}.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(){return function(value){return value?"Yes":"No"}},module.filter("yesNo",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,bindOnce,debounce,module,taiga,trim,__hasProp={}.hasOwnProperty,__extends=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};taiga=this.taiga,trim=this.taiga.trim,bindOnce=this.taiga.bindOnce,debounce=this.taiga.debounce,module=angular.module("taigaCommon"),HistoryController=function(_super){function HistoryController(scope,repo,rs){this.scope=scope,this.repo=repo,this.rs=rs}return __extends(HistoryController,_super),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 historyResult,_i,_len;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;return _this.scope.history=history,_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){var link,templateActivity,templateBase,templateBaseEntries,templateChangeAttachment,templateChangeDiff,templateChangeGeneric,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),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,getUserAvatar,getUserFullName,objectId,renderActivity,renderAttachmentEntry,renderChange,renderChangeEntries,renderChangeEntry,renderChangesHelperText,renderComment,renderComments,renderHistory,save,showAllActivity,showAllComments,type;return type=$attrs.type,objectId=null,showAllComments=!1,showAllActivity=!1,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={assigned_to:"assigned to",is_closed:"is closed",finish_date:"finish date",client_requirement:"client requirement",team_requirement:"team requirement",milestone:"sprint",user_story:"user story",is_iocaine:"is iocaine",is_deprecated:"is deprecated"},humanizedFieldNames[field]||field},getUserFullName=function(userId){var _ref;return null!=(_ref=$scope.usersById[userId])?_ref.full_name_display:void 0},getUserAvatar=function(userId){return null!=$scope.usersById[userId]?$scope.usersById[userId].photo:"/images/unnamed.png"},countChanges=function(comment){return _.keys(comment.values_diff).length},formatChange=function(change){return _.isArray(change)?0===change.length?"nil":change.join(", "):""===change?"nil":change===!0?"yes":change===!1?"no":change},renderAttachmentEntry=function(value){var attachments;return attachments=_.map(value,function(changes,type){return"new"===type?_.map(changes,function(change){return templateChangeDiff({name:"new attachment",diff:change.filename})}):"deleted"===type?_.map(changes,function(change){return templateChangeDiff({name:"deleted attachment",diff:change.filename})}):_.map(changes,function(change){var diff,name;return name="updated attachment "+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")},renderChangeEntry=function(field,value){var from,name,to;return"description"===field?templateChangeDiff({name:"description",diff:value[1]}):"points"===field?templateChangePoints({points:value}):"attachments"===field?renderAttachmentEntry(value):"assigned_to"===field?(name=getHumanizedFieldName(field),from=formatChange(value[0]||"Unassigned"),to=formatChange(value[1]||"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,join){var entries;return null==join&&(join=!0),entries=_.map(change.values_diff,function(value,field){return renderChangeEntry(field,value)}),join?entries.join("\n"):entries},renderChangesHelperText=function(change){var size;return size=countChanges(change),1===size?"Made "+size+" change":"Made "+size+" changes"},renderComment=function(comment){var _ref;return comment.delete_comment_date||comment.delete_comment_user?templateDeletedComment({deleteCommentDate:moment(comment.delete_comment_date).format("DD MMM YYYY HH:mm"),deleteCommentUser:comment.delete_comment_user.name,deleteComment:comment.comment_html,activityId:comment.id,canRestoreComment:comment.delete_comment_user.pk===$scope.user.id||$scope.project.my_permissions.indexOf("modify_project")>-1}):templateActivity({avatar:getUserAvatar(comment.user.pk),userFullName:comment.user.name,creationDate:moment(comment.created_at).format("DD MMM YYYY HH:mm"),comment:comment.comment_html,changesText:renderChangesHelperText(comment),changes:renderChangeEntries(comment,!1),mode:"comment",deleteCommentDate:comment.delete_comment_date?moment(comment.delete_comment_date).format("DD MMM YYYY HH:mm"):void 0,deleteCommentUser:(null!=(_ref=comment.delete_comment_user)?_ref.name:void 0)?comment.delete_comment_user.name:void 0,activityId:comment.id,canDeleteComment:comment.user.pk===$scope.user.id||$scope.project.my_permissions.indexOf("modify_project")>-1})},renderChange=function(change){var _ref;return templateActivity({avatar:getUserAvatar(change.user.pk),userFullName:change.user.name,creationDate:moment(change.created_at).format("DD MMM YYYY HH:mm"),comment:change.comment_html,changes:renderChangeEntries(change,!1),changesText:"",mode:"activity",deleteCommentDate:change.delete_comment_date?moment(change.delete_comment_date).format("DD MMM YYYY HH:mm"):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 showMore;return showMore=entries.length===totalEntries?0:totalEntries-entries.length,templateBaseEntries({entries:entries,showMore:showMore})},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(){return function(target){var model,onError,onSuccess;return $scope.$broadcast("markdown-editor:submit"),$el.find(".comment-list").addClass("activeanimation"),onSuccess=function(){return $ctrl.loadHistory(type,objectId)["finally"](function(){return $loading.finish(target)})},onError=function(){return $loading.finish(target),$confirm.notify("error")},model=$scope.$eval($attrs.ngModel),$loading.start(target),$ctrl.repo.save(model).then(onSuccess,onError)}}(this)),$scope.$watch("comments",renderComments),$scope.$watch("history",renderActivity),$scope.$on("history:reload",function(){return $ctrl.loadHistory(type,objectId)}),$el.on("click",".add-comment a.button-green",debounce(2e3,function(event){var target;return event.preventDefault(),target=angular.element(event.currentTarget),save(target)})),$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(){return $(this).addClass("active")}),$el.on("click",".history-tabs li a",function(){return $el.find(".history-tabs li a").toggleClass("active"),$el.find(".history section").toggleClass("hidden")}),$el.on("click",".comment-delete",debounce(2e3,function(event){var activityId,target;return 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 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){return 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",HistoryDirective])}.call(this),function(){var ImportProjectButtonDirective,module;module=angular.module("taigaCommon"),ImportProjectButtonDirective=function($rs,$confirm,$location,$navUrls){var link;return link=function($scope,$el){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("Uploading dump file"),onSuccess=function(result){var ctx,message,title;return loader.stop(),202===result.status?(title="Our Oompa Loompas are importing your project",message="This process could take a few minutes <br/> We will send you an email when ready",$confirm.success(title,message)):(ctx={project:result.data.slug},$location.path($navUrls.resolve("project-admin-project-profile-details",ctx)),$confirm.notify("success","Your project has been imported successfuly."))},onError=function(result){var errorMsg,_ref;return loader.stop(),console.log("Error",result),errorMsg="Our oompa loompas have some problems importing your dump data. Please try again. ",429===result.status?errorMsg="Sorry, our oompa loompas are very busy right now. Please try again in a few minutes. ":(null!=(_ref=result.data)?_ref._error_message:void 0)&&(errorMsg="Our oompa loompas have some problems importing your dump data: "+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",ImportProjectButtonDirective])}.call(this),function(){var AssignedToLightboxDirective,BlockLightboxDirective,BlockingMessageInputDirective,CreateBulkUserstoriesDirective,CreateEditUserstoryDirective,LightboxDirective,LightboxKeyboardNavigationService,LightboxService,NotionButtonDirective,NotionLightboxDirective,WatchersLightboxDirective,bindOnce,debounce,module,timeout,__hasProp={}.hasOwnProperty,__extends=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};module=angular.module("taigaCommon"),bindOnce=this.taiga.bindOnce,timeout=this.taiga.timeout,debounce=this.taiga.debounce,LightboxService=function(_super){function LightboxService(animationFrame){this.animationFrame=animationFrame}return __extends(LightboxService,_super),LightboxService.prototype.open=function($el){var docEl,lightboxContent;return lightboxContent=$el.children().not(".close"),lightboxContent.hide(),$el.css("display","flex"),$el.find("input,textarea").first().focus(),this.animationFrame.add(function(){return function(){return $el.addClass("open"),lightboxContent.show()}}(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))},LightboxService.prototype.close=function($el){var docEl;return docEl=angular.element(document),docEl.off(".lightbox"),docEl.off(".keyboard-navigation"),$el.one("transitionend",function(){return function(){return $el.removeAttr("style"),$el.removeClass("open").removeClass("close")}}(this)),$el.addClass("close")},LightboxService.prototype.closeAll=function(){var docEl,lightboxEl,_i,_len,_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",LightboxService]),LightboxKeyboardNavigationService=function(_super){function LightboxKeyboardNavigationService(){return LightboxKeyboardNavigationService.__super__.constructor.apply(this,arguments)}return __extends(LightboxKeyboardNavigationService,_super),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(".active"),13===code)return activeElement.trigger("click");if(40===code){if(!activeElement.length)return $el.find(".watcher-single:first").addClass("active");if(next=activeElement.next(".watcher-single"),next.length)return activeElement.removeClass("active"),next.addClass("active")}else if(38===code){if(!activeElement.length)return $el.find(".watcher-single:last").addClass("active");if(prev=activeElement.prev(".watcher-single"),prev.length)return activeElement.removeClass("active"),prev.addClass("active")}},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){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){var link;return link=function($scope,$el,$attrs,$model){var block,unblock;return $el.find("h2.title").text($attrs.title),unblock=$qqueue.bindAdd(function(){return function(item,finishCallback){var promise;return promise=$tgrepo.save(item),promise.then(function(){return $confirm.notify("success"),$rootscope.$broadcast("history:reload"),$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(){return function(item){var promise;return $model.$setViewValue(item),$loading.start($el.find(".button-green")),promise=$tgrepo.save($model.$modelValue),promise.then(function(){return $confirm.notify("success"),$rootscope.$broadcast("history:reload")}),promise.then(null,function(){return $confirm.notify("error"),item.revert(),$model.$setViewValue(item)}),promise["finally"](function(){return $loading.finish($el.find(".button-green")),lightboxService.close($el)})}}(this)),$scope.$on("block",function(){return $el.find(".reason").val($model.$modelValue.blocked_note),lightboxService.open($el)}),$scope.$on("unblock",function(){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",BlockLightboxDirective]),BlockingMessageInputDirective=function($log,$template){var link,template,templateFn;return template=$template.get("common/lightbox/lightbox-blocking-message-input.html",!0),link=function($scope,$el,$attrs){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",BlockingMessageInputDirective]),CreateEditUserstoryDirective=function($repo,$model,$rs,$rootScope,lightboxService,$loading){var link;return link=function($scope,$el){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("Create"),$el.find(".title").html("New user story "),$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("Save"),$el.find(".title").html("Edit user story "),$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(){return function(event){var broadcastEvent,form,promise;return event.preventDefault(),form=$el.find("form").checksley(),form.validate()?($loading.start(submitButton),$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 $loading.finish(submitButton),lightboxService.close($el),$rootScope.$broadcast(broadcastEvent,data)}),promise.then(null,function(data){return $loading.finish(submitButton),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",".submit-button",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",CreateEditUserstoryDirective]),CreateBulkUserstoriesDirective=function($repo,$rs,$rootscope,lightboxService,$loading){var link;return link=function($scope,$el){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(){return function(event){var form,promise;return event.preventDefault(),form=$el.find("form").checksley({onlyOneErrorElement:!0}),form.validate()?($loading.start(submitButton),promise=$rs.userstories.bulkCreate($scope["new"].projectId,$scope["new"].statusId,$scope["new"].bulk),promise.then(function(result){return $loading.finish(submitButton),$rootscope.$broadcast("usform:bulk:success",result),lightboxService.close($el)}),promise.then(null,function(data){return $loading.finish(submitButton),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",".submit-button",submit),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgLbCreateBulkUserstories",["$tgRepo","$tgResources","$rootScope","lightboxService","$tgLoading",CreateBulkUserstoriesDirective]),AssignedToLightboxDirective=function(lightboxService,lightboxKeyboardNavigationService,$template){var link;return link=function($scope,$el){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 $el.find("input").focus(),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),$el.find("div.watchers").html(html),lightboxKeyboardNavigationService.init($el)},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),$el.find("input").focus()}),$scope.$watch("usersSearch",function(searchingText){return null!=searchingText?render(selectedUser,searchingText):void 0}),$el.on("click",".watcher-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",AssignedToLightboxDirective]),WatchersLightboxDirective=function($repo,lightboxService,lightboxKeyboardNavigationService){var link;return link=function($scope,$el){var closeLightbox,getFilteredUsers,render,selectedItem;return selectedItem=null,getFilteredUsers=function(text){var users,_filterUsers;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 $el.find("input").focus(),ctx={selected:!1,users:_.first(users,5),showMore:users.length>5},html=usersTemplate(ctx),$el.find("div.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),lightboxKeyboardNavigationService.init($el)}),$scope.$watch("usersSearch",function(searchingText){var users;if(null!=searchingText)return users=getFilteredUsers(searchingText),render(users)}),$el.on("click",".watcher-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",WatchersLightboxDirective]),NotionLightboxDirective=function(lightboxService){var link;return link=function($scope,$el){return $scope.$on("notion:open",function(event,lightboxId){return $el.attr("id")===lightboxId?lightboxService.open($el):void 0}),$el.on("click",".button-green",function(){return lightboxService.close($el)}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgLbNotion",["lightboxService",NotionLightboxDirective]),NotionButtonDirective=function($log,$rootScope){var link;return link=function($scope,$el,$attrs){return null==$attrs.tgLbNotionButton?$log.error("NotionButtonDirective: the directive need the id of the notion lightbox"):($el.on("click",function(){return $rootScope.$broadcast("notion:open",$attrs.tgLbNotionButton)}),$scope.$on("$destroy",function(){return $el.off()}))},{link:link}},module.directive("tgLbNotionButton",["$log","$rootScope",NotionButtonDirective])}.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){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")}),$rootscope.$on("$routeChangeSuccess",function(){return tgLoader.startCurrentPageLoader()}),$rootscope.$on("$locationChangeSuccess",function(){return tgLoader.reset()})},{link:link}},module.directive("tgLoader",["tgLoader","$rootScope",LoaderDirective]),Loader=function(){var config,defaultConfig,forceDisabled;forceDisabled=!1,defaultConfig={enabled:!1,minTime:300},config=_.merge({},defaultConfig),this.add=function(){return function(){return forceDisabled?void 0:config.enabled=!0}},this.$get=["$rootScope",function($rootscope){var pageLoaded,reset,start,startLoadTime;return startLoadTime=0,reset=function(){return config=_.merge({},defaultConfig)},pageLoaded=function(force){var diff,endTime,timeoutValue;return null==force&&(force=!1),startLoadTime?(timeoutValue=0,force||(endTime=(new Date).getTime(),diff=endTime-startLoadTime,diff<config.minTime&&(timeoutValue=config.minTime-diff)),timeout(timeoutValue,function(){return $rootscope.$broadcast("loader:end")})):void 0},start=function(){return startLoadTime=(new Date).getTime(),$rootscope.$broadcast("loader:start")},{reset:reset,pageLoaded:pageLoaded,start:start,startCurrentPageLoader:function(){return config.enabled?start():void 0},onStart:function(fn){return $rootscope.$on("loader:start",fn)},onEnd:function(fn){return $rootscope.$on("loader:end",fn)},preventLoading:function(){return forceDisabled=!0},disablePreventLoading:function(){return forceDisabled=!1}}}]},module.provider("tgLoader",[Loader])}.call(this),function(){var TgLoadingService,module,__hasProp={}.hasOwnProperty,__extends=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};module=angular.module("taigaCommon"),TgLoadingService=function(_super){function TgLoadingService(){return TgLoadingService.__super__.constructor.apply(this,arguments)}return __extends(TgLoadingService,_super),TgLoadingService.prototype.start=function(target){return target.hasClass("loading")?void 0:(target.data("loading-old-content",target.html()),target.addClass("loading"),target.html("<img class='loading-spinner' src='/svg/spinner-circle.svg' alt='loading...' />"))},TgLoadingService.prototype.finish=function(target){var oldContent;return target.hasClass("loading")?(oldContent=target.data("loading-old-content"),target.data("loading-old-content",null),target.html(oldContent),target.removeClass("loading")):void 0},TgLoadingService}(taiga.Service),module.service("$tgLoading",TgLoadingService)}.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(){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(){return function(onClose){return onClose&&onClose.call($el),$el.fadeOut(function(){return $el.removeClass("active").removeClass("fix")}),$el.off("popup:close")}}(this),closeAll=function(){return function(){return $(".popover.active").each(function(){return $(this).trigger("popup:close")})}}(this),open=function(){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(){return closePopover(onClose)}))}}(this),close=function(){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){return $log.error.apply($log,arguments),Raven.captureException(exception)}):($log.debug("Using the default logging exception handler."),function(){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 <span class="tag" style="border-left: 5px solid <%- tag.color %>"><%- tag.name %></span>\n<% }) %>'),kanban:_.template('<% _.each(tags, function(tag) { %>\n <a class="kanban-tag" href="" style="border-color: <%- tag.color %>" title="<%- tag.name %>" />\n<% }) %>'),taskboard:_.template('<% _.each(tags, function(tag) { %>\n <a class="taskboard-tag" href="" style="border-color: <%- tag.color %>" title="<%- tag.name %>" />\n<% }) %>')},link=function($scope,$el,$attrs){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){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(){return function(tag){return tag.color?tag.style="border-left: 5px solid "+tag.color:void 0}}(this)),html=templateTags(ctx),$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)})):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(),hideSaveButton()},removeInputLastCharacter=function(){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 tagsColors,_ref;
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",LbTagLineDirective]),TagLineDirective=function($rootScope,$repo,$rs,$confirm,$qqueue,$template){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-1!==$scope.project.my_permissions.indexOf($attrs.requiredPerm)},renderTags=function(tags,tagsColors){var ctx,html;return ctx={tags:_.map(tags,function(t){return{name:t,color:tagsColors[t]}}),isEditable:isEditable()},html=templateTags(ctx),$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("history:reload")},onError=function(){return $confirm.notify("error"),model.revert(),$model.$setViewValue(model)},$repo.save(model).then(onSuccess,onError)):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("history:reload")},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(),hideSaveButton()},removeInputLastCharacter=function(){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",function(project){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(project.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 tagsColors,_ref,_ref1;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",TagLineDirective])}.call(this),function(){var bindOnce,module,taiga,tgMarkitupDirective;taiga=this.taiga,bindOnce=this.taiga.bindOnce,module=angular.module("taigaCommon"),tgMarkitupDirective=function($rootscope,$rs,$tr,$selectedText,$template){var link,previewTemplate;return previewTemplate=$template.get("common/wysiwyg/wysiwyg-markitup-preview.html",!0),link=function($scope,$el,$attrs,$model){var closePreviewMode,element,markdownCaretPositon,markdownSettings,markdownTitle,preview,previewDomNode,removeEmptyLine,setCaretPosition;return element=angular.element($el),previewDomNode=$("<div/>",{"class":"preview"}),closePreviewMode=function(){return element.parents(".markdown").find(".preview").remove(),element.parents(".markItUp").show()},$scope.$on("markdown-editor:submit",function(){return closePreviewMode()}),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 markdown;return markdownDomNode.append(previewTemplate({data:data.data})),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})})},markdownCaretPositon=!1,setCaretPosition=function(elm,caretPos){var range;return elm.createTextRange?(range=elm.createTextRange(),range.move("character",caretPos),range.select()):elm.selectionStart?(elm.focus(),elm.setSelectionRange(caretPos,caretPos)):void 0},removeEmptyLine=function(textarea,line,currentCaretPosition){var lines,removedLineLength;return lines=textarea.value.split("\n"),removedLineLength=lines[line].length,lines[line]="",textarea.value=lines.join("\n"),currentCaretPosition-removedLineLength+1},markdownSettings={nameSpace:"markdown",onShiftEnter:{keepDefault:!1,openWith:"\n\n"},onEnter:{keepDefault:!1,replaceWith:function(){return function(data){var breakLineAtBeginning,cursorLine,emptyListItem,lastLine,lines,match,newLineContent;if(lines=data.textarea.value.split("\n"),cursorLine=data.textarea.value.slice(0,+(data.caretPosition-1)+1||9e9).split("\n").length,newLineContent=data.textarea.value.slice(data.caretPosition).split("\n")[0],lastLine=lines[cursorLine-1],match=lastLine.match(/^(\s*- ).*/))if(emptyListItem=lastLine.match(/^(\s*)\-\s$/))markdownCaretPositon=removeEmptyLine(data.textarea,lines.length-1,data.caretPosition);else if(breakLineAtBeginning=newLineContent.match(/^(\s*)\-\s/),!breakLineAtBeginning&&match)return"\n"+match[1];if(match=lastLine.match(/^(\s*\* ).*/))if(emptyListItem=lastLine.match(/^(\s*\* )$/))markdownCaretPositon=removeEmptyLine(data.textarea,lines.length-1,data.caretPosition);else if(breakLineAtBeginning=newLineContent.match(/^(\s*)\*\s/),!breakLineAtBeginning&&match)return"\n"+match[1];if(match=lastLine.match(/^(\s*)(\d+)\.\s/))if(emptyListItem=lastLine.match(/^(\s*)(\d+)\.\s$/))markdownCaretPositon=removeEmptyLine(data.textarea,lines.length-1,data.caretPosition);else if(breakLineAtBeginning=newLineContent.match(/^(\s*)(\d+)\.\s/),!breakLineAtBeginning)return"\n"+(match[1]+(parseInt(match[2],10)+1))+". ";return"\n"}}(this),afterInsert:function(data){var caretPosition,line,scrollRelation,totalLines;return markdownCaretPositon?(setCaretPosition(data.textarea,markdownCaretPositon),caretPosition=markdownCaretPositon,markdownCaretPositon=!1):caretPosition=data.caretPosition,totalLines=data.textarea.value.split("\n").length,line=data.textarea.value.slice(0,+(caretPosition-1)+1||9e9).split("\n").length,scrollRelation=line/totalLines,$el.scrollTop(scrollRelation*$el[0].scrollHeight-$el.height()/2)}},markupSet:[{name:$tr.t("markdown-editor.heading-1"),key:"1",placeHolder:$tr.t("markdown-editor.placeholder"),closeWith:function(markItUp){return markdownTitle(markItUp,"=")}},{name:$tr.t("markdown-editor.heading-2"),key:"2",placeHolder:$tr.t("markdown-editor.placeholder"),closeWith:function(markItUp){return markdownTitle(markItUp,"-")}},{name:$tr.t("markdown-editor.heading-3"),key:"3",openWith:"### ",placeHolder:$tr.t("markdown-editor.placeholder")},{separator:"---------------"},{name:$tr.t("markdown-editor.bold"),key:"B",openWith:"**",closeWith:"**"},{name:$tr.t("markdown-editor.italic"),key:"I",openWith:"_",closeWith:"_"},{name:$tr.t("markdown-editor.strike"),key:"S",openWith:"~~",closeWith:"~~"},{separator:"---------------"},{name:$tr.t("markdown-editor.bulleted-list"),openWith:"- "},{name:$tr.t("markdown-editor.numeric-list"),openWith:function(markItUp){return markItUp.line+". "}},{separator:"---------------"},{name:$tr.t("markdown-editor.picture"),key:"P",replaceWith:'![[![Alternative text]!]]([![Url:!:http://]!] "[![Title]!]")'},{name:$tr.t("markdown-editor.link"),key:"L",openWith:"[",closeWith:']([![Url:!:http://]!] "[![Title]!]")',placeHolder:$tr.t("markdown-editor.link-placeholder")},{separator:"---------------"},{name:$tr.t("markdown-editor.quotes"),openWith:"> "},{name:$tr.t("markdown-editor.code-block"),openWith:"```\n",closeWith:"\n```"},{separator:"---------------"},{name:$tr.t("markdown-editor.preview"),call:preview,className:"preview-icon"}],afterInsert:function(event){var target;return target=angular.element(event.textarea),$model.$setViewValue(target.val())}},markdownTitle=function(markItUp,char){var heading,i,n,_i,_ref;for(heading="",n=$.trim(markItUp.selection||markItUp.placeHolder).length,i=_i=0,_ref=n-1;_ref>=0?_ref>=_i:_i>=_ref;i=_ref>=0?++_i:--_i)heading+=char;return"\n"+heading+"\n"},element.markItUp(markdownSettings),element.on("keypress",function(){return $scope.$apply()}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,require:"ngModel"}},module.directive("tgMarkitup",["$rootScope","$tgResources","$tgI18n","$selectedText","$tgTemplate",tgMarkitupDirective])}.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($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){var $ctrl,initializeSelectedFilters,renderFilters,renderSelectedFilters,selectQFilter,selectedFilters,showCategories,showFilters,toggleFilterSelection;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 name,val,values,_i,_len;showCategories(),selectedFilters=[];for(name in filters)for(values=filters[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(){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(){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)},toggleFilterSelection=function(type,id){var currentFiltersType,filter,filters;return filters=$scope.filters[type],filter=_.find(filters,{id:taiga.toString(id)}),filter.selected=!filter.selected,filter.selected?(selectedFilters.push(filter),$scope.$apply(function(){return $ctrl.selectFilter(type,id),$ctrl.filterVisibleUserstories()})):(selectedFilters=_.reject(selectedFilters,filter),$scope.$apply(function(){return $ctrl.unselectFilter(type,id),$ctrl.filterVisibleUserstories()})),renderSelectedFilters(selectedFilters),currentFiltersType=$el.find("h2 a.subfilter span.title").prop("data-type"),type===currentFiltersType&&renderFilters(_.reject(filters,"selected")),$ctrl.loadUserstories()},selectQFilter=debounceLeading(100,function(value){return void 0!==value?(0===value.length?$ctrl.replaceFilter("q",null):$ctrl.replaceFilter("q",value),$ctrl.loadUserstories()):void 0}),$scope.$watch("filtersQ",selectQFilter),$scope.$on("filters:loaded",function(ctx,filters){return initializeSelectedFilters(filters)}),$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",["$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){var link;return link=function($scope,$el){var createSprint,hasErrors,remove,submit,submitButton;return hasErrors=!1,createSprint=!0,$scope.sprint={project:null,name:null,estimated_start:null,estimated_finish:null},submit=debounce(2e3,function(){return function(event){var broadcastEvent,form,newSprint,promise,target;return event.preventDefault(),target=angular.element(event.currentTarget),form=$el.find("form").checksley(),form.validate()?(hasErrors=!1,newSprint=angular.copy($scope.sprint),broadcastEvent=null,createSprint?(newSprint.estimated_start=moment(newSprint.estimated_start).format("YYYY-MM-DD"),newSprint.estimated_finish=moment(newSprint.estimated_finish).format("YYYY-MM-DD"),promise=$repo.create("milestones",newSprint),broadcastEvent="sprintform:create:success"):(newSprint.setAttr("estimated_start",moment(newSprint.estimated_start).format("YYYY-MM-DD")),newSprint.setAttr("estimated_finish",moment(newSprint.estimated_finish).format("YYYY-MM-DD")),promise=$repo.save(newSprint),broadcastEvent="sprintform:edit:success"),$loading.start(submitButton),promise.then(function(data){return $loading.finish(submitButton),createSprint&&($scope.sprintsCounter+=1),$rootscope.$broadcast(broadcastEvent,data),lightboxService.close($el)}),promise.then(null,function(data){return $loading.finish(submitButton),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="Delete sprint",message=$scope.sprint.name,$confirm.askOnDelete(title,message).then(function(){return function(finish){var onError,onSuccess;return onSuccess=function(){return finish(),$scope.milestonesCounter-=1,lightboxService.close($el),$rootscope.$broadcast("sprintform:remove:success")},onError=function(){return finish(!1),$confirm.notify("error")},$repo.remove($scope.sprint).then(onSuccess,onError)}}(this))},$scope.$on("sprintform:create",function(event,projectId){var estimatedFinish,estimatedStart,lastSprint,lastSprintNameDom;return createSprint=!0,$scope.sprint.project=projectId,$scope.sprint.name=null,$scope.sprint.slug=null,lastSprint=$scope.sprints[0],estimatedStart=moment(),$scope.sprint.estimated_start?estimatedStart=moment($scope.sprint.estimated_start):null!=lastSprint&&(estimatedStart=moment(lastSprint.estimated_finish)),$scope.sprint.estimated_start=estimatedStart.format("DD MMM YYYY"),estimatedFinish=moment().add(2,"weeks"),$scope.sprint.estimated_finish?estimatedFinish=moment($scope.sprint.estimated_finish):null!=lastSprint&&(estimatedFinish=moment(lastSprint.estimated_finish).add(2,"weeks")),$scope.sprint.estimated_finish=estimatedFinish.format("DD MMM YYYY"),lastSprintNameDom=$el.find(".last-sprint-name"),null!=(null!=lastSprint?lastSprint.name:void 0)&&lastSprintNameDom.html(" last sprint is <strong> "+lastSprint.name+" ;-) </strong>"),$el.find(".delete-sprint").addClass("hidden"),$el.find(".title").text("New sprint"),$el.find(".button-green").text("Create"),lightboxService.open($el),$el.find(".sprint-name").focus()}),$scope.$on("sprintform:edit",function(ctx,sprint){return createSprint=!1,$scope.$apply(function(){return $scope.sprint=sprint,$scope.sprint.estimated_start=moment($scope.sprint.estimated_start).format("DD MMM YYYY"),$scope.sprint.estimated_finish=moment($scope.sprint.estimated_finish).format("DD MMM YYYY")}),$el.find(".delete-sprint").removeClass("hidden"),$el.find(".title").text("Edit sprint"),$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(){return $el.find(".sprint-name").val().length>0||hasErrors?$el.find(".last-sprint-name").addClass("disappear"):$el.find(".last-sprint-name").removeClass("disappear")}),submitButton=$el.find(".submit-button"),$el.on("submit","form",submit),$el.on("click",".submit-button",submit),$el.on("click",".delete-sprint .icon-delete",function(event){return event.preventDefault(),remove()}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgLbCreateEditSprint",["$tgRepo","$tgConfirm","$tgResources","$rootScope","lightboxService","$tgLoading",CreateEditSprint])}.call(this),function(){var BacklogController,BacklogDirective,TgBacklogProgressBarDirective,UsPointsDirective,UsRolePointsSelectorDirective,bindMethods,bindOnce,groupBy,mixOf,module,scopeDefer,taiga,tgBacklogGraphDirective,timeout,toggleText,__hasProp={}.hasOwnProperty,__extends=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};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("taigaBacklog"),BacklogController=function(_super){function BacklogController(scope,rootscope,repo,confirm,rs,params,q,location,appTitle,navUrls,events,analytics,tgLoader){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.appTitle=appTitle,this.navUrls=navUrls,this.events=events,this.analytics=analytics,bindMethods(this),this.scope.sectionName="Backlog",this.showTags=!1,this.activeFilters=!1,this.excludeClosedSprints=!0,this.initializeEventHandlers(),promise=this.loadInitialData(),promise.then(function(_this){return function(){return _this.appTitle.set("Backlog - "+_this.scope.project.name),_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)),promise["finally"](tgLoader.pageLoaded)}return __extends(BacklogController,_super),BacklogController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","$appTitle","$tgNavUrls","$tgEvents","$tgAnalytics","tgLoader"],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.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(){return _this.loadSprints(),_this.loadProjectStats(),_this.loadUserstories()}}(this)),this.scope.$on("usform:edit:success",function(_this){return function(){return _this.loadUserstories()}}(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:toggle-closed-sprints-visualization",this.toggleClosedSprintsVisualization)},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(){return _this.loadUserstories(),_this.loadSprints()}}(this)),routingKey2="changes.project."+this.scope.projectId+".milestones",this.events.subscribe(this.scope,routingKey2,function(_this){return function(){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){return _this.scope.stats=stats,_this.scope.stats.completedPercentage=stats.total_points?Math.round(100*stats.closed_points/stats.total_points):0,stats}}(this))},BacklogController.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))},BacklogController.prototype.loadSprints=function(){var params;return params={},this.excludeClosedSprints&&(params.closed=!1),this.rs.sprints.list(this.scope.projectId,params).then(function(_this){return function(sprints){var sprint,_i,_len;for(_i=0,_len=sprints.length;_len>_i;_i++)sprint=sprints[_i],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=_.filter(sprints,function(sprint){return sprint.closed}),_this.excludeClosedSprints||(_this.scope.totalClosedMilestones=_this.scope.closedSprints.length),_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.resetFilters=function(){var selectedStatuses,selectedTags;return selectedTags=_.filter(this.scope.filters.tags,"selected"),selectedStatuses=_.filter(this.scope.filters.statuses,"selected"),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:taiga.toString(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.q.all([this.refreshTagsColors(),this.rs.userstories.listUnassigned(this.scope.projectId,this.scope.httpParams)]),promise.then(function(_this){return function(data){var userstories;return userstories=data[1],_this.scope.userstories=_.sortBy(userstories,"backlog_order"),_this.generateFilters(),_this.filterVisibleUserstories(),_this.rootscope.$broadcast("filters:loaded",_this.scope.filters),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 _this.scope.projectId=project.id,_this.scope.project=project,_this.scope.totalClosedMilestones=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.users,project.roles),_this.initializeSubscription()}}(this)),promise.then(function(_this){return function(){return _this.loadBacklog()}}(this))},BacklogController.prototype.toggleClosedSprintsVisualization=function(){return this.excludeClosedSprints=!this.excludeClosedSprints,this.loadSprints()},BacklogController.prototype.filterVisibleUserstories=function(){var selectedStatuses,selectedTags;return this.scope.visibleUserstories=[],selectedTags=_.filter(this.scope.filters.tags,"selected"),selectedTags=_.map(selectedTags,"name"),this.scope.visibleUserstories=0===selectedTags.length?_.clone(this.scope.userstories,!1):_.reject(this.scope.userstories,function(){return function(us){return 0===_.intersection(selectedTags,us.tags).length?!0:!1}}(this)),selectedStatuses=_.filter(this.scope.filters.statuses,"selected"),selectedStatuses=_.map(selectedStatuses,"id"),selectedStatuses.length>0&&(this.scope.visibleUserstories=_.reject(this.scope.visibleUserstories,function(){return function(us){var res;return res=_.find(selectedStatuses,function(x){return x===taiga.toString(us.status)}),!res}}(this))),this.rs.userstories.storeQueryParams(this.scope.projectId,{status:selectedStatuses,tags:selectedTags,project:this.scope.projectId,milestone:null})},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,_i,_len;for(null==field&&(field="backlog_order"),items=[],index=_i=0,_len=uses.length;_len>_i;index=++_i)item=uses[index],item[field]=index,item.isModified()&&items.push(item);return items},BacklogController.prototype.moveUs=function(ctx,usList,newUsIndex,newSprintId){var data,items,newSprint,oldSprintId,project,promise,promises,us,userstories,_i,_j,_k,_len,_len1,_len2;if(oldSprintId=usList[0].milestone,project=usList[0].project,newSprintId===oldSprintId)return items=null,userstories=null,userstories=null===newSprintId?this.scope.userstories:this.scope.sprintsById[newSprintId].user_stories,this.scope.$apply(function(){var args,key,r,us,_i,_len;for(key=_i=0,_len=usList.length;_len>_i;key=++_i)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 us,_i,_len,_results;for(_results=[],_i=0,_len=usList.length;_len>_i;_i++)us=usList[_i],_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 us,_i,_len,_results;for(_results=[],_i=0,_len=usList.length;_len>_i;_i++)us=usList[_i],_results.push(_this.rootscope.$broadcast("sprint:us:moved",us,oldSprintId,newSprintId));return _results}}(this))),promise;if(null===newSprintId){for(_i=0,_len=usList.length;_len>_i;_i++)us=usList[_i],us.milestone=null;return this.scope.$apply(function(_this){return function(){var args,key,r,sprint,_j,_len1,_results;for(args=[newUsIndex,0].concat(usList),Array.prototype.splice.apply(_this.scope.userstories,args),Array.prototype.splice.apply(_this.scope.visibleUserstories,args),_this.filterVisibleUserstories(),sprint=_this.scope.sprintsById[oldSprintId],_results=[],key=_j=0,_len1=usList.length;_len1>_j;key=++_j)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)})}}(this)),promise.then(null,function(){return console.log("FAIL")}),promise}if(newSprint=this.scope.sprintsById[newSprintId],null===oldSprintId){for(_j=0,_len1=usList.length;_len1>_j;_j++)us=usList[_j],us.milestone=newSprintId;
this.scope.$apply(function(_this){return function(){var args,key,r,_k,_len2,_results;for(args=[newUsIndex,0].concat(usList),Array.prototype.splice.apply(newSprint.user_stories,args),_results=[],key=_k=0,_len2=usList.length;_len2>_k;key=++_k)us=usList[key],r=_this.scope.visibleUserstories.indexOf(us),_this.scope.visibleUserstories.splice(r,1),r=_this.scope.userstories.indexOf(us),_results.push(_this.scope.userstories.splice(r,1));return _results}}(this))}else{for(_k=0,_len2=usList.length;_len2>_k;_k++)us=usList[_k],us.milestone=newSprintId;this.scope.$apply(function(_this){return function(){var args,oldSprint,r,_l,_len3,_results;for(args=[newUsIndex,0].concat(usList),Array.prototype.splice.apply(newSprint.user_stories,args),_results=[],_l=0,_len3=usList.length;_len3>_l;_l++)us=usList[_l],oldSprint=_this.scope.sprintsById[oldSprintId],r=oldSprint.user_stories.indexOf(us),_results.push(oldSprint.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(){return _this.rootscope.$broadcast("sprint:us:moved",us,oldSprintId,newSprintId)}),_this.rs.userstories.bulkUpdateBacklogOrder(project,data).then(function(){var _l,_len3,_results;for(_results=[],_l=0,_len3=usList.length;_len3>_l;_l++)us=usList[_l],_results.push(_this.rootscope.$broadcast("sprint:us:moved",us,oldSprintId,newSprintId));return _results})}}(this)),promise.then(null,function(){return console.log("FAIL")}),promise},BacklogController.prototype.getUrlFilters=function(){return _.pick(this.location.search(),"statuses","tags","q")},BacklogController.prototype.generateFilters=function(){var isSelected,name,plainStatuses,plainTags,searchdata,urlfilters,val,value,_i,_len,_ref;urlfilters=this.getUrlFilters(),urlfilters.q&&(this.scope.filtersQ=urlfilters.q),searchdata={};for(name in urlfilters)for(value=urlfilters[name],null==searchdata[name]&&(searchdata[name]={}),_ref=taiga.toString(value).split(","),_i=0,_len=_ref.length;_len>_i;_i++)val=_ref[_i],searchdata[name][val]=!0;return isSelected=function(type,id){return null!=searchdata[type]&&searchdata[type][id]?!0:!1},this.scope.filters={},plainTags=_.flatten(_.filter(_.map(this.scope.userstories,"tags"))),plainTags.sort(),this.scope.filters.tags=_.map(_.countBy(plainTags),function(_this){return function(v,k){var obj;return obj={id:k,type:"tags",name:k,color:_this.scope.project.tags_colors[k],count:v},isSelected("tags",obj.id)&&(obj.selected=!0),obj}}(this)),plainStatuses=_.map(this.scope.userstories,"status"),plainStatuses=_.filter(plainStatuses,function(){return function(status){return status?status:void 0}}(this)),this.scope.filters.statuses=_.map(_.countBy(plainStatuses),function(_this){return function(v,k){var obj;return obj={id:k,type:"statuses",name:_this.scope.usStatusById[k].name,color:_this.scope.usStatusById[k].color,count:v},isSelected("statuses",obj.id)&&(obj.selected=!0),obj}}(this)),this.scope.filters},BacklogController.prototype.editUserStory=function(us){return this.rootscope.$broadcast("usform:edit",us)},BacklogController.prototype.deleteUserStory=function(us){var message,title;return title="Delete User Story",message=us.subject,this.confirm.askOnDelete(title,message).then(function(_this){return function(finish){var promise;return _this.scope.userstories=_.without(_this.scope.userstories,us),_this.filterVisibleUserstories(),promise=_this.repo.remove(us),promise.then(function(){return finish(),_this.loadBacklog()}),promise.then(null,function(){return 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){var doomLineTemplate,link,linkDoomLine,linkFilters,linkToolbar,showHideFilter,showHideTags;return doomLineTemplate=_.template('<div class="doom-line"><span>Project Scope [Doomline]</span></div>'),linkDoomLine=function($scope,$el){var addDoomLineDom,getUsItems,reloadDoomLine,removeDoomlineDom;return reloadDoomLine=function(){var current_sum,element,elements,scope,stats,total_points,_i,_len,_results;if(null!=$scope.stats){for(removeDoomlineDom(),elements=getUsItems(),stats=$scope.stats,total_points=stats.total_points,current_sum=stats.assigned_points,_results=[],_i=0,_len=elements.length;_len>_i;_i++)if(element=elements[_i],scope=element.scope(),null!=scope.us){if(current_sum+=scope.us.total_points,current_sum>total_points){addDoomLineDom(element);break}_results.push(void 0)}return _results}},removeDoomlineDom=function(){return $el.find(".doom-line").remove()},addDoomLineDom=function(element){return null!=element?element.before(doomLineTemplate({})):void 0},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 moveToCurrentSprint;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){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,$ctrl.filterVisibleUserstories(),$repo.saveAll(selectedUss).then(function(){return $ctrl.loadSprints(),$ctrl.loadProjectStats()})},$el.on("change",".backlog-table-body .user-stories input:checkbox",function(event){var moveToCurrentSprintDom,selectedUsDom,target;return target=angular.element(event.currentTarget),moveToCurrentSprintDom=$el.find("#move-to-current-sprint"),selectedUsDom=$el.find(".backlog-table-body .user-stories input:checkbox:checked"),selectedUsDom.length>0&&$scope.sprints.length>0?moveToCurrentSprintDom.show():moveToCurrentSprintDom.hide(),target.closest(".us-item-row").toggleClass("ui-multisortable-multiple")}),$el.on("click","#move-to-current-sprint",function(){return function(){var ussDom,ussToMove;return ussDom=$el.find(".backlog-table-body .user-stories input:checkbox:checked"),ussToMove=_.map(ussDom,function(item){var itemScope;return itemScope=angular.element(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;return elm=angular.element("#show-tags"),$ctrl.showTags?(elm.addClass("active"),elm.find(".text").text("Hide Tags")):(elm.removeClass("active"),elm.find(".text").text("Show Tags"))},showHideFilter=function($scope,$el,$ctrl){var 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"),toggleText(target.find(".text"),["Remove Filters","Show Filters"]),sidebar.hasClass("active")||$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){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.statuses||filters.tags||filters.q)&&showHideFilter($scope,$el,$ctrl),$scope.$on("showTags",function(){return showHideTags($ctrl)}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgBacklog",["$tgRepo","$rootScope",BacklogDirective]),UsRolePointsSelectorDirective=function($rootscope,$template){var link,selectionTemplate;return selectionTemplate=$template.get("backlog/us-role-points-popover.html",!0),link=function($scope,$el){return bindOnce($scope,"project",function(project){var numberOfRoles,roles;return roles=_.filter(project.roles,"computable"),numberOfRoles=_.size(roles),numberOfRoles>1?$el.append(selectionTemplate({roles:roles})):($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+"/<span>Total</span>")}),$scope.$on("uspoints:clear-selection",function(){return $el.find(".popover").popover().close(),$el.find(".header-points").text("Points")}),$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",UsRolePointsSelectorDirective]),UsPointsDirective=function($repo,$tgTemplate){var link,pointsTemplate,rolesTemplate;return rolesTemplate=$tgTemplate.get("backlog/us-points-roles-popover.html",!0),pointsTemplate=$tgTemplate.get("backlog/us-points-popover.html",!0),link=function($scope,$el,$attrs){var $ctrl,calculateTotalPoints,computableRoles,numberOfRoles,renderPoints,renderPointsSelector,renderRolesSelector,roles,selectedRoleId,updatePointsRoles,updatingSelectedRoleId,us;return $ctrl=$el.controller(),us=$scope.$eval($attrs.tgBacklogUsPoints),updatingSelectedRoleId=null,selectedRoleId=null,numberOfRoles=_.size(us.points),1===numberOfRoles&&(selectedRoleId=_.keys(us.points)[0]),roles=[],updatePointsRoles=function(){return roles=_.map(computableRoles,function(role){var pointId,pointObj;return pointId=us.points[role.id],pointObj=$scope.pointsById[pointId],role=_.clone(role,!0),role.points=null!=pointObj.value?pointObj.value:"?",role})},computableRoles=_.filter($scope.project.roles,"computable"),updatePointsRoles(),0===roles.length&&($el.find(".icon-arrow-bottom").remove(),$el.find("a.us-points").addClass("not-clickable")),renderPointsSelector=function(us,roleId){var html,points;return points=_.map($scope.project.points,function(point){return point=_.clone(point,!0),point.selected=us.points[roleId]===point.id?!1:!0,point}),html=pointsTemplate({points:points}),$el.find(".popover").popover().close(),$el.find(".pop-points-open").remove(),$el.append(html),null==$el.find(".pop-role:visible").css("left")&&$el.find(".pop-points-open").css("left","110px"),$el.find(".pop-points-open").popover().open()},renderRolesSelector=function(){var html;return updatePointsRoles(),html=rolesTemplate({roles:roles}),$el.append(html),$el.find(".pop-role").popover().open(function(){return $(this).remove()})},renderPoints=function(us,roleId){var dom,pointId,pointObj,totalPoints;return dom=$el.find("a > span.points-value"),null===roleId||1===numberOfRoles?(totalPoints=null!=us.total_points?us.total_points:"?",dom.text(totalPoints),dom.parent().prop("title",totalPoints)):(pointId=us.points[roleId],pointObj=$scope.pointsById[pointId],dom.html(""+pointObj.name+" / <span>"+us.total_points+"</span>"),dom.parent().prop("title",""+pointObj.name+" / "+us.total_points))},calculateTotalPoints=function(){var values;return values=_.map(us.points,function(v){return $scope.pointsById[v].value}),values=_.filter(values,function(num){return null!=num}),0===values.length?"?":_.reduce(values,function(acc,num){return acc+num})},$scope.$watch($attrs.tgBacklogUsPoints,function(us){return us?renderPoints(us,selectedRoleId):void 0}),$scope.$on("uspoints:select",function(ctx,roleId){return us=$scope.$eval($attrs.tgBacklogUsPoints),renderPoints(us,roleId),selectedRoleId=roleId}),$scope.$on("uspoints:clear-selection",function(){return us=$scope.$eval($attrs.tgBacklogUsPoints),renderPoints(us,null),selectedRoleId=null}),roles.length>0&&($el.on("click","a.us-points span",function(event){return event.preventDefault(),event.stopPropagation(),us=$scope.$eval($attrs.tgBacklogUsPoints),updatingSelectedRoleId=selectedRoleId,null!=selectedRoleId?renderPointsSelector(us,selectedRoleId):renderRolesSelector(us)}),$el.on("click",".role",function(event){var popRolesDom,target;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"),renderPointsSelector(us,updatingSelectedRoleId)}),$el.on("click",".point",function(event){var points,target;return event.preventDefault(),event.stopPropagation(),target=angular.element(event.currentTarget),$el.find(".pop-points-open").hide(),$el.find(".pop-role").hide(),us=$scope.$eval($attrs.tgBacklogUsPoints),points=_.clone(us.points,!0),points[updatingSelectedRoleId]=target.data("point-id"),$scope.$apply(function(){return us.points=points,us.total_points=calculateTotalPoints(us),renderPoints(us,selectedRoleId),$repo.save(us).then(function(){return $repo.refresh(us).then(function(){return $ctrl.loadProjectStats()})})})})),bindOnce($scope,"project",function(project){return-1===project.my_permissions.indexOf("modify_us")?($el.unbind("click"),$el.find("a").addClass("not-clickable")):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgBacklogUsPoints",["$tgRepo","$tgTemplate",UsPointsDirective]),tgBacklogGraphDirective=function(){var link,redrawChart;return redrawChart=function(element,dataToDraw){var client_increment_line,colors,data,evolution_line,milestonesRange,optimal_line,options,team_increment_line,width,zero_line,_results;return width=element.width(),element.height(width/6),milestonesRange=function(){_results=[];for(var _i=0,_ref=dataToDraw.milestones.length-1;_ref>=0?_ref>=_i:_i>=_ref;_ref>=0?_i++:_i--)_results.push(_i);return _results}.apply(this),data=[],zero_line=_.map(dataToDraw.milestones,function(){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)"}}),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)"}}),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)"}}),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:"Sprints",axisLabelUseCanvas:!0,axisLabelFontSizePixels:14,axisLabelFontFamily:"Verdana, Arial, Helvetica, Tahoma, sans-serif",axisLabelPadding:15,tickFormatter:function(){return""}},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){return 1===flotItem.seriesIndex?"Optimal pending points for sprint "+xval+" should be "+yval:2===flotItem.seriesIndex?"Real pending points for sprint "+xval+" is "+yval:3===flotItem.seriesIndex?"Incremented points by team requirements for sprint "+xval+" is "+Math.abs(yval):"Incremented points by client requirements for sprint "+xval+" is "+Math.abs(yval)}}},element.empty(),element.plot(data,options).data("plot")},link=function($scope,$el){var element;return element=angular.element($el),$scope.$watch("stats",function(){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("tgGmBacklogGraph",tgBacklogGraphDirective),TgBacklogProgressBarDirective=function($template){var adjustPercentaje,link,render,template;return template=$template.get("backlog/progress-bar.html",!0),render=function(el,projectPointsPercentaje,closedPointsPercentaje){return el.html(template({projectPointsPercentaje:projectPointsPercentaje,closedPointsPercentaje:closedPointsPercentaje}))},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,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($el,projectPointsPercentaje,closedPointsPercentaje)):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgBacklogProgressBar",["$tgTemplate",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){var link;return link=function($scope,$el){return bindOnce($scope,"project",function(project){var filterError;if(project.my_permissions.indexOf("modify_us")>-1)return filterError=function(){return $tgConfirm.notify("error","You can't drop on backlog when filters are open")},$el.sortable({connectWith:".sprint",containment:".wrapper",dropOnEmpty:!0,placeholder:"row us-item-row us-item-drag sortable-placeholder",scroll:!0,tolerance:"pointer",revert:!1,cursorAt:{right:15},stop:function(){return $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=ui.item.index(),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)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,setTimeout(function(){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(){var link;return link=function($scope,$el){return bindOnce($scope,"project",function(project){return project.my_permissions.indexOf("modify_us")>-1?($el.sortable({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(){var link;return link=function($scope,$el){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",connectWith:".sprint,.backlog-table-body,.empty-backlog"}),$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(){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",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,refreshSprintTableHeight,slideOptions,sprintTableMinHeight,toggleSprint;return sprintTableMinHeight=50,slideOptions={duration:500,easing:"linear"},refreshSprintTableHeight=function(){return function(sprintTable){return sprintTable.find(".row").length?sprintTable.css("height","auto"):sprintTable.css("height",sprintTableMinHeight)}}(this),toggleSprint=function(){return function($el){var sprintArrow,sprintTable;return sprintTable=$el.find(".sprint-table"),sprintArrow=$el.find(".icon-arrow-up"),sprintArrow.toggleClass("active"),sprintTable.toggleClass("open"),refreshSprintTableHeight(sprintTable)}}(this),link=function($scope,$el,$attrs){return $scope.$watch($attrs.tgBacklogSprint,function(sprint){return sprint=$scope.$eval($attrs.tgBacklogSprint),$scope.$first?toggleSprint($el):sprint.closed?$el.addClass("sprint-closed"):$scope.$first||sprint.closed?void 0:(toggleSprint($el),$el.addClass("sprint-old-open"))}),$el.on("click",".sprint-name > .icon-arrow-up",function(){return toggleSprint($el),$el.find(".sprint-table").slideToggle(slideOptions)}),$el.on("click",".sprint-name > .icon-edit",function(){var sprint;return 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){var link,template;return template=$template.get("backlog/sprint-header.html",!0),link=function($scope,$el,$attrs,$model){var isEditable,isVisible,render;return 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 ctx,estimatedDateRange,finish,start,taskboardUrl;return taskboardUrl=$navUrls.resolve("project-taskboard",{project:$scope.project.slug,sprint:sprint.slug}),start=moment(sprint.estimated_start).format("DD MMM YYYY"),finish=moment(sprint.estimated_finish).format("DD MMM YYYY"),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()},$el.html(template(ctx))},$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",BacklogSprintHeaderDirective]),ToggleExcludeClosedSprintsVisualization=function($rootscope,$loading){var excludeClosedSprints,link;return excludeClosedSprints=!1,link=function($scope,$el){return $el.on("click","",function(){return $loading.start($el.siblings(".load")),$rootscope.$broadcast("backlog:toggle-closed-sprints-visualization")}),$scope.$on("$destroy",function(){return $el.off()}),$scope.$on("sprints:loaded",function(){return function(ctx,sprints){var closedSprints;return closedSprints=_.filter(sprints,function(sprint){return sprint.closed}),$loading.finish($el.siblings(".load")),$el.text(closedSprints.length>0?"Hide closed sprints":"Show closed sprints")}}(this))},{link:link}},module.directive("tgBacklogToggleClosedSprintsVisualization",["$rootScope","$tgLoading",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(){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:"Day",axisLabelUseCanvas:!0,axisLabelFontSizePixels:12,axisLabelFontFamily:"Verdana, Arial, Helvetica, Tahoma, sans-serif",axisLabelPadding:5},yaxis:{min:0},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("DD MMM"),roundedValue=Math.round(yval),1===flotItem.seriesIndex?"Optimal pending points for day "+formattedDate+" should be "+roundedValue:"Real pending points for day "+formattedDate+" is "+roundedValue}}},element.empty(),element.plot(data,options).data("plot")},link=function($scope,$el){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(){return null!=$scope.stats?redrawChart(element,$scope.stats.days):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgSprintGraph",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){var link;return link=function($scope,$el){var submit,submitButton;return $scope.isNew=!0,$scope.$on("taskform:new",function(ctx,sprintId,usId){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,$el.find(".button-green span").html("Create"),$el.find(".title").html("New task "),$el.find(".tag-input").val(""),lightboxService.open($el)}),$scope.$on("taskform:edit",function(ctx,task){return $scope.task=task,$scope.isNew=!1,$el.find(".button-green span").html("Save"),$el.find(".title").html("Edit task "),$el.find(".tag-input").val(""),lightboxService.open($el)}),submitButton=$el.find(".submit-button"),submit=debounce(2e3,function(){return function(event){var broadcastEvent,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"),$loading.start(submitButton),promise.then(function(data){return $loading.finish(submitButton),lightboxService.close($el),$rootscope.$broadcast(broadcastEvent,data)})):void 0}}(this)),$el.on("submit","form",submit),$el.on("click",".submit-button",submit),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},CreateBulkTasksDirective=function($repo,$rs,$rootscope,$loading,lightboxService){var link;return link=function($scope,$el){var submit,submitButton;return $scope.form={data:"",usId:null},submit=debounce(2e3,function(){return function(event){var data,form,projectId,promise,sprintId,usId;return event.preventDefault(),form=$el.find("form").checksley(),form.validate()?($loading.start(submitButton),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 $loading.finish(submitButton),$rootscope.$broadcast("taskform:bulk:success",result),lightboxService.close($el)}),promise.then(null,function(){return $loading.finish(submitButton),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),$el.on("click",".submit-button",submit),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module=angular.module("taigaTaskboard"),module.directive("tgLbCreateEditTask",["$tgRepo","$tgModel","$tgResources","$rootScope","$tgLoading","lightboxService",CreateEditTaskDirective]),module.directive("tgLbCreateBulkTasks",["$tgRepo","$tgResources","$rootScope","$tgLoading","lightboxService",CreateBulkTasksDirective])}.call(this),function(){var TaskboardController,TaskboardDirective,TaskboardSquishColumnDirective,TaskboardTableHeightFixerDirective,TaskboardTaskDirective,TaskboardUserDirective,bindMethods,bindOnce,groupBy,mixOf,module,scopeDefer,taiga,timeout,toggleText,__hasProp={}.hasOwnProperty,__extends=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};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(_super){function TaskboardController(scope,rootscope,repo,confirm,rs,params,q,appTitle,location,navUrls,events,analytics,tgLoader){var promise;this.scope=scope,this.rootscope=rootscope,this.repo=repo,this.confirm=confirm,this.rs=rs,this.params=params,this.q=q,this.appTitle=appTitle,this.location=location,this.navUrls=navUrls,this.events=events,this.analytics=analytics,bindMethods(this),this.scope.sectionName="Taskboard",this.initializeEventHandlers(),promise=this.loadInitialData(),promise.then(function(_this){return function(){return _this.appTitle.set("Taskboard - "+_this.scope.project.name)}}(this)),promise.then(null,this.onInitialDataError.bind(this)),promise["finally"](tgLoader.pageLoaded)}return __extends(TaskboardController,_super),TaskboardController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","$appTitle","$tgLocation","$tgNavUrls","$tgEvents","$tgAnalytics","tgLoader"],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(){return _this.loadTaskboard()}}(this)),routingKey1="changes.project."+this.scope.projectId+".userstories",this.events.subscribe(this.scope,routingKey1,function(_this){return function(){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 _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),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,_this.scope.stats.completedPercentage=stats.totalPointsSum?Math.round(100*stats.completedPointsSum/stats.totalPointsSum):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 status,task,us,_i,_j,_k,_len,_len1,_len2,_ref,_ref1,_ref2;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 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.loadUsersAndRoles()}}(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 index,item,items,_i,_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(){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){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){var link;return link=function($scope,$el){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(){return $el.find(".icon-edit").hasClass("noclick")?void 0:$scope.$apply(function(){return $rootscope.$broadcast("taskform:edit",$scope.task)})})},{link:link}},module.directive("tgTaskboardTask",["$rootScope",TaskboardTaskDirective]),TaskboardTableHeightFixerDirective=function(){var link,mainPadding,renderSize;return mainPadding=32,renderSize=function($el){var columnHeight,elementOffset,windowHeight;return elementOffset=$el.offset().top,windowHeight=angular.element(window).height(),columnHeight=windowHeight-elementOffset-mainPadding,$el.css("height",""+columnHeight+"px")},link=function($scope,$el){return timeout(500,function(){return renderSize($el)}),$scope.$on("resize",function(){return renderSize($el)})},{link:link}},module.directive("tgTaskboardTableHeightFixer",TaskboardTableHeightFixerDirective),TaskboardSquishColumnDirective=function(rs){var avatarWidth,link,maxColumnWidth;return avatarWidth=40,maxColumnWidth=300,link=function($scope,$el){var getCeilWidth,recalculateStatusColumnWidth,recalculateTaskboardWidth,refreshTaskboardTableWidth,setStatusColumnWidth;return $scope.$on("sprint:task:moved",function(){return function(){return recalculateTaskboardWidth()}}(this)),bindOnce($scope,"usTasks",function(){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(){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(){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(){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(){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(){return function(){_.forEach($scope.taskStatusList,function(status){return recalculateStatusColumnWidth(status.id)}),refreshTaskboardTableWidth()}}(this)},{link:link}},module.directive("tgTaskboardSquishColumn",["$tgResources",TaskboardSquishColumnDirective]),TaskboardUserDirective=function(){var clickable,link;return clickable=!1,link=function($scope,$el){var username_label;return username_label=$el.parent().find("a.task-assigned"),username_label.on("click",function(){var $ctrl;if(!$el.find("a").hasClass("noclick"))return $ctrl=$el.controller(),$ctrl.editTaskAssignedTo($scope.task)}),$scope.$watch("task.assigned_to",function(assigned_to){var user;return user=$scope.usersById[assigned_to],void 0===user?_.assign($scope,{name:"Unassigned",imgurl:"/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(){return function(){var $ctrl;if(!$el.find("a").hasClass("noclick"))return $ctrl=$el.controller(),$ctrl.editTaskAssignedTo($scope.task)}}(this))):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){var deleteElement,itemEl,newParentScope,oldParentScope,tdom;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,KanbanColumnHeightFixerDirective,KanbanController,KanbanDirective,KanbanSquishColumnDirective,KanbanUserDirective,KanbanUserstoryDirective,KanbanWipLimitDirective,bindMethods,bindOnce,defaultViewMode,defaultViewModes,groupBy,mixOf,module,scopeDefer,taiga,timeout,toggleText,__hasProp={}.hasOwnProperty,__extends=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};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",defaultViewModes={maximized:{cardClass:"kanban-task-maximized"},minimized:{cardClass:"kanban-task-minimized"}},KanbanController=function(_super){function KanbanController(scope,rootscope,repo,confirm,rs,params,q,location,appTitle,navUrls,events,analytics,tgLoader){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.appTitle=appTitle,this.navUrls=navUrls,this.events=events,this.analytics=analytics,bindMethods(this),this.scope.sectionName="Kanban",this.scope.statusViewModes={},this.initializeEventHandlers(),promise=this.loadInitialData(),promise.then(function(_this){return function(){return _this.appTitle.set("Kanban - "+_this.scope.project.name)}}(this)),promise.then(null,this.onInitialDataError.bind(this)),promise["finally"](tgLoader.pageLoaded)}return __extends(KanbanController,_super),KanbanController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","$appTitle","$tgNavUrls","$tgEvents","$tgAnalytics","tgLoader"],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;return params={status__is_archived:!1},this.rs.userstories.listAll(this.scope.projectId,params).then(function(_this){return function(userstories){var status,usByStatus,_i,_len,_ref;for(_this.scope.userstories=userstories,usByStatus=_.groupBy(userstories,"status"),_ref=_this.scope.usStatusList,_i=0,_len=_ref.length;_len>_i;_i++)status=_ref[_i],null==usByStatus[status.id]&&(usByStatus[status.id]=[]),status.is_archived&&null!=_this.scope.usByStatus&&(usByStatus[status.id]=_this.scope.usByStatus[status.id]),usByStatus[status.id]=_.sortBy(usByStatus[status.id],"kanban_order");return _this.scope.usByStatus=usByStatus,scopeDefer(_this.scope,function(){return _this.scope.$broadcast("userstories:loaded",userstories)}),userstories}}(this))},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 _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(){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.users,project.roles),_this.initializeSubscription(),_this.loadKanban().then(function(){return _this.scope.$broadcast("redraw:wip")})}}(this))},KanbanController.prototype.generateStatusViewModes=function(){var mode,status,storedStatusViewModes,_i,_len,_ref;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],this.scope.statusViewModes[status.id]=_.has(defaultViewModes,mode)?mode:defaultViewMode;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.getCardClass=function(statusId){var mode;return mode=this.scope.statusViewModes[statusId]||defaultViewMode,defaultViewModes[mode].cardClass||defaultViewModes[defaultViewMode].cardClass},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 index,item,items,_i,_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(){var link;return link=function($scope,$el){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]),KanbanColumnHeightFixerDirective=function(){var link,mainPadding,renderSize,scrollPadding;return mainPadding=32,scrollPadding=0,renderSize=function($el){var columnHeight,elementOffset,windowHeight;return elementOffset=$el.parent().parent().offset().top,windowHeight=angular.element(window).height(),columnHeight=windowHeight-elementOffset-mainPadding-scrollPadding,$el.css("height",""+columnHeight+"px")},link=function($scope,$el){return timeout(500,function(){return renderSize($el)}),$scope.$on("resize",function(){return renderSize($el)}),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgKanbanColumnHeightFixer",KanbanColumnHeightFixerDirective),KanbanArchivedStatusHeaderDirective=function($rootscope){var hideArchivedText,link,showArchivedText;return showArchivedText="Show archived",hideArchivedText="Hide archived",link=function($scope,$el,$attrs){var hidden,status;return status=$scope.$eval($attrs.tgKanbanArchivedStatusHeader),hidden=!0,$scope["class"]="icon icon-open-eye",$scope.title=showArchivedText,$el.on("click",function(){return hidden=!hidden,$scope.$apply(function(){return hidden?($scope["class"]="icon icon-open-eye",$scope.title=showArchivedText,$rootscope.$broadcast("kanban:hide-userstories-for-status",status.id)):($scope["class"]="icon 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",KanbanArchivedStatusHeaderDirective]),KanbanArchivedStatusIntroDirective=function(){var hiddenUserStoriexText,link,userStories;return hiddenUserStoriexText="The user stories in this status are hidden by default",userStories=[],link=function($scope,$el,$attrs){var status,updateIntroText;return status=$scope.$eval($attrs.tgKanbanArchivedStatusIntro),$el.text(hiddenUserStoriexText),updateIntroText=function(){return $el.text(userStories.length>0?"":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",KanbanArchivedStatusIntroDirective),KanbanUserstoryDirective=function($rootscope){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.find(".icon-edit").on("click",function(){return $el.find(".icon-edit").hasClass("noclick")?void 0:$scope.$apply(function(){return $rootscope.$broadcast("usform:edit",$model.$modelValue)})}),$scope.$on("$destroy",function(){return $el.off()})},{templateUrl:"kanban/kanban-task.html",link:link,require:"ngModel"}},module.directive("tgKanbanUserstory",["$rootScope",KanbanUserstoryDirective]),KanbanSquishColumnDirective=function(rs){var link;return link=function($scope,$el){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;return $el.disableSelection(),redrawWipLimit=function(){return $el.find(".kanban-wip-limit").remove(),timeout(200,function(){var element;return element=$el.find(".kanban-task")[$scope.$eval($attrs.tgKanbanWipLimit)],element?angular.element(element).before("<div class='kanban-wip-limit'></div>"):void 0})},$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){var clickable,link,template;return template=_.template('<figure class="avatar">\n <a href="#" title="Assign User Story" <% if (!clickable) {%>class="not-clickable"<% } %>>\n <img src="<%- imgurl %>" alt="<%- name %>" class="avatar">\n </a>\n</figure>'),clickable=!1,link=function($scope,$el,$attrs,$model){var render,wtid;return $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,username_label;return ctx=void 0===user?{name:"Unassigned",imgurl:"/images/unnamed.png",clickable:clickable}:{name:user.full_name_display,imgurl:user.photo,clickable:clickable},html=template(ctx),$el.html(html),username_label=$el.parent().find("a.task-assigned"),username_label.html(ctx.name),username_label.on("click",function(){var $ctrl,us;
if(!$el.find("a").hasClass("noclick"))return us=$model.$modelValue,$ctrl=$el.controller(),$ctrl.changeUsAssignedTo(us)})},bindOnce($scope,"project",function(project){return project.my_permissions.indexOf("modify_us")>-1?(clickable=!0,$el.on("click",function(){return function(){var $ctrl,us;if(!$el.find("a").hasClass("noclick"))return us=$model.$modelValue,$ctrl=$el.controller(),$ctrl.changeUsAssignedTo(us)}}(this))):void 0}),$scope.$on("$destroy",function(){return $el.off()})):$log.error("KanbanUserDirective: no attr is defined")},{link:link,require:"ngModel"}},module.directive("tgKanbanUserAvatar",["$log",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){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,bindOnce,groupBy,joinStr,mixOf,module,taiga,toString,__hasProp={}.hasOwnProperty,__extends=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};taiga=this.taiga,mixOf=this.taiga.mixOf,toString=this.taiga.toString,joinStr=this.taiga.joinStr,groupBy=this.taiga.groupBy,bindOnce=this.taiga.bindOnce,module=angular.module("taigaIssues"),IssueDetailController=function(_super){function IssueDetailController(scope,rootscope,repo,confirm,rs,params,q,location,log,appTitle,analytics,navUrls,tgLoader){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.appTitle=appTitle,this.analytics=analytics,this.navUrls=navUrls,this.scope.issueRef=this.params.issueref,this.scope.sectionName="Issue Details",this.initializeEventHandlers(),promise=this.loadInitialData(),promise.then(function(_this){return function(){return _this.appTitle.set(_this.scope.issue.subject+" - "+_this.scope.project.name),_this.initializeOnDeleteGoToUrl()}}(this)),promise.then(null,this.onInitialDataError.bind(this)),promise["finally"](tgLoader.pageLoaded)}return __extends(IssueDetailController,_super),IssueDetailController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","$log","$appTitle","$tgAnalytics","$tgNavUrls","tgLoader"],IssueDetailController.prototype.initializeEventHandlers=function(){return this.scope.$on("attachment:create",function(_this){return function(){return _this.rootscope.$broadcast("history:reload"),_this.analytics.trackEvent("attachment","create","create attachment on issue",1)}}(this)),this.scope.$on("attachment:edit",function(_this){return function(){return _this.rootscope.$broadcast("history:reload")}}(this)),this.scope.$on("attachment:delete",function(_this){return function(){return _this.rootscope.$broadcast("history:reload")}}(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("history:reload"),_this.loadIssue()}}(this))},IssueDetailController.prototype.initializeOnDeleteGoToUrl=function(){var ctx;return ctx={project:this.scope.project.slug},this.scope.onDeleteGoToUrl=this.scope.project.is_issues_activated?this.navUrls.resolve("project-issues",ctx):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}),_this.scope.membersById=groupBy(project.memberships,function(x){return x.user}),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;return _this.scope.issue=issue,_this.scope.issueId=issue.id,_this.scope.commentModel=issue,null!=_this.scope.issue.neighbors.previous.ref&&(ctx={project:_this.scope.project.slug,ref:_this.scope.issue.neighbors.previous.ref},_this.scope.previousUrl=_this.navUrls.resolve("project-issues-detail",ctx)),null!=_this.scope.issue.neighbors.next.ref?(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.users,project.roles),_this.loadIssue()}}(this))},IssueDetailController}(mixOf(taiga.Controller,taiga.PageMixin)),module.controller("IssueDetailController",IssueDetailController),IssueStatusDisplayDirective=function($template){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;return html=template({status:$scope.statusById[issue.status]}),$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",IssueStatusDisplayDirective]),IssueStatusButtonDirective=function($rootScope,$repo,$confirm,$loading,$qqueue,$template){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(){return function(issue){var html,status;return status=$scope.statusById[issue.status],html=template({status:status,statuses:$scope.statusList,editable:isEditable()}),$el.html(html)}}(this),save=$qqueue.bindAdd(function(){return function(value,issue){var onError,onSuccess;return onSuccess=function(){return $confirm.notify("success"),$rootScope.$broadcast("history:reload"),$loading.finish($el.find(".level-name"))},onError=function(){return $confirm.notify("error"),issue.revert(),$model.$setViewValue(issue),$loading.finish($el.find(".level-name"))},$loading.start($el.find(".level-name")),$repo.save(value).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 issue,target;return event.preventDefault(),event.stopPropagation(),isEditable()?(target=angular.element(event.currentTarget),$.fn.popover().closeAll(),issue=$model.$modelValue.clone(),issue.status=target.data("status-id"),$model.$setViewValue(issue),save($model.$modelValue,issue)):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",IssueStatusButtonDirective]),IssueTypeButtonDirective=function($rootScope,$repo,$confirm,$loading,$qqueue,$template){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(){return function(issue){var html,type;return type=$scope.typeById[issue.type],html=template({type:type,typees:$scope.typeList,editable:isEditable()}),$el.html(html)}}(this),save=$qqueue.bindAdd(function(){return function(type){var issue,onError,onSuccess;return $.fn.popover().closeAll(),issue=$model.$modelValue.clone(),issue.type=type,$model.$setViewValue(issue),onSuccess=function(){return $confirm.notify("success"),$rootScope.$broadcast("history:reload"),$loading.finish($el.find(".level-name"))},onError=function(){return $confirm.notify("error"),issue.revert(),$model.$setViewValue(issue),$loading.finish($el.find(".level-name"))},$loading.start($el.find(".level-name")),$repo.save($model.$modelValue).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",IssueTypeButtonDirective]),IssueSeverityButtonDirective=function($rootScope,$repo,$confirm,$loading,$qqueue,$template){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(){return function(issue){var html,severity;return severity=$scope.severityById[issue.severity],html=template({severity:severity,severityes:$scope.severityList,editable:isEditable()}),$el.html(html)}}(this),save=$qqueue.bindAdd(function(){return function(severity){var issue,onError,onSuccess;return $.fn.popover().closeAll(),issue=$model.$modelValue.clone(),issue.severity=severity,$model.$setViewValue(issue),onSuccess=function(){return $confirm.notify("success"),$rootScope.$broadcast("history:reload"),$loading.finish($el.find(".level-name"))},onError=function(){return $confirm.notify("error"),issue.revert(),$model.$setViewValue(issue),$loading.finish($el.find(".level-name"))},$loading.start($el.find(".level-name")),$repo.save($model.$modelValue).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",IssueSeverityButtonDirective]),IssuePriorityButtonDirective=function($rootScope,$repo,$confirm,$loading,$qqueue,$template){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(){return function(issue){var html,priority;return priority=$scope.priorityById[issue.priority],html=template({priority:priority,priorityes:$scope.priorityList,editable:isEditable()}),$el.html(html)}}(this),save=$qqueue.bindAdd(function(){return function(priority){var issue,onError,onSuccess;return $.fn.popover().closeAll(),issue=$model.$modelValue.clone(),issue.priority=priority,$model.$setViewValue(issue),onSuccess=function(){return $confirm.notify("success"),$rootScope.$broadcast("history:reload"),$loading.finish($el.find(".level-name"))},onError=function(){return $confirm.notify("error"),issue.revert(),$model.$setViewValue(issue),$loading.finish($el.find(".level-name"))},$loading.start($el.find(".level-name")),$repo.save($model.$modelValue).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",IssuePriorityButtonDirective]),PromoteIssueToUsButtonDirective=function($rootScope,$repo,$confirm,$qqueue){var link;return link=function($scope,$el,$attrs,$model){var save;return save=$qqueue.bindAdd(function(){return function(issue,finish){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 finish(),$confirm.notify("success"),$rootScope.$broadcast("promote-issue-to-us:success")},onError=function(){return finish(!1),$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="Promote this issue to a new user story",message="Are you sure you want to create a new US from this Issue?",subtitle=issue.subject,$confirm.ask(title,subtitle,message).then(function(){return function(finish){return save(issue,finish)}}(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",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){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(){return function(event){var promise;return event.preventDefault(),form.validate()?($loading.start(submitButton),promise=$repo.create("issues",$scope.issue),promise.then(function(data){return $loading.finish(submitButton),$rootscope.$broadcast("issueform:new:success",data),lightboxService.close($el),$confirm.notify("success")}),promise.then(null,function(){return $loading.finish(submitButton),$confirm.notify("error")})):void 0}}(this)),submitButton=$el.find(".submit-button"),$el.on("submit","form",submit),$el.on("click",".submit-button",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){var submit,submitButton;return $scope.$on("issueform:bulk",function(ctx,projectId){return lightboxService.open($el),$scope["new"]={projectId:projectId,bulk:""}}),submit=debounce(2e3,function(){return function(event){var data,form,projectId,promise;return event.preventDefault(),form=$el.find("form").checksley(),form.validate()?($loading.start(submitButton),data=$scope["new"].bulk,projectId=$scope["new"].projectId,promise=$rs.issues.bulkCreate(projectId,data),promise.then(function(result){return $loading.finish(submitButton),$rootscope.$broadcast("issueform:new:success",result),lightboxService.close($el),$confirm.notify("success")}),promise.then(null,function(){return $loading.finish(submitButton),$confirm.notify("error")})):void 0}}(this)),submitButton=$el.find(".submit-button"),$el.on("submit","form",submit),$el.on("click",".submit-button",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)}},__hasProp={}.hasOwnProperty,__extends=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};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(_super){function IssuesController(scope,rootscope,repo,confirm,rs,urls,params,q,location,appTitle,navUrls,events,analytics,tgLoader){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.appTitle=appTitle,this.navUrls=navUrls,this.events=events,this.analytics=analytics,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(){return _this.appTitle.set("Issues - "+_this.scope.project.name)}}(this)),promise.then(null,this.onInitialDataError.bind(this)),promise["finally"](tgLoader.pageLoaded),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.loadFilters()}}(this)))}return __extends(IssuesController,_super),IssuesController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$tgUrls","$routeParams","$q","$tgLocation","$appTitle","$tgNavUrls","$tgEvents","$tgAnalytics","tgLoader"],IssuesController.prototype.initializeSubscription=function(){var routingKey;return routingKey="changes.project."+this.scope.projectId+".issues",this.events.subscribe(this.scope,routingKey,function(_this){return function(){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 _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}),_this.scope.membersById=groupBy(project.memberships,function(x){return x.user}),project}}(this))},IssuesController.prototype.getUrlFilters=function(){var filters;return filters=_.pick(this.location.search(),"page","tags","statuses","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(){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,key,name,obj,searchdata,val,value,_i,_len,_ref,_ref1,_results;searchdata={},_ref=_.omit(urlfilters,"page","orderBy");for(name in _ref)for(value=_ref[name],null==searchdata[name]&&(searchdata[name]={}),_ref1=(""+value).split(","),_i=0,_len=_ref1.length;_len>_i;_i++)val=_ref1[_i],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 _j,_len1,_results1;for(_results1=[],_j=0,_len1=value.length;_len1>_j;_j++)obj=value[_j],_results1.push(obj.selected=isSelected(obj.type,obj.id)?!0:void 0);return _results1}());return _results},IssuesController.prototype.loadFilters=function(){var 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)),promise=promise.then(function(_this){return function(){return _this.rs.issues.filtersData(_this.scope.projectId)}}(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{id:t[0],count:t[1],type:type,name:t[0]?_this.scope.usersById[t[0]].full_name_display:unknownOption}}),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{id:t[0],name:byIdObject[t[0]].name,color:byIdObject[t[0]].color,count:t[1],type:type}})},tagsFilterFormat=function(tags){return _.map(tags,function(t){return{id:t[0],name:t[0],color:_this.scope.project.tags_colors[t[0]],count:t[1],type:"tags"}})},_this.scope.filters.statuses=choicesFiltersFormat(data.statuses,"statuses",_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.created_by,"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,values,_ref;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":"statuses"===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))},IssuesController.prototype.loadInitialData=function(){var promise;return promise=this.loadProject(),promise.then(function(_this){return function(project){return _this.fillUsersAndRoles(project.users,project.roles),_this.initializeSubscription(),_this.q.all([_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){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?parseInt(numPages,10)+1:parseInt(numPages,10)},renderPagination=function(){var cpage,i,numPages,options,pages,_i;if(numPages=getNumPages(),1>=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=_i=1;numPages>=1?numPages>=_i:_i>=numPages;i=numPages>=1?++_i:--_i)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||pages.push(i===cpage?{classes:"active",num:i,type:"page-active"}:{classes:"page",num:i,type:"page"});return $pagEl.html(template(options))},$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-caret-up":"icon-caret-down",colHeadElement=$el.find(".row.title > div[data-fieldname='"+trim(currentOrder,"-")+"']"),colHeadElement.html(""+colHeadElement.html()+"<span class='icon "+icon+"'></span>")),$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-caret-up":"icon-caret-down",target.html(""+target.html()+"<span class='icon "+icon+"'></span>")
})})})},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",IssuesDirective]),IssuesFiltersDirective=function($log,$location,$rs,$confirm,$loading,$template){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){var $ctrl,initializeSelectedFilters,renderFilters,renderSelectedFilters,selectQFilter,selectedFilters,showCategories,showFilters,toggleFilterSelection;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 name,val,values,_i,_len;selectedFilters=[];for(name in filters)for(values=filters[name],_i=0,_len=values.length;_len>_i;_i++)val=values[_i],val.selected&&selectedFilters.push(val);return renderSelectedFilters(selectedFilters)},renderSelectedFilters=function(selectedFilters){var html;return _.filter(selectedFilters,function(){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),selectedFilters.length>0?$el.find(".save-filters").show():$el.find(".save-filters").hide()},renderFilters=function(filters){var html;return _.filter(filters,function(){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)},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),$scope.$apply(function(){return $ctrl.selectFilter(type,id),$ctrl.selectFilter("page",1),$ctrl.storeFilters(),$ctrl.loadIssues()})):(selectedFilters=_.reject(selectedFilters,filter),$scope.$apply(function(){return $ctrl.unselectFilter(type,id),$ctrl.selectFilter("page",1),$ctrl.storeFilters(),$ctrl.loadIssues()})),renderSelectedFilters(selectedFilters),currentFiltersType=$el.find("h2 a.subfilter span.title").prop("data-type"),type===currentFiltersType?renderFilters(_.reject(filters,"selected")):void 0)},$scope.$on("filters:loaded",function(ctx,filters){return initializeSelectedFilters(filters)}),selectQFilter=debounceLeading(100,function(value){return void 0!==value?(0===value.length?($ctrl.replaceFilter("q",null),$ctrl.storeFilters()):($ctrl.replaceFilter("q",value),$ctrl.storeFilters()),$ctrl.loadIssues()):void 0}),$scope.$watch("filtersQ",selectQFilter),$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="Delete custom filter",message="the custom filter '"+customFilterName+"'",$confirm.askOnDelete(title,message).then(function(finish){var promise;return promise=$ctrl.deleteMyFilter(customFilterName),promise.then(function(){return promise=$ctrl.loadMyFilters(),promise.then(function(filters){return finish(),$scope.filters.myFilters=filters,renderFilters($scope.filters.myFilters)}),promise.then(null,function(){return finish()})}),promise.then(null,function(){return 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()}),$el.on("keyup",".new .my-filter-name",function(event){var newFilter,promise,target;return event.preventDefault(),13===event.keyCode?(target=angular.element(event.currentTarget),newFilter=target.val(),$loading.start($el.find(".new")),promise=$ctrl.saveCurrentFiltersTo(newFilter),promise.then(function(){var loadPromise;return loadPromise=$ctrl.loadMyFilters(),loadPromise.then(function(filters){var currentfilterstype;return $loading.finish($el.find(".new")),$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 $loading.finish($el.find(".new")),$confirm.notify("error","Error loading custom filters")})}),promise.then(null,function(){return $loading.finish($el.find(".new")),$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",["$log","$tgLocation","$tgResources","$tgConfirm","$tgLoading","$tgTemplate",IssuesFiltersDirective]),IssueStatusInlineEditionDirective=function($repo,$template){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 target;return event.preventDefault(),event.stopPropagation(),target=angular.element(event.currentTarget),issue.status=target.data("status-id"),$el.find(".pop-status").popover().close(),updateIssueStatus($el,issue,$scope.issueStatusById),$scope.$apply(function(){return $repo.save(issue).then})}),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(){return function(val){return updateIssueStatus($el,val,$scope.issueStatusById)}}(this)),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgIssueStatusInlineEdition",["$tgRepo","$tgTemplate",IssueStatusInlineEditionDirective]),IssueAssignedToInlineEditionDirective=function($repo,$rootscope){var link,template;return template=_.template('<img src="<%- imgurl %>" alt="<%- name %>"/>\n<figcaption><%- name %></figcaption>'),link=function($scope,$el,$attrs){var $ctrl,issue,updateIssue;return updateIssue=function(issue){var ctx,member;return ctx={name:"Unassigned",imgurl:"/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(){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(){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(){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,bindOnce,groupBy,mixOf,module,taiga,__hasProp={}.hasOwnProperty,__extends=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};taiga=this.taiga,mixOf=this.taiga.mixOf,groupBy=this.taiga.groupBy,bindOnce=this.taiga.bindOnce,module=angular.module("taigaUserStories"),UserStoryDetailController=function(_super){function UserStoryDetailController(scope,rootscope,repo,confirm,rs,params,q,location,log,appTitle,navUrls,analytics,tgLoader){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.appTitle=appTitle,this.navUrls=navUrls,this.analytics=analytics,this.scope.usRef=this.params.usref,this.scope.sectionName="User Story Details",this.initializeEventHandlers(),promise=this.loadInitialData(),promise.then(function(_this){return function(){return _this.appTitle.set(_this.scope.us.subject+" - "+_this.scope.project.name),_this.initializeOnDeleteGoToUrl()}}(this)),promise.then(null,this.onInitialDataError.bind(this)),promise["finally"](tgLoader.pageLoaded)}return __extends(UserStoryDetailController,_super),UserStoryDetailController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","$log","$appTitle","$tgNavUrls","$tgAnalytics","tgLoader"],UserStoryDetailController.prototype.initializeEventHandlers=function(){return this.scope.$on("related-tasks:update",function(_this){return function(){return _this.loadUs(),_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.rootscope.$broadcast("history:reload")}}(this)),this.scope.$on("attachment:edit",function(_this){return function(){return _this.rootscope.$broadcast("history:reload")}}(this)),this.scope.$on("attachment:delete",function(_this){return function(){return _this.rootscope.$broadcast("history:reload")}}(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.membersById=groupBy(project.memberships,function(x){return x.user}),_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(){return this.rs.userstories.getByRef(this.scope.projectId,this.params.usref).then(function(_this){return function(us){var ctx;return _this.scope.us=us,_this.scope.usId=us.id,_this.scope.commentModel=us,null!=_this.scope.us.neighbors.previous.ref&&(ctx={project:_this.scope.project.slug,ref:_this.scope.us.neighbors.previous.ref},_this.scope.previousUrl=_this.navUrls.resolve("project-userstories-detail",ctx)),null!=_this.scope.us.neighbors.next.ref&&(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.users,project.roles),_this.loadUs().then(function(){return _this.q.all([_this.loadSprint(),_this.loadTasks()])})}}(this))},UserStoryDetailController}(mixOf(taiga.Controller,taiga.PageMixin)),module.controller("UserStoryDetailController",UserStoryDetailController),UsStatusDisplayDirective=function($template){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;return html=template({is_closed:us.is_closed,status:$scope.statusById[us.status]}),$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",UsStatusDisplayDirective]),UsTasksProgressDisplayDirective=function($template){var link,template;return template=$template.get("us/us-task-progress.html",!0),link=function($scope,$el,$attrs){var render;return render=function(tasks){var html,progress,totalClosedTasks,totalTasks;return totalTasks=tasks.length,totalClosedTasks=_.filter(tasks,function(){return function(task){return $scope.taskStatusById[task.status].is_closed}}(this)).length,progress=totalTasks>0?100*totalClosedTasks/totalTasks:0,html=template({totalTasks:totalTasks,totalClosedTasks:totalClosedTasks,progress:progress}),$el.html(html)},$scope.$watch($attrs.ngModel,function(tasks){return null!=tasks?render(tasks):void 0}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,restrict:"EA",require:"ngModel"}},module.directive("tgUsTasksProgressDisplay",["$tgTemplate",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(){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(){return function(status){var onError,onSuccess,us;return us=$model.$modelValue.clone(),us.status=status,$.fn.popover().closeAll(),$model.$setViewValue(us),onSuccess=function(){return $confirm.notify("success"),$rootScope.$broadcast("history:reload"),$loading.finish($el.find(".level-name"))},onError=function(){return $confirm.notify("error"),us.revert(),$model.$setViewValue(us),$loading.finish($el.find(".level-name"))},$loading.start($el.find(".level-name")),$repo.save($model.$modelValue).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){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),$el.html(html)):void $el.html("")},save=$qqueue.bindAdd(function(){return function(team_requirement){var promise,us;return us=$model.$modelValue.clone(),us.team_requirement=team_requirement,$model.$setViewValue(us),$loading.start($el.find("label")),promise=$tgrepo.save($model.$modelValue),promise.then(function(){return $loading.finish($el.find("label")),$rootscope.$broadcast("history:reload")}),promise.then(null,function(){return $loading.finish($el.find("label")),$confirm.notify("error"),us.revert(),$model.$setViewValue(us)})}}(this)),$el.on("click",".team-requirement",function(){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",UsTeamRequirementButtonDirective]),UsClientRequirementButtonDirective=function($rootscope,$tgrepo,$confirm,$loading,$qqueue,$template){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=template(ctx),$el.html(html)):void $el.html("")},save=$qqueue.bindAdd(function(){return function(client_requirement){var promise,us;return us=$model.$modelValue.clone(),us.client_requirement=client_requirement,$model.$setViewValue(us),$loading.start($el.find("label")),promise=$tgrepo.save($model.$modelValue),promise.then(function(){return $loading.finish($el.find("label")),$rootscope.$broadcast("history:reload")}),promise.then(null,function(){return $loading.finish($el.find("label")),$confirm.notify("error"),us.revert(),$model.$setViewValue(us)})}}(this)),$el.on("click",".client-requirement",function(){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",UsClientRequirementButtonDirective])}.call(this),function(){var TaskDetailController,TaskIsIocaineButtonDirective,TaskStatusButtonDirective,TaskStatusDisplayDirective,groupBy,mixOf,module,taiga,__hasProp={}.hasOwnProperty,__extends=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};taiga=this.taiga,mixOf=this.taiga.mixOf,groupBy=this.taiga.groupBy,module=angular.module("taigaTasks"),TaskDetailController=function(_super){function TaskDetailController(scope,rootscope,repo,confirm,rs,params,q,location,log,appTitle,navUrls,analytics,tgLoader){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.appTitle=appTitle,this.navUrls=navUrls,this.analytics=analytics,this.scope.taskRef=this.params.taskref,this.scope.sectionName="Task Details",this.initializeEventHandlers(),promise=this.loadInitialData(),promise.then(function(_this){return function(){return _this.appTitle.set(_this.scope.task.subject+" - "+_this.scope.project.name),_this.initializeOnDeleteGoToUrl()}}(this)),promise.then(null,this.onInitialDataError.bind(this)),promise["finally"](tgLoader.pageLoaded)}return __extends(TaskDetailController,_super),TaskDetailController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","$log","$appTitle","$tgNavUrls","$tgAnalytics","tgLoader"],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.rootscope.$broadcast("history:reload")}}(this)),this.scope.$on("attachment:edit",function(_this){return function(){return _this.rootscope.$broadcast("history:reload")}}(this)),this.scope.$on("attachment:delete",function(_this){return function(){return _this.rootscope.$broadcast("history:reload")}}(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}),_this.scope.membersById=groupBy(project.memberships,function(x){return x.user}),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;return _this.scope.task=task,_this.scope.taskId=task.id,_this.scope.commentModel=task,null!=_this.scope.task.neighbors.previous.ref&&(ctx={project:_this.scope.project.slug,ref:_this.scope.task.neighbors.previous.ref},_this.scope.previousUrl=_this.navUrls.resolve("project-tasks-detail",ctx)),null!=_this.scope.task.neighbors.next.ref&&(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.users,project.roles),_this.loadTask().then(function(){return _this.q.all([_this.loadSprint(),_this.loadUserStory()])})}}(this))},TaskDetailController}(mixOf(taiga.Controller,taiga.PageMixin)),module.controller("TaskDetailController",TaskDetailController),TaskStatusDisplayDirective=function($template){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;return html=template({status:$scope.statusById[task.status]}),$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",TaskStatusDisplayDirective]),TaskStatusButtonDirective=function($rootScope,$repo,$confirm,$loading,$qqueue){var link,template;return template=_.template('<div class="status-data <% if(editable){ %>clickable<% }%>">\n <span class="level" style="background-color:<%- status.color %>"></span>\n <span class="status-status"><%- status.name %></span>\n <% if(editable){ %><span class="icon icon-arrow-bottom"></span><% }%>\n <span class="level-name">status</span>\n\n <ul class="popover pop-status">\n <% _.each(statuses, function(st) { %>\n <li><a href="" class="status" title="<%- st.name %>"\n data-status-id="<%- st.id %>"><%- st.name %></a></li>\n <% }); %>\n </ul>\n</div>'),link=function($scope,$el,$attrs,$model){var isEditable,render,save;return isEditable=function(){return-1!==$scope.project.my_permissions.indexOf("modify_task")},render=function(){return function(task){var html,status;return status=$scope.statusById[task.status],html=template({status:status,statuses:$scope.statusList,editable:isEditable()}),$el.html(html)}}(this),save=$qqueue.bindAdd(function(){return function(status){var onError,onSuccess,task;return task=$model.$modelValue.clone(),task.status=status,$model.$setViewValue(task),onSuccess=function(){return $confirm.notify("success"),$rootScope.$broadcast("history:reload"),$loading.finish($el.find(".level-name"))},onError=function(){return $confirm.notify("error"),task.revert(),$model.$setViewValue(task),$loading.finish($el.find(".level-name"))},$loading.start($el.find(".level-name")),$repo.save($model.$modelValue).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",TaskStatusButtonDirective]),TaskIsIocaineButtonDirective=function($rootscope,$tgrepo,$confirm,$loading,$qqueue){var link,template;return template=_.template('<fieldset title="Feeling a bit overwhelmed by a task? Make sure others know about it by clicking on Iocaine when editing a task. It\'s possible to become immune to this (fictional) deadly poison by consuming small amounts over time just as it\'s possible to get better at what you do by occasionally taking on extra challenges!">\n <label for="is-iocaine"\n class="button button-gray is-iocaine <% if(isEditable){ %>editable<% }; %> <% if(isIocaine){ %>active<% }; %>">\n Iocaine\n </label>\n <input type="checkbox" id="is-iocaine" name="is-iocaine"/>\n</fieldset>'),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=template(ctx),$el.html(html)):void $el.html("")},save=$qqueue.bindAdd(function(){return function(is_iocaine){var promise,task;return task=$model.$modelValue.clone(),task.is_iocaine=is_iocaine,$model.$setViewValue(task),$loading.start($el.find("label")),promise=$tgrepo.save(task),promise.then(function(){return $confirm.notify("success"),$rootscope.$broadcast("history:reload")}),promise.then(null,function(){return task.revert(),$model.$setViewValue(task),$confirm.notify("error")}),promise["finally"](function(){return $loading.finish($el.find("label"))})}}(this)),$el.on("click",".is-iocaine",function(){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",TaskIsIocaineButtonDirective])}.call(this),function(){var LeaveProjectDirective,TeamController,TeamFiltersDirective,TeamMemberCurrentUserDirective,TeamMemberStatsDirective,TeamMembersDirective,mixOf,module,taiga,__hasProp={}.hasOwnProperty,__extends=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
};taiga=this.taiga,mixOf=this.taiga.mixOf,module=angular.module("taigaTeam"),TeamController=function(_super){function TeamController(scope,rootscope,repo,rs,params,q,location,navUrls,appTitle,auth,tgLoader){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.appTitle=appTitle,this.auth=auth,this.scope.sectionName="Team",promise=this.loadInitialData(),promise.then(function(_this){return function(){return _this.appTitle.set("Team - "+_this.scope.project.name)}}(this)),promise.then(null,this.onInitialDataError.bind(this)),promise["finally"](tgLoader.pageLoaded)}return __extends(TeamController,_super),TeamController.$inject=["$scope","$rootScope","$tgRepo","$tgResources","$routeParams","$q","$location","$tgNavUrls","$appTitle","$tgAuth","tgLoader"],TeamController.prototype.setRole=function(role){return this.scope.filtersRole=role?role:""},TeamController.prototype.loadMembers=function(){return this.rs.memberships.list(this.scope.projectId,{},!1).then(function(_this){return function(data){var currentUser,membership,_i,_len,_ref;for(currentUser=_this.auth.getUser(),null==currentUser.photo&&(currentUser.photo="/images/unnamed.png"),_this.scope.currentUser=_.find(data,function(membership){return membership.user===currentUser.id}),_this.scope.totals={},_.forEach(data,function(membership){return _this.scope.totals[membership.user]=0}),_this.scope.memberships=_.filter(data,function(membership){return membership.user&&membership.user!==currentUser.id&&membership.is_user_active?membership:void 0}),_ref=_this.scope.memberships,_i=0,_len=_ref.length;_len>_i;_i++)membership=_ref[_i],null==membership.photo&&(membership.photo="/images/unnamed.png");return data}}(this))},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){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.users,project.roles),_this.loadMembers().then(function(){return _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){var link;return link=function($scope,$el,$attrs){return $scope.leave=function(){return $confirm.ask("Leave this project","Are you sure you want to leave the project?").then(function(){return function(finish){var promise;return promise=$rs.projects.leave($attrs.projectid),promise.then(function(){return finish(),$confirm.notify("success"),$location.path($navurls.resolve("home"))}),promise.then(null,function(response){return 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",LeaveProjectDirective])}.call(this),function(){var EditableWikiContentDirective,WikiDetailController,WikiSummaryDirective,bindOnce,debounce,groupBy,mixOf,module,taiga,unslugify,__hasProp={}.hasOwnProperty,__extends=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};taiga=this.taiga,mixOf=this.taiga.mixOf,groupBy=this.taiga.groupBy,bindOnce=this.taiga.bindOnce,unslugify=this.taiga.unslugify,debounce=this.taiga.debounce,module=angular.module("taigaWiki"),WikiDetailController=function(_super){function WikiDetailController(scope,rootscope,repo,model,confirm,rs,params,q,location,filter,log,appTitle,navUrls,analytics,tgLoader){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.appTitle=appTitle,this.navUrls=navUrls,this.analytics=analytics,this.scope.projectSlug=this.params.pslug,this.scope.wikiSlug=this.params.slug,this.scope.sectionName="Wiki",promise=this.loadInitialData(),promise.then(function(_this){return function(){return _this.appTitle.set("Wiki - "+_this.scope.project.name)}}(this)),promise.then(null,this.onInitialDataError.bind(this)),promise["finally"](tgLoader.pageLoaded)}return __extends(WikiDetailController,_super),WikiDetailController.$inject=["$scope","$rootScope","$tgRepo","$tgModel","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","$filter","$log","$appTitle","$tgNavUrls","$tgAnalytics","tgLoader"],WikiDetailController.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.membersById=groupBy(project.memberships,function(x){return x.user}),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(){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){return _this.scope.wikiLinks=wikiLinks}}(this))},WikiDetailController.prototype.loadInitialData=function(){var promise;return promise=this.loadProject(),promise.then(function(_this){return function(project){return _this.fillUsersAndRoles(project.users,project.roles),_this.q.all([_this.loadWikiLinks(),_this.loadWiki()])}}(this))},WikiDetailController.prototype["delete"]=function(){var message,title;return title="Delete Wiki Page",message=unslugify(this.scope.wiki.slug),this.confirm.askOnDelete(title,message).then(function(_this){return function(finish){var onError,onSuccess;return onSuccess=function(){var ctx;return finish(),ctx={project:_this.scope.projectSlug},_this.location.path(_this.navUrls.resolve("project-wiki",ctx)),_this.confirm.notify("success")},onError=function(){return 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){var link,template;return template=$template.get("wiki/wiki-summary.html",!0),link=function($scope,$el,$attrs){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:"/images/unnamed.png"}:{name:user.full_name_display,imgUrl:user.photo},ctx={totalEditions:wiki.editions,lastModifiedDate:moment(wiki.modified_date).format("DD MMM YYYY HH:mm"),user:user},html=template(ctx),$el.html(html)},$scope.$watch($attrs.ngModel,function(wikiPage){return wikiPage?render(wikiPage):void 0}),$scope.$on("wiki:edit",function(event,wikiPage){return render(wikiPage)}),$scope.$on("$destroy",function(){return $el.off()})},{link:link,restrict:"EA",require:"ngModel"}},module.directive("tgWikiSummary",["$log","$tgTemplate",WikiSummaryDirective]),EditableWikiContentDirective=function($window,$document,$repo,$confirm,$loading,$location,$navUrls,$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(){var ctx;if($scope.wiki.html)return $scope.wiki.id?($scope.$apply(function(){return function(){return $scope.wiki.revert()}}(this)),switchToReadMode()):(ctx={project:$scope.projectSlug},$location.path($navUrls.resolve("project-wiki",ctx)))},getSelectedText=function(){return $window.getSelection?$window.getSelection().toString():$document.selection?$document.selection.createRange().text:null},save=$qqueue.bindAdd(function(wiki){var onError,onSuccess,promise;return onSuccess=function(wikiPage){return null==wiki.id&&$analytics.trackEvent("wikipage","create","create wiki page",1),$scope.wiki=wikiPage,$model.setModelValue=wiki,$confirm.notify("success"),switchToReadMode(),$scope.$broadcast("wiki:edit",wikiPage)},onError=function(){return $confirm.notify("error")},$loading.start($el.find(".save-container")),promise=null!=wiki.id?$repo.save(wiki).then(onSuccess,onError):$repo.create("wiki",wiki).then(onSuccess,onError),promise["finally"](function(){return $loading.finish($el.find(".save-container"))})}),$el.on("mousedown",".view-wiki-content",function(event){var target;return target=angular.element(event.target),target.is("pre")?target.data("scroll-pos",target[0].scrollLeft):void 0}),$el.on("mouseup",".view-wiki-content",function(event){var prevPos,target;return target=angular.element(event.target),!isEditable()||target.is("a")||getSelectedText()||target.is("pre")&&(prevPos=target.data("scroll-pos"),target.data("scroll-pos",null),prevPos!==target[0].scrollLeft)?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?($scope.wiki=wikiPage,isEditable()?($el.addClass("editable"),null==wikiPage.id?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","$tgLocation","$tgNavUrls","$tgAnalytics","$tgQqueue",EditableWikiContentDirective])}.call(this),function(){var WikiNavDirective,bindOnce,groupBy,mixOf,module,slugify,taiga,unslugify;taiga=this.taiga,mixOf=this.taiga.mixOf,groupBy=this.taiga.groupBy,bindOnce=this.taiga.bindOnce,slugify=this.taiga.slugify,unslugify=this.taiga.slugify,module=angular.module("taigaWiki"),WikiNavDirective=function($tgrepo,$log,$location,$confirm,$navUrls,$analytics,$loading,$template){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}),$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="Delete Wiki Link",message=$scope.wikiLinks[linkId].title,$confirm.askOnDelete(title,message).then(function(){return function(finish){var promise;return promise=$tgrepo.remove($scope.wikiLinks[linkId]),promise.then(function(){return promise=$ctrl.loadWikiLinks(),promise.then(function(){return finish(),render($scope.wikiLinks)}),promise.then(null,function(){return finish()})}),promise.then(null,function(){return finish(!1),$confirm.notify("error")})}}(this))}),$el.on("keyup",".new input",function(event){var newLink,promise,target;return event.preventDefault(),13===event.keyCode?(target=angular.element(event.currentTarget),newLink=target.val(),$loading.start($el.find(".new")),promise=$tgrepo.create("wiki-links",{project:$scope.projectId,title:newLink,href:slugify(newLink)}),promise.then(function(){var loadPromise;return $analytics.trackEvent("wikilink","create","create wiki link",1),loadPromise=$ctrl.loadWikiLinks(),loadPromise.then(function(){return $loading.finish($el.find(".new")),$el.find(".new").addClass("hidden"),$el.find(".new input").val(""),$el.find(".add-button").show(),render($scope.wikiLinks)}),loadPromise.then(null,function(){return $loading.finish($el.find(".new")),$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 $loading.finish($el.find(".new")),$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",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){var extraTextTemplate,link,template;return extraTextTemplate='<fieldset class="extra-text">\n <textarea placeholder="(Optional) Add a personalized text to the invitation. Tell something lovely to your new members ;-)"></textarea>\n</fieldset>',template=_.template('<div class="add-member-wrapper">\n <fieldset>\n <input type="email" placeholder="Type an Email" <% if(required) { %> data-required="true" <% } %> data-type="email" />\n </fieldset>\n <fieldset>\n <select <% if(required) { %> data-required="true" <% } %> data-required="true">\n <% _.each(roleList, function(role) { %>\n <option value="<%- role.id %>"><%- role.name %></option>\n <% }); %>\n </select>\n <a class="icon icon-plus add-fieldset" href=""></a>\n </fieldset>\n</div>'),link=function($scope,$el){var createFieldSet,resetForm,submit,submitButton;return createFieldSet=function(required){var ctx;return null==required&&(required=!0),ctx={roleList:$scope.roles,required:required},template(ctx)},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(extraTextTemplate),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("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),$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(){return function(event){var form,invitation_extra_text,invitations,memberWrappers,onError,onSuccess;return event.preventDefault(),$loading.start(submitButton),onSuccess=function(){return $loading.finish(submitButton),lightboxService.close($el),$confirm.notify("success"),$rootScope.$broadcast("membersform:new:success")},onError=function(){return $loading.finish(submitButton),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(),$rs.memberships.bulkCreateMemberships($scope.project.id,invitations,invitation_extra_text).then(onSuccess,onError)):void 0):void 0}}(this)),submitButton=$el.find(".submit-button"),$el.on("submit","form",submit),$el.on("click",".submit-button",submit)},{link:link}},module.directive("tgLbCreateMembers",["$tgResources","$rootScope","$tgConfirm","$tgLoading","lightboxService",CreateMembersDirective])}.call(this),function(){var MembershipsController,MembershipsDirective,MembershipsRowActionsDirective,MembershipsRowAdminCheckboxDirective,MembershipsRowAvatarDirective,MembershipsRowRoleSelectorDirective,bindMethods,mixOf,module,taiga,__hasProp={}.hasOwnProperty,__extends=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};taiga=this.taiga,mixOf=this.taiga.mixOf,bindMethods=this.taiga.bindMethods,module=angular.module("taigaAdmin"),MembershipsController=function(_super){function MembershipsController(scope,rootscope,repo,confirm,rs,params,q,location,navUrls,analytics,appTitle){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.appTitle=appTitle,bindMethods(this),this.scope.sectionName="Manage Members",this.scope.project={},this.scope.filters={},promise=this.loadInitialData(),promise.then(function(_this){return function(){return _this.appTitle.set("Membership - "+_this.scope.project.name)}}(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 __extends(MembershipsController,_super),MembershipsController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","$tgNavUrls","$tgAnalytics","$appTitle"],MembershipsController.prototype.loadProject=function(){return this.rs.projects.get(this.scope.projectId).then(function(_this){return function(project){return _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.repo.resolve({pslug:this.params.pslug}).then(function(_this){return function(data){return _this.scope.projectId=data.project,data}}(this)),promise.then(function(_this){return function(){return _this.loadProject()}}(this)).then(function(_this){return function(){return _this.loadUsersAndRoles()}}(this)).then(function(_this){return function(){return _this.loadMembers()}}(this))},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){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?parseInt(numPages,10)+1:parseInt(numPages,10)},renderPagination=function(){var cpage,i,numPages,options,pages,_i;if(numPages=getNumPages(),1>=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=_i=1;numPages>=1?numPages>=_i:_i>=numPages;i=numPages>=1?++_i:--_i)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||pages.push(i===cpage?{classes:"active",num:i,type:"page-active"}:{classes:"page",num:i,type:"page"});return $pagEl.html(template(options))},$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",MembershipsDirective]),MembershipsRowAvatarDirective=function($log,$template){var link,template;return template=$template.get("admin/memberships-row-avatar.html",!0),link=function($scope,$el,$attrs){var member,render;return 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:"/images/unnamed.png"},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",MembershipsRowAvatarDirective]),MembershipsRowAdminCheckboxDirective=function($log,$repo,$confirm,$template){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),$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(){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",MembershipsRowAdminCheckboxDirective]),MembershipsRowRoleSelectorDirective=function($log,$repo,$confirm){var link,template;return template=_.template('<select>\n <% _.each(roleList, function(role) { %>\n <option value="<%- role.id %>" <% if(selectedRole === role.id){ %>selected="selected"<% } %>>\n <%- role.name %>\n </option>\n <% }); %>\n</select>'),link=function($scope,$el,$attrs){var $ctrl,html,member,render;return render=function(member){var ctx,html;return ctx={roleList:$scope.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("click","select",function(){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){var activedTemplate,link,pendingTemplate;return activedTemplate=_.template('<div class="active">\n Active\n</div>\n<a class="delete" href="">\n <span class="icon icon-delete"></span>\n</a>'),pendingTemplate=_.template('<a class="pending" href="">\n Pending\n <span class="icon icon-reload"></span>\n</a>\n<a class="delete" href="" title="Delete">\n <span class="icon icon-delete"></span>\n</a>'),link=function($scope,$el,$attrs){var $ctrl,member,render;return render=function(member){var html;return html=member.user?activedTemplate():pendingTemplate(),$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",".pending",function(event){var onError,onSuccess;return event.preventDefault(),onSuccess=function(){return $confirm.notify("success","We've sent the invitationi again to '"+$scope.member.email+"'.")},onError=function(){return $confirm.notify("error","We haven't sent the invitation.")},$rs.memberships.resendInvitation($scope.member.id).then(onSuccess,onError)}),$el.on("click",".delete",function(event){var message,title;return event.preventDefault(),title="Delete member",message=member.user?member.full_name:"the invitation to "+member.email,$confirm.askOnDelete(title,message).then(function(finish){var onError,onSuccess;return onSuccess=function(){return finish(),$ctrl.loadMembers(),$confirm.notify("success",null,"We've deleted "+message+".")},onError=function(){return finish(!1),$confirm.notify("error",null,"We have not been able to delete "+message+".")},$repo.remove(member).then(onSuccess,onError)})}),$scope.$on("$destroy",function(){return $el.off()
}))},{link:link}},module.directive("tgMembershipsRowActions",["$log","$tgRepo","$tgResources","$tgConfirm",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 ProjectDefaultValuesDirective,ProjectExportDirective,ProjectModulesDirective,ProjectProfileController,ProjectProfileDirective,bindOnce,debounce,groupBy,joinStr,mixOf,module,taiga,toString,trim,__hasProp={}.hasOwnProperty,__extends=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};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(_super){function ProjectProfileController(scope,rootscope,repo,confirm,rs,params,q,location,navUrls,appTitle){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.appTitle=appTitle,this.scope.project={},promise=this.loadInitialData(),promise.then(function(_this){return function(){return _this.appTitle.set("Project profile - "+_this.scope.sectionName+" - "+_this.scope.project.name)}}(this)),promise.then(null,this.onInitialDataError.bind(this)),this.scope.$on("project:loaded",function(_this){return function(){return _this.appTitle.set("Project profile - "+_this.scope.sectionName+" - "+_this.scope.project.name)}}(this))}return __extends(ProjectProfileController,_super),ProjectProfileController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","$tgNavUrls","$appTitle"],ProjectProfileController.prototype.loadProject=function(){return this.rs.projects.get(this.scope.projectId).then(function(_this){return function(project){return _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.repo.resolve({pslug:this.params.pslug}).then(function(_this){return function(data){return _this.scope.projectId=data.project,data}}(this)),promise.then(function(_this){return function(){return _this.loadProject()}}(this))},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){var link;return link=function($scope,$el){var form,submit,submitButton;return form=$el.find("form").checksley({onlyOneErrorElement:!0}),submit=debounce(2e3,function(){return function(event){var promise;return event.preventDefault(),form.validate()?($loading.start(submitButton),promise=$repo.save($scope.project),promise.then(function(){var newUrl;return $loading.finish(submitButton),$confirm.notify("success"),newUrl=$navurls.resolve("project-admin-project-profile-details",{project:$scope.project.slug}),$location.path(newUrl),$scope.$emit("project:loaded",$scope.project)}),promise.then(null,function(data){return $loading.finish(target),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",".submit-button",submit)},{link:link}},module.directive("tgProjectProfile",["$tgRepo","$tgConfirm","$tgLoading","$tgNavUrls","$tgLocation",ProjectProfileDirective]),ProjectDefaultValuesDirective=function($repo,$confirm,$loading){var link;return link=function($scope,$el){var form,submit,submitButton;return form=$el.find("form").checksley({onlyOneErrorElement:!0}),submit=debounce(2e3,function(){return function(event){var promise;return event.preventDefault(),form.validate()?($loading.start(submitButton),promise=$repo.save($scope.project),promise.then(function(){return $loading.finish(submitButton),$confirm.notify("success")}),promise.then(null,function(data){return $loading.finish(target),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",".submit-button",submit),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgProjectDefaultValues",["$tgRepo","$tgConfirm","$tgLoading",ProjectDefaultValuesDirective]),ProjectModulesDirective=function($repo,$confirm,$loading){var link;return link=function($scope,$el){var form,submit;return form=$el.find("form").checksley(),submit=function(){return function(){var promise,target;if(form.validate())return target=angular.element(".admin-functionalities a.button-green"),$loading.start(target),promise=$repo.save($scope.project),promise.then(function(){return $loading.finish(target),$confirm.notify("success"),$scope.$emit("project:loaded",$scope.project)}),promise.then(null,function(data){return $loading.finish(target),$confirm.notify("error",data._error_message)})}}(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_salt="")}),$scope.$watch("project",function(project){return $scope.isVideoconferenceActivated=null!=project.videoconferences?!0:!1})},{link:link}},module.directive("tgProjectModules",["$tgRepo","$tgConfirm","$tgLoading",ProjectModulesDirective]),ProjectExportDirective=function($window,$rs,$confirm){var link;return link=function($scope,$el){var buttonsEl,hideButtons,hideResult,hideSpinner,resultEl,resultMessageEl,resultTitleEl,setAsyncMessage,setAsyncTitle,setLoadingMessage,setLoadingTitle,setSyncMessage,setSyncTitle,showButtons,showErrorMode,showExportResultAsyncMode,showExportResultSyncMode,showLoadingMode,showResult,showSpinner,spinnerEl;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"),setLoadingTitle=function(){return resultTitleEl.html("We are generating your dump file")},setAsyncTitle=function(){return resultTitleEl.html("We are generating your dump file")},setSyncTitle=function(){return resultTitleEl.html("Your dump file ir ready!")},resultMessageEl=$el.find(".result-message "),setLoadingMessage=function(){return resultMessageEl.html("Please don't close this page.")},setAsyncMessage=function(){return resultMessageEl.html("We will send you an email when ready.")},setSyncMessage=function(url){return resultMessageEl.html("If the download doesn't start automatically click <a href='"+url+"' download title='Download the dump file'>here.")},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(){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="Our oompa loompas have some problems generasting your dump. Please try again. ",429===result.status?errorMsg="Sorry, our oompa loompas are very busy right now. Please try again in a few minutes. ":(null!=(_ref=result.data)?_ref._error_message:void 0)&&(errorMsg="Our oompa loompas have some problems generasting your dump: "+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",ProjectExportDirective])}.call(this),function(){var ColorSelectionDirective,ProjectValuesController,ProjectValuesDirective,bindOnce,debounce,groupBy,joinStr,mixOf,module,taiga,toString,trim,__bind=function(fn,me){return function(){return fn.apply(me,arguments)}},__hasProp={}.hasOwnProperty,__extends=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};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"),ProjectValuesController=function(_super){function ProjectValuesController(scope,rootscope,repo,confirm,rs,params,q,location,navUrls,appTitle){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.appTitle=appTitle,this.moveValue=__bind(this.moveValue,this),this.scope.project={},promise=this.loadInitialData(),promise.then(function(_this){return function(){return _this.appTitle.set("Project values - "+_this.scope.sectionName+" - "+_this.scope.project.name)}}(this)),promise.then(null,this.onInitialDataError.bind(this)),this.scope.$on("admin:project-values:move",this.moveValue)}return __extends(ProjectValuesController,_super),ProjectValuesController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","$tgNavUrls","$appTitle"],ProjectValuesController.prototype.loadProject=function(){return this.rs.projects.get(this.scope.projectId).then(function(_this){return function(project){return _this.scope.project=project,_this.scope.$emit("project:loaded",project),project}}(this))},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.loadInitialData=function(){var promise;return promise=this.repo.resolve({pslug:this.params.pslug}).then(function(_this){return function(data){return _this.scope.projectId=data.project,data}}(this)),promise.then(function(_this){return function(){return _this.q.all([_this.loadProject(),_this.loadValues()])}}(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}(mixOf(taiga.Controller,taiga.PageMixin)),module.controller("ProjectValuesController",ProjectValuesController),ProjectValuesDirective=function($log,$repo,$confirm,$location,animationFrame){var link,linkDragAndDrop,linkValue;return linkDragAndDrop=function($scope,$el){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,saveValue,submit,valueType;return $ctrl=$el.controller(),valueType=$attrs.type,initializeNewValue=function(){return $scope.newValue={name:"",is_closed:!1,is_archived:!1}},initializeNewValue(),goToBottomList=function(){return function(focus){var table;return null==focus&&(focus=!1),table=$el.find(".table-main"),$(document.body).scrollTop(table.offset().top+table.height()),focus?$(".new-value input").focus():void 0}}(this),submit=debounce(2e3,function(){return function(){var promise;return promise=$repo.save($scope.project),promise.then(function(){return $confirm.notify("success")}),promise.then(null,function(data){return $confirm.notify("error",data._error_message)})}}(this)),saveValue=debounce(2e3,function(target){var form,promise,value;return form=target.parents("form").checksley(),form.validate()?(value=target.scope().value,promise=$repo.save(value),promise.then(function(){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 $confirm.notify("error"),form.setErrors(data)})):void 0}),cancel=function(target){var row,value;return row=target.parents(".row.table-main"),value=target.scope().value,$scope.$apply(function(){return row.addClass("hidden"),value.revert(),row.siblings(".visualization").removeClass("hidden")})},$el.on("submit","form",function(event){return event.preventDefault(),submit()}),$el.on("click","form a.button-green",function(event){return event.preventDefault(),submit()}),$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 form,promise;return event.preventDefault(),form=$el.find(".new-value").parents("form").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(){return function(){return $ctrl.loadValues().then(function(){return animationFrame.add(function(){return goToBottomList()})}),$el.find(".new-value").addClass("hidden"),initializeNewValue()}}(this)),promise.then(null,function(data){return $confirm.notify("error"),form.setErrors(data)})):void 0})),$el.on("click",".delete-new",function(event){return event.preventDefault(),$el.find(".new-value").hide(),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("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,replacement,subtitle,target,title,value;return event.preventDefault(),target=angular.element(event.currentTarget),value=target.scope().value,choices={},_.each($scope.values,function(option){return value.id!==option.id?choices[option.id]=option.name:void 0}),title="Delete value",subtitle=value.name,replacement="All items with this value will be changed to",0===_.keys(choices).length?$confirm.error("You can't delete all values."):$confirm.askChoice(title,subtitle,choices,replacement).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",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(){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)}.call(this),function(){var EditRoleDirective,NewRoleDirective,RolePermissionsDirective,RolesController,RolesDirective,bindMethods,bindOnce,debounce,mixOf,module,taiga,__hasProp={}.hasOwnProperty,__extends=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},__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(_super){function RolesController(scope,rootscope,repo,confirm,rs,params,q,location,navUrls,appTitle){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.appTitle=appTitle,bindMethods(this),this.scope.sectionName="Permissions",this.scope.project={},this.scope.anyComputableRole=!0,promise=this.loadInitialData(),promise.then(function(_this){return function(){return _this.appTitle.set("Roles - "+_this.scope.project.name)}}(this)),promise.then(null,this.onInitialDataError.bind(this))}return __extends(RolesController,_super),RolesController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","$tgNavUrls","$appTitle"],RolesController.prototype.loadProject=function(){return this.rs.projects.get(this.scope.projectId).then(function(_this){return function(project){return _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(data){return _this.scope.roles=data,_this.scope.role=_this.scope.roles[0],data}}(this))},RolesController.prototype.loadInitialData=function(){var promise;return promise=this.repo.resolve({pslug:this.params.pslug}).then(function(_this){return function(data){return _this.scope.projectId=data.project,data}}(this)),promise.then(function(_this){return function(){return _this.loadProject()}}(this)).then(function(_this){return function(){return _this.loadUsersAndRoles()}}(this)).then(function(_this){return function(){return _this.loadRoles()}}(this))},RolesController.prototype.setRole=function(role){return this.scope.role=role,this.scope.$broadcast("role:changed",this.scope.role)},RolesController.prototype["delete"]=function(){var choices,replacement,role,subtitle,title,warning,_i,_len,_ref;for(title="Delete Role",subtitle=this.scope.role.name,replacement="All the users with this role will be moved to",warning="<strong>Be careful, all role estimations will be removed</strong>",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("You can't delete all values."):this.confirm.askChoice(title,subtitle,choices,replacement,warning).then(function(_this){return function(response){var promise;return promise=_this.repo.remove(_this.scope.role,{moveTo:response.selected}),promise.then(function(){return _this.loadProject(),_this.loadRoles()["finally"](function(){return response.finish()})}),promise.then(null,function(){return _this.confirm.notify("error")})}}(this))},RolesController.prototype.setComputable=debounce(2e3,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}(mixOf(taiga.Controller,taiga.PageMixin,taiga.FiltersMixin)),module.controller("RolesController",RolesController),EditRoleDirective=function($repo,$confirm){var link;return link=function($scope,$el){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(){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){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){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){return $scope.roles.push(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){var baseTemplate,categoryTemplate,link,resumeTemplate;return resumeTemplate=_.template('<div class="resume-title"><%- category.name %></div>\n<div class="summary-role">\n <div class="count"><%- category.activePermissions %>/<%- category.permissions.length %></div>\n <% _.each(category.permissions, function(permission) { %>\n <div class="role-summary-single <% if(permission.active) { %>active<% } %>"\n title="<%- permission.description %>"></div>\n <% }) %>\n</div>\n<div class="icon icon-arrow-bottom"></div>'),categoryTemplate=_.template('<div class="category-config" data-id="<%- index %>">\n <div class="resume">\n </div>\n <div class="category-items">\n <div class="items-container">\n <% _.each(category.permissions, function(permission) { %>\n <div class="category-item" data-id="<%- permission.key %>">\n <span><%- permission.description %></span>\n <div class="check">\n <input type="checkbox" <% if(permission.active) { %>checked="checked"<% } %>/>\n <div></div>\n <span class="check-text check-yes">Yes</span>\n <span class="check-text check-no">No</span>\n </div>\n </div>\n <% }) %>\n </div>\n </div>\n</div>'),baseTemplate=_.template('<div class="category-config-list"></div>'),link=function($scope,$el,$attrs){var $ctrl,generateCategoriesFromRole,renderCategory,renderPermissions,renderResume;return $ctrl=$el.controller(),generateCategoriesFromRole=function(role){var categories,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)})})},setActivePermissionsPerCategory=function(category){return _.map(category,function(x){return _.extend({},x,{activePermissions:_.filter(x.permissions,"active").length})})},categories=[],milestonePermissions=[{key:"view_milestones",description:"View sprints"},{key:"add_milestone",description:"Add sprint"},{key:"modify_milestone",description:"Modify sprint"},{key:"delete_milestone",description:"Delete sprint"}],categories.push({name:"Sprints",permissions:setActivePermissions(milestonePermissions)}),userStoryPermissions=[{key:"view_us",description:"View user story"},{key:"add_us",description:"Add user story"},{key:"modify_us",description:"Modify user story"},{key:"delete_us",description:"Delete user story"}],categories.push({name:"User Stories",permissions:setActivePermissions(userStoryPermissions)}),taskPermissions=[{key:"view_tasks",description:"View tasks"},{key:"add_task",description:"Add task"},{key:"modify_task",description:"Modify task"},{key:"delete_task",description:"Delete task"}],categories.push({name:"Tasks",permissions:setActivePermissions(taskPermissions)}),issuePermissions=[{key:"view_issues",description:"View issues"},{key:"add_issue",description:"Add issue"},{key:"modify_issue",description:"Modify issue"},{key:"delete_issue",description:"Delete issue"}],categories.push({name:"Issues",permissions:setActivePermissions(issuePermissions)}),wikiPermissions=[{key:"view_wiki_pages",description:"View wiki pages"},{key:"add_wiki_page",description:"Add wiki page"},{key:"modify_wiki_page",description:"Modify wiki page"},{key:"delete_wiki_page",description:"Delete wiki page"},{key:"view_wiki_links",description:"View wiki links"},{key:"add_wiki_link",description:"Add wiki link"},{key:"delete_wiki_link",description:"Delete wiki link"}],categories.push({name:"Wiki",permissions:setActivePermissions(wikiPermissions)}),setActivePermissionsPerCategory(categories)},renderResume=function(element,category){return element.find(".resume").html(resumeTemplate({category:category}))},renderCategory=function(category,index){var html;return html=categoryTemplate({category:category,index:index}),html=angular.element(html),renderResume(html,category),html},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.push("view_project"),activePermissions},target=angular.element(event.currentTarget),$scope.role.permissions=getActivePermissions(),onSuccess=function(role){var categories,categoryId;return categories=generateCategoriesFromRole(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()},$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",RolePermissionsDirective])
}.call(this),function(){var BitbucketController,BitbucketWebhooksDirective,GithubController,GithubWebhooksDirective,GitlabController,GitlabWebhooksDirective,NewWebhookDirective,SelectInputText,ValidOriginIpsDirective,WebhookDirective,WebhooksController,bindMethods,debounce,mixOf,module,taiga,timeout,__hasProp={}.hasOwnProperty,__extends=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};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(_super){function WebhooksController(scope,repo,rs,params,appTitle){var promise;this.scope=scope,this.repo=repo,this.rs=rs,this.params=params,this.appTitle=appTitle,bindMethods(this),this.scope.sectionName="Webhooks",this.scope.project={},promise=this.loadInitialData(),promise.then(function(_this){return function(){return _this.appTitle.set("Webhooks - "+_this.scope.project.name)}}(this)),promise.then(null,this.onInitialDataError.bind(this)),this.scope.$on("webhooks:reload",this.loadWebhooks)}return __extends(WebhooksController,_super),WebhooksController.$inject=["$scope","$tgRepo","$tgResources","$routeParams","$appTitle"],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.get(this.scope.projectId).then(function(_this){return function(project){return _this.scope.project=project,_this.scope.$emit("project:loaded",project),project}}(this))},WebhooksController.prototype.loadInitialData=function(){var promise;return promise=this.repo.resolve({pslug:this.params.pslug}).then(function(_this){return function(data){return _this.scope.projectId=data.project,data}}(this)),promise.then(function(_this){return function(){return _this.loadProject()}}(this)).then(function(_this){return function(){return _this.loadWebhooks()}}(this))},WebhooksController}(mixOf(taiga.Controller,taiga.PageMixin,taiga.FiltersMixin)),module.controller("WebhooksController",WebhooksController),WebhookDirective=function($rs,$repo,$confirm){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(){return $rs.webhooklogs.list(webhook.id).then(function(){return function(webhooklogs){var log,_i,_len,_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.data,void 0,2),log.prettyDate=moment(log.created).format("DD MMM YYYY [at] hh:mm:ss");return webhook.logs_counter=webhooklogs.length,webhook.logs=webhooklogs,updateShowHideHistoryText()}}(this))},updateShowHideHistoryText=function(){var historyElement,textElement;return textElement=$el.find(".toggle-history"),historyElement=textElement.parents(".single-webhook-wrapper").find(".webhooks-history"),textElement.text(historyElement.hasClass("open")?"(Hide history)":"(Show history)")},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,value;return form=target.parents("form").checksley(),form.validate()?(value=target.scope().value,promise=$repo.save(webhook),promise.then(function(){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(){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),saveWebhook(target)):27===event.keyCode?(target=angular.element(event.currentTarget),cancel(target)):void 0}),$el.on("click",".delete-webhook",function(){var message,title;return title="Delete webhook",message="Webhook '"+webhook.name+"'",$confirm.askOnDelete(title,message).then(function(){return function(finish){var onError,onSucces;return onSucces=function(){return finish(),$scope.$emit("webhooks:reload")},onError=function(){return 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(){return function(){return updateLogs()}}(this))})},{link:link}},module.directive("tgWebhook",["$tgResources","$tgRepo","$tgConfirm","$tgLoading",WebhookDirective]),NewWebhookDirective=function($rs,$repo,$confirm){var link;return link=function($scope,$el,$attrs){var addWebhookDOMNode,formDOMNode,initializeNewValue,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}),formDOMNode.on("click",".add-new",debounce(2e3,function(event){var form,promise;return event.preventDefault(),form=formDOMNode.checksley(),form.validate()?($scope.newValue.project=$scope.project.id,promise=$repo.create("webhooks",$scope.newValue),promise.then(function(){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",".cancel-new",function(){return $scope.$apply(function(){return initializeNewValue()})}),addWebhookDOMNode.on("click",function(){return formDOMNode.removeClass("hidden"),formDOMNode.find("input")[0].focus()})},{link:link}},module.directive("tgNewWebhook",["$tgResources","$tgRepo","$tgConfirm","$tgLoading",NewWebhookDirective]),GithubController=function(_super){function GithubController(scope,repo,rs,params,appTitle){var promise;this.scope=scope,this.repo=repo,this.rs=rs,this.params=params,this.appTitle=appTitle,bindMethods(this),this.scope.sectionName="Github",this.scope.project={},promise=this.loadInitialData(),promise.then(function(_this){return function(){return _this.appTitle.set("Github - "+_this.scope.project.name)}}(this)),promise.then(null,this.onInitialDataError.bind(this))}return __extends(GithubController,_super),GithubController.$inject=["$scope","$tgRepo","$tgResources","$routeParams","$appTitle"],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.get(this.scope.projectId).then(function(_this){return function(project){return _this.scope.project=project,_this.scope.$emit("project:loaded",project),project}}(this))},GithubController.prototype.loadInitialData=function(){var promise;return promise=this.repo.resolve({pslug:this.params.pslug}).then(function(_this){return function(data){return _this.scope.projectId=data.project,data}}(this)),promise.then(function(_this){return function(){return _this.loadProject()}}(this)).then(function(_this){return function(){return _this.loadModules()}}(this))},GithubController}(mixOf(taiga.Controller,taiga.PageMixin,taiga.FiltersMixin)),module.controller("GithubController",GithubController),GitlabController=function(_super){function GitlabController(scope,repo,rs,params,appTitle){var promise;this.scope=scope,this.repo=repo,this.rs=rs,this.params=params,this.appTitle=appTitle,bindMethods(this),this.scope.sectionName="Gitlab",this.scope.project={},promise=this.loadInitialData(),promise.then(function(_this){return function(){return _this.appTitle.set("Gitlab - "+_this.scope.project.name)}}(this)),promise.then(null,this.onInitialDataError.bind(this)),this.scope.$on("project:modules:reload",function(_this){return function(){return _this.loadModules()}}(this))}return __extends(GitlabController,_super),GitlabController.$inject=["$scope","$tgRepo","$tgResources","$routeParams","$appTitle"],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.get(this.scope.projectId).then(function(_this){return function(project){return _this.scope.project=project,_this.scope.$emit("project:loaded",project),project}}(this))},GitlabController.prototype.loadInitialData=function(){var promise;return promise=this.repo.resolve({pslug:this.params.pslug}).then(function(_this){return function(data){return _this.scope.projectId=data.project,data}}(this)),promise.then(function(_this){return function(){return _this.loadProject()}}(this)).then(function(_this){return function(){return _this.loadModules()}}(this))},GitlabController}(mixOf(taiga.Controller,taiga.PageMixin,taiga.FiltersMixin)),module.controller("GitlabController",GitlabController),BitbucketController=function(_super){function BitbucketController(scope,repo,rs,params,appTitle){var promise;this.scope=scope,this.repo=repo,this.rs=rs,this.params=params,this.appTitle=appTitle,bindMethods(this),this.scope.sectionName="Bitbucket",this.scope.project={},promise=this.loadInitialData(),promise.then(function(_this){return function(){return _this.appTitle.set("Bitbucket - "+_this.scope.project.name)}}(this)),promise.then(null,this.onInitialDataError.bind(this)),this.scope.$on("project:modules:reload",function(_this){return function(){return _this.loadModules()}}(this))}return __extends(BitbucketController,_super),BitbucketController.$inject=["$scope","$tgRepo","$tgResources","$routeParams","$appTitle"],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.get(this.scope.projectId).then(function(_this){return function(project){return _this.scope.project=project,_this.scope.$emit("project:loaded",project),project}}(this))},BitbucketController.prototype.loadInitialData=function(){var promise;return promise=this.repo.resolve({pslug:this.params.pslug}).then(function(_this){return function(data){return _this.scope.projectId=data.project,data}}(this)),promise.then(function(_this){return function(){return _this.loadProject()}}(this)).then(function(_this){return function(){return _this.loadModules()}}(this))},BitbucketController}(mixOf(taiga.Controller,taiga.PageMixin,taiga.FiltersMixin)),module.controller("BitbucketController",BitbucketController),SelectInputText=function(){var link;return link=function($scope,$el){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){var form,submit,submitButton;return form=$el.find("form").checksley({onlyOneErrorElement:!0}),submit=debounce(2e3,function(){return function(event){var promise;return event.preventDefault(),form.validate()?($loading.start(submitButton),promise=$repo.saveAttribute($scope.github,"github"),promise.then(function(){return $loading.finish(submitButton),$confirm.notify("success")}),promise.then(null,function(data){return $loading.finish(submitButton),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",".submit-button",submit)},{link:link}},module.directive("tgGithubWebhooks",["$tgRepo","$tgConfirm","$tgLoading",GithubWebhooksDirective]),GitlabWebhooksDirective=function($repo,$confirm,$loading){var link;return link=function($scope,$el){var form,submit,submitButton;return form=$el.find("form").checksley({onlyOneErrorElement:!0}),submit=debounce(2e3,function(){return function(event){var promise;return event.preventDefault(),form.validate()?($loading.start(submitButton),promise=$repo.saveAttribute($scope.gitlab,"gitlab"),promise.then(function(){return $loading.finish(submitButton),$confirm.notify("success"),$scope.$emit("project:modules:reload")}),promise.then(null,function(data){return $loading.finish(submitButton),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",".submit-button",submit)},{link:link}},module.directive("tgGitlabWebhooks",["$tgRepo","$tgConfirm","$tgLoading",GitlabWebhooksDirective]),BitbucketWebhooksDirective=function($repo,$confirm,$loading){var link;return link=function($scope,$el){var form,submit,submitButton;return form=$el.find("form").checksley({onlyOneErrorElement:!0}),submit=debounce(2e3,function(){return function(event){var promise;return event.preventDefault(),form.validate()?($loading.start(submitButton),promise=$repo.saveAttribute($scope.bitbucket,"bitbucket"),promise.then(function(){return $loading.finish(submitButton),$confirm.notify("success"),$scope.$emit("project:modules:reload")}),promise.then(null,function(data){return $loading.finish(submitButton),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",".submit-button",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){var link;return link=function($scope,$el){var form,onErrorSubmit,onSuccessSubmit,submit,submitButton;return $scope.data={},$scope.templates=[],form=$el.find("form").checksley({onlyOneErrorElement:!0}),onSuccessSubmit=function(response){return $cacheFactory.get("$http").removeAll(),$loading.finish(submitButton),$rootscope.$broadcast("projects:reload"),$confirm.notify("success","Success"),$location.url($projectUrl.get(response)),lightboxService.close($el)},onErrorSubmit=function(response){var error_field,error_step,selectors,_i,_len,_ref;for($loading.finish(submitButton),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(){return function(event){var promise;return event.preventDefault(),form.validate()?($loading.start(submitButton),promise=$repo.create("projects",$scope.data),promise.then(onSuccessSubmit,onErrorSubmit)):void 0}}(this),$scope.$on("projects:create",function(){return $scope.data={total_story_points:100,total_milestones:5},$scope.templates.length?$scope.data.creation_template=_.head(_.filter($scope.templates,function(x){return"scrum"===x.slug})).id:$rs.projects.templates().then(function(){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,next,step,valid,_i,_len,_ref;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",".submit-button",submit),$el.on("click",".close",function(event){return event.preventDefault(),lightboxService.close($el)})},{link:link}},module.directive("tgLbCreateProject",["$rootScope","$tgRepo","$tgConfirm","$location","$tgNavUrls","$tgResources","$projectUrl","$tgLoading","lightboxService","$cacheFactory",CreateProject]),DeleteProjectDirective=function($repo,$rootscope,$auth,$location,$navUrls,$confirm,lightboxService,tgLoader){var link;return link=function($scope,$el){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(){return tgLoader.pageLoaded(),$rootscope.$broadcast("projects:reload"),$location.path($navUrls.resolve("home")),$confirm.notify("success")}),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",DeleteProjectDirective])}.call(this),function(){var ProjectController,ProjectsController,ProjectsListDirective,ProjectsPaginationDirective,bindOnce,module,taiga,__hasProp={}.hasOwnProperty,__extends=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};taiga=this.taiga,module=angular.module("taigaProject"),bindOnce=this.taiga.bindOnce,ProjectsController=function(_super){function ProjectsController(scope,q,rs,rootscope,navUrls,auth,location,appTitle,projectUrl,tgLoader){var promise;this.scope=scope,this.q=q,this.rs=rs,this.rootscope=rootscope,this.navUrls=navUrls,this.auth=auth,this.location=location,this.appTitle=appTitle,this.projectUrl=projectUrl,this.appTitle.set("Projects"),this.auth.isAuthenticated()||this.location.path(this.navUrls.resolve("login")),this.user=this.auth.getUser(),this.projects=[],promise=this.loadInitialData(),promise.then(function(_this){return function(){return _this.scope.$emit("projects:loaded")}}(this)),promise.then(null,this.onInitialDataError.bind(this)),promise["finally"](tgLoader.pageLoaded)}return __extends(ProjectsController,_super),ProjectsController.$inject=["$scope","$q","$tgResources","$rootScope","$tgNavUrls","$tgAuth","$tgLocation","$appTitle","$projectUrl","tgLoader"],ProjectsController.prototype.loadInitialData=function(){return this.rs.projects.list().then(function(_this){return function(projects){var project,_i,_len;for(_this.projects={recents:projects.slice(0,8),all:projects},_i=0,_len=projects.length;_len>_i;_i++)project=projects[_i],project.url=_this.projectUrl.get(project);return projects}}(this))},ProjectsController.prototype.newProject=function(){return this.rootscope.$broadcast("projects:create")},ProjectsController.prototype.logout=function(){return this.auth.logout(),this.location.path(this.navUrls.resolve("login"))},ProjectsController}(taiga.Controller),module.controller("ProjectsController",ProjectsController),ProjectController=function(_super){function ProjectController(scope,rs,repo,params,q,rootscope,appTitle,location,navUrls){var promise;this.scope=scope,this.rs=rs,this.repo=repo,this.params=params,this.q=q,this.rootscope=rootscope,this.appTitle=appTitle,this.location=location,this.navUrls=navUrls,promise=this.loadInitialData(),promise.then(function(_this){return function(){return _this.appTitle.set(_this.scope.project.name),_this.scope.$emit("regenerate:project-pagination")}}(this)),promise.then(null,this.onInitialDataError.bind(this))}return __extends(ProjectController,_super),ProjectController.$inject=["$scope","$tgResources","$tgRepo","$routeParams","$q","$rootScope","$appTitle","$tgLocation","$tgNavUrls"],ProjectController.prototype.loadInitialData=function(){var promise;return promise=this.repo.resolve({pslug:this.params.pslug}).then(function(_this){return function(data){return _this.scope.projectId=data.project,data}}(this)),promise.then(function(_this){return function(){return _this.loadPageData()}}(this)).then(function(_this){return function(){return _this.scope.$emit("project:loaded",_this.scope.project)}}(this))},ProjectController.prototype.loadPageData=function(){return this.q.all([this.loadProjectStats(),this.loadProject()])},ProjectController.prototype.loadProject=function(){return this.rs.projects.get(this.scope.projectId).then(function(_this){return function(project){return _this.scope.project=project,project}}(this))},ProjectController.prototype.loadProjectStats=function(){return this.rs.projects.stats(this.scope.projectId).then(function(_this){return function(stats){return _this.scope.stats=stats,stats}}(this))},ProjectController}(taiga.Controller),module.controller("ProjectController",ProjectController),ProjectsPaginationDirective=function(){var link;return link=function($scope,$el){var checkButtonVisibility,container,containerSize,hasNextPage,hasPagination,hasPrevPage,hide,nextBtn,nextPage,pageSize,prevBtn,prevPage,remove,render,visible;return prevBtn=$el.find(".v-pagination-previous"),nextBtn=$el.find(".v-pagination-next"),container=$el.find("ul"),pageSize=0,containerSize=0,render=function(){return pageSize=$el.find(".v-pagination-list").height(),container.find("li").length&&hasPagination()?(hasNextPage()?visible(nextBtn):hide(nextBtn),hasPrevPage()?visible(prevBtn):hide(prevBtn)):remove()},hasPagination=function(){return containerSize=container.height(),containerSize>pageSize},hasPrevPage=function(top){return null==top&&(top=-parseInt(container.css("top"),10)||0),0!==top},hasNextPage=function(top){return containerSize=container.height(),top||(top=-parseInt(container.css("top"),10)||0),containerSize>pageSize&&containerSize>top+pageSize},nextPage=function(callback){var lastLi,maxTop,newTop,top;return top=parseInt(container.css("top"),10),newTop=top-pageSize,lastLi=$el.find(".v-pagination-list li:last-child"),maxTop=-(lastLi.position().top+lastLi.outerHeight()-pageSize),maxTop>newTop&&(newTop=maxTop),container.animate({top:newTop},callback),newTop},prevPage=function(callback){var newTop,top;return top=parseInt(container.css("top"),10),newTop=top+pageSize,newTop>0&&(newTop=0),container.animate({top:newTop},callback),newTop},visible=function(element){return element.css("visibility","visible")},hide=function(element){return element.css("visibility","hidden")},checkButtonVisibility=function(){},remove=function(){return container.css("top",0),hide(prevBtn),hide(nextBtn)},$el.on("click",".v-pagination-previous",function(event){var newTop;return event.preventDefault(),container.is(":animated")?void 0:(visible(nextBtn),newTop=prevPage(),hasPrevPage(newTop)?void 0:hide(prevBtn))}),$el.on("click",".v-pagination-next",function(event){var newTop;return event.preventDefault(),container.is(":animated")?void 0:(visible(prevBtn),newTop=-nextPage(),hasNextPage(newTop)?void 0:hide(nextBtn))}),$scope.$on("regenerate:project-pagination",function(){return remove(),render()}),$(window).on("resize.projects-pagination",render),$scope.$on("$destroy",function(){return $(window).off("resize.projects-pagination")})},{link:link}},module.directive("tgProjectsPagination",["$timeout",ProjectsPaginationDirective]),ProjectsListDirective=function($compile,$template){var link,template;return template=$template.get("project/project-list.html",!0),link=function($scope,$el){var render;return render=function(projects){return $el.html($compile(template({projects:projects}))($scope)),$scope.$emit("regenerate:project-pagination")},$scope.$watch("projects",function(projects){return null!=projects?render(projects):void 0})},{link:link}},module.directive("tgProjectsList",["$compile","$tgTemplate",ProjectsListDirective])}.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,taigaContribPlugins,__hasProp={}.hasOwnProperty,__extends=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};taigaContribPlugins=this.taigaContribPlugins=this.taigaContribPlugins||[],ContribController=function(_super){function ContribController(rootScope,scope,params,repo,rs,confirm,appTitle){var promise;this.rootScope=rootScope,this.scope=scope,this.params=params,this.repo=repo,this.rs=rs,this.confirm=confirm,this.appTitle=appTitle,this.scope.currentPlugin=_.first(_.where(taigaContribPlugins,{slug:this.params.plugin})),this.scope.pluginTemplate="contrib/"+this.scope.currentPlugin.slug,this.scope.projectSlug=this.params.pslug,this.scope.adminPlugins=_.where(this.rootScope.contribPlugins,{type:"admin"}),promise=this.loadInitialData(),promise.then(function(_this){return function(){return _this.appTitle.set(_this.scope.project.name)}}(this)),promise.then(null,function(_this){return function(){return _this.confirm.notify("error")}}(this))}return __extends(ContribController,_super),ContribController.$inject=["$rootScope","$scope","$routeParams","$tgRepo","$tgResources","$tgConfirm","$appTitle"],ContribController.prototype.loadProject=function(){return this.rs.projects.get(this.scope.projectId).then(function(_this){return function(project){return _this.scope.project=project,_this.scope.$emit("project:loaded",project),_this.scope.$broadcast("project:loaded",project),project}}(this))},ContribController.prototype.loadInitialData=function(){var promise;return promise=this.repo.resolve({pslug:this.params.pslug}).then(function(_this){return function(data){return _this.scope.projectId=data.project,data
}}(this)),promise.then(function(_this){return function(){return _this.loadProject()}}(this))},ContribController}(taiga.Controller),module=angular.module("taigaBase"),module.controller("ContribController",ContribController)}.call(this),function(){var FiltersStorageService,taiga,__hasProp={}.hasOwnProperty,__extends=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};taiga=this.taiga,FiltersStorageService=function(_super){function FiltersStorageService(storage,params){this.storage=storage,this.params=params}return __extends(FiltersStorageService,_super),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,__hasProp={}.hasOwnProperty,__extends=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};taiga=this.taiga,HttpService=function(_super){function HttpService(http,q,storage){this.http=http,this.q=q,this.storage=storage,HttpService.__super__.constructor.call(this)}return __extends(HttpService,_super),HttpService.$inject=["$http","$q","$tgStorage"],HttpService.prototype.headers=function(){var token;return token=this.storage.get("token"),token?{Authorization:"Bearer "+token}:{}},HttpService.prototype.request=function(options){return options.headers=_.merge({},options.headers||{},this.headers()),_.isPlainObject(options.data)&&(options.data=JSON.stringify(options.data)),this.http(options)},HttpService.prototype.get=function(url,params,options){return options=_.merge({method:"GET",url:url},options),params&&(options.params=params),this.request(options)},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 I18nDirective,I18nService,bindOnce,defaults,module,taiga,__hasProp={}.hasOwnProperty,__extends=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};taiga=this.taiga,bindOnce=this.taiga.bindOnce,defaults={ns:"app",fallbackLng:"en",async:!1,lng:"en"},I18nService=function(_super){function I18nService(rootscope,localesEn){this.rootscope=rootscope,this.options=_.clone(defaults,!0),this.options.resStore={en:{app:localesEn}}}return __extends(I18nService,_super),I18nService.prototype.setLanguage=function(language){return i18n.setLng(language),this.rootscope.currentLang=language,this.rootscope.$broadcast("i18n:changeLang",language)},I18nService.prototype.initialize=function(){return i18n.init(this.options),this.rootscope.t=i18n.t},I18nService.prototype.t=function(path,opts){return i18n.t(path,opts)},I18nService}(taiga.Service),I18nDirective=function($rootscope,$i18n){var link;return link=function($scope,$el,$attrs){var ns,options,opts,v,values,_i,_len,_ref,_results;for(values=$attrs.tr.split(","),options=$attrs.trOpts||"{}",opts=$scope.$eval(options),_results=[],_i=0,_len=values.length;_len>_i;_i++)v=values[_i],-1===v.indexOf(":")?_results.push($el.html(_.escape($i18n.t(v,opts)))):(_ref=v.split(":"),ns=_ref[0],v=_ref[1],_results.push($el.attr(ns,_.escape($i18n.t(v,opts)))));return _results},{link:link,restrict:"A",scope:!1}},module=angular.module("taigaBase"),module.service("$tgI18n",["$rootScope","localesEn",I18nService]),module.directive("tr",["$rootScope","$tgI18n",I18nDirective])}.call(this),function(){var locationFactory,module;locationFactory=function($location,$route){return $location.noreload=function(scope){var lastRoute,un;return lastRoute=$route.current,un=scope.$on("$locationChangeSuccess",function(){return $route.current=lastRoute,un()}),$location},$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},__hasProp={}.hasOwnProperty,__extends=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};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(_super){function ModelService(q,urls,storage,http){this.q=q,this.urls=urls,this.storage=storage,this.http=http,ModelService.__super__.constructor.call(this)}return __extends(ModelService,_super),ModelService.$inject=["$q","$tgUrls","$tgStorage","$tgHttp"],ModelService}(taiga.Service),provider=function(){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,__hasProp={}.hasOwnProperty,__extends=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};taiga=this.taiga,trim=this.taiga.trim,bindOnce=this.taiga.bindOnce,module=angular.module("taigaBase"),NavigationUrlsService=function(_super){function NavigationUrlsService(){this.urls={}}return __extends(NavigationUrlsService,_super),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 name,params,promises,values,_ref;return _ref=_.map(data.split(":"),trim),name=_ref[0],params=_ref[1],params=params?_.map(params.split(","),trim):[],values=_.map(params,function(x){return trim(x.split("=")[1])}),promises=_.map(values,function(x){return bindOnceP($scope,x)}),$q.all(promises).then(function(){var item,key,options,value,_i,_len,_ref1;for(options={},_i=0,_len=params.length;_len>_i;_i++)item=params[_i],_ref1=_.map(item.split("="),trim),key=_ref1[0],value=_ref1[1],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,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),target.data("fullUrl",fullUrl),target.is("a")&&target.attr("href",fullUrl),$el.on("click",function(event){if(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,__hasProp={}.hasOwnProperty,__extends=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};taiga=this.taiga,RepositoryService=function(_super){function RepositoryService(q,model,storage,http,urls){this.q=q,this.model=model,this.storage=storage,this.http=http,this.urls=urls,RepositoryService.__super__.constructor.call(this)}return __extends(RepositoryService,_super),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){return defered.resolve(_this.model.make_model(name,_data,null,dataTypes))}}(this)),promise.error(function(){return function(data){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(){return defered.resolve(model)}),promise.error(function(){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(){return function(data){return model._isModified=!1,model._attrs=_.extend(model.getAttrs(),data),model._modifiedAttrs={},model.applyCasts(),defered.resolve(model)}}(this)),promise.error(function(data){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(){return function(data){return model._isModified=!1,model._attrs=_.extend(model.getAttrs(),data),model._modifiedAttrs={},model.applyCasts(),defered.resolve(model)}}(this)),promise.error(function(data){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){return model._modifiedAttrs={},model._attrs=data,model._isModified=!1,model.applyCasts(),defered.resolve(model)}),promise.error(function(data){return defered.reject(data)}),defered.promise},RepositoryService.prototype.queryMany=function(name,params,options){var httpOptions,url;return null==options&&(options={}),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){return _.map(data.data,function(x){return _this.model.make_model(name,x)})}}(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(){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.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,__hasProp={}.hasOwnProperty,__extends=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};taiga=this.taiga,StorageService=function(_super){function StorageService(){StorageService.__super__.constructor.call(this)}return __extends(StorageService,_super),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,__hasProp={}.hasOwnProperty,__extends=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};format=function(fmt,obj){return obj=_.clone(obj),fmt.replace(/%s/g,function(){return String(obj.shift())})},taiga=this.taiga,UrlsService=function(_super){function UrlsService(config){this.config=config,this.urls={},this.mainUrl=config.get("api")}return __extends(UrlsService,_super),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}(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(){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(){return function(evt){return $rootScope.$apply(function(){var data,model;file.status="done";try{data=JSON.parse(evt.target.responseText)}catch(_error){data={}}return model=$model.make_model(urlName,data),defered.resolve(model)})}}(this),uploadFailed=function(){return function(){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,$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(){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(){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){return $repo.queryOne("issues","by_ref?project="+projectId+"&ref="+ref)},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.stats=function(projectId){return $repo.queryOneRaw("projects",""+projectId+"/issues_stats")},service.filtersData=function(projectId){return $repo.queryOneRaw("projects",""+projectId+"/issue_filters_data")},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(){return deferred.resolve()}),promise.then(null,function(){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(){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,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(){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){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){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.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.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,failed,maxFileSize,response,uploadComplete,uploadFailed,uploadProgress,xhr;return defered=$q.defer(),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(){return function(evt){var message,percent;return percent=Math.round(evt.loaded/evt.total*100),message="Uloaded "+sizeFormat(evt.loaded)+" of "+sizeFormat(evt.total),statusUpdater("in-progress",null,message,percent)}}(this),uploadComplete=function(){return function(){return statusUpdater("done","Importing Project","This process can take a while, please keep the window open.")}}(this),uploadFailed=function(){return function(){return statusUpdater("error")}}(this),complete=function(){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(){return function(){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",resourceProvider])}.call(this),function(){var module,resourceProvider,taiga;taiga=this.taiga,resourceProvider=function($repo){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){var service;return service={},service["do"]=function(projectId,term){var params,url;return url=$urls.resolve("search"),params={project:projectId,text:term,get_all:!1},$http.get(url,params).then(function(data){return data.data})},function(instance){return instance.search=service}},module=angular.module("taigaResources"),module.factory("$tgSearchResourcesProvider",["$tgRepo","$tgUrls","$tgHttp",resourceProvider])}.call(this),function(){var generateHash,module,resourceProvider,taiga;taiga=this.taiga,generateHash=taiga.generateHash,resourceProvider=function($repo,$model,$storage){var hashSuffixUserstories,service;return service={},hashSuffixUserstories="userstories-queryparams",service.get=function(projectId,sprintId){return $repo.queryOne("milestones",sprintId).then(function(sprint){var uses;return service.storeUserstoriesQueryParams(projectId,{milestone:sprintId}),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).then(function(){return function(milestones){var m,uses,_i,_len;for(_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}}(this))},service.storeUserstoriesQueryParams=function(projectId,params){var hash,ns;return ns=""+projectId+":"+hashSuffixUserstories,hash=generateHash([projectId,ns]),$storage.set(hash,params)},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){return $repo.queryOne("tasks","by_ref?project="+projectId+"&ref="+ref)},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.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 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){return $repo.queryOne("userstories","by_ref?project="+projectId+"&ref="+ref)},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.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){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,__hasProp={}.hasOwnProperty,__extends=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};taiga=this.taiga,mixOf=this.taiga.mixOf,debounce=this.taiga.debounce,module=angular.module("taigaUserSettings"),UserChangePasswordController=function(_super){function UserChangePasswordController(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="Change Password",this.scope.project={},this.scope.user=this.auth.getUser(),promise=this.loadInitialData(),promise.then(null,this.onInitialDataError.bind(this))}return __extends(UserChangePasswordController,_super),UserChangePasswordController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","$tgNavUrls","$tgAuth"],UserChangePasswordController.prototype.loadProject=function(){return this.rs.projects.get(this.scope.projectId).then(function(_this){return function(project){return _this.scope.project=project,_this.scope.$emit("project:loaded",project),project}}(this))},UserChangePasswordController.prototype.loadInitialData=function(){var promise;return promise=this.repo.resolve({pslug:this.params.pslug}).then(function(_this){return function(data){return _this.scope.projectId=data.project,data}}(this)),promise.then(function(_this){return function(){return _this.loadProject()}}(this))},UserChangePasswordController}(mixOf(taiga.Controller,taiga.PageMixin)),module.controller("UserChangePasswordController",UserChangePasswordController),UserChangePasswordDirective=function($rs,$confirm,$loading){var link;return link=function($scope,$el){var submit,submitButton;return submit=debounce(2e3,function(){return function(event){var promise;return event.preventDefault(),$scope.newPassword1!==$scope.newPassword2?void $confirm.notify("error","The passwords dosn't match"):($loading.start(submitButton),promise=$rs.userSettings.changePassword($scope.currentPassword,$scope.newPassword1),promise.then(function(){return $loading.finish(submitButton),$confirm.notify("success")}),promise.then(null,function(response){return $loading.finish(submitButton),$confirm.notify("error",response.data._error_message)}))}}(this)),submitButton=$el.find(".submit-button"),$el.on("submit","form",submit),$el.on("click",".submit-button",submit),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgUserChangePassword",["$tgResources","$tgConfirm","$tgLoading",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){var submit;return $scope.$on("deletelightbox:new",function(){return lightboxService.open($el)}),$scope.$on("$destroy",function(){return $el.off()}),submit=function(){var promise;return promise=$repo.remove($scope.user),promise.then(function(){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,__hasProp={}.hasOwnProperty,__extends=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};taiga=this.taiga,mixOf=this.taiga.mixOf,sizeFormat=this.taiga.sizeFormat,module=angular.module("taigaUserSettings"),debounce=this.taiga.debounce,UserSettingsController=function(_super){function UserSettingsController(scope,rootscope,config,repo,confirm,rs,params,q,location,navUrls,auth){var maxFileSize,promise;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.scope.sectionName="User Profile",this.scope.project={},this.scope.user=this.auth.getUser(),maxFileSize=this.config.get("maxUploadFileSize",null),maxFileSize&&(this.scope.maxFileSizeMsg="[Max, size: "+sizeFormat(maxFileSize)),promise=this.loadInitialData(),promise.then(null,this.onInitialDataError.bind(this))}return __extends(UserSettingsController,_super),UserSettingsController.$inject=["$scope","$rootScope","$tgConfig","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","$tgNavUrls","$tgAuth"],UserSettingsController.prototype.loadProject=function(){return this.rs.projects.get(this.scope.projectId).then(function(_this){return function(project){return _this.scope.project=project,_this.scope.$emit("project:loaded",project),project}}(this))},UserSettingsController.prototype.loadInitialData=function(){var promise;return promise=this.repo.resolve({pslug:this.params.pslug}).then(function(_this){return function(data){return _this.scope.projectId=data.project,data}}(this)),promise.then(function(_this){return function(){return _this.loadProject()}}(this))},UserSettingsController.prototype.openDeleteLightbox=function(){return this.rootscope.$broadcast("deletelightbox:new",this.scope.user)},UserSettingsController}(mixOf(taiga.Controller,taiga.PageMixin)),module.controller("UserSettingsController",UserSettingsController),UserProfileDirective=function($confirm,$auth,$repo){var link;return link=function($scope,$el){var submit;return submit=debounce(2e3,function(){return function(event){var changeEmail,form,onError,onSuccess;return event.preventDefault(),form=$el.find("form").checksley(),form.validate()?(changeEmail=$scope.user.isAttributeModified("email"),onSuccess=function(){return $auth.setUser($scope.user),changeEmail?$confirm.success("<strong>Check your inbox!</strong><br /> We have sent a mail to your account<br /> with the instructions to set your new address"):$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),$el.on("click",".submit-button",submit),$scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgUserProfile",["$tgConfirm","$tgAuth","$tgRepo",UserProfileDirective]),UserAvatarDirective=function($auth,$model,$rs,$confirm){var link;return link=function($scope,$el){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").hide(),$confirm.notify("success")},onError=function(response){return 413===response.status&&showSizeInfo(),$el.find(".overlay").hide(),$confirm.notify("error",response.data._error_message)},$el.on("click",".button.change",function(){return $el.find("#avatar-field").click()}),$el.on("change","#avatar-field",function(){return $scope.avatarAttachment?($el.find(".overlay").css("display","flex"),$rs.userSettings.changeAvatar($scope.avatarAttachment).then(onSuccess,onError)):void 0}),$el.on("click","a.use-gravatar",function(){return $el.find(".overlay").show(),$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,__hasProp={}.hasOwnProperty,__extends=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};taiga=this.taiga,mixOf=this.taiga.mixOf,bindOnce=this.taiga.bindOnce,module=angular.module("taigaUserSettings"),UserNotificationsController=function(_super){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="Email Notifications",this.scope.project={},this.scope.user=this.auth.getUser(),promise=this.loadInitialData(),promise.then(null,this.onInitialDataError.bind(this))}return __extends(UserNotificationsController,_super),UserNotificationsController.$inject=["$scope","$rootScope","$tgRepo","$tgConfirm","$tgResources","$routeParams","$q","$tgLocation","$tgNavUrls","$tgAuth"],UserNotificationsController.prototype.loadProject=function(){return this.rs.projects.get(this.scope.projectId).then(function(_this){return function(project){return _this.scope.project=project,_this.scope.$emit("project:loaded",project),project}}(this))},UserNotificationsController.prototype.loadNotifyPolicies=function(){return this.rs.notifyPolicies.list().then(function(_this){return function(notifyPolicies){return _this.scope.notifyPolicies=notifyPolicies,notifyPolicies}}(this))},UserNotificationsController.prototype.loadInitialData=function(){var promise;return promise=this.repo.resolve({pslug:this.params.pslug}).then(function(_this){return function(data){return _this.scope.projectId=data.project,data}}(this)),promise.then(function(_this){return function(){return _this.loadProject()}}(this)).then(function(_this){return function(){return _this.loadNotifyPolicies()}}(this))},UserNotificationsController}(mixOf(taiga.Controller,taiga.PageMixin)),module.controller("UserNotificationsController",UserNotificationsController),UserNotificationsDirective=function(){var link;return link=function($scope,$el){return $scope.$on("$destroy",function(){return $el.off()})},{link:link}},module.directive("tgUserNotifications",UserNotificationsDirective),UserNotificationsListDirective=function($repo,$confirm){var link,template;return template=_.template('<% _.each(notifyPolicies, function (notifyPolicy, index) { %>\n<div class="policy-table-row" data-index="<%- index %>">\n <div class="policy-table-project"><span><%- notifyPolicy.project_name %></span></div>\n <div class="policy-table-all">\n <fieldset>\n <input type="radio"\n name="policy-<%- notifyPolicy.id %>" id="policy-all-<%- notifyPolicy.id %>"\n value="2" <% if (notifyPolicy.notify_level == 2) { %>checked="checked"<% } %>/>\n <label for="policy-all-<%- notifyPolicy.id %>">All</label>\n </fieldset>\n </div>\n <div class="policy-table-involved">\n <fieldset>\n <input type="radio"\n name="policy-<%- notifyPolicy.id %>" id="policy-involved-<%- notifyPolicy.id %>"\n value="1" <% if (notifyPolicy.notify_level == 1) { %>checked="checked"<% } %> />\n <label for="policy-involved-<%- notifyPolicy.id %>">Involved</label>\n </fieldset>\n </div>\n <div class="policy-table-none">\n <fieldset>\n <input type="radio"\n name="policy-<%- notifyPolicy.id %>" id="policy-none-<%- notifyPolicy.id %>"\n value="3" <% if (notifyPolicy.notify_level == 3) { %>checked="checked"<% } %> />\n <label for="policy-none-<%- notifyPolicy.id %>">None</label>\n </fieldset>\n </div>\n</div>\n<% }) %>'),link=function($scope,$el,$attrs){var render;return render=function(){return $el.off(),$el.html(template({notifyPolicies:$scope.notifyPolicies})),$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",UserNotificationsListDirective])}.call(this),function(){var AUTH_URL,GithubLoginButtonDirective,module,taiga;taiga=this.taiga,module=angular.module("taigaIntegrations"),AUTH_URL="https://github.com/login/oauth/authorize",GithubLoginButtonDirective=function($window,$params,$location,$config,$events,$confirm,$auth,$navUrls,$loader){var link,template;return template='<a class="button button-github" href="" title="Enter with your github account">\n <span class="icon icon-github"></span>\n <span>Login with Github</span>\n</a>',link=function($scope,$el){var clientId,loginOnError,loginOnSuccess,loginWithGitHubAccount,renderGitHubButton;return(clientId=$config.get("gitHubClientId",null))?(renderGitHubButton=function(){return clientId?$el.html(template):void 0},loginOnSuccess=function(){var nextUrl;return nextUrl=$params.next&&$params.next!==$navUrls.resolve("login")?$params.next:$navUrls.resolve("home"),$events.setupConnection(),$location.search("next",null),$location.search("token",null),$location.search("state",null),$location.search("code",null),$location.path(nextUrl)},loginOnError=function(response){return $location.search("state",null),$location.search("code",null),$loader.pageLoaded(),response.data.error_message?$confirm.notify("light-error",response.data.error_message):$confirm.notify("light-error","Our Oompa Loompas have not been able to get you credentials from GitHub.")},loginWithGitHubAccount=function(){var code,data,token,type;return type=$params.state,code=$params.code,token=$params.token,"github"===type&&code?($loader.start(),data={code:code,token:token},$auth.login(data,type).then(loginOnSuccess,loginOnError)):void 0},renderGitHubButton(),loginWithGitHubAccount(),$el.on("click",".button-github",function(){var redirectToUri,url;return redirectToUri=$location.absUrl(),url=""+AUTH_URL+"?client_id="+clientId+"&redirect_uri="+redirectToUri+"&state=github&scope=user:email",$window.location.href=url}),$scope.$on("$destroy",function(){return $el.off()})):void 0},{link:link,restrict:"EA",template:""}},module.directive("tgGithubLoginButton",["$window","$routeParams","$tgLocation","$tgConfig","$tgEvents","$tgConfirm","$tgAuth","$tgNavUrls","tgLoader",GithubLoginButtonDirective])}.call(this),function(){var configure,module,taiga;taiga=this.taiga,module=angular.module("taigaPlugins",["ngRoute"]),configure=function($routeProvider){return $routeProvider.when("/humans.html",{templateUrl:"/plugins/humanshtml/templates/humans.html"})},module.config(["$routeProvider",configure])}.call(this),function(){var TermsNoticeDirective,module,taiga,template;taiga=this.taiga,module=angular.module("taigaPlugins",["ngRoute"]),template=_.template('<p class="register-text">\n <span>By clicking "Sign up", you agree to our <br /></span>\n <a href="<%= termsUrl %>" title="See terms of service" target="_blank"> terms of service</a>\n <span> and</span>\n <a href="<%= privacyUrl %>" title="See privacy policy" target="_blank"> privacy policy.</a>\n</p>'),TermsNoticeDirective=function($config){var privacyPolicyUrl,templateFn,termsOfServiceUrl;return privacyPolicyUrl=$config.get("privacyPolicyUrl"),termsOfServiceUrl=$config.get("termsOfServiceUrl"),templateFn=function(){var ctx;
return privacyPolicyUrl&&termsOfServiceUrl?(ctx={termsUrl:termsOfServiceUrl,privacyUrl:privacyPolicyUrl},template(ctx)):""},{scope:{},restrict:"AE",template:templateFn}},module.directive("tgTermsNotice",["$tgConfig",TermsNoticeDirective])}.call(this),function(){var module;module=angular.module("taigaPlugins",["ngRoute"])}.call(this),angular.module("taigaBase").value("localesEn",{checksley:{defaultMessage:"This value seems to be invalid.","type-email":"This value should be a valid email.","type-url":"This value should be a valid url.","type-urlstrict":"This value should be a valid url.","type-number":"This value should be a valid number.","type-digits":"This value should be digits.","type-dateIso":"This value should be a valid date (YYYY-MM-DD).","type-alphanum":"This value should be alphanumeric.","type-phone":"This value should be a valid phone number.",notnull:"This value should not be null.",notblank:"This value should not be blank.",required:"This value is required.",regexp:"This value seems to be invalid.",min:"This value should be greater than or equal to %s.",max:"This value should be lower than or equal to %s.",range:"This value should be between %s and %s.",minlength:"This value is too short. It should have %s characters or more.",maxlength:"This value is too long. It should have %s characters or less.",rangelength:"This value length is invalid. It should be between %s and %s characters long.",mincheck:"You must select at least %s choices.",maxcheck:"You must select %s choices or less.",rangecheck:"You must select between %s and %s choices.",equalto:"This value should be the same."},common:{subject:"Subject",save:"Save",blocked:"Blocked",cancel:"Cancel",status:"Status","new-bulk":"New bulk insert","one-item-line":"One item per line..."},pagination:{next:"Next",prev:"Previous"},"markdown-editor":{"heading-1":"First Level Heading","heading-2":"Second Level Heading","heading-3":"Third Level Heading",bold:"Bold",italic:"Italic",strike:"Strike","bulleted-list":"Bulleted List","numeric-list":"Numeric List",picture:"Picture",link:"Link",quotes:"Quotes","code-block":"Code Block / Code",preview:"Preview",help:"Help",placeholder:"Your title here...","link-placeholder":"Your text to link here..."},us:{"title-new":"New User Story","team-requirement":"Team Requirement","client-requirement":"Client Requirement"}});
//# sourceMappingURL=app.js.map