forked from lockydl/conventions-bower
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ga-conventions.min.js
5 lines (5 loc) · 136 KB
/
ga-conventions.min.js
1
2
3
4
5
angular.module("ngAmbassador.activityFeed",["ngAmbassador.services","ngAmbassador.api"]).directive("gaActivityFeed",["$api","$timeout","$promiseKeeper",function($api,$timeout,$promiseKeeper){"use strict";return{restrict:"E",scope:{endpoint:"@",numberOfItems:"@",columns:"@",feedTitle:"@",companyCurrency:"@",companyPoints:"@",ambassadorTemplate:"=",config:"=",filters:"="},templateUrl:"../ambassador/templates/activity-feed.html",link:function(scope,element,attrs){function loadActivity(){scope.activities=[],scope.feedColumns=[];var requestData=void 0!==scope.filters?angular.copy(scope.filters):{};requestData.page_size=scope.numberOfItems;var loadingPromise=$promiseKeeper.add();$api.use("default").all(scope.endpoint).getList(requestData).then(function(data){loadingPromise.deferred.resolve(),scope.activities=data,1==scope.columns?(getOrientation(scope.activities),scope.feedColumns[0]=scope.activities):(itemsPerColumn=Math.ceil(data.length/scope.columns),splitIntoColumns(scope.activities))})}function splitIntoColumns(data){for(var i=0;i<scope.columns;i++)scope.feedColumns.push([]),angular.forEach(data,function(activity,index){index>=itemsPerColumn*i&&itemsPerColumn*(i+1)>index&&(activity.orientation="right",scope.feedColumns[i].push(activity))})}function getOrientation(data){angular.forEach(data,function(activity,index){0===index?activity.orientation="left":activity.type!==data[index-1].type?activity.orientation="left"===data[index-1].orientation?"right":"left":activity.orientation=data[index-1].orientation})}var itemsPerColumn=Math.ceil(scope.numberOfItems/scope.columns),initialized=!1;scope.$watch("filters",function(newValue,oldValue){(newValue!==oldValue||initialized===!1)&&(loadActivity(),initialized=!0)},!0),scope.activityTime=function(dateTime){var now=moment.utc(),activityTime=moment.utc(dateTime),readableDiff=0,timeUnit="seconds";return now.diff(activityTime,"years")>=1?(readableDiff=now.diff(activityTime,"years"),timeUnit=1===readableDiff?"year":"years"):now.diff(activityTime,"months")>=1?(readableDiff=now.diff(activityTime,"months"),timeUnit=1===readableDiff?"month":"months"):now.diff(activityTime,"days")>=1?(readableDiff=now.diff(activityTime,"days"),timeUnit=1===readableDiff?"day":"days"):now.diff(activityTime,"hours")>=1?(readableDiff=now.diff(activityTime,"hours"),timeUnit=1===readableDiff?"hour":"hours"):now.diff(activityTime,"minutes")>=1?(readableDiff=now.diff(activityTime,"minutes"),timeUnit=1===readableDiff?"minute":"minutes"):(readableDiff=now.diff(activityTime,"seconds"),timeUnit=1===readableDiff?"second":"seconds"),readableDiff+" "+timeUnit+" ago"}}}}]),angular.module("ngAmbassador.alerts",["duScroll"]).factory("$alertMap",function(){return{createNew:function(){var stack={app:null,page:null,form:null};return{getSystem:function(type,name){if(null===stack[type])return stack[type]={},!1;for(var key in stack[type])if(key===name)return stack[type][key];return!1},createSystem:function(type,name,update){return void 0===update&&(update=null),stack[type][name]={update:update,alerts:[],element:null},stack[type][name]},registerUpdate:function(type,name,update){return stack[type][name].update=update,stack[type][name]},removeSystem:function(type,name){delete stack[type][name]},addAlert:function(type,name,alert){stack[type][name].alerts.push(alert)},removeAlert:function(type,name,index){var system=this.getSystem(type,name);return system.alerts.splice(index,1)},getIndex:function(alert){return stack[alert.type][alert.name].alerts.indexOf(alert)},setScrollElement:function(type,name,element){stack[type][name].element=element}}}}}).factory("$alertStack",["$document","$compile","$timeout","$alertMap",function($document,$compile,$timeout,$alertMap){function startTimer(options){options.timerStart=new Date,options.alertTimer=$timeout(function(){$alertStack.close(options)},options.timerVal)}function addSystemToDom(options){var body=$document.find("body").eq(0),angularDomEl=angular.element("<alert-system></alert-system>");angularDomEl.attr("type",options.type),angularDomEl.attr("name",options.name),angularDomEl.addClass("page");var alertSystemEl=$compile(angularDomEl)(options.scope);body.append(alertSystemEl)}function addAlert(system,options){activeAlerts.addAlert(options.type,options.name,options),options.timer&&startTimer(options),null!==system.update&&system.update(system.alerts)}var activeAlerts=$alertMap.createNew(),$alertStack={};return $alertStack.getAlerts=function(type,name){var system=activeAlerts.getSystem(type,name);return system.alerts},$alertStack.registerSystem=function(type,name,update){var system=activeAlerts.getSystem(type,name);return system&&null!==system.update?update(system.alerts):system&&null===system.update?(system=activeAlerts.registerUpdate(type,name,update),update(system.alerts)):(system=activeAlerts.createSystem(type,name,update),void 0!==update&&update(system.alerts)),system},$alertStack.setScrollElement=function(type,name,element){activeAlerts.setScrollElement(type,name,element)},$alertStack.deleteSystem=function(type,name){activeAlerts.removeSystem(type,name)},$alertStack.add=function(options,checked){var waitToLoad,system=activeAlerts.getSystem(options.type,options.name);!system&&options.register?(system=$alertStack.registerSystem(options.type,options.name),addAlert(system,options)):system||options.register||void 0!==checked?system||options.register||!checked?addAlert(system,options):(addSystemToDom(options),waitToLoad=setInterval(function(){system=activeAlerts.getSystem(options.type,options.name),system&&(clearInterval(waitToLoad),addAlert(system,options))},100)):$timeout(function(){$alertStack.add(options,!0)},500),options.scroll&&(options.scrollToAlert?$document.scrollToElement(activeAlerts.getSystem(options.type,options.name).element,parseInt(options.scrollOffset,10),500):$document.scrollTo(0,0,500))},$alertStack.close=function(alert,index){void 0===index&&(index=activeAlerts.getIndex(alert)),activeAlerts.removeAlert(alert.type,alert.name,index),null!==alert.callback&&alert.callback()},$alertStack.pauseTimer=function(alerts,index){var alert=alerts[index];alert.timerVal-=new Date-alert.timerStart,alert.timer&&$timeout.cancel(alert.alertTimer)},$alertStack.resumeTimer=function(alerts,index){var alert=alerts[index];alert.timer&&startTimer(alert)},$alertStack}]).provider("$alert",function(){var $alertProvider={options:{style:"info",type:"page",name:void 0,register:!1,text:"",timer:!0,timerVal:4e3,callback:null,scroll:!1,scrollToAlert:!1,scrollOffset:15,actions:null},$get:["$rootScope","$alertStack",function($rootScope,$alertStack){var $alert={};return $alert.add=function(alertOptions){var defaultScroll=!1;angular.isUndefined(alertOptions.scroll)&&(defaultScroll="form"===alertOptions.type?!0:!1),alertOptions=angular.extend({},$alertProvider.options,alertOptions);var alertScope=(alertOptions.scope||$rootScope).$new();$alertStack.add({scope:alertScope,style:alertOptions.style,type:alertOptions.type,name:alertOptions.name,register:alertOptions.register,text:alertOptions.text,timer:alertOptions.timer,timerVal:alertOptions.timerVal,callback:alertOptions.callback,actions:alertOptions.actions,scroll:alertOptions.scroll||defaultScroll,scrollToAlert:alertOptions.scrollToAlert,scrollOffset:alertOptions.scrollOffset})},$alert.clearAll=function(type,alertSystem){var alerts=$alertStack.getAlerts(type,alertSystem),alertsToClose=[];angular.forEach(alerts,function(alert){alertsToClose.push(alert)}),angular.forEach(alertsToClose,function(alert){$alertStack.close(alert)})},$alert}]};return $alertProvider}).directive("alertSystem",["$alertStack","$timeout","$document",function($alertStack,$timeout,$document){return{restrict:"EA",template:'<div class="alert-system-inner"><alert ng-mouseenter="toggleTimer(true, $index)" ng-mouseleave="toggleTimer(false, $index)" ng-repeat="alert in alerts" ng-animate="\'alert\'" type="{{alert.style}}" close="closeAlert(alert, $index)"><i class="fa" ng-class="{\'fa-check-circle-o\': alert.style === \'success\' && !alert.snippet, \'fa-check\': alert.style === \'success\' && alert.snippet, \'fa-info-circle\': alert.style === \'info\' && !alert.snippet, \'fa-info\': alert.style === \'info\' && alert.snippet, \'fa-exclamation-circle\': alert.style === \'warning\' && !alert.snippet, \'fa-exclamation-triangle\': alert.style === \'warning\' && alert.snippet, \'fa-times\': alert.style === \'danger\', \'fa-bullhorn\': alert.banner}"></i><div class="alert-content-wrapper"><ga-value-template value="alert.text" scope-level="{{scopeLevel || 4}}"></ga-value-template><div class="alert-actions" ng-if="alert.banner && alert.actions"><i ng-if="alert.actions.accept" ng-click="alertAction(alert, $index, alert.actions.accept)" class="ion ion-ios-checkmark-outline"></i><i ng-if="alert.actions.dismiss" ng-click="alertAction(alert, $index, alert.actions.dismiss)" class="ion ion-ios-close-outline"></i></div></div></alert></div>',scope:{type:"@",name:"@",scopeLevel:"=?"},link:function(scope,elm,attrs){var type=angular.isDefined(scope.type)?scope.type:"page",name=angular.isDefined(scope.name)?scope.name:null,update=function(alerts){$timeout(function(){0!==alerts.length&&angular.isDefined(attrs.appearance)&&"snippet"===attrs.appearance&&(alerts[alerts.length-1].snippet=!0),0!==alerts.length&&angular.isDefined(attrs.appearance)&&"banner"===attrs.appearance&&(alerts[alerts.length-1].banner=!0),scope.alerts=alerts})};scope.toggleTimer=function(pause,index){var alerts=$alertStack.getAlerts(type,name);pause?$alertStack.pauseTimer(alerts,index):$alertStack.resumeTimer(alerts,index)},$alertStack.registerSystem(type,name,update),$alertStack.setScrollElement(type,name,elm),elm.addClass("alert-system"),"page"===type?elm.addClass("page"):"app"===type&&elm.addClass("app"),scope.closeAlert=function(alert,index){$alertStack.close(alert,index)},scope.alertAction=function(alert,index,action){action(),scope.closeAlert(alert,index)},scope.$on("$destroy",function(){var alerts=$alertStack.getAlerts(type,name);angular.isDefined(alerts)&&0===alerts.length&&$alertStack.deleteSystem(type,name)})}}}]).factory("$errors",["$alert",function($alert){return{output:function(options,error){var errorAlerts=[],fieldError=!1;if(error&&"object"==typeof error){for(var key in error)"detail"===key?errorAlerts.push(error[key]):"non_field_errors"===key?errorAlerts.push(error[key][0]):fieldError=!0;fieldError===!0&&errorAlerts.push("Please ensure all required fields are properly completed.")}else angular.isDefined(options.defaultMessage)?errorAlerts.push(options.defaultMessage):errorAlerts.push("Something went wrong. Please try again or contact support.");for(var i=0;i<errorAlerts.length;i++)if(2>i){var alertConfig={type:options.alertSystemType?options.alertSystemType:"page",name:options.alertSystem,timer:void 0===options.alertTimer||options.alertScroll===!0?!0:!1,timerVal:options.alertTimerVal?options.alertTimerVal:4e3,register:!0,style:"danger",text:errorAlerts[i]};angular.isDefined(options.alertScroll)&&(alertConfig.scroll=options.alertScroll),angular.isDefined(options.alertScrollToError)&&(alertConfig.scrollToAlert=options.alertScrollToError),angular.isDefined(options.alertScrollOffset)&&(alertConfig.scrollOffset=options.alertScrollOffset),"page"===alertConfig.type&&(alertConfig.register=!1),$alert.add(alertConfig)}}}}]),angular.module("ngAmbassador.api",["restangular"]).factory("$api",["Restangular","$browserDetect",function(Restangular,$browserDetect){var instances=[],$api={};return $api.create=function(config){var instance=Restangular.withConfig(function(RestangularConfigurer){RestangularConfigurer.setBaseUrl(config.url),RestangularConfigurer.setRequestSuffix("/"),RestangularConfigurer.setRestangularFields({id:"uid"}),"Explorer"===$browserDetect.name&&$browserDetect.version<=9&&(RestangularConfigurer.setJsonp(!0),RestangularConfigurer.setDefaultRequestParams("jsonp",{callback:"JSON_CALLBACK"})),RestangularConfigurer.setResponseExtractor(function(response,operation,what,url){var newResponse;return"getList"===operation?angular.isDefined(response.count)?(newResponse=response.results,newResponse.count=response.count,newResponse.next=response.next,newResponse.previous=response.previous):(newResponse=response,newResponse.count=_.size(response)):newResponse=response,newResponse})});return instance.url=config.url,"undefined"!=typeof config["default"]&&config["default"]===!0?(instance["default"]=!0,instances["default"]=instance):instance["default"]=!1,instances[config.identifier]=instance,instance},$api.use=function(identifier){var use=instances[identifier];return use.setToken=function(token){instances[identifier].token=token,use.setDefaultHeaders({Authorization:"Token "+token}),"undefined"!=typeof instances[identifier]&&instances[identifier]===!0&&(instances["default"].token=token,instances["default"].setDefaultHeaders({Authorization:"Token "+token}))},use.getToken=function(){return instances[identifier].token},use.getUrl=function(){return instances[identifier].url},use},$api}]),angular.module("ngAmbassador.buttons",["ngClipboard","angularSpinner","ngAmbassador.services"]).config(["ngClipProvider",function(ngClipProvider){ngClipProvider.setPath("bower_components/zeroclipboard/dist/ZeroClipboard.swf")}]).directive("gaButton",["$helper",function($helper){"use strict";return{restrict:"E",transclude:!0,scope:{color:"@",size:"@",loading:"=",buttonDisabled:"=",buttonClick:"&",buttonName:"@",clipboard:"=",customColor:"=",customTextColor:"=",borderWidth:"=",borderColor:"=",fontSize:"=",buttonTooltip:"@",buttonTooltipPlacement:"@"},template:function(element,attrs){var clipboardString="",clipboardClass="",tooltipString="",tooltipPlacement="";return attrs.clipboard?(clipboardString='clip-copy="clipboard"',clipboardClass="btn-clipboard"):attrs.buttonTooltip&&(tooltipString='tooltip="{{buttonTooltip}}" tooltip-is-open="!loadingDisabled"',attrs.buttonTooltipPlacement&&(tooltipPlacement='tooltip-placement="{{buttonTooltipPlacement}}"')),'<button ng-mouseover="setButtonStyle(true)" ng-mouseleave="setButtonStyle(false)" ng-style="buttonStyle" class="btn btn-{{color}} {{btnSize}} '+clipboardClass+'" '+clipboardString+' ng-class="{\'disabled\': loadingDisabled}" ng-disabled="buttonDisabled" ng-click="buttonClick({button: buttonName}); setButtonStyle();" '+tooltipString+tooltipPlacement+'><span ng-class="{ loading: loading }" ng-transclude></span><span ng-show="loading" class="btn-spinner" us-spinner="btnSpinner"></span></button>'},link:function(scope,element,attrs){switch(scope.btnClick=null,scope.loadingDisabled=!1,scope.btnSize="",scope.btnSpinner={},scope.size){case"sm":scope.btnSpinner={radius:4,width:3,length:4,lines:9};break;case"ml":scope.btnSpinner={radius:6,width:4,length:5,lines:10};break;case"lg":scope.btnSpinner={radius:9,width:5,length:5,lines:11};break;default:scope.btnSpinner={radius:5,width:3,length:4,lines:10}}switch(scope.color){case"primary":case"gray":case"danger":scope.btnSpinner.color="#ffffff";break;case"default":scope.btnSpinner.color="#666666"}scope.setButtonStyle=function(hover){scope.buttonStyle={},scope.customColor&&(hover?(scope.buttonStyle["background-color"]=$helper.colorLuminance(scope.customColor,-.1),scope.buttonStyle["border-color"]=$helper.colorLuminance(scope.customColor,-.1)):(scope.buttonStyle["background-color"]=scope.customColor,scope.buttonStyle["border-color"]=scope.customColor)),scope.customTextColor&&(scope.buttonStyle.color=scope.customTextColor,scope.btnSpinner.color=scope.customTextColor),scope.borderColor&&(scope.buttonStyle["border-color"]=scope.borderColor),scope.borderWidth&&(scope.buttonStyle["border-width"]=parseInt(scope.borderWidth)+"px"),scope.fontSize&&(scope.buttonStyle["font-size"]=parseInt(scope.fontSize)+"px")},scope.$watch("customTextColor+customColor+borderWidth+borderColor",function(){scope.setButtonStyle(!1)}),scope.$watch("loading",function(loading){loading?scope.loadingDisabled=!0:scope.loadingDisabled=!1}),"md"!==scope.size&&(scope.btnSize="btn-"+scope.size)}}}]),angular.module("ngAmbassador.charts",["ngAmbassador.services","angles"]).directive("gaLineChart",[function(){return{restrict:"E",templateUrl:"../ambassador/templates/charts/line-chart.html",replace:!1,scope:{config:"=",height:"@",width:"@"},link:function(scope,elm,attrs){var initChart=function(){scope.chartHeight=scope.height?scope.height:"150",scope.chartWidth=scope.width?scope.width:"300",scope.chart={},scope.options=scope.config.options||{},scope.chart.labels=scope.config.labels,scope.chart.datasets=[];for(var i=0;i<scope.config.datasets.length;i++){var dataset={active:!0,label:scope.config.datasets[i].label,fillColor:"rgba(255,255,255,0)",strokeColor:scope.config.datasets[i].color,pointColor:scope.config.datasets[i].color,pointStrokeColor:"#fff",pointHighlightFill:"#fff",pointHighlightStroke:scope.config.datasets[i].color,data:scope.config.datasets[i].data};scope.chart.datasets.push(dataset)}scope.chartCopy=JSON.parse(JSON.stringify(scope.chart))};scope.$watch("config",function(){initChart()}),scope.toggleDataset=function(index){scope.chartCopy.datasets[index].active=scope.chartCopy.datasets[index].active?!1:!0;for(var updatedDataset=[],activeCount=0,i=0;i<scope.chartCopy.datasets.length;i++)scope.chartCopy.datasets[i].active===!0&&(updatedDataset.push(scope.chartCopy.datasets[i]),activeCount++);activeCount>0?scope.chart.datasets=JSON.parse(JSON.stringify(updatedDataset)):scope.chartCopy.datasets[index].active=scope.chartCopy.datasets[index].active?!1:!0}}}}]).directive("gaDoughnutChart",["$helper",function($helper){return{restrict:"E",templateUrl:"../ambassador/templates/charts/doughnut-chart.html",replace:!1,scope:{config:"=",responsive:"="},link:function(scope,elm,attrs){var initChart=function(){scope.chartData=[],scope.chartDataCopy=[],scope.chartLeftLabels=[],scope.chartRightLabels=[],scope.chartResponsive=void 0===scope.responsive?!0:scope.responsive,scope.options=scope.config.options||{};for(var chartTotal=$helper.sum(scope.config.datasets,"value"),i=0;i<scope.config.datasets.length;i++){var dataset={active:!0,label:scope.config.datasets[i].label,iconClass:scope.config.datasets[i].iconClass,highlight:$helper.colorLuminance(scope.config.datasets[i].color,.1),color:scope.config.datasets[i].color,value:scope.config.datasets[i].value,percent:Math.round(scope.config.datasets[i].value/chartTotal*100)||0,id:i};scope.chartData.push(dataset),i<Math.ceil(scope.config.datasets.length/2)&&scope.chartLeftLabels.push(dataset),i>=Math.ceil(scope.config.datasets.length/2)&&scope.chartRightLabels.push(dataset)}scope.chartDataCopy=JSON.parse(JSON.stringify(scope.chartData))};scope.$watch("config",function(){initChart()}),scope.toggleDataset=function(index){scope.chartDataCopy[index].active=scope.chartDataCopy[index].active?!1:!0;for(var updatedDataset=[],activeCount=0,i=0;i<scope.chartDataCopy.length;i++)scope.chartDataCopy[i].active===!0&&(updatedDataset.push(scope.chartDataCopy[i]),activeCount++);activeCount>0?scope.chartData=JSON.parse(JSON.stringify(updatedDataset)):scope.chartDataCopy[index].active=scope.chartDataCopy[index].active?!1:!0},scope.checkActive=function(index){return scope.chartDataCopy[index].active}}}}]),angular.module("ngAmbassador.constants",[]).constant("CONVENTIONS_ENV","production"),angular.module("ngAmbassador.file",["angularFileUpload","ngAmbassador.api"]).factory("$file",["$upload","$api",function($upload,$api){var $file={};return $file.download=function(url){var hiddenIFrameID="ga-download",iframe=document.getElementById(hiddenIFrameID);null===iframe&&(iframe=document.createElement("iframe"),iframe.id=hiddenIFrameID,iframe.style.display="none",document.body.appendChild(iframe)),iframe.src=url},$file.upload=function(config){return config.headers={Authorization:"Token "+$api.use("default").getToken()},$upload.upload(config)},$file}]),angular.module("ngAmbassador.filters",[]).filter("capitalize",[function(){return function(input){return void 0!==input?(null!==input&&(input=input.toLowerCase()),input.substring(0,1).toUpperCase()+input.substring(1)):void 0}}]).filter("fileSize",[function(){return function(input){if(void 0!==input){var b=Math,c=b.log,d=1e3,e=c(input)/c(d)|0;return(input/b.pow(d,e)).toFixed(2)+" "+(e?"kMGTPEZY"[--e]+"B":"Bytes")}}}]),angular.module("ngAmbassador.forms",["ngAmbassador.constants","colorpicker.module","toggle-switch","ngAmbassador.services","ngAmbassador.api"]).factory("$validationUtilities",["$q","$api",function($q,$api){return{doesAmbassadorEmailExist:function(value,originalValue){var deferred=$q.defer();return value===originalValue?deferred.resolve():$api.use("default").all("ambassadors").getList({email:value}).then(function(data){data.count>=1&&value!==originalValue?deferred.reject("This email address already exists."):deferred.resolve()}),deferred.promise},doesTeamMemberExist:function(value,originalValue){var deferred=$q.defer();return value===originalValue?deferred.resolve():$api.use("default").all("team").getList({email:value}).then(function(data){data.count>=1&&value!==originalValue?deferred.reject("Email address is already in use by another user."):deferred.resolve()}),deferred.promise},dropdownItemSelected:function(value){var deferred=$q.defer();return void 0===value?deferred.reject("You must make a selection."):deferred.resolve(),deferred.promise},gaSelectItemSelected:function(value,originalValue,multi){function isEmptyObject(obj){var key;for(key in obj)return!1;return!0}var deferred=$q.defer();return 0===value.length||isEmptyObject(value)?deferred.reject("You must make a selection."):deferred.resolve(),deferred.promise},isInteger:function(value){var deferred=$q.defer(),integer_regex=/^-?\d+$/;return integer_regex.test(value.trim())?deferred.resolve():deferred.reject("Invalid number. Please enter a whole number."),deferred.promise},isIntegerOrFloat:function(value){var deferred=$q.defer(),float_regex=/^-?\d+\.?\d+?$/,integer_regex=/^-?\d+$/;return float_regex.test(value.trim())||integer_regex.test(value.trim())?deferred.resolve():deferred.reject("Invalid format. Please enter a whole or decimal number."),deferred.promise},isLessThanMaxLength:function(value,originalValue,additionalParams){var deferred=$q.defer();return value.length>additionalParams.maxLength?deferred.reject("You may only use up to "+additionalParams.maxLength+" characters."):deferred.resolve(),deferred.promise},isLessThanMaxNumber:function(value,originalValue,additionalParams){var deferred=$q.defer(),dollarValue=parseInt(value,10);return dollarValue>additionalParams.maxNumber?deferred.reject("Number cannot be larger than "+additionalParams.maxNumber+"."):deferred.resolve(),deferred.promise},isNotEmpty:function(value){var deferred=$q.defer();return value.toString().trim().length>0?deferred.resolve():deferred.reject("The field must not be empty."),deferred.promise},isEqualTo:function(value,originalValue,additionalParams){var deferred=$q.defer();return void 0!==additionalParams.comparison&&value.toString()===additionalParams.comparison.toString()?deferred.resolve():deferred.reject("The passwords do not match."),deferred.promise},isRequiredIf:function(value,originalValue,additionalParams){var deferred=$q.defer();return void 0===additionalParams.parentField||0===additionalParams.parentField.toString().length||additionalParams.parentField.toString().length>0&&value.toString().length>0?deferred.resolve():deferred.reject("This field is required."),deferred.promise},isNotFutureDate:function(date){var deferred=$q.defer(),today=new Date,dateInFuture=!1;if(date instanceof Array)for(var i=0;i<date.length;i++){if(new Date(date[i]).setHours(0,0,0,0)>today.setHours(0,0,0,0)){deferred.reject(),dateInFuture=!0;break}i!==date.length-1||dateInFuture||deferred.resolve()}else new Date(date).setHours(0,0,0,0)>today.setHours(0,0,0,0)?deferred.reject():deferred.resolve();return deferred.promise},isValidCreditCard:function(value,originalValue){var deferred=$q.defer();if(value===originalValue)deferred.resolve();else{/[^0-9-\s]+/.test(value.trim())&&deferred.reject("Invalid credit card number.");var nCheck=0,nDigit=0,bEven=!1;value=value.replace(/\D/g,"");for(var n=value.length-1;n>=0;n--){var cDigit=value.charAt(n);nDigit=parseInt(cDigit,10),bEven&&(nDigit*=2)>9&&(nDigit-=9),nCheck+=nDigit,bEven=!bEven}nCheck%10===0?deferred.resolve():deferred.reject("Invalid credit card number.")}return deferred.promise},isValidEmail:function(value){var deferred=$q.defer(),re=/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;return re.test(value.trim())?deferred.resolve():deferred.reject("Invalid email address."),deferred.promise},isValidUrl:function(value){var deferred=$q.defer(),re=/^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i;return re.test(value.trim())?deferred.resolve():deferred.reject('Invalid url. Please use the format "http(s)://url.com".'),deferred.promise},isValidUrlWithoutProtocol:function(value){var deferred=$q.defer(),re=/^(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i;return re.test(value.trim())?deferred.resolve():deferred.reject('Invalid url. Please use the format "url.com or subdomain.url.com".'),deferred.promise},isValidUrlWithSubdomain:function(value){var deferred=$q.defer(),re=/^(?!\-)(?:[a-zA-Z\d\-]{0,62}[a-zA-Z\d]\.){2,126}(?!\d+)[a-zA-Z\d]{1,63}$/i;return re.test(value.trim())?deferred.resolve():deferred.reject('Invalid url. The url must contain a subdomain. Please use the format "subdomain.url.com".'),deferred.promise},isUrl:function(value){var deferred=$q.defer(),withProtocol=/^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i,withoutProtocol=/^(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i;return withProtocol.test(value.trim())||withoutProtocol.test(value.trim())?deferred.resolve():deferred.reject("Invalid url."),deferred.promise},isZipCode:function(value){var deferred=$q.defer(),re=/^\d{5}([\-]?\d{4})?$/;return re.test(value.trim())?deferred.resolve():deferred.reject("Invalid zip code. Please follow the XXXXX-XXXX format (with last 4 digits optional)."),deferred.promise},validDollarAmount:function(value,originalValue){var deferred=$q.defer(),currency_regex=/^-?\d{1,6}\.?\d{1,2}?$/,integer_regex=/^-?\d+$/;return currency_regex.test(value.trim())||integer_regex.test(value.trim())?deferred.resolve():deferred.reject("Invalid format. Please enter a whole number, or a number in the format 'xx.xx'."),deferred.promise},validEmailOrShortcode:function(value,originalValue){var deferred=$q.defer(),error_message="",re=/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,search_object={},key=re.test(value.trim())?"email":"short_code";return search_object[key]=value,error_message="email"===key?"Referring ambassador with this email does not exist.":"Short code does not exist or the email is incomplete.",$api.use("default").all("ambassadors").getList(search_object).then(function(data){0===data.count?deferred.reject(error_message):deferred.resolve()},function(error){deferred.reject(error_message)}),deferred.promise},containsTags:function(value,originalValue,additionalParams){var deferred=$q.defer(),tagsContained=0,missingTags=[];return angular.forEach(additionalParams.requiredTags,function(tag){value.indexOf("{"+tag+"}")>-1?tagsContained++:missingTags.push("{"+tag+"}")}),tagsContained===additionalParams.requiredTags.length?deferred.resolve():deferred.reject("Not all required tags are present. Missing tags: "+missingTags.join(", ")),
deferred.promise}}}]).directive("gaFormField",["$q","$timeout","$compile","$helper",function($q,$timeout,$compile,$helper){return{restrict:"E",replace:!0,scope:{isDisabled:"=?",isReadonly:"=?",extraClasses:"@",fieldType:"@?",helpText:"@?",label:"@?",defaultDropdownText:"@?",model:"=?",modelValue:"@",modelText:"@",showModelValue:"=?",additionalParams:"=?",callbackFunction:"&",options:"=?",pristine:"=",isRequired:"@?",isRequiredIf:"=?",isRequiredIfField:"=?",requiredText:"@?",rules:"=?",equalTo:"=?",stateClasses:"=?",validatedField:"=",validationThreshold:"@?",validationWait:"@?",showPasswordStrength:"@?",placeholder:"@?",showAsterisks:"=",trim:"@?",errorMessage:"=?",loading:"=?",radioConfig:"=?"},link:function(scope,element,attrs,ctrl){function get_template(){var disabledString=void 0!==scope.isDisabled?"ng-disabled='disableField'":"",readonlyString=void 0!==scope.isReadonly?"ng-readonly='readonlyField'":"",trueValueString="undefined"!=typeof scope.additionalParams&&"undefined"!=typeof scope.additionalParams.trueValue?' ng-true-value="{{additionalParams.trueValue}}"':"",falseValueString="undefined"!=typeof scope.additionalParams&&"undefined"!=typeof scope.additionalParams.falseValue?' ng-false-value="{{additionalParams.falseValue}}"':"",colorpickerString="colorpicker"===scope.fieldType?" colorpicker ":"";colorpickerString+=void 0!==scope.additionalParams&&void 0!==scope.additionalParams.appendToParent&&scope.additionalParams.appendToParent===!1?"":'colorpicker-parent="true" ';var colorPreviewString='<div class=\'color-preview\' ng-style=\'{"background-color": model || "#ffffff", "border-color": colorPreviewBorderColor || "#e1e1e1"}\'></div>',caretChevronClass=attrs.hasOwnProperty("appearance")&&"snippet"===attrs.appearance?"fa fa-chevron-down":"caret",errorIcon=attrs.hasOwnProperty("appearance")&&"snippet"===attrs.appearance?"fa-exclamation-triangle":"fa-exclamation",calendarIcon=attrs.hasOwnProperty("appearance")&&"snippet"===attrs.appearance?"fa fa-calendar":"glyphicon glyphicon-calendar",autoExpandString="undefined"!=typeof scope.additionalParams&&"undefined"!=typeof scope.additionalParams.textExpand&&scope.additionalParams.textExpand===!0?" expand-textarea ":"",input_template="<div class='inner-field-wrapper {{ extraClasses }}' ng-class='{\"inner-field-loading\":loading}'> <input ng-trim='{{trimValue}}' ng-model='model' placeholder='{{ placeholder }}' class='form-control' type='text' "+disabledString+readonlyString+colorpickerString+">"+colorPreviewString+" <i ng-show=\"state=='working' || loading\" class='fa fa-refresh fa-spin'></i> <i ng-show=\"state=='success'\" class='fa fa-check'></i> <i ng-show=\"state=='error'\" class='fa "+errorIcon+"'></i></div><span class='help-block'>{{ helpText }}</span>",textarea_template="<div class='inner-field-wrapper {{ extraClasses }}'> <textarea ng-model='model' class='form-control'"+autoExpandString+disabledString+readonlyString+" placeholder='{{ placeholder }}'></textarea></div><span class='help-block'>{{ helpText }}</span>",redactor_template='<div class=\'inner-field-wrapper {{ extraClasses }}\'> <div class="redactor-disabled-overlay" ng-if="isDisabled"></div> <textarea ng-hide="!redactorLoaded" ng-model="model" ga-redactor="redactorConfig" placeholder="{{ placeholder }}"></textarea></div><span class=\'help-block\'>{{ helpText }}</span>',select_template="";if(scope.options){if(scope.dropdown={isOpen:!1},"simple-select"===scope.fieldType){var model_value=scope.modelValue?scope.modelValue:"value",model_text=scope.modelText?scope.modelText:"text";select_template="<div class='inner-field-wrapper {{ extraClasses }}'> <div class='dropdown dropdown-select dropdown-form' is-open='dropdown.isOpen' ng-class='{disabled: isDisabled}'> <a class='dropdown-toggle btn btn-default' "+disabledString+"> <span ng-if='defaultDropdownText && !model'>{{defaultDropdownText}}</span> <span ng-if='showModelValue && model'>{{model."+model_value+"}} - </span>{{model."+model_text+"}} <span class='"+caretChevronClass+"'></span> </a> <ul class='dropdown-menu'> <li ng-repeat='o in options'> <a ng-click='selectItem(o, true)'><span ng-if='showModelValue'>{{o."+model_value+"}} - </span>{{o."+model_text+"}}</a> </li> </ul> </div></div>"}else select_template="<div class='inner-field-wrapper {{ extraClasses }}'> <div class='dropdown dropdown-select dropdown-form' is-open='dropdown.isOpen' ng-class='{disabled: isDisabled}'> <a class='dropdown-toggle btn btn-default' "+disabledString+"> {{modelLabel || defaultDropdownText || 'Select one'}} <span class='"+caretChevronClass+"'></span> </a> <ul class='dropdown-menu'> <li ng-repeat='o in options'> <a ng-click='selectItem(o, false)'>{{o.name}}</a> </li> </ul> </div></div>";select_template+="<span class='help-block'>{{ helpText }}</span>"}var gaselect_template="<div class='inner-field-wrapper {{ extraClasses }}'> <ga-select model='model' endpoint='{{additionalParams.config.endpoint}}' comparator='{{additionalParams.config.comparator}}' is-disabled='isDisabled' data='additionalParams.config.data' multi='{{additionalParams.config.multi}}' placeholder='{{additionalParams.config.placeholder}}' label='{{additionalParams.config.label}}'></ga-select></div><span class='help-block'>{{ helpText }}</span>",checkbox_template="<div class='form-group checkbox-group no-label'> <div class='inner-field-wrapper {{ extraClasses }}'> <div class='input-group'> <span class='input-group-addon' ng-class='{disabled: isDisabled}'><div><input ng-model='model' id='"+scope.$id+"' "+disabledString+trueValueString+falseValueString+" type='checkbox' ng-change='callback(model)'><label for='"+scope.$id+"'></label></div></span> <label class='form-control' "+disabledString+" for='"+scope.$id+"'>"+scope.label+"<span ng-if='showAsterisks!==false'>{{labelSuffix}}</span></label> </div> </div> <span class='help-block'>{{ helpText }}</span></div>",password_template="<div class='inner-field-wrapper {{ extraClasses }}'> <input ng-model='model' class='form-control' "+disabledString+" type='password' placeholder='{{ placeholder }}'>";"true"===scope.showPasswordStrength&&(password_template+="<span ga-password-strength='model' id='password-strength' class='label label-input'></span>"),password_template+="</div><span class='help-block'>{{ helpText }}</span>";var password_conf_template="<div class='inner-field-wrapper {{ extraClasses }}'> <input ng-model='model' class='form-control' "+disabledString+" type='password' placeholder='{{ placeholder }}'> <i ng-show='state==\"working\"' class='fa fa-refresh fa-spin'></i> <i ng-show='state==\"success\"' class='fa fa-check'></i> <i ng-show='state==\"error\"' class='fa "+errorIcon+"'></i></div><span class='help-block'>{{ helpText }}</span>",datepicker_template="<div class='inner-field-wrapper datepicker-field {{ extraClasses }}'>";scope.additionalParams&&scope.additionalParams.calendarButton&&(datepicker_template+="<div class='input-group'>"),datepicker_template+="<input type='text' "+disabledString+" class='form-control' placeholder='{{ placeholder }}' datepicker-popup='{{additionalParams.format || \"MM-dd-yyyy\"}}' datepicker-options='additionalParams.dateOptions' is-open='additionalParams.isOpen' ng-click='toggleDatepicker($event, true)' show-button-bar='false' ng-model='model' min-date='additionalParams.minDate' max-date='additionalParams.maxDate' />",scope.additionalParams&&scope.additionalParams.calendarButton&&(datepicker_template+=" <span class='input-group-btn'> <button type='button' "+disabledString+" class='btn btn-default' ng-click='toggleDatepicker($event)'><i class='"+calendarIcon+"'></i></button> </span> </div>"),datepicker_template+="</div><span class='help-block'>{{ helpText }}</span>",radio_template="<div class='mbsy-radio-group'> <label class='mbsy-radio' ng-class='{disabled: isDisabled}' ng-repeat='radio in radioConfig.buttons' for='{{radio.id}}'> <input "+disabledString+" type='radio' ng-model='$parent.model' ng-change='radioChange(radio.value)' ng-value='radio.value' name='{{radioConfig.name}}' id='{{radio.id}}'/> <span>{{radio.label}}</span> </label></div><span class='help-block'>{{ helpText }}</span>";var template="<div class='form-group'> <label ng-if='label'>"+scope.label+"<span ng-if='showAsterisks!==false'>{{labelSuffix}}</span></label> <div class='async-loader'>";return"textarea"===scope.fieldType?template+=textarea_template:"ga-redactor"===scope.fieldType?template+=redactor_template:"select"===scope.fieldType||"simple-select"===scope.fieldType?template+=select_template:"ga-select"===scope.fieldType?template+=gaselect_template:"password"===scope.fieldType?template+=password_template:"date"===scope.fieldType?("undefined"!=typeof scope.additionalParams.dateOptions?scope.additionalParams.dateOptions.showWeeks=!1:scope.additionalParams.dateOptions={showWeeks:!1},template+=datepicker_template):"checkbox"===scope.fieldType?template=checkbox_template:"password-conf"===scope.fieldType?(scope.$watch("equalTo",function(value){scope.additionalParams={comparison:scope.equalTo},value&&scope.model&&(scope.model="",validate("change"))}),template+=password_conf_template):template+="radio"===scope.fieldType?radio_template:input_template,void 0!==scope.isRequiredIf&&scope.$watch("isRequiredIfField",function(value){if(value)scope.labelSuffix="*",scope.validatedField=!1,required=!0;else{scope.labelSuffix="",scope.validatedField=!0,required=!1;for(var key in scope.stateClasses)element.removeClass(scope.stateClasses[key]),labelElement.removeClass(scope.stateClasses[key]);scope.state="",scope.helpText=void 0===originalHelpText?"":originalHelpText}scope.additionalParams={parentField:value}}),"checkbox"!==scope.fieldType&&(template+=" </div></div>"),template}function getTypeLabel(type){angular.forEach(scope.options,function(commissionType){type===commissionType.value&&(scope.modelLabel=commissionType.name)}),angular.isUndefined(scope.modelLabel)&&(scope.modelLabel="Select one")}function get_field_type(){return"password"===scope.fieldType||"password-conf"===scope.fieldType?element.find("input"):element.find(scope.fieldType)}function bind_events(){function waitForDirective(){0===element.find("input").length?$timeout(function(){waitForDirective()},500):typeaheadBinding()}function typeaheadBinding(){element.find("input").bind("blur",function(){function validateOnBlur(){0===element.find("ul").length?validate("blur"):$timeout(function(){validateOnBlur()},50)}validateOnBlur()}),element.find("input").bind("focus",function(){fieldPristine&&(originalValue=angular.copy(scope.model),fieldPristine=!1)})}("select"===scope.fieldType||"simple-select"===scope.fieldType)&&inputElement.bind("change",validate),"ga-select"!==scope.fieldType?(inputElement.bind("blur keyup",function(evt){if(timer&&$timeout.cancel(timer),"blur"===evt.type)validate(evt);else if(9!==evt.keyCode){var validationWait=1500;void 0!==scope.validationWait&&(validationWait=parseInt(scope.validationWait,10)),timer=$timeout(function(){(""!==inputElement[0].value||required===!0)&&validate(evt)},validationWait)}}),inputElement.bind("focus",function(){fieldPristine&&(originalValue=angular.copy(scope.model),fieldPristine=!1)})):(!scope.additionalParams.config.data||scope.additionalParams.config.data.length>=25)&&waitForDirective()}function handle_error(error){$timeout(function(){scope.state="error",scope.helpText=void 0!==scope.additionalParams&&void 0!==scope.additionalParams.errorMessage?scope.additionalParams.errorMessage:error,scope.validatedField=!1,element.addClass(scope.stateClasses.error),labelElement.addClass(scope.stateClasses.error)})}function initialize(){if(void 0===scope.stateClasses)scope.stateClasses=defaultStateClasses;else for(var key in defaultStateClasses)scope.stateClasses.hasOwnProperty(key)||(scope.stateClasses[key]=defaultStateClasses[key]);scope.validationThreshold=void 0===scope.validationThreshold?1:parseInt(scope.validationThreshold,10),required="true"===scope.isRequired?!0:!1}function success(){scope.state="success",scope.helpText=originalHelpText,element.removeClass(scope.stateClasses.error),scope.validatedField=!0,element.addClass(scope.stateClasses.success),labelElement.removeClass(scope.stateClasses.error)}function getValue(evt){var value=null;if("select"===scope.fieldType||"ga-select"===scope.fieldType||"radio"===scope.fieldType||"ga-redactor"===scope.fieldType)value=scope.model;else if("simple-select"===scope.fieldType)value="undefined"==typeof scope.model||""===scope.model?"":scope.modelText?scope.model[scope.modelText]:scope.model.name;else if(void 0!==evt.target)try{value=evt.srcElement.value}catch(e){value=evt.target.value}else value=scope.model;return value}function validate(evt){if(scope.rules.length>0){var value=null,result=null,first=!0;value=getValue(evt),scope.validatedField=!0,scope.pristine=!1,required===!0&&angular.isDefined(value)&&(""===value||"function"==typeof value.trim&&0===value.trim().length||value===!1&&"radio"!==scope.fieldType||"ga-select"===scope.fieldType&&_.isEmpty(value))?handle_error(scope.requiredText?scope.requiredText:"This field is required."):""!==value&&scope.rules.length>0?(scope.state="working",("change"===evt.type||"blur"===evt.type||void 0!==value&&value.toString().length>=scope.validationThreshold||void 0!==value)&&(angular.forEach(scope.rules,function(validation_function,key){first?(result=validation_function(value,originalValue,scope.additionalParams),first=!1):result=result.then(function(){return validation_function(value,originalValue,scope.additionalParams)})}),scope.rules.length>0&&result.then(success,handle_error))):(scope.clearValidationErrors(),scope.$$phase||"checkbox"===scope.fieldType||$timeout(function(){scope.$apply()},0))}else{var value=getValue(evt);required===!0&&angular.isDefined(value)&&(""===value||"function"==typeof value.trim&&0===value.trim().length||value===!1&&"radio"!==scope.fieldType||"ga-select"===scope.fieldType&&_.isEmpty(value))?handle_error(scope.requiredText?scope.requiredText:"This field is required."):required!==!0||angular.isUndefined(value)&&"radio"===scope.fieldType||success()}}if(scope.disableField=!1,angular.isUndefined(scope.rules)&&(scope.rules=[]),scope.$watch("isDisabled",function(){scope.disableField=scope.isDisabled}),scope.$watch("isReadonly",function(){scope.readonlyField=scope.isReadonly}),scope.trimValue="true"===scope.trim?!1:!0,"ga-redactor"===scope.fieldType){var validateRedactor,tagAdded=!1;scope.redactorConfig={blurCallback:function(e){scope.$broadcast("REDACTOR_CHANGE",{event:e.type})}},angular.extend(scope.redactorConfig,scope.additionalParams.redactorConfig),scope.$on("TAG_ADDED",function(event){tagAdded=!0})}scope.$on("REDACTOR_CHANGE",function(event,args){validate(args.event)}),scope.selectItem=function(item,simpleSelect){simpleSelect?scope.model=item:(scope.modelLabel=item.name,scope.model=item.value),scope.dropdown.isOpen=!1,"function"==typeof scope.callbackFunction&&scope.callbackFunction({selected:item}),validate("change")},scope.toggleDatepicker=function($event,openDatepicker){$event.preventDefault(),$event.stopPropagation(),scope.additionalParams.isOpen=openDatepicker?openDatepicker:!scope.additionalParams.isOpen},scope.callback=function(checked){"function"==typeof scope.callbackFunction&&scope.callbackFunction({selected:checked})},scope.radioChange=function(value){"function"==typeof scope.radioConfig.callback&&scope.radioConfig.callback(value)},scope.$watch("model",function(newValue,oldValue){if("undefined"==typeof newValue||"string"==typeof newValue||"undefined"==typeof scope.additionalParams||"undefined"==typeof scope.additionalParams.trueValue&&"undefined"==typeof scope.additionalParams.falseValue||(scope.model=scope.model.toString()),"true"===scope.trim&&void 0!==newValue&&(scope.model=newValue.trim()),void 0!==scope.additionalParams&&scope.additionalParams.config&&newValue!==oldValue&&$timeout(function(){validate("change")},0),("checkbox"===scope.fieldType&&newValue!==oldValue||"date"===scope.fieldType||"radio"===scope.fieldType)&&validate("change"),angular.isDefined(scope.model)&&"select"===scope.fieldType&&getTypeLabel(scope.model),"colorpicker"===scope.fieldType){var color=scope.model||"#ffffff";scope.colorPreviewBorderColor=$helper.colorLuminance(color,-.2)}if("ga-redactor"===scope.fieldType){var delay=tagAdded?0:1500;void 0!==validateRedactor&&$timeout.cancel(validateRedactor),validateRedactor=$timeout(function(){validate("change"),tagAdded=!1},delay)}scope.errorMessage=""},!0),void 0===scope.fieldType&&(scope.fieldType="input"),"true"===scope.isRequired&&(scope.labelSuffix="*"),element.html(get_template()),$compile(element.contents())(scope);var defaultStateClasses={error:"has-error",success:"has-success",working:"working"},fieldPristine=!0,inputElement=get_field_type(),labelElement=element.find("label"),originalHelpText=scope.helpText,originalValue=fieldPristine&&null!==scope.model?angular.copy(scope.model):"",required=null,timer=null;scope.clearValidationErrors=function(){if("undefined"==typeof scope.errorMessage||""===scope.errorMessage||null===scope.errorMessage){for(var key in scope.stateClasses)element.removeClass(scope.stateClasses[key]),labelElement.removeClass(scope.stateClasses[key]);scope.state="",scope.helpText=void 0===originalHelpText?"":originalHelpText,scope.validatedField=!0}},scope.$watch("errorMessage",function(newValue,oldValue){if(angular.isDefined(scope.errorMessage))if(""!==scope.errorMessage&&void 0!==validateRedactor&&$timeout.cancel(validateRedactor),""!==newValue&&null!==newValue){var errorMsg=angular.isArray(newValue)===!0?newValue[0]:newValue;handle_error(errorMsg)}else{var value=getValue("change");required&&(required&&angular.isDefined(value)&&(""===value||"function"==typeof value.trim&&0===value.trim().length||value===!1)||!angular.isDefined(value))||"ga-select"===scope.fieldType&&_.isEmpty(value)||scope.clearValidationErrors()}}),initialize(),bind_events()}}}]).directive("gaPasswordStrength",[function(){return{replace:!1,restrict:"A",scope:{gaPasswordStrength:"="},link:function(scope,elem,attrs){var strength={text:["Weak","Acceptable","Strong","Very Strong"],classes:["danger","warning","primary","success"],mesureStrength:function(p){for(var _force=0,_regex=/[$-/:-?{-~!""^_`\[\]]/g,_lowerLetters=/[a-z]+/.test(p),_upperLetters=/[A-Z]+/.test(p),_numbers=/[0-9]+/.test(p),_symbols=_regex.test(p),_flags=[_lowerLetters,_upperLetters,_numbers,_symbols],_passedMatches=0,i=0;i<_flags.length;i++)_flags[i]===!0&&_passedMatches++;return _force+=2*p.length+(p.length>=10?1:0),_force+=10*_passedMatches,_force=p.length<=6?Math.min(_force,10):_force,_force=1===_passedMatches?Math.min(_force,10):_force,_force=2===_passedMatches?Math.min(_force,20):_force,_force=3===_passedMatches?Math.min(_force,40):_force},getColor:function(s){var idx=0;return idx=10>=s?0:20>=s?1:40>=s?2:3,{idx:idx+1,text:this.text[idx],color_class:this.classes[idx]}}};scope.$watch("gaPasswordStrength",function(){if(""===scope.gaPasswordStrength||"undefined"==typeof scope.gaPasswordStrength)elem.css({display:"none"});else{var c=strength.getColor(strength.mesureStrength(scope.gaPasswordStrength));elem.css({display:"inline"}),elem.removeClass("label-danger").removeClass("label-warning").removeClass("label-info").removeClass("label-primary").removeClass("label-success").removeClass("label-warning").addClass("label label-"+c.color_class).text(c.text)}})}}}]).directive("gaSelect",["$api","$q",function($api,$q){"use strict";return{restrict:"E",scope:{model:"=",data:"=",defaultOption:"=",endpoint:"@",multi:"@",label:"@",placeholder:"@",comparator:"@",resetDisabled:"=",search:"&",isDisabled:"=",property:"@",resultModel:"=",noItemsText:"=?",displaySelectedAs:"@",noItemsCallback:"&?",resultClasses:"=?",allowInputValue:"=?",searchProperties:"=?",sortBy:"@?",filterParams:"=?",maxItemListHeight:"@?",validPattern:"=?"},templateUrl:"../ambassador/templates/directive.chooser.html",replace:!1,link:function(scope,element,attrs){function setBinding(){waitForInputEl(),element.find("input").bind("keydown",function(e){13!==e.keyCode&&element.removeClass("has-error")})}function setClasses(){if(scope.resultClasses){var classes=[];angular.forEach(scope.resultClasses,function(resultClass){classes.push("'"+resultClass["class"]+"':"+(resultClass.negate?"!":"")+(scope.dropdown.isEnabled?"item.":"match.model.")+resultClass.condition)}),scope.classesString="{"+classes.join()+"}"}}function handleEmptyDropdown(show){scope.dropdown.isEnabled&&(show?(scope.noItemsText="undefined"==typeof scope.noItemsText||""===scope.noItemsText||null===scope.noItemsText?"Nothing to select":scope.noItemsText,scope.hideDropdown=!1,scope.showNoItemsMessage=!0):"undefined"==typeof scope.noItemsText||""===scope.noItemsText||null===scope.noItemsText?(scope.hideDropdown=!0,scope.showNoItemsMessage=!1):(scope.hideDropdown=!1,scope.showNoItemsMessage=!0))}scope.callbackDefined="undefined"==typeof attrs.noItemsCallback?!1:!0,scope.predicate="undefined"!=typeof scope.sortBy?scope.sortBy:scope.label,scope.dropdown={isEnabled:!1,isOpen:!1},scope.loadingItems=!1,scope.selected={},scope.originalPlaceholder=scope.placeholder,scope.typeaheadTemplate="../ambassador/templates/directive.chooser.typeahead.html";var abortSearch;if(scope.placeListBeneath=attrs.hasOwnProperty("newLook"),scope.isManualEntry=attrs.hasOwnProperty("manualEntry"),scope.isManualEntry){scope.entered={isValid:function(){var valid=scope.validPattern?this.value.match(scope.validPattern):!0;return valid||element.addClass("has-error"),valid},value:""};var waitForInputEl=scope.$watch(function(){return element.find("input").length>0?!0:!1},function(inputEl){inputEl&&setBinding()})}element.bind("keydown",function(e){if((38===e.keyCode||40===e.keyCode)&&element[0].getElementsByClassName("dropdown-menu").length>0){var dropdownElem=element[0].getElementsByClassName("dropdown-menu")[0].getBoundingClientRect(),activeElem=element[0].getElementsByClassName("active")[0].getBoundingClientRect();activeElem.top+activeElem.height>dropdownElem.top+dropdownElem.height&&(element[0].getElementsByClassName("dropdown-menu")[0].scrollTop+=activeElem.top+activeElem.height-(dropdownElem.top+dropdownElem.height)),activeElem.top<dropdownElem.top&&(element[0].getElementsByClassName("dropdown-menu")[0].scrollTop-=dropdownElem.top-activeElem.top)}}),"undefined"==typeof scope.searchProperties&&(scope.searchProperties=[scope.label]),scope.$watch("model",function(){scope.showReset="undefined"!=typeof scope.model[scope.label]&&"undefined"!=typeof scope.model||scope.allowInputValue&&"string"==typeof scope.model&&""!==scope.model?!0:!1,scope.placeholder=scope.multi!==!0&&"undefined"!=typeof scope.model&&scope.model[scope.label]?scope.model[scope.label]:scope.originalPlaceholder,"undefined"!=typeof scope.model&&"undefined"!=typeof scope.property&&(scope.multi!==!0&&"true"!==scope.multi&&"object"==typeof scope.model?scope.resultModel=scope.model[scope.property]:scope.allowInputValue?scope.resultModel=scope.model:(scope.resultModel=[],angular.forEach(scope.model,function(item){scope.resultModel.push(item[scope.property])}))),scope.data&&scope.data.length===scope.model.length&&handleEmptyDropdown(!0)},!0),scope.allowInputValue&&scope.$watch("selected.item",function(value){"undefined"!=typeof value&&"object"!=typeof value&&(scope.model=value)}),scope.multi!==!0&&scope.model[scope.label]&&(scope.placeholder=scope.model[scope.label]),scope.$watch("data",function(data){data&&(data.length<25?scope.dropdown.isEnabled=!0:scope.dropdown.isEnabled=!1,0===data.length?handleEmptyDropdown():scope.data.length===scope.model.length?handleEmptyDropdown(!0):(scope.hideDropdown=!1,scope.showNoItemsMessage=!1)),setClasses()},!0),scope.$watch("noItemsText",function(){scope.data&&0===scope.data.length&&handleEmptyDropdown()}),scope.noItemsFunction=function(){scope.dropdown.isOpen=!1,"function"==typeof scope.noItemsCallback&&scope.noItemsCallback()},scope.removeItem=function(item){var index=scope.model.indexOf(item);scope.model.splice(index,1),scope.showNoItemsMessage=!1},scope.addItem=function(item){scope.multi?(scope.model.push(item),scope.selected.item="",scope.isManualEntry&&(scope.entered.value="")):scope.model=item,scope.allowInputValue||(scope.selected.item=""),scope.dropdown.isOpen=!1},scope.addItemManual=function(item){var newItem={};if(newItem[scope.label]=item,scope.multi){var addItem=!0;angular.forEach(scope.model,function(item){item[scope.label]===newItem[scope.label]&&(element.addClass("has-error"),scope.entered.value="",addItem=!1)}),addItem&&scope.addItem(newItem)}else scope.addItem(newItem)},scope.resetField=function(){scope.isDisabled||(scope.model={},scope.placeholder=scope.originalPlaceholder,scope.selected.item="")},attrs.search?scope.searchFunction=function(val){var results=scope.search({val:val});return results}:scope.searchFunction=function(val){abortSearch&&abortSearch.resolve(),abortSearch=$q.defer();var defaultParams={search:val,ordering:scope.predicate,page_size:50,page:1},queryParams=angular.extend({},defaultParams);return"undefined"!=typeof scope.filterParams&&(queryParams="undefined"!=typeof scope.filterParams.async?angular.extend(defaultParams,scope.filterParams.async):angular.extend(defaultParams,scope.filterParams)),scope.loadingItems=!0,$api.use("default").all(scope.endpoint).withHttpConfig({timeout:abortSearch.promise}).getList(queryParams).then(function(data){var results=[];if(scope.model.length>0)for(var i=0;i<data.length;i++){var item=scope.filterChosen(data[i]);item&&results.push(item)}else results=data;return scope.loadingItems=!1,results})},scope.filterChosen=function(item){if(0===scope.model.length)return item;for(var chosen=!0,i=0,l=scope.model.length;l>i;i++)scope.comparator||item!==scope.model[i]?scope.comparator&&item[scope.comparator]===scope.model[i][scope.comparator]&&(chosen=!1):chosen=!1;return chosen?item:!1},scope.filterItems=function(item){if("undefined"==typeof scope.filterParams)return item;var params="undefined"!=typeof scope.filterParams.nonAsync?scope.filterParams.nonAsync:scope.filterParams,valid=!0;for(var key in params)params[key]!==item[key]&&(valid=!1);return valid?item:!1},scope.getMatchingItems=function($viewValue){if("true"!==attrs.searchWholeObject){for(var matchingItems=[],i=0;i<scope.data.length;i++)for(var j=0;j<scope.searchProperties.length;j++){var property=scope.searchProperties[j];if(-1!==scope.data[i][property].toString().toLowerCase().indexOf($viewValue.toString().toLowerCase())){matchingItems.push(scope.data[i]);break}}return matchingItems}return scope.data}}}}]).directive("gaRedactor",["$script","$api","$timeout","$window","CONVENTIONS_ENV",function($script,$api,$timeout,$window,CONVENTIONS_ENV){"use strict";return{restrict:"A",require:"ngModel",link:function(scope,element,attrs,ngModel){scope.redactorLoaded=!1;var editor,updateModel=function(value){$timeout(function(){scope.$apply(function(){ngModel.$setViewValue(value)})})},additionalOptions=attrs.gaRedactor?scope.$eval(attrs.gaRedactor):{},options={changeCallback:updateModel,imageUpload:$api.use("default").getUrl()+"/misc/images/.json",apiToken:$api.use("default").getToken(),apiTokenName:"Token",premailerEndpoint:$api.use("default").getUrl()+"/misc/premail/.json",deniedTags:["html","head","title","link","body","meta","script","applet"],plugins:["fontsize","fontcolor","fontfamily","gaimageupload","gaimporttemplate","taglist"],buttons:["html","formatting","bold","italic","deleted","unorderedlist","orderedlist","image","table","link","alignment","horizontalrule"],buttonsHide:["backcolor"]};angular.extend(options,additionalOptions);var initRedactor=function(){var $_element=$(element);$timeout(function(){editor=$($_element).redactor(options),ngModel.$render()}),ngModel.$render=function(){angular.isDefined(editor)&&$timeout(function(){$($_element).redactor("set",ngModel.$viewValue||""),scope.redactorLoaded=!0})}};if("test"===CONVENTIONS_ENV)initRedactor();else{var redactorPrerequisites=[];if("production"===CONVENTIONS_ENV){var redactorPath=additionalOptions.redactorPath?additionalOptions.redactorPath:"bower_components/ambassador-conventions/";redactorPrerequisites=[redactorPath+"ga-redactor.min.js"]}else"development"===CONVENTIONS_ENV&&(redactorPrerequisites=["ambassador/scripts/lib/redactor/redactor.js","ambassador/scripts/lib/redactor/plugins/fontcolor.js","ambassador/scripts/lib/redactor/plugins/fontfamily.js","ambassador/scripts/lib/redactor/plugins/fontsize.js","ambassador/scripts/lib/redactor/plugins/gaimageupload.js","ambassador/scripts/lib/redactor/plugins/gaimporttemplate.js","ambassador/scripts/lib/redactor/plugins/taglist.js"]);$script.load(["//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"]).then(function(){$script.load(redactorPrerequisites).then(function(){$timeout(initRedactor)})})}}}}]).directive("gaSlider",["$parse","$timeout",function($parse,$timeout){return{restrict:"AE",template:'<input type="text" />',require:"ngModel",scope:{max:"=",min:"=",step:"=",value:"=",ngModel:"=",ngDisabled:"=",range:"=",sliderid:"=",formater:"&",onStartSlide:"&",onStopSlide:"&",onSlide:"&"},link:function($scope,element,attrs,ngModelCtrl,$compile){function initSlider(){attrs.ngChange&&ngModelCtrl.$viewChangeListeners.push(function(){$scope.$apply(attrs.ngChange)});var options={};$scope.sliderid&&(options.id=$scope.sliderid),$scope.min&&(options.min=parseFloat($scope.min)),$scope.max&&(options.max=parseFloat($scope.max)),attrs.step&&(options.step=parseFloat($scope.step)),attrs.precision&&(options.precision=parseFloat(attrs.precision)),attrs.orientation&&(options.orientation=attrs.orientation),$scope.value&&(angular.isNumber($scope.value)||angular.isArray($scope.value)?options.value=$scope.value:angular.isString($scope.value)&&(0===attrs.value.indexOf("[")?options.value=angular.fromJson($scope.value):options.value=parseFloat($scope.value))),$scope.range&&(options.range=$scope.range===!0),attrs.selection&&(options.selection=attrs.selection),attrs.tooltip&&(options.tooltip=attrs.tooltip),attrs.tooltipseparator&&(options.tooltip_separator=attrs.tooltipseparator),attrs.tooltipsplit&&(options.tooltip_split="true"===attrs.tooltipsplit),attrs.handle&&(options.handle=attrs.handle),attrs.reversed&&(options.reversed="true"===attrs.reversed),attrs.enabled&&(options.enabled="true"===attrs.enabled),attrs.naturalarrowkeys&&(options.natural_arrow_keys="true"===attrs.naturalarrowkeys),attrs.formater&&(options.formater=$scope.$eval($scope.formater)),options.range&&!options.value&&(options.value=[0,0]);var slider=new Slider(element.children()[0],options),updateEvent=attrs.updateevent||"slide";slider.on(updateEvent,function(ev){var sliderValue="undefined"!=typeof ev.value?ev.value:ev;ngModelCtrl.$setViewValue(sliderValue),$timeout(function(){$scope.$apply()})}),slider.on("slideStop",function(ev){var sliderValue="undefined"!=typeof ev.value?ev.value:ev;ngModelCtrl.$setViewValue(sliderValue),$timeout(function(){$scope.$apply()})});var sliderEvents={slide:"onSlide",slideStart:"onStartSlide",slideStop:"onStopSlide"};angular.forEach(sliderEvents,function(sliderEventAttr,sliderEvent){slider.on(sliderEvent,function(ev){if($scope[sliderEventAttr]){var invoker=$parse(attrs[sliderEventAttr]);invoker($scope.$parent,{$event:ev,value:ev.value}),$timeout(function(){$scope.$apply()})}})}),angular.isDefined(attrs.ngDisabled)&&$scope.$watch("ngDisabled",function(value){value?slider.disable():slider.enable()}),$scope.$watch("ngModel",function(value){slider.setValue(value)})}initSlider()}}}]).directive("expandTextarea",[function(){return{restrict:"A",link:function(scope,element,attrs){autosize(element)}}}]),angular.module("ngAmbassador.infiniteScroll",["infinite-scroll","angularSpinner","ngAmbassador.services","ngAmbassador.api","ngAmbassador.alerts"]).directive("gaInfiniteScroll",["$api","$diff","$errors","$promiseKeeper","$q",function($api,$diff,$errors,$promiseKeeper,$q){
"use strict";return{restrict:"E",transclude:!0,scope:!0,template:'<div id="infinite-container" infinite-scroll="nextPage()" infinite-scroll-disabled="loadingNextPage"></div><div class="infinite-spinner" ng-if="loadingNextPage && (currentPage > 1 || updatingData)" us-spinner="infiniteSpinner"></div><alert-system name="infinite-scroll-alerts" type="page"></alert-system>',link:function(scope,element,attrs,ctrl,transclude){scope.endpoint=attrs.endpoint,scope.distance=attrs.distance,scope.currentPage=1,scope.loadingNextPage=!1,scope.updatingData=!1,scope.items=[],scope.count=0,scope.scollDistance="undefined"!=typeof scope.distance?scope.distance:1,scope.initialGet=!0,scope.initialGetLoading=!0,scope.infiniteSpinner={radius:5,width:3,length:4,lines:10,color:"#94A4A5"},scope.queryParams={};var abortSearch,initializePromise=$promiseKeeper.add();attrs.$observe("params",function(params){"undefined"!=typeof params&&""!==params&&(scope.queryParams=JSON.parse(params))}),scope.nextPage=function(){1===scope.currentPage&&initializePromise.deferred.resolve();var queryParams=angular.extend({},scope.queryParams);queryParams.page=scope.currentPage,scope.loadingNextPage||0!==scope.count&&scope.count<=scope.items.length||(scope.loadingNextPage=!0,$api.use("default").all(scope.endpoint).getList(queryParams).then(function(data){if(scope.initialGetLoading=!1,scope.count=data.count,0!==data.count){for(var i=0;i<data.length;i++)scope.items.push(data[i]);scope.currentPage++,queryParams.page=scope.currentPage,scope.loadingNextPage=!1,scope.initialGet=!1}},function(error){scope.initialGetLoading=!1,0!==error.status&&$errors.output({alertSystem:"infinite-scroll-alerts",alertSystemType:"page",defaultMessage:"Something went wrong while trying to get the data. Please try again or contact support."},error.data)}))},scope.updateData=function(){"undefined"!=typeof abortSearch&&abortSearch.resolve(),abortSearch=$q.defer(),scope.currentPage=1,scope.loadingNextPage=!0,scope.updatingData=!0;var queryParams=angular.extend({},scope.queryParams);queryParams.page=scope.currentPage,$api.use("default").all(scope.endpoint).withHttpConfig({timeout:abortSearch.promise}).getList(queryParams).then(function(data){if(scope.items=[],scope.count=data.count,scope.loadingNextPage=!1,scope.updatingData=!1,0!==data.count){for(var i=0;i<data.length;i++)scope.items.push(data[i]);scope.currentPage=2,queryParams.page=scope.currentPage}},function(error){0!==error.status&&$errors.output({alertSystem:"infinite-scroll-alerts",alertSystemType:"page",defaultMessage:"Something went wrong while trying to get the data. Please try again or contact support."},error.data)})},scope.$watch("queryParams",function(newValue,oldValue){$diff.compare(oldValue,newValue)&&scope.updateData()},!0),transclude(scope,function(clone,scope){angular.element(element.find("div")[0]).append(clone)})}}}]),angular.module("ngAmbassador",["ui.bootstrap","ngAmbassador.constants","ngAmbassador.activityFeed","ngAmbassador.alerts","ngAmbassador.api","ngAmbassador.buttons","ngAmbassador.charts","ngAmbassador.file","ngAmbassador.filters","ngAmbassador.forms","ngAmbassador.infiniteScroll","ngAmbassador.misc","ngAmbassador.modals","ngAmbassador.services","ngAmbassador.stats","ngAmbassador.tables"]),angular.module("ngAmbassador.misc",["ngAmbassador.services"]).directive("fillWindow",["$timeout",function($timeout){return{scope:{subtractElems:"@",applyToChildren:"@",additionalOffset:"@",ignore:"@"},link:function(scope,element,attrs){function resizeElements(){var windowWidth=angular.isDefined(attrs.windowWidth)?attrs.windowWidth:window.innerWidth;if(resize=!0,angular.isDefined(scope.ignore)){var ignoreSizes=scope.ignore.split(";");angular.forEach(ignoreSizes,function(size){windowWidth>=screenSizes[size].minWidth&&windowWidth<=screenSizes[size].maxWidth&&(resize=!1)}),resize?adjustElemHeight():resetHeight()}else adjustElemHeight()}function resetHeight(){if("true"!==scope.applyToChildren)element[0].style.minHeight="0px";else{var childElems=element[0].children;angular.forEach(childElems,function(child){child.style.minHeight="0px"})}}function adjustElemHeight(){resetHeight();var documentHeight=document.documentElement.scrollHeight>document.documentElement.clientHeight?document.documentElement.scrollHeight:document.documentElement.clientHeight,subtractHeight=0;if(angular.isDefined(scope.subtractElems)&&""!==scope.subtractElems){var elements=scope.subtractElems.split(";");angular.forEach(elements,function(elem){subtractHeight+=parseFloat(window.getComputedStyle(document.getElementsByClassName(elem)[0]).height)})}if(subtractHeight+=element[0].offsetTop,"true"!==scope.applyToChildren)element[0].style.minHeight=documentHeight-subtractHeight-(angular.isUndefined(scope.additionalOffset)?0:scope.additionalOffset)+"px";else{var childElems=element[0].children;angular.forEach(childElems,function(child){child.style.minHeight=documentHeight-subtractHeight-(angular.isUndefined(scope.additionalOffset)?0:scope.additionalOffset)+"px"})}}function checkElementHeights(){if("true"!==scope.applyToChildren)parseInt(window.getComputedStyle(element[0]).height)>parseInt(window.getComputedStyle(element[0]).minHeight)&&resizeElements();else for(var childElems=element[0].children,i=0;i<childElems.length;i++)if(parseInt(window.getComputedStyle(childElems[i]).height)>parseInt(window.getComputedStyle(childElems[i]).minHeight)){resizeElements();break}}var timeout,screenSizes={"extra-small":{minWidth:0,maxWidth:767},small:{minWidth:768,maxWidth:991},medium:{minWidth:992,maxWidth:1199},large:{minWidth:1200,maxWidth:1/0}},resize=!0;scope.$watch(function(){resizeElements()}),window.onresize=function(){$timeout.cancel(timeout),resizeElements(),timeout=$timeout(function(){checkElementHeights()},50)}}}}]).directive("clickAnywhereButHere",["$document",function($document){return{restrict:"A",link:function(scope,elem,attr,ctrl){elem.bind("click",function(e){e.stopPropagation()}),$document.bind("click",function(){scope.$apply(attr.clickAnywhereButHere)})}}}]).directive("fillParent",["$window",function($window){return{link:function(scope,element,attrs){function setHeight(){var parentHeight=window.getComputedStyle(element.parent()[0]).height;element[0].style.minHeight=parentHeight}scope.$watch(function(){setHeight()}),angular.element($window).bind("resize",function(){setHeight()})}}}]).directive("equalizeHeights",["$window",function($window){return{link:function(scope,element,attrs){function goThroughRows(){angular.forEach(targets,function(target,index){target.style.height="auto",0==index?(currentRowOffset=target.offsetTop,row.push(target),height=window.getComputedStyle(target).height):target.offsetTop!=currentRowOffset?(changeHeight(height),row=[],row.push(target),currentRowOffset=target.offsetTop,height=window.getComputedStyle(target).height):(row.push(target),parseFloat(window.getComputedStyle(target).height)>parseFloat(height)&&(height=window.getComputedStyle(target).height)),index==targets.length-1&&(row.push(target),parseFloat(window.getComputedStyle(target).height)>parseFloat(height)&&(height=window.getComputedStyle(target).height),changeHeight(height),row=[],currentRowOffset=0,height=0)})}function changeHeight(height){angular.forEach(row,function(target){target.style.height=height})}var targets=element[0].children,currentRowOffset=0,height=0,row=[];element[0].style.overflow="hidden",scope.$watch(function(){goThroughRows()}),angular.element($window).bind("resize",function(){goThroughRows()})}}}]).directive("gaEnter",function(){return function(scope,element,attrs){element.bind("keydown keypress",function(event){13===event.which&&(scope.$apply(function(){scope.$eval(attrs.gaEnter)}),event.preventDefault())})}}).directive("gaLoader",["$timeout","$window",function($timeout,$window){return{restrict:"E",replace:!0,template:'<div ng-class="{\'fade-in\':loading===true, \'fade-out\':loading===false }" class="ga-loader"><div ng-if="showLoader" class="ga-spinner"><span class="loader-text">Loading</span><svg class="spinner" width="100px" height="100px" viewBox="0 0 66 66" xmlns="http://www.w3.org/2000/svg"><circle class="path" fill="none" stroke-width="5" stroke-linecap="round" cx="33" cy="33" r="30"></circle></svg></div></div>',scope:{loading:"=",activePositioning:"@"},link:function(scope,elm,attrs){function keepSpinnerInView(){if(scope.showLoader){var tableBounds=scope.thisElement.getBoundingClientRect(),spinner=angular.element(scope.thisElement.children[0]),isTopHidden=tableBounds.top<0,isBottomHidden=tableBounds.bottom>window.innerHeight,spinnerTop=null;if(isTopHidden&&isBottomHidden)spinnerTop=-tableBounds.top+window.innerHeight/2;else if(isTopHidden){var y=(tableBounds.height-tableBounds.top)/2;spinnerTop=Math.min(y,tableBounds.height-50)}else if(isBottomHidden){var y=(tableBounds.height-(tableBounds.bottom-window.innerHeight))/2;spinnerTop=Math.max(50,y)}spinner.css("top",spinnerTop?spinnerTop+"px":"")}}scope.thisElement=elm[0],scope.showLoader=scope.loading===!0,scope.activeSpinnerPositioning=!0,"false"===scope.activePositioning&&(scope.activeSpinnerPositioning=!1),scope.$watch("loading",function(newValue,oldValue){scope.loading?(scope.showLoader=!0,scope.activeSpinnerPositioning&&$timeout(keepSpinnerInView,1)):newValue!==oldValue&&$timeout(function(){scope.showLoader=!1},300)}),scope.activeSpinnerPositioning&&angular.element($window).bind("resize scroll",keepSpinnerInView)}}}]).directive("gaValueTemplate",["$compile",function($compile){return{restrict:"E",scope:{value:"=",responsive:"=",compression:"=",min:"=",max:"=",scopeLevel:"@"},replace:!0,template:"<div ng-style='{fontSize:fontSize}'></div>",link:function(scope,element,attrs){element.html(scope.value),void 0===scope.scopeLevel&&(scope.scopeLevel=3);for(var valueScope=scope,i=1;i<=scope.scopeLevel;i++)valueScope=valueScope.$parent;$compile(element.contents())(valueScope),scope.compressor=scope.compression||1,scope.minFontSize=scope.min||Number.NEGATIVE_INFINITY,scope.maxFontSize=scope.max||Number.POSITIVE_INFINITY,scope.elementWidth=element[0].offsetWidth,scope.resizer=function(){scope.elementWidth=element[0].offsetWidth,scope.fontSize=Math.max(Math.min(scope.elementWidth/(10*scope.compressor),parseFloat(scope.maxFontSize)),parseFloat(scope.minFontSize))+"px"},scope.responsive&&(scope.resizer(),scope.$watch("value",function(){scope.resizer()}),angular.element(window).bind("resize",function(){scope.$apply(scope.resizer)}),scope.$watch(function(){return element[0].offsetWidth},function(){scope.resizer()}))}}}]).directive("gaCurrency",["$filter",function($filter){return{restrict:"E",replace:!0,scope:{type:"=",amount:"=",pointsLabel:"=",currency:"=",typesConfig:"=",showTooltip:"@"},template:"<div><span ng-if='showTooltip' ga-dynamic-tooltip='{{displayAmount}}' ga-dynamic-tooltip-placement='{{showTooltip}}'>{{displayAmount}}</span><span ng-if='!showTooltip'>{{displayAmount}}</span></div>",link:function(scope,element,attrs,ctrl){var currencies={USD:"$",GBP:"£",SGD:"S$",EUR:"€",AUD:"A$",ZAR:"R",BRL:"R$",CAD:"C$",NZD:"NZ$"},updateAmount=function(){var filter=$filter("currency"),amountTest=parseFloat(scope.amount);angular.isDefined(scope.type)&&angular.isDefined(scope.typesConfig)&&-1!==scope.typesConfig.nonMonetary.indexOf(scope.type)?scope.displayAmount=filter(amountTest,"",2)+" "+scope.pointsLabel:scope.displayAmount=filter(amountTest,currencies[scope.currency],2)};scope.$watch("amount",function(){updateAmount()})}}}]).directive("gaAvatar",["$filter",function($filter){return{restrict:"E",scope:{image:"=",disableFade:"=",alt:"@"},template:"<div class='ga-avatar'><img ng-src='{{image}}' ng-class='{ \"fade-in\": avatarLoaded===true }' ></div>",link:function(scope,element,attrs){scope.disableFade!==!0?element.find("img").bind("load",function(event){scope.avatarLoaded=!0,scope.$$phase||scope.$apply()}):scope.avatarLoaded=!0}}}]).directive("gaDynamicTooltip",["$window",function($window){return{restrict:"A",transclude:!0,template:'<div tooltip="{{tooltipText}}" tooltip-placement="{{tooltipPlacement}}" ng-transclude></div>',link:function(scope,element,attrs){function tooltipHandler(showTooltip){scope.tooltipText=showTooltip?attrs.gaDynamicTooltip:""}scope.tooltipText="",scope.tooltipPlacement=angular.isDefined(attrs.gaDynamicTooltipPlacement)?attrs.gaDynamicTooltipPlacement:"top",scope.minWidthToShowTooltip=angular.isDefined(attrs.showTooltipAfter)?parseInt(attrs.showTooltipAfter):!1;var count=0,waitForTooltipToRender=scope.$watch(function(){var innerWidth=element.find("span")[0].getBoundingClientRect().width,outerWidth=element.children()[0].getBoundingClientRect().width;return count++,count>=5&&waitForTooltipToRender(),innerWidth>0&&outerWidth>0?scope.minWidthToShowTooltip?innerWidth>scope.minWidthToShowTooltip:innerWidth>=outerWidth:void 0},function(showTooltip){tooltipHandler(showTooltip)});angular.element($window).bind("resize",function(){var innerWidth=element.find("span")[0].getBoundingClientRect().width,outerWidth=element.children()[0].getBoundingClientRect().width;innerWidth>0&&outerWidth>0&&tooltipHandler(scope.minWidthToShowTooltip?innerWidth>scope.minWidthToShowTooltip:innerWidth>=outerWidth)})}}}]).directive("gaEnter",function(){return function(scope,element,attrs){element.bind("keypress",function(event){13===event.which&&(scope.$apply(function(){scope.$eval(attrs.gaEnter)}),event.preventDefault())})}}),angular.module("ngAmbassador.modals",[]).factory("$gaModal",["$modal","$injector",function($modal,$injector){var $gaModal={};return $gaModal.open=function(config){var modalInstance;return config.controller=["$scope","$modalInstance",function($scope,$modalInstance){$scope.title=config.title,$scope.buttons=config.buttons,$scope.close=function(){$modalInstance.dismiss("cancel")};for(var property in config.resolve)$scope[property]=$injector.invoke(config.resolve[property])}],"undefined"!=typeof config.templateUrl&&(config.template='<ga-modal-template modal-title="title" close="close()" buttons="buttons"><div ng-include="\''+config.templateUrl+"'\"></div></ga-modal-template>",delete config.templateUrl),modalInstance=$modal.open(config)},$gaModal}]).directive("gaModalTemplate",[function(){return{restrict:"E",transclude:!0,scope:{modalTitle:"=",buttons:"=",close:"&"},templateUrl:"../ambassador/templates/modal.html",link:function(scope){scope.wrapperHasClass=!1,angular.forEach(scope.buttons,function(button){void 0!==button.wrapperClass&&""!==button.wrapperClass&&(scope.wrapperHasClass=!0)})}}}]).directive("gaModalInfo",[function(){return{restrict:"E",transclude:!0,scope:{type:"@"},template:"<div class=\"modal-info modal-info-{{type}}\"><div class=\"modal-info-icon\"><i class=\"fa\" ng-class=\"{'fa-exclamation': type === 'danger', 'fa-exclamation-circle': type === 'warning', 'fa-info-circle': type === 'info', 'fa-check-circle': type === 'success'}\"></i><div></div></div><div ng-transclude></div></div>",link:function(scope){var types=["success","info","warning","danger"];(angular.isUndefined(scope.type)||-1===types.indexOf(scope.type))&&(scope.type="info")}}}]),angular.module("ngAmbassador.services",[]).factory("$helper",function(){return{colorLuminance:function(hex,lum){hex=String(hex).replace(/[^0-9a-f]/gi,""),hex.length<6&&(hex=hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2]),lum=lum||0;var c,i,rgb="#";for(i=0;3>i;i++)c=parseInt(hex.substr(2*i,2),16),c=Math.round(Math.min(Math.max(0,c+c*lum),255)).toString(16),rgb+=("00"+c).substr(c.length);return rgb},sum:function(obj,key){for(var sum=0,i=0;i<obj.length;i++)sum+=parseFloat(obj[i][key]);return sum}}}).factory("$promiseKeeper",["$q","$timeout",function($q,$timeout){var $promiseKeeper={},promises=[],promiseData=[],keeperStartTime=null,keeperConfig={expect:0,timeout:30,success:function(){},loading:function(){}},promiseConfig={id:"promise",status:"new"},_startPromising=function(){"function"==typeof keeperConfig.loading&&keeperConfig.loading();var promiseCount=promises.length;$q.all(promises)["finally"](function(){"function"==typeof keeperConfig.success&&promises.length===promiseCount&&(keeperConfig.success(),_resetPromises())})},_resetPromises=function(){promises=[],promiseData=[],keeperStartTime=null};return $promiseKeeper.getActive=function(){return promiseData.length>0?promiseData:!1},$promiseKeeper.config=function(config){keeperConfig=angular.extend(keeperConfig,config)},$promiseKeeper.add=function(config){var deferred=$q.defer(),promiseConf=angular.extend(angular.copy(promiseConfig),config);promiseConf.promise=deferred.promise,promiseConf.deferred=deferred,promiseConf.status="loading",promiseConf.id="promise"+(parseInt(promises.length)+1),promiseConf.start=(new Date).getTime(),promiseData.push(promiseConf),promises.push(deferred.promise),null===keeperStartTime&&(keeperStartTime=(new Date).getTime());var promiseTimeout=$timeout(function(){promiseConf.status="timeout",promiseConf.deferred.reject(promiseConf)},1e3*parseInt(keeperConfig.timeout)-(promiseConf.start-keeperStartTime));return promiseConf.promise.then(function(){$timeout.cancel(promiseTimeout),promiseConf.status="success"}),_startPromising(),promiseConf},$promiseKeeper}]).factory("$script",["$q",function($q){var $script={};return $script.load=function(urls,callback){var promises=[];return angular.forEach(urls,function(url){var scriptPromise=$q.defer();promises.push(scriptPromise.promise);for(var head=document.getElementsByTagName("head")[0],script=null,allScripts=head.getElementsByTagName("script"),i=allScripts.length-1;i>=0;i--){var sc=allScripts[i],gaLoaded=sc.getAttribute("ga-loaded");if(null!==gaLoaded&&url===sc.getAttribute("src")){if("true"===gaLoaded)return void scriptPromise.resolve();script=sc;break}}null===script&&(script=document.createElement("script"),script.type="text/javascript",script.src=url,script.setAttribute("ga-loaded","false"),head.appendChild(script)),script.addEventListener?script.addEventListener("load",function(){script.setAttribute("ga-loaded","true"),scriptPromise.resolve()},!1):script.onreadystatechange=function(){"loaded"===script.readyState&&(script.setAttribute("ga-loaded","true"),scriptPromise.resolve())}}),$q.all(promises)},$script}]).factory("$browserDetect",[function(){function _searchString(data){for(var i=0;i<data.length;i++){var dataString=data[i].string,dataProp=data[i].prop;if(this.versionSearchString=data[i].versionSearch||data[i].identity,dataString){if(-1!==dataString.indexOf(data[i].subString))return data[i].identity}else if(dataProp)return data[i].identity}}function _searchVersion(dataString){var index=dataString.indexOf(this.versionSearchString);if(-1!==index)return parseFloat(dataString.substring(index+this.versionSearchString.length+1))}var $browserDetect={},_dataBrowser=[{string:navigator.userAgent,subString:"Chrome",identity:"Chrome"},{string:navigator.userAgent,subString:"OmniWeb",versionSearch:"OmniWeb/",identity:"OmniWeb"},{string:navigator.vendor,subString:"Apple",identity:"Safari",versionSearch:"Version"},{prop:window.opera,identity:"Opera",versionSearch:"Version"},{string:navigator.vendor,subString:"iCab",identity:"iCab"},{string:navigator.vendor,subString:"KDE",identity:"Konqueror"},{string:navigator.userAgent,subString:"Firefox",identity:"Firefox"},{string:navigator.vendor,subString:"Camino",identity:"Camino"},{string:navigator.userAgent,subString:"Netscape",identity:"Netscape"},{string:navigator.userAgent,subString:"MSIE",identity:"Explorer",versionSearch:"MSIE"},{string:navigator.userAgent,subString:"Gecko",identity:"Mozilla",versionSearch:"rv"},{string:navigator.userAgent,subString:"Mozilla",identity:"Netscape",versionSearch:"Mozilla"}],_dataOS=[{string:navigator.platform,subString:"Win",identity:"Windows"},{string:navigator.platform,subString:"Mac",identity:"Mac"},{string:navigator.userAgent,subString:"iPhone",identity:"iPhone/iPod"},{string:navigator.platform,subString:"Linux",identity:"Linux"}];return $browserDetect.name=_searchString(_dataBrowser)||!1,$browserDetect.version=_searchVersion(navigator.userAgent)||_searchVersion(navigator.appVersion)||!1,$browserDetect.OS=_searchString(_dataOS)||!1,$browserDetect}]).factory("$diff",[function(){var $diff={};return $diff.compare=function(original,toCompare,emptyStringIsNotNull){var diffObj,objectDiff={},objectsEqual=!0;return objectDiff.diff=function(a,b){var oldKeys=_.keys(a),newKeys=_.keys(b),removed=_.difference(oldKeys,newKeys),union=_.union(newKeys,oldKeys),changes={};return _.each(union,function(k){var equal=!0;!emptyStringIsNotNull&&(null===a[k]&&""===b[k]||""===a[k]&&null===b[k])||_.isFunction(a[k])||_.isFunction(b[k])||(equal=_.isDate(a[k])&&_.isDate(b[k])?_.isEqual(new Date(a[k]).setHours(0,0,0,0),new Date(b[k]).setHours(0,0,0,0)):"number"==typeof a[k]||"number"==typeof b[k]?_.isEqual(+a[k],+b[k]):_.isEqual(a[k],b[k]),equal||(objectsEqual=!1,changes[k]=b[k]))}),_.each(removed,function(k){_.isFunction(a[k])||_.isFunction(b[k])||(changes[k]="")}),objectsEqual?!1:changes},diffObj=objectDiff.diff(original,toCompare)},$diff}]),angular.module("ngAmbassador.stats",["ngAmbassador.misc"]).directive("gaStatBoxOne",[function(){return{restrict:"E",replace:!0,templateUrl:"../ambassador/templates/stats/stats.box-1.html",scope:{boxes:"=",autoWidth:"="},link:function(scope,elm,attrs){scope.styles={},scope.getStyles=function(){return scope.autoWidth===!0&&(scope.styles.width=100/scope.boxes.length+"%"),scope.styles}}}}]).directive("gaStatBoxTwo",[function(){return{restrict:"E",replace:!0,templateUrl:"../ambassador/templates/stats/stats.box-2.html",scope:{boxes:"=",autoWidth:"=",fontMax:"@",fontMin:"@",fontMultiplier:"@"},link:function(scope,elm,attrs){scope.styles={},scope.max=scope.fontMax||32,scope.min=scope.fontMin||12,scope.multiplier=scope.fontMultiplier||1,scope.getStyles=function(){return scope.autoWidth===!0&&(scope.styles.width=100/scope.boxes.length+"%"),scope.styles}}}}]).directive("gaStatBoxThree",[function(){return{restrict:"E",replace:!0,templateUrl:"../ambassador/templates/stats/stats.box-3.html",scope:{boxes:"=",autoWidth:"="},link:function(scope,elm,attrs){scope.styles={},scope.getStyles=function(){return scope.autoWidth===!0&&(scope.styles.width=100/scope.boxes.length+"%"),scope.styles}}}}]).directive("gaProportionRings",[function(){return{restrict:"E",replace:!0,templateUrl:"../ambassador/templates/stats/proportion-rings.html",scope:{total:"=",rings:"=",hideValue:"=?",direction:"@?",lineStyle:"@?",size:"=?",lineWidth:"=?"}}}]).directive("gaProportionRing",["$timeout",function($timeout){"use strict";function easeInOutQuad(tlength,dt,x0,dx){return dt/=tlength/2,1>dt?dx/2*dt*dt+x0:(dt--,-dx/2*(dt*(dt-2)-1)+x0)}var Angle0=-Math.PI/2,_2PI=2*Math.PI,PresetColors={blue:"#2f95d8",green:"#73ab76",red:"#ce6563",yellow:"#f4d10d",high:"#cd1f15",medium:"#f29b30",low:"#777777"},DefaultColor=PresetColors.blue,DefaultBackgroundColor="transparent";return{restrict:"E",replace:!0,templateUrl:"../ambassador/templates/stats/proportion-ring.html",scope:{total:"=",value:"=",name:"@",color:"=",background:"=?",hideValue:"=?",direction:"@?",lineStyle:"@?",size:"=?",lineWidth:"=?"},link:function(scope,elements){function determinColor(attrColor,defaultColor){var c=defaultColor,cSpec=attrColor;return cSpec&&("#"===cSpec.charAt(0)?c=cSpec:PresetColors.hasOwnProperty(cSpec)&&(c=PresetColors[cSpec])),c}function easing(elapsed){return easeInOutQuad(duration,elapsed,0,arcAngle)}function drawArc(angle){var endAngle=counterClockwise?Angle0+_2PI-angle:Angle0+angle;context.beginPath(),context.arc(center,center,radius,Angle0,endAngle,counterClockwise),context.stroke()}function draw(){if(!animating)return context.clearRect(0,0,outerDiameter,outerDiameter),void drawArc(arcAngle);window.requestAnimationFrame(draw);var elapsed=+new Date-animationStart;drawArc(easing(elapsed)),elapsed>=duration&&(animating=!1)}function initiateDraw(){canvas.getContext&&(animationStart=+new Date,drawArc(.001),window.requestAnimationFrame(draw))}function renderedWidth(el){return el.getBoundingClientRect().width}var e=elements[0],innerElement=e.querySelector(".ga-proportion-ring-inner"),size=scope.size?scope.size:150,thickness=scope.lineWidth?scope.lineWidth:8,outerDiameter=size,innerDiameter=size-2*thickness,center=outerDiameter/2,radius=center-thickness/2,counterClockwise="clockwise"===scope.direction?!1:!0,color=determinColor(scope.color,DefaultColor),background=determinColor(scope.background,DefaultBackgroundColor);e.style.width=outerDiameter+"px",e.style.height=outerDiameter+"px",e.style.borderWidth=thickness+"px",innerElement.style.width=innerDiameter+"px",innerElement.style.height=innerDiameter+"px",innerElement.style.marginTop=0,innerElement.style.marginRight=thickness+"px",innerElement.style.marginBottom=thickness+"px",innerElement.style.marginLeft=0,innerElement.style.backgroundColor=background;var canvas=e.querySelector("canvas");canvas.width=outerDiameter,canvas.height=outerDiameter,canvas.style.marginTop="-"+thickness+"px",canvas.style.marginLeft="-"+thickness+"px";var proportion=scope.value/scope.total;proportion=Math.max(0,Math.min(proportion,1));var arcAngle=_2PI*proportion;arcAngle=Math.max(Math.min(_2PI-.001,arcAngle),.001);var duration=600*(2+proportion),context=canvas.getContext("2d");context.lineWidth=thickness,context.lineCap=scope.lineStyle?scope.lineStyle:"round",context.strokeStyle=color;var animationStart,animating=!0;scope.displayValue=Number(scope.value).toLocaleString(),scope.hideValue?(scope.textColor=color,angular.element(innerElement).addClass("ga-proportion-ring-hide-value")):scope.textColor=null;var maxWidth=renderedWidth(innerElement)-10,minFontSize=13,setFontSizeFor=["nominal"];scope.hideValue||setFontSizeFor.push("numeric"),$timeout(function(){angular.forEach(setFontSizeFor,function(which){for(var el=e.querySelector(".ga-proportion-ring-"+which+"-label"),fontSize=parseInt(getComputedStyle(el).fontSize);renderedWidth(el)>maxWidth&&fontSize>minFontSize;)el.style.fontSize=--fontSize+"px";el.style.color=scope.textColor,el.style.opacity=""}),initiateDraw()})}}}]),function(){var tempNumber=1e6*Math.PI;if(tempNumber.toLocaleString("de")===tempNumber.toLocaleString("fr")){var formatNumber=function(number,delimiter,decimalDelimiter){var numberString=number.toString(),splitNumber=numberString.split("."),splitFloats="";return splitNumber[1]&&splitNumber[1].length>3&&(splitFloats=decimalDelimiter+number.toFixed(3).toString().split(".")[1]),splitNumber[0].split(/(?=(?:\d{3})+$)/g).join(delimiter)+splitFloats};window.Number.prototype.toLocaleString=function(){var locale,navigatorLanguage,localeCharacters,localeMap={en:{delimiter:",",decimal:"."},au:{delimiter:",",decimal:"."},gb:{delimiter:",",decimal:"."},fr:{delimiter:" ",decimal:","},de:{delimiter:".",decimal:","},at:{delimiter:",",decimal:"."},fi:{delimiter:" ",decimal:","},nl:{delimiter:".",decimal:","},es:{delimiter:".",decimal:","},da:{delimiter:".",decimal:","},el:{delimiter:".",decimal:","},et:{delimiter:" ",decimal:","},it:{delimiter:".",decimal:","},pl:{delimiter:" ",decimal:","},sv:{delimiter:" ",decimal:","},ru:{delimiter:" ",decimal:","},no:{delimiter:",",decimal:"."}};return navigatorLanguage=navigator&&navigator.language||"en",navigatorLanguage=navigatorLanguage.replace(/\-\w+$/g,""),locale=arguments[0]||navigatorLanguage,localeCharacters=localeMap[locale],localeCharacters?formatNumber(this,localeCharacters.delimiter,localeCharacters.decimal):this.valueOf()}}}(),angular.module("ngAmbassador.tables",["smartTable.table","ambassador.table.filters","ngAmbassador.services","ngAmbassador.api","ngAmbassador.alerts"]),function(global,angular){"use strict";function ColumnProvider(DefaultColumnConfiguration){function Column(config){return this instanceof Column?void angular.extend(this,config):new Column(config)}this.setDefaultOption=function(option){angular.extend(Column.prototype,option)},DefaultColumnConfiguration.headerTemplateUrl="../ambassador/templates/table/table.default-header.html",this.setDefaultOption(DefaultColumnConfiguration),this.$get=function(){return Column}}var smartTableColumnModule=angular.module("smartTable.column",[]).constant("DefaultColumnConfiguration",{isSortable:!0,isEditable:!1,type:"text",headerTemplateUrl:"",map:"",label:"",group:"",sortPredicate:"",formatFunction:"",formatParameter:"",filterPredicate:"",cellTemplate:"",cellTemplateUrl:"",headerClass:"",cellClass:"",saving:!1,width:"",maxWidth:"",pinnedWidth:0});ColumnProvider.$inject=["DefaultColumnConfiguration"],smartTableColumnModule.provider("Column",ColumnProvider),global.ColumnProvider=ColumnProvider}(window,angular),function(angular){"use strict";angular.module("smartTable.directives",["ui.bootstrap.position"]).directive("smartTable",["DefaultTableConfiguration","$injector","$timeout","$window",function(defaultConfig,$injector,$timeout,$window){return{restrict:"EA",scope:{dataSource:"=rows",columnCollection:"=columns",config:"=",exposedData:"=?"},replace:"true",templateUrl:"../ambassador/templates/table/table.html",controller:"SmartTableCtrl",link:function(scope,element,attr,ctrl){function setConfig(){var newConfig=angular.extend({},defaultConfig,scope.config),length=void 0!==scope.columns?scope.columns.length:0;if(scope.table={load:!1},"undefined"!=typeof scope.config.tableFilterSetType?(scope.table.load=!1,scope.filterSetType=scope.config.tableFilterSetType):(scope.table.load=!0,scope.filterSetType=""),scope.filters=[],"undefined"==typeof scope.config.searchPlacement&&(scope.config.searchPlacement="right"),ctrl.setGlobalConfig(newConfig),newConfig.dependencies)for(var x=0;x<newConfig.dependencies.length;x++)scope[newConfig.dependencies[x]]=$injector.get(newConfig.dependencies[x]);if("multiple"!==newConfig.selectionMode||newConfig.displaySelectionCheckbox!==!0)for(var i=length-1;i>=0;i--)scope.columns[i].isSelectionColumn===!0&&ctrl.removeColumn(i);else ctrl.insertColumn({cellTemplateUrl:"../ambassador/templates/table/table.select-checkbox.html",headerTemplateUrl:"../ambassador/templates/table/table.select-all-checkbox.html",isSelectionColumn:!0,isSortable:!1,cellClass:"smart-table-checkbox-cell",headerClass:"smart-table-checkbox-header-cell",pinnedWidth:40},0);angular.isDefined(newConfig.manageActions)&&newConfig.editDeleteBtns!==!0&&newConfig.manageBtns!==!0&&(angular.isUndefined(newConfig.tableActionButtons)||newConfig.tableActionButtons===!1)&&ctrl.insertColumn({cellTemplate:"<manage-table-btn></manage-table-btn>",isSortable:!1,cellClass:"smart-table-manage-cell",headerClass:"smart-table-header-manage-cell"},scope.columns.length),newConfig.editDeleteBtns!==!0||!angular.isUndefined(newConfig.tableActionButtons)&&newConfig.tableActionButtons!==!1||ctrl.insertColumn({cellTemplate:"<table-edit-delete></table-edit-delete>",isSortable:!1},scope.columns.length),newConfig.useServer||scope.$watch("dataSource.length",function(newValue,oldValue){oldValue!==newValue&&(scope.dataCollection=scope.dataSource,0===scope.dataCollection.length?scope.noResults=!0:scope.noResults=!1,ctrl.setRowsLength(),ctrl.sortBy())})}function setTablePinning(){var tableElem=_.find(element.find("table"),function(table){return table.classList.contains("smart-table")});$timeout(tableElem.getBoundingClientRect().width>angular.element(angular.element(tableElem).parent())[0].getBoundingClientRect().width-4?function(){scope.$broadcast("SET_ROW_HEIGHT",{tableId:scope.tableId}),scope.tablePinningActive=!0,element.addClass("table-pinning-active")}:function(){scope.tablePinningActive=!1,element.removeClass("table-pinning-active")})}function createTableStyles(){function sameOrNull(something){return"undefined"!=typeof something&&something?something:null}function calculateCellStyles(isHeader){isHeader=!!isHeader;var styles=new Array(N);for(i=0;N>i;i++)isHeader?styles[i]={"text-align":sameOrNull(C[i].align),width:sameOrNull(C[i].width)}:styles[i]={"text-align":sameOrNull(C[i].align),"min-width":i<scope.tablePinnedCols?C[i].pinnedWidth+"px":null,"max-width":i<scope.tablePinnedCols&&!sameOrNull(C[i].maxWidth)?C[i].pinnedWidth+"px":sameOrNull(C[i].maxWidth)};return styles}function calculateCellPinnedStyles(isHeader){
isHeader=!!isHeader;var i,pinnedStyles=new Array(N),heightStyle=!isHeader&&scope.tablePinnedHeight?scope.tablePinnedHeight+"px":null,left=2;for(i=0;i<scope.tablePinnedCols;i++){var thisWidth=C[i].pinnedWidth;pinnedStyles[i]={width:thisWidth+"px",left:left+"px",height:heightStyle},left+=thisWidth}if(heightStyle)for(;N>i;i++)pinnedStyles[i]={height:heightStyle};return pinnedStyles}function stylesToCSS(styleObj){var str="";for(var key in styleObj)styleObj.hasOwnProperty(key)&&styleObj[key]&&(str+=key+":"+styleObj[key]+";");return str}function assembleCellCSS(cellSelector,cellStyles){for(var styleString="",i=cellStyles.length-1;i>=0;i--)if("undefined"!=typeof cellStyles[i]){var thisCellCSS=stylesToCSS(cellStyles[i]);thisCellCSS&&(styleString+=cellSelector+":nth-child("+(i+1)+"){"+thisCellCSS+"}")}return styleString}for(var C=scope.columns,N=C.length,tableMargin=0,y=scope.tablePinnedCols-1;y>=0;y--)tableMargin+=C[y].pinnedWidth;for(var tableSelector='.smart-table-container[ga-smart-table-id="'+scope.tableId+'"] table',headerCellStyles=calculateCellStyles(!0),dataCellStyles=calculateCellStyles(!1),headerCellSelector=tableSelector+" th.smart-table-header-cell",dataCellSelector=tableSelector+" td.smart-table-data-cell",headerCellsCSS=assembleCellCSS(headerCellSelector,headerCellStyles),dataCellsCSS=assembleCellCSS(dataCellSelector,dataCellStyles),pinnedTableSelector='.smart-table-container[ga-smart-table-id="'+scope.tableId+'"].table-pinning-active table.pinned',headerCellPinnedStyles=calculateCellPinnedStyles(!0),dataCellPinnedStyles=calculateCellPinnedStyles(!1),headerCellPinnedSelector=pinnedTableSelector+" th.smart-table-header-cell",dataCellPinnedSelector=pinnedTableSelector+" td.smart-table-data-cell",pinnedHeaderCellsCSS=assembleCellCSS(headerCellPinnedSelector,headerCellPinnedStyles),pinnedDataCellsCSS=assembleCellCSS(dataCellPinnedSelector,dataCellPinnedStyles),styleStr=headerCellsCSS+dataCellsCSS+pinnedTableSelector+"{padding-left:"+tableMargin+"px;}"+pinnedHeaderCellsCSS+pinnedDataCellsCSS,styleEl=null,styleElements=document.head.getElementsByTagName("style"),i=styleElements.length-1;i>=0;i--)if(styleElements[i].getAttribute("ga-smart-table-id")==scope.tableId){styleEl=angular.element(styleElements[i]);break}null===styleEl&&(styleEl=angular.element("<style>"),styleEl.attr("ga-smart-table-id",scope.tableId),angular.element(document.head).append(styleEl)),styleEl.text(styleStr)}for(var tablesThusFar=angular.element(document.getElementsByClassName("smart-table-container")),i=tablesThusFar.length;i>=0;i--)element[0]===tablesThusFar[i]&&(scope.tableId=i);if(scope.tableSize={table:0,wrapper:0},scope.tablePinningActive=!1,scope.columnCollection)for(var i=0,l=scope.columnCollection.length;l>i;i++)ctrl.insertColumn(scope.columnCollection[i]);scope.config.useServer=angular.isDefined(scope.dataSource)?!1:!0,scope.$on("FILTERS_CHANGED",function(){$timeout(function(){scope.currentPage=1,scope.$broadcast("UPDATE_PAGINATION"),ctrl.filterTable()})}),setConfig(),ctrl.setTableFilters();var counter=0,waitForTableToRender=scope.$watch(function(){return element.find("table").length>0?element.find("table")[0].getBoundingClientRect().width:0},function(newValue,oldValue){newValue>0&&(counter++,counter>=10&&waitForTableToRender(),setTablePinning()),element.removeClass("invisible")});angular.element($window).bind("resize",function(){setTablePinning()}),createTableStyles()}}}]).directive("smartTableDataRow",["$compile","$position","$document","$timeout",function($compile,$position,$document,$timeout){return{require:"^smartTable",restrict:"C",link:function(scope,element,attr,ctrl){scope.initialCellHeights=[],scope.setRowHeight=function(){for(var heights=_.union(scope.initialCellHeights,[element[0].getBoundingClientRect().height]),height=_.max(heights),cells=element.children(),i=0;i<element.children().length;i++)i<scope.tablePinnedCols?angular.element(cells[i])[0].style.minHeight=height+"px":angular.element(cells[i])[0].style.height=height+"px"},scope.$on("SET_ROW_HEIGHT",function(event,args){args.tableId!==scope.tableId||scope.tablePinnedHeight&&0!==scope.tablePinnedHeight||scope.setRowHeight()});var _config;null!==(_config=scope.config)&&"function"==typeof _config.rowFunction&&_config.rowFunction(scope,element,attr,ctrl),element.bind("click",function(){scope.$apply(function(){ctrl.toggleSelection(scope.dataRow)})})}}}]).directive("smartTableHeaderCell",function(){return{restrict:"C",require:"^smartTable",link:function(scope,element,attr,ctrl){element.bind("click",function(event){"INPUT"!==event.target.nodeName&&scope.column.isSortable&&scope.$apply(function(){ctrl.sortBy(scope.column)})})}}}).directive("smartTableSelectAll",function(){return{restrict:"C",require:"^smartTable",link:function(scope,element,attr,ctrl){element.bind("click",function(event){ctrl.toggleSelectionAll(element[0].checked===!0)})}}}).directive("stopEvent",function(){return{restrict:"A",link:function(scope,element,attr){element.bind(attr.stopEvent,function(e){e.stopPropagation()})}}}).directive("smartTableSearch",["$api","$errors",function($api,$errors){return{restrict:"C",require:"^smartTable",scope:{columnSpan:"@",tableEmpty:"="},templateUrl:"../ambassador/templates/table/table.search-cell.html",replace:!1,link:function(scope,element,attr,ctrl){var searchValueLoaded=!1;""!==scope.$parent.saved.searchString?(scope.searchValue=scope.$parent.saved.searchString.search,searchValueLoaded=!0):scope.searchValue="",scope.$watch("searchValue",function(newValue,oldValue){(newValue!==oldValue||searchValueLoaded)&&(ctrl.search(newValue,null,searchValueLoaded),searchValueLoaded=!1)}),element.bind("keydown keypress",function(event){13===event.which&&(scope.$apply(function(){ctrl.search(scope.searchValue,null,!0)}),event.preventDefault())}),scope.$on("CLEAR_SEARCH",function(){searchValueLoaded=!0,scope.searchValue=""})}}}]).directive("tableExternalOrdering",[function(){return{restrict:"C",templateUrl:"../ambassador/templates/table/table.external-ordering.html",require:"^smartTable",link:function(scope,element,attrs,ctrl){scope.getData=function(order){scope.externalOrderingOpen=!1,scope.selectedOrder=order;var ordering={sortPredicate:order.predicate,reverse:!1};ctrl.sortByNonColumn(ordering)}}}}]).directive("tableApplyAction",function(){return{restrict:"C",templateUrl:"../ambassador/templates/table/table.apply-action.html",require:"^smartTable",link:function(scope,element,attrs,ctrl){function getSelected(){var i,l=scope.displayedCollection.length,rowsSelected=[];for(i=0;l>i;i++)scope.displayedCollection[i].isSelected&&rowsSelected.push(scope.displayedCollection[i]);return rowsSelected}scope.applyAction={isOpen:!1},scope.action=function(a){var selected=getSelected();scope.applyAction.isOpen=!1,selected.length>0&&(a.loader===!0&&ctrl.showLoader(!0),a.action(selected,function(tableAction){ctrl.toggleSelectionAll(!1),void 0!==tableAction&&("deleteRows"===tableAction?ctrl[tableAction](selected):ctrl[tableAction]())}))}}}}).directive("tableActionButtons",["$timeout",function($timeout){return{restrict:"C",templateUrl:"../ambassador/templates/table/table.actions.html",require:"^smartTable",link:function(scope,element,attrs,ctrl){function getSelected(){var i,l=scope.displayedCollection.length,rowsSelected=[];for(i=0;l>i;i++)scope.displayedCollection[i].isSelected&&rowsSelected.push(scope.displayedCollection[i]);return rowsSelected}scope.numSelected=0,scope.loading={manage:[],"default":[]},scope.manageActions&&angular.forEach(scope.manageActions,function(){scope.loading.manage.push(!1)}),scope.defaultActions&&angular.forEach(scope.defaultActions,function(){scope.loading["default"].push(!1)}),scope.$on("TABLE_UPDATED",function(){for(var i=0;i<scope.dataCollection;i++)scope.dataCollection[i].isSelected=!1;ctrl.toggleSelectionAll(!1)}),scope.$on("ITEM_SELECTED",function(event,data){$timeout(function(){"undefined"!=typeof data&&(scope.dataRow=data.row),scope.numSelected=getSelected().length})}),scope.action=function(a){var selected=getSelected();selected.length>0&&(a.loader===!0&&ctrl.showLoader(!0),a.action(selected,function(tableAction){ctrl.toggleSelectionAll(!1),void 0!==tableAction&&("deleteRows"===tableAction?ctrl[tableAction](selected):ctrl[tableAction]())}))},scope.actionSingle=function(action,index){action(scope.dataRow,function(tableAction){ctrl.toggleSelectionAll(!1),void 0!==tableAction&&ctrl[tableAction](scope.dataRow)},function(status){scope.loading.manage[index]=status})},scope.actionDefault=function(a,index){var selected=0===getSelected().length?scope.displayedCollection:getSelected(),spinnerFunc=function(status){scope.loading["default"][index]=status,status||ctrl.toggleSelectionAll(!1)},btnSpinnerFunc=a.loader?null:spinnerFunc;a.loader===!0&&ctrl.showLoader(!0),a.action(selected,function(tableAction){ctrl.toggleSelectionAll(!1),void 0!==tableAction&&ctrl[tableAction]()},btnSpinnerFunc)}}}}]).directive("displayPerPage",function(){return{restrict:"E",templateUrl:"../ambassador/templates/table/table.display-per-page.html",require:"^smartTable",link:function(scope,element,attrs,ctrl){function capitaliseFirstLetter(string){return string.charAt(0).toUpperCase()+string.slice(1)}var waitForEndpoint=scope.$watch("apiEndpoint",function(){angular.isDefined(scope.apiEndpoint)&&(scope.label=angular.isDefined(scope.paginateLabel)?scope.paginateLabel:capitaliseFirstLetter(scope.apiEndpoint),waitForEndpoint())});scope.pageResults=[{text:"10 results",value:10},{text:"25 results",value:25},{text:"50 results",value:50},{text:"100 results",value:100}],scope.setDisplayPerPage=function(value){scope.setItemsPerPage(value),ctrl.setCurrentPage(1),scope.useServer?ctrl.updateTable():(scope.displayedCollection=ctrl.pipe(scope.dataCollection),ctrl.setPageDisplay())}}}}).directive("manageTableBtn",["$parse",function($parse){return{restrict:"E",templateUrl:"../ambassador/templates/table/table.manage-action-dropdown.html",require:"^?smartTable",link:function(scope,element,attrs,ctrl){if(scope.showTags=!1,scope.manageActionTags){scope.tags=angular.copy(scope.manageActionTags);for(var i=0;i<scope.tags.length;i++)scope.tags[i].active=$parse(scope.tags[i].show)(scope),scope.tags[i].active===!0&&(scope.showTags=!0)}scope.loading=!1,scope.spinnerConf={radius:3,width:2,length:3,lines:9,color:"#ffffff"},scope.action=function(action){action(scope.dataRow,function(tableAction){ctrl.updateTable()},function(status){scope.loading=status})},scope.isZero=function(amount){return 0===parseFloat(amount)},scope.isOpen=!1}}}]).directive("tableEditDelete",function(){return{restrict:"E",templateUrl:"../ambassador/templates/table/table.manage-action-buttons.html",require:"^smartTable",link:function(scope,element,attrs,ctrl){scope.loading=[],angular.forEach(scope.manageActions,function(){scope.loading.push(!1)}),scope.spinnerConf={radius:3,width:2,length:3,lines:9,color:"#ffffff"},scope.action=function(action,index){action(scope.dataRow,function(tableAction){void 0!==tableAction&&ctrl[tableAction](scope.dataRow)},function(status){scope.loading[index]=status})}}}}).directive("tooltipCell",function(){return{restrict:"E",templateUrl:"../ambassador/templates/table/table.tooltip-cell.html",require:"^smartTable",link:function(scope,element,attrs,ctrl){}}}).directive("smartTableDataCell",["$filter","$http","$templateCache","$compile","$parse","$window",function(filter,http,templateCache,compile,parse,$window){return{restrict:"C",template:'<div ng-if="column.cellTemplateUrl" ng-include="column.cellTemplateUrl"></div>',compile:function(element,attributes){return{pre:function(scope,element,attributes,controller,transcludeFn){function defaultContent(){scope.formattedValue=format(getter(row),column.formatFunction,column.formatParameter),element.text(scope.formattedValue)}function setCellHeight(height){scope.initialCellHeights[scope.$index]=height}var childScope,column=scope.column,format=filter("format"),row=scope.dataRow,getter=parse(column.map),count=0;if(scope.$index<scope.tablePinnedCols&&(!scope.tablePinnedHeight||0===scope.tablePinnedHeight))var waitForCellToRender=scope.$watch(function(){return count++,count>=5&&waitForCellToRender(),element[0].getBoundingClientRect().height},function(newValue){setCellHeight(newValue)});column.cellTemplateUrl||(column.cellTemplate?(childScope=scope.$new(),element.html(column.cellTemplate),compile(element.contents())(childScope)):defaultContent()),angular.element($window).bind("resize",function(){setCellHeight(element[0].getBoundingClientRect().height)})}}}}}]).directive("inputType",function(){return{restrict:"A",priority:1,link:function(scope,ielement,iattr){var type=scope.$eval(iattr.type);iattr.$set("type",type)}}}),angular.module("smartTable.filters",[]).constant("DefaultFilters",["currency","date","json","lowercase","number","uppercase"]).filter("format",["$filter","DefaultFilters",function(filter,defaultfilters){return function(value,formatFunction,filterParameter){var returnFunction;return(returnFunction=formatFunction&&angular.isFunction(formatFunction)?formatFunction:-1!==defaultfilters.indexOf(formatFunction)?filter(formatFunction):function(value){return value})(value,filterParameter)}}]),angular.module("smartTable.table",["smartTable.column","smartTable.utilities","smartTable.directives","smartTable.filters","ui.bootstrap.pagination.smartTable"]).constant("DefaultTableConfiguration",{selectionMode:"none",isGlobalSearchActivated:!1,isSearchActive:!0,displaySelectionCheckbox:!1,isPaginationEnabled:!0,isTopPaginationEnabled:!1,itemsByPage:10,maxSize:3,dependencies:[],apiEndpoint:"",tableClass:"",defaultParams:{},sortAlgorithm:"",filterAlgorithm:"",colGroupings:[],tablePinnedCols:0,tablePinnedHeight:0,trackById:null}).controller("SmartTableCtrl",["$scope","$rootScope","Column","$filter","$parse","ArrayUtility","DefaultTableConfiguration","$api","$timeout","$promiseKeeper","$errors",function(scope,rootScope,Column,filter,parse,arrayUtility,defaultConfig,$api,$timeout,$promiseKeeper,$errors){function setColGroups(){for(var colGroups=[],colIncrement=0,i=0;i<scope.colGroupings.length;i++){if(scope.colGroupings[i].start>colIncrement)for(var x=colIncrement;x<scope.colGroupings[i].start;x++)colGroups.push({label:"",length:1}),colIncrement++;colIncrement+=scope.colGroupings[i].length,colGroups.push(scope.colGroupings[i])}if(colIncrement!==scope.columns.length)for(var x=colIncrement;x<scope.columns.length;x++)colGroups.push({label:"",length:1});return colGroups}function isAllSelected(){var i,l=scope.displayedCollection.length;for(i=0;l>i;i++)if(scope.displayedCollection[i].isSelected!==!0)return!1;return!0}function sortDataRow(array,column){var sortAlgo=(scope.sortAlgorithm&&angular.isFunction(scope.sortAlgorithm))===!0?scope.sortAlgorithm:filter("orderBy");return column?arrayUtility.sort(array,sortAlgo,column.sortPredicate,column.reverse):array}function selectDataRow(array,selectionMode,index,select){var dataRow,oldValue;if(angular.isArray(array)&&("multiple"===selectionMode||"single"===selectionMode)&&index>=0&&index<array.length){if(dataRow=array[index],"single"===selectionMode)for(var i=0,l=array.length;l>i;i++)oldValue=array[i].isSelected,array[i].isSelected=!1,oldValue===!0&&scope.$emit("selectionChange",{item:array[i]});dataRow.isSelected=select,scope.holder.isAllSelected=isAllSelected(),scope.$emit("selectionChange",{item:dataRow})}}function setOrdering(column){return column.reverse?"-"+column.sortPredicate:column.sortPredicate}function parseFilters(filtersArray){var filters={};return angular.isDefined(filtersArray)&&0!==filtersArray.length?(filtersArray.forEach(function(filter){filters[filter.param]=filter.param_val}),filters):filters}function filterTableServer(data){rootScope.$broadcast("TABLE_FINISHED_LOADING",{tableId:scope.tableId,count:data.length,filters:scope.filters,search:scope.config.search}),scope.fullDatasetLoad?(scope.exposedData=angular.copy(data),scope.displayedCollection=data.splice(scope.currentPage*scope.itemsByPage-scope.itemsByPage,scope.itemsByPage),scope.fullDatasetLoad=!1):scope.displayedCollection=data,rootScope.$broadcast("RESET_SELECT_ALL",{tableId:scope.tableId}),$timeout(function(){scope.$broadcast("SET_ROW_HEIGHT",{tableId:scope.tableId})}),scope.totalRows=data.count,self.calculateNumberOfPages(scope.totalRows),self.setPageDisplay()}function useServer(){self.getData().then(function(data){filterTableServer(data)})}function checkFilterFuncs(){for(var i=0,l=scope.filters.length;l>i;i++)if(void 0===scope.filters[i].filterFunc)return!0;return!1}scope.columns=[],scope.dataCollection=scope.dataSource||[],scope.displayedCollection=[],scope.numberOfPages=0,scope.currentPage=1,scope.holder={isAllSelected:!1},scope.useServer=!1,scope.tableLoader=!1,scope.noResults=!1,scope.tableEmpty=!1,scope.saved={filtersId:void 0,searchString:""},scope.fullDatasetLoad=angular.isArray(scope.exposedData)&&0===scope.exposedData.length?!0:!1;var lastColumnSort,search,predicate={},self=this;scope.$on("RESET_SELECT_ALL",function(event,args){if(args.tableId===scope.tableId){for(var i=0;i<scope.dataCollection;i++)scope.dataCollection[i].isSelected=!1;scope.holder.isAllSelected=!1}}),scope.isColInGroup=function(colIndex){for(var colIncrement=0,i=0;i<scope.colGroups.length;i++)if(colIncrement+=scope.colGroups[i].length,colIncrement-1>=colIndex)return""!==scope.colGroups[i].label?!0:!1},scope.isGroupBorder=function(colIndex){for(var colIncrement=0,i=0;i<scope.colGroups.length;i++)if(colIncrement+=scope.colGroups[i].length,colIncrement-1>=colIndex){if(""!==scope.colGroups[i].label&&colIndex===scope.colGroups[i].start)return colIndex-1!==scope.colGroups[i-1].start+scope.colGroups[i-1].length-1?"start":"start-no-border";if(""!==scope.colGroups[i].label&&colIndex===scope.colGroups[i].start+scope.colGroups[i].length-1)return"end"}},scope.updateFilters=function(newFilters){if("undefined"!=typeof newFilters&&(scope.filters=newFilters,scope.$broadcast("FILTERS_CHANGED")),"undefined"!=typeof scope.filterSetType&&""!==scope.filterSetType)if("undefined"!=typeof scope.saved.filtersId){for(var searchSaved=void 0,found=!1,i=0;i<scope.saved.filters.length;i++)if("undefined"!=typeof scope.saved.filters[i].search){scope.searchChanged?(scope.saved.filters[i].search=scope.config.search,found=!0):searchSaved=scope.saved.filters[i];break}scope.searchChanged||(scope.saved.filters=scope.filters.slice(),"undefined"!=typeof searchSaved&&scope.saved.filters.push(searchSaved)),scope.searchChanged&&!found&&scope.saved.filters.push({search:scope.config.search}),$api.use("default").one("filters",scope.saved.filtersId).patch({filters:scope.saved.filters}).then(function(data){},function(error){$errors.output({alertSystem:"table-filter-alerts",alertSystemType:"page",defaultMessage:"There was an error saving your filter set. Please try removing the last filter and adding it again if you want it to be saved."},error.data)})}else{var filterSet={name:scope.filterSetType+" filters",type:scope.filterSetType,filters:scope.searchChanged?[{search:scope.config.search}]:scope.filters};$api.use("default").all("filters").post(filterSet).then(function(data){scope.saved.filtersId=data.id},function(error){$errors.output({alertSystem:"table-filter-alerts",alertSystemType:"page",defaultMessage:"There was an error saving your filter set. Please try removing the last filter and adding it again if you want it to be saved."},error.data)})}scope.searchChanged=!1},scope.setItemsPerPage=function(value){scope.itemsByPage=value},scope.clearSearch=function(){scope.$broadcast("CLEAR_SEARCH")},scope.itemSelected=function(dataRow){scope.$broadcast("ITEM_SELECTED",{row:dataRow}),$timeout(function(){scope.holder.isAllSelected=isAllSelected()})},scope.getRowIndex=function(dataRow){return scope.displayedCollection.indexOf(dataRow)},scope.$on("EXPORT_COLLECTION",function(){scope.tableData.displayedCollection=scope.displayedCollection}),scope.$on("UPDATE_TABLE",function(){angular.isArray(scope.exposedData)&&(scope.currentPage=1,scope.$broadcast("UPDATE_PAGINATION"),scope.fullDatasetLoad=!0),self.updateTable()}),this.setRowsLength=function(){scope.totalRows=scope.dataCollection.length},this.calculateNumberOfPages=function(total){scope.numberOfPages=0===total||scope.itemsByPage<1?1:Math.ceil(total/scope.itemsByPage),scope.$broadcast("UPDATE_PAGINATION")},this.setPageDisplay=function(){var rowsShowing=scope.itemsByPage;scope.pageStartNumber=(scope.currentPage-1)*rowsShowing+1,scope.pageEndNumber=(scope.currentPage-1)*rowsShowing+scope.displayedCollection.length},this.setGlobalConfig=function(config){angular.extend(scope,defaultConfig,config)},this.changePage=function(page){var oldPage=scope.currentPage;angular.isNumber(page.page)&&(scope.currentPage=page.page,scope.$broadcast("UPDATE_PAGINATION"),scope.useServer?this.getData().then(function(data){filterTableServer(data)}):(scope.displayedCollection=this.pipe(scope.dataCollection),scope.holder.isAllSelected=isAllSelected(),this.setPageDisplay(),scope.$emit("changePage",{oldValue:oldPage,newValue:scope.currentPage})))},this.sortBy=function(column){var index=scope.columns.indexOf(column);-1!==index&&column.isSortable===!0&&(lastColumnSort&&lastColumnSort!==column&&(lastColumnSort.reverse="none"),column.sortPredicate=column.sortPredicate||column.map,column.reverse=column.reverse!==!0,lastColumnSort=column),scope.useServer?this.getData(column).then(function(data){filterTableServer(data)}):(scope.displayedCollection=this.pipe(scope.dataCollection),this.setPageDisplay())},this.sortByNonColumn=function(params){lastColumnSort=params,scope.useServer?(this.setCurrentPage(1),this.getData(params).then(function(data){filterTableServer(data)})):(scope.displayedCollection=this.pipe(scope.dataCollection),this.setPageDisplay())},this.search=function(input,column,instant){scope.config.search=input,scope.searchChanged=!0,instant===!0?($timeout.cancel(search),scope.currentPage=1,scope.$broadcast("UPDATE_PAGINATION"),self.getData().then(function(data){filterTableServer(data),scope.updateFilters(),scope.saved.searchString={search:scope.config.search}})):(column&&-1!==scope.columns.indexOf(column)?predicate[column.map]=input:predicate={$:input},scope.useServer?(void 0!==search&&$timeout.cancel(search),search=$timeout(function(){scope.currentPage=1,scope.$broadcast("UPDATE_PAGINATION"),self.getData().then(function(data){filterTableServer(data),scope.updateFilters(),scope.saved.searchString={search:scope.config.search}})},1500)):(scope.currentPage=1,scope.$broadcast("UPDATE_PAGINATION"),scope.displayedCollection=this.pipe(scope.dataCollection),scope.updateFilters()))},this.pipe=function(array){var output,filterAlgo=(scope.filterAlgorithm&&angular.isFunction(scope.filterAlgorithm))===!0?scope.filterAlgorithm:filter("filter");return output=sortDataRow(arrayUtility.filter(array,filterAlgo,predicate),lastColumnSort),this.calculateNumberOfPages(scope.totalRows),scope.isPaginationEnabled?arrayUtility.fromTo(output,(scope.currentPage-1)*scope.itemsByPage,scope.itemsByPage):output},this.updateTable=function(){this.getData().then(function(data){filterTableServer(data),rootScope.$broadcast("TABLE_UPDATED"),scope.numSelected=0;for(var i=0;i<scope.dataCollection;i++)scope.dataCollection[i].isSelected=!1;scope.holder.isAllSelected=!1})},this.filterTable=function(){var filtered;scope.useServer||checkFilterFuncs()?useServer():(filtered=scope.dataCollection,angular.forEach(scope.filters,function(filter){filtered=filtered.filter(function(item){return filter.filterFunc(item,filter)})}),scope.totalRows=filtered.length,scope.displayedCollection=this.pipe(filtered),this.setPageDisplay())};var tableLoaderPromise;this.showLoader=function(){$promiseKeeper.getActive()?("undefined"==typeof tableLoaderPromise||"success"===tableLoaderPromise.status)&&(tableLoaderPromise=$promiseKeeper.add()):scope.tableLoader=!0},this.setCurrentPage=function(page){scope.currentPage=page,scope.$broadcast("UPDATE_PAGINATION")},this.hideLoader=function(){scope.tableLoader=!1,void 0!==tableLoaderPromise&&tableLoaderPromise.deferred.resolve()},this.getData=function(column){var data,searchConfig={},filters=parseFilters(scope.filters),search=void 0===scope.config.search||""===scope.config.search?{}:{search:scope.config.search},orderParam=scope.config.displayTopAmbassadorsOrdering?"stat":"ordering";(scope.currentPage-1)*scope.itemsByPage>=scope.totalRows-scope.deletingRows&&(scope.currentPage>1&&scope.currentPage--,scope.deletingRows=0),angular.extend(searchConfig,scope.defaultParams,search,filters,{page:scope.currentPage,page_size:scope.fullDatasetLoad?0:scope.itemsByPage}),void 0!==lastColumnSort?searchConfig[orderParam]=setOrdering(lastColumnSort):void 0!==column?searchConfig[orderParam]=setOrdering(column):void 0!==scope.startingOrder&&(searchConfig[orderParam]=scope.startingOrder),self.showLoader();var ignoredParams=["page","page_size","ordering"];return data=$api.use("default").all(scope.apiEndpoint).getList(searchConfig),data.then(function(results){if(0===results.length){scope.noResults=!0,scope.tableEmpty=!0;for(var key in searchConfig)-1===ignoredParams.indexOf(key)&&(scope.tableEmpty=!1)}else scope.noResults=!1;self.hideLoader()},function(error){scope.noResults=!0,self.hideLoader(),scope.currentPage>1?(scope.currentPage--,self.updateTable()):$errors.output({alertSystem:"table-filter-alerts",alertSystemType:"page",defaultMessage:'There was an error while loading the table. Please try reloading the page or contact <a href="http://support.getambassador.com/customer/portal/emails/new" target="_blank">support</a> if the problem persists.'},error.data)}),data},this.setTableFilters=function(){"undefined"!=typeof scope.config.tableFilterSetType?(scope.colGroups=setColGroups(),$api.use("default").all("filters").getList({type:scope.config.tableFilterSetType}).then(function(data){if(data[0]&&"undefined"!=typeof data[0].id){scope.saved.filtersId=data[0].id,scope.saved.filters=data[0].filters||[];for(var removeIndex=null,i=0;i<scope.saved.filters.length;i++)if("undefined"!=typeof scope.saved.filters[i].search){removeIndex=i,scope.config.search=scope.saved.filters[i].search;break}var temp=null!==removeIndex?(temp=scope.saved.filters.slice(),temp.splice(removeIndex,1),temp):scope.saved.filters.slice();scope.filters=temp,scope.filters.length>0&&!removeIndex&&scope.$broadcast("FILTERS_CHANGED"),scope.saved.searchString=null!==removeIndex?scope.saved.filters[removeIndex]:{search:""}}else scope.saved.filters=[],self.initialize();scope.table.load=!0},function(error){$errors.output({alertSystem:"table-filter-alerts",alertSystemType:"page",defaultMessage:"There was an error fetching your previously saved filter set. Please reload the page to try again."},error.data),scope.table.load=!0})):self.initialize()},this.initialize=function(){scope.colGroups=setColGroups(),self.getData().then(function(data){filterTableServer(data)})},this.insertColumn=function(columnConfig,index){var column=new Column(columnConfig);arrayUtility.insertAt(scope.columns,index,column)},this.removeColumn=function(columnIndex){arrayUtility.removeAt(scope.columns,columnIndex)},this.moveColumn=function(oldIndex,newIndex){arrayUtility.moveAt(scope.columns,oldIndex,newIndex)},this.clearColumns=function(){scope.columns.length=0},this.toggleSelection=function(dataRow){var index=scope.dataCollection.indexOf(dataRow);-1!==index&&selectDataRow(scope.dataCollection,scope.selectionMode,index,dataRow.isSelected!==!0)},this.toggleSelectionAll=function(value){var i=0,l=scope.displayedCollection.length;if("multiple"===scope.selectionMode){for(;l>i;i++)selectDataRow(scope.displayedCollection,scope.selectionMode,i,value===!0);value===!1&&(scope.holder.isAllSelected=!1),scope.$broadcast("ITEM_SELECTED")}},this.removeDataRow=function(rowIndex){var toRemove=arrayUtility.removeAt(scope.displayedCollection,rowIndex);arrayUtility.removeAt(scope.dataCollection,scope.dataCollection.indexOf(toRemove))},this.moveDataRow=function(oldIndex,newIndex){arrayUtility.moveAt(scope.displayedCollection,oldIndex,newIndex)},this.updateDataRow=function(dataRow,propertyName,newValue){var oldValue,index=scope.displayedCollection.indexOf(dataRow),getter=parse(propertyName),setter=getter.assign;-1!==index&&(oldValue=getter(scope.displayedCollection[index]),oldValue!==newValue&&(setter(scope.displayedCollection[index],newValue),scope.$emit("updateDataRow",{item:scope.displayedCollection[index]})))},this.deleteRow=function(dataRow){dataRow.remove().then(function(){var index=scope.displayedCollection.indexOf(dataRow);self.removeDataRow(index),scope.deletingRows=1,self.updateTable()})},this.deleteRows=function(dataRows){var count=dataRows.length;angular.forEach(dataRows,function(dataRow){dataRow.remove().then(function(){var index=scope.displayedCollection.indexOf(dataRow);self.removeDataRow(index),--count,0===count&&(scope.deletingRows=dataRows.length,self.updateTable())})})}}])}(angular),function(angular){"use strict";angular.module("smartTable.utilities",[]).factory("ArrayUtility",function(){var removeAt=function(arrayRef,index){return index>=0&&index<arrayRef.length?arrayRef.splice(index,1)[0]:void 0},insertAt=function(arrayRef,index,item){index>=0&&index<arrayRef.length?arrayRef.splice(index,0,item):arrayRef.push(item)},moveAt=function(arrayRef,oldIndex,newIndex){var elementToMove;oldIndex>=0&&oldIndex<arrayRef.length&&newIndex>=0&&newIndex<arrayRef.length&&(elementToMove=arrayRef.splice(oldIndex,1)[0],arrayRef.splice(newIndex,0,elementToMove))},sort=function(arrayRef,sortAlgorithm,predicate,reverse){return sortAlgorithm&&angular.isFunction(sortAlgorithm)?sortAlgorithm(arrayRef,predicate,reverse===!0):arrayRef},filter=function(arrayRef,filterAlgorithm,predicate){return filterAlgorithm&&angular.isFunction(filterAlgorithm)?filterAlgorithm(arrayRef,predicate):arrayRef},fromTo=function(arrayRef,min,length){var limit,start,out=[];if(!angular.isArray(arrayRef))return arrayRef;start=Math.max(min,0),start=Math.min(start,arrayRef.length-1>0?arrayRef.length-1:0),length=Math.max(0,length),limit=Math.min(start+length,arrayRef.length);for(var i=start;limit>i;i++)out.push(arrayRef[i]);return out};return{removeAt:removeAt,insertAt:insertAt,moveAt:moveAt,sort:sort,filter:filter,fromTo:fromTo}}),angular.module("ui.bootstrap.pagination.smartTable",[]).constant("paginationConfig",{boundaryLinks:!1,directionLinks:!0,firstText:"First",previousText:"<",nextText:">",lastText:"Last"}).directive("paginationSmartTable",["paginationConfig","$timeout",function(paginationConfig,$timeout){return{restrict:"EA",require:"^smartTable",scope:{numPages:"=",currentPage:"=",maxSize:"="},templateUrl:"../ambassador/templates/table/table.pagination.html",replace:!0,link:function(scope,element,attrs,ctrl){function makePage(number,text,isActive,isDisabled,prevNext,prevNextAltText){return{number:number,text:prevNext?text:"Page "+text,altText:prevNext?prevNextAltText:text,active:isActive,disabled:isDisabled}}function updatePagination(numPages,currentPage,maxSize){scope.pages=[];var startPage=1,endPage=scope.numPages;scope.maxSize&&scope.maxSize<scope.numPages&&(startPage=Math.max(scope.currentPage-Math.floor(scope.maxSize/2),1),endPage=startPage+scope.maxSize-1,endPage>scope.numPages&&(endPage=scope.numPages,startPage=endPage-scope.maxSize+1));for(var number=startPage;endPage>=number;number++){var page=makePage(number,number,scope.isActive(number),!1);scope.pages.push(page)}if(directionLinks){var previousPage=makePage(scope.currentPage-1,previousText,!1,scope.noPrevious(),!0,"<");scope.pages.unshift(previousPage);var nextPage=makePage(scope.currentPage+1,nextText,!1,scope.noNext(),!0,">");scope.pages.push(nextPage)}if(boundaryLinks){var firstPage=makePage(1,firstText,!1,scope.noPrevious());scope.pages.unshift(firstPage);var lastPage=makePage(scope.numPages,lastText,!1,scope.noNext());scope.pages.push(lastPage)}scope.currentPage>scope.numPages&&scope.selectPage(scope.numPages)}var boundaryLinks=angular.isDefined(attrs.boundaryLinks)?scope.$eval(attrs.boundaryLinks):paginationConfig.boundaryLinks,directionLinks=angular.isDefined(attrs.directionLinks)?scope.$eval(attrs.directionLinks):paginationConfig.directionLinks,firstText=angular.isDefined(attrs.firstText)?attrs.firstText:paginationConfig.firstText,previousText=angular.isDefined(attrs.previousText)?attrs.previousText:paginationConfig.previousText,nextText=angular.isDefined(attrs.nextText)?attrs.nextText:paginationConfig.nextText,lastText=angular.isDefined(attrs.lastText)?attrs.lastText:paginationConfig.lastText;
scope.$on("UPDATE_PAGINATION",function(){$timeout(function(){updatePagination(scope.numPages,scope.currentPage,scope.maxSize)})}),scope.noPrevious=function(){return 1===scope.currentPage},scope.noNext=function(){return scope.currentPage===scope.numPages},scope.isActive=function(page){return scope.currentPage===page},scope.selectPage=function(page){!scope.isActive(page)&&page>0&&page<=scope.numPages&&(scope.currentPage=page,ctrl.changePage({page:page}))}}}}]),angular.module("ambassador.table.filters",[]).directive("tableFilterSelect",["$api","$errors","$filter","$timeout","dateParser",function($api,$errors,$filter,$timeout,dateParser){return{restrict:"E",scope:{filters:"=",config:"=",currency:"=",filterSetType:"@",filtersId:"=?",savedFilters:"=?",updateFilters:"&",tableEmpty:"=",dropdownLabel:"@"},controller:"tableFilterCtrl",templateUrl:"../ambassador/templates/table/table.filter-select.html",link:function(scope,elm,attrs,ctrl){function Filter(config){this.label=config.label,this.param=config.param,this.param_val=null,this.val_label_prefix=config.displayParamPrefix,this.val_label=config.displayParam,angular.isDefined(config.filterFunc)&&(this.filterFunc=config.filterFunc)}function checkCurrentFilters(newFilter){return angular.forEach(scope.filters,function(filter){return filter.template===newFilter.template?!0:void 0}),!1}var currencies={USD:"$",GBP:"£",SGD:"S$",EUR:"€",AUD:"A$",ZAR:"R",BRL:"R$",CAD:"C$",NZD:"NZ$"};scope.currencySymbol=currencies[scope.currency],scope.datepickerConfig={isOpen:!0},scope.filterSelect={isOpen:!1},scope.selectFilter=function(filter){scope.filterValueError=!1,scope.focusInput=!1,"typeahead"===filter.template&&(scope.useDropdown=filter.useDropdown,filter.useDropdown?scope.typeaheadData=filter.data:scope.typeaheadData=[]),"calendar"===filter.template&&(scope.datepickerConfig.isOpen=!0),scope.selectedFilter=filter,scope.$broadcast("FILTER_SELECTED")},scope.selectOption=function(value){scope.filterValue=value,scope.addFilter(scope.selectedFilter,scope.filterValue)},scope.checkDate=function(filter,value){var format="undefined"!=typeof scope.activeFilter.config.format?scope.activeFilter.config.format:"MM-dd-yyyy";$timeout(function(){"undefined"!=typeof dateParser.parse(elm.find("input")[0].value,format)&&scope.addFilter(filter,value)},0)},scope.addFilter=function(filter,value){var newFilter;if(""!==scope.filterValue&&(value=scope.filterValue),""!==value&&!checkCurrentFilters(filter)){if(newFilter=new Filter(filter),"calendar"===filter.template)newFilter.param_val=$filter("date")(value,"yyyy-MM-dd"),newFilter.val_label=$filter("date")(value,scope.activeFilter.config.format?scope.activeFilter.config.format:"MM-dd-yyyy");else if("number"===filter.template||"money"===filter.template){var v=value.replace(/[\,]/g,"");_.isNumber(+v)&&!_.isNaN(+v)?(scope.filterValueError=!1,scope.focusInput=!1,newFilter.param_val=v,newFilter.val_label=("money"===filter.template?scope.currencySymbol:"")+$filter("number")(v,2)):(scope.filterValueError=!0,scope.focusInput=!0)}else"text"===filter.template?(newFilter.param_val=value,newFilter.val_label=value):"undefined"!=typeof filter.options?(newFilter.param_val=value.value,newFilter.val_label=value.label):(newFilter.param_val="undefined"!=typeof filter.async.param?value[filter.async.param]:value[newFilter.param],newFilter.val_label=newFilter.val_label_prefix?value[newFilter.val_label_prefix]+" - "+value[newFilter.val_label]:value[newFilter.val_label]);scope.filterValueError||(scope.$emit("FILTERS_CHANGED"),scope.filters.push(newFilter),scope.updateFilters(),scope.selectedFilter="",scope.$broadcast("FILTER_SELECTED"),scope.filterSelect.isOpen=!1)}},scope.clearAll=function(){scope.filters.length=0,scope.$emit("FILTERS_CHANGED"),scope.filterSelect.isOpen=!1,scope.updateFilters()},scope.resetFilter=function(){scope.selectedFilter="",scope.$broadcast("FILTER_SELECTED")},scope.filterSelected=function(item){if(0===scope.filters.length)return item;for(var found=!0,i=0;i<scope.filters.length;i++){if(item.label===scope.filters[i].label){found=!0;break}found=!1}return found?void 0:item},void 0!==scope.config&&(ctrl.setConfig(scope.config),scope.filters.length>0&&angular.forEach(scope.filters,function(filter){scope.filterSelected(filter)}))}}}]).directive("tableFilterActive",[function(){return{restrict:"E",scope:{filters:"=",updateFilters:"&",search:"=",updateSearch:"&"},controller:"tableFilterCtrl",templateUrl:"../ambassador/templates/table/table.filter-active.html",link:function(scope,elm,attrs,ctrl){scope.removeFilter=function(filter){scope.filters=_.without(scope.filters,filter),scope.updateFilters({newFilters:scope.filters})},scope.clearSearch=function(){scope.search="",scope.updateSearch()}}}}]).directive("tableFilterInput",["$compile","$timeout",function($compile,$timeout){return{restrict:"E",require:"^tableFilterSelect",link:function(scope,elm,attrs,ctrl){function compileInput(filterTemp){filterTemp?elm.html(templates[filterTemp]):elm.html(""),$compile(elm.contents())(scope)}function filterSelected(filter){""===filter?(compileInput(),scope.filterValue=""):(scope.activeFilter=filter,compileInput(filter.template),("text"===filter.template||"number"===filter.template||"money"===filter.template)&&$timeout(function(){elm.find("input")[0].focus()}),"typeahead"===filter.template&&(filter.useDropdown||$timeout(function(){elm.find("input")[0].focus()})))}var templates={text:'<div class="input-group"><input ng-model="filterValue" ga-enter="addFilter(selectedFilter, filterValue)" class="form-control" type="text"><span class="input-group-btn"><button ng-click="addFilter(selectedFilter, filterValue)" class="btn btn-default" type="button"><i class="fa fa-plus"></i></button></span></div>',select:'<div class="table-dropdown open"><a class="dropdown-toggle btn btn-default"> Select an option<i class="caret"></i></a><ul class="dropdown-menu"><li ng-repeat="o in activeFilter.options"><a ng-click="selectOption(o)">{{o.label}}</a></li></ul></div>',number:'<div class="input-group" ng-class="{\'has-error\': filterValueError}"><input ng-model="filterValue" ga-enter="addFilter(selectedFilter, filterValue)" class="form-control" type="text"><span class="input-group-btn"><button ng-click="addFilter(selectedFilter, filterValue)" class="btn btn-default" type="button"><i class="fa fa-plus"></i></button></span></div>',money:'<div class="input-group input-money" ng-class="{\'has-error\': filterValueError}"><span class="input-group-addon">{{currencySymbol}}</span><input ng-model="filterValue" ga-enter="addFilter(selectedFilter, filterValue)" type="text" class="form-control"><span class="input-group-btn"><button ng-click="addFilter(selectedFilter, filterValue)" class="btn btn-default" type="button"><i class="fa fa-plus"></i></button></span></div>',typeahead:'<div><div ng-if="!useDropdown" class="async-loader"><input type="text" ng-model="filterValue" placeholder="Search {{activeFilter.async.endpoint}}" typeahead="o as o[activeFilter.async.field] for o in asyncSearch($viewValue) | filter:{ activeFilter.async.field: $viewValue} | limitTo:15" typeahead-loading="async.loadingResults" typeahead-wait-ms="async.asyncWaitTime" typeahead-template-url="../ambassador/templates/table/table.typeahead-filter-template.html" typeahead-on-select="addFilter(selectedFilter, filterValue)" class="form-control"><i ng-show="async.loadingResults" class="fa fa-refresh fa-spin"></i></div><div ng-if="useDropdown" class="dropdown dropdown-select" is-open="tyepaheadDropdown.isOpen" ng-init="tyepaheadDropdown.isOpen = true"><a class="dropdown-toggle btn btn-default">Select {{activeFilter.async.endpoint}} <i class="caret"></i></a><ul class="dropdown-menu"><li ng-repeat="o in typeaheadData" ng-if="typeaheadData.length > 0"><a ng-click="addFilter(selectedFilter, o)"><span ng-if="activeFilter.async.displayPrefix !== undefined">{{o[activeFilter.async.displayPrefix]}} - </span>{{o[activeFilter.async.field]}}</a></li><li ng-if="typeaheadData.length === 0"><a ng-if="activeFilter.noItems !== undefined && !activeFilter.noItems.callback" ng-click="resetFilter()"><span ng-if="activeFilter.noItems.text !== undefined">{{activeFilter.noItems.text}}</span><span ng-if="!activeFilter.noItems.text">No {{activeFilter.async.endpoint}} to select</span></a><a ng-if="activeFilter.noItems !== undefined && activeFilter.noItems.callback !== undefined" ng-click="callbackFunction()"><span ng-if="activeFilter.noItems.text !== undefined">{{activeFilter.noItems.text}}</span><span ng-if="!activeFilter.noItems.text">No {{activeFilter.async.endpoint}} to select</span></a></li></ul></div></div>',calendar:'<div class="datepicker-field"><input type="text" class="form-control" ng-change="checkDate(selectedFilter, filterValue)" placeholder="{{activeFilter.config.format.toLowerCase() || \'mm-dd-yyyy\'}}" datepicker-popup="{{activeFilter.config.format || \'MM-dd-yyyy\'}}" datepicker-options="{showWeeks: false}" is-open="datepickerConfig.isOpen" ng-click="datepickerConfig.isOpen = true;" show-button-bar="false" ng-model="filterValue" min-date="activeFilter.config.minDate" max-date="activeFilter.config.maxDate" /></div>'};scope.$on("FILTER_SELECTED",function(){filterSelected(scope.selectedFilter)}),scope.$watch("focusInput",function(focus){$timeout(function(){focus&&scope.filterValueError&&(elm.find("input")[0].focus(),scope.focusInput=!1)})}),scope.callbackFunction=function(){scope.activeFilter.noItems.callback(),scope.resetFilter()}}}}]).controller("tableFilterCtrl",["$scope","$api","$q",function($scope,$api,$q){var abortSearch;$scope.selectedFilter="",$scope.filterValue="",$scope.async={loadingResults:!1,asyncWaitTime:500},$scope.activeFilter={},$scope.filterOptions=[],this.setConfig=function(config){angular.forEach(config,function(filter){"typeahead"===filter.template&&$scope.getData(filter),$scope.filterOptions.push(filter)})},$scope.getData=function(filter){$api.use("default").all(filter.async.endpoint).getList({page_size:25}).then(function(data){data.count<=25?(filter.data=data,filter.useDropdown=!0):filter.useDropdown=!1})},$scope.asyncSearch=function(value){return abortSearch&&abortSearch.resolve(),abortSearch=$q.defer(),$scope.async.loadingResults=!0,$api.use("default").all($scope.activeFilter.async.endpoint).withHttpConfig({timeout:abortSearch.promise}).getList({search:value,ordering:$scope.activeFilter.async.field}).then(function(data){return $scope.async.loadingResults=!1,data})}}])}(angular);