From e052fff8dcffeaa67069b98055367e1c108dc415 Mon Sep 17 00:00:00 2001 From: Andrew Kos Date: Wed, 24 Feb 2016 11:15:38 -0600 Subject: [PATCH] new build --- dist/scripts/scripts.js | 3 ++- dist/scripts/scripts.min.js | 10 +++++----- dist/scripts/templates.js | 2 +- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/dist/scripts/scripts.js b/dist/scripts/scripts.js index 3671b9454..7593d8330 100644 --- a/dist/scripts/scripts.js +++ b/dist/scripts/scripts.js @@ -5833,7 +5833,8 @@ angular.module('cms.tunic.config', [ * @returns {boolean} true if url should be intercepted, false otherwise. */ shouldBeIntercepted: function (url) { - return url.startsWith(backendRoot + apiPath); + var urlTest = backendRoot + apiPath; + return urlTest !== '' && url.startsWith(urlTest); } }; }; diff --git a/dist/scripts/scripts.min.js b/dist/scripts/scripts.min.js index d8c4e7f08..8524974af 100644 --- a/dist/scripts/scripts.min.js +++ b/dist/scripts/scripts.min.js @@ -1,8 +1,8 @@ function safeApply(scope,fn){scope.$$phase||scope.$root.$$phase?fn():scope.$apply(function(){fn()})}!function(w){function computeStyle(element,image,selection){var scale,selector='.image[data-image-id="'+image.id+'"]>div',elementWidth=$(selector).width(),elementHeight=image.height/image.width*elementWidth,s_width=selection.x1-selection.x0,s_height=selection.y1-selection.y0,tmp_selection=selection;s_width&&s_height||(s_width=elementWidth,s_height=elementHeight,tmp_selection={x0:0,y0:0,x1:s_width,y1:s_height});var imageUrl=w.BC_ADMIN_URL+"/"+image.id+"/original/1200.jpg";scale=elementWidth/s_width;var rules={"background-image":"url("+imageUrl+")","background-size":scaleNumber(image.width,scale)+"px","background-position":"-"+scaleNumber(tmp_selection.x0,scale)+"px -"+scaleNumber(tmp_selection.y0,scale)+"px","background-repeat":"no-repeat"};createStyle(selector,rules,"image-css-"+image.id)}function createStyle(selector,rules,classname){var styleNode=document.createElement("style");styleNode.type="text/css",styleNode.className=classname;var css="",temp=""+selector+"{";for(var rule in rules)temp+=rule+":"+rules[rule]+";";temp+="}",css+=temp,styleNode.styleSheet?styleNode.styleSheet.cssText=css:styleNode.appendChild(document.createTextNode(css)),$(document).find("head").append(styleNode)}function scaleNumber(num,by_scale){return Math.floor(num*by_scale)}function computeAspectRatio(_w,_h){if(0!==_w&&0!==_h){var aspectRatio=Math.ceil(_w/_h*10);switch(aspectRatio){case 30:case 31:crop="3x1";break;case 20:crop="2x1";break;case 14:crop="4x3";break;case 18:crop="16x9";break;case 8:crop="3x4";break;case 10:crop="1x1";break;default:crop="original"}return crop}return"16x9"}w.picturefill=function(element){var ps;element&&"image"===element.getAttribute("data-type")?ps=[element]:("undefined"==typeof element&&(element=w.document),ps=element.getElementsByTagName("div"));for(var i=0,il=ps.length;il>i;i++){var el=ps[i];if("image"===el.getAttribute("data-type")){var div=el.getElementsByTagName("div")[0];if(null!==el.getAttribute("data-image-id")){var id=el.getAttribute("data-image-id"),crop=el.getAttribute("data-crop"),_w=div.offsetWidth,_h=div.offsetHeight;crop&&""!==crop&&"auto"!==crop||(crop=computeAspectRatio(_w,_h)),el.getAttribute("data-format")?format=el.getAttribute("data-format"):format="jpg";var element=div;id&&($(".image-css-"+id).remove(),$.ajax({url:w.BC_ADMIN_URL+"/api/"+id,headers:{"X-Betty-Api-Key":w.BC_API_KEY,"Content-Type":void 0},success:$.proxy(function(res){var imageData=res;if("original"===this.crop){createStyle('.image[data-image-id="'+this.id+'"]>div',{"padding-bottom":res.height/res.width*100+"%"},"image-css-"+this.id);var cropDetails={x0:0,x1:res.width,y0:0,y1:res.height}}else var cropDetails=imageData.selections[this.crop];computeStyle(this.element,imageData,cropDetails)},{element:element,id:id,crop:crop}),error:$.proxy(function(){"original"===this.crop&&createStyle('.image[data-image-id="'+this.id+'"]>div',{"padding-bottom":"56.25%","background-color":"rgba(200, 0,0, .5)"},"image-css-"+this.id)},{id:id,crop:crop})}))}}}}}(this),$(document).unbind("keydown").bind("keydown",function(event){var doPrevent=!1;if(8===event.keyCode){var d=event.srcElement||event.target;doPrevent=["TEXTAREA","INPUT"].indexOf(-1!==d.tagName.toUpperCase())?d.readOnly||d.disabled:d.isContentEditable?!1:!0}doPrevent&&event.preventDefault()}),angular.module("lodash",[]).constant("_",window._),angular.module("URLify",[]).constant("URLify",window.URLify),angular.module("jquery",[]).constant("$",window.$),angular.module("moment",[]).constant("moment",window.moment),angular.module("PNotify",[]).constant("PNotify",window.PNotify),angular.module("keypress",[]).constant("keypress",window.keypress),angular.module("Raven",[]).constant("Raven",window.Raven),angular.module("OnionEditor",[]).constant("OnionEditor",window.OnionEditor),angular.module("bulbsCmsApp",["bulbsCmsApp.settings","ngCookies","ngResource","ngRoute","ui.bootstrap","ui.bootstrap.datetimepicker","restangular","BettyCropper","jquery","lodash","URLify","moment","PNotify","keypress","Raven","firebase","ipCookie","bulbs.api","OnionEditor","contentServices","cms.tunic","bettyEditable","bugReporter","campaigns","filterWidget","filterListWidget","polls","promotedContent","statusFilter","templateTypeField","specialCoverage","sections","reports"]).config(function($locationProvider,$routeProvider,$sceProvider,routes){$locationProvider.html5Mode(!0),$routeProvider.when("/cms/app/list/",{templateUrl:routes.PARTIALS_URL+"contentlist.html",controller:"ContentlistCtrl",reloadOnSearch:!1}).when("/cms/app/edit/:id/",{templateUrl:routes.PARTIALS_URL+"contentedit.html",controller:"ContenteditCtrl",reloadOnSearch:!1}).when("/cms/app/edit/:id/contributions/",{templateUrl:routes.PARTIALS_URL+"contributions.html",controller:"ContributionsCtrl"}).when("/cms/app/targeting/",{templateUrl:routes.PARTIALS_URL+"targeting-editor.html",controller:"TargetingCtrl"}).when("/cms/app/notifications/",{templateUrl:routes.PARTIALS_URL+"cms-notifications.html",controller:"CmsNotificationsCtrl"}).when("/cms/app/reporting/",{templateUrl:routes.PARTIALS_URL+"reporting.html",controller:"ReportingCtrl"}).when("/cms/app/pzones/",{templateUrl:routes.PARTIALS_URL+"pzones.html",controller:"PzoneCtrl"}).otherwise({redirectTo:"/cms/app/list/"}),$sceProvider.enabled(!1)}).config(function($provide,$httpProvider){$provide.decorator("$exceptionHandler",function($delegate){return function(exception,cause){$delegate(exception,cause),window.Raven.captureException(exception)}}),$httpProvider.interceptors.push("BugReportInterceptor"),$httpProvider.interceptors.push("PermissionsInterceptor"),$httpProvider.interceptors.push("BadRequestInterceptor"),$httpProvider.interceptors.push("TunicInterceptor")}).run(function($rootScope,$http,$cookies){$http.defaults.headers.common["X-CSRFToken"]=$cookies.csrftoken;var deleteHeaders=$http.defaults.headers["delete"]||{};deleteHeaders["X-CSRFToken"]=$cookies.csrftoken,$http.defaults.headers["delete"]=deleteHeaders}).constant("TIMEZONE_NAME","America/Chicago"),angular.module("bulbs.api",["restangular","moment"]),angular.module("bulbs.api").factory("AuthorService",function(Restangular){return Restangular.setBaseUrl("/cms/api/v1/"),Restangular.setRequestSuffix("/"),Restangular.extendModel("author",function(obj){return angular.extend(obj,{getFullName:function(){return obj.first_name+" "+obj.last_name}})}),Restangular.all("author")}),angular.module("bulbs.api").factory("ContentService",function(Restangular){return Restangular.setBaseUrl("/cms/api/v1/"),Restangular.setRequestSuffix("/"),Restangular.extendModel("content",function(obj){var extendAuthor=function(author){return angular.extend(author,{getFullName:function(){return obj.contributor.first_name+" "+obj.contributor.last_name}})};for(var i in obj.authors)obj.authors[i]=extendAuthor(obj.authors[i]);return obj}),Restangular.extendModel("contributions",function(obj){return obj&&obj.contributor&&(obj.contributor=angular.extend(obj.contributor,{getFullName:function(){return obj.contributor.first_name+" "+obj.contributor.last_name}})),obj}),Restangular.extendCollection("contributions",function(collection){return collection.save=function(data){return collection.post(data).then(function(contributions){return Restangular.restangularizeCollection("contributions",contributions)})},collection}),Restangular.service("content")}),angular.module("bulbs.api").factory("ContributionRoleService",function(Restangular){return Restangular.withConfig(function(RestangularConfigurer){RestangularConfigurer.setBaseUrl("/cms/api/v1/contributions/"),RestangularConfigurer.setRequestSuffix("/")}).service("role")}).factory("ContentReportingService",function(Restangular){return Restangular.withConfig(function(RestangularConfigurer){RestangularConfigurer.setBaseUrl("/cms/api/v1/contributions/"),RestangularConfigurer.setRequestSuffix("/")}).service("contentreporting")}).factory("FreelancePayReportingService",function(Restangular,moment){return Restangular.withConfig(function(RestangularConfigurer){RestangularConfigurer.setBaseUrl("/cms/api/v1/contributions/"),RestangularConfigurer.setRequestSuffix("/")}).service("freelancereporting")}).factory("ContributionReportingService",function(Restangular,moment){return Restangular.extendModel("reporting",function(obj){return obj.user=angular.extend(obj.user,{toString:function(){return obj.user.full_name||obj.user.username}}),obj.content=angular.extend(obj.content,{toString:function(){return obj.content.title+" ("+moment(obj.content.published).format("MM/DD/YYYY h:mm a")+")"}}),obj}),Restangular.withConfig(function(RestangularConfigurer){RestangularConfigurer.setBaseUrl("/cms/api/v1/contributions/"),RestangularConfigurer.setRequestSuffix("/")}).service("reporting")}),function(){function BettyCropperService($http,$interpolate,$q,IMAGE_SERVER_URL,BC_API_KEY,BettyImage,$){function upload(){var uploadImageDeferred=$q.defer();angular.element(fileInputId).remove();var fileInput=angular.element(inputTemplate);return angular.element("body").append(fileInput),fileInput.click(),fileInput.unbind("change"),fileInput.bind("change",function(e){1!==e.target.files.length&&uploadImageDeferred.reject("We need exactly one image!");var file=e.target.files[0];0!==file.type.indexOf("image/")&&uploadImageDeferred.reject("Not an image!"),file.size>10485760&&uploadImageDeferred.reject("The file is too large!");var imageData=new FormData;imageData.append("image",file),$http({method:"POST",url:IMAGE_SERVER_URL+"/api/new",headers:{"X-Betty-Api-Key":BC_API_KEY,"Content-Type":void 0,"X-CSRFToken":void 0},data:imageData,transformRequest:angular.identity,transformResponse:function(data,headersGetter){"string"==typeof data&&(data=$.parseJSON(data));var image=new BettyImage(data);return image}}).success(function(success){uploadImageDeferred.resolve(success)}).error(function(error){uploadImageDeferred.reject(error)})}),uploadImageDeferred.promise}function get(id){return $http({method:"GET",url:IMAGE_SERVER_URL+"/api/"+id,headers:{"X-Betty-Api-Key":BC_API_KEY,"Content-Type":void 0,"X-CSRFToken":void 0},transformRequest:angular.identity,transformResponse:function(data,headersGetter){return"string"==typeof data&&(data=$.parseJSON(data)),new BettyImage(data)}})}function detailPatch(id,name,credit,selections){return $http({method:"PATCH",url:IMAGE_SERVER_URL+"/api/"+id,headers:{"X-Betty-Api-Key":BC_API_KEY,"Content-Type":void 0,"X-CSRFToken":void 0},data:{name:name,credit:credit,selections:selections},transformRequest:angular.identity,transformResponse:function(data,headersGetter){return"string"==typeof data&&(data=$.parseJSON(data)),new BettyImage(data)}})}function updateSelection(id,ratio,selections){return $http({method:"POST",url:IMAGE_SERVER_URL+"/api/"+id+"/"+ratio,headers:{"X-Betty-Api-Key":BC_API_KEY,"Content-Type":void 0,"X-CSRFToken":void 0},data:selections})}var fileInputId="#bulbs-cms-hidden-image-file-input",inputTemplate='';this.upload=upload,this.get=get,this.detail=get,this.detailPatch=detailPatch,this.updateSelection=updateSelection}function BettyImageFactory($interpolate,$http,IMAGE_SERVER_URL,BC_API_KEY,DEFAULT_IMAGE_WIDTH,Selection,$){function BettyImage(data){this.id=data.id,this.name=data.name,this.width=data.width,this.height=data.height,this.selections={};for(var ratio in data.selections)this.selections[ratio]=new Selection(data.selections[ratio])}return BettyImage.prototype.scaleToFit=function(width,height){var scale;if(width&&height){var fitRatio=width/height,thisRatio=this.width/this.height;scale=fitRatio>thisRatio?height/this.height:width/this.width}else width&&(scale=width/this.width),height&&(scale=height/this.height);var scaled={width:Math.round(this.width*scale),height:Math.round(this.height*scale),scale:scale};return scaled},BettyImage.prototype.getStyles=function(width,height,ratio){0===height&&(height=null);var selection=this.selections[ratio],scaledSelection=selection.scaleToFit(width,height);return{"background-image":"url("+this.url("original",DEFAULT_IMAGE_WIDTH,"jpg")+")","background-size":Math.floor(scaledSelection.width()/selection.width()*this.width)+"px","background-position":"-"+scaledSelection.x0+"px -"+scaledSelection.y0+"px",height:scaledSelection.height()+"px",width:scaledSelection.width()+"px","background-repeat":"no-repeat",position:"relative"}},BettyImage.prototype.url=function(ratio,width,format){for(var exp=$interpolate("{{ base_url }}/{{ id }}/{{ ratio }}/{{ width }}.{{ format }}"),idStr=this.id.toString(),segmentedId="",i=0;ithisRatio?height/this.height():width/this.width()}else width&&(scale=width/this.width()),height&&(scale=height/this.height());return this.scaleBy(scale)},Selection}angular.module("BettyCropper",["restangular","jquery"]).value("DEFAULT_IMAGE_WIDTH",1200).factory("Selection",SelectionFactory).factory("BettyImage",BettyImageFactory).service("BettyCropper",BettyCropperService)}(),angular.module("autocompleteBasic",["BulbsAutocomplete","BulbsAutocomplete.suggest","bulbsCmsApp.settings"]).value("AUTOCOMPLETE_BASIC_DEBOUNCE",200).directive("autocompleteBasic",function(routes){return{controller:function(_,$scope,BULBS_AUTOCOMPLETE_EVENT_KEYPRESS,AUTOCOMPLETE_BASIC_DEBOUNCE){$scope.writables={searchTerm:""},$scope.currentSelection=null,$scope.autocompleteItems=[];var $getItems=function(){return $scope.searchFunction($scope.writables.searchTerm).then(function(data){return _.map(data,function(item){return{name:$scope.itemDisplayFormatter({item:item}),value:item}})})};$scope.updateAutocomplete=_.debounce(function(){$scope.writables.searchTerm&&$getItems().then(function(results){$scope.autocompleteItems=results})},AUTOCOMPLETE_BASIC_DEBOUNCE),$scope.delayClearAutocomplete=function(){_.delay(function(){$scope.clearAutocomplete(),$scope.$digest()},200)},$scope.clearAutocomplete=function(){$scope.writables.searchTerm="",$scope.autocompleteItems=[]},$scope.clearSelectionOverlay=function(){$scope.clearAutocomplete(),$scope.showSelectionOverlay=!1,$scope.updateNgModel(null),$scope.onSelect({selection:null})},$scope.handleKeypress=function($event){27===$event.keyCode?$scope.clearAutocomplete():40===$event.keyCode&&_.isEmpty($scope.autocompleteItems)?$scope.updateAutocomplete():$scope.$broadcast(BULBS_AUTOCOMPLETE_EVENT_KEYPRESS,$event)},$scope.handleSelect=function(selection){selection&&$scope.updateNgModel&&($scope.updateNgModel(selection),$scope.showSelectionOverlay=!0),$scope.clearAutocomplete(),$scope.onSelect({selection:selection})}},link:function(scope,iElement,iAttrs,ngModelCtrl){ngModelCtrl&&(ngModelCtrl.$formatters.push(function(modelValue){return scope.currentSelection=modelValue,modelValue}),ngModelCtrl.$parsers.push(function(viewValue){return scope.currentSelection=viewValue,viewValue}),scope.updateNgModel=function(selection){var newViewValue=null;selection&&(newViewValue=selection.value),ngModelCtrl.$setViewValue(newViewValue)})},require:"?ngModel",restrict:"E",scope:{hideSearchIcon:"&",inputId:"@",inputPlaceholder:"@",itemDisplayFormatter:"&",onSelect:"&",searchFunction:"="},templateUrl:routes.COMPONENTS_URL+"autocomplete-basic/autocomplete-basic.html"}}),angular.module("bettyEditable",["BettyCropper","bulbsCmsApp.settings"]).directive("bettyEditable",["$http","routes","BettyCropper","openImageCropModal","DEFAULT_IMAGE_WIDTH",function($http,routes,BettyCropper,openImageCropModal,DEFAULT_IMAGE_WIDTH){return{restrict:"E",templateUrl:routes.COMPONENTS_URL+"betty-editable/betty-editable.html",scope:{addStyles:"@",editable:"=?",hideMetas:"=",image:"=",placeholderText:"@",ratio:"@"},controller:function($scope,$element){$scope.editable=angular.isDefined($scope.editable)?$scope.editable:!0,$scope.upload=function(e){BettyCropper.upload().then(function(success){$scope.image={id:success.id,caption:null,alt:null},$scope.bettyImage=success},function(error){console.log(error)},function(progress){console.log(progress)})},$scope.edit=function(e){openImageCropModal($scope.image).then(function(image){null===image.id?$scope.image=null:($scope.image=image,BettyCropper.get($scope.image.id).then(function(response){$scope.bettyImage=response.data,$scope.setStyles()}))})}},link:function(scope,element,attrs){void 0===scope.bettyImage&&(scope.bettyImage=null),scope.setStyles=function(){if(scope.bettyImage)scope.imageStyling=scope.bettyImage.getStyles(element.parent().width(),null,scope.ratio);else{var ratioWidth=parseInt(scope.ratio.split("x")[0],10),ratioHeight=parseInt(scope.ratio.split("x")[1],10);scope.imageStyling={"background-color":"#333",position:"relative",width:element.parent().width(),height:Math.floor(element.parent().width()*ratioHeight/ratioWidth)+"px"}}},scope.$watch("image",function(newImage,oldImage){newImage&&newImage.id&&BettyCropper.get(newImage.id).then(function(response){scope.bettyImage=response.data})}),scope.$watch("bettyImage",function(newImage,oldImage){scope.setStyles()},!0),element.resize(scope.setStyles),scope.removeImage=function(){scope.image=null},scope.editImage=function(){openImageCropModal(scope.image).then(function(success){console.log(success)})}}}}]),angular.module("bugReporter",[]).directive("bugReporter",["$http","$window","routes",function($http,$window,routes){return{restrict:"E",templateUrl:routes.COMPONENTS_URL+"bug-reporter/bug-reporter-button.html",scope:{},controller:function($scope,$element,$timeout){$scope.report={},$scope.reportButton={idle:"Submit",busy:"Sending",finished:"Sent!",error:"Error!"},$scope.modalVisible=!1,$scope.showThankYou=!1,$scope.showModal=function(){$scope.modalVisible=!0},$scope.dismissModal=function(){$scope.modalVisible=!1,$scope.showThankYou=!1},$scope.sendToWebtech=function(){var report="When I tried to:\n\n"+$scope.report.firstRes+"\n\nI thought this would happen:\n\n"+$scope.report.secondRes+"\n\n...but this happened instead:\n\n"+$scope.report.thirdRes,data={report:report,url:$window.location.href,user_agent:$window.navigator.userAgent};return $http.post("/cms/api/v1/report-bug/",data)},$scope.sendToWebtechCbk=function(promise){promise.then(function(){$scope.showThankYou=!0,$timeout(function(){$scope.dismissModal();for(var entry in $scope.report)$scope.report[entry]=""},5e3)})},$window.showBugReportModal=function(){$scope.$apply($scope.showModal())}},link:function(scope,element){}}}]),angular.module("campaigns.edit.directive",["apiServices.campaign.factory","BettyCropper","bulbsCmsApp.settings","campaigns.edit.sponsorPixel","lodash","saveButton.directive","topBar"]).directive("campaignsEdit",function(routes){return{controller:function(_,$location,$q,$routeParams,$scope,Campaign){"new"===$routeParams.id?($scope.model=Campaign.$build(),$scope.isNew=!0):$scope.model=Campaign.$find($routeParams.id),window.onbeforeunload=function(e){return!_.isEmpty($scope.model.$dirty())||$scope.isNew||$scope.needsSave?"You have unsaved changes.":void 0},$scope.$on("$destroy",function(){delete window.onbeforeunload}),$scope.addPixel=function(){var pixel={url:"",campaign_type:""};$scope.model.pixels.push(pixel)},$scope.deletePixel=function(pixel){$scope.model.pixels=_.without($scope.model.pixels,pixel)},$scope.saveModel=function(){var promise;if($scope.model)promise=$scope.model.$save().$asPromise().then(function(data){$location.path("/cms/app/campaigns/edit/"+data.id+"/")});else{var deferred=$q.defer();deferred.reject(),promise=deferred.promise}return promise}},restrict:"E",scope:{getModelId:"&modelId"},templateUrl:routes.COMPONENTS_URL+"campaigns/campaigns-edit/campaigns-edit.html"}}),angular.module("campaigns.edit.sponsorPixel.directive",[]).constant("PIXEL_TYPES",[{name:"Listing",value:"Listing"},{name:"Detail",value:"Detail"}]).directive("campaignsEditSponsorPixel",function(routes){return{controller:function($scope,PIXEL_TYPES){$scope.PIXEL_TYPES=PIXEL_TYPES},restrict:"E",scope:{model:"="},templateUrl:routes.COMPONENTS_URL+"campaigns/campaigns-edit/campaigns-edit-sponsor-pixel/campaigns-edit-sponsor-pixel.html"}}),angular.module("campaigns.edit.sponsorPixel",["campaigns.edit.sponsorPixel.directive"]),angular.module("campaigns.edit",["campaigns.edit.directive"]).config(function($routeProvider,routes){$routeProvider.when("/cms/app/campaigns/edit/:id/",{controller:function($routeParams,$scope,$window){$window.document.title=routes.CMS_NAMESPACE+" | Edit Campaign",$scope.routeId=$routeParams.id},template:'',reloadOnSearch:!1})}),angular.module("campaigns.list.directive",["bulbsCmsApp.settings","confirmationModal","apiServices.campaign.factory","momentFormatterFilter","ui.bootstrap.pagination"]).directive("campaignsList",function(routes){return{controller:function($scope,$location,Campaign){$scope.$campaigns=Campaign.$collection(),$scope.$retrieveCampaigns=function(){$scope.$campaigns.$refresh()},$scope.$addCampaign=function(){$location.path("/cms/app/campaigns/edit/new/")},$scope.$removeCampaign=function(campaign){campaign.$destroy()},$scope.$retrieveCampaigns()},restrict:"E",scope:{},templateUrl:routes.COMPONENTS_URL+"campaigns/campaigns-list/campaigns-list.html"}}),angular.module("campaigns.list",["apiServices.campaign.factory","bulbsCmsApp.settings","listPage","moment"]).config(function($routeProvider,routes){$routeProvider.when("/cms/app/campaigns/",{controller:function($scope,$window,Campaign){$window.document.title=routes.CMS_NAMESPACE+" | Campaign",$scope.modelFactory=Campaign},templateUrl:routes.COMPONENTS_URL+"campaigns/campaigns-list/campaigns-list-page.html"})}),angular.module("campaigns",["campaigns.edit","campaigns.list"]),angular.module("confirmationModal",["bulbsCmsApp.settings","confirmationModal.factory"]).directive("confirmationModalOpener",function(ConfirmationModal){return{restrict:"A",scope:{modalBody:"@",modalCancelText:"@",modalOkText:"@",modalOnCancel:"&",modalOnOk:"&",modalTitle:"@"},link:function(scope,element){var modalInstance=null;element.addClass("confirmation-modal-opener"),element.on("click",function(){modalInstance=new ConfirmationModal(scope)})}}}),angular.module("confirmationModal.factory",["ui.bootstrap.modal"]).factory("ConfirmationModal",function($modal,routes){var ConfirmationModal=function(scope){return function(scope){$modal.open({controller:function($scope,$modalInstance){$scope.confirm=function(){$scope.$close(),$scope.modalOnOk()},$scope.cancel=function(){$scope.$dismiss(),$scope.modalOnCancel()}},scope:scope,templateUrl:routes.COMPONENTS_URL+"confirmation-modal/confirmation-modal.html"})}(scope)};return ConfirmationModal}),angular.module("customSearch.contentItem.directive",[]).directive("customSearchContentItem",function(routes){return{restrict:"E",scope:{model:"=",controllerService:"=",onUpdate:"&"},templateUrl:routes.COMPONENTS_URL+"custom-search/custom-search-content-item/custom-search-content-item.html"}}),angular.module("customSearch.contentItem",["customSearch.contentItem.directive"]),angular.module("customSearch.directive",["bulbsCmsApp.settings","customSearch.contentItem","customSearch.service","customSearch.simpleContentSearch","customSearch.group"]).directive("customSearch",function(routes){return{controller:function(_,$scope,CustomSearchService){$scope.customSearchService=new CustomSearchService,$scope.resetFilters=function(){$scope.customSearchService.setPage(1),$scope.customSearchService.setQuery(""),$scope.addedFilterOn=!1,$scope.removedFilterOn=!1},$scope.$conditionalContentRetrieve=function(){$scope.addedFilterOn?$scope.customSearchService.$filterContentByIncluded():$scope.removedFilterOn?$scope.customSearchService.$filterContentByExcluded():$scope.customSearchService.$retrieveContent()},$scope.$contentRetrieve=function(){$scope.customSearchService.$retrieveContent(),$scope.onUpdate()}},link:function(scope,iElement,iAttrs,ngModelCtrl){ngModelCtrl.$formatters.push(function(modelValue){scope.customSearchService.data(modelValue),scope.customSearchService.$retrieveContent()})},require:"ngModel",restrict:"E",scope:{onUpdate:"&"},templateUrl:routes.COMPONENTS_URL+"custom-search/custom-search.html"}}),angular.module("customSearch.group.condition.directive",["contentServices.factory","customSearch.settings","BulbsAutocomplete","BulbsAutocomplete.suggest"]).directive("customSearchGroupCondition",function(routes){return{controller:function(_,$q,$scope,BULBS_AUTOCOMPLETE_EVENT_KEYPRESS,ContentFactory,CUSTOM_SEARCH_CONDITION_FIELDS,CUSTOM_SEARCH_CONDITION_TYPES){$scope.conditionTypes=CUSTOM_SEARCH_CONDITION_TYPES,$scope.fieldTypes=CUSTOM_SEARCH_CONDITION_FIELDS,$scope.writables={searchTerm:""},$scope.autocompleteItems=[],$scope.data=$scope.controllerService.groupsConditionsGet($scope.groupIndex,$scope.conditionIndex);var $getItems=function(){return ContentFactory.all($scope.data.field).getList({search:$scope.writables.searchTerm}).then(function(items){var field=_.find($scope.fieldTypes,function(type){return type.endpoint===$scope.data.field});return _.map(items,function(item){return{name:item[field.value_structure.name],value:item[field.value_structure.value]}})})};$scope.updateAutocomplete=function(){$scope.writables.searchTerm&&$getItems().then(function(results){$scope.autocompleteItems=results})},$scope.delayClearAutocomplete=function(){_.delay(function(){$scope.clearAutocomplete(),$scope.$digest()},200)},$scope.clearAutocomplete=function(){$scope.writables.searchTerm="",$scope.autocompleteItems=[]},$scope.handleKeypress=function($event){27===$event.keyCode?$scope.clearAutocomplete():$scope.$broadcast(BULBS_AUTOCOMPLETE_EVENT_KEYPRESS,$event)}},restrict:"E",scope:{controllerService:"=",groupIndex:"=",conditionIndex:"=",onUpdate:"&",remove:"&"},templateUrl:routes.COMPONENTS_URL+"custom-search/custom-search-group/custom-search-group-condition/custom-search-group-condition.html"}}),angular.module("customSearch.group.condition",["customSearch.group.condition.directive"]),angular.module("customSearch.group.directive",["customSearch.settings","uuid4"]).directive("customSearchGroup",function(routes){return{controller:function($scope,CUSTOM_SEARCH_TIME_PERIODS,uuid4){$scope.data=$scope.controllerService.groupsGet($scope.groupIndex),$scope.timePeriods=CUSTOM_SEARCH_TIME_PERIODS,$scope.uuid=uuid4.generate(),$scope.$update=function(){$scope.controllerService.$groupsUpdateResultCountFor($scope.groupIndex).then(function(){$scope.onUpdate()})},$scope.controllerService.$groupsUpdateResultCountFor($scope.groupIndex)},restrict:"E",scope:{controllerService:"=",groupIndex:"=",remove:"&",onUpdate:"&"},templateUrl:routes.COMPONENTS_URL+"custom-search/custom-search-group/custom-search-group.html"}}),angular.module("customSearch.group",["customSearch.group.directive","customSearch.group.condition"]),angular.module("customSearch.service",["customSearch.settings","apiServices.customSearch.factory"]).factory("CustomSearchService",function(_,CustomSearch,CUSTOM_SEARCH_CONDITION_FIELDS,CUSTOM_SEARCH_CONDITION_TYPES,CUSTOM_SEARCH_REQUEST_CAP_MS,CUSTOM_SEARCH_TIME_PERIODS){var defaultData={groups:[],includedIds:[],excludedIds:[],pinnedIds:[]},CustomSearchService=function(data){this.data(data),this.$page=1,this.$query="",this.content={}};return CustomSearchService.prototype.data=function(data){return _.isUndefined(data)?this._data=defaultData:this._data=_.defaults(data,defaultData),this._data},CustomSearchService.prototype._$getContent=_.debounce(function(queryData){var self=this;return CustomSearch.$retrieveContent(queryData).then(function(data){self.content=data})},CUSTOM_SEARCH_REQUEST_CAP_MS),CustomSearchService.prototype.$filterContentByIncluded=function(){var contentQuery={includedIds:this._data.includedIds,page:this.$page,query:this.$query};return this._$getContent(contentQuery)},CustomSearchService.prototype.$filterContentByExcluded=function(){var contentQuery={includedIds:this._data.excludedIds,page:this.$page,query:this.$query};return this._$getContent(contentQuery)},CustomSearchService.prototype.$retrieveContent=function(){var contentQuery=_.assign({page:this.$page,query:this.$query,preview:!0},this._data);return this._$getContent(contentQuery)},CustomSearchService.prototype.$groupsUpdateResultCountFor=function(index){var self=this;return function(index){return CustomSearch.$retrieveGroupCount(self._data.groups[index]).then(function(count){self._data.groups[index].$result_count=count})}(index)},CustomSearchService.prototype.groupsResultCountGet=function(index){return this._data.groups[index].$result_count||0},CustomSearchService.prototype.groupsList=function(){return this._data.groups},CustomSearchService.prototype.groupsAdd=function(data){return _.isUndefined(data)&&(data={}),data=_.defaults(data,{conditions:[],time:null,$result_count:0}),this._data.groups.push(data),data},CustomSearchService.prototype.groupsGet=function(index){return this._data.groups[index]},CustomSearchService.prototype.groupsRemove=function(index){return this._data.groups.splice(index,1).length>0},CustomSearchService.prototype.groupsClear=function(){this._data.groups=[]},CustomSearchService.prototype.groupsConditionsAdd=function(groupIndex,data){return _.isUndefined(data)&&(data={}),data=_.defaults(data,{field:CUSTOM_SEARCH_CONDITION_FIELDS[0].endpoint,type:CUSTOM_SEARCH_CONDITION_TYPES[0].value,values:[]}),this._data.groups[groupIndex].conditions.push(data),data},CustomSearchService.prototype.groupsConditionsGet=function(groupIndex,conditionIndex){return this._data.groups[groupIndex].conditions[conditionIndex]},CustomSearchService.prototype.groupsConditionsList=function(groupIndex){return this._data.groups[groupIndex].conditions},CustomSearchService.prototype.groupsConditionsRemove=function(groupIndex,conditionIndex){return this._data.groups[groupIndex].conditions.splice(conditionIndex,1).length>0},CustomSearchService.prototype.groupsTimePeriodSet=function(groupIndex){var value=CUSTOM_SEARCH_TIME_PERIODS[0].value;return this._data.groups[groupIndex].time=value,value},CustomSearchService.prototype.groupsTimePeriodGet=function(groupIndex){return this._data.groups[groupIndex].time||null},CustomSearchService.prototype.groupsTimePeriodRemove=function(groupIndex){this._data.groups[groupIndex].time=null},CustomSearchService.prototype.groupsConditionsValuesAdd=function(groupIndex,conditionIndex,value){var values=this._data.groups[groupIndex].conditions[conditionIndex].values,matches=_.find(values,function(existingValue){return existingValue.name===value.name&&existingValue.value===value.value});matches||values.push(value)},CustomSearchService.prototype.groupsConditionsValuesClear=function(groupIndex,conditionIndex){this._data.groups[groupIndex].conditions[conditionIndex].values=[]; },CustomSearchService.prototype.groupsConditionsValuesList=function(groupIndex,conditionIndex){return this._data.groups[groupIndex].conditions[conditionIndex].values},CustomSearchService.prototype.groupsConditionsValuesRemove=function(groupIndex,conditionIndex,valueIndex){return this._data.groups[groupIndex].conditions[conditionIndex].values.splice(valueIndex,1).length>0},CustomSearchService.prototype.includesList=function(){return this._data.includedIds},CustomSearchService.prototype.includesAdd=function(id){this._data.includedIds.push(id),this._data.includedIds=_.uniq(this._data.includedIds),this.excludesRemove(id)},CustomSearchService.prototype.includesRemove=function(id){this._data.includedIds=_.without(this._data.includedIds,id)},CustomSearchService.prototype.includesHas=function(id){return _.includes(this._data.includedIds,id)},CustomSearchService.prototype.excludesList=function(){return this._data.excludedIds},CustomSearchService.prototype.excludesAdd=function(id){this._data.excludedIds.push(id),this._data.excludedIds=_.uniq(this._data.excludedIds),this.includesRemove(id),this.pinsRemove(id)},CustomSearchService.prototype.excludesRemove=function(id){this._data.excludedIds=_.without(this._data.excludedIds,id)},CustomSearchService.prototype.excludesHas=function(id){return _.includes(this._data.excludedIds,id)},CustomSearchService.prototype.pinsList=function(){return this._data.pinnedIds},CustomSearchService.prototype.pinsAdd=function(id){this._data.pinnedIds.push(id),this._data.pinnedIds=_.uniq(this._data.pinnedIds),this.excludesRemove(id)},CustomSearchService.prototype.pinsRemove=function(id){this._data.pinnedIds=_.without(this._data.pinnedIds,id)},CustomSearchService.prototype.pinsHas=function(id){return _.includes(this._data.pinnedIds,id)},CustomSearchService.prototype.getPage=function(){return this.$page},CustomSearchService.prototype.setPage=function(page){this.$page=page},CustomSearchService.prototype.getQuery=function(){return this.$query},CustomSearchService.prototype.setQuery=function(query){this.$query=query},CustomSearchService}),angular.module("customSearch.settings",[]).value("CUSTOM_SEARCH_CONDITION_FIELDS",[{name:"Content Type",endpoint:"content-type",value_structure:{name:"name",value:"doctype"}},{name:"Feature Type",endpoint:"feature-type",value_structure:{name:"name",value:"slug"}},{name:"Tag",endpoint:"tag",value_structure:{name:"name",value:"slug"}}]).value("CUSTOM_SEARCH_CONDITION_TYPES",[{name:"is any of",value:"any"},{name:"is all of",value:"all"},{name:"is none of",value:"none"}]).value("CUSTOM_SEARCH_TIME_PERIODS",[{name:"Past Day",value:"1 day"},{name:"Past Week",value:"1 week"}]).value("CUSTOM_SEARCH_REQUEST_CAP_MS",150),angular.module("customSearch.simpleContentSearch.directive",["BulbsAutocomplete","BulbsAutocomplete.suggest"]).directive("customSearchSimpleContentSearch",function(routes){return{controller:function(_,$scope,BULBS_AUTOCOMPLETE_EVENT_KEYPRESS,ContentFactory){$scope.writables={searchTerm:""},$scope.autocompleteItems=[];var $getItems=function(){return ContentFactory.all("content").getList({search:$scope.writables.searchTerm}).then(function(results){return _.chain(results).take(10).map(function(item){return{name:"ID: "+item.id+" | "+item.title,value:item.id}}).value()})};$scope.updateAutocomplete=function(){$scope.writables.searchTerm&&$getItems().then(function(results){$scope.autocompleteItems=results})},$scope.delayClearAutocomplete=function(){_.delay(function(){$scope.clearAutocomplete(),$scope.$digest()},200)},$scope.clearAutocomplete=function(){$scope.writables.searchTerm="",$scope.autocompleteItems=[]},$scope.handleKeypress=function($event){27===$event.keyCode?$scope.clearAutocomplete():$scope.$broadcast(BULBS_AUTOCOMPLETE_EVENT_KEYPRESS,$event)}},restrict:"E",scope:{onSelect:"&"},templateUrl:routes.COMPONENTS_URL+"custom-search/custom-search-simple-content-search/custom-search-simple-content-search.html"}}),angular.module("customSearch.simpleContentSearch",["customSearch.simpleContentSearch.directive"]),angular.module("customSearch",["bulbsCmsApp.settings","customSearch.directive"]),angular.module("EditorsPick",["customSearch"]).config(function($routeProvider,routes){$routeProvider.when("/cms/app/sod/",{controller:function($scope,$window){$window.document.title=routes.CMS_NAMESPACE+" | SoD",$scope.$watch("queryData",function(){console.log(arguments)}),$scope.queryData={},$scope.updateQueryData=function(){$scope.queryData={groups:[{conditions:[{field:"content-type",type:"all",values:[{name:"for display",value:"actually-use-this-value-123"}]}],time:"1 day"}],included_ids:[1],excluded_ids:[2],pinned_ids:[3],page:1,query:"query balh blah blahb"}},$scope.updateConditionData=function(){$scope.queryData.groups[0].conditions=[{field:"content-type",type:"all",values:[{name:"ANOTHER THIGN",value:"actually-use-this-value-123"}]}]}},templateUrl:routes.COMPONENTS_URL+"editors-pick/editors-pick.html",reloadOnSearch:!1})}),angular.module("filterListWidget.directive",["bulbsCmsApp.settings"]).directive("filterListWidget",function(_,$http,$location,$timeout,$,routes){return{restrict:"E",scope:{filters:"="},templateUrl:routes.COMPONENTS_URL+"filter-list-widget/filter-list-widget.html",link:function(scope,element,attrs){function getAutocompletes(search){return $timeout.cancel(filterInputTimeout),filterInputCounter=0,search.length<1?(scope.autocompleteArray=[],void scope.$apply()):void $http({url:"/cms/api/v1/things/?type=tag&type=feature_type&type=author",method:"GET",params:{q:search}}).success(function(data){scope.autocompleteArray=data})}function arrowSelect(direction){var $toSelect,$entries=$element.find(".entry"),$selected=$element.find(".entry.selected");$selected.length>0?("up"===direction&&($toSelect=$selected.first().prev()),"down"===direction&&($toSelect=$selected.first().next())):("up"===direction&&($toSelect=$entries.last()),"down"===direction&&($toSelect=$entries.first())),scope.selectEntry($toSelect)}function applyFilterChange(filterObject){filterObject.page=1,$location.search(filterObject),scope.autocompleteArray=[],$input.trigger("blur")}function getFilterObjects(){var search=$location.search();if(scope.filters={},"undefined"==typeof search)return void console.log("undefined");var filterParamsToTypes={authors:"author",tags:"tag",feature_types:"feature_type"};for(var filterParam in filterParamsToTypes){var filterType=filterParamsToTypes[filterParam];"string"==typeof search[filterParam]&&(search[filterParam]=[search[filterParam]]);for(var i in search[filterParam]){var value=search[filterParam][i];scope.filters[filterType+value]={query:value,type:filterParam},getQueryToLabelMappings(filterType,value)}}search.search&&(scope.filterInputValue=search.search)}function getQueryToLabelMappings(type,query){scope.queryToLabelMappings=scope.queryToLabelMappings||{},query in scope.queryToLabelMappings||$http({url:"/cms/api/v1/things/?type="+type,method:"GET",params:{q:query}}).success(function(data){for(var i in data)scope.queryToLabelMappings[data[i].value]=data[i].name})}var $element=$(element),$input=$element.find("input");scope.autocompleteArray=[];var filterInputTimeout,filterInputCounter=0;$input.on("input",function(e){var search=$input.val();scope.searchTerm=search,$timeout.cancel(filterInputTimeout),filterInputTimeout=$timeout(function(){getAutocompletes(search)},200),filterInputCounter>2&&getAutocompletes(search)}),$input.on("keyup",function(e){38===e.keyCode&&arrowSelect("up"),40===e.keyCode&&arrowSelect("down"),13===e.keyCode&&($element.find(".selected").length>0?$timeout(function(){angular.element(".selected > a").triggerHandler("click")},0):scope.addFilter("search",$input.val()))}),scope.search=function(){scope.addFilter("search",scope.filterInputValue)},scope.clearSearch=function(){scope.filterInputValue=""},scope.clearFilters=function(){return scope.filters={},scope.filterInputValue="",applyFilterChange({})},$element.on("mouseover",".entry",function(){scope.selectEntry(this)}),scope.selectEntry=function(entry){$element.find(".selected").removeClass("selected"),$(entry).addClass("selected")},$input.on("blur",function(){$element.find(".dropdown-menu").fadeOut(200)}),$input.on("focus",function(){$element.find(".dropdown-menu").fadeIn(200)}),scope.addFilter=function(type,newFilterValue){var filterObject=$location.search();return"search"===type?filterObject.search=newFilterValue:(filterObject[type]||(filterObject[type]=[]),"string"==typeof filterObject[type]&&(filterObject[type]=[filterObject[type]]),_.contains(filterObject[type],newFilterValue)||filterObject[type].push(newFilterValue)),applyFilterChange(filterObject)},scope.deleteFilter=function(key){var filterObject=$location.search(),toDelete=scope.filters[key];"string"==typeof filterObject[toDelete.type]&&(filterObject[toDelete.type]=[filterObject[toDelete.type]]);var toSplice;for(var i in filterObject[toDelete.type])if(filterObject[toDelete.type][i]===toDelete.query){toSplice=i;break}return filterObject[toDelete.type].splice(i,1),filterObject.search=$input.val(),delete scope.filters[key],applyFilterChange(filterObject)},scope.$on("$routeUpdate",function(){getFilterObjects()}),getFilterObjects()}}}),angular.module("filterListWidget",["filterListWidget.directive"]),angular.module("filterWidget.directive",["bulbsCmsApp.settings","contentServices.listService"]).directive("filterWidget",function(_,$http,$location,$timeout,$,ContentListService,routes){return{restrict:"E",scope:{},templateUrl:routes.COMPONENTS_URL+"filter-widget/filter-widget.html",link:function(scope,element,attrs){function getAutocompletes(search){return $timeout.cancel(filterInputTimeout),filterInputCounter=0,search.length<1?(scope.autocompleteArray=[],void scope.$apply()):void $http({url:"/cms/api/v1/things/?type=tag&type=feature_type&type=author",method:"GET",params:{q:search}}).success(function(data){scope.autocompleteArray=data})}function arrowSelect(direction){var $toSelect,$entries=$element.find(".entry"),$selected=$element.find(".entry.selected");$selected.length>0?("up"===direction&&($toSelect=$selected.first().prev()),"down"===direction&&($toSelect=$selected.first().next())):("up"===direction&&($toSelect=$entries.last()),"down"===direction&&($toSelect=$entries.first())),scope.selectEntry($toSelect)}function applyFilterChange(filterObject){return filterObject.page=1,$location.search(filterObject),scope.autocompleteArray=[],$input.trigger("blur"),ContentListService.$updateContent(filterObject)}function getFilterObjects(){var search=$location.search();if(scope.filterObjects={},"undefined"==typeof search)return void console.log("undefined");var filterParamsToTypes={authors:"author",tags:"tag",feature_types:"feature_type"};for(var filterParam in filterParamsToTypes){var filterType=filterParamsToTypes[filterParam];"string"==typeof search[filterParam]&&(search[filterParam]=[search[filterParam]]);for(var i in search[filterParam]){var value=search[filterParam][i];scope.filterObjects[filterType+value]={query:value,type:filterParam},getQueryToLabelMappings(filterType,value)}}search.search&&(scope.filterInputValue=search.search)}function getQueryToLabelMappings(type,query){scope.queryToLabelMappings=scope.queryToLabelMappings||{},query in scope.queryToLabelMappings||$http({url:"/cms/api/v1/things/?type="+type,method:"GET",params:{q:query}}).success(function(data){for(var i in data)scope.queryToLabelMappings[data[i].value]=data[i].name})}var $element=$(element),$input=$element.find("input");scope.autocompleteArray=[];var filterInputTimeout,filterInputCounter=0;$input.on("input",function(e){var search=$input.val();scope.searchTerm=search,$timeout.cancel(filterInputTimeout),filterInputTimeout=$timeout(function(){getAutocompletes(search)},200),filterInputCounter>2&&getAutocompletes(search)}),$input.on("keyup",function(e){38===e.keyCode&&arrowSelect("up"),40===e.keyCode&&arrowSelect("down"),13===e.keyCode&&($element.find(".selected").length>0?$timeout(function(){angular.element(".selected > a").triggerHandler("click")},0):scope.addFilter("search",$input.val()))}),scope.search=function(){scope.addFilter("search",scope.filterInputValue)},scope.clearSearch=function(){scope.filterInputValue=""},scope.clearFilters=function(){return scope.filterObjects={},scope.filterInputValue="",applyFilterChange({})},$element.on("mouseover",".entry",function(){scope.selectEntry(this)}),scope.selectEntry=function(entry){$element.find(".selected").removeClass("selected"),$(entry).addClass("selected")},$input.on("blur",function(){$element.find(".dropdown-menu").fadeOut(200)}),$input.on("focus",function(){$element.find(".dropdown-menu").fadeIn(200)}),scope.addFilter=function(type,newFilterValue){var filterObject=$location.search();return"search"===type?filterObject.search=newFilterValue:(filterObject[type]||(filterObject[type]=[]),"string"==typeof filterObject[type]&&(filterObject[type]=[filterObject[type]]),_.contains(filterObject[type],newFilterValue)||filterObject[type].push(newFilterValue)),applyFilterChange(filterObject)},scope.deleteFilter=function(key){var filterObject=$location.search(),toDelete=scope.filterObjects[key];"string"==typeof filterObject[toDelete.type]&&(filterObject[toDelete.type]=[filterObject[toDelete.type]]);var toSplice;for(var i in filterObject[toDelete.type])if(filterObject[toDelete.type][i]===toDelete.query){toSplice=i;break}return filterObject[toDelete.type].splice(i,1),filterObject.search=$input.val(),delete scope.filterObjects[key],applyFilterChange(filterObject)},scope.$on("$routeUpdate",function(){getFilterObjects()}),getFilterObjects()}}}),angular.module("filterWidget",["filterWidget.directive"]),angular.module("genericAjaxButton.controller",[]).controller("GenericAjaxButtonController",function($scope){$scope.STATES={DONE:"done",PROGRESS:"in-progress",ERROR:"error"},$scope.doClick=function(){$scope.state=$scope.STATES.PROGRESS,$scope.clickFunction().then(function(){$scope.state=$scope.STATES.DONE})["catch"](function(){$scope.state=$scope.STATES.ERROR})}}),angular.module("genericAjaxButton.directive",["bulbsCmsApp.settings","genericAjaxButton.controller"]).directive("genericAjaxButton",function(routes){return{controller:"GenericAjaxButtonController",restrict:"E",scope:{disableWhen:"&",clickFunction:"=",cssBtnClassComplete:"@",cssBtnClassError:"@",cssBtnClassProgress:"@",cssIconComplete:"@",textError:"@",textProgress:"@",textComplete:"@"},templateUrl:routes.COMPONENTS_URL+"generic-ajax-button/generic-ajax-button.html"}}),angular.module("genericAjaxButton",["genericAjaxButton.directive"]),angular.module("saveButton.directive",["genericAjaxButton"]).directive("saveButton",function(routes){return{controller:"GenericAjaxButtonController",link:{pre:function(scope){scope.cssIconComplete="glyphicon-floppy-disk",scope.textProgress="Saving...",scope.textComplete="Save"}},restrict:"E",scope:{disableWhen:"&",clickFunction:"="},templateUrl:routes.COMPONENTS_URL+"generic-ajax-button/generic-ajax-button.html"}}),angular.module("polls.edit.directive",["apiServices.poll.factory","apiServices.answer.factory","BettyCropper","lodash","saveButton.directive","topBar"]).constant("RESPONSE_TYPES",[{name:"Text Only",value:"Text"},{name:"Image + Text",value:"Image"}]).directive("pollsEdit",function(routes){return{templateUrl:routes.COMPONENTS_URL+"polls/polls-edit/polls-edit.html",controller:function(_,$http,$location,$q,$routeParams,$scope,Answer,Poll){"new"===$routeParams.id?($scope.model={},$scope.isNew=!0):Poll.getPoll($routeParams.id).then(function(response){$scope.model=response,$scope.answers=response.answers}),window.onbeforeunload=function(e){return!_.isEmpty($scope.model.$dirty())||$scope.isNew||$scope.needsSave?"You have unsaved changes.":void 0},$scope.$on("$destroy",function(){delete window.onbeforeunload}),$scope.saveModel=function(){return $scope.model?$scope.isNew?Poll.postPoll($scope.model).then(function(data){var answerPromise=_.map($scope.answers,function(answer){return Answer.postAnswer(answer,data.id)});return $q.all(answerPromise).then(function(){$location.path("/cms/app/polls/edit/"+data.id+"/")})}):(Answer.updatePollAnswers($scope),$scope.deletedAnswers=[],Poll.updatePoll($scope.model)):$q.reject("Save failed")},$scope.deletedAnswers=[];var newId=$scope.answers?$scope.answers.length:0;$scope.addAnswer=function(){$scope.answers.push({id:newId++,notOnSodahead:!0})},$scope.isNew&&($scope.answers=[],_.times(3,$scope.addAnswer)),$scope.removeAnswer=function(answerId){var deletedAnswer=_.remove($scope.answers,function(a){return a.id===answerId});deletedAnswer[0].notOnSodahead||$scope.deletedAnswers.push(deletedAnswer[0])}},restrict:"E",scope:{getModelId:"&modelId"}}}),angular.module("polls.edit",["polls.edit.directive"]).config(function($routeProvider,routes){$routeProvider.when("/cms/app/polls/edit/:id/",{controller:function($routeParams,$scope,$window){$window.document.title=routes.CMS_NAMESPACE+" | Edit Poll",$scope.routeId=$routeParams.id},template:'',reloadOnSearch:!1})}),angular.module("polls.list",["apiServices.poll.factory","bulbsCmsApp.settings","listPage","moment"]).config(function($routeProvider,routes){$routeProvider.when("/cms/app/polls/",{controller:function($scope,$window,Poll){$window.document.title=routes.CMS_NAMESPACE+" | Poll",$scope.modelFactory=Poll},templateUrl:routes.COMPONENTS_URL+"polls/polls-list/polls-list-page.html"})}),angular.module("polls",["polls.list","polls.edit"]),angular.module("promotedContentArticle.directive",["bulbsCmsApp.settings"]).directive("promotedContentArticle",function(routes){return{restrict:"E",scope:{article:"="},templateUrl:routes.COMPONENTS_URL+"promoted-content/promoted-content-article/promoted-content-article.html"}}),angular.module("promotedContentArticle",["promotedContentArticle.directive"]),angular.module("promotedContentList.directive",["bulbsCmsApp.settings","promotedContent.service","promotedContentArticle","promotedContentSave","ui.sortable"]).directive("promotedContentList",function($,routes){return{controller:function($scope,PromotedContentService){$scope.pzoneData=PromotedContentService.getData(),$scope.moveUp=function(index){PromotedContentService.moveContentUp(index)},$scope.moveDown=function(index){PromotedContentService.moveContentDn(index)},$scope.remove=function(article){PromotedContentService.$removeContentFromPZone(article.id)},$scope.completeAction=function(index){PromotedContentService.$completeContentAction(index)},$scope.stopAction=function(){PromotedContentService.stopContentAction()},$scope.markDirty=function(){PromotedContentService.markDirtySelectedPZone()},$scope.disableControls=function(){return PromotedContentService.isPZoneRefreshPending()}},link:function(scope,element,attr){scope.sortableOptions={beforeStop:function(e,ui){ui.helper.css("margin-top",0),ui.item.parent().removeClass("ui-sortable-dragging")},cancel:".ui-sortable-unsortable",change:function(e,ui){ui.helper.css("margin-top",$(window).scrollTop())},containment:"promoted-content-list",distance:3,opacity:.75,placeholder:"dropzone",start:function(e,ui){ui.item.parent().addClass("ui-sortable-dragging"),ui.helper.css("margin-top",$(window).scrollTop())},stop:function(){scope.markDirty()}}},restrict:"E",scope:{},templateUrl:routes.COMPONENTS_URL+"promoted-content/promoted-content-list/promoted-content-list.html"}}),angular.module("promotedContentList",["promotedContentList.directive"]),angular.module("promotedContentOperationsList.directive",["bulbsCmsApp.settings","promotedContent.service"]).directive("promotedContentOperationsList",function(_,moment,routes){return{controller:function(moment,$scope,PromotedContentService){$scope.pzoneData=PromotedContentService.getData(),$scope.scheduleDateFrom=moment(),$scope.scheduleDateTo=moment().add(3,"days"),$scope.deleteStatus={message:"",isError:!1},PromotedContentService.$ready().then(function(){$scope.aggregatedOperations=$scope.pzoneData.operations.concat($scope.pzoneData.unsavedOperations)}),$scope.removeOperation=function(operation){PromotedContentService.$removeOperation(operation.id).then(function(){$scope.deleteStatus={message:"Operation successfully removed!",isError:!1}})["catch"](function(err){$scope.deleteStatus={message:err,isError:!0}})},$scope.clearDeleteStatus=function(){$scope.deleteStatus.message=""},$scope.setPreviewTime=function(time){PromotedContentService.setPreviewTime(time.add(1,"minute"))},$scope.disableControls=function(){return PromotedContentService.isPZoneRefreshPending()},$scope.operationsStale=function(){return PromotedContentService.isPZoneOperationsStale()},$scope.refreshingOperations=!1,$scope.refreshOperations=function(){$scope.refreshingOperations||($scope.refreshingOperations=!0,PromotedContentService.$refreshOperations({from:$scope.scheduleDateFrom.toISOString(),to:$scope.scheduleDateTo.toISOString()})["finally"](function(){$scope.refreshingOperations=!1}))}},link:function(scope,element,attr){var operationTime=function(operation){var compTime;return compTime=operation.whenAsMoment?operation.whenAsMoment:scope.pzoneData.previewTime?scope.pzoneData.previewTime:moment()};scope.aggregatedOperations={},scope.groupDateFormat="M/D/YY @ h:mma";var aggregator=function(){var tempAggregate=scope.pzoneData.operations.concat(scope.pzoneData.unsavedOperations);scope.aggregatedOperations=_.chain(tempAggregate).sortBy(operationTime).groupBy(function(operation){return operationTime(operation).format(scope.groupDateFormat)}).pairs().map(function(pair){return[moment(pair[0],scope.groupDateFormat),pair[1]]}).sortBy(function(pair){return pair[0]}).value()};scope.$watchCollection("pzoneData.operations",aggregator),scope.$watchCollection("pzoneData.unsavedOperations",aggregator)},restrict:"E",scope:{},templateUrl:routes.COMPONENTS_URL+"promoted-content/promoted-content-operations-list/promoted-content-operations-list.html"}}),angular.module("promotedContentOperationsList",["promotedContentOperationsList.directive"]),angular.module("promotedContentPzoneSelect.directive",["bulbsCmsApp.settings","promotedContent.service"]).directive("promotedContentPzoneSelect",function(routes){return{controller:function($scope,PromotedContentService){$scope.pzoneData=PromotedContentService.getData(),$scope.selectedPZoneName="",PromotedContentService.$ready().then(function(){$scope.selectedPZoneName=$scope.pzoneData.selectedPZone.name}),$scope.changePZone=function(name){!function(name){PromotedContentService.$refreshPZones().then(function(){PromotedContentService.$selectPZone(name)})}(name)},$scope.disableControls=function(){return PromotedContentService.isPZoneRefreshPending()}},restrict:"E",scope:{},templateUrl:routes.COMPONENTS_URL+"promoted-content/promoted-content-pzone-select/promoted-content-pzone-select.html"}}),angular.module("promotedContentPzoneSelect",["promotedContentPzoneSelect.directive"]),angular.module("promotedContentSave.directive",["bulbsCmsApp.settings","promotedContent.service"]).directive("promotedContentSave",function(routes){return{controller:function($scope,PromotedContentService){$scope.pzoneData=PromotedContentService.getData(),$scope.savePZone=function(){PromotedContentService.$saveSelectedPZone()},$scope.clearOperations=function(){PromotedContentService.clearUnsavedOperations(),PromotedContentService.$refreshSelectedPZone($scope.pzoneData.previewTime)},$scope.disableControls=function(){return PromotedContentService.isPZoneRefreshPending()}},restrict:"E",scope:{},templateUrl:routes.COMPONENTS_URL+"promoted-content/promoted-content-save/promoted-content-save.html"}}),angular.module("promotedContentSave",["promotedContentSave.directive"]),angular.module("promotedContentSearch.directive",["bulbsCmsApp.settings","statusFilter","filterWidget","promotedContent.service","promotedContentArticle"]).directive("promotedContentSearch",function(routes){return{controller:function(_,moment,$scope,$location,PromotedContentService){$scope.pzoneData=PromotedContentService.getData(),$scope.pageNumber=$location.search().page||"1",$scope.goToPage=function(){PromotedContentService.$refreshAllContent({page:$scope.pageNumber},!0)},$scope.contentIsEnabled=function(content){var notAlreadyInList=$scope.pzoneData.selectedPZone&&_.isUndefined(_.find($scope.pzoneData.selectedPZone.content,{id:content.id})),immediateDraggable=null===$scope.pzoneData.previewTime&&moment().isAfter(content.published),futureDraggable=null!==$scope.pzoneData.previewTime&&moment().isBefore($scope.pzoneData.previewTime)&&$scope.pzoneData.previewTime.isAfter(content.published);return notAlreadyInList&&(immediateDraggable||futureDraggable)},$scope.beginInsert=function(article){PromotedContentService.beginContentInsert(article)},$scope.beginReplace=function(article){PromotedContentService.beginContentReplace(article)},$scope.stopAction=function(){PromotedContentService.stopContentAction()},$scope.disableControls=function(){return PromotedContentService.isPZoneRefreshPending()}},link:function(scope,element,attr){scope.tools=null,scope.openToolsFor=function(article){var doOpen=!1;return scope.disableControls()||(scope.tools=article.id,doOpen=!0),doOpen},scope.closeTools=function(){return scope.tools=null,!0},scope.toolsOpenFor=function(article){return scope.tools===article.id}},restrict:"E",scope:{},templateUrl:routes.COMPONENTS_URL+"promoted-content/promoted-content-search/promoted-content-search.html"}}),angular.module("promotedContentSearch",["promotedContentSearch.directive"]),angular.module("promotedContent.service",["contentServices","moment","restangular"]).service("PromotedContentService",function($,_,moment,$q,Restangular,ContentFactory,ContentListService){var PromotedContentService=this;PromotedContentService._serviceData={allContent:ContentListService.getData(),actionContent:null,action:null,pzones:[],unsavedOperations:[],operations:[],selectedPZone:null,previewTime:null};var _data=PromotedContentService._serviceData,setupDefer=$q.defer(),readableOperationTypes={INSERT:"INSERT",DELETE:"DELETE",REPLACE:"REPLACE"};PromotedContentService.readableOperationTypes=readableOperationTypes;var operationTypeToReadable={promotion_insertoperation:readableOperationTypes.INSERT,promotion_deleteoperation:readableOperationTypes.DELETE,promotion_replaceoperation:readableOperationTypes.REPLACE},readableToOperationType=_.reduce(operationTypeToReadable,function(result,val,key){return result[val]=key,result},{}),pzoneRefreshPending=!1,pzoneOperationsStale=!0;PromotedContentService.isPZoneRefreshPending=function(){return pzoneRefreshPending},PromotedContentService.isPZoneOperationsStale=function(){return pzoneOperationsStale},PromotedContentService.$refreshPZones=function(filters){var deferred=$q.defer();return pzoneRefreshPending?(deferred.reject(),deferred.promise):(pzoneRefreshPending=!0,ContentFactory.all("pzone").getList(filters).then(function(data){return _data.pzones=data,_.each(_data.pzones,function(pzone){pzone.saved=!0}),deferred.resolve(),_data.pzones})["catch"](function(err){return deferred.reject(),err})["finally"](function(){pzoneRefreshPending=!1}))},PromotedContentService.markDirtySelectedPZone=function(){delete _data.selectedPZone.saved},PromotedContentService.markSavedSelectedPZone=function(){_data.selectedPZone.saved=!0},PromotedContentService.makeOperationsStale=function(){_data.operations=[],pzoneOperationsStale=!0},PromotedContentService.$saveSelectedPZone=function(){var defer=$q.defer();return _data.previewTime&&_data.previewTime.isAfter(moment())?(PromotedContentService.makeOperationsStale(),_.each(_data.unsavedOperations,function(operation){operation.when=_data.previewTime?_data.previewTime.toISOString():null,delete operation.client_id}),_data.selectedPZone.all("operations").post(_data.unsavedOperations).then(function(){defer.resolve(_data.selectedPZone)}),PromotedContentService.clearUnsavedOperations()):_data.previewTime?defer.reject("Cannot save operations in the past."):(PromotedContentService.clearUnsavedOperations(),PromotedContentService.makeOperationsStale(),_data.selectedPZone.put().then(function(){defer.resolve(_data.selectedPZone)})["catch"](function(err){defer.reject(err)})),defer.promise},PromotedContentService.$refreshAllContent=function(){return ContentListService.$updateContent.apply(ContentListService,arguments)},PromotedContentService.$addOperation=function(props){var defer=$q.defer();if(PromotedContentService.isPreviewTimeImmediate())defer.resolve();else if(PromotedContentService.isPreviewTimePast())defer.reject("Cannot add operations in the past.");else{var lastId=_.max(_data.unsavedOperations,"client_id").client_id,nextId=lastId?lastId+1:0,allProps=_.assign({client_id:nextId,type_name:readableToOperationType[props.cleanType]||"",pzone:_data.selectedPZone.id,applied:!1,content:null,content_title:"",index:null},props),operation=Restangular.restangularizeElement(_data.selectedPZone.all("operations"),allProps);_data.unsavedOperations.push(operation),defer.resolve(operation)}return defer.promise},PromotedContentService.$removeOperation=function(id){var defer=$q.defer(),index=_.findIndex(_data.operations,{id:id}),operation=_data.operations[index];return operation?operation.whenAsMoment.isAfter(moment())?operation.remove().then(function(){_data.operations.splice(index,1),defer.resolve()})["catch"](function(err){404===err.status?defer.reject("Cannot find operation to delete."):defer.reject(err)}):defer.reject("Cannot delete an operation in the past."):defer.reject("Could not find saved operation with id "+id+" to delete."),defer.promise},PromotedContentService.clearUnsavedOperations=function(){_data.unsavedOperations=[],PromotedContentService.markSavedSelectedPZone()},PromotedContentService.$refreshOperations=function(params){return _data.selectedPZone.getList("operations",params).then(function(data){return _data.operations=data,_.each(_data.operations,function(operation){operation.cleanType=operationTypeToReadable[operation.type_name],operation.whenAsMoment=moment(operation.when)}),pzoneOperationsStale=!1,_data.operations})["catch"](function(err){return err})},PromotedContentService.$selectPZone=function(name){return _data.selectedPZone=_.find(_data.pzones,{name:name})||_data.pzones[0],PromotedContentService.clearUnsavedOperations(),PromotedContentService.$refreshSelectedPZone(_data.previewTime)},PromotedContentService.$removeContentFromPZone=function(contentId){var defer=$q.defer(),i=_.findIndex(_data.selectedPZone.content,{id:contentId});return i>=0?PromotedContentService.$addOperation({cleanType:readableOperationTypes.DELETE,content:contentId,content_title:_data.selectedPZone.content[i].title}).then(function(){PromotedContentService.markDirtySelectedPZone(),_data.selectedPZone.content.splice(i,1),defer.resolve()})["catch"](function(err){defer.reject(err)}):defer.reject("Could not find content with given id to delete."),defer.promise};var moveTo=function(indexFrom,indexTo){var ret=!1,content=_data.selectedPZone.content;if(indexFrom>=0&&indexFrom=0&&indexTo0&&(content[indexTo]=splicer[0],ret=!0,PromotedContentService.markDirtySelectedPZone())}return ret};PromotedContentService.moveContentUp=function(index){return moveTo(index,index-1)},PromotedContentService.moveContentDn=function(index){return moveTo(index,index+1)},PromotedContentService.beginContentInsert=function(article){_data.actionContent=article,_data.action=readableOperationTypes.INSERT},PromotedContentService.beginContentReplace=function(article){_data.actionContent=article,_data.action=readableOperationTypes.REPLACE},PromotedContentService.stopContentAction=function(){_data.actionContent=null,_data.action=null},PromotedContentService.$completeContentAction=function(index){var deferred=$q.defer();return _data.action?PromotedContentService.$addOperation({cleanType:_data.action,content:_data.actionContent.id,content_title:_data.actionContent.title,index:index}).then(function(){var duplicateIndex=_.findIndex(_data.selectedPZone.content,{id:_data.actionContent.id });index!==duplicateIndex&&duplicateIndex>=0&&_data.selectedPZone.content.splice(duplicateIndex,1);var replace=_data.action===readableOperationTypes.REPLACE;_data.selectedPZone.content.splice(index,replace?1:0,_data.actionContent),PromotedContentService.stopContentAction(),PromotedContentService.markDirtySelectedPZone(),deferred.resolve()})["catch"](deferred.reject):deferred.reject("No action to complete in progress."),deferred.promise},PromotedContentService.setPreviewTime=function(time){return _data.previewTime=time,PromotedContentService.clearUnsavedOperations(),PromotedContentService.$refreshSelectedPZone(_data.previewTime)},PromotedContentService.setPreviewTimeToImmediate=function(){PromotedContentService.setPreviewTime(null)},PromotedContentService.isPreviewTimeImmediate=function(){return null===_data.previewTime},PromotedContentService.isPreviewTimePast=function(){return!PromotedContentService.isPreviewTimeImmediate()&&_data.previewTime.isBefore(moment())},PromotedContentService.$refreshSelectedPZone=function(time){var params={};time&&(params.preview=time.toISOString()),PromotedContentService.makeOperationsStale();var deferred=$q.defer();return pzoneRefreshPending?deferred.reject():(pzoneRefreshPending=!0,_data.selectedPZone.get(params).then(function(data){return deferred.resolve(),_data.selectedPZone=data,_data.selectedPZone})["catch"](function(err){return deferred.reject(),err})["finally"](function(){PromotedContentService.markSavedSelectedPZone(),pzoneRefreshPending=!1})),deferred.promise},PromotedContentService.getData=function(){return _data},PromotedContentService.$ready=function(){return setupDefer.promise},PromotedContentService.$refreshPZones().then(function(){return PromotedContentService.$refreshAllContent()}).then(function(){return PromotedContentService.$selectPZone()}).then(function(){setupDefer.resolve()})}),angular.module("promotedContentTimePicker.directive",["bulbsCmsApp.settings","promotedContent.service"]).directive("promotedContentTimePicker",function(routes){return{controller:function(moment,$scope,PromotedContentService){$scope.contentData=PromotedContentService.getData(),$scope.setPreviewTime=function(previewTime){PromotedContentService.setPreviewTime(previewTime)},$scope.setPreviewTimeToImmediate=function(){$scope.previewTime=null,PromotedContentService.setPreviewTimeToImmediate()},$scope.disableControls=function(){return PromotedContentService.isPZoneRefreshPending()}},restrict:"E",scope:{},templateUrl:routes.COMPONENTS_URL+"promoted-content/promoted-content-time-picker/promoted-content-time-picker.html"}}),angular.module("promotedContentTimePicker",["promotedContentTimePicker.directive"]),angular.module("promotedContent",["bulbsCmsApp.settings","promotedContentPzoneSelect","promotedContentList","promotedContentSearch","promotedContentTimePicker","promotedContentOperationsList"]).config(function($routeProvider,routes){$routeProvider.when("/cms/app/promotion/",{controller:["$window",function($window){$window.document.title=routes.CMS_NAMESPACE+" | Promotion Tool"}],templateUrl:routes.COMPONENTS_URL+"promoted-content/promoted-content.html",reloadOnSearch:!1})}),angular.module("lineItems.edit.directive",["apiServices.lineItem.factory","bulbsCmsApp.settings","lodash","saveButton.directive","topBar"]).directive("lineItemsEdit",function(routes){return{controller:function(_,$location,$q,$routeParams,$scope,LineItem){"new"===$routeParams.id?($scope.model=LineItem.$build(),$scope.isNew=!0):$scope.model=LineItem.$find($routeParams.id),window.onbeforeunload=function(e){return!_.isEmpty($scope.model.$dirty())||$scope.isNew||$scope.needsSave?"You have unsaved changes.":void 0},$scope.$on("$destroy",function(){delete window.onbeforeunload}),$scope.saveModel=function(){var promise;if($scope.model)promise=$scope.model.$save().$asPromise().then(function(data){$location.path("/cms/app/line-items/edit/"+data.id+"/")});else{var deferred=$q.defer();deferred.reject(),promise=deferred.promise}return promise}},restrict:"E",scope:{getModelId:"&modelId"},templateUrl:routes.COMPONENTS_URL+"reporting/reporting-line-items-edit/reporting-line-items-edit.html"}}),angular.module("lineItems.edit",["lineItems.edit.directive"]).config(function($routeProvider,routes){$routeProvider.when("/cms/app/line-items/edit/:id/",{controller:function($routeParams,$scope,$window){$window.document.title=routes.CMS_NAMESPACE+" | Edit Line Item",$scope.routeId=$routeParams.id},template:'',reloadOnSearch:!1})}),angular.module("lineItems.list",["apiServices.lineItem.factory","bulbsCmsApp.settings","listPage"]).config(function($routeProvider,routes){$routeProvider.when("/cms/app/line-items/",{controller:function($scope,$window,LineItem){$window.document.title=routes.CMS_NAMESPACE+" | Line Items",$scope.modelFactory=LineItem},templateUrl:routes.COMPONENTS_URL+"reporting/reporting-line-items-list/reporting-line-items-list.html"})}),angular.module("rateOverrides.edit.directive",["apiServices.rateOverride.factory","apiServices.featureType.factory","bulbsCmsApp.settings","lodash","saveButton.directive","topBar"]).directive("rateOverridesEdit",function(routes){return{controller:function(_,$location,$http,$q,$routeParams,$scope,ContentFactory,FeatureType,RateOverride,Raven){var resourceUrl="/cms/api/v1/contributions/role/";"new"===$routeParams.id?($scope.model=RateOverride.$build(),$scope.isNew=!0):($scope.model=RateOverride.$find($routeParams.id),$scope.model.$promise.then(function(){$scope.model.hasOwnProperty("role")&&null!==$scope.model.role&&($scope.model.role=$scope.model.role.id)})),window.onbeforeunload=function(e){return!_.isEmpty($scope.model.$dirty())||$scope.isNew||$scope.needsSave?"You have unsaved changes.":void 0},$scope.$on("$destroy",function(){delete window.onbeforeunload}),$scope.getPaymentType=function(roleId){if($scope.hasOwnProperty("roles")){for(var i=0;i<$scope.roles.length;i++)if($scope.roles[i].id===roleId)return $scope.roles[i].payment_type;return null}},$scope.isFeatureRated=function(){return"FeatureType"===$scope.getPaymentType($scope.model.role)?!0:!1},$scope.isHourlyRated=function(){return"Hourly"===$scope.getPaymentType($scope.model.role)?!0:!1},$scope.isFlatRated=function(){return"Flat Rate"===$scope.getPaymentType($scope.model.role)?!0:!1},$scope.addFeatureType=function(){$scope.model.hasOwnProperty("featureTypes")||($scope.model.featureTypes=[]),$scope.model.featureTypes.push({featureType:null,rate:0})},$scope.getFeatureTypes=function(){$http({method:"GET",url:resourceUrl}).success(function(data){$scope.featureTypes=data.results||data}).error(function(data,status,headers,config){Raven.captureMessage("Error fetching FeatureTypes",{extra:data})})},$scope.getRoles=function(){$http({method:"GET",url:resourceUrl}).success(function(data){$scope.roles=data.results||data}).error(function(data,status,headers,config){Raven.captureMessage("Error fetching Roles",{extra:data})})},$scope.searchFeatureTypes=function(searchTerm){return FeatureType.simpleSearch(searchTerm)},$scope.saveModel=function(){var promise;if($scope.model)promise=$scope.model.$save().$asPromise().then(function(data){$location.path("/cms/app/rate-overrides/edit/"+data.id+"/"),$scope.model.hasOwnProperty("role")&&null!==$scope.model.role&&($scope.model.role=$scope.model.role.id)});else{var deferred=$q.defer();deferred.reject(),promise=deferred.promise}return promise},$scope.getRoles(),$scope.getFeatureTypes()},restrict:"E",scope:{getModelId:"&modelId"},templateUrl:routes.COMPONENTS_URL+"reporting/reporting-rate-overrides-edit/reporting-rate-overrides-edit.html"}}),angular.module("rateOverrides.edit",["rateOverrides.edit.directive"]).config(function($routeProvider,routes){$routeProvider.when("/cms/app/rate-overrides/edit/:id/",{controller:function($routeParams,$scope,$window){$window.document.title=routes.CMS_NAMESPACE+" | Edit Rate Override",$scope.routeId=$routeParams.id},template:'',reloadOnSearch:!1})}),angular.module("rateOverrides.list",["apiServices.rateOverride.factory","bulbsCmsApp.settings","listPage"]).config(function($routeProvider,routes){$routeProvider.when("/cms/app/rate-overrides/",{controller:function($scope,$window,RateOverride){$window.document.title=routes.CMS_NAMESPACE+" | Rate Overrides",$scope.modelFactory=RateOverride},templateUrl:routes.COMPONENTS_URL+"reporting/reporting-rate-overrides-list/reporting-rate-overrides-list.html"})}),angular.module("roles.edit.directive",["apiServices.reporting.factory","bulbsCmsApp.settings","lodash","saveButton.directive","topBar"]).constant("PAYMENT_TYPES",[{name:"Flat Rate",value:"Flat Rate"},{name:"FeatureType",value:"FeatureType"},{name:"Hourly",value:"Hourly"},{name:"Manual",value:"Manual"}]).directive("rolesEdit",function(routes){return{controller:function(_,$location,$q,$routeParams,$scope,Role,PAYMENT_TYPES){$scope.page="contributions",$scope.PAYMENT_TYPES=PAYMENT_TYPES,"new"===$routeParams.id?($scope.model=Role.$build(),$scope.isNew=!0):$scope.model=Role.$find($routeParams.id).$then(function(){$scope.model.feature_type_rates.$fetch(),$scope.model.flat_rates.$fetch(),$scope.model.hourly_rates.$fetch()}),window.onbeforeunload=function(e){return!_.isEmpty($scope.model.$dirty())||$scope.isNew||$scope.needsSave?"You have unsaved changes.":void 0},$scope.$on("$destroy",function(){delete window.onbeforeunload}),$scope.rateEditable=function(){var paymentTypes=PAYMENT_TYPES.slice(0,3);return paymentTypes.indexOf($scope.model.paymentType>=0)?!0:!1},$scope.getDirtyRates=function(){var dirty=[];return $scope.model.hasOwnProperty("flat_rate")&&!_.isEmpty($scope.model.flat_rate.$dirty())&&dirty.push($scope.model.flat_rate),$scope.model.hasOwnProperty("hourly_rate")&&!_.isEmpty($scope.model.hourly_rate.$dirty())&&dirty.push($scope.model.hourly_rate),$scope.model.feature_type_rates.forEach(function(rate){_.isEmpty(rate.$dirty())||dirty.push(rate)}),dirty},$scope.saveDirtyRates=function(){var dirtyRates=$scope.getDirtyRates();dirtyRates.forEach(function(rate){rate.$save()})},$scope.saveModel=function(){var promise;if($scope.saveDirtyRates(),$scope.model)promise=$scope.model.$save().$asPromise().then(function(data){$location.path("/cms/app/roles/edit/"+data.id+"/")});else{var deferred=$q.defer();deferred.reject(),promise=deferred.promise}return promise}},restrict:"E",scope:{getModelId:"&modelId"},templateUrl:routes.COMPONENTS_URL+"reporting/reporting-roles-edit/reporting-roles-edit.html"}}),angular.module("roles.edit",["roles.edit.directive"]).config(function($routeProvider,routes){$routeProvider.when("/cms/app/roles/edit/:id/",{controller:function($routeParams,$scope,$window){$window.document.title=routes.CMS_NAMESPACE+" | Edit Role",$scope.routeId=$routeParams.id},template:'',reloadOnSearch:!1})}),angular.module("roles.list",["apiServices.reporting.factory","bulbsCmsApp.settings","listPage"]).config(function($routeProvider,routes){$routeProvider.when("/cms/app/roles/",{controller:function($scope,$window,Role){$window.document.title=routes.CMS_NAMESPACE+" | Roles",$scope.modelFactory=Role},templateUrl:routes.COMPONENTS_URL+"reporting/reporting-roles-list/reporting-roles-list.html"})}),angular.module("reports",["lineItems.edit","lineItems.list","rateOverrides.edit","rateOverrides.list","roles.edit","roles.list"]),angular.module("sections.edit.directive",["apiServices.section.factory","BettyCropper","bulbsCmsApp.settings","copyButton","customSearch","lodash","saveButton.directive","sections.settings","topBar"]).directive("sectionsEdit",function(routes){return{controller:function(_,$location,$q,$scope,EXTERNAL_URL,SECTIONS_LIST_REL_PATH,Section){$scope.LIST_URL=EXTERNAL_URL+SECTIONS_LIST_REL_PATH,$scope.needsSave=!1;var modelId=$scope.getModelId();"new"===modelId?($scope.model=Section.$build(),$scope.isNew=!0):$scope.model=Section.$find($scope.getModelId()),window.onbeforeunload=function(e){return!_.isEmpty($scope.model.$dirty())||$scope.isNew||$scope.needsSave?"You have unsaved changes.":void 0},$scope.$on("$destroy",function(){delete window.onbeforeunload}),$scope.saveModel=function(){var promise;if($scope.model)promise=$scope.model.$save().$asPromise().then(function(data){"new"===modelId&&$location.path("/cms/app/section/edit/"+data.id+"/"),$scope.isNew=!1,$scope.needsSave=!1});else{var deferred=$q.defer();deferred.reject(),promise=deferred.promise}return promise}},restrict:"E",scope:{getModelId:"&modelId"},templateUrl:routes.COMPONENTS_URL+"sections/sections-edit/sections-edit.html"}}),angular.module("sections.edit",["sections.edit.directive"]).config(function($routeProvider,routes){$routeProvider.when("/cms/app/section/edit/:id/",{controller:function($routeParams,$scope,$window){$window.document.title=routes.CMS_NAMESPACE+" | Edit Section",$scope.routeId=$routeParams.id},template:'',reloadOnSearch:!1})}),angular.module("sections.list.directive",["bulbsCmsApp.settings","confirmationModal","apiServices.section.factory"]).directive("sectionsList",function(routes){return{controller:function($scope,$location,Section){$scope.$list=Section.$collection(),$scope.$retrieve=function(){$scope.$list.$refresh()},$scope.$add=function(){$location.path("/cms/app/section/edit/new/")},$scope.$remove=function(item){item.$destroy()},$scope.$retrieve()},restrict:"E",scope:{},templateUrl:routes.COMPONENTS_URL+"sections/sections-list/sections-list.html"}}),angular.module("sections.list",["apiServices.section.factory","bulbsCmsApp.settings","listPage","sections.settings"]).config(function($routeProvider,routes){$routeProvider.when("/cms/app/section/",{controller:function($scope,$window,EXTERNAL_URL,SECTIONS_LIST_REL_PATH,Section){$window.document.title=routes.CMS_NAMESPACE+" | Section",$scope.modelFactory=Section,$scope.LIST_URL=EXTERNAL_URL+SECTIONS_LIST_REL_PATH},templateUrl:routes.COMPONENTS_URL+"sections/sections-list/sections-list-page.html"})}),angular.module("sections.settings",[]).value("SECTIONS_LIST_REL_PATH","/section/"),angular.module("sections",["sections.list","sections.edit"]),angular.module("specialCoverage.edit.directive",["apiServices.specialCoverage.factory","autocompleteBasic","bulbsCmsApp.settings","apiServices.campaign.factory","copyButton","customSearch","lodash","specialCoverage.settings","topBar","ui.bootstrap.tooltip","videoList"]).directive("specialCoverageEdit",function(routes){return{controller:function(_,$location,$q,$scope,$modal,Campaign,EXTERNAL_URL,SPECIAL_COVERAGE_LIST_REL_PATH,SpecialCoverage){$scope.ACTIVE_STATES=SpecialCoverage.ACTIVE_STATES,$scope.LIST_URL=EXTERNAL_URL+SPECIAL_COVERAGE_LIST_REL_PATH,$scope.needsSave=!1;var modelId=$scope.getModelId();"new"===modelId?($scope.model=SpecialCoverage.$build(),$scope.isNew=!0):$scope.model=SpecialCoverage.$find($scope.getModelId()),window.onbeforeunload=function(e){return!_.isEmpty($scope.model.$dirty())||$scope.isNew||$scope.needsSave?"You have unsaved changes.":void 0},$scope.$on("$destroy",function(){delete window.onbeforeunload}),$scope.saveModel=function(){var promise;if($scope.model)promise=$scope.model.$save().$asPromise().then(function(data){"new"===modelId&&$location.path("/cms/app/special-coverage/edit/"+data.id+"/"),$scope.isNew=!1,$scope.needsSave=!1});else{var deferred=$q.defer();deferred.reject(),promise=deferred.promise}return promise},$scope.previewLinkModal=function(){return $modal.open({templateUrl:routes.PARTIALS_URL+"modals/preview-link-modal.html",scope:$scope,resolve:{}})},$scope.searchCampaigns=function(searchTerm){return Campaign.simpleSearch(searchTerm)}},restrict:"E",scope:{getModelId:"&modelId"},templateUrl:routes.COMPONENTS_URL+"special-coverage/special-coverage-edit/special-coverage-edit.html"}}),angular.module("specialCoverage.edit",["specialCoverage.edit.directive"]).config(function($routeProvider,routes){$routeProvider.when("/cms/app/special-coverage/edit/:id/",{controller:function($routeParams,$scope,$window){$window.document.title=routes.CMS_NAMESPACE+" | Edit Special Coverage",$scope.routeId=$routeParams.id},template:''})}),angular.module("specialCoverage.list.directive",["bulbsCmsApp.settings","confirmationModal","apiServices.specialCoverage.factory"]).directive("specialCoverageList",function(routes){return{controller:function($scope,$location,SpecialCoverage){$scope.$list=SpecialCoverage.$collection(),$scope.$retrieve=function(){$scope.$list.$refresh()},$scope.$add=function(){$location.path("/cms/app/special-coverage/edit/new/")},$scope.$remove=function(item){item.$destroy()},$scope.$retrieve()},restrict:"E",scope:{},templateUrl:routes.COMPONENTS_URL+"special-coverage/special-coverage-list/special-coverage-list.html"}}),angular.module("specialCoverage.list",["apiServices.specialCoverage.factory","bulbsCmsApp.settings","listPage","moment","specialCoverage.settings"]).config(function($routeProvider,routes){$routeProvider.when("/cms/app/special-coverage/",{controller:function($scope,$window,EXTERNAL_URL,SPECIAL_COVERAGE_LIST_REL_PATH,SpecialCoverage){$window.document.title=routes.CMS_NAMESPACE+" | Special Coverage",$scope.modelFactory=SpecialCoverage,$scope.LIST_URL=EXTERNAL_URL+SPECIAL_COVERAGE_LIST_REL_PATH},templateUrl:routes.COMPONENTS_URL+"special-coverage/special-coverage-list/special-coverage-list-page.html"})}),angular.module("specialCoverage.settings",[]).value("SPECIAL_COVERAGE_LIST_REL_PATH","/special/"),angular.module("specialCoverage",["specialCoverage.list","specialCoverage.edit"]),angular.module("statusFilter.directive",["bulbsCmsApp.settings","contentServices.listService"]).provider("StatusFilterOptions",function(moment){var _statuses=[{label:"Draft",key:"status",value:"draft"},{label:"Published",key:"before",value:function(){return moment().format("YYYY-MM-DDTHH:mmZ")}},{label:"Scheduled",key:"after",value:function(){return moment().format("YYYY-MM-DDTHH:mmZ")}},{label:"All",key:null,value:null}];this.setStatuses=function(statuses){_statuses=statuses},this.$get=function(){return{getStatuses:function(){return _statuses}}}}).directive("statusFilter",function($location,_,StatusFilterOptions,ContentListService,routes){return{templateUrl:routes.COMPONENTS_URL+"status-filter/status-filter.html",restrict:"E",scope:{},controller:"ContentlistCtrl",link:function(scope,element,attrs){function getValue(option){var value;return value="function"==typeof option.value?option.value():option.value}scope.options=StatusFilterOptions.getStatuses(),scope.isActive=function(option){if(option.key&&option.key in $location.search()&&$location.search()[option.key]===getValue(option))return!0;if(!option.key){var possibleKeys=_.pluck(scope.options,"key"),searchKeys=_.keys($location.search());return _.intersection(possibleKeys,searchKeys).length>0?!1:!0}return!1},scope.filterByStatus=function(option){var value,search={};return option.key&&(value=getValue(option),search[option.key]=value),ContentListService.$updateContent(search,!1)}}}}),angular.module("statusFilter",["statusFilter.directive"]),angular.module("templateTypeField.directive",[]).directive("templateTypeField",function(routes){return{controller:function(_,$scope,ContentFactory,TEMPLATE_TYPES){$scope.templateTypes=_.filter(TEMPLATE_TYPES,{content_type:$scope.content.polymorphic_ctype})},restrict:"E",scope:{content:"="},templateUrl:routes.COMPONENTS_URL+"template-type-field/template-type-field.html"}}),angular.module("templateTypeField",["templateTypeField.directive"]).value("TEMPLATE_TYPES",[{name:"Small Width",slug:"small-width",content_type:"content_content"},{name:"Large Width",slug:"large-width",content_type:"content_content"}]),angular.module("topBar.directive",[]).directive("topBar",function(routes){return{restrict:"E",scope:{logoHref:"@",itemsDropdownTitle:"@",itemsDropdown:"=",itemsTop:"=",saveFunction:"=",saveDisableWhen:"&"},templateUrl:routes.COMPONENTS_URL+"top-bar/top-bar-base.html",link:function(scope){scope.NAV_LOGO=routes.NAV_LOGO}}}),angular.module("topBar.item.factory",[]).factory("TopBarItem",function(){var TopBarItem=function(params){this.displayText=params.displayText||"",this.displayIconClasses=params.displayIconClasses||"",this.containerClasses=params.containerClasses||"",this.clickFunction=params.clickFunction||function(){}};return TopBarItem}),angular.module("topBar",["topBar.directive","topBar.item.factory"]),angular.module("apiServices.mixins.fieldDisplay",["restmod"]).factory("FieldDisplay",function($parse,restmod){var parserWrap=function(value){return function(value){var parsed=$parse(value);return function(record){return parsed({record:record})}}(value)},getOrdering=function(sorts){return function(sorts){return function(direction){var ordering="";return ordering="desc"===direction?"-"+sorts:sorts}}(sorts)};return restmod.mixin(function(){this.define("Scope.$fieldDisplays",function(){var fieldDisplays=this.getProperty("fieldDisplays");if(fieldDisplays){var i;for(i=0;i0)for(var key in featureTypes){var obj=featureTypes[key];obj.hasOwnProperty("featureType")&&(obj.featureType.hasOwnProperty("name")?_req.data.feature_types[key].feature_type=obj.featureType.name:obj.featureType.hasOwnProperty("value")&&(_req.data.feature_types[key].feature_type.slug=obj.featureType.value))}},"before-render":function(record){if(record.hasOwnProperty("feature_types"))for(var key in record.feature_types)record.feature_types[key].hasOwnProperty("feature_type")&&record.feature_types[key].feature_type.hasOwnProperty("name")&&(record.feature_types[key].feature_type=record.feature_types[key].feature_type.name)}}})}),angular.module("apiServices.reporting.factory",["apiServices","apiServices.mixins.fieldDisplay"]).factory("Role",function(_,restmod){var roleEndpoint="contributions/role";return restmod.model(roleEndpoint).mix("FieldDisplay","NestedDirtyModel",{flat_rates:{hasMany:restmod.model(null,{}).mix("NestedDirtyModel"),path:"flat_rates",params:{},hooks:{"after-fetch-many":function(){this.length>0?this.$owner.flat_rate=this[0]:this.$owner.flat_rate=this.$owner.flat_rates.$create({rate:0})}}},hourly_rates:{hasMany:restmod.model(null,{rate:0}).mix("NestedDirtyModel"),path:"hourly_rates",params:{},hooks:{"after-fetch-many":function(){this.length>0?this.$owner.hourly_rate=this[0]:this.$owner.hourly_rate=this.$owner.hourly_rates.$create({rate:0})}}},feature_type_rates:{hasMany:restmod.model(null,{}).mix("NestedDirtyModel"),path:"feature_type_rates",params:{},hooks:{"after-fetch-many":function(){var next=this.$metadata.next;_.isUndefined(next)||null===next||(this.$owner.feature_type_rates.$page++,this.$owner.feature_type_rates.$fetch())}}},$config:{name:"Role",plural:"Roles",primaryKey:"id",fieldDisplays:[{title:"Role",value:"record.name"},{title:"Payment Type",value:"record.paymentType"}]}})}),angular.module("apiServices.section.factory",["apiServices","apiServices.customSearch.count.factory","apiServices.mixins.fieldDisplay"]).factory("Section",function(_,CustomSearchCount,restmod){var sectionEndpoint="section";return restmod.model(sectionEndpoint).mix("FieldDisplay","NestedDirtyModel",{$config:{name:"Section",plural:"Sections",primaryKey:"id",fieldDisplays:[{title:"Section Name",value:"record.name",sorts:"name"},{title:"Article Count",value:"record.$resultCount"}]},query:{init:{}},promoted:{init:!0},$hooks:{"after-fetch":function(){this.$refreshResultCount()},"after-fetch-many":function(){_.each(this,function(record){record.$refreshResultCount()})}},$extend:{Record:{$refreshResultCount:function(){var record=this;return CustomSearchCount.$retrieveResultCount(this.query).then(function(count){record.$resultCount=count})}}}})}),angular.module("apiServices.specialCoverage.factory",["apiServices","apiServices.campaign.factory","apiServices.mixins.fieldDisplay","filters.moment","VideohubClient.api"]).factory("SpecialCoverage",function(_,$parse,restmod,Video){ -var ACTIVE_STATES={INACTIVE:"Inactive",PROMOTED:"Pin to HP"};return restmod.model("special-coverage").mix("FieldDisplay","NestedDirtyModel",{$config:{name:"Special Coverage",plural:"Special Coverages",primaryKey:"id",fieldDisplays:[{title:"List Title",value:"record.name",sorts:"name"},{title:"Sponsor",value:'record.campaign.sponsorName || "--"',sorts:"campaign__sponsor_name"},{title:"Campaign",value:'record.campaign.campaignLabel || "--"',sorts:"campaign__campaign_label"},{title:"Start Date",value:'record.startDate.format("MM/DD/YY") || "--"',sorts:"start_date"},{title:"End Date",value:'record.endDate.format("MM/DD/YY") || "--"',sorts:"end_date"}]},end_date:{encode:"moment_to_date_string"},start_date:{encode:"moment_to_date_string"},endDate:{decode:"date_string_to_moment"},startDate:{decode:"date_string_to_moment"},campaign:{belongsTo:"Campaign",prefetch:!0,key:"campaign"},listUrl:{mask:"CU"},query:{init:{}},videos:{belongsToMany:"Video",keys:"videos"},active:{init:!0},promoted:{init:!1},$hooks:{"after-fetch":function(){this.$loadVideosData()},"after-save":function(){this.$loadVideosData()}},$extend:{Record:{$loadVideosData:function(){_.each(this.videos,function(video){video.$fetch()})},addVideo:function(video){var added=!1,existingVideo=_.find(this.videos,function(existingVideo){return video.id===existingVideo.id});return existingVideo||(this.videos.push(video),added=!0),added},$activeState:function(activeState){return _.isString(activeState)?activeState===ACTIVE_STATES.ACTIVE?(this.active=!0,this.promoted=!1):activeState===ACTIVE_STATES.PROMOTED?(this.active=!0,this.promoted=!0):(this.active=!1,this.promoted=!1):(activeState=ACTIVE_STATES.INACTIVE,this.active&&this.promoted?activeState=ACTIVE_STATES.PROMOTED:this.active&&(activeState=ACTIVE_STATES.ACTIVE)),activeState}},Model:{ACTIVE_STATES:_.clone(ACTIVE_STATES)}}})}),angular.module("apiServices.video.factory",["apiServices"]).value("VIDEOHUB_CHANNEL","onion").factory("Video",function(_,restmod,VIDEOHUB_CHANNEL){var singleRoot="root",videohubEndpoint="videohub-video",search=restmod.model(videohubEndpoint+"/search_hub").mix({$config:{jsonRootSingle:singleRoot},results:{hasMany:"Video"},$hooks:{"after-request":function(_req){var newData={};newData[singleRoot]=_req.data,_req.data=newData}}}),video=restmod.model(videohubEndpoint).mix({$config:{name:"Video",primaryKey:"id"},$extend:{Model:{searchVideoHub:function(query){return search.$create({query:query,filters:{channel:VIDEOHUB_CHANNEL}}).$asPromise()}}}});return video}),angular.module("contentServices.factory",[]).factory("ContentFactory",function(Restangular,contentApiConfig){return Restangular.withConfig(function(RestangularConfigurer){RestangularConfigurer.setBaseUrl(contentApiConfig.baseUrl)})}).constant("contentApiConfig",{baseUrl:"/cms/api/v1"}),angular.module("contentServices.listService",["contentServices.factory"]).service("ContentListService",function(_,$location,$q,ContentFactory){var ContentListService=this;this._serviceData={filters:$location.search()||{},content:[],totalItems:0};var _data=this._serviceData;ContentListService.updateFilters=function(addFilters,merge){return merge?_data.filters=_.assign($location.search()||{},addFilters):_data.filters=addFilters,$location.search(_data.filters),_data.filters},ContentListService.$updateContent=function(addFilters,merge){var updateParams=ContentListService.updateFilters(addFilters||_data.filters,merge);return ContentFactory.all("content").getList(updateParams).then(function(data){return _data.content=data,_data.totalItems=data.metadata.count,_data})},ContentListService.getData=function(){return _data}}),angular.module("contentServices",["contentServices.factory","contentServices.listService"]),angular.module("copyButton",[]).directive("copyButton",function(routes){return{controller:function($scope,$timeout){$scope.okCopy=!1,$scope.okCopyButton=function(){$scope.okCopy=!0,$timeout(function(){$scope.okCopy=!1},1e3)}},restrict:"E",scope:{buttonClassesDefault:"@",buttonClassesSuccess:"@",buttonText:"@",content:"@"},templateUrl:routes.SHARED_URL+"copy-button/copy-button.html"}}),angular.module("filters.moment",["moment"]).filter("date_string_to_moment",function(moment){return function(dateStr){if(dateStr&&dateStr.length){var m=moment(dateStr);if(m.isValid())return m}return null}}).filter("moment_to_date_string",function(moment){return function(momentObj){return moment.isMoment(momentObj)&&momentObj.isValid()?momentObj.format():""}}),angular.module("listPage",["bulbsCmsApp.settings","confirmationModal","copyButton","lodash"]).directive("listPage",function(routes){return{controller:function(_,$scope,$location,$parse){$scope.name=$scope.modelFactory.identity(),$scope.namePlural=$scope.modelFactory.identity(!0),$scope.fields=$scope.modelFactory.$fieldDisplays(),$scope.$list=$scope.modelFactory.$collection(),$scope.orderingFilter={},$scope.searchFilter={},$scope.toggledFilters={},$scope.copyContentInContext=function(record){var value="";return $scope.toolCopyContent&&(value=$parse($scope.toolCopyContent)({record:record})),value},$scope.$retrieve=_.debounce(function(addParams){$scope.loadingResults=!0;var allParams=_.merge({},$scope.orderingFilter,$scope.toggledFilters,$scope.searchFilter,addParams);return $scope.$list.$refresh(allParams).$then(function(){$scope.loadingResults=!1})},250),$scope.$search=function(query){$scope.searchFilter={},query&&($scope.searchFilter[$scope.searchParameter]=query),$scope.$list.$page=1,$scope.$retrieve()},$scope.filterButtonsParsed=$scope.filterButtons(),$scope.$toggleFilters=function(params){$scope.toggledFilters=params,$scope.$list.$page=1,$scope.$retrieve()},$scope.sortingField=null,$scope.sortDirection="asc",$scope.$sort=function(field){var direction;direction=field.title===$scope.sortingField&&"desc"===$scope.sortDirection?"asc":"desc",function(field,direction){$scope.orderingFilter={ordering:field.getOrdering(direction)},$scope.$retrieve().$then(function(){$scope.sortingField=field.title,$scope.sortDirection=direction})}(field,direction)},$scope.$add=function(){$location.path("/cms/app/"+$scope.cmsPage+"/edit/new/")},$scope.$remove=function(item){item.$destroy()},$scope.goToEditPage=function(item){$location.path("/cms/app/"+$scope.cmsPage+"/edit/"+item.id+"/")},$scope.activeFilterButton=_.chain($scope.filterButtonsParsed).findWhere({active:!0}).tap(function(button){button&&($scope.toggledFilters=button.params)}).result("title").value()||"",$scope.$retrieve()},restrict:"E",scope:{cmsPage:"@",filterButtons:"&",modelFactory:"=",searchParameter:"@",toolCopyContent:"@"},templateUrl:routes.SHARED_URL+"list-page/list-page.html"}}),angular.module("momentFormatterFilter",["moment"]).filter("momentFormatter",function(moment){return function(date,format){var m=moment(date);return m.isValid()?m.format(format):""}}),angular.module("slugify",[]).filter("slugify",function(){return function(text){return text.toString().toLowerCase().replace(/\s+/g,"-").replace(/[^\w\-]+/g,"").replace(/\-\-+/g,"-").replace(/^-+/,"").replace(/-+$/,"")}}),angular.module("cms.tunic.config",["lodash"]).provider("TunicConfig",["_",function(_){var apiPath="",backendRoot="",requestToken="",error=function(message){return new Error("Configuration Error (TunicConfig) "+message)};this.setApiPath=function(value){if(!_.isString(value))throw error("apiPath must be a string!");return apiPath=value,this},this.setBackendRoot=function(value){if(!_.isString(value))throw error("backendRoot must be a string!");return backendRoot=value,this},this.setRequestToken=function(value){if(!_.isString(value))throw error("requestToken must be a string!");return requestToken=value,this},this.$get=function(){return{getRequestToken:_.constant(requestToken),buildBackendApiUrl:function(relUrl){return backendRoot+apiPath+(relUrl||"")},shouldBeIntercepted:function(url){return url.startsWith(backendRoot+apiPath)}}}}]),angular.module("cms.tunic.interceptor",["cms.tunic.config"]).service("TunicInterceptor",["TunicConfig",function(TunicConfig){return this.request=function(config){return TunicConfig.shouldBeIntercepted(config.url)&&(config.headers=config.headers||{},config.headers.Authorization="Token "+TunicConfig.getRequestToken()),config},this}]),angular.module("cms.tunic",["cms.tunic.config","cms.tunic.interceptor"]),angular.module("utils",[]).service("Utils",function(){var Utils=this;return Utils.slugify=function(text){return text.toString().toLowerCase().replace(/\s+/g,"-").replace(/[^\w\-]+/g,"").replace(/\-\-+/g,"-").replace(/^-+/,"").replace(/-+$/,"")},Utils.moveTo=function(list,indexFrom,indexTo){var ret=!1;if(indexFrom>=0&&indexFrom=0&&indexTo0&&(list[indexTo]=splicer[0],ret=!0)}return ret},Utils.removeFrom=function(list,index){return list.splice(index,1).length>0},Utils}),angular.module("videoList.video.directive",["bulbsCmsApp.settings","filters.moment"]).directive("videoListVideo",function(routes){return{restrict:"E",scope:{model:"="},templateUrl:routes.SHARED_URL+"video-list/video-list-video/video-list-video.html"}}),angular.module("videoList",["autocompleteBasic","jquery","videoList.video.directive","ui.sortable","utils","VideohubClient.api","VideohubClient.settings"]).directive("videoList",function($,routes){return{controller:function(_,$scope,Utils,Video,VIDEOHUB_DEFAULT_CHANNEL){$scope.videoChannel=VIDEOHUB_DEFAULT_CHANNEL,$scope.moveUp=function(index){Utils.moveTo($scope.videos,index,index-1),$scope.onUpdate()},$scope.moveDown=function(index){Utils.moveTo($scope.videos,index,index+1),$scope.onUpdate()},$scope["delete"]=function(index){Utils.removeFrom($scope.videos,index),$scope.onUpdate()},$scope.addVideo=function(video){$scope.addVideoCallback({video:video}),$scope.onUpdate()},$scope.searchVideos=function(query){return Video.$postSearch({query:query,channel:VIDEOHUB_DEFAULT_CHANNEL})}},link:function(scope,element,attr){scope.sortableOptions={beforeStop:function(e,ui){ui.helper.css("margin-top",0)},change:function(e,ui){ui.helper.css("margin-top",$(window).scrollTop())},containment:"video-list",distance:3,opacity:.75,placeholder:"dropzone",start:function(e,ui){ui.helper.css("margin-top",$(window).scrollTop())}}},restrict:"E",scope:{addVideoCallback:"&addVideo",videos:"=",onUpdate:"&"},templateUrl:routes.SHARED_URL+"video-list/video-list.html"}}),angular.module("bulbsCmsApp").directive("activeNav",function($location){return{template:'
  • {{label}}
  • ',restrict:"E",scope:{},replace:!0,link:function(scope,element,attrs){scope.href=attrs.href,scope.label=attrs.label,0===$location.path().indexOf(scope.href)&&element.addClass("active")}}}),angular.module("bulbsCmsApp").directive("addImage",function($http,$window,routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"add-image.html",scope:{article:"="},link:function(scope,element,attrs){var attrName=attrs.attrName||"images";scope.article[attrName]=scope.article[attrName]||[],"false"===attrs.caption&&(scope.hideCaption=!0),scope.format=attrs.format||"jpg",scope.crop=attrs.crop||"16x9",scope.placeholderText=attrs.placeholderText||"Optional Image",scope.addAnImage=function(){$window.uploadImage({onSuccess:function(data){scope.$apply(function(){scope.article[attrName].push({id:data.id.toString(),alt:null,caption:null}),setTimeout($window.picturefill,200)})},onError:function(data){scope.$apply(function(){$window.alert("Error: ",data)})},onProgress:function(data){}})}}}}),angular.module("bulbsCmsApp").directive("articlecontainer",function(routes,LOADING_IMG_SRC){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"promotion-tool-article-container.html",scope:{article:"="},link:function(scope,element,attrs){scope.LOADING_IMG_SRC=LOADING_IMG_SRC,scope.ratio=attrs.ratio}}}),angular.module("bulbsCmsApp").directive("authorsField",function(routes,userFilter,$){return{templateUrl:routes.PARTIALS_URL+"taglike-autocomplete-field.html",restrict:"E",replace:!0,scope:{article:"="},link:function(scope,element,attrs){scope.name="author",scope.label="Authors",scope.placeholder="Authors",scope.resourceUrl="/cms/api/v1/author/?ordering=name&search=",scope.display=userFilter,scope.$watch("article.authors",function(){scope.objects=scope.article.authors},!0),scope.add=function(o,input){for(var t in scope.article.authors)if(scope.article.authors[t].id===o.id)return;scope.article.authors.push(o),$(input).val("")},scope["delete"]=function(e){var author=$(e.target).parents("[data-taglikeobject]").data("taglikeobject"),id=author.id,newauthors=[];for(var i in scope.article.authors)scope.article.authors[i].id!==id&&newauthors.push(scope.article.authors[i]);scope.article.authors=newauthors}}}}),angular.module("bulbsCmsApp").directive("bulbsAutocomplete",function($http,$location,$compile,$timeout,$,Login,Raven){var autocomplete_dropdown_template='';return{restrict:"AC",link:function(scope,element,attrs){function getAutocompletes(val){$timeout.cancel(inputTimeout),inputCounter=0,$http({method:"GET",url:scope.resourceUrl+val}).success(function(data){var results=data.results||data;scope.autocomplete_list=results.splice(0,5)}).error(function(data,status,headers,config){Raven.captureMessage("Error in getAutocompletes",{extra:data})})}var $elem=$(element).find("input");$elem.attr("autocomplete","off");var dropdown=$($compile(autocomplete_dropdown_template)(scope));$(dropdown).css({position:"absolute",top:$elem.position().top+$elem.outerHeight(),left:$elem.position().left,minWidth:$elem.outerWidth(),display:"none"}),$elem.parent().append(dropdown),$(dropdown).fadeIn("fast"),scope.$watch(function(){return{top:$elem.position().top+$elem.outerHeight(),left:$elem.position().left,minWidth:$elem.outerWidth()}},function(newValue,oldValue){$(dropdown).css({top:newValue.top,left:newValue.left,minWidth:newValue.minWidth})},!0);var inputTimeout,inputCounter=0;$elem.on("focus",function(e){$elem.on("input",function(){var val=$elem.val();""===val?scope.autocomplete_list=[]:($timeout.cancel(inputTimeout),inputTimeout=$timeout(function(){getAutocompletes(val)},200),inputCounter>2&&getAutocompletes(val))}),$(dropdown).fadeIn("fast")}),$elem.on("blur",function(e){$(dropdown).fadeOut("fast")}),$(dropdown).on("mouseover",".entry",function(e){$(dropdown).find(".selected").removeClass("selected"),$(this).addClass("selected")}),$elem.on("keyup",function(e){if(40===e.keyCode)if(0===$("div.selected",dropdown).length)$("div.entry",dropdown).first().addClass("selected");else{var curDownSelect=$("div.selected",dropdown),curDownSelectNext=curDownSelect.next("div");0===curDownSelectNext.length?$("div.entry",dropdown).first().addClass("selected"):curDownSelectNext.addClass("selected"),curDownSelect.removeClass("selected")}if(38===e.keyCode)if(0===$("div.selected",dropdown).length)$("div.entry",dropdown).last().addClass("selected");else{var curSelect=$("div.selected",dropdown),curSelectNext=curSelect.prev("div");0===curSelectNext.length?$("div.entry",dropdown).last().addClass("selected"):curSelectNext.addClass("selected"),curSelect.removeClass("selected")}if(13===e.keyCode){var selected=$("div.selected",dropdown);0===selected.length&&scope.onClick($elem.val(),!0),selected.click()}}),scope.onClick=function(o,freeForm){scope.add(o,$elem,freeForm||!1),scope.autocomplete_list=[]}}}}),angular.module("bulbsCmsApp").directive("cmsNotification",function(routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"cms-notification.html",scope:{notification:"="},controller:"CmsNotificationCtrl"}}),angular.module("bulbsCmsApp").directive("cmsNotifyContainer",function(routes){return{restrict:"E",scope:{},templateUrl:routes.PARTIALS_URL+"cms-notify-container.html",controller:"CmsNotifyContainerCtrl"}}),angular.module("bulbsCmsApp").directive("contributorField",function(routes,$){return{templateUrl:routes.PARTIALS_URL+"textlike-autocomplete-field.html",restrict:"E",replace:!0,scope:{override:"="},link:function(scope,element,attrs){scope.name="contributor",scope.label="Contributors",scope.placeholder="Contributors",scope.resourceUrl="/cms/api/v1/author/?ordering=name&search=",scope.$watch("override.contributor",function(){scope.override.hasOwnProperty("contributor")&&null!==scope.override.contributor&&(scope.model=scope.override.contributor.full_name||scope.override.contributor.fullName)}),scope.display=function(o){return o&&o.full_name||""},scope.add=function(o,input){scope.override.hasOwnProperty("contributor")&&null!==scope.override.contributor&&scope.override.contributor.id===o.id||(scope.override.contributor=o,$("#feature-type-container").removeClass("newtag"),$("#feature-type-container").addClass("newtag"))},scope["delete"]=function(e){scope.override.contributor=null,scope.model=null}}}}),angular.module("bulbsCmsApp").directive("createContent",function($http,$window,$,IfExistsElse,Login,ContentFactory,routes,AUTO_ADD_AUTHOR,Raven){return{restrict:"E",templateUrl:routes.DIRECTIVE_PARTIALS_URL+"create-content.html",controller:function($scope){function saveArticle(){$("button.go").removeClass("btn-danger").addClass("btn-success").html(' Going'),$http({url:"/cms/api/v1/content/?doctype="+$scope.contentType,method:"POST",data:$scope.init}).success(function(resp){var new_id=resp.id,new_path="/cms/app/edit/"+new_id+"/";$scope.rating_type&&(new_path+="?rating_type="+$scope.rating_type),$window.location.href=$window.location.origin+new_path}).error(function(data,status,headers,config){403===status?$("button.go").html(' Please Log In'):$("button.go").removeClass("btn-success").addClass("btn-danger").html(' Error'),$scope.gotSave=!1})}$scope.gotTags=!1,$scope.gotUser=!1,$scope.gotSave=!1,$scope.$watch(function(){return $scope.gotTags&&$scope.gotUser&&$scope.gotSave},function(val){val&&saveArticle($scope.init)}),$scope.newArticle=function(e){var init={title:$scope.newTitle};angular.extend($scope.init,init),$scope.tag?IfExistsElse.ifExistsElse(ContentFactory.all("tag").getList({ordering:"name",search:$scope.tag}),{slug:$scope.tag},function(tag){$scope.init.tags=[tag],$scope.gotTags=!0},function(value){console.log("couldnt find tag "+value.slug+" for initial value")},function(data,status,headers,config){Raven.captureMessage("Error Creating Article",{extra:data})}):$scope.gotTags=!0,AUTO_ADD_AUTHOR?ContentFactory.one("me").get().then(function(data){$scope.init.authors=[data],$scope.gotUser=!0}):$scope.gotUser=!0,$scope.gotSave=!0}},link:function(scope,element,attrs){scope.panel=1,$(element).find("a.create-content").on("click",function(e){$("a.create-content.active").removeClass("active"),$(this).addClass("active")}),$(element).find("a.create-content").on("click",function(e){return scope.contentTypeLabel=$(this).text(),scope.contentType=$(this).data("content_type")||null,scope.init=$(this).data("init")||{},scope.tag=$(this).data("tag")||null,scope.rating_type=$(this).data("rating_type")||null,scope.$apply(),$(this).hasClass("go-next")?(e.preventDefault(),$("#create button.next-pane").click(),!1):!0}),$("button.next-pane:not(.hide)").on("click",function(e){scope.panel=2,$(".new-title").focus()}),$(element).on("keydown",".editor",function(e){13===e.keyCode&&scope.newTitle&&$(element).find(".go").click()}),$("#create").on("hidden.bs.modal",function(){scope.newTitle="",scope.panel=1})}}}),angular.module("bulbsCmsApp").directive("datetimeSelectionModalOpener",function($modal,routes){return{restrict:"A",scope:{modDatetime:"=?ngModel",modalTitle:"@",modalOnClose:"&"},link:function(scope,element){var modalInstance=null;element.addClass("datetime-selection-modal-opener"),element.on("click",function(){modalInstance=$modal.open({templateUrl:routes.PARTIALS_URL+"modals/datetime-selection-modal.html",controller:"DatetimeSelectionModalCtrl",scope:scope}),modalInstance.result.then(function(newDate){scope.modDatetime=newDate,scope.modalOnClose({newDate:newDate})})})}}}),angular.module("bulbsCmsApp").directive("devicepreview",function($,routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"devicepreview.html",link:function(scope,element,attrs){var pP=$("#page-prev"),tN=pP.find(".nav a"),cO=pP.find(".tab-content .active");tN.click(function(e){var newId=$(this).attr("href").split("#")[1];e.preventDefault(),cO.attr("id",newId)}),$("#page-prev").on("show.bs.collapse",function(){$(this).find(".fa").removeClass("fa-plus-square-o").addClass("fa-minus-square-o")}),$("#page-prev").on("hide.bs.collapse",function(){$(this).find(".fa").removeClass("fa-minus-square-o").addClass("fa-plus-square-o")})}}}),angular.module("bulbsCmsApp").directive("onionEditor",function(routes,$,Zencoder,BettyCropper,openImageCropModal,VIDEO_EMBED_URL,OnionEditor){return{require:"ngModel",replace:!0,restrict:"E",templateUrl:routes.PARTIALS_URL+"editor.html",scope:{ngModel:"="},link:function(scope,element,attrs,ngModel){function read(){safeApply(scope,function(){var html=editor.getContent();html===defaultValue&&(html=""),ngModel.$setViewValue(html)})}if(ngModel){var formatting;attrs.formatting&&(formatting=attrs.formatting.split(","));var options={},defaultValue="";"multiline"===attrs.role?(defaultValue="


    ",options={multiline:!0,formatting:formatting||["link","bold","italic","blockquote","heading","list","strike","underline"],placeholder:{text:attrs.placeholder||"

    Write here

    ",container:$(".editorPlaceholder",element[0])[0]},link:{domain:attrs.linkDomain||!1,searchHandler:window[attrs.linkSearchHandler]||!1},statsContainer:".wordcount",inlineObjects:attrs.inlineObjects,image:{insertDialog:BettyCropper.upload,editDialog:openImageCropModal},video:{insertDialog:Zencoder.onVideoFileUpload,editDialog:Zencoder.openVideoThumbnailModal,videoEmbedUrl:VIDEO_EMBED_URL}}):($(".document-tools, .embed-tools",element).hide(),defaultValue="",options={multiline:!1,placeholder:{text:attrs.placeholder||"Write here",container:$(".editorPlaceholder",element[0])[0]},formatting:formatting||[]});var editor=new OnionEditor($(".editor",element[0])[0],options);ngModel.$render=function(){editor.setContent(ngModel.$viewValue||defaultValue),setTimeout(function(){editor.setChangeHandler(read)})},ngModel.$isEmpty=function(value){return!value||editor.scribe.allowsBlockElements()&&value===defaultValue},scope.$watch(ngModel,function(){editor.setContent(ngModel.$viewValue||defaultValue),window.picturefill&&window.picturefill(element[0])})}}}}),angular.module("bulbsCmsApp").directive("encodeStatus",function($http,$interval,$,Zencoder,routes){return{templateUrl:routes.PARTIALS_URL+"encode-status.html",restrict:"E",link:function(scope,element,attrs){function updateEncodeStatuses(){var updateEncodeStatus=function(i){return function(videoid){Zencoder.encodingVideos[videoid].encode_status_endpoints&&Zencoder.encodingVideos[videoid].encode_status_endpoints.json&&$http({method:"GET",url:Zencoder.encodingVideos[videoid].encode_status_endpoints.json,headers:{"X-CSRFToken":void 0}}).success(function(data){scope.encodingVideos[videoid].job_status=data,"finished"===data.state&&(scope.encodingVideos[videoid].finished=!0)})}(i)};for(var i in Zencoder.encodingVideos)scope.encodingVideos[i]&&scope.encodingVideos[i].finished||(scope.encodingVideos[i]=Zencoder.encodingVideos[i],updateEncodeStatus(i))}scope.encodingVideos={},scope.$watch(function(){return Zencoder.encodingVideos},function(){updateEncodeStatuses()},!0),$interval(function(){$("iframe").filter(function(){return this.src.match(/\/video\/embed\/?/)}).each(function(){var idRegex=/\/video\/embed\/?\?id=(\d+)/,id=idRegex.exec(this.src)[1];id in Zencoder.encodingVideos||Zencoder.getVideo(id).then(function(data){Zencoder.encodingVideos[id]=data.data})}),updateEncodeStatuses()},5e3)}}}),angular.module("bulbsCmsApp").directive("featuretypeField",function(routes,IfExistsElse,ContentFactory,Raven,$){return{templateUrl:routes.PARTIALS_URL+"textlike-autocomplete-field.html",restrict:"E",scope:{article:"=",hideLabel:"="},replace:!0,link:function(scope,element,attrs){scope.name="feature_type",scope.label="Feature Type",scope.placeholder="Feature Type",scope.resourceUrl="/cms/api/v1/things/?type=feature_type&q=",scope.$watch("article.feature_type",function(){scope.model=scope.article.feature_type}),scope.display=function(o){return o&&o.name||""},scope.add=function(o,input,freeForm){var fVal=freeForm?o:o.name;IfExistsElse.ifExistsElse(ContentFactory.all("things").getList({type:"feature_type",q:fVal}),{name:fVal},function(ft){scope.article.feature_type=ft.name,$("#feature-type-container").removeClass("newtag")},function(value){scope.article.feature_type=value.name,$("#feature-type-container").addClass("newtag")},function(data,status){Raven.captureMessage("Error Adding Feature Type",{extra:data})})},scope["delete"]=function(e){scope.article.feature_type=null}}}}),angular.module("bulbsCmsApp").directive("hideIfForbidden",function($http){function hideElement(element){element.addClass("hidden")}return{restrict:"A",link:function(scope,element,attrs){$http({method:"OPTIONS",url:attrs.optionsUrl,noPermissionIntercept:!0}).success(function(data,status){403===status&&hideElement(element)}).error(function(data,status){403===status&&hideElement(element)})}}}),angular.module("bulbsCmsApp").directive("lazyInclude",function(routes,$,$compile,$q,$http,$templateCache,Gettemplate){return{restrict:"A",scope:!0,link:function(scope,element,attrs){var templateUrl=routes.PARTIALS_URL+attrs.template,$element=$(element);scope.$evalAsync(function(){scope.$watch(function(){return $element.is(":visible")},function(visible){visible&&!scope.loaded&&(scope.loaded=!0,Gettemplate.get(templateUrl).then(function(html){var template=angular.element(html),compiledEl=$compile(template)(scope);element.html(compiledEl),element.css("height","auto")}))})})}}}),angular.module("bulbsCmsApp").directive("loggedInUser",function(routes,CurrentUser){return{restrict:"E",replace:!0,templateUrl:routes.PARTIALS_URL+"logged-in-user.html",scope:{},link:function(scope,element,attrs){scope.current_user=CurrentUser}}}),angular.module("bulbsCmsApp").directive("navBar",function(routes,navbar_options,CurrentUser){return{restrict:"E",scope:!1,templateUrl:function(tElement,tAttrs){return navbar_options[tAttrs.view]?routes.DIRECTIVE_PARTIALS_URL+navbar_options[tAttrs.view]+".html":routes.PARTIALS_URL+tAttrs.view+".html"},link:function(scope){scope.NAV_LOGO=routes.NAV_LOGO,scope.current_user=CurrentUser}}}),angular.module("bulbsCmsApp").directive("responsiveImage",function($window,$){return{link:function(scope,element,attrs){attrs.$observe("imageId",function(val){$(element).find("img").remove(),element.attr("data-image-id",attrs.imageId),element.attr("data-crop",attrs.crop),attrs.imageId&&$(element).is(":visible")&&($window.pictureFillElement(element[0]),element.show())})}}}),angular.module("bulbsCmsApp").directive("roleField",function($http,routes,$,Raven){return{templateUrl:routes.PARTIALS_URL+"rolefield.html",restrict:"E",replace:!0,scope:{model:"="},link:function(scope,element,attrs){var resourceUrl="/cms/api/v1/contributions/role/";scope.roleValue=null,scope.roleOptions=[],scope.$watch("model.role",function(){for(var i=0;i Save",busy:"Saving",finished:"Saved",error:"Error"})}),scope.save=function(){if(attrs.confirmClickWith){var message=attrs.confirmClickWith;if(!$window.confirm(message))return}scope.colors=scope.colors_tmp,element.prop("disabled",!0).html(" "+scope.config.busy);var save_promise=scope.getPromise(),saveSuccess=function(result){return scope.colors=scope.colors_tmp,element.prop("disabled",!1).html(" "+scope.config.finished),$timeout(function(){element.html(scope.config.idle)},1e3).then(function(){return result})};if(save_promise){var promise=save_promise.then(saveSuccess)["catch"](function(reason){return scope.colors="btn-danger",element.prop("disabled",!1).html(" "+scope.config.error),$q.reject(reason)});scope.saveCbk&&scope.saveCbk({promise:promise})}else saveSuccess()}}}}),angular.module("bulbsCmsApp").directive("sectionsField",function(routes,_,IfExistsElse,ContentFactory,Raven,$){return{templateUrl:routes.PARTIALS_URL+"taglike-autocomplete-field.html",restrict:"E",replace:!0,link:function(scope,element,attrs){scope.name="section",scope.label="Sections",scope.placeholder="Enter a section",scope.resourceUrl="/cms/api/v1/tag/?ordering=name&types=core_section&search=",scope.display=function(o){return o.name},scope.$watch("article.tags",function(){scope.objects=_.where(scope.article.tags,{type:"core_section"})},!0),scope.add=function(o,input,freeForm){var tagVal=freeForm?o:o.name;IfExistsElse.ifExistsElse(ContentFactory.all("tag").getList({ordering:"name",search:tagVal}),{name:tagVal},function(tag){scope.article.tags.push(tag)},function(){console.log("Can't create sections.")},function(data,status){Raven.captureMessage("Error Adding Section",{extra:data})}),$(input).val("")},scope["delete"]=function(e){var tag=$(e.target).parents("[data-taglikeobject]").data("taglikeobject"),name=tag.name,newtags=[];for(var i in scope.article.tags)scope.article.tags[i].name!==name&&newtags.push(scope.article.tags[i]);scope.article.tags=newtags}}}}),angular.module("bulbsCmsApp").directive("slideshowPane",function($http,$window,$compile,$,routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"slideshow-pane.html",scope:{article:"=",image:"=",index:"="},link:function(scope,element,attrs){var $element=$(element);"false"===attrs.caption&&(scope.hideCaption=!0),scope.format=attrs.format||"jpg",scope.crop=attrs.crop||"16x9",scope.removeImage=function(index){scope.article.slides.splice(index,1)},scope.editImage=function(index){$window.openImageDrawer(scope.article.slides[index].id,function(data){function removeLoadingGif(){$element.find('.image img[src="'+routes.LOADING_IMG_SRC+'"]').remove()}removeLoadingGif(),$element.find(".image").data("imageId")!==data.id&&($element.find(".image img").on("load",removeLoadingGif),$element.find(".image img").after(''),scope.article.slides[index].id=data.id.toString(),scope.$apply(),$window.picturefill(),$element.find(".image img")[0].complete&&removeLoadingGif())},function(){},function(oldImage){scope.article.slides[index]=oldImage,$window.picturefill()})}}}}),angular.module("bulbsCmsApp").directive("staticImage",function(routes,STATIC_IMAGE_URL){return{templateUrl:routes.PARTIALS_URL+"static-image.html",restrict:"E",scope:{image:"="},link:function(scope,element,attrs){var ratio=attrs.ratio||"16x9";scope.$watch("image",function(){scope.image&&scope.image.id?scope.imageUrl=STATIC_IMAGE_URL.replace("{{ratio}}",ratio).replace("{{image}}",scope.image.id):scope.imageUrl=!1})}}}),angular.module("bulbsCmsApp").directive("tagsField",function(routes,_,IfExistsElse,ContentFactory,Raven,$){return{templateUrl:routes.PARTIALS_URL+"taglike-autocomplete-field.html",restrict:"E",scope:{article:"="}, -replace:!0,link:function(scope,element,attrs){scope.name="tag",scope.label="Tags",scope.placeholder="Enter a tag",scope.resourceUrl="/cms/api/v1/tag/?ordering=name&types=content_tag&search=",scope.display=function(o){return o.name},scope.$watch("article.tags",function(){scope.objects=_.where(scope.article.tags,{type:"content_tag"})},!0),scope.add=function(o,input,freeForm){var tagVal=freeForm?o:o.name;IfExistsElse.ifExistsElse(ContentFactory.all("tag").getList({ordering:"name",search:tagVal}),{name:tagVal},function(tag){scope.article.tags.push(tag)},function(value){scope.article.tags.push({name:value.name,type:"content_tag","new":!0})},function(data,status){Raven.captureMessage("Error Adding Tag",{extra:data})}),$(input).val("")},scope["delete"]=function(e){var tag=$(e.target).parents("[data-taglikeobject]").data("taglikeobject"),name=tag.name,newtags=[];for(var i in scope.article.tags)scope.article.tags[i].name!==name&&newtags.push(scope.article.tags[i]);scope.article.tags=newtags}}}}),angular.module("bulbsCmsApp").directive("targeting",function(routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"targeting.html",link:function(scope,element,attrs){scope.addTargetingRow=function(index){scope.targetingArray.push([])},scope.removeTargetingRow=function(index){scope.targetingArray.splice(index,1)}}}}),angular.module("bulbsCmsApp").directive("videoUpload",function($http,$window,$timeout,$sce,$,routes){return{templateUrl:routes.PARTIALS_URL+"mainvideo.html",scope:{article:"="},restrict:"E",link:function(scope,element,attrs){function abortUpload(){setProgress(0),scope.req&&scope.req.abort(),scope.video={},setProgress(0)}function abortEncode(){$.ajax("https://app.zencoder.com/api/v2/jobs/"+scope.video.job_id+"/cancel.json?api_key="+$window.videoAttrs.zencoderApiKey,{type:"PUT",success:function(data){scope.video.status=3,fakeInput.val("Encoding failed! Please try again.")}})}function setProgress(progress){return 0===progress||100===progress?void progressEl.hide():void((0===scope.lastProgress||Math.abs(progress-scope.lastProgress)>2)&&(progressBar.css("width",Math.floor(progress)+"%"),scope.lastProgress=progress,progressEl.show()))}function updateEncodeProgress(){progressBar.addClass("progress-bar-success"),delete $http.defaults.headers.common["X-Requested-With"],$http({url:"https://app.zencoder.com/api/v2/jobs/"+scope.video.job_id+"/progress.json",method:"GET",params:{api_key:$window.videoAttrs.zencoderApiKey},useXDomain:!0}).success(function(data){"waiting"===data.state||"pending"===data.state||"processing"===data.state?(scope.video.status=2,data.progress>5?(setProgress(data.progress),$timeout(updateEncodeProgress,500)):$timeout(updateEncodeProgress,2e3)):(setProgress(0),"finished"===data.state&&(scope.video.status=1),("failed"===data.state||"cancelled"===data.state)&&(scope.video.status=3,fakeInput.val("Encoding failed! Please try again.")))}).error(function(data){$(".alert-danger").fadeIn().delay(1e3).fadeOut()})}console.log("video upload here"),console.log(scope.video_id),scope.$watch("article.video",function(){scope.article.video&&(scope.embedUrl=$sce.trustAsUrl("/video/embed?id="+scope.article.video),$http({method:"GET",url:"/videos/api/video/"+scope.article.video+"/"}).success(function(data){console.log("getting video from API"),console.log(data),scope.video=data,$window.initVideoWidget(data.id)}))}),scope.$watch("video",function(){});var progressEl=element.find("div.progress"),progressBar=element.find("div.progress-bar"),fakeInput=element.find("input.fake-input");scope.lastProgress=0,scope.addVideo=function(){console.log("chooseFile"),$window.uploadVideo(element.find(".video-container")[0],{onSuccess:function(videoid){scope.$apply(function(){console.log("addVideo onSuccess callback"),console.log(videoid),scope.article.video=videoid})},onError:function(data){console.log("addVideo onError callback"),console.log(data)},onProgress:function(data){console.log("addVideo onProgress callback"),console.log(data)}})},scope.clearVideo=function(areYouSure){areYouSure?($("#s3upload-file-input").val(""),scope.article.video=null):$("#confirm-clear-video-modal").modal("show")},scope.abort=function(){return scope.encoding?void abortEncode():void abortUpload()};var initialCheckRan=!1;scope.$watch("video",function(){scope.video&&scope.video.job_id&&!initialCheckRan&&(updateEncodeProgress(),initialCheckRan=!0)})}}}),angular.module("bulbsCmsApp").directive("videoEmbed",function(VIDEO_EMBED_URL){return{template:'
    ',restrict:"E",link:function(scope,element,attrs){scope.videoUrl=VIDEO_EMBED_URL+attrs.videoId}}}),angular.module("bulbsCmsApp").directive("videoField",function(Zencoder,routes){return{templateUrl:routes.PARTIALS_URL+"video-field.html",restrict:"E",scope:{article:"="},link:function(scope,element,attrs){scope.removeVideo=function(){scope.article.video=null},scope.uploadVideo=function(){Zencoder.onVideoFileUpload().then(function(success){console.log(success),scope.article.video=success.attrs.id},angular.noop,function(progress){console.log(progress),scope.uploadProgress=progress})},scope.thumbnailModal=function(){Zencoder.openVideoThumbnailModal(scope.article.video).result.then(function(resolve){console.log("thumbnail modal resolve"),console.log(resolve)},function(reject){console.log("thumbnail modal rejected")})}}}}),angular.module("bulbsCmsApp").directive("autocompleteMenu",function($timeout,$animate,$compile,routes){return{restrict:"E",replace:!0,transclude:!0,controller:angular.noop,scope:{items:"=items",pIndex:"=index",select:"&select"},link:function($scope,element,attrs){$scope.selectItem=function(index){$scope.select(index)},$scope.setIndex=function(index){$scope.index=index,attrs.index&&($scope.pIndex=parseInt(index,10))},attrs.index&&$scope.$watch("pIndex",function(value){$scope.index=parseInt(value,10)}),$scope.label=function(index){var viewValue=$scope.items[index][attrs.labelAttr];return"function"==typeof viewValue&&(viewValue=viewValue()),viewValue}},template:'
    • {{ label($index) }}
    '}}),angular.module("bulbsCmsApp").directive("autocomplete",function($timeout,$animate,$compile,routes){return{restrict:"E",replace:!0,require:"ngModel",transclude:!0,controller:function($scope,$element,$attrs,$injector){$scope.service=$injector.get($attrs.service),$scope.placeholder=$attrs.placeholder||""},link:function($scope,element,attrs,ngModel,transclude){function queryData(query){var searchParams={};searchParams[attrs.searchParam||"search"]=query,$scope.service.getList(searchParams).then(function(results){results.length>5?menuScope.items=results.slice(0,5):menuScope.items=results,timeoutId=null})}function appendMenu(){isMenuAppended||(isMenuAppended=!0,menuScope.index=0,$animate.enter(menuEl,element.parent(),element)),styleMenu()}function reset(){ngModel.$render(),menuScope.items=[],menuScope.index=0,$animate.leave(menuEl)["finally"](function(){isMenuAppended=!1})}function styleMenu(){var offset=(window.getComputedStyle(element[0]),element.offset());offset.left="auto",offset.right="auto",offset.top=element.outerHeight(),offset.minWidth=element.outerWidth(),angular.forEach(offset,function(value,key){!isNaN(value)&&angular.isNumber(value)&&(value+="px"),menuEl[0].style[key]=value,menuEl.css("z-index",1e3)})}var isMenuAppended=!1,inputEl=element.find("input"),timeoutId=null;ngModel.$render=function(){if(ngModel.$viewValue){var viewValue=ngModel.$viewValue[attrs.labelAttr];"function"==typeof viewValue&&(viewValue=viewValue()),element.find("input").val(viewValue),inputEl.attr("disabled","disabled")}},$scope.openMenu=function(e){inputEl.removeAttr("disabled"),inputEl[0].focus()},inputEl.on("blur keyup change",function(){if(void 0===inputEl.attr("disabled")){appendMenu();var value=inputEl.val();value&&(timeoutId&&$timeout.cancel(timeoutId),timeoutId=$timeout(function(){queryData(value)},150))}});var menuScope=$scope.$new();menuScope.items=[],menuScope.index=0,menuScope.select=function(index){ngModel.$setViewValue(menuScope.items[index]),reset()};var menuEl=angular.element(document.createElement("autocomplete-menu"));menuEl.attr({items:"items",select:"select(index)",index:"index","label-attr":attrs.labelAttr}),transclude(menuScope,function(clone){menuEl.append(clone)}),$compile(menuEl)(menuScope),element.find("input").on("keyup",function(e){switch(e.which){case 27:""===inputEl.val()?reset():inputEl.val("");break;case 40:$scope.$apply(function(){menuScope.index=(menuScope.index+1)%menuScope.items.length});break;case 38:$scope.$apply(function(){menuScope.index?menuScope.index=menuScope.index-1:menuScope.index=menuScope.items.length-1});break;case 13:menuScope.index>=0&&(ngModel.$setViewValue(menuScope.items[menuScope.index]),reset());break;default:return}})},templateUrl:routes.PARTIALS_URL+"autocomplete.html"}}),angular.module("bulbsCmsApp").controller("BadrequestmodalCtrl",function($scope,$modalInstance,detail){$scope.detail=detail}),angular.module("bulbsCmsApp").controller("ChangelogmodalCtrl",function($scope,$modalInstance,_,ContentFactory,article){$scope.article=article,$scope.users={},ContentFactory.all("log").getList({content:article.id}).then(function(data){$scope.changelog=data;var userIds=_.unique(_.pluck(data,"user")),resp=function(data){$scope.users[data.id]=data};for(var i in userIds)ContentFactory.one("author",userIds[i]).get().then(resp)})}),angular.module("bulbsCmsApp").controller("CmsNotificationCtrl",function($scope,moment){var valid=function(){$scope.postDateValid=$scope.postDate&&(!$scope.notifyEndDate||$scope.postDate<$scope.notifyEndDate),$scope.notifyEndDateValid=$scope.notifyEndDate&&$scope.postDate&&$scope.notifyEndDate>$scope.postDate,$scope.titleValid=$scope.notification.title&&$scope.notification.title.length>0&&$scope.notification.title.length<=110,$scope.notificationValid=$scope.postDateValid&&$scope.notifyEndDateValid&&$scope.titleValid};$scope.postDate=$scope.notification.post_date?moment($scope.notification.post_date):null,$scope.$watch("postDate",function(){$scope.postDate?($scope.notification.post_date=$scope.postDate.format(),$scope.notifyEndDate=$scope.postDate.clone().add({days:3})):$scope.notification.post_date=null}),$scope.notifyEndDate=$scope.notification.notify_end_date?moment($scope.notification.notify_end_date):null,$scope.$watch("notifyEndDate",function(){$scope.notifyEndDate?$scope.notification.notify_end_date=$scope.notifyEndDate.format():$scope.notification.notify_end_date=null}),$scope.notificationDirty=!1,$scope.$watch("notification",function(newValue,oldValue){angular.equals(newValue,oldValue)||($scope.notificationDirty=!0,valid())},!0),valid(),$scope.saveNotification=function(){$scope.$parent.userIsSuperuser&&$scope.notificationDirty&&$scope.notificationValid&&$scope.$parent.$saveNotification($scope.notification).then(function(newNotification){$scope.notification=newNotification,$scope.notificationDirty=!1})["catch"](function(error){console.log("Notification save failed",error)})},$scope.deleteNotification=function(){$scope.$parent.userIsSuperuser&&$scope.$parent.$deleteNotification($scope.notification)["catch"](function(error){console.log("Notification delete failed",error)})}}),angular.module("bulbsCmsApp").controller("CmsNotificationsCtrl",function($q,$window,$scope,routes,CmsNotificationsApi,CurrentUser,_,moment){$window.document.title=routes.CMS_NAMESPACE+" | Notifications",CurrentUser.$retrieveData().then(function(user){user.is_superuser&&($scope.userIsSuperuser=!0),CmsNotificationsApi.getList().then(function(notifications){var removeIndicies=[];_.each(notifications,function(notification,i){!user.is_superuser&&moment(notification.post_date).isAfter(moment())&&removeIndicies.push(i)}),_.each(removeIndicies,function(i){notifications.splice(i,1)}),$scope.notifications=notifications})}),$scope.newNotification=function(){var notification={post_date:null,notify_end_date:null};return $scope.notifications.unshift(notification),notification},$scope.$saveNotification=function(notification){var saveDefer=$q.defer(),savePromise=saveDefer.promise;return $scope.userIsSuperuser?"id"in notification?notification.put().then(function(updatedNotification){saveDefer.resolve(updatedNotification)}):$scope.notifications.post(notification).then(function(newNotification){var i=$scope.notifications.indexOf(notification);$scope.notifications[i]=newNotification,saveDefer.resolve(newNotification)})["catch"](function(error){saveDefer.reject(error)}):saveDefer.reject("Insufficient permissions."),savePromise},$scope.$deleteNotification=function(notification){var deleteDefer=$q.defer(),deletePromise=deleteDefer.promise,removeFromList=function(index){$scope.notifications.splice(index,1),deleteDefer.resolve()};if($scope.userIsSuperuser){var i=$scope.notifications.indexOf(notification);i>-1?_.isFunction(notification.remove)?notification.remove().then(function(){removeFromList(i)})["catch"](function(error){deleteDefer.reject(error)}):removeFromList(i):deleteDefer.reject("Cannot find notification in notification list. Unable to delete.")}else deleteDefer.reject("You do not have sufficient permissions to delete a notification.");return deletePromise}}),angular.module("bulbsCmsApp").controller("CmsNotifyContainerCtrl",function($scope,ipCookie,moment,CmsNotificationsApi,URLify,_){var genCookieKey=function(id){return"dismissed-cms-notification-"+id},updateNotificationsDisplay=function(notifications){var now=moment();$scope.notifications=_.filter(notifications,function(notification){return!ipCookie(genCookieKey(notification.id))&&moment(notification.post_date).isBefore(now)&&moment(notification.notify_end_date).isAfter(now)?!0:void 0})};CmsNotificationsApi.getList().then(function(notifications){updateNotificationsDisplay(notifications)}),$scope.dismissNotification=function(notification){var cookieKey=URLify(genCookieKey(notification.id));ipCookie(cookieKey,!0,{expires:moment(notification.notify_end_date).add({days:1}).diff(moment(),"days"),path:"/cms/app"}),updateNotificationsDisplay($scope.notifications)}}),angular.module("bulbsCmsApp").controller("ContenteditCtrl",function($scope,$routeParams,$http,$window,$location,$timeout,$interval,$compile,$q,$modal,$,_,moment,keypress,Raven,PNotify,IfExistsElse,VersionStorageApi,ContentFactory,FirebaseApi,FirebaseArticleFactory,Login,VersionBrowserModalOpener,routes){function getContent(){return ContentFactory.one("content",$routeParams.id).get().then(getArticleCallback)}function saveToContentApi(){$scope.article.put().then(saveArticleSuccessCbk)["catch"](saveArticleErrorCbk)}function saveArticleErrorCbk(data){$(navbarSave).removeClass("btn-success").addClass("btn-danger").html(" Error"),400===status&&($scope.errors=data),$scope.saveArticleDeferred.reject()}function saveArticleSuccessCbk(resp){VersionStorageApi.$create($scope.article,$scope.articleIsDirty),$(navbarSave).html(" Saved!"),setTimeout(function(){$(navbarSave).html(saveHTML)},2500),$window.article=$scope.article=resp,$scope.last_saved_article=angular.copy(resp),$scope.articleIsDirty=!1,$scope.errors=null,$location.search("rating_type",null),$scope.saveArticleDeferred.resolve(resp)}$scope.PARTIALS_URL=routes.PARTIALS_URL,$scope.CONTENT_PARTIALS_URL=routes.CONTENT_PARTIALS_URL,$scope.MEDIA_ITEM_PARTIALS_URL=routes.MEDIA_ITEM_PARTIALS_URL,$scope.page="edit",$scope.CACHEBUSTER=routes.CACHEBUSTER;var getArticleCallback=function(data){$window.article=$scope.article=data,$scope.last_saved_article=angular.copy(data),FirebaseApi.$connection.onConnect(function(){$scope.firebaseConnected=!0}).onDisconnect(function(){$scope.firebaseConnected=!1}),FirebaseArticleFactory.$retrieveCurrentArticle().then(function($article){var currentUser,savePNotify,$activeUsers=$article.$activeUsers(),$versions=$article.$versions();return $versions.$loaded(function(){$versions.$watch(function(e){if("child_added"===e.event){var newVersion=_.sortBy($versions,function(version){return-version.timestamp})[0];if(currentUser&&newVersion.user.id!==currentUser.id){savePNotify&&savePNotify.remove();var msg=""+newVersion.user.displayName+" -- "+moment(newVersion.timestamp).format("MMM Do YYYY, h:mma")+"
    ";$scope.articleIsDirty&&(msg+=" You have unsaved changes that may conflict when you save."),msg+=" Open the version browser to see their latest version.",savePNotify=new PNotify({title:"Another User Saved!",text:msg,type:"error",mouse_reset:!1,hide:!1,confirm:{confirm:!0,buttons:[{text:"Open Version Browser",addClass:"btn-primary",click:function(notice){notice.mouse_reset=!1,notice.remove(),VersionBrowserModalOpener.open($scope,$scope.article)}},{addClass:"hide"}]},buttons:{closer_hover:!1,sticker:!1}})}}})}),$activeUsers.$watch(function(){$scope.activeUsers=_.chain($activeUsers).groupBy(function(user){return user.id}).map(function(group){var groupedUser=group[0];return groupedUser.count=group.length,currentUser&&groupedUser.id===currentUser.id&&(groupedUser.displayName="You"),groupedUser}).sortBy(function(user){return"You"===user.displayName?"":user.displayName}).value()}),$article.$registerCurrentUserActive().then(function(user){currentUser=user}),$article})};getContent(),$scope.$watch("article.title",function(){$window.document.title=routes.CMS_NAMESPACE+" | Editing "+($scope.article&&$(""+$scope.article.title+"").text())}),$scope.saveArticleDeferred=$q.defer(),$scope.saveArticleIfDirty=function(){return $scope.articleIsDirty?$scope.saveArticle():$q.when($scope.article)},$scope.saveArticle=function(){return $(navbarSave).removeClass("btn-danger").addClass("btn-success").html(" Saving"),ContentFactory.one("content",$routeParams.id).get().then(function(data){data.last_modified&&$scope.article.last_modified&&moment(data.last_modified)>moment($scope.article.last_modified)?($scope.saveArticleDeferred.reject(),$modal.open({templateUrl:routes.PARTIALS_URL+"modals/last-modified-guard-modal.html",controller:"LastmodifiedguardmodalCtrl",scope:$scope,resolve:{articleOnPage:function(){return $scope.article},articleOnServer:function(){return data}}})):$scope.postValidationSaveArticle()})["catch"](saveArticleErrorCbk),$scope.saveArticleDeferred.promise};var listener=new keypress.Listener;listener.simple_combo("cmd s",function(e){$scope.saveArticle()}),listener.simple_combo("ctrl s",function(e){$scope.saveArticle()}),$scope.postValidationSaveArticle=function(){return"Published"!==$scope.article.status&&($scope.article.slug=$window.URLify($scope.article.title,50)),saveToContentApi(),$scope.saveArticleDeferred.promise};var saveHTML=" Save",navbarSave=".navbar-save";$scope.articleIsDirty=!1,$scope.$watch(function(){return!angular.equals($scope.article,$scope.last_saved_article)},function(isDirty){$scope.articleIsDirty=isDirty}),$scope.$watch("articleIsDirty",function(){$scope.articleIsDirty?$window.onbeforeunload=function(){return"You have unsaved changes. Do you want to continue?"}:$window.onbeforeunload=function(){}}),$scope.publishSuccessCbk=function(){return getContent()},$scope.trashSuccessCbk=function(){$timeout(function(){$window.history.back()},1500)}}),angular.module("bulbsCmsApp").controller("ContentlistCtrl",function($scope,$http,$timeout,$location,$window,$q,$,ContentListService,LOADING_IMG_SRC,routes){$scope.contentData=[],ContentListService.$updateContent({page:1}).then(function(data){$scope.contentData=data}),$scope.LOADING_IMG_SRC=LOADING_IMG_SRC,$window.document.title=routes.CMS_NAMESPACE+" | Content",$scope.pageNumber=$location.search().page||"1",$scope.myStuff=!1,$scope.search=$location.search().search,$scope.collapse={},$scope.goToPage=function(){ContentListService.$updateContent({page:$scope.pageNumber},!0)},$scope.publishSuccessCbk=function(data){var i;for(i=0;i<$scope.contentData.content.length&&$scope.contentData.content[i].id!==data.article.id;i++);for(var field in data.response)$scope.contentData.content[i][field]=data.response[field];return $q.when()},$scope.trashSuccessCbk=function(){$timeout(function(){ContentListService.$updateContent(),$("#confirm-trash-modal").modal("hide")},1500)},$("body").on("shown.bs.collapse",".panel-collapse",function(e){$scope.$digest()})}).directive("ngConfirmClick",[function(){return{link:function(scope,element,attr){var msg=attr.ngConfirmClick||"Are you sure?",clickAction=attr.confirmedClick;element.bind("click",function(){window.confirm(msg)&&scope.$eval(clickAction)})}}}]),angular.module("bulbsCmsApp").controller("ContentworkflowCtrl",function($scope,$http,$modal,$window,moment,routes,VersionBrowserModalOpener,TemporaryUrlModalOpener,TIMEZONE_NAME){$scope.TIMEZONE_LABEL=moment.tz(TIMEZONE_NAME).format("z"),$scope.trashContentModal=function(articleId){return $modal.open({templateUrl:routes.PARTIALS_URL+"modals/confirm-trash-modal.html",controller:"TrashcontentmodalCtrl",scope:$scope,resolve:{articleId:function(){return articleId}}})},$scope.pubTimeModal=function(article){return $modal.open({templateUrl:routes.PARTIALS_URL+"modals/publish-date-modal.html",controller:"PubtimemodalCtrl",scope:$scope,resolve:{article:function(){return article}}})},$scope.sendToEditorModal=function(article){return $modal.open({templateUrl:routes.PARTIALS_URL+"modals/send-to-editor-modal.html",controller:"SendtoeditormodalCtrl",scope:$scope,resolve:{article:function(){return article}}})},$scope.changelogModal=function(article){return $modal.open({templateUrl:routes.PARTIALS_URL+"modals/changelog-modal.html",controller:"ChangelogmodalCtrl",scope:$scope,resolve:{article:function(){return article}}})},$scope.thumbnailModal=function(article){return $modal.open({templateUrl:routes.PARTIALS_URL+"modals/thumbnail-modal.html",controller:"ThumbnailModalCtrl",scope:$scope,resolve:{article:function(){return article}}})},$scope.sponsoredContentModal=function(article){return $modal.open({templateUrl:routes.PARTIALS_URL+"modals/sponsored-content-modal.html",scope:$scope,resolve:{article:function(){return article}}})},$scope.sponsorModal=function(article){return $modal.open({templateUrl:routes.PARTIALS_URL+"modals/sponsor-modal.html",scope:$scope,controller:"SponsormodalCtrl",resolve:{article:function(){return article}}})},$scope.versionBrowserModal=function(article){VersionBrowserModalOpener.open($scope,article)},$scope.temporaryUrlModal=function(article){TemporaryUrlModalOpener.open($scope,article)},$scope.descriptionModal=function(article){return $modal.open({templateUrl:routes.PARTIALS_URL+"modals/description-modal.html",controller:"DescriptionModalCtrl",scope:$scope,size:"lg",resolve:{article:function(){return article}}})},$scope.getStatus=function(article){return article&&article.published?moment(article.published)>moment()?"scheduled":"published":"unpublished"}}),angular.module("bulbsCmsApp").controller("ContributionsCtrl",function($scope,$routeParams,$http,$window,$location,$timeout,$compile,$q,$modal,_,routes,ContributionRoleService,ContentService){function save(){angular.element("#save-btn").html(' Saving'),$scope.contributions.save($scope.contributions).then(function(contributions){angular.element("#save-btn").addClass("btn-success").removeClass("btn-danger"),angular.element("#save-btn").html(' Save'),$scope.clean=!0},function(res){angular.element("#save-btn").addClass("btn-danger").removeClass("btn-success"),angular.element("#save-btn").html(' Error')})}function add(){$scope.contributions.push({contributor:null,content:$scope.contentId,rate:{rate:0},role:null}),$scope.collapsed.push(!1)}function getRoles(){return ContributionRoleService.getList().then(function(roles){$scope.roles=roles,getContributions()})}function getContributions(){return ContentService.one($scope.contentId).all("contributions").getList().then(function(contributions){for(var i in contributions)null!==contributions[i]&&void 0!==contributions[i].role&&(contributions[i].hasOwnProperty("rate")&&"object"==typeof contributions[i].rate&&null!==contributions[i].rate&&(contributions[i].rate=contributions[i].rate.rate),"object"==typeof contributions[i].role&&(contributions[i].paymentType=contributions[i].role.payment_type,contributions[i].roleObject=contributions[i].role,contributions[i].role=contributions[i].role.id));$scope.contributions=contributions,$scope.collapsed=new Array(contributions.length),$scope.contributions.forEach(function(item,index){$scope.contributionLabels[index]=_.find($scope.roles,function(role){return role.id===item.role}).name,$scope.collapsed[index]=!0})})}function getContent(){ContentService.one($scope.contentId).get().then(function(content){$scope.content=content,$scope.article={id:content.id}})}function remove(index){$scope.contributions.splice(index,1),$scope.collapsed.splice(index,1)}function updateLabel(index){$scope.contributionLabels[index]=_.find($scope.roles,function(role){return $scope.contributions[index].roleObject=role,$scope.contributions[index].paymentType=role.payment_type,role.id===$scope.contributions[index].role}).name}$scope.NAV_LOGO=routes.NAV_LOGO,$scope.contentId=parseInt($routeParams.id,10),$scope.paymentType="",$scope.contributions=[],$scope.contributionLabels=[],$scope.roles=[],$scope.collapsed=[],$scope.page="contributions",$scope.clean=!0,$scope.save=save,$scope.add=add,$scope.remove=remove,$scope.updateLabel=updateLabel,$scope.isFlatRate=function(contribution){return contribution.hasOwnProperty("roleObject")&&"Flat Rate"===contribution.roleObject.payment_type?!0:!1},$scope.isFeatureType=function(contribution){return contribution.hasOwnProperty("roleObject")&&"FeatureType"===contribution.roleObject.payment_type?($scope.setFeatureRate(contribution),!0):!1},$scope.setFeatureRate=function(contribution){for(var i in contribution.roleObject.rates.feature_type){var featureTypeRate=contribution.roleObject.rates.feature_type[i];$scope.content.feature_type===featureTypeRate.feature_type&&(contribution.featureTypeRate=featureTypeRate.rate)}},$scope.isHourly=function(contribution){return contribution.hasOwnProperty("roleObject")&&"Hourly"===contribution.roleObject.payment_type?!0:!1},$scope.isManual=function(contribution){return contribution.hasOwnProperty("roleObject")&&"Manual"===contribution.roleObject.payment_type?!0:!1},$scope.getHourlyPay=function(contribution){return contribution.roleObject?contribution.roleObject.rate?contribution.roleObject.rate/60*(contribution.minutes_worked||0):0:void 0},$scope.$watch("contributions",function(newContributions,oldContributions){oldContributions.length>0&&($scope.clean=!1)},!0),getRoles(),getContent()}),angular.module("bulbsCmsApp").controller("DatetimeSelectionModalCtrl",function($scope,$modalInstance,TIMEZONE_NAME,moment){$scope.dateValid=!1,$scope.$watch("tempDatetime",function(){$scope.dateValid=moment($scope.tempDatetime).isValid()}),$scope.tempDatetime=angular.copy($scope.modDatetime),$scope.tempDatetime||($scope.tempDatetime=moment()),$scope.TIMEZONE_LABEL=moment.tz(TIMEZONE_NAME).format("z");var timeNowWithOffset=function(){return moment.tz(TIMEZONE_NAME)};$scope.setDate=function(newDate){$scope.tempDatetime=moment(newDate)},$scope.setDateToday=function(){var now=timeNowWithOffset();$scope.tempDatetime=moment().year(now.year()).month(now.month()).date(now.date())},$scope.setDateTomorrow=function(){var now=timeNowWithOffset();$scope.tempDatetime=moment().year(now.year()).month(now.month()).date(now.date()+1)},$scope.setTimeNow=function(){$scope.tempDatetime=timeNowWithOffset()},$scope.setTimeMidnight=function(){$scope.tempDatetime=timeNowWithOffset().hour(24).minute(0)},$scope.chooseDatetime=function(){if($scope.dateValid){var retMoment=moment($scope.tempDatetime);$modalInstance.close(retMoment)}else console.error("Attempting to choose invalid date.")}}),angular.module("bulbsCmsApp").controller("DescriptionModalCtrl",function($scope,$modalInstance,article){$scope.article=article}),angular.module("bulbsCmsApp").controller("ForbiddenmodalCtrl",function($scope,detail){$scope.detail=detail}),angular.module("bulbsCmsApp").controller("ImageCropModalCtrl",function($scope,$timeout,$modalInstance,BettyCropper,Selection,DEFAULT_IMAGE_WIDTH,imageData,ratios,$){$scope.selectedCrop=null,$scope.cropMode=!1,$scope.ratios=ratios,$scope.finished=!1,$scope.thumb_container_styles={},$scope.imageData=imageData,$scope.image||($scope.image=null,BettyCropper.get(imageData.id).then(function(success){$scope.image=success.data})),$scope.$watch("image",function(image){if(image){var finished=!0;for(var ratio in image.selections)if("auto"===image.selections[ratio].source){finished=!1;break}$scope.finished=finished,$scope.scaleData=image.scaleToFit(550,400),angular.element(".crop-image-container img").one("load",function(){$(this).Jcrop({allowSelect:!1,allowMove:!0,allowResize:!0,keySupport:!1},function(){$scope.jcrop_api=this})}),$scope.image_url=image.url("original",DEFAULT_IMAGE_WIDTH,"jpg"),$scope.ratios||($scope.ratios=Object.keys(image.selections)),$scope.setThumbStyles()}}),$scope.$watch("selectedCrop",function(crop){if($scope.image){var finished=!0;for(var ratio in $scope.image.selections)if("auto"===$scope.image.selections[ratio].source&&ratio!==crop){finished=!1;break}$scope.finished=finished}}),$scope.selectCrop=function(ratio){if(!ratio){ratio=Object.keys($scope.image.selections)[0];for(var key in $scope.image.selections)if("auto"===$scope.image.selections[key].source){ratio=key;break}}var selection=$scope.image.selections[ratio].scaleBy($scope.scaleData.scale);$scope.jcrop_api&&($scope.jcrop_api.setOptions({aspectRatio:selection.width()/selection.height()}),$scope.jcrop_api.setSelect([selection.x0,selection.y0,selection.x1,selection.y1])),$scope.cropMode=!0,$scope.selectedCrop=ratio},$scope.setThumbStyles=function(){$scope.thumb_styles=$scope.thumb_styles||{};for(var ratio in $scope.image.selections){var scaledSelection=$scope.image.selections[ratio].scaleToFit(170,170);$scope.thumb_container_styles[ratio]={"padding-top":Math.round((180-scaledSelection.height())/2)+"px","padding-bottom":"5px","padding-left":Math.round((180-scaledSelection.width())/2)+"px","padding-right":"5px"},$scope.thumb_styles[ratio]=$scope.image.getStyles(170,170,ratio)}},$scope.save=function(ratio){var jcrop_selection=$scope.jcrop_api.tellSelect(),newSelection=new Selection({x0:jcrop_selection.x,x1:jcrop_selection.x2,y0:jcrop_selection.y,y1:jcrop_selection.y2,source:"user"});return newSelection=newSelection.scaleBy(1/$scope.scaleData.scale),newSelection.x1>$scope.image.width&&(newSelection.x1=$scope.image.width),newSelection.y1>$scope.image.height&&(newSelection.y1=$scope.image.height),this.image.updateSelection(ratio,newSelection)},$scope.saveAndQuit=function(){var ratio=$scope.selectedCrop;this.save(ratio).then(function(success){var ratio=success.data[0],selection=success.data[1];$scope.image.selections[ratio]=selection}),$scope.cropMode=!1,$modalInstance.close(imageData)},$scope.saveAndNext=function(){var ratio=$scope.selectedCrop;this.save(ratio).then(function(success){var ratio=success.data[0],selection=success.data[1];$scope.image.selections[ratio]=selection;var nextRatioIndex=($scope.ratios.indexOf(ratio)+1)%$scope.ratios.length;$scope.selectCrop($scope.ratios[nextRatioIndex])})}}),angular.module("bulbsCmsApp").controller("LastmodifiedguardmodalCtrl",function($scope,$modalInstance,_,moment,ContentFactory,articleOnPage,articleOnServer){$scope.articleOnServer=articleOnServer,ContentFactory.all("log").getList({content:articleOnPage.id}).then(function(log){var latest=_.max(log,function(entry){return moment(entry.action_time)}),lastSavedById=latest.user;ContentFactory.one("author",lastSavedById).get().then(function(data){ -$scope.lastSavedBy=data})}),$scope.loadFromServer=function(){_.each($scope.articleOnServer,function(value,key){$scope.article[key]=value}),$scope.articleIsDirty=!0,$modalInstance.close()},$scope.saveAnyway=function(){$modalInstance.close(),$scope.$parent.postValidationSaveArticle()}}),angular.module("bulbsCmsApp").controller("LoginmodalCtrl",function($scope,Login,$modalInstance,$){$scope.login=function(){var username=$("input[name='username']").val(),password=$("input[name='password']").val();Login.login(username,password).then(function(){$modalInstance.close()},function(){$modalInstance.dismiss()})}}),angular.module("bulbsCmsApp").controller("PubtimemodalCtrl",function($scope,$http,$modal,$modalInstance,$,moment,Login,routes,article,TIMEZONE_NAME,Raven){$scope.article=article,$scope.pubButton={idle:"Publish",busy:"Publishing",finished:"Published!",error:"Error!"},$scope.$watch("pickerValue",function(newVal){var pubTimeMoment=moment(newVal);$scope.datePickerValue=moment().year(pubTimeMoment.year()).month(pubTimeMoment.month()).date(pubTimeMoment.date()),$scope.timePickerValue=moment().hour(pubTimeMoment.hour()).minute(pubTimeMoment.minute())});var modelDateFormat="YYYY-MM-DDTHH:mmZ";$scope.setTimeShortcut=function(shortcut){if("now"===shortcut){var now=moment();$scope.pickerValue=now}if("midnight"===shortcut){var midnight=moment().hour(24).minute(0);$scope.pickerValue=midnight}},$scope.setDateShortcut=function(shortcut){var today=moment.tz(TIMEZONE_NAME);"today"===shortcut&&($scope.datePickerValue=moment().year(today.year()).month(today.month()).date(today.date())),"tomorrow"===shortcut&&($scope.datePickerValue=moment().year(today.year()).month(today.month()).date(today.date()+1))},$scope.setPubTime=function(){if(!$scope.article.feature_type)return $modalInstance.dismiss(),void $modal.open({templateUrl:routes.PARTIALS_URL+"modals/pubtime-validation-modal.html"});var newDate=moment($scope.datePickerValue),newTime=moment($scope.timePickerValue),newDateTime=moment.tz(TIMEZONE_NAME).year(newDate.year()).month(newDate.month()).date(newDate.date()).hour(newTime.hour()).minute(newTime.minute()).format(modelDateFormat),data={published:newDateTime};return $http({url:"/cms/api/v1/content/"+$scope.article.id+"/publish/",method:"POST",data:data})},$scope.setPubTimeCbk=function(publish_promise){publish_promise.then(function(result){$scope.article.published=result.data.published,$scope.publishSuccessCbk&&$scope.publishSuccessCbk({article:$scope.article,response:result.data}),$modalInstance.close()})["catch"](function(reason){Raven.captureMessage("Error Setting Pubtime",{extra:reason.data}),$modalInstance.dismiss()})},$scope.unpubButton={idle:"Unpublish",busy:"Unpublishing",finished:"Unpublished!",error:"Error"},$scope.unpublish=function(){return $http({url:"/cms/api/v1/content/"+$scope.article.id+"/publish/",method:"POST",data:{published:!1}})},$scope.unpublishCbk=function(unpub_promise){unpub_promise.then(function(result){$scope.publishSuccessCbk&&$scope.publishSuccessCbk({article:$scope.article,response:result.data}),$modalInstance.close()})["catch"](function(reason){$scope.publishSuccessCbk&&$scope.publishSuccessCbk({article:$scope.article,response:reason.data}),$modalInstance.dismiss()})},$scope.article.published?$scope.pickerValue=moment.tz($scope.article.published,TIMEZONE_NAME):$scope.setTimeShortcut("now")}),angular.module("bulbsCmsApp").controller("ReportingCtrl",function($http,$scope,$window,$,$location,$filter,$interpolate,Login,routes,moment,ContributionReportingService,ContentReportingService,FreelancePayReportingService){function loadReport(report,start,end,order,apiUrl){if($scope.items=[],"undefined"==typeof apiUrl?$scope.apiURL=report.downloadURL:$scope.apiURL=apiUrl,$scope.apiURL+="?page="+$scope.reportParams.pageNumber,$scope.downloadURL=report.downloadURL+"?format=csv",end){var endParam=$filter("date")(end,"yyyy-MM-dd");$scope.reportParams.end=endParam,$scope.apiURL+="&end="+endParam,$scope.downloadURL+="&end="+endParam}if(start){var startParam=$filter("date")(start,"yyyy-MM-dd");$scope.reportParams.start=startParam,$scope.apiURL+="&start="+startParam,$scope.downloadURL+="&start="+startParam}if(order&&($scope.apiURL+="&ordering="+order.key),$scope.publishedFilter&&($scope.apiURL+="&published="+$scope.publishedFilter,$scope.downloadURL+="&published="+$scope.publishedFilter,$scope.reportParams.published=$scope.publishedFilter),$scope.userFilter&&($scope.apiURL+="&staff="+$scope.userFilter,$scope.downloadURL+="&staff="+$scope.userFilter,$scope.reportParams.staff=$scope.userFilter),$scope.moreFilters)for(var key in $scope.moreFilters)"authors"===$scope.moreFilters[key].type?($scope.apiURL+="&contributors="+$scope.moreFilters[key].query,$scope.downloadURL+="&contributors="+$scope.moreFilters[key].query,$scope.reportParams.contributors=$scope.moreFilters[key].query):($scope.apiURL+="&"+$scope.moreFilters[key].type+"="+$scope.moreFilters[key].query,$scope.downloadURL+="&"+$scope.moreFilters[key].type+"="+$scope.moreFilters[key].query,$scope.reportParams[$scope.moreFilters[key].type]=$scope.moreFilters[key].query);$http({method:"GET",url:$scope.apiURL}).then(function(data){$scope.items=[],$scope.pageTotal=data.data.count,data.data.results.forEach(function(lineItem){var item=[];report.headings.forEach(function(heading){var exp=$interpolate("{{item."+heading.expression+"}}"),value=exp({item:lineItem});item.push(value)}),$scope.items.push(item)})})}$window.document.title=routes.CMS_NAMESPACE+" | Reporting",$scope.userFilter="",$scope.userFilters=[{name:"All",value:""},{name:"Staff",value:"staff"},{name:"Freelance",value:"freelance"}],$scope.publishedFilter="",$scope.publishedFilters=[{name:"All Content",value:""},{name:"Published",value:"published"}],$scope.reports={Contributions:{service:ContributionReportingService,headings:[{title:"Content ID",expression:"content.id"},{title:"Headline",expression:"content.title"},{title:"FeatureType",expression:"content.feature_type"},{title:"Contributor",expression:"user.payroll_name"},{title:"Role",expression:"role"},{title:"Pay",expression:"pay"},{title:"Date",expression:"content.published | date: 'MM/dd/yyyy'"}],downloadURL:"/cms/api/v1/contributions/reporting/",orderOptions:[{label:"Order by User",key:"user"},{label:"Order by Content",key:"content"}]},Content:{service:ContentReportingService,headings:[{title:"Content ID",expression:"id"},{title:"Headline",expression:"title"},{title:"Feature Type",expression:"feature_type"},{title:"Video",expression:"video_id"},{title:"Article Cost",expression:"value"},{title:"Date Published",expression:"published | date: 'MM/dd/yyyy'"}],orderOptions:[],downloadURL:"/cms/api/v1/contributions/contentreporting/"},"Freelance Pay":{service:FreelancePayReportingService,headings:[{title:"Contributor",expression:"contributor.full_name"},{title:"Contribution #",expression:"contributions_count"},{title:"Pay",expression:"pay"},{title:"Payment Date",expression:"payment_date | date: 'MM/dd/yyyy'"}],orderOptions:[],downloadURL:"/cms/api/v1/contributions/freelancereporting/"}},$scope.items=[],$scope.headings=[],$scope.orderOptions=[],$scope.startInitial=moment().startOf("month").format("YYYY-MM-DD"),$scope.endInitial=moment().endOf("month").format("YYYY-MM-DD"),$scope.reportParams={pageNumber:1,start:$scope.startInitial,end:$scope.endInitial},$scope.reportDisabled=!0,$scope.pageTotal=null,$scope.moreFilters=[],$scope.startOpen=!1,$scope.endOpen=!1,$scope.setReport=function($reportingService){$scope.reportDisabled===!0&&($scope.reportDisabled=!1),$scope.reportParams.pageNumber=1,$scope.report=$reportingService},$scope.setUserFilter=function(value){$scope.userFilter=value,loadReport($scope.report,$scope.reportParams.start,$scope.reportParams.end,$scope.orderBy)},$scope.setPublishedFilter=function(value){$scope.publishedFilter=value,"published"===value&&($scope.reportParams.end=moment().format("YYYY-MM-DD")),loadReport($scope.report,$scope.reportParams.start,$scope.reportParams.end,$scope.orderBy)},$scope.openStart=function($event){$event.preventDefault(),$event.stopPropagation(),$scope.startOpen=!0},$scope.openEnd=function($event){$event.preventDefault(),$event.stopPropagation(),$scope.endOpen=!0},$scope.orderingChange=function(){loadReport($scope.report,$scope.reportParams.start,$scope.reportParams.end,$scope.orderBy)},$scope.downloadIsValid=function(){return"undefined"!==$scope.report?!0:!1},$scope.$watch("report",function(report){report&&($scope.orderOptions=report.orderOptions,report.orderOptions.length>0?$scope.orderBy=report.orderOptions[0]:$scope.orderBy=null,$scope.headings=[],report.headings.forEach(function(heading){$scope.headings.push(heading.title)}),loadReport(report,$scope.reportParams.start,$scope.reportParams.end,$scope.orderBy))}),$scope.$watchCollection("[reportParams.start, reportParams.end]",function(params){if($scope.report){var start=params[0],end=params[1];loadReport($scope.report,start,end,$scope.orderBy)}}),$scope.goToPage=function(){loadReport($scope.report,$scope.reportParams.start,$scope.reportParams.end)}}),angular.module("bulbsCmsApp").controller("SponsormodalCtrl",function($scope,ContentFactory,article,Campaign){$scope.article=article,$scope.article.campaign?$scope.campaign=Campaign.$find($scope.article.campaign):$scope.campaign=null,$scope.updateArticle=function(selection){$scope.article.campaign=selection.value.id},$scope.searchCampaigns=function(searchTerm){return Campaign.simpleSearch(searchTerm)}}),angular.module("bulbsCmsApp").controller("TargetingCtrl",function($scope,$http,$window,$q,$location,tar_options,routes){$window.document.title=routes.CMS_NAMESPACE+" | Targeting Editor";var canceller;$scope.search=function(url){url&&("undefined"==typeof canceller?canceller=$q.defer():(canceller.resolve(),canceller=$q.defer()),$http({method:"GET",url:tar_options.endpoint,timeout:canceller.promise,params:{url:$scope.url}}).success(function(data){$scope.targetingArray=[];for(var k in data)$scope.targetingArray.push([k,data[k]])}).error(function(data,status,headers,config){404===status&&($scope.targetingArray=[],$scope.targetingArray.push(["",""]))}))},$scope.save=function(){var data={};for(var i in $scope.targetingArray)data[$scope.targetingArray[i][0]]=$scope.targetingArray[i][1];return $http({method:"POST",url:tar_options.endpoint+"?url="+$scope.url,data:data}).success(function(data){$scope.targetingArray=[];for(var k in data)$scope.targetingArray.push([k,data[k]])})},$scope.keyHandler=function(event,url){13===event.keyCode?this.search(url):27===event.keyCode&&(event.currentTarget.value="")};var search=$location.search();search&&search.url&&($scope.url=decodeURIComponent(search.url))}),angular.module("bulbsCmsApp").value("ARTICLE_TEMPORARY_URL_DAYS_VALID",7).value("ARTICLE_TEMPORARY_URL_BASE","http://0.0.0.0:9069/unpublished/").controller("TemporaryUrlModalCtrl",function($scope,$routeParams,ContentFactory,ARTICLE_TEMPORARY_URL_DAYS_VALID,ARTICLE_TEMPORARY_URL_BASE,_,moment){var content=ContentFactory.one("content",$routeParams.id);$scope.TEMP_LINK_DAYS_VALID=ARTICLE_TEMPORARY_URL_DAYS_VALID,$scope.TEMP_URL_BASE=ARTICLE_TEMPORARY_URL_BASE,$scope.tokens=[],content.getList("list_tokens").then(function(tokenList){$scope.tokens=tokenList;var expiredIndicies=[];_.each($scope.tokens,function(token,i){token.create_date=moment(token.create_date),token.expire_date=moment(token.expire_date),moment().isAfter(token.expire_date)?expiredIndicies.push(i):token.daysTillExpire=token.expire_date.diff(moment(),"days")+1});for(var i=expiredIndicies.length-1;i>=0;i--)$scope.tokens.splice(expiredIndicies[i],1)}),$scope.createToken=function(){var now=moment();ContentFactory.one("content",$routeParams.id).post("create_token",{create_date:now,expire_date:now.clone().add({days:ARTICLE_TEMPORARY_URL_DAYS_VALID})}).then(function(token){token.create_date=moment(token.create_date),token.expire_date=moment(token.expire_date),token.daysTillExpire=token.expire_date.diff(moment(),"days")+1,$scope.tokens.push(token),$scope.newestToken=token})}}),angular.module("bulbsCmsApp").controller("ThumbnailModalCtrl",function($scope,BettyCropper,$modalInstance,article){$scope.article=article,$scope.selectCustomThumbnail=function(){BettyCropper.upload().then(function(success){$scope.article.thumbnail_override=success},function(error){console.log(error)},function(progress){console.log(progress)})}}),angular.module("bulbsCmsApp").controller("TrashcontentmodalCtrl",function($scope,$http,$modalInstance,$,Login,articleId,Raven){$scope.deleteButton={idle:"Delete",busy:"Trashing",finished:"Trashed",error:"Error!"},$scope.trashContent=function(){return $http({method:"POST",url:"/cms/api/v1/content/"+articleId+"/trash/"})},$scope.trashCbk=function(trash_promise){trash_promise.then(function(result){console.log("trash success"),$scope.trashSuccessCbk(),$modalInstance.close()})["catch"](function(reason){return 404===reason.status?($scope.trashSuccessCbk(),void $modalInstance.close()):(Raven.captureMessage("Error Deleting Article",{extra:reason}),void $modalInstance.dismiss())})}}),angular.module("bulbsCmsApp").controller("UnpublishCtrl",function($scope,$http,$q){$scope.unpubButton={idle:"Unpublish",busy:"Unpublishing",finished:"Unpublished!",error:"Error"},$scope.unpublish=function(){return $http({url:"/cms/api/v1/content/"+$scope.article.id+"/publish/",method:"POST",data:{published:!1}})},$scope.unpublishCbk=function(unpub_promise){unpub_promise.then(function(result){$scope.publishSuccessCbk&&$scope.publishSuccessCbk({article:$scope.article,response:result.data})})["catch"](function(reason){$scope.publishSuccessCbk&&$scope.publishSuccessCbk({article:$scope.article,response:reason.data})})}}),angular.module("bulbsCmsApp").controller("VersionBrowserModalCtrl",function($scope,$modalInstance,_,moment,VersionStorageApi,FirebaseApi,FIREBASE_ARTICLE_MAX_VERSIONS){FirebaseApi.$authorize().then(function(){$scope.maxVersions=FIREBASE_ARTICLE_MAX_VERSIONS}),VersionStorageApi.$all().then(function(versions){$scope.versions=_.chain(versions).each(function(version){version.timestamp_display=moment(version.timestamp).format("MMM Do YYYY, h:mma")}).sortBy(function(version){return-version.timestamp}).value(),$scope.selectedVersion=$scope.versions[0],$scope.setPreview=function(version){$scope.selectedVersion=version},$scope.restoreSelected=function(){_.each($scope.selectedVersion.content,function(value,key){$scope.article[key]=value}),$scope.articleIsDirty=!0,$modalInstance.close()}})}),angular.module("bulbsCmsApp").controller("VideothumbnailmodalCtrl",function($scope,$http,$modalInstance,Zencoder,videoId,VIDEO_THUMBNAIL_URL,CUSTOM_VIDEO_POSTER_URL){function compilePosterUrl(thumbnail){return VIDEO_THUMBNAIL_URL.replace("{{video}}",videoId).replace("{{thumbnail}}",pad4(thumbnail))}function pad4(num){var s="0000"+num;return s.substr(s.length-4)}var DEFAULT_THUMBNAIL=4,MAX_THUMBNAIL=19;$scope.uploadedImage={id:null},$scope.mode="still",Zencoder.getVideo(videoId).then(function(response){$scope.video=response.data,"In Progress"===response.data.status?($scope.inProgress=!0,$scope.video.poster=$scope.video.poster||null):$scope.video.poster=$scope.video.poster||compilePosterUrl(DEFAULT_THUMBNAIL)}),$scope.$watch("video.poster",function(){if($scope.video&&$scope.video.poster){var defaultUrl=VIDEO_THUMBNAIL_URL.replace("{{video}}",videoId),thumbnailIndex=defaultUrl.indexOf("{{thumbnail}}");0===$scope.video.poster.indexOf(defaultUrl.substr(0,thumbnailIndex))?($scope.currentThumbnail=Number($scope.video.poster.substr(thumbnailIndex,4)),$scope.uploadedImage.id=null):$scope.currentThumbnail=!1}}),$scope.$watch("uploadedImage.id",function(){$scope.uploadedImage.id&&($scope.video.poster=CUSTOM_VIDEO_POSTER_URL.replace("{{ratio}}","16x9").replace("{{image}}",$scope.uploadedImage.id))}),$scope.nextThumb=function(){$scope.video.poster=compilePosterUrl($scope.currentThumbnail0?$scope.currentThumbnail-1:MAX_THUMBNAIL)},$scope.defaultThumb=function(){$scope.video.poster=compilePosterUrl(DEFAULT_THUMBNAIL)},$scope.setPoster=function(){Zencoder.setVideo($scope.video),$modalInstance.close($scope.video.poster)},$scope.reencode=function(){Zencoder.encode(videoId)}}),angular.module("bulbsCmsApp").factory("AdApi",function(Restangular,adApiConfig){return Restangular.withConfig(function(RestangularConfigurer){RestangularConfigurer.setBaseUrl(adApiConfig.baseUrl)})}).constant("adApiConfig",{baseUrl:"/ads"}),angular.module("bulbsCmsApp").factory("BadRequestInterceptor",function($q,$injector,routes){return{responseError:function(rejection){return $injector.invoke(function($modal){if(400===rejection.status){var detail=rejection.data||{something:["Something was wrong with your request."]};$modal.open({templateUrl:routes.PARTIALS_URL+"modals/400-modal.html",controller:"BadrequestmodalCtrl",resolve:{detail:function(){return detail}}})}}),$q.reject(rejection)}}}),angular.module("bulbsCmsApp").factory("BugReportInterceptor",function($q,$window,PNotify){return{responseError:function(rejection){if(rejection.status>=500){var stack={animation:!0,dir1:"up",dir2:"left"};new PNotify({title:"You found a bug!",text:"Looks like something just went wrong, and we need your help to fix it! Report it, and we'll make sure it never happens again.",type:"error",confirm:{confirm:!0,align:"left",buttons:[{text:"Report Bug",addClass:"btn-danger pnotify-report-bug",click:function(notice){notice.remove(),$window.showBugReportModal()}},{addClass:"hidden"}]},buttons:{sticker:!1},icon:"fa fa-bug pnotify-error-icon",addclass:"stack-bottomright",stack:stack})}return $q.reject(rejection)}}}),angular.module("bulbsCmsApp").config(function(RestangularProvider,bulbsApiConfig){RestangularProvider.setResponseExtractor(function(response,operation,what,url){var newResponse=response;return"getList"===operation&&"undefined"!=typeof response.results&&(newResponse=response.results,newResponse.metadata={count:response.count,next:response.next,previous:response.previous}),newResponse}),bulbsApiConfig.requestSuffix&&RestangularProvider.setRequestSuffix(bulbsApiConfig.requestSuffix)}).constant("bulbsApiConfig",{requestSuffix:"/"}),angular.module("bulbsCmsApp").factory("CmsNotificationsApi",function($q,ContentFactory){return ContentFactory.service("notifications")}),angular.module("bulbsCmsApp").service("CurrentUser",function(ContentFactory,$q){var userDefer=$q.defer(),$userPromise=userDefer.promise;this.data=[];var self=this;this.getItems=function(){ContentFactory.one("me").get().then(function(data){self.data=data,userDefer.resolve(data)})},this.getItems(),this.$retrieveData=function(){return $userPromise},this.$simplified=function(){return $userPromise.then(function(user){var displayName=user.first_name&&user.last_name?user.first_name+" "+user.last_name:user.email||user.username;return{id:user.id,displayName:displayName}})}}),angular.module("bulbsCmsApp").value("FIREBASE_URL","https://luminous-fire-8340.firebaseio.com/").value("FIREBASE_ROOT","a-site-is-not-configured").factory("FirebaseApi",function(FirebaseRefFactory,$firebase,$rootScope,$q,CurrentUser,FIREBASE_URL,FIREBASE_ROOT){var rootRef=FirebaseRefFactory.newRef(FIREBASE_URL+"sites/"+FIREBASE_ROOT),authDefer=$q.defer(),$authorize=authDefer.promise;$authorize["catch"](function(error){error&&console.error("Firebase login failed:",error)}),CurrentUser.$retrieveData().then(function(user){"firebase_token"in user&&user.firebase_token?rootRef.auth(user.firebase_token,function(error){error?authDefer.reject(error):authDefer.resolve(rootRef)}):authDefer.reject()});var connectedRef=FirebaseRefFactory.newRef(FIREBASE_URL+".info/connected");connectedRef.on("value",function(connected){connected.val()?$rootScope.$emit("firebase-reconnected"):$rootScope.$emit("firebase-disconnected"),$rootScope.$emit("firebase-connection-state-changed")});var $connection={onConnect:function(callback){return $rootScope.$on("firebase-reconnected",callback),$connection},onDisconnect:function(callback){return $rootScope.$on("firebase-disconnected",callback),$connection},onChange:function(callback){$rootScope.$on("firebase-connection-state-changed",callback)}};return{$authorize:function(){return $authorize},$connection:$connection}}),angular.module("bulbsCmsApp").value("FIREBASE_ARTICLE_MAX_VERSIONS",25).factory("FirebaseArticleFactory",function($q,$firebase,$routeParams,_,moment,FirebaseApi,CurrentUser,FIREBASE_ARTICLE_MAX_VERSIONS){var createArticle=function(rootRef,articleId){var articleRef=rootRef.child("articles/"+articleId),$activeUsers=$firebase(articleRef.child("users")).$asArray(),$versions=$firebase(articleRef.child("versions")).$asArray(),addCurrentUserToActiveUsers=function(){var registeredDeferred=$q.defer(),registeredPromise=registeredDeferred.promise;return CurrentUser.$simplified().then(function(user){$activeUsers.$add(user).then(function(userRef){userRef.onDisconnect().remove(),registeredDeferred.resolve(user)})["catch"](function(error){registeredDeferred.reject(error)})})["catch"](function(error){registeredDeferred.reject(error)}),registeredPromise},registerCurrentUserActive=function(){return FirebaseApi.$connection.onConnect(addCurrentUserToActiveUsers),addCurrentUserToActiveUsers()};return{ref:articleRef,$activeUsers:function(){return $activeUsers},$versions:function(){return $versions},$registerCurrentUserActive:registerCurrentUserActive,$createVersion:function(articleData){var createDefer=$q.defer(),$createPromise=createDefer.promise;return CurrentUser.$simplified().then(function(user){var numVersions=$versions.length;numVersions+1>FIREBASE_ARTICLE_MAX_VERSIONS&&_.chain($versions).sortBy(function(version){return version.timestamp}).every(function(version){return $versions.$remove(version),numVersions--,numVersions+1>FIREBASE_ARTICLE_MAX_VERSIONS});var versionData={timestamp:moment().valueOf(),user:user,content:articleData};$versions.$add(versionData).then(createDefer.resolve)["catch"](createDefer.reject)}),$createPromise}}};return{$retrieveArticle:function(articleId){var retrieveDeferred=$q.defer(),retrievePromise=retrieveDeferred.promise;return FirebaseApi.$authorize().then(function(rootRef){retrieveDeferred.resolve(createArticle(rootRef,articleId))})["catch"](function(error){retrieveDeferred.reject(error)}),retrievePromise},$retrieveCurrentArticle:function(){return this.$retrieveArticle($routeParams.id)}}}),angular.module("bulbsCmsApp").service("FirebaseRefFactory",function(Firebase){return{newRef:function(url){return new Firebase(url)}}}),angular.module("bulbsCmsApp").service("Gettemplate",function($templateCache,$q,$http){this.get=function(templateUrl){var template=$templateCache.get(templateUrl);if(template)return $q.when(template);var deferred=$q.defer();return $http.get(templateUrl,{cache:!0}).success(function(html){$templateCache.put(templateUrl,html),deferred.resolve(html)}),deferred.promise}}),angular.module("bulbsCmsApp").service("IfExistsElse",function($window,$http){this.ifExistsElse=function(restQ,propertiesToValues,existsCbk,elseCbk,errorCbk){restQ.then(function(data){for(var resList=data.results||data,j=0;jkeyTime}return pickForRemoval}).each(function(value,key){$window.localStorage.removeItem(key)});try{$window.localStorage.setItem(version.timestamp,JSON.stringify(version.content)),createDefer.resolve(version)}catch(error){console.log("Maybe you've been saving too much? Failed again at adding entry, no more retries: "+error),createDefer.reject("Maybe you've been saving too much? Failed again at adding entry, no more retries: "+error)}}}):createDefer.reject("You don't have local storage capabilities in your browser. Use a better browser."),createPromise},$versions:function(){var retrieveDefer=$q.defer(),retrievePromise=retrieveDefer.promise,versions=_.chain($window.localStorage).pick(function(stored,key){var keySplit=key.split(".");return 3===keySplit.length&&keySplit[0]===keyPrefixArticle&&keySplit[1]===$routeParams.id}).map(function(stored){return JSON.parse(stored)}).value();return retrieveDefer.resolve(versions),retrievePromise}}}),angular.module("bulbsCmsApp").service("Login",function($rootScope,$http,$cookies,$window,$,routes){return $rootScope.$watch(function(){return $cookies.csrftoken},function(newCsrf,oldCsrf){$http.defaults.headers.common["X-CSRFToken"]=newCsrf,$window.jqueryCsrfSetup&&$window.jqueryCsrfSetup()}),{login:function(username,password){var data=$.param({username:username,password:password});return $http({method:"POST",url:"/login/",data:data,headers:{"Content-Type":"application/x-www-form-urlencoded"}})}}}),angular.module("bulbsCmsApp").factory("openImageCropModal",function($modal,routes){var openImageCropModal=function(imageData,ratios){return $modal.open({templateUrl:routes.PARTIALS_URL+"image-crop-modal.html",controller:"ImageCropModalCtrl",resolve:{imageData:function(){return imageData},ratios:function(){return ratios||!1}},backdrop:"static"}).result};return openImageCropModal}),angular.module("bulbsCmsApp").factory("PermissionsInterceptor",function($q,$injector,routes){return{responseError:function(rejection){return rejection.config&&rejection.config.noPermissionIntercept?$q.when(rejection):($injector.invoke(function($modal){if(403===rejection.status)if(rejection.data&&rejection.data.detail&&rejection.data.detail.indexOf("credentials")>0)$modal.open({templateUrl:routes.PARTIALS_URL+"modals/login-modal.html",controller:"LoginmodalCtrl"});else{var detail=rejection.data&&rejection.data.detail||"Forbidden";$modal.open({templateUrl:routes.PARTIALS_URL+"modals/403-modal.html",controller:"ForbiddenmodalCtrl",resolve:{detail:function(){return detail}}})}}),$q.reject(rejection))}}}),angular.module("bulbsCmsApp").factory("TemporaryUrlModalOpener",function($modal,routes){var modal=null;return{open:function($scope,article){return modal&&modal.close(),modal=$modal.open({templateUrl:routes.PARTIALS_URL+"modals/temporary-url-modal.html",controller:"TemporaryUrlModalCtrl",scope:$scope,resolve:{article:function(){return article}}})}}}),angular.module("bulbsCmsApp").factory("VersionStorageApi",function($q,FirebaseApi,FirebaseArticleFactory,LocalStorageBackup,_){var firebaseAvailableDefer=$q.defer(),$firebaseAvailable=firebaseAvailableDefer.promise;FirebaseApi.$authorize().then(function(){firebaseAvailableDefer.resolve(FirebaseArticleFactory.$retrieveCurrentArticle())})["catch"](function(){firebaseAvailableDefer.reject()});var _omitter=_.memoize(function(value,key){return _.isFunction(value)||_.find(key,function(c){return"."===c||"#"===c||"$"===c||"/"===c||"["===c||"]"===c})},function(value,key){return[key,value]}),_deepScrub=function(obj){var clone,transValue;return _.isUndefined(obj)?clone=null:_.isPlainObject(obj)?(clone={},_.forOwn(obj,function(value,key){transValue=_deepScrub(value),_omitter(transValue,key)||(clone[key]=transValue)})):_.isArray(obj)?(clone=[],_.each(obj,function(value,key){transValue=_deepScrub(value),_omitter(transValue,key)||clone.push(transValue)})):clone=obj,clone},scrubArticle=function(articleData){return _deepScrub(articleData)};return{$create:function(rawArticleData,articleIsDirty){var articleData=scrubArticle(rawArticleData),createDefer=$q.defer(),createPromise=createDefer.promise;return $firebaseAvailable.then(function($currentArticle){articleIsDirty||$currentArticle.$versions().length<1?$currentArticle.$createVersion(articleData).then(function(versionData){createDefer.resolve(versionData)})["catch"](function(){createDefer.reject()}):createDefer.reject()})["catch"](function(){LocalStorageBackup.$versions().then(function(versions){articleIsDirty||versions.length<1?LocalStorageBackup.$create(articleData).then(function(versionData){createDefer.resolve(versionData)})["catch"](function(error){createDefer.reject(error)}):createDefer.reject()})}),createPromise},$all:function(){var allDefer=$q.defer(),allPromise=allDefer.promise;return $firebaseAvailable.then(function($currentArticle){$currentArticle.$versions().$loaded(function(versions){allDefer.resolve(versions)})})["catch"](function(){LocalStorageBackup.$versions().then(function(versions){allDefer.resolve(versions)})["catch"](function(error){allDefer.reject(error)})}),allPromise.then(function(versions){return _.sortBy(versions,function(version){return-version.timestamp})})}}}),angular.module("bulbsCmsApp").factory("VersionBrowserModalOpener",function($modal,routes){var modal=null;return{open:function($scope,article){return modal&&modal.close(),modal=$modal.open({templateUrl:routes.PARTIALS_URL+"modals/version-browser-modal.html",controller:"VersionBrowserModalCtrl",scope:$scope,size:"lg",resolve:{article:function(){return article}}})}}}),angular.module("bulbsCmsApp").service("Zencoder",function($http,$q,$modal,$,routes){function getNewVideoUploadCredentials(file){var data={name:file.name};data=$.param(data);var newVideoDeferred=$q.defer();return $http({method:"POST",url:newVideoUrl,data:data,headers:{"Content-Type":"application/x-www-form-urlencoded"}}).success(function(data){newVideoDeferred.resolve({file:file,attrs:data})}).error(function(data){newVideoDeferred.reject(data)}),newVideoDeferred.promise}function uploadToS3(videoObject){var s3deferred=$q.defer(),formData=new FormData;return formData.append("key",videoObject.attrs.key),formData.append("AWSAccessKeyId",videoObject.attrs.AWSAccessKeyId),formData.append("acl",videoObject.attrs.acl),formData.append("success_action_status",videoObject.attrs.success_action_status),formData.append("policy",videoObject.attrs.policy),formData.append("signature",videoObject.attrs.signature),formData.append("file",videoObject.file),$.ajax(videoObject.attrs.upload_endpoint,{processData:!1,contentType:!1,data:formData,type:"POST",xhr:function(){var req=$.ajaxSettings.xhr();return req&&req.upload.addEventListener("progress",function(e){var percent=e.loaded/e.total*100;s3deferred.notify(percent)},!1),req},success:function(data){s3deferred.resolve(videoObject)},error:function(data){s3deferred.reject(data)}}),s3deferred.promise}function encode(videoObject){var encodeDeferred=$q.defer();return $http({method:"POST",url:"/video/"+videoObject.attrs.id+"/encode"}).success(function(data){videoObject.attrs.encode_status_endpoints=data,_encodingVideos[videoObject.attrs.id]=videoObject.attrs,encodeDeferred.resolve(videoObject)}).error(function(data){encodeDeferred.reject(data)}),encodeDeferred.promise}var newVideoUrl="/video/new",fileInputId="#bulbs-cms-hidden-video-file-input",inputTemplate='';this.onVideoFileUpload=function(){var clickDeferred=$q.defer();angular.element(fileInputId).remove();var file,fileInput=angular.element(inputTemplate); -return angular.element("body").append(fileInput),fileInput.click(),fileInput.unbind("change"),fileInput.bind("change",function(elem){0!==this.files.length?(file=this.files[0],file.size>1073741824&&clickDeferred.reject("Upload file cannot be larger than 1024MB."),0!==file.type.indexOf("video/")&&clickDeferred.reject("You must upload a video file.")):clickDeferred.reject("Please select a file."),getNewVideoUploadCredentials(file).then(uploadToS3).then(encode,angular.noop,function(uploadPercentComplete){clickDeferred.notify(uploadPercentComplete)}).then(function(videoObject){clickDeferred.resolve(videoObject)},function(error){clickDeferred.reject(error)})}),clickDeferred.promise},this.encode=function(videoId){encode({attrs:{id:videoId}})},this.openVideoThumbnailModal=function(videoId){return $modal.open({templateUrl:routes.PARTIALS_URL+"modals/video-thumbnail-modal.html",controller:"VideothumbnailmodalCtrl",resolve:{videoId:function(){return videoId}}})},this.getVideo=function(videoId){var url="/video/"+videoId;return $http({method:"GET",url:url})},this.setVideo=function(video){var url="/video/"+video.id,data=$.param(video);return $http({method:"POST",url:url,data:data,headers:{"Content-Type":"application/x-www-form-urlencoded"}})};var _encodingVideos={};this.encodingVideos=_encodingVideos}),angular.module("bulbsCmsApp").filter("truncateByCharacters",function(){return function(input,chars,breakOnWord){if(isNaN(chars))return input;if(0>=chars)return"";if(input&&input.length>=chars){if(input=input.substring(0,chars),breakOnWord)for(;" "===input.charAt(input.length-1);)input=input.substr(0,input.length-1);else{var lastspace=input.lastIndexOf(" ");-1!==lastspace&&(input=input.substr(0,lastspace))}return 1===chars?input+".":input+"..."}return input}}),angular.module("bulbsCmsApp").filter("truncateByWords",function(){return function(input,words){if(isNaN(words))return input;if(0>=words)return"";if(input){var inputWords=input.split(/\s+/);inputWords.length>words&&(input=inputWords.slice(0,words).join(" ")+"...")}return input}}),angular.module("bulbsCmsApp").filter("tzDate",function(dateFilter,moment,TIMEZONE_NAME){return function(input,format){if(!input)return"";var inDate=moment.tz(input,TIMEZONE_NAME),newdate=inDate.format("YYYY-MM-DDTHH:mm"),formattedDate=dateFilter(newdate,format);return format.toLowerCase().indexOf("h")>-1&&(formattedDate+=" "+inDate.format("z")),formattedDate}}),angular.module("bulbsCmsApp").filter("user",function(){return function(user){return user?user.full_name?user.full_name:user.first_name&&user.last_name?user.first_name+" "+user.last_name:user.username:""}}); -//# sourceMappingURL=scripts.min.js.1456263460648.map \ No newline at end of file +var ACTIVE_STATES={INACTIVE:"Inactive",PROMOTED:"Pin to HP"};return restmod.model("special-coverage").mix("FieldDisplay","NestedDirtyModel",{$config:{name:"Special Coverage",plural:"Special Coverages",primaryKey:"id",fieldDisplays:[{title:"List Title",value:"record.name",sorts:"name"},{title:"Sponsor",value:'record.campaign.sponsorName || "--"',sorts:"campaign__sponsor_name"},{title:"Campaign",value:'record.campaign.campaignLabel || "--"',sorts:"campaign__campaign_label"},{title:"Start Date",value:'record.startDate.format("MM/DD/YY") || "--"',sorts:"start_date"},{title:"End Date",value:'record.endDate.format("MM/DD/YY") || "--"',sorts:"end_date"}]},end_date:{encode:"moment_to_date_string"},start_date:{encode:"moment_to_date_string"},endDate:{decode:"date_string_to_moment"},startDate:{decode:"date_string_to_moment"},campaign:{belongsTo:"Campaign",prefetch:!0,key:"campaign"},listUrl:{mask:"CU"},query:{init:{}},videos:{belongsToMany:"Video",keys:"videos"},active:{init:!0},promoted:{init:!1},$hooks:{"after-fetch":function(){this.$loadVideosData()},"after-save":function(){this.$loadVideosData()}},$extend:{Record:{$loadVideosData:function(){_.each(this.videos,function(video){video.$fetch()})},addVideo:function(video){var added=!1,existingVideo=_.find(this.videos,function(existingVideo){return video.id===existingVideo.id});return existingVideo||(this.videos.push(video),added=!0),added},$activeState:function(activeState){return _.isString(activeState)?activeState===ACTIVE_STATES.ACTIVE?(this.active=!0,this.promoted=!1):activeState===ACTIVE_STATES.PROMOTED?(this.active=!0,this.promoted=!0):(this.active=!1,this.promoted=!1):(activeState=ACTIVE_STATES.INACTIVE,this.active&&this.promoted?activeState=ACTIVE_STATES.PROMOTED:this.active&&(activeState=ACTIVE_STATES.ACTIVE)),activeState}},Model:{ACTIVE_STATES:_.clone(ACTIVE_STATES)}}})}),angular.module("apiServices.video.factory",["apiServices"]).value("VIDEOHUB_CHANNEL","onion").factory("Video",function(_,restmod,VIDEOHUB_CHANNEL){var singleRoot="root",videohubEndpoint="videohub-video",search=restmod.model(videohubEndpoint+"/search_hub").mix({$config:{jsonRootSingle:singleRoot},results:{hasMany:"Video"},$hooks:{"after-request":function(_req){var newData={};newData[singleRoot]=_req.data,_req.data=newData}}}),video=restmod.model(videohubEndpoint).mix({$config:{name:"Video",primaryKey:"id"},$extend:{Model:{searchVideoHub:function(query){return search.$create({query:query,filters:{channel:VIDEOHUB_CHANNEL}}).$asPromise()}}}});return video}),angular.module("contentServices.factory",[]).factory("ContentFactory",function(Restangular,contentApiConfig){return Restangular.withConfig(function(RestangularConfigurer){RestangularConfigurer.setBaseUrl(contentApiConfig.baseUrl)})}).constant("contentApiConfig",{baseUrl:"/cms/api/v1"}),angular.module("contentServices.listService",["contentServices.factory"]).service("ContentListService",function(_,$location,$q,ContentFactory){var ContentListService=this;this._serviceData={filters:$location.search()||{},content:[],totalItems:0};var _data=this._serviceData;ContentListService.updateFilters=function(addFilters,merge){return merge?_data.filters=_.assign($location.search()||{},addFilters):_data.filters=addFilters,$location.search(_data.filters),_data.filters},ContentListService.$updateContent=function(addFilters,merge){var updateParams=ContentListService.updateFilters(addFilters||_data.filters,merge);return ContentFactory.all("content").getList(updateParams).then(function(data){return _data.content=data,_data.totalItems=data.metadata.count,_data})},ContentListService.getData=function(){return _data}}),angular.module("contentServices",["contentServices.factory","contentServices.listService"]),angular.module("copyButton",[]).directive("copyButton",function(routes){return{controller:function($scope,$timeout){$scope.okCopy=!1,$scope.okCopyButton=function(){$scope.okCopy=!0,$timeout(function(){$scope.okCopy=!1},1e3)}},restrict:"E",scope:{buttonClassesDefault:"@",buttonClassesSuccess:"@",buttonText:"@",content:"@"},templateUrl:routes.SHARED_URL+"copy-button/copy-button.html"}}),angular.module("filters.moment",["moment"]).filter("date_string_to_moment",function(moment){return function(dateStr){if(dateStr&&dateStr.length){var m=moment(dateStr);if(m.isValid())return m}return null}}).filter("moment_to_date_string",function(moment){return function(momentObj){return moment.isMoment(momentObj)&&momentObj.isValid()?momentObj.format():""}}),angular.module("listPage",["bulbsCmsApp.settings","confirmationModal","copyButton","lodash"]).directive("listPage",function(routes){return{controller:function(_,$scope,$location,$parse){$scope.name=$scope.modelFactory.identity(),$scope.namePlural=$scope.modelFactory.identity(!0),$scope.fields=$scope.modelFactory.$fieldDisplays(),$scope.$list=$scope.modelFactory.$collection(),$scope.orderingFilter={},$scope.searchFilter={},$scope.toggledFilters={},$scope.copyContentInContext=function(record){var value="";return $scope.toolCopyContent&&(value=$parse($scope.toolCopyContent)({record:record})),value},$scope.$retrieve=_.debounce(function(addParams){$scope.loadingResults=!0;var allParams=_.merge({},$scope.orderingFilter,$scope.toggledFilters,$scope.searchFilter,addParams);return $scope.$list.$refresh(allParams).$then(function(){$scope.loadingResults=!1})},250),$scope.$search=function(query){$scope.searchFilter={},query&&($scope.searchFilter[$scope.searchParameter]=query),$scope.$list.$page=1,$scope.$retrieve()},$scope.filterButtonsParsed=$scope.filterButtons(),$scope.$toggleFilters=function(params){$scope.toggledFilters=params,$scope.$list.$page=1,$scope.$retrieve()},$scope.sortingField=null,$scope.sortDirection="asc",$scope.$sort=function(field){var direction;direction=field.title===$scope.sortingField&&"desc"===$scope.sortDirection?"asc":"desc",function(field,direction){$scope.orderingFilter={ordering:field.getOrdering(direction)},$scope.$retrieve().$then(function(){$scope.sortingField=field.title,$scope.sortDirection=direction})}(field,direction)},$scope.$add=function(){$location.path("/cms/app/"+$scope.cmsPage+"/edit/new/")},$scope.$remove=function(item){item.$destroy()},$scope.goToEditPage=function(item){$location.path("/cms/app/"+$scope.cmsPage+"/edit/"+item.id+"/")},$scope.activeFilterButton=_.chain($scope.filterButtonsParsed).findWhere({active:!0}).tap(function(button){button&&($scope.toggledFilters=button.params)}).result("title").value()||"",$scope.$retrieve()},restrict:"E",scope:{cmsPage:"@",filterButtons:"&",modelFactory:"=",searchParameter:"@",toolCopyContent:"@"},templateUrl:routes.SHARED_URL+"list-page/list-page.html"}}),angular.module("momentFormatterFilter",["moment"]).filter("momentFormatter",function(moment){return function(date,format){var m=moment(date);return m.isValid()?m.format(format):""}}),angular.module("slugify",[]).filter("slugify",function(){return function(text){return text.toString().toLowerCase().replace(/\s+/g,"-").replace(/[^\w\-]+/g,"").replace(/\-\-+/g,"-").replace(/^-+/,"").replace(/-+$/,"")}}),angular.module("cms.tunic.config",["lodash"]).provider("TunicConfig",["_",function(_){var apiPath="",backendRoot="",requestToken="",error=function(message){return new Error("Configuration Error (TunicConfig) "+message)};this.setApiPath=function(value){if(!_.isString(value))throw error("apiPath must be a string!");return apiPath=value,this},this.setBackendRoot=function(value){if(!_.isString(value))throw error("backendRoot must be a string!");return backendRoot=value,this},this.setRequestToken=function(value){if(!_.isString(value))throw error("requestToken must be a string!");return requestToken=value,this},this.$get=function(){return{getRequestToken:_.constant(requestToken),buildBackendApiUrl:function(relUrl){return backendRoot+apiPath+(relUrl||"")},shouldBeIntercepted:function(url){var urlTest=backendRoot+apiPath;return""!==urlTest&&url.startsWith(urlTest)}}}}]),angular.module("cms.tunic.interceptor",["cms.tunic.config"]).service("TunicInterceptor",["TunicConfig",function(TunicConfig){return this.request=function(config){return TunicConfig.shouldBeIntercepted(config.url)&&(config.headers=config.headers||{},config.headers.Authorization="Token "+TunicConfig.getRequestToken()),config},this}]),angular.module("cms.tunic",["cms.tunic.config","cms.tunic.interceptor"]),angular.module("utils",[]).service("Utils",function(){var Utils=this;return Utils.slugify=function(text){return text.toString().toLowerCase().replace(/\s+/g,"-").replace(/[^\w\-]+/g,"").replace(/\-\-+/g,"-").replace(/^-+/,"").replace(/-+$/,"")},Utils.moveTo=function(list,indexFrom,indexTo){var ret=!1;if(indexFrom>=0&&indexFrom=0&&indexTo0&&(list[indexTo]=splicer[0],ret=!0)}return ret},Utils.removeFrom=function(list,index){return list.splice(index,1).length>0},Utils}),angular.module("videoList.video.directive",["bulbsCmsApp.settings","filters.moment"]).directive("videoListVideo",function(routes){return{restrict:"E",scope:{model:"="},templateUrl:routes.SHARED_URL+"video-list/video-list-video/video-list-video.html"}}),angular.module("videoList",["autocompleteBasic","jquery","videoList.video.directive","ui.sortable","utils","VideohubClient.api","VideohubClient.settings"]).directive("videoList",function($,routes){return{controller:function(_,$scope,Utils,Video,VIDEOHUB_DEFAULT_CHANNEL){$scope.videoChannel=VIDEOHUB_DEFAULT_CHANNEL,$scope.moveUp=function(index){Utils.moveTo($scope.videos,index,index-1),$scope.onUpdate()},$scope.moveDown=function(index){Utils.moveTo($scope.videos,index,index+1),$scope.onUpdate()},$scope["delete"]=function(index){Utils.removeFrom($scope.videos,index),$scope.onUpdate()},$scope.addVideo=function(video){$scope.addVideoCallback({video:video}),$scope.onUpdate()},$scope.searchVideos=function(query){return Video.$postSearch({query:query,channel:VIDEOHUB_DEFAULT_CHANNEL})}},link:function(scope,element,attr){scope.sortableOptions={beforeStop:function(e,ui){ui.helper.css("margin-top",0)},change:function(e,ui){ui.helper.css("margin-top",$(window).scrollTop())},containment:"video-list",distance:3,opacity:.75,placeholder:"dropzone",start:function(e,ui){ui.helper.css("margin-top",$(window).scrollTop())}}},restrict:"E",scope:{addVideoCallback:"&addVideo",videos:"=",onUpdate:"&"},templateUrl:routes.SHARED_URL+"video-list/video-list.html"}}),angular.module("bulbsCmsApp").directive("activeNav",function($location){return{template:'
  • {{label}}
  • ',restrict:"E",scope:{},replace:!0,link:function(scope,element,attrs){scope.href=attrs.href,scope.label=attrs.label,0===$location.path().indexOf(scope.href)&&element.addClass("active")}}}),angular.module("bulbsCmsApp").directive("addImage",function($http,$window,routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"add-image.html",scope:{article:"="},link:function(scope,element,attrs){var attrName=attrs.attrName||"images";scope.article[attrName]=scope.article[attrName]||[],"false"===attrs.caption&&(scope.hideCaption=!0),scope.format=attrs.format||"jpg",scope.crop=attrs.crop||"16x9",scope.placeholderText=attrs.placeholderText||"Optional Image",scope.addAnImage=function(){$window.uploadImage({onSuccess:function(data){scope.$apply(function(){scope.article[attrName].push({id:data.id.toString(),alt:null,caption:null}),setTimeout($window.picturefill,200)})},onError:function(data){scope.$apply(function(){$window.alert("Error: ",data)})},onProgress:function(data){}})}}}}),angular.module("bulbsCmsApp").directive("articlecontainer",function(routes,LOADING_IMG_SRC){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"promotion-tool-article-container.html",scope:{article:"="},link:function(scope,element,attrs){scope.LOADING_IMG_SRC=LOADING_IMG_SRC,scope.ratio=attrs.ratio}}}),angular.module("bulbsCmsApp").directive("authorsField",function(routes,userFilter,$){return{templateUrl:routes.PARTIALS_URL+"taglike-autocomplete-field.html",restrict:"E",replace:!0,scope:{article:"="},link:function(scope,element,attrs){scope.name="author",scope.label="Authors",scope.placeholder="Authors",scope.resourceUrl="/cms/api/v1/author/?ordering=name&search=",scope.display=userFilter,scope.$watch("article.authors",function(){scope.objects=scope.article.authors},!0),scope.add=function(o,input){for(var t in scope.article.authors)if(scope.article.authors[t].id===o.id)return;scope.article.authors.push(o),$(input).val("")},scope["delete"]=function(e){var author=$(e.target).parents("[data-taglikeobject]").data("taglikeobject"),id=author.id,newauthors=[];for(var i in scope.article.authors)scope.article.authors[i].id!==id&&newauthors.push(scope.article.authors[i]);scope.article.authors=newauthors}}}}),angular.module("bulbsCmsApp").directive("bulbsAutocomplete",function($http,$location,$compile,$timeout,$,Login,Raven){var autocomplete_dropdown_template='';return{restrict:"AC",link:function(scope,element,attrs){function getAutocompletes(val){$timeout.cancel(inputTimeout),inputCounter=0,$http({method:"GET",url:scope.resourceUrl+val}).success(function(data){var results=data.results||data;scope.autocomplete_list=results.splice(0,5)}).error(function(data,status,headers,config){Raven.captureMessage("Error in getAutocompletes",{extra:data})})}var $elem=$(element).find("input");$elem.attr("autocomplete","off");var dropdown=$($compile(autocomplete_dropdown_template)(scope));$(dropdown).css({position:"absolute",top:$elem.position().top+$elem.outerHeight(),left:$elem.position().left,minWidth:$elem.outerWidth(),display:"none"}),$elem.parent().append(dropdown),$(dropdown).fadeIn("fast"),scope.$watch(function(){return{top:$elem.position().top+$elem.outerHeight(),left:$elem.position().left,minWidth:$elem.outerWidth()}},function(newValue,oldValue){$(dropdown).css({top:newValue.top,left:newValue.left,minWidth:newValue.minWidth})},!0);var inputTimeout,inputCounter=0;$elem.on("focus",function(e){$elem.on("input",function(){var val=$elem.val();""===val?scope.autocomplete_list=[]:($timeout.cancel(inputTimeout),inputTimeout=$timeout(function(){getAutocompletes(val)},200),inputCounter>2&&getAutocompletes(val))}),$(dropdown).fadeIn("fast")}),$elem.on("blur",function(e){$(dropdown).fadeOut("fast")}),$(dropdown).on("mouseover",".entry",function(e){$(dropdown).find(".selected").removeClass("selected"),$(this).addClass("selected")}),$elem.on("keyup",function(e){if(40===e.keyCode)if(0===$("div.selected",dropdown).length)$("div.entry",dropdown).first().addClass("selected");else{var curDownSelect=$("div.selected",dropdown),curDownSelectNext=curDownSelect.next("div");0===curDownSelectNext.length?$("div.entry",dropdown).first().addClass("selected"):curDownSelectNext.addClass("selected"),curDownSelect.removeClass("selected")}if(38===e.keyCode)if(0===$("div.selected",dropdown).length)$("div.entry",dropdown).last().addClass("selected");else{var curSelect=$("div.selected",dropdown),curSelectNext=curSelect.prev("div");0===curSelectNext.length?$("div.entry",dropdown).last().addClass("selected"):curSelectNext.addClass("selected"),curSelect.removeClass("selected")}if(13===e.keyCode){var selected=$("div.selected",dropdown);0===selected.length&&scope.onClick($elem.val(),!0),selected.click()}}),scope.onClick=function(o,freeForm){scope.add(o,$elem,freeForm||!1),scope.autocomplete_list=[]}}}}),angular.module("bulbsCmsApp").directive("cmsNotification",function(routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"cms-notification.html",scope:{notification:"="},controller:"CmsNotificationCtrl"}}),angular.module("bulbsCmsApp").directive("cmsNotifyContainer",function(routes){return{restrict:"E",scope:{},templateUrl:routes.PARTIALS_URL+"cms-notify-container.html",controller:"CmsNotifyContainerCtrl"}}),angular.module("bulbsCmsApp").directive("contributorField",function(routes,$){return{templateUrl:routes.PARTIALS_URL+"textlike-autocomplete-field.html",restrict:"E",replace:!0,scope:{override:"="},link:function(scope,element,attrs){scope.name="contributor",scope.label="Contributors",scope.placeholder="Contributors",scope.resourceUrl="/cms/api/v1/author/?ordering=name&search=",scope.$watch("override.contributor",function(){scope.override.hasOwnProperty("contributor")&&null!==scope.override.contributor&&(scope.model=scope.override.contributor.full_name||scope.override.contributor.fullName)}),scope.display=function(o){return o&&o.full_name||""},scope.add=function(o,input){scope.override.hasOwnProperty("contributor")&&null!==scope.override.contributor&&scope.override.contributor.id===o.id||(scope.override.contributor=o,$("#feature-type-container").removeClass("newtag"),$("#feature-type-container").addClass("newtag"))},scope["delete"]=function(e){scope.override.contributor=null,scope.model=null}}}}),angular.module("bulbsCmsApp").directive("createContent",function($http,$window,$,IfExistsElse,Login,ContentFactory,routes,AUTO_ADD_AUTHOR,Raven){return{restrict:"E",templateUrl:routes.DIRECTIVE_PARTIALS_URL+"create-content.html",controller:function($scope){function saveArticle(){$("button.go").removeClass("btn-danger").addClass("btn-success").html(' Going'),$http({url:"/cms/api/v1/content/?doctype="+$scope.contentType,method:"POST",data:$scope.init}).success(function(resp){var new_id=resp.id,new_path="/cms/app/edit/"+new_id+"/";$scope.rating_type&&(new_path+="?rating_type="+$scope.rating_type),$window.location.href=$window.location.origin+new_path}).error(function(data,status,headers,config){403===status?$("button.go").html(' Please Log In'):$("button.go").removeClass("btn-success").addClass("btn-danger").html(' Error'),$scope.gotSave=!1})}$scope.gotTags=!1,$scope.gotUser=!1,$scope.gotSave=!1,$scope.$watch(function(){return $scope.gotTags&&$scope.gotUser&&$scope.gotSave},function(val){val&&saveArticle($scope.init)}),$scope.newArticle=function(e){var init={title:$scope.newTitle};angular.extend($scope.init,init),$scope.tag?IfExistsElse.ifExistsElse(ContentFactory.all("tag").getList({ordering:"name",search:$scope.tag}),{slug:$scope.tag},function(tag){$scope.init.tags=[tag],$scope.gotTags=!0},function(value){console.log("couldnt find tag "+value.slug+" for initial value")},function(data,status,headers,config){Raven.captureMessage("Error Creating Article",{extra:data})}):$scope.gotTags=!0,AUTO_ADD_AUTHOR?ContentFactory.one("me").get().then(function(data){$scope.init.authors=[data],$scope.gotUser=!0}):$scope.gotUser=!0,$scope.gotSave=!0}},link:function(scope,element,attrs){scope.panel=1,$(element).find("a.create-content").on("click",function(e){$("a.create-content.active").removeClass("active"),$(this).addClass("active")}),$(element).find("a.create-content").on("click",function(e){return scope.contentTypeLabel=$(this).text(),scope.contentType=$(this).data("content_type")||null,scope.init=$(this).data("init")||{},scope.tag=$(this).data("tag")||null,scope.rating_type=$(this).data("rating_type")||null,scope.$apply(),$(this).hasClass("go-next")?(e.preventDefault(),$("#create button.next-pane").click(),!1):!0}),$("button.next-pane:not(.hide)").on("click",function(e){scope.panel=2,$(".new-title").focus()}),$(element).on("keydown",".editor",function(e){13===e.keyCode&&scope.newTitle&&$(element).find(".go").click()}),$("#create").on("hidden.bs.modal",function(){scope.newTitle="",scope.panel=1})}}}),angular.module("bulbsCmsApp").directive("datetimeSelectionModalOpener",function($modal,routes){return{restrict:"A",scope:{modDatetime:"=?ngModel",modalTitle:"@",modalOnClose:"&"},link:function(scope,element){var modalInstance=null;element.addClass("datetime-selection-modal-opener"),element.on("click",function(){modalInstance=$modal.open({templateUrl:routes.PARTIALS_URL+"modals/datetime-selection-modal.html",controller:"DatetimeSelectionModalCtrl",scope:scope}),modalInstance.result.then(function(newDate){scope.modDatetime=newDate,scope.modalOnClose({newDate:newDate})})})}}}),angular.module("bulbsCmsApp").directive("devicepreview",function($,routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"devicepreview.html",link:function(scope,element,attrs){var pP=$("#page-prev"),tN=pP.find(".nav a"),cO=pP.find(".tab-content .active");tN.click(function(e){var newId=$(this).attr("href").split("#")[1];e.preventDefault(),cO.attr("id",newId)}),$("#page-prev").on("show.bs.collapse",function(){$(this).find(".fa").removeClass("fa-plus-square-o").addClass("fa-minus-square-o")}),$("#page-prev").on("hide.bs.collapse",function(){$(this).find(".fa").removeClass("fa-minus-square-o").addClass("fa-plus-square-o")})}}}),angular.module("bulbsCmsApp").directive("onionEditor",function(routes,$,Zencoder,BettyCropper,openImageCropModal,VIDEO_EMBED_URL,OnionEditor){return{require:"ngModel",replace:!0,restrict:"E",templateUrl:routes.PARTIALS_URL+"editor.html",scope:{ngModel:"="},link:function(scope,element,attrs,ngModel){function read(){safeApply(scope,function(){var html=editor.getContent();html===defaultValue&&(html=""),ngModel.$setViewValue(html)})}if(ngModel){var formatting;attrs.formatting&&(formatting=attrs.formatting.split(","));var options={},defaultValue="";"multiline"===attrs.role?(defaultValue="


    ",options={multiline:!0,formatting:formatting||["link","bold","italic","blockquote","heading","list","strike","underline"],placeholder:{text:attrs.placeholder||"

    Write here

    ",container:$(".editorPlaceholder",element[0])[0]},link:{domain:attrs.linkDomain||!1,searchHandler:window[attrs.linkSearchHandler]||!1},statsContainer:".wordcount",inlineObjects:attrs.inlineObjects,image:{insertDialog:BettyCropper.upload,editDialog:openImageCropModal},video:{insertDialog:Zencoder.onVideoFileUpload,editDialog:Zencoder.openVideoThumbnailModal,videoEmbedUrl:VIDEO_EMBED_URL}}):($(".document-tools, .embed-tools",element).hide(),defaultValue="",options={multiline:!1,placeholder:{text:attrs.placeholder||"Write here",container:$(".editorPlaceholder",element[0])[0]},formatting:formatting||[]});var editor=new OnionEditor($(".editor",element[0])[0],options);ngModel.$render=function(){editor.setContent(ngModel.$viewValue||defaultValue),setTimeout(function(){editor.setChangeHandler(read)})},ngModel.$isEmpty=function(value){return!value||editor.scribe.allowsBlockElements()&&value===defaultValue},scope.$watch(ngModel,function(){editor.setContent(ngModel.$viewValue||defaultValue),window.picturefill&&window.picturefill(element[0])})}}}}),angular.module("bulbsCmsApp").directive("encodeStatus",function($http,$interval,$,Zencoder,routes){return{templateUrl:routes.PARTIALS_URL+"encode-status.html",restrict:"E",link:function(scope,element,attrs){function updateEncodeStatuses(){var updateEncodeStatus=function(i){return function(videoid){Zencoder.encodingVideos[videoid].encode_status_endpoints&&Zencoder.encodingVideos[videoid].encode_status_endpoints.json&&$http({method:"GET",url:Zencoder.encodingVideos[videoid].encode_status_endpoints.json,headers:{"X-CSRFToken":void 0}}).success(function(data){scope.encodingVideos[videoid].job_status=data,"finished"===data.state&&(scope.encodingVideos[videoid].finished=!0)})}(i)};for(var i in Zencoder.encodingVideos)scope.encodingVideos[i]&&scope.encodingVideos[i].finished||(scope.encodingVideos[i]=Zencoder.encodingVideos[i],updateEncodeStatus(i))}scope.encodingVideos={},scope.$watch(function(){return Zencoder.encodingVideos},function(){updateEncodeStatuses()},!0),$interval(function(){$("iframe").filter(function(){return this.src.match(/\/video\/embed\/?/)}).each(function(){var idRegex=/\/video\/embed\/?\?id=(\d+)/,id=idRegex.exec(this.src)[1];id in Zencoder.encodingVideos||Zencoder.getVideo(id).then(function(data){Zencoder.encodingVideos[id]=data.data})}),updateEncodeStatuses()},5e3)}}}),angular.module("bulbsCmsApp").directive("featuretypeField",function(routes,IfExistsElse,ContentFactory,Raven,$){return{templateUrl:routes.PARTIALS_URL+"textlike-autocomplete-field.html",restrict:"E",scope:{article:"=",hideLabel:"="},replace:!0,link:function(scope,element,attrs){scope.name="feature_type",scope.label="Feature Type",scope.placeholder="Feature Type",scope.resourceUrl="/cms/api/v1/things/?type=feature_type&q=",scope.$watch("article.feature_type",function(){scope.model=scope.article.feature_type}),scope.display=function(o){return o&&o.name||""},scope.add=function(o,input,freeForm){var fVal=freeForm?o:o.name;IfExistsElse.ifExistsElse(ContentFactory.all("things").getList({type:"feature_type",q:fVal}),{name:fVal},function(ft){scope.article.feature_type=ft.name,$("#feature-type-container").removeClass("newtag")},function(value){scope.article.feature_type=value.name,$("#feature-type-container").addClass("newtag")},function(data,status){Raven.captureMessage("Error Adding Feature Type",{extra:data})})},scope["delete"]=function(e){scope.article.feature_type=null}}}}),angular.module("bulbsCmsApp").directive("hideIfForbidden",function($http){function hideElement(element){element.addClass("hidden")}return{restrict:"A",link:function(scope,element,attrs){$http({method:"OPTIONS",url:attrs.optionsUrl,noPermissionIntercept:!0}).success(function(data,status){403===status&&hideElement(element)}).error(function(data,status){403===status&&hideElement(element)})}}}),angular.module("bulbsCmsApp").directive("lazyInclude",function(routes,$,$compile,$q,$http,$templateCache,Gettemplate){return{restrict:"A",scope:!0,link:function(scope,element,attrs){var templateUrl=routes.PARTIALS_URL+attrs.template,$element=$(element);scope.$evalAsync(function(){scope.$watch(function(){return $element.is(":visible")},function(visible){visible&&!scope.loaded&&(scope.loaded=!0,Gettemplate.get(templateUrl).then(function(html){var template=angular.element(html),compiledEl=$compile(template)(scope);element.html(compiledEl),element.css("height","auto")}))})})}}}),angular.module("bulbsCmsApp").directive("loggedInUser",function(routes,CurrentUser){return{restrict:"E",replace:!0,templateUrl:routes.PARTIALS_URL+"logged-in-user.html",scope:{},link:function(scope,element,attrs){scope.current_user=CurrentUser}}}),angular.module("bulbsCmsApp").directive("navBar",function(routes,navbar_options,CurrentUser){return{restrict:"E",scope:!1,templateUrl:function(tElement,tAttrs){return navbar_options[tAttrs.view]?routes.DIRECTIVE_PARTIALS_URL+navbar_options[tAttrs.view]+".html":routes.PARTIALS_URL+tAttrs.view+".html"},link:function(scope){scope.NAV_LOGO=routes.NAV_LOGO,scope.current_user=CurrentUser}}}),angular.module("bulbsCmsApp").directive("responsiveImage",function($window,$){return{link:function(scope,element,attrs){attrs.$observe("imageId",function(val){$(element).find("img").remove(),element.attr("data-image-id",attrs.imageId),element.attr("data-crop",attrs.crop),attrs.imageId&&$(element).is(":visible")&&($window.pictureFillElement(element[0]),element.show())})}}}),angular.module("bulbsCmsApp").directive("roleField",function($http,routes,$,Raven){return{templateUrl:routes.PARTIALS_URL+"rolefield.html",restrict:"E",replace:!0,scope:{model:"="},link:function(scope,element,attrs){var resourceUrl="/cms/api/v1/contributions/role/";scope.roleValue=null,scope.roleOptions=[],scope.$watch("model.role",function(){for(var i=0;i Save",busy:"Saving",finished:"Saved",error:"Error"})}),scope.save=function(){if(attrs.confirmClickWith){var message=attrs.confirmClickWith;if(!$window.confirm(message))return}scope.colors=scope.colors_tmp,element.prop("disabled",!0).html(" "+scope.config.busy);var save_promise=scope.getPromise(),saveSuccess=function(result){return scope.colors=scope.colors_tmp,element.prop("disabled",!1).html(" "+scope.config.finished),$timeout(function(){element.html(scope.config.idle)},1e3).then(function(){return result})};if(save_promise){var promise=save_promise.then(saveSuccess)["catch"](function(reason){return scope.colors="btn-danger",element.prop("disabled",!1).html(" "+scope.config.error),$q.reject(reason)});scope.saveCbk&&scope.saveCbk({promise:promise})}else saveSuccess()}}}}),angular.module("bulbsCmsApp").directive("sectionsField",function(routes,_,IfExistsElse,ContentFactory,Raven,$){return{templateUrl:routes.PARTIALS_URL+"taglike-autocomplete-field.html",restrict:"E",replace:!0,link:function(scope,element,attrs){scope.name="section",scope.label="Sections",scope.placeholder="Enter a section",scope.resourceUrl="/cms/api/v1/tag/?ordering=name&types=core_section&search=",scope.display=function(o){return o.name},scope.$watch("article.tags",function(){scope.objects=_.where(scope.article.tags,{type:"core_section"})},!0),scope.add=function(o,input,freeForm){var tagVal=freeForm?o:o.name;IfExistsElse.ifExistsElse(ContentFactory.all("tag").getList({ordering:"name",search:tagVal}),{name:tagVal},function(tag){scope.article.tags.push(tag)},function(){console.log("Can't create sections.")},function(data,status){Raven.captureMessage("Error Adding Section",{extra:data})}),$(input).val("")},scope["delete"]=function(e){var tag=$(e.target).parents("[data-taglikeobject]").data("taglikeobject"),name=tag.name,newtags=[];for(var i in scope.article.tags)scope.article.tags[i].name!==name&&newtags.push(scope.article.tags[i]);scope.article.tags=newtags}}}}),angular.module("bulbsCmsApp").directive("slideshowPane",function($http,$window,$compile,$,routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"slideshow-pane.html",scope:{article:"=",image:"=",index:"="},link:function(scope,element,attrs){var $element=$(element);"false"===attrs.caption&&(scope.hideCaption=!0),scope.format=attrs.format||"jpg",scope.crop=attrs.crop||"16x9",scope.removeImage=function(index){scope.article.slides.splice(index,1)},scope.editImage=function(index){$window.openImageDrawer(scope.article.slides[index].id,function(data){function removeLoadingGif(){$element.find('.image img[src="'+routes.LOADING_IMG_SRC+'"]').remove()}removeLoadingGif(),$element.find(".image").data("imageId")!==data.id&&($element.find(".image img").on("load",removeLoadingGif),$element.find(".image img").after(''),scope.article.slides[index].id=data.id.toString(),scope.$apply(),$window.picturefill(),$element.find(".image img")[0].complete&&removeLoadingGif())},function(){},function(oldImage){scope.article.slides[index]=oldImage,$window.picturefill()})}}}}),angular.module("bulbsCmsApp").directive("staticImage",function(routes,STATIC_IMAGE_URL){return{templateUrl:routes.PARTIALS_URL+"static-image.html",restrict:"E",scope:{image:"="},link:function(scope,element,attrs){var ratio=attrs.ratio||"16x9";scope.$watch("image",function(){scope.image&&scope.image.id?scope.imageUrl=STATIC_IMAGE_URL.replace("{{ratio}}",ratio).replace("{{image}}",scope.image.id):scope.imageUrl=!1})}}}),angular.module("bulbsCmsApp").directive("tagsField",function(routes,_,IfExistsElse,ContentFactory,Raven,$){return{templateUrl:routes.PARTIALS_URL+"taglike-autocomplete-field.html", +restrict:"E",scope:{article:"="},replace:!0,link:function(scope,element,attrs){scope.name="tag",scope.label="Tags",scope.placeholder="Enter a tag",scope.resourceUrl="/cms/api/v1/tag/?ordering=name&types=content_tag&search=",scope.display=function(o){return o.name},scope.$watch("article.tags",function(){scope.objects=_.where(scope.article.tags,{type:"content_tag"})},!0),scope.add=function(o,input,freeForm){var tagVal=freeForm?o:o.name;IfExistsElse.ifExistsElse(ContentFactory.all("tag").getList({ordering:"name",search:tagVal}),{name:tagVal},function(tag){scope.article.tags.push(tag)},function(value){scope.article.tags.push({name:value.name,type:"content_tag","new":!0})},function(data,status){Raven.captureMessage("Error Adding Tag",{extra:data})}),$(input).val("")},scope["delete"]=function(e){var tag=$(e.target).parents("[data-taglikeobject]").data("taglikeobject"),name=tag.name,newtags=[];for(var i in scope.article.tags)scope.article.tags[i].name!==name&&newtags.push(scope.article.tags[i]);scope.article.tags=newtags}}}}),angular.module("bulbsCmsApp").directive("targeting",function(routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"targeting.html",link:function(scope,element,attrs){scope.addTargetingRow=function(index){scope.targetingArray.push([])},scope.removeTargetingRow=function(index){scope.targetingArray.splice(index,1)}}}}),angular.module("bulbsCmsApp").directive("videoUpload",function($http,$window,$timeout,$sce,$,routes){return{templateUrl:routes.PARTIALS_URL+"mainvideo.html",scope:{article:"="},restrict:"E",link:function(scope,element,attrs){function abortUpload(){setProgress(0),scope.req&&scope.req.abort(),scope.video={},setProgress(0)}function abortEncode(){$.ajax("https://app.zencoder.com/api/v2/jobs/"+scope.video.job_id+"/cancel.json?api_key="+$window.videoAttrs.zencoderApiKey,{type:"PUT",success:function(data){scope.video.status=3,fakeInput.val("Encoding failed! Please try again.")}})}function setProgress(progress){return 0===progress||100===progress?void progressEl.hide():void((0===scope.lastProgress||Math.abs(progress-scope.lastProgress)>2)&&(progressBar.css("width",Math.floor(progress)+"%"),scope.lastProgress=progress,progressEl.show()))}function updateEncodeProgress(){progressBar.addClass("progress-bar-success"),delete $http.defaults.headers.common["X-Requested-With"],$http({url:"https://app.zencoder.com/api/v2/jobs/"+scope.video.job_id+"/progress.json",method:"GET",params:{api_key:$window.videoAttrs.zencoderApiKey},useXDomain:!0}).success(function(data){"waiting"===data.state||"pending"===data.state||"processing"===data.state?(scope.video.status=2,data.progress>5?(setProgress(data.progress),$timeout(updateEncodeProgress,500)):$timeout(updateEncodeProgress,2e3)):(setProgress(0),"finished"===data.state&&(scope.video.status=1),("failed"===data.state||"cancelled"===data.state)&&(scope.video.status=3,fakeInput.val("Encoding failed! Please try again.")))}).error(function(data){$(".alert-danger").fadeIn().delay(1e3).fadeOut()})}console.log("video upload here"),console.log(scope.video_id),scope.$watch("article.video",function(){scope.article.video&&(scope.embedUrl=$sce.trustAsUrl("/video/embed?id="+scope.article.video),$http({method:"GET",url:"/videos/api/video/"+scope.article.video+"/"}).success(function(data){console.log("getting video from API"),console.log(data),scope.video=data,$window.initVideoWidget(data.id)}))}),scope.$watch("video",function(){});var progressEl=element.find("div.progress"),progressBar=element.find("div.progress-bar"),fakeInput=element.find("input.fake-input");scope.lastProgress=0,scope.addVideo=function(){console.log("chooseFile"),$window.uploadVideo(element.find(".video-container")[0],{onSuccess:function(videoid){scope.$apply(function(){console.log("addVideo onSuccess callback"),console.log(videoid),scope.article.video=videoid})},onError:function(data){console.log("addVideo onError callback"),console.log(data)},onProgress:function(data){console.log("addVideo onProgress callback"),console.log(data)}})},scope.clearVideo=function(areYouSure){areYouSure?($("#s3upload-file-input").val(""),scope.article.video=null):$("#confirm-clear-video-modal").modal("show")},scope.abort=function(){return scope.encoding?void abortEncode():void abortUpload()};var initialCheckRan=!1;scope.$watch("video",function(){scope.video&&scope.video.job_id&&!initialCheckRan&&(updateEncodeProgress(),initialCheckRan=!0)})}}}),angular.module("bulbsCmsApp").directive("videoEmbed",function(VIDEO_EMBED_URL){return{template:'
    ',restrict:"E",link:function(scope,element,attrs){scope.videoUrl=VIDEO_EMBED_URL+attrs.videoId}}}),angular.module("bulbsCmsApp").directive("videoField",function(Zencoder,routes){return{templateUrl:routes.PARTIALS_URL+"video-field.html",restrict:"E",scope:{article:"="},link:function(scope,element,attrs){scope.removeVideo=function(){scope.article.video=null},scope.uploadVideo=function(){Zencoder.onVideoFileUpload().then(function(success){console.log(success),scope.article.video=success.attrs.id},angular.noop,function(progress){console.log(progress),scope.uploadProgress=progress})},scope.thumbnailModal=function(){Zencoder.openVideoThumbnailModal(scope.article.video).result.then(function(resolve){console.log("thumbnail modal resolve"),console.log(resolve)},function(reject){console.log("thumbnail modal rejected")})}}}}),angular.module("bulbsCmsApp").directive("autocompleteMenu",function($timeout,$animate,$compile,routes){return{restrict:"E",replace:!0,transclude:!0,controller:angular.noop,scope:{items:"=items",pIndex:"=index",select:"&select"},link:function($scope,element,attrs){$scope.selectItem=function(index){$scope.select(index)},$scope.setIndex=function(index){$scope.index=index,attrs.index&&($scope.pIndex=parseInt(index,10))},attrs.index&&$scope.$watch("pIndex",function(value){$scope.index=parseInt(value,10)}),$scope.label=function(index){var viewValue=$scope.items[index][attrs.labelAttr];return"function"==typeof viewValue&&(viewValue=viewValue()),viewValue}},template:'
    • {{ label($index) }}
    '}}),angular.module("bulbsCmsApp").directive("autocomplete",function($timeout,$animate,$compile,routes){return{restrict:"E",replace:!0,require:"ngModel",transclude:!0,controller:function($scope,$element,$attrs,$injector){$scope.service=$injector.get($attrs.service),$scope.placeholder=$attrs.placeholder||""},link:function($scope,element,attrs,ngModel,transclude){function queryData(query){var searchParams={};searchParams[attrs.searchParam||"search"]=query,$scope.service.getList(searchParams).then(function(results){results.length>5?menuScope.items=results.slice(0,5):menuScope.items=results,timeoutId=null})}function appendMenu(){isMenuAppended||(isMenuAppended=!0,menuScope.index=0,$animate.enter(menuEl,element.parent(),element)),styleMenu()}function reset(){ngModel.$render(),menuScope.items=[],menuScope.index=0,$animate.leave(menuEl)["finally"](function(){isMenuAppended=!1})}function styleMenu(){var offset=(window.getComputedStyle(element[0]),element.offset());offset.left="auto",offset.right="auto",offset.top=element.outerHeight(),offset.minWidth=element.outerWidth(),angular.forEach(offset,function(value,key){!isNaN(value)&&angular.isNumber(value)&&(value+="px"),menuEl[0].style[key]=value,menuEl.css("z-index",1e3)})}var isMenuAppended=!1,inputEl=element.find("input"),timeoutId=null;ngModel.$render=function(){if(ngModel.$viewValue){var viewValue=ngModel.$viewValue[attrs.labelAttr];"function"==typeof viewValue&&(viewValue=viewValue()),element.find("input").val(viewValue),inputEl.attr("disabled","disabled")}},$scope.openMenu=function(e){inputEl.removeAttr("disabled"),inputEl[0].focus()},inputEl.on("blur keyup change",function(){if(void 0===inputEl.attr("disabled")){appendMenu();var value=inputEl.val();value&&(timeoutId&&$timeout.cancel(timeoutId),timeoutId=$timeout(function(){queryData(value)},150))}});var menuScope=$scope.$new();menuScope.items=[],menuScope.index=0,menuScope.select=function(index){ngModel.$setViewValue(menuScope.items[index]),reset()};var menuEl=angular.element(document.createElement("autocomplete-menu"));menuEl.attr({items:"items",select:"select(index)",index:"index","label-attr":attrs.labelAttr}),transclude(menuScope,function(clone){menuEl.append(clone)}),$compile(menuEl)(menuScope),element.find("input").on("keyup",function(e){switch(e.which){case 27:""===inputEl.val()?reset():inputEl.val("");break;case 40:$scope.$apply(function(){menuScope.index=(menuScope.index+1)%menuScope.items.length});break;case 38:$scope.$apply(function(){menuScope.index?menuScope.index=menuScope.index-1:menuScope.index=menuScope.items.length-1});break;case 13:menuScope.index>=0&&(ngModel.$setViewValue(menuScope.items[menuScope.index]),reset());break;default:return}})},templateUrl:routes.PARTIALS_URL+"autocomplete.html"}}),angular.module("bulbsCmsApp").controller("BadrequestmodalCtrl",function($scope,$modalInstance,detail){$scope.detail=detail}),angular.module("bulbsCmsApp").controller("ChangelogmodalCtrl",function($scope,$modalInstance,_,ContentFactory,article){$scope.article=article,$scope.users={},ContentFactory.all("log").getList({content:article.id}).then(function(data){$scope.changelog=data;var userIds=_.unique(_.pluck(data,"user")),resp=function(data){$scope.users[data.id]=data};for(var i in userIds)ContentFactory.one("author",userIds[i]).get().then(resp)})}),angular.module("bulbsCmsApp").controller("CmsNotificationCtrl",function($scope,moment){var valid=function(){$scope.postDateValid=$scope.postDate&&(!$scope.notifyEndDate||$scope.postDate<$scope.notifyEndDate),$scope.notifyEndDateValid=$scope.notifyEndDate&&$scope.postDate&&$scope.notifyEndDate>$scope.postDate,$scope.titleValid=$scope.notification.title&&$scope.notification.title.length>0&&$scope.notification.title.length<=110,$scope.notificationValid=$scope.postDateValid&&$scope.notifyEndDateValid&&$scope.titleValid};$scope.postDate=$scope.notification.post_date?moment($scope.notification.post_date):null,$scope.$watch("postDate",function(){$scope.postDate?($scope.notification.post_date=$scope.postDate.format(),$scope.notifyEndDate=$scope.postDate.clone().add({days:3})):$scope.notification.post_date=null}),$scope.notifyEndDate=$scope.notification.notify_end_date?moment($scope.notification.notify_end_date):null,$scope.$watch("notifyEndDate",function(){$scope.notifyEndDate?$scope.notification.notify_end_date=$scope.notifyEndDate.format():$scope.notification.notify_end_date=null}),$scope.notificationDirty=!1,$scope.$watch("notification",function(newValue,oldValue){angular.equals(newValue,oldValue)||($scope.notificationDirty=!0,valid())},!0),valid(),$scope.saveNotification=function(){$scope.$parent.userIsSuperuser&&$scope.notificationDirty&&$scope.notificationValid&&$scope.$parent.$saveNotification($scope.notification).then(function(newNotification){$scope.notification=newNotification,$scope.notificationDirty=!1})["catch"](function(error){console.log("Notification save failed",error)})},$scope.deleteNotification=function(){$scope.$parent.userIsSuperuser&&$scope.$parent.$deleteNotification($scope.notification)["catch"](function(error){console.log("Notification delete failed",error)})}}),angular.module("bulbsCmsApp").controller("CmsNotificationsCtrl",function($q,$window,$scope,routes,CmsNotificationsApi,CurrentUser,_,moment){$window.document.title=routes.CMS_NAMESPACE+" | Notifications",CurrentUser.$retrieveData().then(function(user){user.is_superuser&&($scope.userIsSuperuser=!0),CmsNotificationsApi.getList().then(function(notifications){var removeIndicies=[];_.each(notifications,function(notification,i){!user.is_superuser&&moment(notification.post_date).isAfter(moment())&&removeIndicies.push(i)}),_.each(removeIndicies,function(i){notifications.splice(i,1)}),$scope.notifications=notifications})}),$scope.newNotification=function(){var notification={post_date:null,notify_end_date:null};return $scope.notifications.unshift(notification),notification},$scope.$saveNotification=function(notification){var saveDefer=$q.defer(),savePromise=saveDefer.promise;return $scope.userIsSuperuser?"id"in notification?notification.put().then(function(updatedNotification){saveDefer.resolve(updatedNotification)}):$scope.notifications.post(notification).then(function(newNotification){var i=$scope.notifications.indexOf(notification);$scope.notifications[i]=newNotification,saveDefer.resolve(newNotification)})["catch"](function(error){saveDefer.reject(error)}):saveDefer.reject("Insufficient permissions."),savePromise},$scope.$deleteNotification=function(notification){var deleteDefer=$q.defer(),deletePromise=deleteDefer.promise,removeFromList=function(index){$scope.notifications.splice(index,1),deleteDefer.resolve()};if($scope.userIsSuperuser){var i=$scope.notifications.indexOf(notification);i>-1?_.isFunction(notification.remove)?notification.remove().then(function(){removeFromList(i)})["catch"](function(error){deleteDefer.reject(error)}):removeFromList(i):deleteDefer.reject("Cannot find notification in notification list. Unable to delete.")}else deleteDefer.reject("You do not have sufficient permissions to delete a notification.");return deletePromise}}),angular.module("bulbsCmsApp").controller("CmsNotifyContainerCtrl",function($scope,ipCookie,moment,CmsNotificationsApi,URLify,_){var genCookieKey=function(id){return"dismissed-cms-notification-"+id},updateNotificationsDisplay=function(notifications){var now=moment();$scope.notifications=_.filter(notifications,function(notification){return!ipCookie(genCookieKey(notification.id))&&moment(notification.post_date).isBefore(now)&&moment(notification.notify_end_date).isAfter(now)?!0:void 0})};CmsNotificationsApi.getList().then(function(notifications){updateNotificationsDisplay(notifications)}),$scope.dismissNotification=function(notification){var cookieKey=URLify(genCookieKey(notification.id));ipCookie(cookieKey,!0,{expires:moment(notification.notify_end_date).add({days:1}).diff(moment(),"days"),path:"/cms/app"}),updateNotificationsDisplay($scope.notifications)}}),angular.module("bulbsCmsApp").controller("ContenteditCtrl",function($scope,$routeParams,$http,$window,$location,$timeout,$interval,$compile,$q,$modal,$,_,moment,keypress,Raven,PNotify,IfExistsElse,VersionStorageApi,ContentFactory,FirebaseApi,FirebaseArticleFactory,Login,VersionBrowserModalOpener,routes){function getContent(){return ContentFactory.one("content",$routeParams.id).get().then(getArticleCallback)}function saveToContentApi(){$scope.article.put().then(saveArticleSuccessCbk)["catch"](saveArticleErrorCbk)}function saveArticleErrorCbk(data){$(navbarSave).removeClass("btn-success").addClass("btn-danger").html(" Error"),400===status&&($scope.errors=data),$scope.saveArticleDeferred.reject()}function saveArticleSuccessCbk(resp){VersionStorageApi.$create($scope.article,$scope.articleIsDirty),$(navbarSave).html(" Saved!"),setTimeout(function(){$(navbarSave).html(saveHTML)},2500),$window.article=$scope.article=resp,$scope.last_saved_article=angular.copy(resp),$scope.articleIsDirty=!1,$scope.errors=null,$location.search("rating_type",null),$scope.saveArticleDeferred.resolve(resp)}$scope.PARTIALS_URL=routes.PARTIALS_URL,$scope.CONTENT_PARTIALS_URL=routes.CONTENT_PARTIALS_URL,$scope.MEDIA_ITEM_PARTIALS_URL=routes.MEDIA_ITEM_PARTIALS_URL,$scope.page="edit",$scope.CACHEBUSTER=routes.CACHEBUSTER;var getArticleCallback=function(data){$window.article=$scope.article=data,$scope.last_saved_article=angular.copy(data),FirebaseApi.$connection.onConnect(function(){$scope.firebaseConnected=!0}).onDisconnect(function(){$scope.firebaseConnected=!1}),FirebaseArticleFactory.$retrieveCurrentArticle().then(function($article){var currentUser,savePNotify,$activeUsers=$article.$activeUsers(),$versions=$article.$versions();return $versions.$loaded(function(){$versions.$watch(function(e){if("child_added"===e.event){var newVersion=_.sortBy($versions,function(version){return-version.timestamp})[0];if(currentUser&&newVersion.user.id!==currentUser.id){savePNotify&&savePNotify.remove();var msg=""+newVersion.user.displayName+" -- "+moment(newVersion.timestamp).format("MMM Do YYYY, h:mma")+"
    ";$scope.articleIsDirty&&(msg+=" You have unsaved changes that may conflict when you save."),msg+=" Open the version browser to see their latest version.",savePNotify=new PNotify({title:"Another User Saved!",text:msg,type:"error",mouse_reset:!1,hide:!1,confirm:{confirm:!0,buttons:[{text:"Open Version Browser",addClass:"btn-primary",click:function(notice){notice.mouse_reset=!1,notice.remove(),VersionBrowserModalOpener.open($scope,$scope.article)}},{addClass:"hide"}]},buttons:{closer_hover:!1,sticker:!1}})}}})}),$activeUsers.$watch(function(){$scope.activeUsers=_.chain($activeUsers).groupBy(function(user){return user.id}).map(function(group){var groupedUser=group[0];return groupedUser.count=group.length,currentUser&&groupedUser.id===currentUser.id&&(groupedUser.displayName="You"),groupedUser}).sortBy(function(user){return"You"===user.displayName?"":user.displayName}).value()}),$article.$registerCurrentUserActive().then(function(user){currentUser=user}),$article})};getContent(),$scope.$watch("article.title",function(){$window.document.title=routes.CMS_NAMESPACE+" | Editing "+($scope.article&&$(""+$scope.article.title+"").text())}),$scope.saveArticleDeferred=$q.defer(),$scope.saveArticleIfDirty=function(){return $scope.articleIsDirty?$scope.saveArticle():$q.when($scope.article)},$scope.saveArticle=function(){return $(navbarSave).removeClass("btn-danger").addClass("btn-success").html(" Saving"),ContentFactory.one("content",$routeParams.id).get().then(function(data){data.last_modified&&$scope.article.last_modified&&moment(data.last_modified)>moment($scope.article.last_modified)?($scope.saveArticleDeferred.reject(),$modal.open({templateUrl:routes.PARTIALS_URL+"modals/last-modified-guard-modal.html",controller:"LastmodifiedguardmodalCtrl",scope:$scope,resolve:{articleOnPage:function(){return $scope.article},articleOnServer:function(){return data}}})):$scope.postValidationSaveArticle()})["catch"](saveArticleErrorCbk),$scope.saveArticleDeferred.promise};var listener=new keypress.Listener;listener.simple_combo("cmd s",function(e){$scope.saveArticle()}),listener.simple_combo("ctrl s",function(e){$scope.saveArticle()}),$scope.postValidationSaveArticle=function(){return"Published"!==$scope.article.status&&($scope.article.slug=$window.URLify($scope.article.title,50)),saveToContentApi(),$scope.saveArticleDeferred.promise};var saveHTML=" Save",navbarSave=".navbar-save";$scope.articleIsDirty=!1,$scope.$watch(function(){return!angular.equals($scope.article,$scope.last_saved_article)},function(isDirty){$scope.articleIsDirty=isDirty}),$scope.$watch("articleIsDirty",function(){$scope.articleIsDirty?$window.onbeforeunload=function(){return"You have unsaved changes. Do you want to continue?"}:$window.onbeforeunload=function(){}}),$scope.publishSuccessCbk=function(){return getContent()},$scope.trashSuccessCbk=function(){$timeout(function(){$window.history.back()},1500)}}),angular.module("bulbsCmsApp").controller("ContentlistCtrl",function($scope,$http,$timeout,$location,$window,$q,$,ContentListService,LOADING_IMG_SRC,routes){$scope.contentData=[],ContentListService.$updateContent({page:1}).then(function(data){$scope.contentData=data}),$scope.LOADING_IMG_SRC=LOADING_IMG_SRC,$window.document.title=routes.CMS_NAMESPACE+" | Content",$scope.pageNumber=$location.search().page||"1",$scope.myStuff=!1,$scope.search=$location.search().search,$scope.collapse={},$scope.goToPage=function(){ContentListService.$updateContent({page:$scope.pageNumber},!0)},$scope.publishSuccessCbk=function(data){var i;for(i=0;i<$scope.contentData.content.length&&$scope.contentData.content[i].id!==data.article.id;i++);for(var field in data.response)$scope.contentData.content[i][field]=data.response[field];return $q.when()},$scope.trashSuccessCbk=function(){$timeout(function(){ContentListService.$updateContent(),$("#confirm-trash-modal").modal("hide")},1500)},$("body").on("shown.bs.collapse",".panel-collapse",function(e){$scope.$digest()})}).directive("ngConfirmClick",[function(){return{link:function(scope,element,attr){var msg=attr.ngConfirmClick||"Are you sure?",clickAction=attr.confirmedClick;element.bind("click",function(){window.confirm(msg)&&scope.$eval(clickAction)})}}}]),angular.module("bulbsCmsApp").controller("ContentworkflowCtrl",function($scope,$http,$modal,$window,moment,routes,VersionBrowserModalOpener,TemporaryUrlModalOpener,TIMEZONE_NAME){$scope.TIMEZONE_LABEL=moment.tz(TIMEZONE_NAME).format("z"),$scope.trashContentModal=function(articleId){return $modal.open({templateUrl:routes.PARTIALS_URL+"modals/confirm-trash-modal.html",controller:"TrashcontentmodalCtrl",scope:$scope,resolve:{articleId:function(){return articleId}}})},$scope.pubTimeModal=function(article){return $modal.open({templateUrl:routes.PARTIALS_URL+"modals/publish-date-modal.html",controller:"PubtimemodalCtrl",scope:$scope,resolve:{article:function(){return article}}})},$scope.sendToEditorModal=function(article){return $modal.open({templateUrl:routes.PARTIALS_URL+"modals/send-to-editor-modal.html",controller:"SendtoeditormodalCtrl",scope:$scope,resolve:{article:function(){return article}}})},$scope.changelogModal=function(article){return $modal.open({templateUrl:routes.PARTIALS_URL+"modals/changelog-modal.html",controller:"ChangelogmodalCtrl",scope:$scope,resolve:{article:function(){return article}}})},$scope.thumbnailModal=function(article){return $modal.open({templateUrl:routes.PARTIALS_URL+"modals/thumbnail-modal.html",controller:"ThumbnailModalCtrl",scope:$scope,resolve:{article:function(){return article}}})},$scope.sponsoredContentModal=function(article){return $modal.open({templateUrl:routes.PARTIALS_URL+"modals/sponsored-content-modal.html",scope:$scope,resolve:{article:function(){return article}}})},$scope.sponsorModal=function(article){return $modal.open({templateUrl:routes.PARTIALS_URL+"modals/sponsor-modal.html",scope:$scope,controller:"SponsormodalCtrl",resolve:{article:function(){return article}}})},$scope.versionBrowserModal=function(article){VersionBrowserModalOpener.open($scope,article)},$scope.temporaryUrlModal=function(article){TemporaryUrlModalOpener.open($scope,article)},$scope.descriptionModal=function(article){return $modal.open({templateUrl:routes.PARTIALS_URL+"modals/description-modal.html",controller:"DescriptionModalCtrl",scope:$scope,size:"lg",resolve:{article:function(){return article}}})},$scope.getStatus=function(article){return article&&article.published?moment(article.published)>moment()?"scheduled":"published":"unpublished"}}),angular.module("bulbsCmsApp").controller("ContributionsCtrl",function($scope,$routeParams,$http,$window,$location,$timeout,$compile,$q,$modal,_,routes,ContributionRoleService,ContentService){function save(){angular.element("#save-btn").html(' Saving'),$scope.contributions.save($scope.contributions).then(function(contributions){angular.element("#save-btn").addClass("btn-success").removeClass("btn-danger"),angular.element("#save-btn").html(' Save'),$scope.clean=!0},function(res){angular.element("#save-btn").addClass("btn-danger").removeClass("btn-success"),angular.element("#save-btn").html(' Error')})}function add(){$scope.contributions.push({contributor:null,content:$scope.contentId,rate:{rate:0},role:null}),$scope.collapsed.push(!1)}function getRoles(){return ContributionRoleService.getList().then(function(roles){$scope.roles=roles,getContributions()})}function getContributions(){return ContentService.one($scope.contentId).all("contributions").getList().then(function(contributions){for(var i in contributions)null!==contributions[i]&&void 0!==contributions[i].role&&(contributions[i].hasOwnProperty("rate")&&"object"==typeof contributions[i].rate&&null!==contributions[i].rate&&(contributions[i].rate=contributions[i].rate.rate),"object"==typeof contributions[i].role&&(contributions[i].paymentType=contributions[i].role.payment_type,contributions[i].roleObject=contributions[i].role,contributions[i].role=contributions[i].role.id));$scope.contributions=contributions,$scope.collapsed=new Array(contributions.length),$scope.contributions.forEach(function(item,index){$scope.contributionLabels[index]=_.find($scope.roles,function(role){return role.id===item.role}).name,$scope.collapsed[index]=!0})})}function getContent(){ContentService.one($scope.contentId).get().then(function(content){$scope.content=content,$scope.article={id:content.id}})}function remove(index){$scope.contributions.splice(index,1),$scope.collapsed.splice(index,1)}function updateLabel(index){$scope.contributionLabels[index]=_.find($scope.roles,function(role){return $scope.contributions[index].roleObject=role,$scope.contributions[index].paymentType=role.payment_type,role.id===$scope.contributions[index].role}).name}$scope.NAV_LOGO=routes.NAV_LOGO,$scope.contentId=parseInt($routeParams.id,10),$scope.paymentType="",$scope.contributions=[],$scope.contributionLabels=[],$scope.roles=[],$scope.collapsed=[],$scope.page="contributions",$scope.clean=!0,$scope.save=save,$scope.add=add,$scope.remove=remove,$scope.updateLabel=updateLabel,$scope.isFlatRate=function(contribution){return contribution.hasOwnProperty("roleObject")&&"Flat Rate"===contribution.roleObject.payment_type?!0:!1},$scope.isFeatureType=function(contribution){return contribution.hasOwnProperty("roleObject")&&"FeatureType"===contribution.roleObject.payment_type?($scope.setFeatureRate(contribution),!0):!1},$scope.setFeatureRate=function(contribution){for(var i in contribution.roleObject.rates.feature_type){var featureTypeRate=contribution.roleObject.rates.feature_type[i];$scope.content.feature_type===featureTypeRate.feature_type&&(contribution.featureTypeRate=featureTypeRate.rate)}},$scope.isHourly=function(contribution){return contribution.hasOwnProperty("roleObject")&&"Hourly"===contribution.roleObject.payment_type?!0:!1},$scope.isManual=function(contribution){return contribution.hasOwnProperty("roleObject")&&"Manual"===contribution.roleObject.payment_type?!0:!1},$scope.getHourlyPay=function(contribution){return contribution.roleObject?contribution.roleObject.rate?contribution.roleObject.rate/60*(contribution.minutes_worked||0):0:void 0},$scope.$watch("contributions",function(newContributions,oldContributions){oldContributions.length>0&&($scope.clean=!1)},!0),getRoles(),getContent()}),angular.module("bulbsCmsApp").controller("DatetimeSelectionModalCtrl",function($scope,$modalInstance,TIMEZONE_NAME,moment){$scope.dateValid=!1,$scope.$watch("tempDatetime",function(){$scope.dateValid=moment($scope.tempDatetime).isValid()}),$scope.tempDatetime=angular.copy($scope.modDatetime),$scope.tempDatetime||($scope.tempDatetime=moment()),$scope.TIMEZONE_LABEL=moment.tz(TIMEZONE_NAME).format("z");var timeNowWithOffset=function(){return moment.tz(TIMEZONE_NAME)};$scope.setDate=function(newDate){$scope.tempDatetime=moment(newDate)},$scope.setDateToday=function(){var now=timeNowWithOffset();$scope.tempDatetime=moment().year(now.year()).month(now.month()).date(now.date())},$scope.setDateTomorrow=function(){var now=timeNowWithOffset();$scope.tempDatetime=moment().year(now.year()).month(now.month()).date(now.date()+1)},$scope.setTimeNow=function(){$scope.tempDatetime=timeNowWithOffset()},$scope.setTimeMidnight=function(){$scope.tempDatetime=timeNowWithOffset().hour(24).minute(0)},$scope.chooseDatetime=function(){if($scope.dateValid){var retMoment=moment($scope.tempDatetime);$modalInstance.close(retMoment)}else console.error("Attempting to choose invalid date.")}}),angular.module("bulbsCmsApp").controller("DescriptionModalCtrl",function($scope,$modalInstance,article){$scope.article=article}),angular.module("bulbsCmsApp").controller("ForbiddenmodalCtrl",function($scope,detail){$scope.detail=detail}),angular.module("bulbsCmsApp").controller("ImageCropModalCtrl",function($scope,$timeout,$modalInstance,BettyCropper,Selection,DEFAULT_IMAGE_WIDTH,imageData,ratios,$){$scope.selectedCrop=null,$scope.cropMode=!1,$scope.ratios=ratios,$scope.finished=!1,$scope.thumb_container_styles={},$scope.imageData=imageData,$scope.image||($scope.image=null,BettyCropper.get(imageData.id).then(function(success){$scope.image=success.data})),$scope.$watch("image",function(image){if(image){var finished=!0;for(var ratio in image.selections)if("auto"===image.selections[ratio].source){finished=!1;break}$scope.finished=finished,$scope.scaleData=image.scaleToFit(550,400),angular.element(".crop-image-container img").one("load",function(){$(this).Jcrop({allowSelect:!1,allowMove:!0,allowResize:!0,keySupport:!1},function(){$scope.jcrop_api=this})}),$scope.image_url=image.url("original",DEFAULT_IMAGE_WIDTH,"jpg"),$scope.ratios||($scope.ratios=Object.keys(image.selections)),$scope.setThumbStyles()}}),$scope.$watch("selectedCrop",function(crop){if($scope.image){var finished=!0;for(var ratio in $scope.image.selections)if("auto"===$scope.image.selections[ratio].source&&ratio!==crop){finished=!1;break}$scope.finished=finished}}),$scope.selectCrop=function(ratio){if(!ratio){ratio=Object.keys($scope.image.selections)[0];for(var key in $scope.image.selections)if("auto"===$scope.image.selections[key].source){ratio=key;break}}var selection=$scope.image.selections[ratio].scaleBy($scope.scaleData.scale);$scope.jcrop_api&&($scope.jcrop_api.setOptions({aspectRatio:selection.width()/selection.height()}),$scope.jcrop_api.setSelect([selection.x0,selection.y0,selection.x1,selection.y1])),$scope.cropMode=!0,$scope.selectedCrop=ratio},$scope.setThumbStyles=function(){$scope.thumb_styles=$scope.thumb_styles||{};for(var ratio in $scope.image.selections){var scaledSelection=$scope.image.selections[ratio].scaleToFit(170,170);$scope.thumb_container_styles[ratio]={"padding-top":Math.round((180-scaledSelection.height())/2)+"px","padding-bottom":"5px","padding-left":Math.round((180-scaledSelection.width())/2)+"px","padding-right":"5px"},$scope.thumb_styles[ratio]=$scope.image.getStyles(170,170,ratio)}},$scope.save=function(ratio){var jcrop_selection=$scope.jcrop_api.tellSelect(),newSelection=new Selection({x0:jcrop_selection.x,x1:jcrop_selection.x2,y0:jcrop_selection.y,y1:jcrop_selection.y2,source:"user"});return newSelection=newSelection.scaleBy(1/$scope.scaleData.scale),newSelection.x1>$scope.image.width&&(newSelection.x1=$scope.image.width),newSelection.y1>$scope.image.height&&(newSelection.y1=$scope.image.height),this.image.updateSelection(ratio,newSelection)},$scope.saveAndQuit=function(){var ratio=$scope.selectedCrop;this.save(ratio).then(function(success){var ratio=success.data[0],selection=success.data[1];$scope.image.selections[ratio]=selection}),$scope.cropMode=!1,$modalInstance.close(imageData)},$scope.saveAndNext=function(){var ratio=$scope.selectedCrop;this.save(ratio).then(function(success){var ratio=success.data[0],selection=success.data[1];$scope.image.selections[ratio]=selection;var nextRatioIndex=($scope.ratios.indexOf(ratio)+1)%$scope.ratios.length;$scope.selectCrop($scope.ratios[nextRatioIndex])})}}),angular.module("bulbsCmsApp").controller("LastmodifiedguardmodalCtrl",function($scope,$modalInstance,_,moment,ContentFactory,articleOnPage,articleOnServer){$scope.articleOnServer=articleOnServer,ContentFactory.all("log").getList({content:articleOnPage.id}).then(function(log){var latest=_.max(log,function(entry){return moment(entry.action_time)}),lastSavedById=latest.user; +ContentFactory.one("author",lastSavedById).get().then(function(data){$scope.lastSavedBy=data})}),$scope.loadFromServer=function(){_.each($scope.articleOnServer,function(value,key){$scope.article[key]=value}),$scope.articleIsDirty=!0,$modalInstance.close()},$scope.saveAnyway=function(){$modalInstance.close(),$scope.$parent.postValidationSaveArticle()}}),angular.module("bulbsCmsApp").controller("LoginmodalCtrl",function($scope,Login,$modalInstance,$){$scope.login=function(){var username=$("input[name='username']").val(),password=$("input[name='password']").val();Login.login(username,password).then(function(){$modalInstance.close()},function(){$modalInstance.dismiss()})}}),angular.module("bulbsCmsApp").controller("PubtimemodalCtrl",function($scope,$http,$modal,$modalInstance,$,moment,Login,routes,article,TIMEZONE_NAME,Raven){$scope.article=article,$scope.pubButton={idle:"Publish",busy:"Publishing",finished:"Published!",error:"Error!"},$scope.$watch("pickerValue",function(newVal){var pubTimeMoment=moment(newVal);$scope.datePickerValue=moment().year(pubTimeMoment.year()).month(pubTimeMoment.month()).date(pubTimeMoment.date()),$scope.timePickerValue=moment().hour(pubTimeMoment.hour()).minute(pubTimeMoment.minute())});var modelDateFormat="YYYY-MM-DDTHH:mmZ";$scope.setTimeShortcut=function(shortcut){if("now"===shortcut){var now=moment();$scope.pickerValue=now}if("midnight"===shortcut){var midnight=moment().hour(24).minute(0);$scope.pickerValue=midnight}},$scope.setDateShortcut=function(shortcut){var today=moment.tz(TIMEZONE_NAME);"today"===shortcut&&($scope.datePickerValue=moment().year(today.year()).month(today.month()).date(today.date())),"tomorrow"===shortcut&&($scope.datePickerValue=moment().year(today.year()).month(today.month()).date(today.date()+1))},$scope.setPubTime=function(){if(!$scope.article.feature_type)return $modalInstance.dismiss(),void $modal.open({templateUrl:routes.PARTIALS_URL+"modals/pubtime-validation-modal.html"});var newDate=moment($scope.datePickerValue),newTime=moment($scope.timePickerValue),newDateTime=moment.tz(TIMEZONE_NAME).year(newDate.year()).month(newDate.month()).date(newDate.date()).hour(newTime.hour()).minute(newTime.minute()).format(modelDateFormat),data={published:newDateTime};return $http({url:"/cms/api/v1/content/"+$scope.article.id+"/publish/",method:"POST",data:data})},$scope.setPubTimeCbk=function(publish_promise){publish_promise.then(function(result){$scope.article.published=result.data.published,$scope.publishSuccessCbk&&$scope.publishSuccessCbk({article:$scope.article,response:result.data}),$modalInstance.close()})["catch"](function(reason){Raven.captureMessage("Error Setting Pubtime",{extra:reason.data}),$modalInstance.dismiss()})},$scope.unpubButton={idle:"Unpublish",busy:"Unpublishing",finished:"Unpublished!",error:"Error"},$scope.unpublish=function(){return $http({url:"/cms/api/v1/content/"+$scope.article.id+"/publish/",method:"POST",data:{published:!1}})},$scope.unpublishCbk=function(unpub_promise){unpub_promise.then(function(result){$scope.publishSuccessCbk&&$scope.publishSuccessCbk({article:$scope.article,response:result.data}),$modalInstance.close()})["catch"](function(reason){$scope.publishSuccessCbk&&$scope.publishSuccessCbk({article:$scope.article,response:reason.data}),$modalInstance.dismiss()})},$scope.article.published?$scope.pickerValue=moment.tz($scope.article.published,TIMEZONE_NAME):$scope.setTimeShortcut("now")}),angular.module("bulbsCmsApp").controller("ReportingCtrl",function($http,$scope,$window,$,$location,$filter,$interpolate,Login,routes,moment,ContributionReportingService,ContentReportingService,FreelancePayReportingService){function loadReport(report,start,end,order,apiUrl){if($scope.items=[],"undefined"==typeof apiUrl?$scope.apiURL=report.downloadURL:$scope.apiURL=apiUrl,$scope.apiURL+="?page="+$scope.reportParams.pageNumber,$scope.downloadURL=report.downloadURL+"?format=csv",end){var endParam=$filter("date")(end,"yyyy-MM-dd");$scope.reportParams.end=endParam,$scope.apiURL+="&end="+endParam,$scope.downloadURL+="&end="+endParam}if(start){var startParam=$filter("date")(start,"yyyy-MM-dd");$scope.reportParams.start=startParam,$scope.apiURL+="&start="+startParam,$scope.downloadURL+="&start="+startParam}if(order&&($scope.apiURL+="&ordering="+order.key),$scope.publishedFilter&&($scope.apiURL+="&published="+$scope.publishedFilter,$scope.downloadURL+="&published="+$scope.publishedFilter,$scope.reportParams.published=$scope.publishedFilter),$scope.userFilter&&($scope.apiURL+="&staff="+$scope.userFilter,$scope.downloadURL+="&staff="+$scope.userFilter,$scope.reportParams.staff=$scope.userFilter),$scope.moreFilters)for(var key in $scope.moreFilters)"authors"===$scope.moreFilters[key].type?($scope.apiURL+="&contributors="+$scope.moreFilters[key].query,$scope.downloadURL+="&contributors="+$scope.moreFilters[key].query,$scope.reportParams.contributors=$scope.moreFilters[key].query):($scope.apiURL+="&"+$scope.moreFilters[key].type+"="+$scope.moreFilters[key].query,$scope.downloadURL+="&"+$scope.moreFilters[key].type+"="+$scope.moreFilters[key].query,$scope.reportParams[$scope.moreFilters[key].type]=$scope.moreFilters[key].query);$http({method:"GET",url:$scope.apiURL}).then(function(data){$scope.items=[],$scope.pageTotal=data.data.count,data.data.results.forEach(function(lineItem){var item=[];report.headings.forEach(function(heading){var exp=$interpolate("{{item."+heading.expression+"}}"),value=exp({item:lineItem});item.push(value)}),$scope.items.push(item)})})}$window.document.title=routes.CMS_NAMESPACE+" | Reporting",$scope.userFilter="",$scope.userFilters=[{name:"All",value:""},{name:"Staff",value:"staff"},{name:"Freelance",value:"freelance"}],$scope.publishedFilter="",$scope.publishedFilters=[{name:"All Content",value:""},{name:"Published",value:"published"}],$scope.reports={Contributions:{service:ContributionReportingService,headings:[{title:"Content ID",expression:"content.id"},{title:"Headline",expression:"content.title"},{title:"FeatureType",expression:"content.feature_type"},{title:"Contributor",expression:"user.payroll_name"},{title:"Role",expression:"role"},{title:"Pay",expression:"pay"},{title:"Date",expression:"content.published | date: 'MM/dd/yyyy'"}],downloadURL:"/cms/api/v1/contributions/reporting/",orderOptions:[{label:"Order by User",key:"user"},{label:"Order by Content",key:"content"}]},Content:{service:ContentReportingService,headings:[{title:"Content ID",expression:"id"},{title:"Headline",expression:"title"},{title:"Feature Type",expression:"feature_type"},{title:"Video",expression:"video_id"},{title:"Article Cost",expression:"value"},{title:"Date Published",expression:"published | date: 'MM/dd/yyyy'"}],orderOptions:[],downloadURL:"/cms/api/v1/contributions/contentreporting/"},"Freelance Pay":{service:FreelancePayReportingService,headings:[{title:"Contributor",expression:"contributor.full_name"},{title:"Contribution #",expression:"contributions_count"},{title:"Pay",expression:"pay"},{title:"Payment Date",expression:"payment_date | date: 'MM/dd/yyyy'"}],orderOptions:[],downloadURL:"/cms/api/v1/contributions/freelancereporting/"}},$scope.items=[],$scope.headings=[],$scope.orderOptions=[],$scope.startInitial=moment().startOf("month").format("YYYY-MM-DD"),$scope.endInitial=moment().endOf("month").format("YYYY-MM-DD"),$scope.reportParams={pageNumber:1,start:$scope.startInitial,end:$scope.endInitial},$scope.reportDisabled=!0,$scope.pageTotal=null,$scope.moreFilters=[],$scope.startOpen=!1,$scope.endOpen=!1,$scope.setReport=function($reportingService){$scope.reportDisabled===!0&&($scope.reportDisabled=!1),$scope.reportParams.pageNumber=1,$scope.report=$reportingService},$scope.setUserFilter=function(value){$scope.userFilter=value,loadReport($scope.report,$scope.reportParams.start,$scope.reportParams.end,$scope.orderBy)},$scope.setPublishedFilter=function(value){$scope.publishedFilter=value,"published"===value&&($scope.reportParams.end=moment().format("YYYY-MM-DD")),loadReport($scope.report,$scope.reportParams.start,$scope.reportParams.end,$scope.orderBy)},$scope.openStart=function($event){$event.preventDefault(),$event.stopPropagation(),$scope.startOpen=!0},$scope.openEnd=function($event){$event.preventDefault(),$event.stopPropagation(),$scope.endOpen=!0},$scope.orderingChange=function(){loadReport($scope.report,$scope.reportParams.start,$scope.reportParams.end,$scope.orderBy)},$scope.downloadIsValid=function(){return"undefined"!==$scope.report?!0:!1},$scope.$watch("report",function(report){report&&($scope.orderOptions=report.orderOptions,report.orderOptions.length>0?$scope.orderBy=report.orderOptions[0]:$scope.orderBy=null,$scope.headings=[],report.headings.forEach(function(heading){$scope.headings.push(heading.title)}),loadReport(report,$scope.reportParams.start,$scope.reportParams.end,$scope.orderBy))}),$scope.$watchCollection("[reportParams.start, reportParams.end]",function(params){if($scope.report){var start=params[0],end=params[1];loadReport($scope.report,start,end,$scope.orderBy)}}),$scope.goToPage=function(){loadReport($scope.report,$scope.reportParams.start,$scope.reportParams.end)}}),angular.module("bulbsCmsApp").controller("SponsormodalCtrl",function($scope,ContentFactory,article,Campaign){$scope.article=article,$scope.article.campaign?$scope.campaign=Campaign.$find($scope.article.campaign):$scope.campaign=null,$scope.updateArticle=function(selection){$scope.article.campaign=selection.value.id},$scope.searchCampaigns=function(searchTerm){return Campaign.simpleSearch(searchTerm)}}),angular.module("bulbsCmsApp").controller("TargetingCtrl",function($scope,$http,$window,$q,$location,tar_options,routes){$window.document.title=routes.CMS_NAMESPACE+" | Targeting Editor";var canceller;$scope.search=function(url){url&&("undefined"==typeof canceller?canceller=$q.defer():(canceller.resolve(),canceller=$q.defer()),$http({method:"GET",url:tar_options.endpoint,timeout:canceller.promise,params:{url:$scope.url}}).success(function(data){$scope.targetingArray=[];for(var k in data)$scope.targetingArray.push([k,data[k]])}).error(function(data,status,headers,config){404===status&&($scope.targetingArray=[],$scope.targetingArray.push(["",""]))}))},$scope.save=function(){var data={};for(var i in $scope.targetingArray)data[$scope.targetingArray[i][0]]=$scope.targetingArray[i][1];return $http({method:"POST",url:tar_options.endpoint+"?url="+$scope.url,data:data}).success(function(data){$scope.targetingArray=[];for(var k in data)$scope.targetingArray.push([k,data[k]])})},$scope.keyHandler=function(event,url){13===event.keyCode?this.search(url):27===event.keyCode&&(event.currentTarget.value="")};var search=$location.search();search&&search.url&&($scope.url=decodeURIComponent(search.url))}),angular.module("bulbsCmsApp").value("ARTICLE_TEMPORARY_URL_DAYS_VALID",7).value("ARTICLE_TEMPORARY_URL_BASE","http://0.0.0.0:9069/unpublished/").controller("TemporaryUrlModalCtrl",function($scope,$routeParams,ContentFactory,ARTICLE_TEMPORARY_URL_DAYS_VALID,ARTICLE_TEMPORARY_URL_BASE,_,moment){var content=ContentFactory.one("content",$routeParams.id);$scope.TEMP_LINK_DAYS_VALID=ARTICLE_TEMPORARY_URL_DAYS_VALID,$scope.TEMP_URL_BASE=ARTICLE_TEMPORARY_URL_BASE,$scope.tokens=[],content.getList("list_tokens").then(function(tokenList){$scope.tokens=tokenList;var expiredIndicies=[];_.each($scope.tokens,function(token,i){token.create_date=moment(token.create_date),token.expire_date=moment(token.expire_date),moment().isAfter(token.expire_date)?expiredIndicies.push(i):token.daysTillExpire=token.expire_date.diff(moment(),"days")+1});for(var i=expiredIndicies.length-1;i>=0;i--)$scope.tokens.splice(expiredIndicies[i],1)}),$scope.createToken=function(){var now=moment();ContentFactory.one("content",$routeParams.id).post("create_token",{create_date:now,expire_date:now.clone().add({days:ARTICLE_TEMPORARY_URL_DAYS_VALID})}).then(function(token){token.create_date=moment(token.create_date),token.expire_date=moment(token.expire_date),token.daysTillExpire=token.expire_date.diff(moment(),"days")+1,$scope.tokens.push(token),$scope.newestToken=token})}}),angular.module("bulbsCmsApp").controller("ThumbnailModalCtrl",function($scope,BettyCropper,$modalInstance,article){$scope.article=article,$scope.selectCustomThumbnail=function(){BettyCropper.upload().then(function(success){$scope.article.thumbnail_override=success},function(error){console.log(error)},function(progress){console.log(progress)})}}),angular.module("bulbsCmsApp").controller("TrashcontentmodalCtrl",function($scope,$http,$modalInstance,$,Login,articleId,Raven){$scope.deleteButton={idle:"Delete",busy:"Trashing",finished:"Trashed",error:"Error!"},$scope.trashContent=function(){return $http({method:"POST",url:"/cms/api/v1/content/"+articleId+"/trash/"})},$scope.trashCbk=function(trash_promise){trash_promise.then(function(result){console.log("trash success"),$scope.trashSuccessCbk(),$modalInstance.close()})["catch"](function(reason){return 404===reason.status?($scope.trashSuccessCbk(),void $modalInstance.close()):(Raven.captureMessage("Error Deleting Article",{extra:reason}),void $modalInstance.dismiss())})}}),angular.module("bulbsCmsApp").controller("UnpublishCtrl",function($scope,$http,$q){$scope.unpubButton={idle:"Unpublish",busy:"Unpublishing",finished:"Unpublished!",error:"Error"},$scope.unpublish=function(){return $http({url:"/cms/api/v1/content/"+$scope.article.id+"/publish/",method:"POST",data:{published:!1}})},$scope.unpublishCbk=function(unpub_promise){unpub_promise.then(function(result){$scope.publishSuccessCbk&&$scope.publishSuccessCbk({article:$scope.article,response:result.data})})["catch"](function(reason){$scope.publishSuccessCbk&&$scope.publishSuccessCbk({article:$scope.article,response:reason.data})})}}),angular.module("bulbsCmsApp").controller("VersionBrowserModalCtrl",function($scope,$modalInstance,_,moment,VersionStorageApi,FirebaseApi,FIREBASE_ARTICLE_MAX_VERSIONS){FirebaseApi.$authorize().then(function(){$scope.maxVersions=FIREBASE_ARTICLE_MAX_VERSIONS}),VersionStorageApi.$all().then(function(versions){$scope.versions=_.chain(versions).each(function(version){version.timestamp_display=moment(version.timestamp).format("MMM Do YYYY, h:mma")}).sortBy(function(version){return-version.timestamp}).value(),$scope.selectedVersion=$scope.versions[0],$scope.setPreview=function(version){$scope.selectedVersion=version},$scope.restoreSelected=function(){_.each($scope.selectedVersion.content,function(value,key){$scope.article[key]=value}),$scope.articleIsDirty=!0,$modalInstance.close()}})}),angular.module("bulbsCmsApp").controller("VideothumbnailmodalCtrl",function($scope,$http,$modalInstance,Zencoder,videoId,VIDEO_THUMBNAIL_URL,CUSTOM_VIDEO_POSTER_URL){function compilePosterUrl(thumbnail){return VIDEO_THUMBNAIL_URL.replace("{{video}}",videoId).replace("{{thumbnail}}",pad4(thumbnail))}function pad4(num){var s="0000"+num;return s.substr(s.length-4)}var DEFAULT_THUMBNAIL=4,MAX_THUMBNAIL=19;$scope.uploadedImage={id:null},$scope.mode="still",Zencoder.getVideo(videoId).then(function(response){$scope.video=response.data,"In Progress"===response.data.status?($scope.inProgress=!0,$scope.video.poster=$scope.video.poster||null):$scope.video.poster=$scope.video.poster||compilePosterUrl(DEFAULT_THUMBNAIL)}),$scope.$watch("video.poster",function(){if($scope.video&&$scope.video.poster){var defaultUrl=VIDEO_THUMBNAIL_URL.replace("{{video}}",videoId),thumbnailIndex=defaultUrl.indexOf("{{thumbnail}}");0===$scope.video.poster.indexOf(defaultUrl.substr(0,thumbnailIndex))?($scope.currentThumbnail=Number($scope.video.poster.substr(thumbnailIndex,4)),$scope.uploadedImage.id=null):$scope.currentThumbnail=!1}}),$scope.$watch("uploadedImage.id",function(){$scope.uploadedImage.id&&($scope.video.poster=CUSTOM_VIDEO_POSTER_URL.replace("{{ratio}}","16x9").replace("{{image}}",$scope.uploadedImage.id))}),$scope.nextThumb=function(){$scope.video.poster=compilePosterUrl($scope.currentThumbnail0?$scope.currentThumbnail-1:MAX_THUMBNAIL)},$scope.defaultThumb=function(){$scope.video.poster=compilePosterUrl(DEFAULT_THUMBNAIL)},$scope.setPoster=function(){Zencoder.setVideo($scope.video),$modalInstance.close($scope.video.poster)},$scope.reencode=function(){Zencoder.encode(videoId)}}),angular.module("bulbsCmsApp").factory("AdApi",function(Restangular,adApiConfig){return Restangular.withConfig(function(RestangularConfigurer){RestangularConfigurer.setBaseUrl(adApiConfig.baseUrl)})}).constant("adApiConfig",{baseUrl:"/ads"}),angular.module("bulbsCmsApp").factory("BadRequestInterceptor",function($q,$injector,routes){return{responseError:function(rejection){return $injector.invoke(function($modal){if(400===rejection.status){var detail=rejection.data||{something:["Something was wrong with your request."]};$modal.open({templateUrl:routes.PARTIALS_URL+"modals/400-modal.html",controller:"BadrequestmodalCtrl",resolve:{detail:function(){return detail}}})}}),$q.reject(rejection)}}}),angular.module("bulbsCmsApp").factory("BugReportInterceptor",function($q,$window,PNotify){return{responseError:function(rejection){if(rejection.status>=500){var stack={animation:!0,dir1:"up",dir2:"left"};new PNotify({title:"You found a bug!",text:"Looks like something just went wrong, and we need your help to fix it! Report it, and we'll make sure it never happens again.",type:"error",confirm:{confirm:!0,align:"left",buttons:[{text:"Report Bug",addClass:"btn-danger pnotify-report-bug",click:function(notice){notice.remove(),$window.showBugReportModal()}},{addClass:"hidden"}]},buttons:{sticker:!1},icon:"fa fa-bug pnotify-error-icon",addclass:"stack-bottomright",stack:stack})}return $q.reject(rejection)}}}),angular.module("bulbsCmsApp").config(function(RestangularProvider,bulbsApiConfig){RestangularProvider.setResponseExtractor(function(response,operation,what,url){var newResponse=response;return"getList"===operation&&"undefined"!=typeof response.results&&(newResponse=response.results,newResponse.metadata={count:response.count,next:response.next,previous:response.previous}),newResponse}),bulbsApiConfig.requestSuffix&&RestangularProvider.setRequestSuffix(bulbsApiConfig.requestSuffix)}).constant("bulbsApiConfig",{requestSuffix:"/"}),angular.module("bulbsCmsApp").factory("CmsNotificationsApi",function($q,ContentFactory){return ContentFactory.service("notifications")}),angular.module("bulbsCmsApp").service("CurrentUser",function(ContentFactory,$q){var userDefer=$q.defer(),$userPromise=userDefer.promise;this.data=[];var self=this;this.getItems=function(){ContentFactory.one("me").get().then(function(data){self.data=data,userDefer.resolve(data)})},this.getItems(),this.$retrieveData=function(){return $userPromise},this.$simplified=function(){return $userPromise.then(function(user){var displayName=user.first_name&&user.last_name?user.first_name+" "+user.last_name:user.email||user.username;return{id:user.id,displayName:displayName}})}}),angular.module("bulbsCmsApp").value("FIREBASE_URL","https://luminous-fire-8340.firebaseio.com/").value("FIREBASE_ROOT","a-site-is-not-configured").factory("FirebaseApi",function(FirebaseRefFactory,$firebase,$rootScope,$q,CurrentUser,FIREBASE_URL,FIREBASE_ROOT){var rootRef=FirebaseRefFactory.newRef(FIREBASE_URL+"sites/"+FIREBASE_ROOT),authDefer=$q.defer(),$authorize=authDefer.promise;$authorize["catch"](function(error){error&&console.error("Firebase login failed:",error)}),CurrentUser.$retrieveData().then(function(user){"firebase_token"in user&&user.firebase_token?rootRef.auth(user.firebase_token,function(error){error?authDefer.reject(error):authDefer.resolve(rootRef)}):authDefer.reject()});var connectedRef=FirebaseRefFactory.newRef(FIREBASE_URL+".info/connected");connectedRef.on("value",function(connected){connected.val()?$rootScope.$emit("firebase-reconnected"):$rootScope.$emit("firebase-disconnected"),$rootScope.$emit("firebase-connection-state-changed")});var $connection={onConnect:function(callback){return $rootScope.$on("firebase-reconnected",callback),$connection},onDisconnect:function(callback){return $rootScope.$on("firebase-disconnected",callback),$connection},onChange:function(callback){$rootScope.$on("firebase-connection-state-changed",callback)}};return{$authorize:function(){return $authorize},$connection:$connection}}),angular.module("bulbsCmsApp").value("FIREBASE_ARTICLE_MAX_VERSIONS",25).factory("FirebaseArticleFactory",function($q,$firebase,$routeParams,_,moment,FirebaseApi,CurrentUser,FIREBASE_ARTICLE_MAX_VERSIONS){var createArticle=function(rootRef,articleId){var articleRef=rootRef.child("articles/"+articleId),$activeUsers=$firebase(articleRef.child("users")).$asArray(),$versions=$firebase(articleRef.child("versions")).$asArray(),addCurrentUserToActiveUsers=function(){var registeredDeferred=$q.defer(),registeredPromise=registeredDeferred.promise;return CurrentUser.$simplified().then(function(user){$activeUsers.$add(user).then(function(userRef){userRef.onDisconnect().remove(),registeredDeferred.resolve(user)})["catch"](function(error){registeredDeferred.reject(error)})})["catch"](function(error){registeredDeferred.reject(error)}),registeredPromise},registerCurrentUserActive=function(){return FirebaseApi.$connection.onConnect(addCurrentUserToActiveUsers),addCurrentUserToActiveUsers()};return{ref:articleRef,$activeUsers:function(){return $activeUsers},$versions:function(){return $versions},$registerCurrentUserActive:registerCurrentUserActive,$createVersion:function(articleData){var createDefer=$q.defer(),$createPromise=createDefer.promise;return CurrentUser.$simplified().then(function(user){var numVersions=$versions.length;numVersions+1>FIREBASE_ARTICLE_MAX_VERSIONS&&_.chain($versions).sortBy(function(version){return version.timestamp}).every(function(version){return $versions.$remove(version),numVersions--,numVersions+1>FIREBASE_ARTICLE_MAX_VERSIONS});var versionData={timestamp:moment().valueOf(),user:user,content:articleData};$versions.$add(versionData).then(createDefer.resolve)["catch"](createDefer.reject)}),$createPromise}}};return{$retrieveArticle:function(articleId){var retrieveDeferred=$q.defer(),retrievePromise=retrieveDeferred.promise;return FirebaseApi.$authorize().then(function(rootRef){retrieveDeferred.resolve(createArticle(rootRef,articleId))})["catch"](function(error){retrieveDeferred.reject(error)}),retrievePromise},$retrieveCurrentArticle:function(){return this.$retrieveArticle($routeParams.id)}}}),angular.module("bulbsCmsApp").service("FirebaseRefFactory",function(Firebase){return{newRef:function(url){return new Firebase(url)}}}),angular.module("bulbsCmsApp").service("Gettemplate",function($templateCache,$q,$http){this.get=function(templateUrl){var template=$templateCache.get(templateUrl);if(template)return $q.when(template);var deferred=$q.defer();return $http.get(templateUrl,{cache:!0}).success(function(html){$templateCache.put(templateUrl,html),deferred.resolve(html)}),deferred.promise}}),angular.module("bulbsCmsApp").service("IfExistsElse",function($window,$http){this.ifExistsElse=function(restQ,propertiesToValues,existsCbk,elseCbk,errorCbk){restQ.then(function(data){for(var resList=data.results||data,j=0;jkeyTime}return pickForRemoval}).each(function(value,key){$window.localStorage.removeItem(key)});try{$window.localStorage.setItem(version.timestamp,JSON.stringify(version.content)),createDefer.resolve(version)}catch(error){console.log("Maybe you've been saving too much? Failed again at adding entry, no more retries: "+error),createDefer.reject("Maybe you've been saving too much? Failed again at adding entry, no more retries: "+error)}}}):createDefer.reject("You don't have local storage capabilities in your browser. Use a better browser."),createPromise},$versions:function(){var retrieveDefer=$q.defer(),retrievePromise=retrieveDefer.promise,versions=_.chain($window.localStorage).pick(function(stored,key){var keySplit=key.split(".");return 3===keySplit.length&&keySplit[0]===keyPrefixArticle&&keySplit[1]===$routeParams.id}).map(function(stored){return JSON.parse(stored)}).value();return retrieveDefer.resolve(versions),retrievePromise}}}),angular.module("bulbsCmsApp").service("Login",function($rootScope,$http,$cookies,$window,$,routes){return $rootScope.$watch(function(){return $cookies.csrftoken},function(newCsrf,oldCsrf){$http.defaults.headers.common["X-CSRFToken"]=newCsrf,$window.jqueryCsrfSetup&&$window.jqueryCsrfSetup()}),{login:function(username,password){var data=$.param({username:username,password:password});return $http({method:"POST",url:"/login/",data:data,headers:{"Content-Type":"application/x-www-form-urlencoded"}})}}}),angular.module("bulbsCmsApp").factory("openImageCropModal",function($modal,routes){var openImageCropModal=function(imageData,ratios){return $modal.open({templateUrl:routes.PARTIALS_URL+"image-crop-modal.html",controller:"ImageCropModalCtrl",resolve:{imageData:function(){return imageData},ratios:function(){return ratios||!1}},backdrop:"static"}).result};return openImageCropModal}),angular.module("bulbsCmsApp").factory("PermissionsInterceptor",function($q,$injector,routes){return{responseError:function(rejection){return rejection.config&&rejection.config.noPermissionIntercept?$q.when(rejection):($injector.invoke(function($modal){if(403===rejection.status)if(rejection.data&&rejection.data.detail&&rejection.data.detail.indexOf("credentials")>0)$modal.open({templateUrl:routes.PARTIALS_URL+"modals/login-modal.html",controller:"LoginmodalCtrl"});else{var detail=rejection.data&&rejection.data.detail||"Forbidden";$modal.open({templateUrl:routes.PARTIALS_URL+"modals/403-modal.html",controller:"ForbiddenmodalCtrl",resolve:{detail:function(){return detail}}})}}),$q.reject(rejection))}}}),angular.module("bulbsCmsApp").factory("TemporaryUrlModalOpener",function($modal,routes){var modal=null;return{open:function($scope,article){return modal&&modal.close(),modal=$modal.open({templateUrl:routes.PARTIALS_URL+"modals/temporary-url-modal.html",controller:"TemporaryUrlModalCtrl",scope:$scope,resolve:{article:function(){return article}}})}}}),angular.module("bulbsCmsApp").factory("VersionStorageApi",function($q,FirebaseApi,FirebaseArticleFactory,LocalStorageBackup,_){var firebaseAvailableDefer=$q.defer(),$firebaseAvailable=firebaseAvailableDefer.promise;FirebaseApi.$authorize().then(function(){firebaseAvailableDefer.resolve(FirebaseArticleFactory.$retrieveCurrentArticle())})["catch"](function(){firebaseAvailableDefer.reject()});var _omitter=_.memoize(function(value,key){return _.isFunction(value)||_.find(key,function(c){return"."===c||"#"===c||"$"===c||"/"===c||"["===c||"]"===c})},function(value,key){return[key,value]}),_deepScrub=function(obj){var clone,transValue;return _.isUndefined(obj)?clone=null:_.isPlainObject(obj)?(clone={},_.forOwn(obj,function(value,key){transValue=_deepScrub(value),_omitter(transValue,key)||(clone[key]=transValue)})):_.isArray(obj)?(clone=[],_.each(obj,function(value,key){transValue=_deepScrub(value),_omitter(transValue,key)||clone.push(transValue)})):clone=obj,clone},scrubArticle=function(articleData){return _deepScrub(articleData)};return{$create:function(rawArticleData,articleIsDirty){var articleData=scrubArticle(rawArticleData),createDefer=$q.defer(),createPromise=createDefer.promise;return $firebaseAvailable.then(function($currentArticle){articleIsDirty||$currentArticle.$versions().length<1?$currentArticle.$createVersion(articleData).then(function(versionData){createDefer.resolve(versionData)})["catch"](function(){createDefer.reject()}):createDefer.reject()})["catch"](function(){LocalStorageBackup.$versions().then(function(versions){articleIsDirty||versions.length<1?LocalStorageBackup.$create(articleData).then(function(versionData){createDefer.resolve(versionData)})["catch"](function(error){createDefer.reject(error)}):createDefer.reject()})}),createPromise},$all:function(){var allDefer=$q.defer(),allPromise=allDefer.promise;return $firebaseAvailable.then(function($currentArticle){$currentArticle.$versions().$loaded(function(versions){allDefer.resolve(versions)})})["catch"](function(){LocalStorageBackup.$versions().then(function(versions){allDefer.resolve(versions)})["catch"](function(error){allDefer.reject(error)})}),allPromise.then(function(versions){return _.sortBy(versions,function(version){return-version.timestamp})})}}}),angular.module("bulbsCmsApp").factory("VersionBrowserModalOpener",function($modal,routes){var modal=null;return{open:function($scope,article){return modal&&modal.close(),modal=$modal.open({templateUrl:routes.PARTIALS_URL+"modals/version-browser-modal.html",controller:"VersionBrowserModalCtrl",scope:$scope,size:"lg",resolve:{article:function(){return article}}})}}}),angular.module("bulbsCmsApp").service("Zencoder",function($http,$q,$modal,$,routes){function getNewVideoUploadCredentials(file){var data={name:file.name};data=$.param(data);var newVideoDeferred=$q.defer();return $http({method:"POST",url:newVideoUrl,data:data,headers:{"Content-Type":"application/x-www-form-urlencoded"}}).success(function(data){newVideoDeferred.resolve({file:file,attrs:data})}).error(function(data){newVideoDeferred.reject(data)}),newVideoDeferred.promise}function uploadToS3(videoObject){var s3deferred=$q.defer(),formData=new FormData;return formData.append("key",videoObject.attrs.key),formData.append("AWSAccessKeyId",videoObject.attrs.AWSAccessKeyId),formData.append("acl",videoObject.attrs.acl),formData.append("success_action_status",videoObject.attrs.success_action_status),formData.append("policy",videoObject.attrs.policy),formData.append("signature",videoObject.attrs.signature),formData.append("file",videoObject.file),$.ajax(videoObject.attrs.upload_endpoint,{processData:!1,contentType:!1,data:formData,type:"POST",xhr:function(){var req=$.ajaxSettings.xhr();return req&&req.upload.addEventListener("progress",function(e){var percent=e.loaded/e.total*100;s3deferred.notify(percent)},!1),req},success:function(data){s3deferred.resolve(videoObject)},error:function(data){s3deferred.reject(data)}}),s3deferred.promise}function encode(videoObject){var encodeDeferred=$q.defer();return $http({method:"POST",url:"/video/"+videoObject.attrs.id+"/encode"}).success(function(data){videoObject.attrs.encode_status_endpoints=data,_encodingVideos[videoObject.attrs.id]=videoObject.attrs,encodeDeferred.resolve(videoObject)}).error(function(data){encodeDeferred.reject(data)}),encodeDeferred.promise}var newVideoUrl="/video/new",fileInputId="#bulbs-cms-hidden-video-file-input",inputTemplate='';this.onVideoFileUpload=function(){var clickDeferred=$q.defer(); +angular.element(fileInputId).remove();var file,fileInput=angular.element(inputTemplate);return angular.element("body").append(fileInput),fileInput.click(),fileInput.unbind("change"),fileInput.bind("change",function(elem){0!==this.files.length?(file=this.files[0],file.size>1073741824&&clickDeferred.reject("Upload file cannot be larger than 1024MB."),0!==file.type.indexOf("video/")&&clickDeferred.reject("You must upload a video file.")):clickDeferred.reject("Please select a file."),getNewVideoUploadCredentials(file).then(uploadToS3).then(encode,angular.noop,function(uploadPercentComplete){clickDeferred.notify(uploadPercentComplete)}).then(function(videoObject){clickDeferred.resolve(videoObject)},function(error){clickDeferred.reject(error)})}),clickDeferred.promise},this.encode=function(videoId){encode({attrs:{id:videoId}})},this.openVideoThumbnailModal=function(videoId){return $modal.open({templateUrl:routes.PARTIALS_URL+"modals/video-thumbnail-modal.html",controller:"VideothumbnailmodalCtrl",resolve:{videoId:function(){return videoId}}})},this.getVideo=function(videoId){var url="/video/"+videoId;return $http({method:"GET",url:url})},this.setVideo=function(video){var url="/video/"+video.id,data=$.param(video);return $http({method:"POST",url:url,data:data,headers:{"Content-Type":"application/x-www-form-urlencoded"}})};var _encodingVideos={};this.encodingVideos=_encodingVideos}),angular.module("bulbsCmsApp").filter("truncateByCharacters",function(){return function(input,chars,breakOnWord){if(isNaN(chars))return input;if(0>=chars)return"";if(input&&input.length>=chars){if(input=input.substring(0,chars),breakOnWord)for(;" "===input.charAt(input.length-1);)input=input.substr(0,input.length-1);else{var lastspace=input.lastIndexOf(" ");-1!==lastspace&&(input=input.substr(0,lastspace))}return 1===chars?input+".":input+"..."}return input}}),angular.module("bulbsCmsApp").filter("truncateByWords",function(){return function(input,words){if(isNaN(words))return input;if(0>=words)return"";if(input){var inputWords=input.split(/\s+/);inputWords.length>words&&(input=inputWords.slice(0,words).join(" ")+"...")}return input}}),angular.module("bulbsCmsApp").filter("tzDate",function(dateFilter,moment,TIMEZONE_NAME){return function(input,format){if(!input)return"";var inDate=moment.tz(input,TIMEZONE_NAME),newdate=inDate.format("YYYY-MM-DDTHH:mm"),formattedDate=dateFilter(newdate,format);return format.toLowerCase().indexOf("h")>-1&&(formattedDate+=" "+inDate.format("z")),formattedDate}}),angular.module("bulbsCmsApp").filter("user",function(){return function(user){return user?user.full_name?user.full_name:user.first_name&&user.last_name?user.first_name+" "+user.last_name:user.username:""}}); +//# sourceMappingURL=scripts.min.js.1456334137417.map \ No newline at end of file diff --git a/dist/scripts/templates.js b/dist/scripts/templates.js index bb9f92177..f1205a8c0 100644 --- a/dist/scripts/templates.js +++ b/dist/scripts/templates.js @@ -3,4 +3,4 @@ $templateCache.put("/views/encode-status.html",'

    Targeting Editor

    '),$templateCache.put("/views/targeting.html",'
    KeyValue
    '),$templateCache.put("/views/textlike-autocomplete-field.html",'

    {{model}}
    '),$templateCache.put("/views/toolbar.html",''),$templateCache.put("/views/video-field.html",'
    60% Complete
    '),$templateCache.put("/components/autocomplete-basic/autocomplete-basic.html",'
    {{ itemDisplayFormatter({item: currentSelection}) }}
    No results found
    '),$templateCache.put("/components/betty-editable/betty-editable.html",'
    '),$templateCache.put("/components/bug-reporter/bug-reporter-button.html",'
    '),$templateCache.put("/components/campaigns/campaigns-edit/campaigns-edit-sponsor-pixel/campaigns-edit-sponsor-pixel.html",'
    '),$templateCache.put("/components/campaigns/campaigns-edit/campaigns-edit.html",'

    Campaigns > New Campaign {{ model.campaignLabel }}

    Sponsor Pixels
    '),$templateCache.put("/components/campaigns/campaigns-list/campaigns-list-page.html","
    "),$templateCache.put("/components/campaigns/campaigns-list/campaigns-list.html",'
    CampaignSponsorStart DateEnd DateTools
    {{ campaign.campaignLabel }}{{ campaign.sponsorName }}{{ campaign.startDate | momentFormatter : \'MM/DD/YY\' }}{{ campaign.endDate | momentFormatter : \'MM/DD/YY\' }}
    No campaigns, click "Add Campaign" below to add the first one!
    '),$templateCache.put("/components/confirmation-modal/confirmation-modal.html",""),$templateCache.put("/components/custom-search/custom-search-content-item/custom-search-content-item.html",'
    Article ID: {{ model.id }} | {{ model.feature_type }}
    {{ model.title }}
    Published
    {{ model.published | date : \'M/d/yyyy, h:mm a\' }}
    '),$templateCache.put("/components/custom-search/custom-search-group/custom-search-group-condition/custom-search-group-condition.html",'
    {{ value.name }}
    '),$templateCache.put("/components/custom-search/custom-search-group/custom-search-group.html",'
    Total Results from this Group: {{ controllerService.groupsResultCountGet(groupIndex) }}
    '),$templateCache.put("/components/custom-search/custom-search-simple-content-search/custom-search-simple-content-search.html",'
    Manually Add Article to List
    '),$templateCache.put("/components/custom-search/custom-search.html",'

    Current List Based on Above Parameters Total Results in List: {{ customSearchService.content.count }}
    '),$templateCache.put("/components/editors-pick/editors-pick.html","

    Editors Pick

    "),$templateCache.put("/components/filter-list-widget/filter-list-widget.html",'
    {{queryToLabelMappings[f.query]}}
    Clear filters
    "),$templateCache.put("/components/filter-widget/filter-widget.html",'
    {{queryToLabelMappings[f.query]}}
    Clear filters
    "),$templateCache.put("/components/generic-ajax-button/generic-ajax-button.html","'),$templateCache.put("/components/polls/polls-edit/polls-edit.html",'

    Responses

    '), $templateCache.put("/components/polls/polls-list/polls-list-page.html","
    "),$templateCache.put("/components/promoted-content/promoted-content-article/promoted-content-article.html",'

    · No type set
    Not published

    '),$templateCache.put("/components/promoted-content/promoted-content-list/promoted-content-list.html",'

    Content List
    on {{ pzoneData.previewTime.toDate() | date: \'MMM d, yyyy @ h:mma\' }} Now

    Viewing a past list, past lists cannot be modified.
    Select an item below to finish your {{ pzoneData.action }} operation.
    {{ pzoneData.selectedPZone.zone_length - pzoneData.selectedPZone.content.length }} spots left
    • All {{ pzoneData.selectedPZone.zone_length }} spots filled, content below will not display
      {{ pzoneData.selectedPZone.zone_length - pzoneData.selectedPZone.content.length }} spots left
    '),$templateCache.put("/components/promoted-content/promoted-content-operations-list/promoted-content-operations-list.html",'

    Schedule {{ pzoneData.selectedPZone.name }}

    From: to:
    {{ deleteStatus.message }} Dismiss
    • {{ group[0].format(groupDateFormat) }} ({{ group[1].length }} Events)
      • {{ operation.cleanType }} @ position {{operation.index + 1}}
      Loading operations...
      '),$templateCache.put("/components/promoted-content/promoted-content-pzone-select/promoted-content-pzone-select.html",'
      Loading {{ selectedPZoneName }}...
      '),$templateCache.put("/components/promoted-content/promoted-content-save/promoted-content-save.html",'
      {{ pzoneData.unsavedOperations.length }} Unsaved Operation Operations'),$templateCache.put("/components/promoted-content/promoted-content-search/promoted-content-search.html",'

      Search Content

      '),$templateCache.put("/components/promoted-content/promoted-content-time-picker/promoted-content-time-picker.html",'
      '),$templateCache.put("/components/promoted-content/promoted-content.html",'

      Promoted Content

      '),$templateCache.put("/components/reporting/reporting-line-items-edit/reporting-line-items-edit.html",'

      Line Items > New Line Item Edit Line Item

      '),$templateCache.put("/components/reporting/reporting-line-items-list/reporting-line-items-list.html",'
      '),$templateCache.put("/components/reporting/reporting-rate-overrides-edit/reporting-rate-overrides-edit.html",'

      Edit Rate Override

      $
      '),$templateCache.put("/components/reporting/reporting-rate-overrides-list/reporting-rate-overrides-list.html",'
      '),$templateCache.put("/components/reporting/reporting-roles-edit/reporting-roles-edit.html",'

      Roles > New Role {{ model.name }}

      Feature TypesRates
      {{ rate.featureType }}
      '),$templateCache.put("/components/reporting/reporting-roles-list/reporting-roles-list.html",'
      '),$templateCache.put("/components/sections/sections-edit/sections-edit-page.html",""),$templateCache.put("/components/sections/sections-edit/sections-edit.html",'

      Sections > New Section {{ model.name }}

      {{ LIST_URL }}
      '),$templateCache.put("/components/sections/sections-list/sections-list-page.html",'
      '),$templateCache.put("/components/sections/sections-list/sections-list.html",'
      Section NameArticle CountTools
      {{ item.name }}{{ item.$resultCount }}
      No section, click "Add Section" below to add the first one!
      '),$templateCache.put("/components/special-coverage/special-coverage-edit/special-coverage-edit-page.html",""),$templateCache.put("/components/special-coverage/special-coverage-edit/special-coverage-edit.html",'

      Special Coverage Lists > New Special Coverage {{ model.name }}

      {{ LIST_URL }}
      3x1 Image, 900px wide

      Content List

      Video Playlist

      '),$templateCache.put("/components/special-coverage/special-coverage-list/special-coverage-list-page.html","
      "),$templateCache.put("/components/special-coverage/special-coverage-list/special-coverage-list.html",'
      List TitleSponsorCampaignStatusTools
      {{ item.name }}{{ item.campaign.sponsorName }}{{ item.campaign.campaignLabel }}{{ item.$activeState() }}
      No special coverages, click "Add Special Coverage" below to add the first one!
      '), $templateCache.put("/components/status-filter/status-filter.html",''),$templateCache.put("/components/template-type-field/template-type-field.html",'
      '),$templateCache.put("/components/top-bar/top-bar-base.html",''),$templateCache.put("/shared/copy-button/copy-button.html",' '),$templateCache.put("/shared/list-page/list-page.html",'

      {{ namePlural }}

      {{ field.title }}
      {{ field.evaluate(item) }}
      No {{ namePlural }}, click "Add {{ name }}" below to add the first {{ name }}!
      '),$templateCache.put("/shared/video-list/video-list-video/video-list-video.html","
      Video ID: {{ model.id }} | {{ model.channel.name }}
      {{ model.title }}
      Published
      {{ (model.published | date_string_to_moment).format('M/D/YYYY, h:mma') }}
      "),$templateCache.put("/shared/video-list/video-list.html",'
      Current List Items in List: {{ videos.length }}
      There are no videos in this list, search for a video to add to playlist.
      ')}]); -//# sourceMappingURL=templates.js.1456263459616.map \ No newline at end of file +//# sourceMappingURL=templates.js.1456334137288.map \ No newline at end of file