diff --git a/dist/scripts/scripts.js b/dist/scripts/scripts.js index 39eb95f6c..ea1a375a9 100644 --- a/dist/scripts/scripts.js +++ b/dist/scripts/scripts.js @@ -1,2 +1,2 @@ "use strict";angular.module("underscore",[]).value("_",window._),angular.module("NProgress",[]).value("NProgress",window.NProgress),angular.module("URLify",[]).value("URLify",window.URLify),angular.module("jquery",[]).value("$",window.$),angular.module("bulbsCmsApp",["ngCookies","ngResource","ngSanitize","ngRoute","ui.bootstrap","jquery","underscore","NProgress","URLify"]).config(["$locationProvider","$routeProvider","$sceProvider","routes",function($locationProvider,$routeProvider,$sceProvider,routes){$locationProvider.html5Mode(!0),$routeProvider.when("/cms/app/list/:queue/",{templateUrl:routes.PARTIALS_URL+"contentlist.html",controller:"ContentlistCtrl",reloadOnSearch:!1}).when("/cms/app/edit/:id/",{templateUrl:routes.PARTIALS_URL+"contentedit.html",controller:"ContenteditCtrl"}).when("/cms/app/promotion/",{templateUrl:routes.PARTIALS_URL+"promotion.html",controller:"PromotionCtrl",reloadOnSearch:!1}).when("/cms/app/targeting/",{templateUrl:routes.PARTIALS_URL+"targeting-editor.html",controller:"TargetingCtrl"}).when("/cms/app/pzones/",{templateUrl:routes.PARTIALS_URL+"pzones.html",controller:"PzoneCtrl"}).otherwise({redirectTo:"/cms/app/list/published/"}),$sceProvider.enabled(!1)}]).config(["$provide",function($provide){$provide.decorator("$exceptionHandler",function($delegate){return function(exception,cause){$delegate(exception,cause),window.Raven.captureException(exception)}})}]).run(["$rootScope","$http","$cookies",function($rootScope,$http,$cookies){$http.defaults.headers.post["X-CSRFToken"]=$cookies.csrftoken}]),angular.module("bulbsCmsApp").controller("ContentlistCtrl",["$scope","$http","$timeout","$location","$routeParams","$window","$","_","Contentlist",function($scope,$http,$timeout,$location,$routeParams,$window,$,_,Contentlist){function updateIsMyStuff(){if(!$location.search().authors)return void($scope.myStuff=!1);var authors=$location.search().authors;"string"==typeof authors&&(authors=[authors]),$scope.myStuff=1===authors.length&&authors[0]===$window.current_user?!0:!1}$window.document.title="AVCMS | Content",$scope.search=$location.search().search,$scope.queue=$routeParams.queue||"all",$scope.articles=[{id:-1,title:"Loading"}],$scope.myStuff=!1,updateIsMyStuff(),$scope.$on("$routeUpdate",function(){updateIsMyStuff()}),$scope.$watch("myStuff",function(){$scope.myStuff?$("#meOnly").bootstrapSwitch("setState",!0,!0):$("#meOnly").bootstrapSwitch("setState",!1,!0)}),$("#meOnly").on("switch-change",function(e,data){var value=data.value;value===!0?($location.search().authors=[$window.current_user],$scope.getContent()):value===!1&&(delete $location.search().authors,$scope.getContent())});var url="/cms/api/v1/content/";if("all"!==$scope.queue){var statusMappings={published:"before="+moment().format("YYYY-MM-DDTHH:mmZ"),waiting:"status=Waiting for Editor",draft:"status=Draft",scheduled:"after="+moment().format("YYYY-MM-DDTHH:mmZ")};url="/cms/api/v1/content/?"+statusMappings[$scope.queue]}Contentlist.setUrl(url);var getContentCallback=function($scope,data){$scope.articles=data.results,$scope.totalItems=data.count};$scope.getContent=function(){Contentlist.getContent($scope,getContentCallback)},$scope.getContent(),$scope.goToPage=function(page){$location.search(_.extend($location.search(),{page:page})),$scope.getContent()},$scope.sort=function(sort){$location.search().ordering&&0===$location.search().ordering.indexOf(sort)&&(sort="-"+sort),$location.search(_.extend($location.search(),{ordering:sort})),$scope.getContent()},$scope.publishSuccessCbk=function(article,data){var i;for(i=0;i<$scope.articles.length&&$scope.articles[i].id!==article.id;i++);for(var field in data)$scope.articles[i][field]=data[field]},$scope.trashSuccessCbk=function(){$timeout(function(){$scope.getContent(),$("#confirm-trash-modal").modal("hide")},1500)},$(".expcol").click(function(e){e.preventDefault();var nS="1"===$(this).attr("state")?"0":"1",i=nS?"minus":"plus",t=nS?"Collapse":"Expand",tP=$($(this).attr("href")).find(".panel-collapse");tP.collapse("0"===$(this).attr("state")?"show":"hide"),$(this).html(' '+t+" all"),$(this).attr("state",nS)}),$("#meOnly").bootstrapSwitch()}]).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("ContenteditCtrl",["$scope","$routeParams","$http","$window","$location","$timeout","$compile","$q","$","IfExistsElse","PARTIALS_URL","CONTENT_PARTIALS_URL","CACHEBUSTER","MEDIA_ITEM_PARTIALS_URL",function($scope,$routeParams,$http,$window,$location,$timeout,$compile,$q,$,IfExistsElse,PARTIALS_URL,CONTENT_PARTIALS_URL,CACHEBUSTER,MEDIA_ITEM_PARTIALS_URL){function mediaItemExistsCbkFactory(index){return function(media_item){$scope.article.ratings[index].media_item=media_item,$scope.mediaItemCallbackCounter-=1}}function mediaItemDoesNotExistCbkFactory(index){return function(){saveMediaItem(index)}}function saveMediaItem(index){var type=$scope.article.ratings[index].type,media_item=$scope.article.ratings[index].media_item,url="/reviews/api/v1/"+type+"/",method="POST";media_item.id&&(url+=media_item.id+"/",method="PUT"),$http({url:url,method:method,data:media_item}).success(function(resp){$scope.article.ratings[index].media_item=resp,$scope.mediaItemCallbackCounter-=1}).error(saveArticleErrorCbk)}function saveToContentApi(){$("#save-article-btn").html(" Saving"),$http({url:"/cms/api/v1/content/"+($scope.article.id||"")+"/",method:"PUT",data:$scope.article}).success(saveArticleSuccessCbk).error(saveArticleErrorCbk)}function saveArticleErrorCbk(data,status){return 403===status?($scope.showLoginModal(),void $("#save-article-btn").html("Save")):($("#save-article-btn").html(" Error!"),400===status&&($scope.errors=data),void $scope.saveArticleDeferred.reject())}function saveArticleSuccessCbk(resp){$("#save-article-btn").html(" Saved!"),setTimeout(function(){$("#save-article-btn").html("Save")},1e3),$scope.article=resp,$scope.errors=null,$location.search("rating_type",null),dirtGone(),$scope.saveArticleDeferred.resolve(resp)}function getArticle(callback){$http({url:"/cms/api/v1/content/"+$routeParams.id+"/",method:"GET"}).success(function(data){$scope.article=data,$window.article=$scope.article,callback&&callback(data)}).error(function(data,status){$scope.errors=$scope.errors||{},500===status&&($scope.errors["Server Error"]=$scope.errors["Server Error"]||[],$scope.errors["Server Error"].push("There was a problem with the content API."))})}function waitForDirt(){$(".edit-page").one("change input","input,div.editor",function(){window.onbeforeunload=function(){return"You have unsaved changes. Leave anyway?"}})}function dirtGone(){window.onbeforeunload=function(){}}$scope.CONTENT_PARTIALS_URL=CONTENT_PARTIALS_URL,$scope.MEDIA_ITEM_PARTIALS_URL=MEDIA_ITEM_PARTIALS_URL,$scope.CACHEBUSTER=CACHEBUSTER,$scope.$watch(function(){return"AVCMS | Editing "+($scope.article&&$(""+$scope.article.title+"").text())||""},function(newTitle){$window.document.title=newTitle}),$("body").removeClass();var nav=$($compile($("#edit-page-nav-bar-template").html())($scope));$("ul.edit-page-nav").html(nav),$("ul.nav").show(),$scope.tagDisplayFn=function(o){return o.name},$scope.tagCallback=function(o,input,freeForm){var tagVal=freeForm?o:o.name;IfExistsElse.ifExistsElse("/cms/api/v1/tag/?ordering=name&search="+encodeURIComponent(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){403===status&&$scope.showLoginModal()}),$(input).val("")},$scope.sectionCallback=function(o,input,freeForm){var tagVal=freeForm?o:o.name;IfExistsElse.ifExistsElse("/cms/api/v1/tag/?ordering=name&search="+encodeURIComponent(tagVal),{name:tagVal},function(tag){$scope.article.tags.push(tag)},function(){console.log("Can't create sections.")},function(data,status){403===status&&$scope.showLoginModal()}),$(input).val("")},$scope.removeTag=function(e){var tag=$(e.target).parents("[data-tag]").data("tag"),id=tag.id,newtags=[];for(var i in $scope.article.tags)$scope.article.tags[i].id!==id&&newtags.push($scope.article.tags[i]);$scope.article.tags=newtags},$scope.removeAuthor=function(e){var author=$(e.target).parents("[data-author]").data("author"),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},$scope.featureTypeDisplayFn=function(o){return o.name},$scope.featureTypeCallback=function(o,input,freeForm){var fVal=freeForm?o:o.name;IfExistsElse.ifExistsElse("/cms/api/v1/things/?type=feature_type&q="+encodeURIComponent(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){403===status&&$scope.showLoginModal()})},$scope.authorDisplayFn=function(o){return o.first_name&&o.last_name&&o.first_name+" "+o.last_name||"username: "+o.username},$scope.authorCallback=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.saveArticleDeferred=$q.defer(),$scope.mediaItemCallbackCounter=void 0,$scope.$watch("mediaItemCallbackCounter",function(){0===$scope.mediaItemCallbackCounter&&saveToContentApi()}),$scope.saveArticle=function(){var data=$scope.article;$scope.article.title=$scope.editors.content_title_editor.getContent(),"Published"!==$scope.article.status&&($scope.article.slug=$window.URLify($scope.article.title,50)),$scope.article.subhead=$scope.editors.content_subhead_editor.getContent(),$scope.editors.content_body_editor&&($scope.article.body=$scope.editors.content_body_editor.getContent()),$scope.mediaItemCallbackCounter=data.ratings&&data.ratings.length||saveToContentApi();for(var i in data.ratings){var show;if("tvseason"===data.ratings[i].type){var identifier=data.ratings[i].media_item.identifier;show=data.ratings[i].media_item.show,IfExistsElse.ifExistsElse("/reviews/api/v1/tvseason/?season="+identifier+"&show="+encodeURIComponent(show),{identifier:identifier,show:show},mediaItemExistsCbkFactory(i),mediaItemDoesNotExistCbkFactory(i),saveArticleErrorCbk)}else if("tvepisode"===data.ratings[i].type){show=data.ratings[i].media_item.show;var season=data.ratings[i].media_item.season,episode=data.ratings[i].media_item.episode;IfExistsElse.ifExistsElse("/reviews/api/v1/tvepisode/?show="+encodeURIComponent(show)+"&season="+season+"&episode="+episode,{show:show,season:season,episode:episode},mediaItemExistsCbkFactory(i),mediaItemDoesNotExistCbkFactory(i),saveArticleErrorCbk)}else saveMediaItem(i)}return $scope.saveArticleDeferred.promise},$scope.displayAuthorAutocomplete=function(obj){return obj.first_name+" "+obj.last_name},getArticle(function(data){$window.cock=data,!$location.search().rating_type||data.ratings&&0!==data.ratings.length||($scope.article.ratings=[{type:$location.search().rating_type}]),$scope.$watch("article.detail_image.id",function(newVal,oldVal){$scope.article&&(newVal&&oldVal&&newVal===oldVal||null!==newVal&&(!$scope.article.image||!$scope.article.image.id||newVal&&oldVal&&$scope.article.image&&$scope.article.image.id&&oldVal===$scope.article.image.id||!oldVal&&newVal)&&($scope.article.image={id:newVal,alt:null,caption:null}))})}),waitForDirt(),$("#extra-info-modal").on("shown.bs.modal",function(){$window.picturefill()}),$scope.initEditor=function(name,id,options,articleField){$scope.editors=$scope.editors||{},$scope.editors[name]=new window.Editor(options),angular.element(id+" .editor").bind("input",function(){$scope.article[articleField]=$scope.editors[name].getContent()})},$window.initEditor=$scope.initEditor,$scope.$on("$destroy",function(){for(var editor in $scope.editors)$scope.editors[editor].destroy()}),$scope.addRating=function(type){$scope.article.ratings.push({grade:"",type:type,media_item:{type:type}}),$("#add-review-modal").modal("hide")},$scope.deleteRating=function(index){$scope.article.ratings.splice(index,1)},$scope.publishSuccessCbk=function(){getArticle()},$scope.trashSuccessCbk=function(){$timeout(function(){$window.history.back()},1500)}}]),angular.module("bulbsCmsApp").controller("NavCtrl",["$scope","$location","$",function($scope,$location,$){$scope.isEditPage=0===$location.path().indexOf("/cms/app/edit/")?!0:!1,console.log("is Edit Page: "+$scope.isEditPage),$scope.isEditPage||$("ul.nav").show(),$scope.isActive=function(viewLocation){return 0===$location.path().indexOf(viewLocation)}}]),angular.module("bulbsCmsApp").controller("PromotionCtrl",["$scope","$http","$window","$","Contentlist","promo_options",function($scope,$http,$window,$,Contentlist,promo_options){$window.document.title=promo_options.namespace+" | Promotion Tool",$scope.getPzones=function(url){$http({method:"GET",url:url}).success(function(data){$scope.pzones=data.results,$scope.pzone=data.results[0],$scope.$watch("pzone",function(pzone){$scope.promotedArticles=pzone.content.length?pzone.content.slice(0):[{hey_checkthis:!0,title:"Nothing Promoted!",feature_type:"Click an article on the right and use 'Insert'"}]})}).error(function(){alert("Content list does not exist.")})},Contentlist.setUrl("/cms/api/v1/content/?published=True");var getContentCallback=function($scope,data){$scope.articles=data.results,$scope.totalItems=data.count};$scope.getContent=function(){Contentlist.getContent($scope,getContentCallback)},$scope.$on("$viewContentLoaded",function(){$scope.getPzones(promo_options.endpoint),$scope.getContent()}),$scope.articleIsInPromotedArticles=function(id){if($scope.promotedArticles)for(var i in $scope.promotedArticles)if($scope.promotedArticles[i].id===id)return!0;return!1};var pA=$(".promotion-area"),pC=$(".promotion-container");$scope.insertArticleMode=function(article){$scope.selectedArticle=article,pA.addClass("select-mode"),pC.off("click"),pC.on("click",".promotion-area.select-mode .article-container",function(){var index=$(this).parents("[data-index]").data("index")-0;$scope.insertArticle(index),pA.removeClass("select-mode"),$scope.$apply()})},$scope.insertArticle=function(index){var limit=promo_options.upper_limits[$scope.pzone.name];$scope.promotedArticles[index]&&$scope.promotedArticles[index].id?$scope.promotedArticles.splice(index,0,$scope.selectedArticle):$scope.promotedArticles.splice(index,1,$scope.selectedArticle),limit&&$scope.promotedArticles.length>limit&&$scope.promotedArticles.pop($scope.promotedArticles.length)},$scope.replaceArticleMode=function(article){$scope.selectedArticle=article,pA.addClass("select-mode"),pC.off("click"),pC.on("click",".promotion-area.select-mode .article-container",function(){var index=$(this).parents("[data-index]").data("index");$scope.replaceArticle(index),pA.removeClass("select-mode"),$scope.$apply()})},$scope.replaceArticle=function(index){$scope.promotedArticles.splice(index,1,$scope.selectedArticle)},$scope.save=function(){var items=$scope.promotedArticles.slice(0);items[0].id||items.shift(),$(".save-button").html(' Saving');var payload=$scope.pzone;payload.content=$scope.promotedArticles[0].hey_checkthis?[]:$scope.promotedArticles,$http({method:"PUT",url:promo_options.endpoint+$scope.pzone.id+"/",data:payload}).success(function(data){$scope.pzone.content=data.content,$(".save-button").removeClass("btn-danger").addClass("btn-success").html(' Saved'),window.setTimeout(function(){$(".save-button").html("Save")},2e3)}).error(function(){$(".save-button").removeClass("btn-success").addClass("btn-danger").html(' Error'),window.setTimeout(function(){$(".save-button").html("Save")},2e3)})},$scope.moveUp=function(index){if(0!==index){var toMove=$scope.promotedArticles[index];$scope.promotedArticles[index]=$scope.promotedArticles[index-1],$scope.promotedArticles[index-1]=toMove}},$scope.moveDown=function(index){if(index!==$scope.promotedArticles.length-1){var toMove=$scope.promotedArticles[index];$scope.promotedArticles[index]=$scope.promotedArticles[index+1],$scope.promotedArticles[index+1]=toMove}},$scope.remove=function(index){$scope.promotedArticles.splice(index,1)},$("body").on("shown.bs.collapse","#page-prev .collapse",function(){$window.picturefill()})}]),angular.module("bulbsCmsApp").controller("PzoneCtrl",["$scope","$http","$window","$","Contentlist","routes",function($scope,$http,$window,$,Contentlist,routes){function getPzone(){$http({method:"GET",url:"/promotions/api/pzone/"+$scope.pzoneName+"/"}).success(function(data){$scope.pzone=data}).error(function(){console.log("Zone does not exist.")})}$window.document.title="AVCMS | Pzone Editor",$scope.pzoneName="homepage-one",$scope.newContentId=null,$scope.$watch("pzoneName",function(){getPzone()}),$scope.typeChanged=function(){console.log("Type changed!"),void 0!==$scope.pzone&&($scope.pzone.data={})},Contentlist.setUrl("/cms/api/v1/content/?published=True");var getContentCallback=function($scope,data){$scope.articles=data.results,$scope.totalItems=data.count};$scope.getContent=function(){Contentlist.getContent($scope,getContentCallback)},$scope.getContent(),$scope.getPZoneTemplate=function(){return routes.PARTIALS_URL+"pzones/"+$scope.pzone.zone_type+".html"},$scope.remove=function(contentId){var index=$scope.pzone.data.content_ids.indexOf(contentId);-1!==index&&$scope.pzone.data.content_ids.splice(index,1)},$scope.add=function(prepend){void 0===$scope.pzone.data.content_ids&&($scope.pzone.data.content_ids=[]),prepend&&$scope.newContentIdPrepend?$scope.pzone.data.content_ids.unshift($scope.newContentIdPrepend):$scope.newContentId&&$scope.pzone.data.content_ids.push($scope.newContentId),$scope.newContentId=null,$scope.newContentIdPrepend=null},$scope.save=function(){$("#save-pzone-btn").html(' Saving'),$http({method:"PUT",url:"/promotions/api/pzone/"+$scope.pzoneName+"/",data:$scope.pzone}).success(function(){$("#save-pzone-btn").html(' Saved!'),window.setTimeout(function(){$("#save-pzone-btn").html("Save")},2e3)}).error(function(){$("#save-pzone-btn").html(' Saved!'),window.setTimeout(function(){$("#save-pzone-btn").html("Save")},2e3)})}}]),angular.module("bulbsCmsApp").controller("TargetingCtrl",["$scope","$http","$window","$q","$location","tar_options","NProgress",function($scope,$http,$window,$q,$location,tar_options,NProgress){$window.document.title=tar_options.namespace+" | Targeting Editor",NProgress.configure({minimum:.4});var canceller;$scope.search=function(url){url&&("undefined"==typeof canceller?canceller=$q.defer():(canceller.resolve(),NProgress.set(0),canceller=$q.defer()),NProgress.start(),$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]]);NProgress.done()}).error(function(data,status){404==status&&($scope.targetingArray=[],$scope.targetingArray.push(["",""]),NProgress.done())}))},$scope.save=function(){var data={};for(var i in $scope.targetingArray)data[$scope.targetingArray[i][0]]=$scope.targetingArray[i][1];NProgress.start(),$http({method:"POST",url:tar_options.endpoint+"?url="+$scope.url,data:data}).success(function(){NProgress.done()}).error(function(){NProgress.done()})},$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").service("IfExistsElse",["$window","$http",function($window,$http){this.ifExistsElse=function(resourceUrl,propertiesToValues,existsCbk,elseCbk,errorCbk){$http({url:resourceUrl,method:"GET"}).success(function(data){var allFieldsMatch,resList=data.results||data;for(var j in resList){allFieldsMatch=!0;for(var property in propertiesToValues)if(resList[j][property]!==propertiesToValues[property]){allFieldsMatch=!1;break}if(allFieldsMatch)return void existsCbk(resList[j])}elseCbk(propertiesToValues)}).error(errorCbk)}}]),angular.module("bulbsCmsApp").service("Contentlist",["$http","$location","$timeout","$window",function($http,$location,$timeout,$window){this.url="/cms/api/v1/content",this.setUrl=function(url){this.url=url},this.getContent=function($scope,callback){var params={};for(var p in $location.search()){var value=$location.search()[p];"false"!==value&&"undefined"!==value&&""!==value&&(params[p]=value)}$location.search(params),params={};for(var k in $location.search())params[k]=$location.search()[k];$scope.params=params,$scope.currentPage=params.page||1,$scope.articles=[{id:-1,title:"Loading"}],$window.NProgress.configure({minimum:.4}),$window.NProgress.start(),$http({method:"GET",url:this.url,params:params}).success(function(data){$window.NProgress.done(),callback($scope,data)}).error(function(data,status){if(403===status){var path=$location.path();$window.location.href=$window.location.origin+"/login?next="+path}})}}]),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").directive("articlecontainer",["routes","LOADING_IMG_SRC",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("bulbsAutocomplete",["$http","$location","$compile","$timeout","$",function($http,$location,$compile,$timeout,$){return{restrict:"A",scope:!0,link:function(scope,element,attrs){function getAutocompletes(val){$timeout.cancel(inputTimeout),inputCounter=0,$http({method:"GET",url:attrs.resourceUrl+val}).success(function(data){var results=data.results||data;scope.autocomplete_list=results.splice(0,5)}).error(function(data,status){403===status&&scope.showLoginModal()})}scope.displayfn=scope[attrs.displayfn],scope.callback=scope[attrs.callback];var $elem=$(element).find("input");$elem.attr("autocomplete","off");var dropdown=$($compile($("#autocomplete-dropdown-template").html())(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){$(dropdown).css({top:newValue.top,left:newValue.left,minWidth:newValue.minWidth})},!0);var inputTimeout,inputCounter=0;$elem.on("focus",function(){$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")}),scope.blurTimeout,$elem.on("blur",function(){$(dropdown).fadeOut("fast")}),$(dropdown).on("mouseover",".entry",function(){$(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.callback(o,$elem,freeForm||!1),scope.autocomplete_list=[]}}}}]),angular.module("bulbsCmsApp").directive("bettyimage",["$http","routes",function($http,routes){return{replace:!0,restrict:"E",templateUrl:routes.PARTIALS_URL+"bettyimage.html",scope:{image:"=",ratio:"=",width:"@"},controller:["$scope",function(){}],link:function(scope,element){scope.width=parseInt(scope.width,10);{var ratioWidth=parseInt(scope.ratio.split("x")[0],10),ratioHeight=parseInt(scope.ratio.split("x")[1],10);scope.width*ratioHeight/ratioWidth+"px"}element.css("width",scope.width+"px"),element.css("height",scope.width*ratioHeight/ratioWidth+"px");var selection=scope.image.selections[scope.ratio],selectionWidth=selection.x1-selection.x0,scale=scope.width/selectionWidth,requestWidth=Math.round(scale*(scope.image.width-selectionWidth)+scope.width);element.css("background-image","url("+routes.IMAGE_SERVER_URL+"/"+scope.image.id+"/original/"+requestWidth+".jpg)"),element.css("background-position",scale*selection.x0*-1+"px "+scale*selection.y0*-1+"px")}}}]),angular.module("bulbsCmsApp").directive("createContent",["$http","$window","$","IfExistsElse","PARTIALS_URL",function($http,$window,$,IfExistsElse,PARTIALS_URL){return{restrict:"E",templateUrl:PARTIALS_URL+"create-content.html",controller:["$scope",function($scope){function saveArticle(){$("button.go").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(){console.log("wow. error."),$("button.go").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(){var init={title:$scope.newTitle};angular.extend($scope.init,init),$scope.tag?IfExistsElse.ifExistsElse("/cms/api/v1/tag/?ordering=name&search="+encodeURIComponent($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){403===status&&$scope.showLoginModal()}):$scope.gotTags=!0,IfExistsElse.ifExistsElse("/cms/api/v1/user/?ordering=name&search="+$window.current_user,{username:$window.current_user},function(user){$scope.init.authors=[user],$scope.gotUser=!0},function(){console.log("are you bruce willis in sixth sense? dunno.")},function(data,status){403===status&&$scope.showLoginModal()}),$scope.gotSave=!0}}],link:function(scope,element){$(element).find("a.create-content").on("click",function(){$("a.create-content.active").removeClass("active"),$(this).addClass("active")}),$(element).find("a.create-content").on("click",function(){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")&&$("#create button.next-pane").click(),!0}),$("button.next-pane:not(.hide)").on("click",function(){console.log("next clicked"),console.log(scope.contentType),console.log(scope.init),$("#createcontent-01").addClass("hidden"),$("#createcontent-02").removeClass("hidden"),$("button.next-pane:not(.hide)").addClass("hidden"),$(".new-title").focus()}),$(element).find(".new-title").on("keydown",function(e){13===e.keyCode&&$(element).find(".go").click()})}}}]),angular.module("bulbsCmsApp").directive("devicepreview",["$","routes",function($,routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"devicepreview.html",link:function(){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("filterwidget",["$http","$location","$window","$timeout","$","routes",function($http,$location,$window,$timeout,$,routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"filterwidget.html",link:function(scope,element){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.getContent(),scope.autocompleteArray=[],$input.trigger("blur")}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.searchTerm,scope.autocompleteArray=[];var filterInputTimeout,filterInputCounter=0;$input.on("input",function(){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?$element.find(".selected").click():scope.addFilter("search",$input.val()))}),$element.find(".search-button").on("click",function(){scope.addFilter("search",$input.val())}),$element.find(".clear-button").on("click",function(){$(this).prev("input").val(""),scope.filterObjects={},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();"search"===type?filterObject.search=newFilterValue:(filterObject[type]||(filterObject[type]=[]),"string"==typeof filterObject[type]&&(filterObject[type]=[filterObject[type]]),filterObject[type].push(newFilterValue),$input.val("")),applyFilterChange(filterObject),scope.filterInputValue=""},scope.deleteFilter=function(key){var filterObject=$location.search(),toDelete=scope.filterObjects[key];"string"==typeof filterObject[toDelete.type]&&(filterObject[type]=[filterObject[type]]);var toSplice;for(var i in filterObject[toDelete.type])if(filterObject[toDelete.type][i]===toDelete.query){toSplice=i;break}filterObject[toDelete.type].splice(i,1),filterObject.search=$input.val(),delete scope.filterObjects[key],applyFilterChange(filterObject)},scope.$watch("locationSearch",function(search){if(scope.filterObjects={},"undefined"!=typeof search){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)}}),scope.$on("$routeUpdate",function(){scope.locationSearch=$location.search()}),scope.locationSearch=$location.search()}}}]),angular.module("bulbsCmsApp").directive("imagedrawer",["$http","$window","$","routes","BC_API_KEY",function($http,$window,$,routes,BC_API_KEY){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"imagedrawer.html",scope:{openImageDrawer:"=",closeImageDrawer:"=",article:"="},controller:["$scope",function($scope){function scaleSelection(scale,selection){return[Math.floor(scale*selection[0]),Math.floor(scale*selection[1]),Math.floor(scale*selection[2]),Math.floor(scale*selection[3])]}$scope.current_image={},$scope.$watch("current_image",function(){$scope.library_images=prependCurrentImage($scope.library_images,$scope.current_image)}),$scope.library_images=[];var prependCurrentImage=function(library,current_image){var new_library=library;if(current_image.id){for(var i in new_library)if(new_library[i].id===current_image.id){new_library.splice(i,1);break}new_library.unshift(current_image)}return new_library},refreshImageLibrary=function(params){params=params||{},console.log(BC_API_KEY),$http({method:"GET",url:routes.BC_ADMIN_URL+"/api/search",params:params,headers:{"X-Betty-Api-Key":BC_API_KEY}}).success(function(data){$scope.library_images=prependCurrentImage(data.results,$scope.current_image)})};$scope.drawerUpload=function(){$window.uploadImage({onProgress:function(){},onSuccess:function(data){refreshImageLibrary(),$scope.onChangeFn(data),$scope.current_image=data},onError:$scope.onCancelFn,onCancel:$scope.onCancelFn})};var refreshCurrentImage=function(id,field){console.log(BC_API_KEY),$http({url:routes.BC_ADMIN_URL+"/api/"+id,method:"GET",headers:{"X-Betty-Api-Key":BC_API_KEY}}).success(function(data){field?$scope.current_image[field]=data[field]:$scope.current_image=data,$window.picturefill(!0)}).error(function(){$scope.current_image={}})};$window.refreshCurrentImage=refreshCurrentImage,$scope.$watch("imageLibrarySearch",function(){refreshImageLibrary({q:$scope.imageLibrarySearch})}),$scope.openImageDrawer=function(){var oldId,onChangeFn,onSaveFn,onCancelFn;"function"==typeof arguments[0]?(oldId=null,onChangeFn=arguments[0],onSaveFn=arguments[1],onCancelFn=arguments[2]):(oldId=arguments[0],onChangeFn=arguments[1],onSaveFn=arguments[2],onCancelFn=arguments[3]),$("#image-drawer").off("click"),$("#image-drawer").on("click","#image-library.image",function(){var id=$(this).data("imageId");refreshCurrentImage(id),onChangeFn(id)}),oldId&&($scope.original_image=oldId),refreshCurrentImage(oldId),$scope.oldId=oldId,$scope.onChangeFn=onChangeFn,$scope.onSaveFn=onSaveFn,$scope.onCancelFn=function(id){$scope.original_image&&refreshCurrentImage($scope.original_image),onCancelFn(id)},$("body").addClass("image-drawer-cropper-open"),refreshImageLibrary()},$window.openImageDrawer=$scope.openImageDrawer,$scope.openImageLibrary=function(){$scope.libraryOpen=!0,$("body").addClass("image-drawer-library-open"),$window.picturefill(!0)},$scope.closeImageDrawer=function(){$("body").removeClass("image-drawer-cropper-open"),$("body").removeClass("image-drawer-library-open"),$window.picturefill()},$scope.closeImageLibrary=function(action){"save"===action&&$scope.onSaveFn(),"cancel"===action&&$scope.onCancelFn($scope.oldId),$("body").removeClass("image-drawer-library-open"),$scope.libraryOpen=!1},$scope.saveImageData=function(e){$window.saveImageData(e)},$scope.saveNewCrop=function(image,ratio){image.selections[ratio]={x0:user_selection_scaled[0],y0:user_selection_scaled[1],x1:user_selection_scaled[2],y1:user_selection_scaled[3]},$scope.$apply(),$window.saveNewCrop(image,ratio,user_selection_scaled,{onSuccess:function(){refreshCurrentImage(image.id,"selections")}})};var jcrop_api,user_selection,user_selection_scaled;$("#cropperModal").on("hidden.bs.modal",function(){jcrop_api.destroy()}),$("#cropperModal").on("shown.bs.modal",function(){$window.picturefill()}),$scope.cropImage=function(image,ratio){var width=500;$("#cropper-img").attr("src",routes.IMAGE_SERVER_URL+"/"+image.id+"/original/"+width+".jpg");var aspectWidth=ratio.split("x")[0],aspectHeight=ratio.split("x")[1],scale=width/image.width,selection=[image.selections[ratio].x0,image.selections[ratio].y0,image.selections[ratio].x1,image.selections[ratio].y1],onSelect=function(c){var selection=[c.x,c.y,c.x2,c.y2];user_selection=selection,user_selection_scaled=scaleSelection(1/scale,selection)};$("#cropper-modal-save-button").unbind("click"),$("#cropper-modal-save-button").click(function(){$scope.saveNewCrop(image,ratio)}),$("#cropperModal").modal("show"),$("#cropper-img").Jcrop({onSelect:onSelect,allowMove:!0,allowResize:!0,aspectRatio:aspectWidth/aspectHeight},function(){jcrop_api=this,jcrop_api.setOptions({aspectRatio:aspectWidth/aspectHeight}),this.focus();scaleSelection(scale,selection);this.setSelect(scaleSelection(scale,selection))})}}],link:function(scope){function preventDefault(e){e=e||window.event,e.preventDefault&&e.preventDefault(),e.returnValue=!1}scope.IMAGE_SERVER_URL=routes.IMAGE_SERVER_URL,document.getElementById("image-cropper").onmousewheel=function(e){document.getElementById("image-cropper").scrollTop-=e.wheelDeltaY,preventDefault(e)},document.getElementById("image-library-body").onmousewheel=function(e){document.getElementById("image-library-body").scrollTop-=e.wheelDeltaY,preventDefault(e)}}}}]),angular.module("bulbsCmsApp").directive("listinput",["$","routes",function($,routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"listinput.html",scope:{model:"="},link:function(scope,element,attrs){scope.label=attrs.label,scope.noun=attrs.noun,element.find("input")[0].setAttribute("name",attrs.noun),element.find("input").bind("focus",function(){$(element).find(".preview").hide(),$(element).find(".all-container").show()}),element.find("input").bind("blur",function(){$(element).find(".all-container").hide(),$(element).find(".preview").show()}),element.find("input").bind("keyup",function(e){if(13===e.keyCode){var value=$(this).val();value.length>0&&(scope.model||(scope.model=[]),scope.model.push($(this).val()),scope.$apply(),$(this).val(""))}})}}}]),angular.module("bulbsCmsApp").directive("login",["$http","$cookies","$window","$","routes",function($http,$cookies,$window,$,routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"login.html",link:function(scope){scope.showLoginModal=function(){$("#login-modal").modal("show")},$window.showLoginModal=scope.showLoginModal,scope.login=function(){var username=$('input[name="username"]').val(),password=$('input[name="password"]').val(),data=$.param({username:username,password:password});$http({method:"POST",url:"/login/",data:data,headers:{"Content-Type":"application/x-www-form-urlencoded"}}).success(function(){$("#login-modal").modal("hide")}).error(function(data){console.log("error"),console.log(data)})},scope.$watch(function(){return $cookies.csrftoken},function(newCsrf){$http.defaults.headers.post["X-CSRFToken"]=newCsrf,$window.jqueryCsrfSetup()})}}}]),angular.module("bulbsCmsApp").directive("videoUpload",["$http","$window","$timeout","$sce","$","routes",function($http,$window,$timeout,$sce,$,routes){return{templateUrl:routes.PARTIALS_URL+"mainvideo.html",scope:{article:"="},restrict:"E",link:function(scope,element){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(){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(){$(".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("/videos/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("label.btn"),element.find("div.progress")),progressBar=element.find("div.progress-bar"),fakeInput=(element.find("div.progress span"),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("publishContent",["$http","$","routes",function($http,$,routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"publish-content.html",link:function(scope){function putChanges(article,data){$http({url:"/cms/api/v1/content/"+article.id+"/publish/",method:"POST",data:data}).success(function(resp){scope.publishSuccessCbk(article,resp)}).error(function(error,status){403===status&&scope.showLoginModal()})}scope.openPubTimeModal=function(article){scope.pubTimeArticle=article},scope.openSendToEditorModal=function(article){scope.pubTimeArticle=article},scope.pubTimeCancel=function(){scope.pubTimeArticle=null},scope.pubTimeSave=function(article){if(!article.feature_type)return void $("#pubTimeValidationModal").modal("show");var newPubDate=$("#chooseDate .date input").val();newPubDate&&(newPubDate=moment(newPubDate,"MM/DD/YYYY hh:mm a CST").format("YYYY-MM-DDTHH:mmZ"));var data={published:newPubDate};putChanges(article,data)},scope.pubUnpublish=function(article){$("#chooseDate .date input").val("");var data={published:!1};putChanges(article,data)},$("#chooseDate .datetimepicker2").datetimepicker({language:"en",pick12HourFormat:!0,pickSeconds:!1,maskInput:!1}),scope.sendToEditor=function(article){$http({url:"/cms/api/v1/content/"+article.id+"/send/",method:"POST",data:{notes:scope.noteToEditor}}).success(function(data){scope.publishSuccessCbk(article,data)})},scope.saveThenOpenSendModal=function(article){scope.saveArticle().then(function(){scope.openSendToEditorModal(article),$("#sendToEditor").modal("show")})},scope.saveThenPublish=function(article){scope.saveArticle().then(function(){scope.openPubTimeModal(article),$("#chooseDate").modal("show")})}}}}]),angular.module("bulbsCmsApp").directive("mediaRating",["$http","$","routes",function($http,$,routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"rating.html",scope:!0,controller:["$scope",function($scope){$scope.search=function(el){$scope.searchTimeout=null;for(var inputs=el.find(".media-field input"),searchParams={},i=0;i'),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("targeting",["routes",function(routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"targeting.html",link:function(scope){scope.addTargetingRow=function(){scope.targetingArray.push([])},scope.removeTargetingRow=function(index){scope.targetingArray.splice(index,1)}}}}]),angular.module("bulbsCmsApp").directive("titleimage",["$http","$window","$","routes",function($http,$window,$,routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"titleimage.html",scope:{article:"=",image:"="},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.placeholderText=attrs.placeholderText||"Optional Image",scope.removeTitleImage=function(){scope.image=null},scope.addTitleImage=function(){$window.uploadImage({onSuccess:function(data){scope.$apply(function(){scope.image={id:data.id.toString(),alt:null,caption:null},setTimeout($window.picturefill,200)})},onError:function(data){scope.$apply(function(){alert("Error: ",data)})},onProgress:function(){}})},scope.editTitleImage=function(){$window.openImageDrawer(scope.image.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.image.id=data.id.toString(),scope.$apply(),$window.picturefill(),$element.find(".image img")[0].complete&&removeLoadingGif())},function(){},function(oldImage){scope.image=oldImage,$window.picturefill()})}}}}]),angular.module("bulbsCmsApp").directive("trashContent",["$http","$","routes",function($http,$,routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"trash-content.html",link:function(scope){scope.trashContent=function(idOrConfirmed){idOrConfirmed===!0?($("#trash-confirm-button").html(' Trashing'),$http({method:"POST",url:"/cms/api/v1/content/"+scope.articleIdToTrash+"/trash/"}).success(function(){scope.trashSuccessCbk()}).error(function(data,status){404===status?scope.trashSuccessCbk():403===status?scope.showLoginModal():$("#trash-confirm-button").html(' Error!')})):(scope.articleIdToTrash=idOrConfirmed,$("#confirm-trash-modal").modal("show"))}}}}]),function(global){var OnionCmsUI=OnionCmsUI||function(editor){function init(){toolbarPosition=$("#content-body .document-tools").offset().top+12,$(window).scroll(function(){window.scrollY>toolbarPosition?$("#content-body .document-tools").addClass("fixed"):$("#content-body .document-tools").removeClass("fixed")}),key("⌘+s, ctrl+s",function(e){e.preventDefault()})}var toolbarPosition;editor.on("init",init)};global.EditorModules.push(OnionCmsUI)}(this),function(global){var OnionImage=OnionImage||function(editor){function uploadImage(options){function onProgress(){}function onSuccess(data){options.onSuccess(options.block,{image_id:data.id}),window.picturefill()}function onError(){}function onCancel(){}global.uploadImage({onProgress:onProgress,onSuccess:onSuccess,onError:onError,onCancel:onCancel})}function editImage(options){function onDrawerImageChange(id){$(options.element).attr("data-image-id",id),window.picturefill()}function onDrawerSave(){}function onDrawerCancel(){}current_id=options.element.getAttribute("data-image-id"),openImageDrawer(current_id,onDrawerImageChange,onDrawerSave,onDrawerCancel)}editor.on("inline:edit:image",editImage),editor.on("inline:insert:image",uploadImage);var current_id};global.EditorModules.push(OnionImage)}(this),function(global){var OnionVideo=OnionVideo||function(editor){function cleanup(){for(var old_embeds=$("[data-type=embed] iframe[src^='/videos/embed']").parents("div.embed"),i=0;i")}editor.on("inline:insert:hr",insert)};global.EditorModules.push(HR)}(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()}); \ No newline at end of file +},$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();"search"===type?filterObject.search=newFilterValue:(filterObject[type]||(filterObject[type]=[]),"string"==typeof filterObject[type]&&(filterObject[type]=[filterObject[type]]),filterObject[type].push(newFilterValue),$input.val("")),applyFilterChange(filterObject),scope.filterInputValue=""},scope.deleteFilter=function(key){var filterObject=$location.search(),toDelete=scope.filterObjects[key];"string"==typeof filterObject[toDelete.type]&&(filterObject[type]=[filterObject[type]]);var toSplice;for(var i in filterObject[toDelete.type])if(filterObject[toDelete.type][i]===toDelete.query){toSplice=i;break}filterObject[toDelete.type].splice(i,1),filterObject.search=$input.val(),delete scope.filterObjects[key],applyFilterChange(filterObject)},scope.$watch("locationSearch",function(search){if(scope.filterObjects={},"undefined"!=typeof search){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)}}),scope.$on("$routeUpdate",function(){scope.locationSearch=$location.search()}),scope.locationSearch=$location.search()}}}]),angular.module("bulbsCmsApp").directive("imagedrawer",["$http","$window","$","routes","BC_API_KEY",function($http,$window,$,routes,BC_API_KEY){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"imagedrawer.html",scope:{openImageDrawer:"=",closeImageDrawer:"=",article:"="},controller:["$scope",function($scope){function scaleSelection(scale,selection){return[Math.floor(scale*selection[0]),Math.floor(scale*selection[1]),Math.floor(scale*selection[2]),Math.floor(scale*selection[3])]}$scope.current_image={},$scope.$watch("current_image",function(){$scope.library_images=prependCurrentImage($scope.library_images,$scope.current_image)}),$scope.library_images=[];var prependCurrentImage=function(library,current_image){var new_library=library;if(current_image.id){for(var i in new_library)if(new_library[i].id===current_image.id){new_library.splice(i,1);break}new_library.unshift(current_image)}return new_library},refreshImageLibrary=function(params){params=params||{},$http({method:"GET",url:routes.BC_ADMIN_URL+"/api/search",params:params,headers:{"X-Betty-Api-Key":BC_API_KEY}}).success(function(data){$scope.library_images=prependCurrentImage(data.results,$scope.current_image)})};$scope.drawerUpload=function(){$window.uploadImage({onProgress:function(){},onSuccess:function(data){refreshImageLibrary(),$scope.onChangeFn(data),$scope.current_image=data},onError:$scope.onCancelFn,onCancel:$scope.onCancelFn})};var refreshCurrentImage=function(id,field){$http({url:routes.BC_ADMIN_URL+"/api/"+id,method:"GET",headers:{"X-Betty-Api-Key":BC_API_KEY}}).success(function(data){field?$scope.current_image[field]=data[field]:$scope.current_image=data,$window.picturefill(!0)}).error(function(){$scope.current_image={}})};$window.refreshCurrentImage=refreshCurrentImage,$scope.$watch("imageLibrarySearch",function(){refreshImageLibrary({q:$scope.imageLibrarySearch})}),$scope.openImageDrawer=function(){var oldId,onChangeFn,onSaveFn,onCancelFn;"function"==typeof arguments[0]?(oldId=null,onChangeFn=arguments[0],onSaveFn=arguments[1],onCancelFn=arguments[2]):(oldId=arguments[0],onChangeFn=arguments[1],onSaveFn=arguments[2],onCancelFn=arguments[3]),$("#image-drawer").off("click"),$("#image-drawer").on("click","#image-library.image",function(){var id=$(this).data("imageId");refreshCurrentImage(id),onChangeFn(id)}),oldId&&($scope.original_image=oldId),refreshCurrentImage(oldId),$scope.oldId=oldId,$scope.onChangeFn=onChangeFn,$scope.onSaveFn=onSaveFn,$scope.onCancelFn=function(id){$scope.original_image&&refreshCurrentImage($scope.original_image),onCancelFn(id)},$("body").addClass("image-drawer-cropper-open"),refreshImageLibrary()},$window.openImageDrawer=$scope.openImageDrawer,$scope.openImageLibrary=function(){$scope.libraryOpen=!0,$("body").addClass("image-drawer-library-open"),$window.picturefill(!0)},$scope.closeImageDrawer=function(){$("body").removeClass("image-drawer-cropper-open"),$("body").removeClass("image-drawer-library-open"),$window.picturefill()},$scope.closeImageLibrary=function(action){"save"===action&&$scope.onSaveFn(),"cancel"===action&&$scope.onCancelFn($scope.oldId),$("body").removeClass("image-drawer-library-open"),$scope.libraryOpen=!1},$scope.saveImageData=function(e){$window.saveImageData(e)},$scope.saveNewCrop=function(image,ratio){image.selections[ratio]={x0:user_selection_scaled[0],y0:user_selection_scaled[1],x1:user_selection_scaled[2],y1:user_selection_scaled[3]},$scope.$apply(),$window.saveNewCrop(image,ratio,user_selection_scaled,{onSuccess:function(){refreshCurrentImage(image.id,"selections")}})};var jcrop_api,user_selection,user_selection_scaled;$("#cropperModal").on("hidden.bs.modal",function(){jcrop_api.destroy()}),$("#cropperModal").on("shown.bs.modal",function(){$window.picturefill()}),$scope.cropImage=function(image,ratio){var width=500;$("#cropper-img").attr("src",routes.IMAGE_SERVER_URL+"/"+image.id+"/original/"+width+".jpg");var aspectWidth=ratio.split("x")[0],aspectHeight=ratio.split("x")[1],scale=width/image.width,selection=[image.selections[ratio].x0,image.selections[ratio].y0,image.selections[ratio].x1,image.selections[ratio].y1],onSelect=function(c){var selection=[c.x,c.y,c.x2,c.y2];user_selection=selection,user_selection_scaled=scaleSelection(1/scale,selection)};$("#cropper-modal-save-button").unbind("click"),$("#cropper-modal-save-button").click(function(){$scope.saveNewCrop(image,ratio)}),$("#cropperModal").modal("show"),$("#cropper-img").Jcrop({onSelect:onSelect,allowMove:!0,allowResize:!0,aspectRatio:aspectWidth/aspectHeight},function(){jcrop_api=this,jcrop_api.setOptions({aspectRatio:aspectWidth/aspectHeight}),this.focus();scaleSelection(scale,selection);this.setSelect(scaleSelection(scale,selection))})}}],link:function(scope){function preventDefault(e){e=e||window.event,e.preventDefault&&e.preventDefault(),e.returnValue=!1}scope.IMAGE_SERVER_URL=routes.IMAGE_SERVER_URL,document.getElementById("image-cropper").onmousewheel=function(e){document.getElementById("image-cropper").scrollTop-=e.wheelDeltaY,preventDefault(e)},document.getElementById("image-library-body").onmousewheel=function(e){document.getElementById("image-library-body").scrollTop-=e.wheelDeltaY,preventDefault(e)}}}}]),angular.module("bulbsCmsApp").directive("listinput",["$","routes",function($,routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"listinput.html",scope:{model:"="},link:function(scope,element,attrs){scope.label=attrs.label,scope.noun=attrs.noun,element.find("input")[0].setAttribute("name",attrs.noun),element.find("input").bind("focus",function(){$(element).find(".preview").hide(),$(element).find(".all-container").show()}),element.find("input").bind("blur",function(){$(element).find(".all-container").hide(),$(element).find(".preview").show()}),element.find("input").bind("keyup",function(e){if(13===e.keyCode){var value=$(this).val();value.length>0&&(scope.model||(scope.model=[]),scope.model.push($(this).val()),scope.$apply(),$(this).val(""))}})}}}]),angular.module("bulbsCmsApp").directive("login",["$http","$cookies","$window","$","routes",function($http,$cookies,$window,$,routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"login.html",link:function(scope){scope.showLoginModal=function(){$("#login-modal").modal("show")},$window.showLoginModal=scope.showLoginModal,scope.login=function(){var username=$('input[name="username"]').val(),password=$('input[name="password"]').val(),data=$.param({username:username,password:password});$http({method:"POST",url:"/login/",data:data,headers:{"Content-Type":"application/x-www-form-urlencoded"}}).success(function(){$("#login-modal").modal("hide")}).error(function(data){console.log("error"),console.log(data)})},scope.$watch(function(){return $cookies.csrftoken},function(newCsrf){$http.defaults.headers.post["X-CSRFToken"]=newCsrf,$window.jqueryCsrfSetup()})}}}]),angular.module("bulbsCmsApp").directive("videoUpload",["$http","$window","$timeout","$sce","$","routes",function($http,$window,$timeout,$sce,$,routes){return{templateUrl:routes.PARTIALS_URL+"mainvideo.html",scope:{article:"="},restrict:"E",link:function(scope,element){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(){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(){$(".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("/videos/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("label.btn"),element.find("div.progress")),progressBar=element.find("div.progress-bar"),fakeInput=(element.find("div.progress span"),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("publishContent",["$http","$","routes",function($http,$,routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"publish-content.html",link:function(scope){function putChanges(article,data){$http({url:"/cms/api/v1/content/"+article.id+"/publish/",method:"POST",data:data}).success(function(resp){scope.publishSuccessCbk(article,resp)}).error(function(error,status){403===status&&scope.showLoginModal()})}scope.openPubTimeModal=function(article){scope.pubTimeArticle=article},scope.openSendToEditorModal=function(article){scope.pubTimeArticle=article},scope.pubTimeCancel=function(){scope.pubTimeArticle=null},scope.pubTimeSave=function(article){if(!article.feature_type)return void $("#pubTimeValidationModal").modal("show");var newPubDate=$("#chooseDate .date input").val();newPubDate&&(newPubDate=moment(newPubDate,"MM/DD/YYYY hh:mm a CST").format("YYYY-MM-DDTHH:mmZ"));var data={published:newPubDate};putChanges(article,data)},scope.pubUnpublish=function(article){$("#chooseDate .date input").val("");var data={published:!1};putChanges(article,data)},$("#chooseDate .datetimepicker2").datetimepicker({language:"en",pick12HourFormat:!0,pickSeconds:!1,maskInput:!1}),scope.sendToEditor=function(article){$http({url:"/cms/api/v1/content/"+article.id+"/send/",method:"POST",data:{notes:scope.noteToEditor}}).success(function(data){scope.publishSuccessCbk(article,data)})},scope.saveThenOpenSendModal=function(article){scope.saveArticle().then(function(){scope.openSendToEditorModal(article),$("#sendToEditor").modal("show")})},scope.saveThenPublish=function(article){scope.saveArticle().then(function(){scope.openPubTimeModal(article),$("#chooseDate").modal("show")})}}}}]),angular.module("bulbsCmsApp").directive("mediaRating",["$http","$","routes",function($http,$,routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"rating.html",scope:!0,controller:["$scope",function($scope){$scope.search=function(el){$scope.searchTimeout=null;for(var inputs=el.find(".media-field input"),searchParams={},i=0;i'),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("targeting",["routes",function(routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"targeting.html",link:function(scope){scope.addTargetingRow=function(){scope.targetingArray.push([])},scope.removeTargetingRow=function(index){scope.targetingArray.splice(index,1)}}}}]),angular.module("bulbsCmsApp").directive("titleimage",["$http","$window","$","routes",function($http,$window,$,routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"titleimage.html",scope:{article:"=",image:"="},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.placeholderText=attrs.placeholderText||"Optional Image",scope.removeTitleImage=function(){scope.image=null},scope.addTitleImage=function(){$window.uploadImage({onSuccess:function(data){scope.$apply(function(){scope.image={id:data.id.toString(),alt:null,caption:null},setTimeout($window.picturefill,200)})},onError:function(data){scope.$apply(function(){alert("Error: ",data)})},onProgress:function(){}})},scope.editTitleImage=function(){$window.openImageDrawer(scope.image.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.image.id=data.id.toString(),scope.$apply(),$window.picturefill(),$element.find(".image img")[0].complete&&removeLoadingGif())},function(){},function(oldImage){scope.image=oldImage,$window.picturefill()})}}}}]),angular.module("bulbsCmsApp").directive("trashContent",["$http","$","routes",function($http,$,routes){return{restrict:"E",templateUrl:routes.PARTIALS_URL+"trash-content.html",link:function(scope){scope.trashContent=function(idOrConfirmed){idOrConfirmed===!0?($("#trash-confirm-button").html(' Trashing'),$http({method:"POST",url:"/cms/api/v1/content/"+scope.articleIdToTrash+"/trash/"}).success(function(){scope.trashSuccessCbk()}).error(function(data,status){404===status?scope.trashSuccessCbk():403===status?scope.showLoginModal():$("#trash-confirm-button").html(' Error!')})):(scope.articleIdToTrash=idOrConfirmed,$("#confirm-trash-modal").modal("show"))}}}}]),function(global){var OnionCmsUI=OnionCmsUI||function(editor){function init(){toolbarPosition=$("#content-body .document-tools").offset().top+12,$(window).scroll(function(){window.scrollY>toolbarPosition?$("#content-body .document-tools").addClass("fixed"):$("#content-body .document-tools").removeClass("fixed")}),key("⌘+s, ctrl+s",function(e){e.preventDefault()})}var toolbarPosition;editor.on("init",init)};global.EditorModules.push(OnionCmsUI)}(this),function(global){var OnionImage=OnionImage||function(editor){function uploadImage(options){function onProgress(){}function onSuccess(data){options.onSuccess(options.block,{image_id:data.id}),window.picturefill()}function onError(){}function onCancel(){}global.uploadImage({onProgress:onProgress,onSuccess:onSuccess,onError:onError,onCancel:onCancel})}function editImage(options){function onDrawerImageChange(id){$(options.element).attr("data-image-id",id),window.picturefill()}function onDrawerSave(){}function onDrawerCancel(){}current_id=options.element.getAttribute("data-image-id"),openImageDrawer(current_id,onDrawerImageChange,onDrawerSave,onDrawerCancel)}editor.on("inline:edit:image",editImage),editor.on("inline:insert:image",uploadImage);var current_id};global.EditorModules.push(OnionImage)}(this),function(global){var OnionVideo=OnionVideo||function(editor){function cleanup(){for(var old_embeds=$("[data-type=embed] iframe[src^='/videos/embed']").parents("div.embed"),i=0;i")}editor.on("inline:insert:hr",insert)};global.EditorModules.push(HR)}(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()}); \ No newline at end of file