Mercurial > hg > dml-open-vis
view $/app.js @ 1:f38015048f48 tip
Added GPL
author | Daniel Wolff |
---|---|
date | Sat, 13 Feb 2016 20:43:38 +0100 |
parents | 493bcb69166c |
children |
line wrap: on
line source
/*! * DML Main Vis * http://dml.city.ac.uk/ */ (function($){$.eventsugar={isAttemptToOpenInAnotherWindow:function(event){return 2===event.which||event.metaKey||event.ctrlKey||event.shiftKey}}})(jQuery); (function($){$.widget("custom.combobox",{_create:function(){this.wrapper=$("<span>").addClass("custom-combobox").insertAfter(this.element);this.element.hide();this._createAutocomplete();this._createShowAllButton()},_createAutocomplete:function(){var selected=this.element.children(":selected"),value=selected.val()?selected.text():"";this.input=$("<input>").appendTo(this.wrapper).val(value).attr("title","").addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left").autocomplete({delay:0,minLength:0,source:$.proxy(this,"_source")});this._on(this.input,{autocompleteselect:function(event,ui){ui.item.option.selected=true;this._trigger("select",event,{item:ui.item.option})},autocompletechange:"_applyChange"})},_createShowAllButton:function(){var input=this.input,wasOpen=false;$("<a>").attr("tabIndex",-1).attr("title","Show All Items").tooltip().appendTo(this.wrapper).button({icons:{primary:"ui-icon-triangle-1-s"},text:false}).removeClass("ui-corner-all").addClass("custom-combobox-toggle ui-corner-right").mousedown(function(){wasOpen=input.autocomplete("widget").is(":visible")}).click(function(){input.focus();if(wasOpen){return}input.autocomplete("search","")})},_source:function(request,response){var matcher=new RegExp($.ui.autocomplete.escapeRegex(request.term),"i");response(this.element.children("option").map(function(){var text=$(this).text();if(this.value&&(!request.term||matcher.test(text)))return{label:text,value:text,option:this}}))},_applyChange:function(event,ui){if(ui.item){return}var value=this.input.val(),valueLowerCase=value.toLowerCase(),valid=false;this.element.children("option").each(function(){if($(this).text().toLowerCase()===valueLowerCase){this.selected=valid=true;return false}});this.element.val(value);if(valid){return}},_destroy:function(){this.wrapper.remove();this.element.show()}})})(jQuery); var toString=Object.prototype.toString;if(_){_.mixin({isEventAnAttemptToOpenANewTab:function(event){return event.ctrlKey||event.shiftKey||event.metaKey||event.which==2}})}else{console.error("Can't register _.isClickAnAttemptToOpenANewTab without underscore.js (global variable '_')")} var toString=Object.prototype.toString;if(_){_.mixin({isSimpleObject:function(obj){return toString.call(obj)==="[object Object]"&&obj.constructor===Object}})}else{console.error("Can't register _.isSimpleObject without underscore.js (global variable '_')")} var toString=Object.prototype.toString;if(_){var idCounter=0;var alreadyUsedUniqueIds={};_.mixin({uniqueId:function(prefix){while(true){var id=++idCounter+"";var uniqueId=prefix?prefix+id:id;if(!alreadyUsedUniqueIds[uniqueId]){return uniqueId}}},markUniqueIdAsAlreadyUsed:function(uniqueId){alreadyUsedUniqueIds[uniqueId]=true}})}else{console.error("Can't register _.uniqueId and _.markUniqueIdAsAlreadyUsed without underscore.js (global variable '_')")} if(vg&&false){vg.parse.expr.codegen.functions["myFunction"]=function(args){var a=args.map(vg.parse.expr.codegen);return"window.myFunction("+a[0]+")"}}else{} (function(){if(vg){var Transform=vg.transforms.bin.prototype.__proto__.constructor;function Centroid(graph){Transform.prototype.init.call(this,graph);Transform.addParameters(this,{field:{type:"field"}});this._output={centroid_x:"centroid_x",centroid_y:"centroid_y"};return this.mutates(true)}var prototype=Centroid.prototype=Object.create(Transform.prototype);prototype.constructor=Centroid;prototype.transform=function(input){var output_x=this._output.centroid_x,output_y=this._output.centroid_y,get=this.param("path").accessor;var svg=d3.select("body").append("svg").attr("width",400).attr("height",400);var p=svg.append("path");function update(d){p.attr("d",d["layout_path"]);var bbox=p.node().getBBox();var x=Math.floor(bbox.x+bbox.width/2);var y=Math.floor(bbox.y+bbox.height/2);vg.dataflow.Tuple.set(d,output_x,x);vg.dataflow.Tuple.set(d,output_y,y)}input.add.forEach(update);input.mod.forEach(update);input.rem.forEach(update);input.fields[output_x]=0;input.fields[output_y]=0;return input};Centroid.schema={$schema:"http://json-schema.org/draft-04/schema#",title:"Bin transform",description:"Bins values into quantitative bins (e.g., for a histogram).",type:"object",properties:{type:{"enum":["bin"]},field:{oneOf:[{type:"string"},{$ref:"#/refs/signal"}],description:"The name of the field to calculate centroids from values from."},output:{type:"object",description:"Rename the output data fields",properties:{bin:{type:"string","default":"bin"}},additionalProperties:false}},additionalProperties:false,required:["field"]};vg.transforms.centroid=Centroid;console.log(vg)}else{}})(); "use strict";var App=new Backbone.Marionette.Application; "use strict";App.addInitializer(function(options){Logger.setLevel(Logger.WARN);App.logger=Logger.get("App");App.logger.setLevel(Logger.DEBUG);var previousLogTime=null;Logger.setHandler(function(originalArguments,context){var hdlr=console.log;var messages=Array.prototype.slice.call(originalArguments);if(context.name){messages.unshift(_.str.pad(_.str.sprintf("[%s]",context.name),25," ","right"))}var logDate=new Date;var logTime=logDate.getTime();if(previousLogTime&&logTime-previousLogTime<3e3){messages.unshift(_.str.sprintf(" %4d",logTime-previousLogTime))}else{messages.unshift(" ")}messages.unshift(_.str.sprintf("%s.%03d",logDate.toTimeString().slice(0,8),logTime%1e3));previousLogTime=logTime;if(context.level===Logger.WARN&&console.warn){hdlr=console.warn}else if(context.level===Logger.ERROR&&console.error){hdlr=console.error}else if(context.level===Logger.INFO&&console.info){hdlr=console.info}Function.prototype.apply.call(hdlr,console,messages)});if(!options.enableJasmine){window.onerror=function(message,file,line){App.logger.error("[unhandled]",message,file,line)}}}); "use strict";App.addInitializer(function(options){App.generateAssetURL=function(relativeAssetURL){return _.str.sprintf("$/%s",relativeAssetURL)}}); "use strict";App.addInitializer(function(options){if(window.location.href.indexOf("reset")>0){localStorage.clear();console.log("reset")}if(navigator.appVersion.indexOf("Mac")>0){App.keyboardMappings={ctrl:"meta",ctrlTitle:"cmd",ctrlShift:"shift+meta",ctrlShiftTitle:"cmd+shift"}}else{App.keyboardMappings={ctrl:"ctrl",ctrlTitle:"ctrl",ctrlShift:"ctrl+shift",ctrlShiftTitle:"ctrl+shift"}}App.DataModule.start();App.options.debugAPI=!!App.DataModule.Storage.getStrCache(null,"debug-api");App.options.defaultEntityWidth=400;App.DataModule.CliopatriaAPI.start({apiRootPaths:options.musicLibrary.apiRootPaths,apiVersion:options.musicLibrary.apiVersion,dataVersion:options.musicLibrary.dataVersion,dataCaching:options.musicLibrary.dataCaching});App.NotificationsModule.start();App.ContextModule.start();App.RepresentationModule.start();App.MainRegionModule.start();App.TooltipModule.start();App.HelpModule.start();App.contextManager=new App.ContextModule.AppContextManager;App.context=new App.ContextModule.AppContext;try{App.contextManager.restoreFromStorage(App.context,"")}catch(e){App.contextManager.restoreDefault("")}App.dynamicDefinitionProviderForCollections=new App.DataModule.DynamicDefinitionProviderForCollections;App.dynamicDefinitionProviderForRecordings=new App.DataModule.DymanicDefinitionProviderForRecordings;App.dynamicDerivedConfigDataProvider=new App.RepresentationModule.DynanicDerivedConfigDataProvider({configGridsByType:{collection:App.context.get("state").get("musicCollectionGrid"),recording:App.context.get("state").get("musicRecordingGrid")}});App.PlayerModule.start();var saveContextToStorage=function(){App.contextManager.saveToStorage(App.context)};var throttledSaveAppContextToStorage=_.throttle(saveContextToStorage,1e4,{leading:false});App.context.bind("change",throttledSaveAppContextToStorage);$(window).on("beforeunload",saveContextToStorage);App.mainRegionView=new App.MainRegionModule.MainRegionView({state:App.context.get("state"),el:".app__main-region"});App.MainMenuModule.start();App.TooltipModule.convertTitlesToTooltips($("body"))}); "use strict";App.addInitializer(function(options){App.showHelp=function(options){App.HelpModule.show(options);App.MainMenuModule.flashItem("help")};App.hideHelp=function(options){App.HelpModule.hide(options)};App.helpIsShowing=function(){return App.HelpModule.isShowing()};App.showNotification=function(options){App.NotificationsModule.show(options)};App.hideNotification=function(id){return App.NotificationsModule.hide(id)};var stateHistory=App.context.get("stateHistory");App.undo=function(){if(stateHistory.canUndo()){stateHistory.undo();App.hideNotification("undo_redo")}else{App.showNotification({id:"undo_redo",content:Backbone.Marionette.TemplateCache.get("#notification-content_undo_na")})}App.MainMenuModule.flashItem("undo")};App.redo=function(){if(stateHistory.canRedo()){stateHistory.redo();App.hideNotification("undo_redo")}else{App.showNotification({id:"undo_redo",content:Backbone.Marionette.TemplateCache.get("#notification-content_redo_na")})}App.MainMenuModule.flashItem("redo")};stateHistory.on("change",function(){App.hideNotification("undo_redo")});App.showStateSharing=function(){App.showNotification({id:"states",modifiers:["ttl_20"],content:Backbone.Marionette.TemplateCache.get("#notification-content_states_na")});App.MainMenuModule.flashItem("share")},App.showStateBookmarks=function(){App.showNotification({id:"states",modifiers:["ttl_20"],content:Backbone.Marionette.TemplateCache.get("#notification-content_states_na")});App.MainMenuModule.flashItem("bookmarks")},App.play=function(recordingURI,time){App.PlayerModule.play(recordingURI,time)}}); "use strict";App.addInitializer(function(options){var _this=this;var $document=$(document);var aPopupIsOpen=function(){return App.helpIsShowing()};var askToClosePopups=function(){};$document.bind("keydown","esc",function(event){if(App.helpIsShowing()){App.hideHelp()}});$document.bind("keydown","h",function(event){if(App.helpIsShowing()){App.hideHelp()}else{App.showHelp()}});$document.bind("keydown","f",function(event){if(aPopupIsOpen()){return false}var state=App.context.get("state");state.set("musicRecordingsGridIsShown",!state.get("musicRecordingsGridIsShown"))});$document.bind("keydown",App.keyboardMappings.ctrl+"+z",function(event){if(aPopupIsOpen()){askToClosePopups();return false}App.undo()});$document.bind("keydown",App.keyboardMappings.ctrlShift+"+z",function(event){if(aPopupIsOpen()){askToClosePopups();return false}App.redo()});var moveConfig=function(dimension,offset){var state=App.context.get("state");var configGrid=state.get(state.get("musicRecordingsGridIsShown")?"musicRecordingGrid":"musicCollectionGrid");var configs=null;if(dimension=="entity"){configs=configGrid.get("entityConfigs");var selectedConfig=configGrid.getSelectedEntityConfig();if(selectedConfig){var configToInsertBefore;if(offset==1){configToInsertBefore=configGrid.getNextEntityNeighbour(selectedConfig);if(configToInsertBefore){configToInsertBefore=configGrid.getNextEntityNeighbour(configToInsertBefore)}}else{configToInsertBefore=configGrid.getPrevEntityNeighbour(selectedConfig);if(!configToInsertBefore){return}}configGrid.relocateEntityConfig(selectedConfig,configToInsertBefore?configToInsertBefore:null)}}else{configs=configGrid.get("viewConfigs");var selectedConfig=configGrid.getSelectedViewConfig();if(selectedConfig){var configToInsertBefore;if(offset==1){configToInsertBefore=configGrid.getNextViewNeighbour(selectedConfig);if(configToInsertBefore){configToInsertBefore=configGrid.getNextViewNeighbour(configToInsertBefore)}}else{configToInsertBefore=configGrid.getPrevViewNeighbour(selectedConfig);if(!configToInsertBefore){return}}configGrid.relocateViewConfig(selectedConfig,configToInsertBefore?configToInsertBefore:null)}}};$document.bind("keydown","alt+left",function(event){if(aPopupIsOpen()){askToClosePopups();return false}moveConfig("entity",-1);event.preventDefault();return false});$document.bind("keydown","alt+right",function(event){if(aPopupIsOpen()){askToClosePopups();return false}moveConfig("entity",1);event.preventDefault();return false});$document.bind("keydown","alt+up",function(event){if(aPopupIsOpen()){askToClosePopups();return false}moveConfig("view",-1);event.preventDefault();return false});$document.bind("keydown","alt+down",function(event){if(aPopupIsOpen()){askToClosePopups();return false}moveConfig("view",1);event.preventDefault();return false})}); "use strict";App.addInitializer(function(options){var _this=this;var popupsAreInstant=true;var appRouter=new(Backbone.Router.extend({routes:{help:"navigateToHelp","help/:id":"navigateToHelp","":"navigateToDefault","*notFound":"notFound"},navigateToHelp:function(id){App.HelpModule.show({materialId:id!==null?id:"",instant:popupsAreInstant})},navigateToDefault:function(id){App.HelpModule.hide()},notFound:function(context){App.logger.warn("Route not found",context)}}));App.HelpModule.on("show",function(options){var urlHash="help";if(options.materialId){urlHash+="/"+options.materialId}var needToReplace=Backbone.history.fragment.slice(0,4)=="help";appRouter.navigate(urlHash,{replace:needToReplace})});App.HelpModule.on("hide",function(options){appRouter.navigate("/")});Backbone.history.start({});popupsAreInstant:false}); "use strict";App.addInitializer(function(options){var $document=$(document);var cid=0;var uniqueClientId=function(){return"custom"+cid++};var nextUniqueClientId=function(){return"custom"+cid};$document.bind("keydown","shift+0",function(event){App.context.get("state").unserialize(App.contextManager.defaultSerializedAppContexts[""].stateHistory.currentSerializedState)});var sharedMusicRecordingConfig={viewConfigs:[{clientId:"def4",parameters:{kind:"properties"}},{clientId:"def5",parameters:{kind:"midi-pitch-histogram"}}]};$document.bind("keydown","shift+1",function(event){App.context.get("state").unserialize({musicCollectionGrid:{selectedEntityConfigClientId:nextUniqueClientId(),entityConfigs:[{clientId:uniqueClientId(),parameters:{library:"bl",composer:"Haydn",performer:"Karajan",year:"1959",title:"Symphonies;104"}}],viewConfigs:[{clientId:uniqueClientId(),parameters:{kind:"list"}},{clientId:uniqueClientId(),parameters:{kind:"tuning-stats"}}]},musicRecordingGrid:sharedMusicRecordingConfig})});$document.bind("keydown","shift+2",function(event){App.context.get("state").unserialize({musicCollectionGrid:{selectedEntityConfigClientId:nextUniqueClientId(),entityConfigs:[{clientId:uniqueClientId(),parameters:{library:"bl;charm",composer:"Haydn",title:"Symphony"}}],viewConfigs:[{clientId:uniqueClientId(),parameters:{kind:"list"}},{clientId:uniqueClientId(),parameters:{kind:"tuning-stats"}}]},musicRecordingGrid:sharedMusicRecordingConfig})});$document.bind("keydown","shift+3",function(event){App.context.get("state").unserialize({musicCollectionGrid:{selectedEntityConfigClientId:nextUniqueClientId(),entityConfigs:[{clientId:uniqueClientId(),parameters:{library:"bl;charm",year:"1940-1979",title:"Symphony"}},{clientId:uniqueClientId(),parameters:{kind:"pair",comparisonMode:"superposition"}},{clientId:uniqueClientId(),parameters:{library:"bl;charm",year:"1980-2010",title:"Symphony"}}],viewConfigs:[{clientId:uniqueClientId(),parameters:{kind:"list"}},{clientId:uniqueClientId(),parameters:{kind:"tuning-stats"}}]},musicRecordingGrid:sharedMusicRecordingConfig})});$document.bind("keydown","shift+4",function(event){App.context.get("state").unserialize({musicCollectionGrid:{selectedEntityConfigClientId:nextUniqueClientId(),entityConfigs:[{clientId:uniqueClientId(),parameters:{library:"bl;charm",composer:"Schoenberg"}}],viewConfigs:[{clientId:uniqueClientId(),parameters:{kind:"midi-pitch-histogram"}}]},musicRecordingGrid:sharedMusicRecordingConfig})});$document.bind("keydown","shift+5",function(event){App.context.get("state").unserialize({musicCollectionGrid:{selectedEntityConfigClientId:nextUniqueClientId(),entityConfigs:[{clientId:uniqueClientId(),parameters:{library:"bl",collection:"dinka"}}],viewConfigs:[{clientId:uniqueClientId(),parameters:{kind:"list"}},{clientId:uniqueClientId(),parameters:{kind:"pitch-histogram"}},{clientId:uniqueClientId(),parameters:{kind:"midi-pitch-histogram"}}]},musicRecordingGrid:sharedMusicRecordingConfig})});$document.bind("keydown","shift+6",function(event){App.context.get("state").unserialize({musicCollectionGrid:{selectedEntityConfigClientId:nextUniqueClientId(),entityConfigs:[{clientId:uniqueClientId(),parameters:{library:"bl;charm",composer:"Chopin",title:"Mazurka;Op.68;no.2"}}],viewConfigs:[{clientId:uniqueClientId(),parameters:{kind:"list"}},{clientId:uniqueClientId(),parameters:{kind:"mean-tempo-curve"}}]},musicRecordingGrid:sharedMusicRecordingConfig})});$document.bind("keydown","shift+7",function(event){App.context.get("state").unserialize({musicCollectionGrid:{selectedEntityConfigClientId:nextUniqueClientId(),entityConfigs:[{clientId:uniqueClientId(),parameters:{library:"bl;charm",composer:"Chopin",title:"Mazurka;Op.68;no.2"}},{clientId:uniqueClientId(),parameters:{library:"bl;charm",composer:"Chopin"}}],viewConfigs:[{clientId:uniqueClientId(),parameters:{kind:"list"}},{clientId:uniqueClientId(),parameters:{kind:"mean-tempo-curve"}}]},musicRecordingGrid:sharedMusicRecordingConfig})})}); "use strict";App.addInitializer(function(options){var _this=this;if(!_.isUndefined(options.enableJasmine)){var $document=$(document);if(!options.enableJasmine){$document.bind("keydown","j",function(event){var url=location.protocol+"//"+location.host+location.pathname;if(url.indexOf("?")>-1){url+="&jasmine"}else{url+="?jasmine"}window.location.href=url})}else{executeJasmine();$document.bind("keydown","shift+j",function(event){var url=location.protocol+"//"+location.host+location.pathname;_.each(["jasmine","catch"],function(variable){url=url.replace(new RegExp("\\?"+variable+"[=]?[a-zA-Z%0-9]*&","g"),"?").replace(new RegExp("\\?"+variable+"[=]?[a-zA-Z%0-9]*$","g"),"").replace(new RegExp("\\&"+variable+"[=]?[a-zA-Z%0-9]*&","g"),"&").replace(new RegExp("\\&"+variable+"[=]?[a-zA-Z%0-9]*$","g"),"")});url=url.replace(/\?+/,"?").replace(/\?$/,"");window.location.href=url})}}}); "use strict";App.addInitializer(function(options){var $document=$(document);if(window.location.href.indexOf("track_assets_version")>0){var cssHref=$("link[rel=stylesheet]").attr("href");var assetsVersion=cssHref.slice(cssHref.indexOf("?")+1);var $cssUpdateIndicator=$.bem.generateElement("app","assets-version-indicator");$cssUpdateIndicator.text("assets version: "+assetsVersion);$cssUpdateIndicator.appendTo($(".app"));$cssUpdateIndicator.click(function(){App.showNotification({id:"assets-version-indicator",content:"This element changes colour when the css file recomplies."})})}var codeVersion="2015-03-12";var latestChange="Comparison views and also three new views for collections were added (<b>tuning stats</b>, <b>tonic histogram</b> and <b>pitch class histogram</b>). All three demo states now have the same sets of rows.";var previouslyOpenedCodeVersion=App.DataModule.Storage.getStrCache(null,"code-version");if(codeVersion!=previouslyOpenedCodeVersion){App.DataModule.Storage.setStrCache(null,"introductory-hint-was-read",undefined);App.DataModule.Storage.setStrCache(null,"code-version",codeVersion)}if(previouslyOpenedCodeVersion<"2015-03-12"){App.contextManager.restoreDefault(App.context,"empty")}if(window.location.href.indexOf("scroll")>0){$("body").addClass("scrollable-pres-in-vis-instances")}var latestVisit=App.DataModule.Storage.getStrCache(null,"latest-visit");if(!latestVisit){setTimeout(function(){if(!App.helpIsShowing()){App.MainMenuModule.flashItem("help",20)}},5e3)}App.DataModule.Storage.setStrCache(null,"latest-visit",(new Date).toString());var defaultURIIdentifier=options.musicLibrary.defaultApiRootPaths[0];if(options.musicLibrary.apiRootPaths[0].indexOf(defaultURIIdentifier)==-1){var currentURIIdentifier=options.musicLibrary.apiRootPaths[0].replace(/^[a-zA-Z]*:?\/\//,"").replace(/\/$/,"");setTimeout(function(){App.showNotification({content:Backbone.Marionette.TemplateCache.get("#notification-content_alternative-api")({defaultURIIdentifier:defaultURIIdentifier,currentURIIdentifier:currentURIIdentifier,stuffToRemoveFromAddess:"api2"}),modifiers:["ttl_30","type_warning"]})},1e3)}var debugAPIShortcut=App.keyboardMappings.ctrlShift+"+8";var debugAPIShortcutTitle=App.keyboardMappings.ctrlShiftTitle+"+8";var debugAPIMessageVersion=1;var showDebugAPIModeNotificationIfNeeded=function(){if(App.options.debugAPI&&App.DataModule.Storage.getStrCache(null,"debug-api-message-shown")!=debugAPIMessageVersion){App.showNotification({id:"debug-api",content:Backbone.Marionette.TemplateCache.get("#notification-content_debug-api")({debugAPIShortcut:debugAPIShortcutTitle}),onClose:function(){App.DataModule.Storage.setStrCache(null,"debug-api-message-shown",debugAPIMessageVersion?"1":0)},modifiers:["ttl_ever","type_warning"]})}};$document.bind("keydown",debugAPIShortcut,function(event){App.options.debugAPI=!App.options.debugAPI;if(!App.options.debugAPI){App.hideNotification("debug-api")}showDebugAPIModeNotificationIfNeeded();App.mainRegionView.render(true);App.DataModule.Storage.setStrCache(null,"debug-api",App.options.debugAPI?"1":"")});showDebugAPIModeNotificationIfNeeded();var minWidth=100;var step=20;var maxWidth=2e3;var changeEntityWidth=function(direction){var currentGrid=App.context.get("state").getConfigGridBeingShown();var currentEntityWidth=(currentGrid.get("entityWidth")||App.options.defaultEntityWidth)*1;var diff=direction>0?step:-step;var newEntityWidth=currentEntityWidth+diff;if(newEntityWidth>maxWidth){newEntityWidth=maxWidth}if(newEntityWidth<minWidth){newEntityWidth=minWidth}currentGrid.set("entityWidth",newEntityWidth)};$document.bind("keydown","pageup",function(event){changeEntityWidth(1);event.preventDefault()});$document.bind("keydown","pagedown",function(event){changeEntityWidth(-1);event.preventDefault()})}); "use strict";App.addInitializer(function(options){function getUrlParameter(sParam){var sPageURL=window.location.search.substring(1);var sURLVariables=sPageURL.split("&");for(var i=0;i<sURLVariables.length;i++){var sParameterName=sURLVariables[i].split("=");if(sParameterName[0]==sParam){return sParameterName.length==2?sParameterName[1]:""}}}var screenshotParameterValue=getUrlParameter("screenshot");if(screenshotParameterValue===undefined){return}console.log("Running in screenshot mode: "+screenshotParameterValue);App.options.vegaRenderer="canvas";window.devicePixelRatio=2;var $html=$("html");$html.addClass("screenshot");var screenshotTypes=_.invert(screenshotParameterValue.replace(/%7C/g,"|").split("|"));_.each(_.keys(screenshotTypes),function(screenshotType){$html.addClass("screenshot_"+screenshotType);var wh=screenshotType.split("x");if(wh.length==2){var w=parseInt(wh[0]);var h=parseInt(wh[1]);if(w&&h){$("body").css({width:w,height:h})}}});var intervalId=setInterval(function(){var ready=true;if(screenshotTypes["state_interface"]){}if(ready){if(screenshotTypes["state_interface"]){$(".player__slider-head_type_time").show().css("width","100%");$(".player__time_type_before").text("00:42");$(".player__time_type_after").text("−01:59")}if(screenshotTypes["state_flip"]){var frame=1;for(var i=2;i<7;i++){if(screenshotTypes["frame_"+i]){frame=i}}if(frame>=2&&frame<=5){App.context.get("state").set("musicRecordingsGridIsShown",true);setTimeout(function(){allDone()},frame*50)}return}allDone()}},5e3);var allDone=function(){window.status="screenshot_ready";console.log("screenshot is ready");clearInterval(intervalId)};if(screenshotTypes["state_interface"]){App.context.get("state").unserialize(JSON.parse('{"musicCollectionGrid":{"entityConfigs":[{"clientId":"cf1647","parameters":{"library":"bl","composer":"Mozart","year":"","performer":"","title":"Symphony; 41","collection":"","place":""},"plannedParameterUpdates":{}},{"clientId":"cf544","parameters":{"kind":"pair","comparisonMode":"superposition"},"plannedParameterUpdates":{}},{"clientId":"cf562","parameters":{"library":"bl","title":"Symphony; 40","year":"","composer":"Mozart","performer":"","place":"","collection":""},"plannedParameterUpdates":{"year":"1970-1979","title":"Sonata"}},{"clientId":"cf170","parameters":{"library":"charm","title":"","year":"","composer":"Mozart","performer":"","recordingURI":"http://dml.org/charm/2378"},"plannedParameterUpdates":{}},{"clientId":"cf224","parameters":{},"plannedParameterUpdates":{}}],"viewConfigs":[{"clientId":"custom17","parameters":{"kind":"list","limit":"10","offset":"6","sortBy":"label"},"plannedParameterUpdates":{}},{"clientId":"cf1783","parameters":{"kind":"tonic-histogram","widthToHeightRatio":"2"},"plannedParameterUpdates":{}},{"clientId":"cf780","parameters":{"kind":"key-relative-chord-seq","sequenceCount":"50","sequenceRepresentation":"parallel-coordinates","chordGrouppingIsByType":"1","guidesAreVisible":"1","recordingsInMajorModeAreIncluded":"1","recordingsInMinorModeAreIncluded":"1","chordTypesArePopularOnly":"","chordSequencesWithCyclesAreIncluded":"1","nIsIncluded":"","sequenceStepCount":"5"},"plannedParameterUpdates":{}}],"selectedEntityConfigClientId":"cf562","selectedViewConfigClientId":"cf780","entityWidth":260},"musicRecordingGrid":{"entityConfigs":[{"clientId":"cf204","parameters":{"recordingURI":"http://sounds.bl.uk/resource/026M-1LP0181227XX-0200V0"},"plannedParameterUpdates":{}},{"clientId":"cf209","parameters":{"recordingURI":"http://sounds.bl.uk/resource/026M-1LP0163217XX-0100V0"},"plannedParameterUpdates":{}},{"clientId":"cf214","parameters":{"recordingURI":"http://sounds.bl.uk/resource/026M-1CL0046563XX-0100V0"},"plannedParameterUpdates":{}},{"clientId":"cf219","parameters":{"recordingURI":"http://sounds.bl.uk/resource/026M-1LP0163226XX-0100V0"},"plannedParameterUpdates":{}}],"viewConfigs":[{"clientId":"def4","parameters":{"kind":"properties"},"plannedParameterUpdates":{}},{"clientId":"def5","parameters":{"kind":"midi-pitch-histogram"},"plannedParameterUpdates":{}}]}}'));App.play("http://dml.org/charm/2378");var $fakeMouse=$.bem.generateElement("screenshot","fake-cursor");$fakeMouse.css({left:335,top:430});$("body").append($fakeMouse);$fakeMouse.on("mouseover",function(event){console.log("here",arguments,$fakeMouse);event.pageX=335;event.pageY=430;App.TooltipModule.update(event,"C# → 15",$fakeMouse)});$fakeMouse.trigger("mouseover")}var teaserEntityWidth=200;if(screenshotTypes["state_teaser"]){App.context.get("state").unserialize(JSON.parse('{"musicCollectionGrid":{"entityConfigs":[{"clientId":"cf1647","parameters":{"library":"bl","composer":"","year":"","performer":"","title":"","collection":"uganda","place":""},"plannedParameterUpdates":{}},{"clientId":"cf544","parameters":{"kind":"pair","comparisonMode":"superposition"},"plannedParameterUpdates":{}},{"clientId":"cf1681","parameters":{"library":"bl","composer":"","year":"","performer":"","title":"","collection":"dinka","place":""},"plannedParameterUpdates":{}},{"clientId":"cf660","parameters":{"kind":"pair","comparisonMode":"superposition"},"plannedParameterUpdates":{}},{"clientId":"cf602","parameters":{"kind":"pair","comparisonMode":"direct"},"plannedParameterUpdates":{}},{"clientId":"cf718","parameters":{"library":"bl","composer":"schoenberg","year":"","performer":"","title":"","place":"","collection":""},"plannedParameterUpdates":{}},{"clientId":"cf480","parameters":{"library":"bl","composer":"","year":"","performer":"","title":"symphony","place":"","collection":""},"plannedParameterUpdates":{}},{"clientId":"cf418","parameters":{"library":"bl","title":"piano","year":"","composer":"","performer":"","place":"","collection":""},"plannedParameterUpdates":{}}],"viewConfigs":[{"clientId":"custom17","parameters":{"kind":"pitch-histogram"},"plannedParameterUpdates":{}},{"clientId":"custom18","parameters":{"kind":"midi-pitch-histogram"},"plannedParameterUpdates":{}},{"clientId":"cf1783","parameters":{"kind":"tuning-stats","widthToHeightRatio":"2"},"plannedParameterUpdates":{}},{"clientId":"cf780","parameters":{"kind":"pitch-class-histogram","widthToHeightRatio":"2"},"plannedParameterUpdates":{}},{"clientId":"cf481","parameters":{"kind":"tempo-histogram","tempoMin":"30","tempoMax":"300","tempoNumBins":"50","tempoPeriod":"1","widthToHeightRatio":"2"},"plannedParameterUpdates":{}}],"selectedEntityConfigClientId":"cf1647","entityWidth":200},"musicRecordingGrid":{"entityConfigs":[],"viewConfigs":[{"clientId":"def4","parameters":{"kind":"properties"},"plannedParameterUpdates":{}},{"clientId":"def5","parameters":{"kind":"midi-pitch-histogram"},"plannedParameterUpdates":{}}]}}'))}if(screenshotTypes["state_teaser-wo-piano"]){App.context.get("state").unserialize(JSON.parse('{"musicCollectionGrid":{"entityConfigs":[{"clientId":"cf1647","parameters":{"library":"bl","composer":"","year":"","performer":"","title":"","collection":"uganda","place":""},"plannedParameterUpdates":{}},{"clientId":"cf544","parameters":{"kind":"pair","comparisonMode":"superposition"},"plannedParameterUpdates":{}},{"clientId":"cf1681","parameters":{"library":"bl","composer":"","year":"","performer":"","title":"","collection":"dinka","place":""},"plannedParameterUpdates":{}},{"clientId":"cf660","parameters":{"kind":"pair","comparisonMode":"superposition"},"plannedParameterUpdates":{}},{"clientId":"cf602","parameters":{"kind":"pair","comparisonMode":"direct"},"plannedParameterUpdates":{}},{"clientId":"cf718","parameters":{"library":"bl","composer":"schoenberg","year":"","performer":"","title":"","place":"","collection":""},"plannedParameterUpdates":{}},{"clientId":"cf480","parameters":{"library":"bl","composer":"","year":"","performer":"","title":"symphony","place":"","collection":""},"plannedParameterUpdates":{}}],"viewConfigs":[{"clientId":"custom16","parameters":{"kind":"list"},"plannedParameterUpdates":{}},{"clientId":"custom17","parameters":{"kind":"pitch-histogram"},"plannedParameterUpdates":{}},{"clientId":"custom18","parameters":{"kind":"midi-pitch-histogram"},"plannedParameterUpdates":{}},{"clientId":"cf1783","parameters":{"kind":"tuning-stats","widthToHeightRatio":"2"},"plannedParameterUpdates":{}},{"clientId":"cf1872","parameters":{"kind":"mean-tempo-curve","widthToHeightRatio":"2"},"plannedParameterUpdates":{}},{"clientId":"cf780","parameters":{"kind":"pitch-class-histogram","widthToHeightRatio":"2"},"plannedParameterUpdates":{}},{"clientId":"cf481","parameters":{"kind":"tempo-histogram","tempoMin":"30","tempoMax":"300","tempoNumBins":"50","tempoPeriod":"1","widthToHeightRatio":"2"},"plannedParameterUpdates":{}},{"clientId":"cf1961","parameters":{"kind":"tonic-histogram","widthToHeightRatio":"2"},"plannedParameterUpdates":{}}],"selectedEntityConfigClientId":"cf1647","selectedViewConfigClientId":"","entityWidth":'+teaserEntityWidth+'},"musicRecordingGrid":{"entityConfigs":[],"viewConfigs":[{"clientId":"def4","parameters":{"kind":"properties"},"plannedParameterUpdates":{}},{"clientId":"def5","parameters":{"kind":"midi-pitch-histogram"},"plannedParameterUpdates":{}}]}}'))}if(screenshotTypes["state_flip"]){var musicRecordingsGridIsShown=screenshotTypes["frame_6"]?true:false;App.context.get("state").unserialize(JSON.parse('{"musicRecordingsGridIsShown":'+musicRecordingsGridIsShown+',"musicCollectionGrid":{"entityConfigs":[{"clientId":"cf1647","parameters":{"library":"charm","composer":"Mozart","year":"","performer":"","title":""},"plannedParameterUpdates":{}},{"clientId":"cf562","parameters":{"library":"charm","title":"","year":"","composer":"Haydn","performer":""},"plannedParameterUpdates":{}}],"viewConfigs":[{"clientId":"custom17","parameters":{"kind":"list","limit":"10","offset":"6","sortBy":"label"},"plannedParameterUpdates":{}},{"clientId":"cf1783","parameters":{"kind":"tempo-histogram","widthToHeightRatio":"2","tempoMin":"30","tempoMax":"300","tempoNumBins":"50","tempoPeriod":"1"},"plannedParameterUpdates":{}}],"selectedEntityConfigClientId":"cf1647","selectedViewConfigClientId":"cf1783","entityWidth":260},"musicRecordingGrid":{"entityConfigs":[{"clientId":"cf209","parameters":{"recordingURI":"http://sounds.bl.uk/resource/026M-1LP0163217XX-0100V0"},"plannedParameterUpdates":{}},{"clientId":"cf471","parameters":{"kind":"pair","comparisonMode":"direct"},"plannedParameterUpdates":{}},{"clientId":"cf219","parameters":{"recordingURI":"http://sounds.bl.uk/resource/026M-1LP0163226XX-0100V0"},"plannedParameterUpdates":{}}],"viewConfigs":[{"clientId":"def5","parameters":{"kind":"midi-pitch-histogram"},"plannedParameterUpdates":{}},{"clientId":"cf397","parameters":{"kind":"tempo-nonuniform","widthToHeightRatio":"2"},"plannedParameterUpdates":{}},{"clientId":"cf494","parameters":{"kind":"tempo-normalised","widthToHeightRatio":"2"},"plannedParameterUpdates":{}}],"selectedEntityConfigClientId":"cf471","selectedViewConfigClientId":"cf494","entityWidth":220}}'))}var resizeIfNeededAfterADelay=function(){setInterval(function(){if(screenshotTypes["autosize_grid"]||screenshotTypes["autosize"]){var $configGrid=$(".config-grid:visible");var $cellsSpace=$configGrid.find(".config-grid-cells__space");var maxX=0;var maxY=0;var $visInstances=$cellsSpace.find(".config-grid-cells__vis-instance");if(!$visInstances.length){resizeIfNeededAfterADelay();return}$visInstances.each(function(){var $visInstance=$(this);var position=$visInstance.position();var currentMaxX=position.left+$visInstance.width();var currentMaxY=position.top+$visInstance.height();if(currentMaxX>maxX){maxX=currentMaxX}if(currentMaxY>maxY){maxY=currentMaxY}});$cellsSpace.css({"padding-right":0,"padding-bottom":0,width:maxX,height:maxY,overflow:"visible"});if(screenshotTypes["autosize"]){var $body=$("body");$body.width($cellsSpace.offset().left+$cellsSpace.outerWidth());$body.height($cellsSpace.offset().top+$cellsSpace.outerHeight())}}},100)};resizeIfNeededAfterADelay();$(window).resize(resizeIfNeededAfterADelay)}); "use strict";App.module("HelpModule",function(HelpModule,App,Backbone,Marionette,$,_,Logger){HelpModule.startWithParent=false;var defaultModuleOptions={contentScrollDuration:200,resizeThrottleDuration:200,resizeDebounceDuration:200,scrollThrottleDuration:200,scrollDebounceDuration:200};var moduleOptions;var logger=null;var $help=null;var $helpBody=null;var $helpCloser=null;var $helpContentContainer=null;var $helpContent=null;var $helpContentHeaders=null;var $helpTocContainer=null;var $helpToc=null;var contentScrollSavedPosition=null;var resizing=false;var scrolling=false;var scrollingTo=null;var lastShownMaterialId=null;var pendingMaterialId=null;var $lastContentHeader=null;var assertModuleIsInitialized=function(){if(!$help){throw"HelpModule has not been initialized"}};var updateContentBottomMargin=null;var updateContentScrollSavedPosition=null;var restoreContentScrollSavedPosition=null;var updateTocCurrentItem=null;HelpModule.addInitializer(function(options){moduleOptions=_.extend(defaultModuleOptions,options);logger=Logger.get("HelpModule");updateContentBottomMargin=function(makeBigAndLockScroll){if(makeBigAndLockScroll){$helpContentContainer.css("overflow","hidden");$helpContent.css("border-bottom-width",1e4)}else{$helpContentContainer.css("overflow","scroll");$helpContent.css("border-bottom-width",Math.max(0,$helpContentContainer.outerHeight()-$helpContent.height()+$lastContentHeader.position().top-parseInt($helpContent.css("padding-bottom"),10)+parseInt($lastContentHeader.css("margin-top"),10)))}};updateContentScrollSavedPosition=function(){var scrollTop=$helpContentContainer.scrollTop();var $candidateHeader=$helpContentHeaders.first();for(var i=0;i<=$helpContentHeaders.length;i++){var $helpContentHeader=$($helpContentHeaders[i]);if(!$helpContentHeader.length||$helpContentHeader.position().top>=scrollTop){contentScrollSavedPosition=[Math.floor(scrollTop-$candidateHeader.position().top-parseInt($candidateHeader.css("margin-top")),10),$candidateHeader];updateTocCurrentItem();break}else{$candidateHeader=$helpContentHeader}}App.DataModule.Storage.setStrCache(HelpModule,"saved-scroll-position",contentScrollSavedPosition[0]+" "+contentScrollSavedPosition[1].attr("data-id"))};restoreContentScrollSavedPosition=function(animate){if(animate){scrollingTo=contentScrollSavedPosition[1].attr("data-id")}$helpContentContainer.stop(true,false).scrollTo(contentScrollSavedPosition[1].position().top+parseInt(contentScrollSavedPosition[1].css("margin-top"),10)+contentScrollSavedPosition[0],{duration:animate?moduleOptions.contentScrollDuration:0},function(){scrollingTo=null})};updateTocCurrentItem=function(){var newMaterialId=scrollingTo!==null?scrollingTo:contentScrollSavedPosition[1].attr("data-id");if(lastShownMaterialId!==newMaterialId){$helpToc.children().removeClass("help__toc-element_current");$helpToc.find(_.str.sprintf("[data-id='%s']",newMaterialId)).addClass("help__toc-element_current")}if(lastShownMaterialId!=newMaterialId){if(HelpModule.isShowing()){lastShownMaterialId=newMaterialId;HelpModule.trigger("show",{materialId:newMaterialId})}}};$help=$.bem.generateBlock("help").setMod("help","state","hidden");$helpBody=$.bem.generateElement("help","body");$helpContentContainer=$.bem.generateElement("help","content-container");$helpContent=$.bem.generateElement("help","content");$helpTocContainer=$.bem.generateElement("help","toc-container");$helpToc=$.bem.generateElement("help","toc");$helpCloser=$.bem.generateElement("help","closer");$help.click(function(event){if($help.hasMod("help","state_shown")){HelpModule.hide()}event.stopPropagation()});$helpBody.click(function(event){event.stopPropagation()});$helpContent.addClass("help-content").append($(Backbone.Marionette.TemplateCache.get("#help-content")({Ctrl:_.str.capitalize(App.keyboardMappings.ctrlTitle)})));var usedDataIds=[];$helpContentHeaders=$helpContent.find("h1, h2, h3");$helpContentHeaders.each(function(i,helpContentHeader){var $helpContentHeader=$(helpContentHeader);var title=$helpContentHeader.attr("data-toc");if(!title){title=$helpContentHeader.text()}var id=$helpContentHeader.attr("data-id");if(_.isUndefined(id)){id=_.str.slugify($helpContentHeader.text())}if(usedDataIds.indexOf(id)!=-1){throw _.str.sprintf("There are more than one header with id = '%s' in help",id)}usedDataIds.push(id);$helpContentHeader.attr("data-id",id);var $currentHelpTocElement=$.bem.generateElement("a","help","toc-element").attr("href",id?_.str.sprintf("#help/%s",id):"#help").attr("data-id",id).setMod("help","toc-element","hierarchy",$helpContentHeader.prop("tagName").slice(1)).text(title).click(function(event){if($.eventsugar.isAttemptToOpenInAnotherWindow(event)){return}event.preventDefault();HelpModule.show({materialId:id,forceScroll:true});return false});$helpToc.append($currentHelpTocElement);$lastContentHeader=$helpContentHeader});var rawSavedScrollPosition=App.DataModule.Storage.getStrCache(HelpModule,"saved-scroll-position");if(rawSavedScrollPosition){var i=rawSavedScrollPosition.indexOf(" ");var offset=parseInt(rawSavedScrollPosition.slice(0,i));var $materialHeader=$helpContentHeaders.filter(_.str.sprintf("[data-id='%s']",rawSavedScrollPosition.slice(i+1)));if($materialHeader.length){contentScrollSavedPosition=[offset,$materialHeader]}}if(!contentScrollSavedPosition){contentScrollSavedPosition=[0,$helpContentHeaders.first()]}lastShownMaterialId=contentScrollSavedPosition[1].attr("data-id");if(navigator&&navigator.appVersion&&navigator.appVersion.indexOf("Win")!=-1){$helpCloser.setMod("help","closer","position","right")}$helpCloser.click(function(event){if($help.hasMod("help","state_shown")){HelpModule.hide()}event.stopPropagation()});$helpContentContainer.append($helpContent);$helpTocContainer.append($helpToc);$helpBody.append($helpContentContainer,$helpTocContainer);$help.append($helpBody,$helpCloser);$(".app__help").append($help);$help.setMod("help","animating",true);var $window=$(window);$window.on("resize",function(){if(!HelpModule.isShowing()){return}if(!resizing){resizing=true;updateContentBottomMargin(true)}restoreContentScrollSavedPosition()});$window.on("resize",_.debounce(function(event){if(!HelpModule.isShowing()){return}updateContentBottomMargin();resizing=false;restoreContentScrollSavedPosition(true)},moduleOptions.resizeDebounceDuration));$helpContentContainer.on("scroll",_.throttle(function(event){if(!resizing){scrolling=true;updateContentScrollSavedPosition()}},moduleOptions.scrollThrottleDuration,{trailing:false}));$helpContentContainer.on("scroll",_.debounce(function(event){scrolling=false;updateContentScrollSavedPosition();if(HelpModule.isShowing()&&pendingMaterialId!==null&&pendingMaterialId!=lastShownMaterialId&&pendingMaterialId!=contentScrollSavedPosition[1].attr("data-id")){contentScrollSavedPosition=[0,$helpContentHeaders.filter(_.str.sprintf("[data-id='%s']",pendingMaterialId))];pendingMaterialId=null;restoreContentScrollSavedPosition(true)}else{pendingMaterialId=null}},moduleOptions.scrollDebounceDuration));new ScrollFix($helpContentContainer.get(0));$helpContentContainer.get(0).addEventListener("touchmove",function(event){event.stopPropagation()});var helpContentHasVimeo=false;$helpContent.find("iframe").each(function(){var $iframe=$(this);var src=$iframe.attr("src");if(!_.isString(src)){src=""}if(src.indexOf("vimeo")!==-1){helpContentHasVimeo=true;$(this).attr("data-type","vimeo")}});if(helpContentHasVimeo){var scriptElement=document.createElement("script");scriptElement.type="text/javascript";scriptElement.async=true;scriptElement.src="http://a.vimeocdn.com/js/froogaloop2.min.js";document.getElementsByTagName("body")[0].appendChild(scriptElement)}});HelpModule.show=function(options){var options=$.extend({},options);assertModuleIsInitialized();var helpIsOpening=false;if($help.hasMod("help","state_hidden")||$help.hasMod("help","state_pre-hidden")){helpIsOpening=true;$help.toggleClass("help_animating",!options.instant);$help.setMod("help","state","pre-shown");lastShownMaterialId=null;pendingMaterialId=null;updateContentBottomMargin()}var needToScroll=true;var $materialHeader=$helpContent.find(_.str.sprintf("[data-id='%s']",options.materialId));if($materialHeader.length){pendingMaterialId=options.materialId;if(!scrolling){if(options.forceScroll||!contentScrollSavedPosition[1].is($materialHeader)){contentScrollSavedPosition=[0,$materialHeader]}else{needToScroll=false}}}if(helpIsOpening||needToScroll&&(!scrolling||scrollingTo!==null)){restoreContentScrollSavedPosition(!helpIsOpening);updateTocCurrentItem()}if(!needToScroll){scrollingTo=null;pendingMaterialId=null}if($help.hasMod("help","state_pre-shown")){$help.setMod("help","state","shown")}if(!!options.instant){setTimeout(function(){$help.setMod("help","animating",true)},10)}};HelpModule.hide=function(){assertModuleIsInitialized();$helpContent.find("iframe[data-type=vimeo]").each(function(){if(window.$f){$f(this).api("pause")}});$help.setMod("help","state","pre-hidden");HelpModule.trigger("hide");setTimeout(function(){if($help.hasMod("help","state_pre-hidden")){$help.setMod("help","state","hidden")}},1e3)};HelpModule.isShowing=function(){return $help.hasMod("help","state_pre-shown")||$help.hasMod("help","state_shown")}},Logger); "use strict";App.module("NotificationsModule",function(NotificationsModule,App,Backbone,Marionette,$,_,Logger){NotificationsModule.startWithParent=false;var defaultModuleOptions={defaultTTL:10,minTTLOnUnfreeze:6};var moduleOptions;var logger=null;var $notifications=null;var $notificationStack=null;var addNewNotification=null;var removeNotification=null;var updateNotification=null;var notificationTimeoutHandler=null;var assertModuleIsInitialized=function(){if(!$notifications){throw"NotificationsModule has not been initialized"}};NotificationsModule.addInitializer(function(options){moduleOptions=_.extend(defaultModuleOptions,options);logger=Logger.get("NotificationsModule");logger.debug("Begin init");$notifications=$(".app__notifications").addClass("notifications");$notificationStack=$.bem.generateElement("notifications","stack").appendTo($notifications);var setupNotification=function($notification,notificationOptions){var $notificationContent=$notification.children().eq(0).children().eq(0);if(!$notificationContent.hasClass("notification__content")){$notificationContent=$notificationContent.children().eq(0)}$notificationContent.children().detach();if(notificationOptions.content instanceof $){$notificationContent.append(notificationOptions.content)}else{$notificationContent.html(notificationOptions.content)}$notification.attr("data-id",notificationOptions.id);$notification.data("options",notificationOptions);$notification.data("$content",$notificationContent);var modifiersAsArray=null;if(_.isString(notificationOptions.modifiers)){modifiersAsArray=notificationOptions.modifiers.split(" ")}if(_.isArray(notificationOptions.modifiers)){modifiersAsArray=notificationOptions.modifiers}var state=$notification.getMod("notification","state");$notification.attr("class","notification notification_state_"+state);if(_.isArray(modifiersAsArray)&&modifiersAsArray.length){$notification.addClass("notification_"+modifiersAsArray.join(" notification_"))}if(!$notification.getMod("notification","ttl")){$notification.setMod("notification","ttl",moduleOptions.defaultTTL)}};var freezeTTL=function(){logger.debug("Freeze ttl",this);$(this).addClass("notification_ttl-frozen")};var unfreezeTTL=function(){logger.debug("Unfreeze ttl",this);var $this=$(this);var ttl=$this.getMod("notification","ttl");if(ttl*1==ttl&&ttl<moduleOptions.minTTLOnUnfreeze){$this.setMod("notification","ttl",moduleOptions.minTTLOnUnfreeze)}$this.removeClass("notification_ttl-frozen")};var stopTTL=function(){logger.debug("Stop ttl",this);$(this).setMod("notification","ttl","ever")};addNewNotification=function(notificationOptions){logger.info("Adding new notificaton",notificationOptions);var $notificationContent=$.bem.generateElement("notification","content");var $notificationCloser=$.bem.generateElement("notification","closer");var $notificationBody=$.bem.generateElement("notification","body").append($notificationContent,$notificationCloser);var $notification=$.bem.generateBlock("notification").append($notificationBody);var closeFunction=function(){removeNotification($notification);var onClose=notificationOptions.onClose;if(_.isFunction(onClose)){try{onClose($notification)}catch(e){logger.error("Error when handling onClose",e,$notification,onClose)}}};$notificationCloser.click(closeFunction);$notification.mouseover(freezeTTL);$notification.mouseout(unfreezeTTL);$notification.click(stopTTL);setupNotification($notification,notificationOptions);$notification.setMod("notification","state","pre-shown");$notification.appendTo($notificationStack);var notificationBodyHeight=$notificationBody.outerHeight();$notification.height(notificationBodyHeight);$notification.hide();$notificationBody.hide();$notification.show("blind",{direction:"up"},$notificationStack.children().length==1?1:100+notificationBodyHeight/10*30,function(){$notificationBody.show("slide",{direction:"right",easing:"easeOutQuart"},500,function(){$notification.setMod("notification","state","shown")})})};updateNotification=function($notification,notificationOptions){logger.info("Updating notification",$notification,"with new options",notificationOptions);if($notification.length!==1){logger.error(_.str.sprintf("Can’t replace a notification, this can be done only when $notification contains a single instance.",$notification));return}setupNotification($notification,notificationOptions);if(!$notification.is(":animated")&&$notification.hasClass("notification_state_shown")){$notification.effect("shake",{direction:"up",distance:5,times:2})}};removeNotification=function($notification){logger.debug("Begin remove notification",$notification);if($notification.hasMod("notification","state_pre-hidden")){logger.debug("Notification",$notification,"is already being hidden by another handler");return}$notification.setMod("notification","state","pre-hidden");var $notificationBody=$notification.children().eq(0);var notificationBodyHeight=$notificationBody.outerHeight();$notification.children().eq(0).fadeOut(200,function(){$notification.hide("blind",{direction:"up"},100+notificationBodyHeight/10*30,function(){if($notification.data("options").keepContentInMemoryAfterRemoval){$notification.data("$content").detach()}$notification.remove()})})};notificationTimeoutHandler=setInterval(function(){logger.debug("Notification lifetime interval triggered");$notificationStack.children().filter(".notification_state_shown").not(".notification_ttl-frozen").each(function(){var $thisNotification=$(this);var ttl=$thisNotification.getMod("notification","ttl");if(ttl*1!=ttl){return}ttl=ttl-1;if(ttl<0){removeNotification($thisNotification);var onExpire=$thisNotification.data("options").onExpire;if(_.isFunction(onExpire)){try{onExpire($thisNotification)}catch(e){logger.error("Error when handling onExpire",e,$thisNotification,onExpire)}}}else{$thisNotification.setMod("notification","ttl",ttl)}})},1e3);logger.debug("End init")});NotificationsModule.show=function(notificationOptions){assertModuleIsInitialized();logger.debug("Begin showing a new notification",notificationOptions);var extendedNotificationOptions=_.extend({id:null,modifiers:null,content:"",onClose:null,onExpire:null,keepContentInMemoryAfterRemoval:false},notificationOptions);if(extendedNotificationOptions.id){var $notificationWithTheSameId=$notificationStack.find(_.str.sprintf(".notification[data-id='%s']",extendedNotificationOptions.id)).not(".notification_state_pre-hidden");logger.debug("Detection of a notification witht the same id",extendedNotificationOptions.id,$notificationWithTheSameId,$notificationStack.children());if($notificationWithTheSameId.length&&($notificationWithTheSameId.hasMod("notification","state_shown")||$notificationWithTheSameId.hasMod("notification","state_pre-shown"))){if($notificationWithTheSameId.offset().top<0){removeNotification($notificationWithTheSameId);addNewNotification(extendedNotificationOptions)}else{updateNotification($notificationWithTheSameId,extendedNotificationOptions)}}else{addNewNotification(extendedNotificationOptions)}}else{addNewNotification(extendedNotificationOptions)}logger.debug("End showing a new notification",notificationOptions)};NotificationsModule.hide=function(notificationId){var $notification=$notificationStack.find(_.str.sprintf(".notification[data-id='%s']",notificationId)).not(".notification_state_pre-hidden");if($notification.length){removeNotification($notification)}}},Logger); "use strict";App.module("PlayerModule",function(PlayerModule,App,Backbone,Marionette,$,_,Logger){PlayerModule.startWithParent=false;var defaultModuleOptions={};var moduleOptions;var logger=null;var assertModuleIsInitialized=function(){if(!$notifications){throw"PlayerModule has not been initialized"}};PlayerModule.addInitializer(function(options){moduleOptions=_.extend(defaultModuleOptions,options);logger=Logger.get("PlayerModule");logger.debug("Begin init");PlayerModule.$player=$(Marionette.TemplateCache.get("#player")());PlayerModule.$playerTimeAfter=PlayerModule.$player.find(".player__time_type_after");PlayerModule.$player.hide().appendTo("body");PlayerModule.$jPlayer=$("<div/>").hide().appendTo("body");var volume=App.DataModule.Storage.getStrCache(PlayerModule,"volume");if(volume!==undefined){volume=parseFloat(volume)}if(!_.isNumber(volume)||_.isNaN(volume)||volume<0&&volume>1){volume=undefined}var muted=App.DataModule.Storage.getStrCache(PlayerModule,"muted")?true:false;PlayerModule.$jPlayer.jPlayer({swfPath:"./$/jquery.jplayer.swf",supplied:"mp3",wmode:"window",cssSelectorAncestor:".player__body",useStateClassSkin:true,autoBlur:false,smoothPlayBar:false,keyEnabled:false,remainingDuration:true,toggleDuration:false,volume:volume,solution:"html,flash",muted:muted,cssSelector:{play:".player__command_action_play",pause:".player__command_action_pause",mute:".player__command_action_volume-mute",unmute:".player__command_action_volume-down",volumeMax:".player__command_action_volume-up",volumeBar:".player__slider_type_volume",volumeBarValue:".player__slider-head_type_volume",seekBar:".player__slider_type_time",playBar:".player__slider-head_type_time",currentTime:".player__time_type_before",duration:".player__time_type_after"}});PlayerModule.$jPlayer.on($.jPlayer.event.volumechange,function(event){var volume=PlayerModule.$jPlayer.jPlayer("option","volume");var muted=PlayerModule.$jPlayer.jPlayer("option","muted");App.DataModule.Storage.setStrCache(PlayerModule,"volume",volume+"");App.DataModule.Storage.setStrCache(PlayerModule,"muted",muted?"1":"")});PlayerModule.PlayerView=Backbone.View.extend({el:PlayerModule.$player,initialize:function(){var _this=this;_this.$body=_this.$el.find(".player__body");App.TooltipModule.convertTitlesToTooltips(_this.$el);_this.$el.show();_this.$commandDownload=_this.$(".player__command_action_download");_this.$commandDownload.click(function(event){PlayerModule.$jPlayer.jPlayer("pause")});_this.$label1=_this.$(".player__label_row_1");_this.$label2=_this.$(".player__label_row_2");_this.$cover=_this.$(".player__cover");_this.$messageError=_this.$(".player__message_type_error");_this.$messageLoading=_this.$(".player__message_type_loading");_this.$messageNoRecording=_this.$(".player__message_type_no-recording");_this.$messageNoAudio=_this.$(".player__message_type_no-audio");_this._startPlayingAfterRecordingIsLoaded=false;_this._config=new App.ContextModule.Config;_this._dynamicDefinitionForRecording=App.dynamicDefinitionProviderForRecordings.get(_this._config);_this.listenTo(_this._dynamicDefinitionForRecording,"change",_this.render);_this.listenTo(_this._config,"change",_this.render);this._cachedLabel="initial";_this.render()},render:function(){var _this=this;var recordingAttributes=_this._dynamicDefinitionForRecording.attributes;var label=recordingAttributes.label;var audio=recordingAttributes.audio?recordingAttributes.audio[0]:undefined;if(!_.isEqual(_this._cachedRecordingAttributes,recordingAttributes)){if(!_this._dynamicDefinitionForRecording.attributes.label||!audio){_this.$body.hide();_this.$cover.show();_this.$cover.children().hide();switch(label){case false:_this.$messageError.show();break;case null:_this.$messageLoading.show();break;default:if(label===undefined){_this.$messageNoRecording.show()}else{_this.$messageNoAudio.show()}}PlayerModule.$jPlayer.jPlayer("stop")}else{PlayerModule.$jPlayer.jPlayer("setMedia",{mp3:audio});_this.$cover.hide();_this.$body.show();_this.$label1.text(recordingAttributes.label);_this.$label2.text(recordingAttributes.composer);_this.$commandDownload.attr("href",audio);if(_this._startPlayingAfterRecordingIsLoaded){PlayerModule.$jPlayer.jPlayer("play");_this._startPlayingAfterRecordingIsLoaded=false}}}if(label){}_this._cachedRecordingAttributes=recordingAttributes},play:function(recordingURI,time){var _this=this;if(_this._config.getParameterValue("recordingURI")!=recordingURI){_this._startPlayingAfterRecordingIsLoaded=true;_this._config.updateParameter("recordingURI",recordingURI)}else{PlayerModule.$jPlayer.jPlayer("play",time?time:0)}},stop:function(recordingURI){var _this=this;PlayerModule.$jPlayer.jPlayer("pause")}});PlayerModule.playerView=new PlayerModule.PlayerView});PlayerModule.play=function(recordingURI,time){PlayerModule.playerView.play(recordingURI,time);App.NotificationsModule.show({id:"player",content:PlayerModule.playerView.$el,onClose:function(){PlayerModule.playerView.stop()},modifiers:["ttl_ever","no-padding"],keepContentInMemoryAfterRemoval:true})}},Logger); "use strict";App.module("TooltipModule",function(TooltipModule,App,Backbone,Marionette,$,_){var renderFunctions={};var OBJECT_TYPE_CHORD_SEQUENCE=1;TooltipModule.addInitializer(function(){TooltipModule.TooltipView=Backbone.View.extend({initialize:function(options){var _this=this;_this.$tooltip=$("<div/>").addClass("tooltip").appendTo("body")},update:function(mouseEvent,title,target){var _this=this;if(!mouseEvent||mouseEvent.type=="mouseout"||mouseEvent.type=="mouseup"||!title){_this.previousTarget=null;_this.$tooltip.addClass("tooltip_animation_slow-opacity");_this.$tooltip.removeClass("tooltip_state_visible")}else{if(target!=_this.previousTarget){_this.$tooltip.removeClass("tooltip_animation_slow-opacity");_this.$tooltip.addClass("tooltip_state_visible");_this.$tooltip.html(title)}_this.$tooltip.position({of:mouseEvent,my:"left+20 topt+20",collision:"flip flip"})}}});TooltipModule.tooltipView=new TooltipModule.TooltipView;TooltipModule._updateTooltipForDOMNodeWithExTitle=function(mouseEvent){TooltipModule.tooltipView.update(mouseEvent,$(this).attr("tooltip-title"),this)};TooltipModule.update=function(mouseEvent,title,target){TooltipModule.tooltipView.update(mouseEvent,title,target)};TooltipModule.convertTitlesToTooltips=function($container){$container.find("[title]").each(function(){var $this=$(this);$this.attr("tooltip-title",$this.attr("title")).removeAttr("title");if(App.options.enableTooltipsForControlsWithTitles){$this.on("mouseover",TooltipModule._updateTooltipForDOMNodeWithExTitle).on("mouseout",TooltipModule._updateTooltipForDOMNodeWithExTitle).on("mousemove",TooltipModule._updateTooltipForDOMNodeWithExTitle).on("mouseup",TooltipModule._updateTooltipForDOMNodeWithExTitle)}})}})}); "use strict";App.module("ContextModule",function(ContextModule,App,Backbone,Marionette,$,_,Logger){ContextModule.startWithParent=false;var defaultModuleOptions={stateHistoryMaxLength:20};var logger=null;var assertModuleIsInitialized=function(){if(!logger){throw"ContextModule has not been initialized"}};ContextModule.addInitializer(function(options){ContextModule.moduleOptions=_.extend(defaultModuleOptions,options);logger=Logger.get("ContextModule")})},Logger); "use strict";App.module("ContextModule",function(ContextModule,App,Backbone,Marionette,$,_,Logger){var logger=null;ContextModule.addInitializer(function(options){logger=Logger.get("ContextModule.Config");logger.setLevel(Logger.WARN);ContextModule.Config=Backbone.Model.extend({cidPrefix:"cf",constructor:function(attributes,options){this._modificationPropagationEnabled=true;this._parametersWereModified=false;this._plannedParameterUpdatesWereModified=false;this._cachedHashForTrimmedParameters=null;this._cachedHashForParameters=null;this._cachedHashForPlannedParameterUpdates=null;this._cachedHashForPermanent=null;this._cachedHashForTemp=null;this._cachedHash=null;var defaultParameters=_.isSimpleObject(attributes)&&_.isSimpleObject(attributes.parameters)?attributes.parameters:undefined;var defaultPlannedParameterUpdates=_.isSimpleObject(attributes)&&_.isSimpleObject(attributes.plannedParameterUpdates)?attributes.plannedParameterUpdates:undefined;var realAttributes={};realAttributes.parameters=new Backbone.Model(defaultParameters);realAttributes.plannedParameterUpdates=new Backbone.Model(defaultPlannedParameterUpdates);this.listenTo(realAttributes.parameters,"change",this._registerModificationOfParameters);this.listenTo(realAttributes.plannedParameterUpdates,"change",this._registerModificationOfPlannedParameterUpdates);Backbone.Model.apply(this,[realAttributes,options]);if(attributes&&attributes.clientId){this.cid=attributes.clientId;_.markUniqueIdAsAlreadyUsed(attributes.clientId)}},getClientId:function(){return this.cid},getDimension:function(){return this.collection?this.collection.dimension:undefined},getConfigGridType:function(){return this.collection?this.collection.configGridType:undefined},getParameterValue:function(parameterName){return this.attributes.parameters.attributes[parameterName]},getPlannedParameterValue:function(parameterName){var plannedParameterUpdatesAttributes=this.attributes.plannedParameterUpdates.attributes;if(plannedParameterUpdatesAttributes.hasOwnProperty(parameterName)){return plannedParameterUpdatesAttributes[parameterName]}else{return this.attributes.parameters.attributes[parameterName]}},getPlannedParameterValues:function(parameterName){var result=_.clone(this.attributes.parameters.attributes);var plannedParameterUpdatesAttributes=this.attributes.plannedParameterUpdates.attributes;for(var key in plannedParameterUpdatesAttributes){if(plannedParameterUpdatesAttributes.hasOwnProperty(key)){if(plannedParameterUpdatesAttributes[key]===undefined){if(result.hasOwnProperty(key)){delete result[key]}}else{result[key]=plannedParameterUpdatesAttributes[key]}}}return result},isPlannedToUpdate:function(parameterName){return this.attributes.plannedParameterUpdates.attributes.hasOwnProperty(parameterName)},hasPlannedParameterUpdates:function(){return _.size(this.attributes.plannedParameterUpdates.attributes)>0},updateParameter:function(parameterName,parameterValue){if(!_.isString(parameterName)){throw _.str.sprintf("Config::updateParameter called a non-string parameterName: %s",parameterName)}var prevModificationPropagationEnabled=this._modificationPropagationEnabled;this._modificationPropagationEnabled=false;this.attributes.plannedParameterUpdates.unset(parameterName);if(typeof parameterValue!=="undefined"){this.attributes.parameters.set(parameterName,parameterValue)}else{this.attributes.parameters.unset(parameterName)}if(prevModificationPropagationEnabled){this._triggerModificationEventsIfNeeded();this._modificationPropagationEnabled=true}},planParameterUpdate:function(parameterName,parameterValue){if(!_.isString(parameterName)){throw _.str.sprintf("Config::planParameterUpdate called a non-string parameterName: %s",parameterName)}var prevModificationPropagationEnabled=this._modificationPropagationEnabled;this._modificationPropagationEnabled=false;var plannedParameterUpdatesAttributes=this.attributes.plannedParameterUpdates.attributes;var parametersAttributes=this.attributes.parameters.attributes;if(parameterValue===parametersAttributes[parameterName]){if(this.attributes.plannedParameterUpdates.attributes.hasOwnProperty(parameterName)&&this.attributes.plannedParameterUpdates.attributes[parameterName]===undefined){this.attributes.plannedParameterUpdates.set(parameterName,42,{silent:true})}this.attributes.plannedParameterUpdates.unset(parameterName)}else{if(parameterValue===undefined&&this.attributes.parameters.attributes.hasOwnProperty(parameterName)&&!this.attributes.plannedParameterUpdates.attributes.hasOwnProperty(parameterName)){this.attributes.plannedParameterUpdates.set(parameterName,42,{silent:true})}this.attributes.plannedParameterUpdates.set(parameterName,parameterValue)}if(prevModificationPropagationEnabled){this._triggerModificationEventsIfNeeded();this._modificationPropagationEnabled=true}},cancelPlannedParameterUpdate:function(parameterName){if(!_.isString(parameterName)){throw _.str.sprintf("Config::cancelPlannedParameterUpdate called a non-string parameterName: %s",parameterName)}var prevModificationPropagationEnabled=this._modificationPropagationEnabled;this._modificationPropagationEnabled=false;this.attributes.plannedParameterUpdates.unset(parameterName);if(prevModificationPropagationEnabled){this._triggerModificationEventsIfNeeded();this._modificationPropagationEnabled=true}},updateParameters:function(parameters){if(!_.isSimpleObject(parameters)){throw _.str.sprintf("Config::updateParameters called a wrong argument: %s",parameters)}this._modificationPropagationEnabled=false;for(var parameterName in parameters){if(parameters.hasOwnProperty(parameterName)){this.updateParameter(parameterName,parameters[parameterName])}}this._triggerModificationEventsIfNeeded();this._modificationPropagationEnabled=true},planParameterUpdates:function(parameters){if(!_.isSimpleObject(parameters)){throw _.str.sprintf("Config::planParameterUpdates called with a wrong argument: %s",parameters)}this._modificationPropagationEnabled=false;for(var parameterName in parameters){if(parameters.hasOwnProperty(parameterName)){this.planParameterUpdate(parameterName,parameters[parameterName])}}this._triggerModificationEventsIfNeeded();this._modificationPropagationEnabled=true},cancelPlannedParameterUpdates:function(parameterNames){if(_.isArray(parameterNames)){this._modificationPropagationEnabled=false;for(var i=0;i<parameterNames.length;i++){this.cancelPlannedParameterUpdate(parameterNames[i])}this._triggerModificationEventsIfNeeded();this._modificationPropagationEnabled=true}else if(!_.isUndefined(parameterNames)){throw _.str.sprintf("Config::planParameterUpdates called a non-string parameters: %s",parameters)}else{if(_.keys(this.attributes.plannedParameterUpdates.attributes).length){this.attributes.plannedParameterUpdates.attributes.fix=42}this.attributes.plannedParameterUpdates.clear()}},applyPlannedParameterUpdates:function(){var newParameters=_.extend(this.attributes.parameters.toJSON(),this.attributes.plannedParameterUpdates.toJSON());for(var key in newParameters){if(!newParameters.hasOwnProperty(key))continue;if(typeof newParameters[key]==="undefined"){delete newParameters[key]}}var attributesInPlannedParameterUpdates=this.attributes.plannedParameterUpdates.attributes;for(var key in attributesInPlannedParameterUpdates){if(attributesInPlannedParameterUpdates[key]===undefined){attributesInPlannedParameterUpdates[key]=42;break}}this.unserialize({clientId:this.cid,parameters:newParameters,plannedParameterUpdates:{}})},serialize:function(){var result={clientId:this.cid,parameters:this.attributes.parameters.toJSON(),plannedParameterUpdates:this.attributes.plannedParameterUpdates.toJSON()};return result},unserialize:function(serializedAttributes){var fixedSerializedAttributes=serializedAttributes;if(!_.isSimpleObject(serializedAttributes)){logger.warn("Config::unserialize called for not an object: ",serializedAttributes);fixedSerializedAttributes={}}if(this.cid!=fixedSerializedAttributes.clientId&&!_.isUndefined(fixedSerializedAttributes.clientId)){throw _.str.sprintf("Parameter bag client id (%s) is not equal to the client id of the serialized object (%s).",this.cid,fixedSerializedAttributes.clientId)}this._parametersWereModified=false;this._plannedParameterUpdatesWereModified=false;this._modificationPropagationEnabled=false;var fixedSerializedPlannedParameterUpdates=fixedSerializedAttributes.plannedParameterUpdates;if(!_.isSimpleObject(fixedSerializedPlannedParameterUpdates)){if(_.isSimpleObject(serializedAttributes)){logger.warn("Config::unserialize called for object with faulty plannedParameterUpdates: ",fixedSerializedPlannedParameterUpdates)}fixedSerializedPlannedParameterUpdates={}}if(!_.isEqual(this.attributes.plannedParameterUpdates.attributes,fixedSerializedPlannedParameterUpdates)){this.attributes.plannedParameterUpdates.set("fix",42,{silent:true}).clear().set(fixedSerializedPlannedParameterUpdates)}var fixedSerializedParameters=fixedSerializedAttributes.parameters;if(!_.isSimpleObject(fixedSerializedParameters)){if(_.isSimpleObject(serializedAttributes)){logger.warn("Config::unserialize called for object with faulty parameters: ",fixedSerializedParameters)}fixedSerializedParameters={}}if(!_.isEqual(this.attributes.parameters.toJSON(),fixedSerializedParameters)){this.attributes.parameters.clear().set(fixedSerializedParameters)}this._triggerModificationEventsIfNeeded();this._modificationPropagationEnabled=true},clone:function(){var serializedAttributes=this.serialize();delete serializedAttributes.clientId;return new ContextModule.Config(serializedAttributes)},getHashForParameters:function(){if(this._cachedHashForParameters===null){this._cachedHashForParameters=JSON.stringify(this.attributes.parameters.attributes)}return this._cachedHashForParameters},getHashForTrimmedParameters:function(){if(this._cachedHashForTrimmedParameters===null){var attributesToHash=_.clone(this.attributes.parameters.attributes);for(var key in attributesToHash){if(attributesToHash.hasOwnProperty(key)&&_.isString(attributesToHash[key])){attributesToHash[key]=_.str.trim(attributesToHash[key])}}this._cachedHashForTrimmedParameters=JSON.stringify(attributesToHash)}return this._cachedHashForTrimmedParameters},getHashForPlannedParameterUpdates:function(){if(this._cachedHashForPlannedParameterUpdates===null){var attributes=this.attributes.plannedParameterUpdates.attributes;this._cachedHashForPlannedParameterUpdates=JSON.stringify(attributes);for(var key in attributes){if(attributes.hasOwnProperty(key)&&attributes[key]===undefined){this._cachedHashForPlannedParameterUpdates+=key+"|"}}}return this._cachedHashForPlannedParameterUpdates},getHashForPermanent:function(){if(this._cachedHashForPermanent===null){this._cachedHashForPermanent=this.getHashForParameters()+this.getHashForPlannedParameterUpdates()}return this._cachedHashForPermanent},getHashForTemp:function(){if(this._cachedHashForTemp===null){this._cachedHashForTemp=""}return this._cachedHashForTemp},getHash:function(){if(!this._cachedHash){this._cachedHash=this.getHashForPermanent()+this.getHashForTemp()}return this._cachedHash},_registerModificationOfParameters:function(){this._cachedHashForParameters=null;this._cachedHashForTrimmedParameters=null;this._cachedHashForPermanent=null;this._cachedHash=null;this._parametersWereModified=true;if(this._modificationPropagationEnabled){this._triggerModificationEventsIfNeeded()}},_registerModificationOfPlannedParameterUpdates:function(){this._cachedHashForPlannedParameterUpdates=null;this._cachedHashForPermanent=null;this._cachedHash=null;this._plannedParameterUpdatesWereModified=true;if(this._modificationPropagationEnabled){this._triggerModificationEventsIfNeeded()}},_triggerModificationEventsIfNeeded:function(){this.changed=[true];if(this._parametersWereModified){this.trigger("change:parameters")}if(this._plannedParameterUpdatesWereModified){this.trigger("change:plannedParameterUpdates")}if(this._tempParametersWereModified){this.trigger("change:tempParameters")}if(this._parametersWereModified||this._plannedParameterUpdatesWereModified){this.trigger("change:parametersOrPlannedParameterUpdates");this.trigger("change")}this._parametersWereModified=false;this._plannedParameterUpdatesWereModified=false;this._tempParametersWereModified=false;this.changed=null}})})},Logger); "use strict";App.module("ContextModule",function(ContextModule,App,Backbone,Marionette,$,_,Logger){var logger=null;ContextModule.addInitializer(function(options){ContextModule.ConfigCollection=Backbone.Collection.extend({model:ContextModule.Config,initialize:function(configs,options){this.configGridType=options.configGridType;this.dimension=options.dimension}})})},Logger); "use strict";App.module("ContextModule",function(ContextModule,App,Backbone,Marionette,$,_,Logger){var logger=null;ContextModule.addInitializer(function(options){logger=Logger.get("ContextModule.ConfigGrid");logger.setLevel(Logger.WARN);ContextModule.ConfigGrid=Backbone.Model.extend({defaults:{entityConfigs:null,viewConfigs:null,selectedEntityConfigClientId:null,selectedViewConfigClientId:null},initialize:function(type){this.type=type;this.attributes.entityConfigs=new ContextModule.ConfigCollection(null,{comparator:false,configGridType:type,dimension:"entity"});this.attributes.viewConfigs=new ContextModule.ConfigCollection(null,{comparator:false,configGridType:type,dimension:"view"});this.entityConfigs=this.attributes.entityConfigs;this.viewConfigs=this.attributes.viewConfigs;this._modificationPropagationEnabled=true;this._configCollectionsWereModified=false;this._configsWereModified=false;this._modifiedEntityConfigClientIds=[];this._modifiedViewConfigClientIds=[];this._lastSavedOrderedEntityClientIds=_.pluck(this.attributes.entityConfigs.models,"cid");this._lastSavedOrderedViewClientIds=_.pluck(this.attributes.viewConfigs.models,"cid");this._lastSavedSelectedEntityConfigClientId=this.attributes.selectedEntityConfigClientId;this._lastSavedSelectedViewConfigClientId=this.attributes.selectedViewConfigClientId;this.entityConfigs.bind("add remove reset sort",this._registerModificationOfConfigCollectionForEntities,this);this.viewConfigs.bind("add remove reset sort",this._registerModificationOfConfigCollectionForViews,this);this.entityConfigs.bind("change",this._registerModificationOfConfig,this);this.viewConfigs.bind("change",this._registerModificationOfConfig,this);this.bind("change:selectedEntityConfigClientId",this._registerModificationOfAtomicProperty);this.bind("change:selectedViewConfigClientId",this._registerModificationOfAtomicProperty);this.bind("change:entityWidth",this._registerModificationOfStandardAtomicProperty)},getType:function(){return this.type},getPrevEntityNeighbour:function(entityConfig){return this._getNeighbour(this.attributes.entityConfigs,entityConfig,-1)},getNextEntityNeighbour:function(entityConfig){return this._getNeighbour(this.attributes.entityConfigs,entityConfig,1)},getPrevViewNeighbour:function(viewConfig){return this._getNeighbour(this.attributes.viewConfigs,viewConfig,-1)},getNextViewNeighbour:function(viewConfig){return this._getNeighbour(this.attributes.viewConfigs,viewConfig,1)},relocateEntityConfig:function(entityConfig,indexOrNextConfigOrNextConfigClientId){return this._relocate(this.attributes.entityConfigs,entityConfig,indexOrNextConfigOrNextConfigClientId)},relocateViewConfig:function(viewConfig,indexOrNextConfigOrNextConfigClientId){return this._relocate(this.attributes.viewConfigs,viewConfig,indexOrNextConfigOrNextConfigClientId)},serialize:function(){logger.debug("method called: ConfigGrid::serialize");var _this=this;var result={entityConfigs:this.attributes.entityConfigs.map(function(config){return config.serialize()}),viewConfigs:this.attributes.viewConfigs.map(function(config){return config.serialize()})};if(this.attributes.selectedEntityConfigClientId){result.selectedEntityConfigClientId=this.attributes.selectedEntityConfigClientId}if(this.attributes.selectedViewConfigClientId){result.selectedViewConfigClientId=this.attributes.selectedViewConfigClientId}if(this.attributes.entityWidth){result.entityWidth=this.attributes.entityWidth}return result},getSelectedEntityConfig:function(){return this.attributes.entityConfigs.get(this.attributes.selectedEntityConfigClientId)},getSelectedViewConfig:function(){return this.attributes.viewConfigs.get(this.attributes.selectedViewConfigClientId)},addEntityAndSelectIt:function(entityConfig,indexOrNextConfigOrNextConfigClientId){this._addAndSelect(this.attributes.entityConfigs,entityConfig,_.isUndefined(indexOrNextConfigOrNextConfigClientId)?null:indexOrNextConfigOrNextConfigClientId)},addViewAndSelectIt:function(viewConfig,indexOrNextConfigOrNextConfigClientId){this._addAndSelect(this.attributes.viewConfigs,viewConfig,_.isUndefined(indexOrNextConfigOrNextConfigClientId)?null:indexOrNextConfigOrNextConfigClientId)},removeEntityAndSelectNeighbour:function(entityConfig){this._removeAndSelectNeighbour(this.attributes.entityConfigs,entityConfig)},removeViewAndSelectNeighbour:function(viewConfig){this._removeAndSelectNeighbour(this.attributes.viewConfigs,viewConfig)},_addAndSelect:function(configCollection,config,indexOrNextConfigOrNextConfigClientId){this._modificationPropagationEnabled=false;configCollection.add(config);if(configCollection==this.attributes.entityConfigs){this.attributes.selectedEntityConfigClientId=config.getClientId()}else{this.attributes.selectedViewConfigClientId=config.getClientId()}this._relocate(configCollection,config,indexOrNextConfigOrNextConfigClientId);this._triggerModificationEventsIfNeeded();this._modificationPropagationEnabled=true},_removeAndSelectNeighbour:function(configCollection,config){this._modificationPropagationEnabled=false;var neighbourToSelect=this._getNeighbour(configCollection,config,1);if(!neighbourToSelect){neighbourToSelect=this._getNeighbour(configCollection,config,-1)}configCollection.remove(config);if(configCollection==this.attributes.entityConfigs){this.attributes.selectedEntityConfigClientId=neighbourToSelect?neighbourToSelect.getClientId():null}else{this.attributes.selectedViewConfigClientId=neighbourToSelect?neighbourToSelect.getClientId():null}this._triggerModificationEventsIfNeeded();this._modificationPropagationEnabled=true},unserialize:function(serializedAttributes){logger.debug("method called: ConfigGrid::unserialize");this._modificationPropagationEnabled=false;var fixedSerializedAttributes=serializedAttributes;if(!_.isSimpleObject(serializedAttributes)){logger.warn("ConfigGrid::unserialize called for not an object: ",serializedAttributes);fixedSerializedAttributes={}}var newConfigs=[];var fixedSerializedConfigs=fixedSerializedAttributes.entityConfigs;if(!_.isArray(fixedSerializedConfigs)){if(_.isSimpleObject(serializedAttributes)){logger.warn("ConfigGrid::unserialize called for an object with faulty entityConfigs: ",fixedSerializedConfigs)}fixedSerializedConfigs=[]}for(var i=0;i<fixedSerializedConfigs.length;i++){var serializedConfig=fixedSerializedConfigs[i];var config=this.attributes.entityConfigs.get(serializedConfig.clientId);if(!config){config=new App.ContextModule.Config(serializedConfig)}else{config.unserialize(serializedConfig)}newConfigs.push(config)}this.attributes.entityConfigs.reset(newConfigs);var newConfigs=[];var fixedSerializedConfigs=fixedSerializedAttributes.viewConfigs;if(!_.isArray(fixedSerializedConfigs)){if(_.isSimpleObject(serializedAttributes)){logger.warn("ConfigGrid::unserialize called for an object with faulty viewConfigs: ",fixedSerializedConfigs)}fixedSerializedConfigs=[]}for(var i=0;i<fixedSerializedConfigs.length;i++){var serializedConfig=fixedSerializedConfigs[i];var config=this.attributes.viewConfigs.get(serializedConfig.clientId);if(!config){config=new App.ContextModule.Config(serializedConfig)}else{config.unserialize(serializedConfig)}newConfigs.push(config)}this.attributes.viewConfigs.reset(newConfigs);this.attributes.selectedEntityConfigClientId=fixedSerializedAttributes.selectedEntityConfigClientId;this.attributes.selectedViewConfigClientId=fixedSerializedAttributes.selectedViewConfigClientId;this.attributes.entityWidth=fixedSerializedAttributes.entityWidth;this._triggerModificationEventsIfNeeded();this._modificationPropagationEnabled=true},_getNeighbour:function(configCollection,config,offset){var index=configCollection.indexOf(config);if(index===-1){throw _.str.sprintf("Can't find config %s",JSON.stringify(config.serialize()))}return configCollection.at(index+offset)},_relocate:function(configCollection,config,indexOrNextConfigOrNextConfigClientId){var clientIds=_.pluck(configCollection.models,"cid");var nextConfigClientId=null;if(_.isNumber(indexOrNextConfigOrNextConfigClientId)&&indexOrNextConfigOrNextConfigClientId!=clientIds.length){nextConfigClientId=clientIds[indexOrNextConfigOrNextConfigClientId]}if(_.isObject(indexOrNextConfigOrNextConfigClientId)){nextConfigClientId=indexOrNextConfigOrNextConfigClientId.getClientId()}if(_.isString(indexOrNextConfigOrNextConfigClientId)){if(clientIds.indexOf(indexOrNextConfigOrNextConfigClientId)!==-1){nextConfigClientId=indexOrNextConfigOrNextConfigClientId}}if(!nextConfigClientId&&!_.isNull(indexOrNextConfigOrNextConfigClientId)&&indexOrNextConfigOrNextConfigClientId!=configCollection.size()){throw _.str.sprintf("Wrong value for indexOrNextConfigOrNextConfigClientId %s",indexOrNextConfigOrNextConfigClientId)}var configClientId=config.getClientId();if(!configClientId||clientIds.indexOf(configClientId)==-1){var flattenedConfig=config;if(_.isObject(flattenedConfig)){flattenedConfig=JSON.stringify(flattenedConfig)}throw _.str.sprintf("Config %s with cid %s is either not a Config or does not belong to a corresponding configCollection with cids [%s]",flattenedConfig,_.isObject(config)?config.getClientId():undefined,clientIds.join(", "))}if(configCollection.get(configClientId)!==config){throw _.str.sprintf("Config %s with cid %s is is a clone of what is stored in the grid. Relocation is not possible.",JSON.stringify(config),config.cid)}var newClientIds=_.without(clientIds,configClientId);if(_.isNull(nextConfigClientId)){newClientIds.push(configClientId)}else{var nextConfigIndex=newClientIds.indexOf(nextConfigClientId);var tempClientIds=newClientIds.slice(0,nextConfigIndex);tempClientIds.push(configClientId);newClientIds=tempClientIds.concat(newClientIds.slice(nextConfigIndex))}var oldComparator=configCollection.comparator;configCollection.comparator=function(model){return newClientIds.indexOf(model.getClientId())};configCollection.sort();configCollection.comparator=oldComparator},_registerModificationOfConfigCollectionForEntities:function(modelOrModels,options){if(!_.isEqual(this._lastSavedOrderedEntityClientIds,_.pluck(this.attributes.entityConfigs.models,"cid"))){this._configCollectionsWereModified=true;if(this._modificationPropagationEnabled){this._triggerModificationEventsIfNeeded()}}},_registerModificationOfConfigCollectionForViews:function(modelOrModels,options){if(!_.isEqual(this._lastSavedOrderedViewClientIds,_.pluck(this.attributes.viewConfigs.models,"cid"))){this._configCollectionsWereModified=true;if(this._modificationPropagationEnabled){this._triggerModificationEventsIfNeeded()}}},_registerModificationOfConfig:function(){for(var i=0;i<this.attributes.entityConfigs.length;i++){if(this.attributes.entityConfigs.at(i).hasChanged()){this._configsWereModified=true;this._modifiedEntityConfigClientIds.push(this.attributes.entityConfigs.at(i).getClientId())}}for(var i=0;i<this.attributes.viewConfigs.length;i++){if(this.attributes.viewConfigs.at(i).hasChanged()){this._configsWereModified=true;this._modifiedViewConfigClientIds.push(this.attributes.viewConfigs.at(i).getClientId())}}if(this._modificationPropagationEnabled){this._triggerModificationEventsIfNeeded()}},_registerModificationOfAtomicProperty:function(){if(this._modificationPropagationEnabled){this._triggerModificationEventsIfNeeded(true)}},_registerModificationOfStandardAtomicProperty:function(){if(this._modificationPropagationEnabled){this._triggerModificationEventsIfNeeded()}},_triggerModificationEventsIfNeeded:function(specialCaseForRegisterModificationOfSelection){var triggeredAtLeastSomething=false;if(this._configCollectionsWereModified){triggeredAtLeastSomething=true;this.trigger("change_layout")}var newOrderedEntityClientIds=null;var newOrderedViewClientIds=null;if(this._configCollectionsWereModified||this._modifiedEntityConfigClientIds.length||this._modifiedViewConfigClientIds.length){newOrderedEntityClientIds=_.pluck(this.attributes.entityConfigs.models,"cid");newOrderedViewClientIds=_.pluck(this.attributes.viewConfigs.models,"cid");if(this._modifiedEntityConfigClientIds.length){for(var i=0;i<newOrderedEntityClientIds.length;i++){if(_.indexOf(this._modifiedEntityConfigClientIds,newOrderedEntityClientIds[i])!==-1){triggeredAtLeastSomething=true;this.trigger("change_entity:"+newOrderedEntityClientIds[i])}}}if(this._modifiedViewConfigClientIds.length){for(var i=0;i<newOrderedViewClientIds.length;i++){if(_.indexOf(this._modifiedViewConfigClientIds,newOrderedViewClientIds[i])!==-1){triggeredAtLeastSomething=true;this.trigger("change_view:"+newOrderedViewClientIds[i])}}}for(var i=0;i<newOrderedEntityClientIds.length;i++){var entityClientId=newOrderedEntityClientIds[i];var oldEntityIndex=this._lastSavedOrderedEntityClientIds.indexOf(entityClientId);if(oldEntityIndex==-1){continue}var newPrevEntityClientId=newOrderedEntityClientIds[i-1];var newNextEntityClientId=newOrderedEntityClientIds[i+1];var oldPrevEntityClientId=this._lastSavedOrderedEntityClientIds[oldEntityIndex-1];var oldNextEntityClientId=this._lastSavedOrderedEntityClientIds[oldEntityIndex+1];if(newPrevEntityClientId!=oldPrevEntityClientId||newNextEntityClientId!=oldNextEntityClientId||this._modifiedEntityConfigClientIds.indexOf(newPrevEntityClientId)!==-1||this._modifiedEntityConfigClientIds.indexOf(newNextEntityClientId)!==-1){triggeredAtLeastSomething=true;this.trigger("change_entity_neighbours:"+entityClientId)}}for(var i=0;i<newOrderedViewClientIds.length;i++){var viewClientId=newOrderedViewClientIds[i];var oldViewIndex=this._lastSavedOrderedViewClientIds.indexOf(viewClientId);if(oldViewIndex==-1){continue}var newPrevViewClientId=newOrderedViewClientIds[i-1];var newNextViewClientId=newOrderedViewClientIds[i+1];var oldPrevViewClientId=this._lastSavedOrderedViewClientIds[oldViewIndex-1];var oldNextViewClientId=this._lastSavedOrderedViewClientIds[oldViewIndex+1];if(newPrevViewClientId!=oldPrevViewClientId||newNextViewClientId!=oldNextViewClientId||this._modifiedViewConfigClientIds.indexOf(newPrevViewClientId)!==-1||this._modifiedViewConfigClientIds.indexOf(newNextViewClientId)!==-1){triggeredAtLeastSomething=true;this.trigger("change_view_neighbours:"+viewClientId)}}}this._lastSavedOrderedEntityClientIds=_.pluck(this.attributes.entityConfigs.models,"cid");this._lastSavedOrderedViewClientIds=_.pluck(this.attributes.viewConfigs.models,"cid");if(!this.attributes.entityConfigs.get(this.attributes.selectedEntityConfigClientId)){this.attributes.selectedEntityConfigClientId=null}if(!this.attributes.viewConfigs.get(this.attributes.selectedViewConfigClientId)){this.attributes.selectedViewConfigClientId=null}if(this._lastSavedSelectedEntityConfigClientId!=this.attributes.selectedEntityConfigClientId||this._lastSavedSelectedViewConfigClientId!=this.attributes.selectedViewConfigClientId){if(!specialCaseForRegisterModificationOfSelection){triggeredAtLeastSomething=true}this.trigger("change_selection")}if(this._lastSavedEntityWidth!=this.attributes.entityWidth){triggeredAtLeastSomething=true}this._configCollectionsWereModified=false;this._configsWereModified=false;this._selectionWasModified=false;this._modifiedEntityConfigClientIds=[];this._modifiedViewConfigClientIds=[];this._lastSavedSelectedEntityConfigClientId=this.attributes.selectedEntityConfigClientId;this._lastSavedSelectedViewConfigClientId=this.attributes.selectedViewConfigClientId;this._lastSavedEntityWidth=this.attributes.entityWidth;if(triggeredAtLeastSomething){this.trigger("change")}}})})},Logger); "use strict";App.module("ContextModule",function(ContextModule,App,Backbone,Marionette,$,_,Logger){var logger=null;ContextModule.addInitializer(function(options){logger=Logger.get("ContextModule.State");logger.setLevel(Logger.WARN);ContextModule.State=Backbone.Model.extend({defaults:{musicCollectionGrid:null,musicRecordingGrid:null},initialize:function(){this._modificationPropagationEnabled=true;this._attributesWereModified=false;this.attributes.musicCollectionGrid=new ContextModule.ConfigGrid("collection");this.attributes.musicRecordingGrid=new ContextModule.ConfigGrid("recording");this.attributes.musicCollectionGrid.bind("change",this._registerModificationOfAttribute,this);this.attributes.musicRecordingGrid.bind("change",this._registerModificationOfAttribute,this)},getConfigGridByType:function(type){switch(type){case"recordings":return this.attributes.musicRecordingGrid;case"collections":return this.attributes.musicCollectionGrid;default:return null}},getConfigGridBeingShown:function(){return this.attributes.musicRecordingsGridIsShown?this.attributes.musicRecordingGrid:this.attributes.musicCollectionGrid},serialize:function(){logger.debug("method called: State::serialize");var result={musicCollectionGrid:this.attributes.musicCollectionGrid.serialize(),musicRecordingGrid:this.attributes.musicRecordingGrid.serialize()};if(this.attributes.musicRecordingsGridIsShown){result.musicRecordingsGridIsShown=true}return result},unserialize:function(serializedAttributes){logger.debug("method called: State::unserialize");this._modificationPropagationEnabled=false;this._attributesWereModified=false;var fixedSerializedAttributes=serializedAttributes;if(!_.isSimpleObject(fixedSerializedAttributes)){logger.warn("State::unserialize called for not an object: ",serializedAttributes);fixedSerializedAttributes={}}this.attributes.musicCollectionGrid.unserialize(fixedSerializedAttributes.musicCollectionGrid);this.attributes.musicRecordingGrid.unserialize(fixedSerializedAttributes.musicRecordingGrid);if(this.attributes.musicRecordingsGridIsShown!==fixedSerializedAttributes.musicRecordingsGridIsShown){this._attributesWereModified=true}if(fixedSerializedAttributes.musicRecordingsGridIsShown){this.attributes.musicRecordingsGridIsShown=true}else{delete this.attributes.musicRecordingsGridIsShown}this._triggerModificationEventsIfNeeded();this._modificationPropagationEnabled=true},_registerModificationOfAttribute:function(){this._attributesWereModified=true;if(this._modificationPropagationEnabled){this._triggerModificationEventsIfNeeded()}},_triggerModificationEventsIfNeeded:function(){if(this._attributesWereModified){this.trigger("change")}this._attributesWereModified=false}})})},Logger); "use strict";App.module("ContextModule",function(ContextModule,App,Backbone,Marionette,$,_,Logger){var logger=null;ContextModule.addInitializer(function(options){ContextModule.StateBookmark=Backbone.Model.extend({defaults:{name:null,time:null,serializedState:null,comment:null},initialize:function(){},serialize:function(){logger.debug("method called: State::serialize");var result=_.clone(this.attributes);return result},unserialize:function(serializedAttributes){this.clear({silent:true}).set(serializedAttributes)}})})},Logger); "use strict";App.module("ContextModule",function(ContextModule,App,Backbone,Marionette,$,_,Logger){var logger=null;ContextModule.addInitializer(function(options){logger=Logger.get("ContextModule.StateBookmarkCollection");logger.setLevel(Logger.WARN);ContextModule.StateBookmarkCollection=Backbone.Collection.extend({model:ContextModule.StateBookmark,serialize:function(){return this.map(function(model){return model.serialize()})},unserialize:function(serializedModels){var fixedSerializedModels=serializedModels;if(!_.isArray(serializedModels)){logger.warn("StateBookmarkCollection::unserialize called for not an array: ",serializedModels);fixedSerializedModels=[]}if(!_.isEqual(fixedSerializedModels,this.serialize())){var modelArray=[];for(var i=0;i<fixedSerializedModels.length;i++){var model=new this.model;modelArray.push(model.unserialize(fixedSerializedModels[i]))}this.reset(modelArray)}}})})},Logger); "use strict";App.module("ContextModule",function(ContextModule,App,Backbone,Marionette,$,_,Logger){var logger=null;ContextModule.addInitializer(function(options){ContextModule.StateHistory=Backbone.Model.extend({defaults:{maxStackSize:50,currentSerializedState:undefined,compoundChangeDetector:undefined},_NONE:0,_UNDO:1,_REDO:2,_UNSERIALIZE:3,initialize:function(){this._undoStack=[];this._redoStack=[];this._currentSerializedStateChangeMode=this._NONE;this.on("change:maxStackSize",this._trimStacks,this);this.on("change:currentSerializedState",this._registerNewSerializedState,this)},_registerNewSerializedState:function(){var previousSerialisedState=this.previous("currentSerializedState");if(this._currentSerializedStateChangeMode==this._UNDO){this._redoStack.unshift(previousSerialisedState)}else if(this._currentSerializedStateChangeMode==this._REDO){this._undoStack.unshift(previousSerialisedState)}else if(this._currentSerializedStateChangeMode==this._UNSERIALIZE){}else{if(!_.isEqual(previousSerialisedState,this.attributes.currentSerializedState)){if(this._undoStack.length==0||!_.isFunction(this.attributes.compoundChangeDetector)||!this.attributes.compoundChangeDetector.call(currentSerializedState,previousSerialisedState,this._undoStack[0])){this._undoStack.unshift(previousSerialisedState)}this._redoStack=[]}}this._trimStacks()},getCurrentSerializedState:function(){},undo:function(){if(this._undoStack.length){this._currentSerializedStateChangeMode=this._UNDO;this.set("currentSerializedState",this._undoStack.shift());this._currentSerializedStateChangeMode=this._NONE}else{throw"Undo was called when undo stack was empty"}},redo:function(){if(this._redoStack.length){this._currentSerializedStateChangeMode=this._REDO;this.set("currentSerializedState",this._redoStack.shift());this._currentSerializedStateChangeMode=this._NONE}else{throw"Redo was called when undo stack was empty"}},reset:function(){var stacksWereNotEmpty=this._undoStack.length||this._redoStack.length;this._undoStack=[];this._redoStack=[];if(stacksWereNotEmpty){this.trigger("change")}},canUndo:function(){return!!this._undoStack.length},canRedo:function(){return!!this._redoStack.length},serialize:function(){var result={currentSerializedState:this.attributes.currentSerializedState,undoStack:_.clone(this._undoStack),redoStack:_.clone(this._redoStack)};return result},unserialize:function(serializedAttributes){this._currentSerializedStateChangeMode=this._UNSERIALIZE;var fixedSerializedAttributes=serializedAttributes;if(!_.isSimpleObject(serializedAttributes)){fixedSerializedAttributes={}}this._undoStack=_.isArray(fixedSerializedAttributes.undoStack)?fixedSerializedAttributes.undoStack:[];this._redoStack=_.isArray(fixedSerializedAttributes.redoStack)?fixedSerializedAttributes.redoStack:[];this._trimStacks();this.set("currentSerializedState",fixedSerializedAttributes.currentSerializedState);this._currentSerializedStateChangeMode=this._NONE},_trimStacks:function(){if(this._undoStack.length>this.attributes.maxStackSize){this._undoStack=this._undoStack.slice(0,this.attributes.maxStackSize)}if(this._redoStack.length>this.attributes.maxStackSize){this._redoStack=this._redoStack.slice(0,this.attributes.maxStackSize)}}})})},Logger); "use strict";App.module("ContextModule",function(ContextModule,App,Backbone,Marionette,$,_,Logger){var logger=null;ContextModule.addInitializer(function(options){logger=Logger.get("ContextModule.AppContext");logger.setLevel(Logger.DEBUG);ContextModule.AppContext=Backbone.Model.extend({defaults:function(){return{state:new ContextModule.State,stateHistory:new ContextModule.StateHistory,stateBookmarks:new ContextModule.StateBookmarkCollection}},initialize:function(){this._modificationPropagationEnabled=true;this._linkBetweenStateAndStateHistoryEnabled=true;this._attributesWereModified=false;this._registerStateChange();this.attributes.state.bind("change",this._registerStateChange,this);this.attributes.stateHistory.bind("change",this._registerStateHistoryChange,this);this.attributes.stateBookmarks.bind("change",this._registerStateBookmarksChange,this)},serialize:function(){var result={stateHistory:this.attributes.stateHistory.serialize(),stateBookmarks:this.attributes.stateBookmarks.serialize()};return result},unserialize:function(serializedAttributes){this._modificationPropagationEnabled=false;var fixedSerializedAttributes=serializedAttributes;if(!_.isSimpleObject(fixedSerializedAttributes)){logger.warn("AppContext::unserialize called for not an object: ",serializedAttributes);fixedSerializedAttributes={}}this.attributes.stateBookmarks.unserialize(fixedSerializedAttributes.stateBookmarks);var serializedStateHistory=fixedSerializedAttributes["stateHistory"];if(!_.isSimpleObject(serializedStateHistory)){serializedStateHistory={}}this._linkBetweenStateAndStateHistoryEnabled=false;this.attributes.state.unserialize(serializedStateHistory.currentSerializedState);serializedStateHistory.currentSerializedState=this.attributes.state.serialize();this.attributes.stateHistory.unserialize(serializedStateHistory);this._linkBetweenStateAndStateHistoryEnabled=true;this._triggerModificationEventsIfNeeded();this._modificationPropagationEnabled=true},_registerStateChange:function(){if(this._linkBetweenStateAndStateHistoryEnabled){this.attributes.stateHistory.set("currentSerializedState",this.attributes.state.serialize())}this._registerModificationOfAttribute()},_registerStateHistoryChange:function(){if(this._linkBetweenStateAndStateHistoryEnabled){this.attributes.state.unserialize(this.attributes.stateHistory.get("currentSerializedState"))}if(this._stateHistoryModificationPropagationEnabled){this._registerModificationOfAttribute()}},_registerStateBookmarksChange:function(){this._registerModificationOfAttribute()},_registerModificationOfAttribute:function(){this._attributesWereModified=true;if(this._modificationPropagationEnabled){this._triggerModificationEventsIfNeeded()}},_triggerModificationEventsIfNeeded:function(){if(this._attributesWereModified){this.trigger("change")}this._attributesWereModified=false}})})},Logger); "use strict";App.module("ContextModule",function(ContextModule,App,Backbone,Marionette,$,_,Logger){var logger=null;ContextModule.addInitializer(function(options){logger=Logger.get("ContextModule.AppContextManager");logger.setLevel(Logger.DEBUG);ContextModule.AppContextManager=Backbone.Marionette.Object.extend({initialize:function(){this.defaultSerializedAppContexts={"":{stateHistory:{currentSerializedState:{musicCollectionGrid:{selectedEntityConfigClientId:"def0",entityConfigs:[{clientId:"def0",parameters:{library:"CHARM",composer:"Mozart"}},{clientId:"def1",parameters:{library:"CHARM",composer:"Haydn"}}],viewConfigs:[{clientId:"def2",parameters:{kind:"list"}},{clientId:"def3",parameters:{kind:"tonic-histogram"}}]},musicRecordingGrid:{viewConfigs:[{clientId:"def4",parameters:{kind:"properties"}},{clientId:"def5",parameters:{kind:"midi-pitch-histogram"}}]}}}},empty:{}}},saveToStorage:function(appContext){logger.debug("Saving to storage");return App.DataModule.Storage.setObjCache(ContextModule,"context",appContext.serialize())},restoreFromStorage:function(appContext,nameOfDefaultIfFailure){logger.debug("Restoring from storage");var serializedAppContext=App.DataModule.Storage.getObjCache(ContextModule,"context");if(!serializedAppContext){this.restoreDefault(appContext,nameOfDefaultIfFailure);return false}else{appContext.unserialize(serializedAppContext);return true}},restoreDefault:function(appContext,nameOfDefault){var name=nameOfDefault;if(!name){name=""}logger.debug("Restoring default");appContext.unserialize(this.defaultSerializedAppContexts[name])}})})},Logger); "use strict";App.module("DataModule",function(DataModule,App,Backbone,Marionette,$,_,Logger){DataModule.startWithParent=false},Logger); "use strict";App.module("DataModule.Storage",function(Storage,App,Backbone,Marionette,$,_,Logger){var logger=null;var assertModuleIsInitialized=function(){if(!logger){throw"Storage has not been initialized"}};Storage.addInitializer(function(){logger=Logger.get("DataModule.Storage");logger.debug("Begin init");logger.debug("End init")});Storage.setStrCache=function(module,key,value){assertModuleIsInitialized();var moduleName=_.isObject(module)?module.moduleName:"";if(!moduleName){moduleName=""}if(value===undefined){localStorage&&localStorage.removeItem("dml."+moduleName+"."+key);return true}else if(_.isString(value)){try{localStorage&&localStorage.setItem("dml."+moduleName+"."+key,value);logger.info("Set string cache",moduleName,key,value);return true}catch(e){var maxOutputLength=100;logger.error("Set string cache failed:",moduleName,"→",key,"=",value.slice(0,maxOutputLength)+(value.length>maxOutputLength?"...":""));return false}}else{throw _.str.sprintf("Storage.setStrCache only accepts string for value, %s given: ",typeof value,value)}};Storage.getStrCache=function(module,key){assertModuleIsInitialized();var moduleName=_.isObject(module)?module.moduleName:"";if(!moduleName){moduleName=""}var value=localStorage?localStorage.getItem("dml."+moduleName+"."+key):null;if(value===null){value=undefined}logger.info("Get string cache",module,key,value);return value};Storage.setObjCache=function(module,key,value){if(!(_.isUndefined(value)||_.isNull(value)||_.isObject(value)&&!_.isFunction(value))){throw _.str.sprintf("Storage.setObjCache can only acccept object, got %s",value)}var str=JSON.stringify(value);return Storage.setStrCache(module,key,str)};Storage.getObjCache=function(module,key){assertModuleIsInitialized();var value=localStorage?localStorage.getItem("dml."+module.moduleName+"."+key):null;if(value===null){return undefined}if(value==="null"){return null}try{var value=JSON.parse(value);return value}catch(e){return null}}},Logger); "use strict";App.module("DataModule.CliopatriaAPI",function(CliopatriaAPI,App,Backbone,Marionette,$,_,Logger){CliopatriaAPI.startWithParent=false;var defaultModuleOptions={callbackTimeout:3e4,callbackTimeoutCheckingInterval:1e3,callbackFunctionName:"jsonp_cb",dataVersion:null,apiRootPaths:[],apiVersion:1,dataCaching:true};var logger=null;var dataVersionSuffix=null;var realAPIRootPaths=null;var realAPIRootPathsCount=null;var queryPool=null;var generateQuery=null;var callbackTimeoutExpiryChecker=null;var callbackTimeoutExpiryCheckerId=null;var assertModuleIsInitialized=function(){if(!logger){throw"DataModule.CliopatriaAPI has not been initialized"}};CliopatriaAPI.addInitializer(function(options){CliopatriaAPI.options=_.extend(defaultModuleOptions,options);logger=Logger.get("DataModule.CliopatriaAPI");if(CliopatriaAPI.options.dataVersion){dataVersionSuffix=_.str.sprintf("&format=jsonp&dv=%s",encodeURIComponent(CliopatriaAPI.options.dataVersion))}else{dataVersionSuffix="&format=jsonp"}realAPIRootPaths=[];for(var i=0;i<CliopatriaAPI.options.apiRootPaths.length;++i){var apiRootPath=CliopatriaAPI.options.apiRootPaths[i];realAPIRootPaths.push(_.str.sprintf("%sv%s/",apiRootPath,CliopatriaAPI.options.apiVersion))}realAPIRootPathsCount=realAPIRootPaths.length;if(!realAPIRootPathsCount){logger.error("DataModule.CliopatriaAPI has no registered API paths")}queryPool={};generateQuery=function(methodName,parameters){var sortedParameterPairs=[];for(var parameterName in parameters){sortedParameterPairs.push([parameterName,parameters[parameterName]])}sortedParameterPairs.sort(function(a,b){return _.str.naturalCmp(a[0],b[0])});var encodedParametersAsArrayOfStrings=[];for(var parameterPairIndex in sortedParameterPairs){encodedParametersAsArrayOfStrings.push(encodeURIComponent(sortedParameterPairs[parameterPairIndex][0])+"="+encodeURIComponent(sortedParameterPairs[parameterPairIndex][1]))}if(!CliopatriaAPI.options.dataCaching){encodedParametersAsArrayOfStrings.push("random="+Math.round(Math.random()*1e5))}var encodedParameters=encodedParametersAsArrayOfStrings.join("&");if(methodName=="getCollectionId"){if(encodedParameters.length){encodedParameters+=dataVersionSuffix}else{encodedParameters+=dataVersionSuffix.slice(1)}}return methodName+"?"+encodedParameters};window[CliopatriaAPI.options.callbackFunctionName]=function(data){logger.debug("Callback function called with data:",data);var queryInData=data.query.replace(/%[a-z0-9]{2}/g,function(v){return v.toUpperCase()});queryInData=queryInData.replace(/^.*\/v[\d]\//,"");var queryPoolEntry=queryPool[queryInData];if(!queryPoolEntry){logger.warn(_.str.sprintf("No data API pool entry found for query %s. Response was wasted.",queryInData),data);return}delete queryPool[queryInData];$(queryPoolEntry[4]).remove();executeAllCallbacksOfTheQueryPoolEntry(queryPoolEntry,data.result)};var executeAllCallbacksOfTheQueryPoolEntry=function(queryPoolEntry,result){logger.info(_.str.sprintf("Executing %d callback%s for request %s",queryPoolEntry[3].length,queryPoolEntry[3].length!=1?"s":"",queryPoolEntry[5]),result);for(var i=0;i<queryPoolEntry[3].length;i++){var callback=queryPoolEntry[3][i];if(_.isFunction(callback)){try{callback.call(null,result,queryPoolEntry[5],queryPoolEntry[1],queryPoolEntry[2])}catch(e){logger.error(_.str.sprintf("An error occured when executing callback %s of %s for data API query %s",i+1,queryPoolEntry[3].length,queryPoolEntry[5]),e)}}}};callbackTimeoutExpiryChecker=function(){var currentTimestamp=(new Date).getTime();for(var query in queryPool){var queryPoolEntry=queryPool[query];logger.debug(_.str.sprintf("Checking callback timeouts: timestamp diff = %d ms for query %s",currentTimestamp-queryPoolEntry[0],query));if(currentTimestamp-queryPoolEntry[0]>CliopatriaAPI.options.callbackTimeout){delete queryPool[query];$(queryPoolEntry[4]).remove();executeAllCallbacksOfTheQueryPoolEntry(queryPoolEntry,{errors:[{code:100,message:"API request failed"}]})}}};callbackTimeoutExpiryCheckerId=setInterval(callbackTimeoutExpiryChecker,CliopatriaAPI.options.callbackTimeoutCheckingInterval)});CliopatriaAPI.request=function(methodName,parameters,callback){assertModuleIsInitialized();var query=generateQuery(methodName,parameters);var realAPIRootPath;if(realAPIRootPathsCount==1){realAPIRootPath=realAPIRootPaths[0]}else{var sumOfCharCodes=0;for(var i=0;i<query.length;i++){sumOfCharCodes+=query.charCodeAt(i)}realAPIRootPath=realAPIRootPaths[sumOfCharCodes%realAPIRootPathsCount]}if(!realAPIRootPath){throw _.str.sprintf("API requsest to Cliopatria cannot be made – api root path is undefined")}var requestURI=realAPIRootPath+query;var queryPoolEntry=queryPool[query];if(!queryPoolEntry){logger.info("Sending request",query);var scriptElement=document.createElement("script");scriptElement.type="text/javascript";scriptElement.async=true;scriptElement.src=requestURI;queryPoolEntry=[(new Date).getTime(),methodName,parameters,[callback],scriptElement,query];queryPool[query]=queryPoolEntry;logger.debug("New entry in queryPool: ",query);document.getElementsByTagName("body")[0].appendChild(scriptElement)}else{logger.info("request (imaginary)",query);queryPoolEntry[3].push(callback)}return requestURI};CliopatriaAPI.on("stop",function(){clearInterval(callbackTimeoutExpiryCheckerId)})},Logger); "use strict";App.module("DataModule",function(DataModule,App,Backbone,Marionette,$,_,Logger){DataModule.addInitializer(function(options){DataModule.ModelWithHashableAttributes=Backbone.Model.extend({defaultOptions:{attributesToExcludeFromHash:null,customHashSuffixGenerator:null},initialize:function(attributes,options){this.listenTo(this,"change",this.dropCachedHash);this.options=_.defaults(options||{},this.defaultOptions)},dropCachedHash:function(){this._cachedHash=undefined},getHash:function(){if(!this._cachedHash){var mixOfAttributesAndAttributeHashes={};for(var attributeName in this.attributes){if(this.options.attributesToExcludeFromHash&&_.contains(this.options.attributesToExcludeFromHash,attributeName)){continue}if(this.attributes.hasOwnProperty(attributeName)){var attribute=this.attributes[attributeName];if(attribute&&attribute.getHash){mixOfAttributesAndAttributeHashes[attributeName]=attribute.getHash()}else{mixOfAttributesAndAttributeHashes[attributeName]=attribute}}}var newHash=JSON.stringify(mixOfAttributesAndAttributeHashes);if(this.options.customHashSuffixGenerator&&_.isFunction(this.options.customHashSuffixGenerator)){newHash+=this.options.customHashSuffixGenerator(this.attributes)}this._cachedHash=newHash}return this._cachedHash}})})},Logger); "use strict";App.module("DataModule",function(DataModule,App,Backbone,Marionette,$,_,Logger){DataModule.addInitializer(function(){DataModule.DynamicDefinition=DataModule.ModelWithHashableAttributes.extend({initialize:function(attributes,options){DataModule.ModelWithHashableAttributes.prototype.initialize.apply(this,arguments);this._entityConfig=options.entityConfig;this._provider=options.provider;this._cachedRequestHash="{}";this.listenTo(this._entityConfig,"change:parameters",this.update);this.update()},update:function(force){var parameterHash=this._entityConfig.getHashForParameters();var requestHash=this._provider._requestHashesByParameterHash[parameterHash];if(!requestHash){var requestParameters=this._provider.configParametersToRequestParameters(this._entityConfig);requestHash=JSON.stringify(requestParameters);this._provider._requestHashesByParameterHash[parameterHash]=requestHash;this._provider._requestParametersByRequestHash[requestHash]=requestParameters}if(requestHash==this._cachedRequestHash&&!force){return}if(requestHash!==this._cachedRequestHash){if(this._cachedRequestHash){this.stopListening(this._provider,"change:"+this._cachedRequestHash,this._applyCachedAttributes)}this._cachedRequestHash=requestHash;this.listenTo(this._provider,"change:"+this._cachedRequestHash,this._applyCachedAttributes)}if(this._provider._cachedAttributesByRequestHash[this._cachedRequestHash]&&!force){this._applyCachedAttributes()}else{this._provider.updateResponseForRequestHash(requestHash)}},_applyCachedAttributes:function(){var definitionAttributes=this._provider._cachedAttributesByRequestHash[this._cachedRequestHash];if(_.isUndefined(definitionAttributes)){throw _.str.sprintf("Unexpected cached attributes for DynamicDefinition to be undefined")}if(!_.isEqual(this.attributes,definitionAttributes)){this.attributes=definitionAttributes;this.trigger("change")}}})})},Logger); "use strict";App.module("DataModule",function(DataModule,App,Backbone,Marionette,$,_,Logger){DataModule.addInitializer(function(){DataModule.DynamicDefinitionProvider=Marionette.Object.extend({options:{DynamicDefinition:undefined,apiMethod:undefined,customAttributesWhenNotApplicable:undefined,customAttributesWhileBeingUpdated:undefined,customAttributesWhenIsFaulty:undefined},definitionIsFaulty:function(definition){},definitionIsBeingUpdated:function(definition){},configParametersToRequestParameters:function(config){},apiResponseToDynamicDefinitionAttributes:function(data,query){},initialize:function(){this._dynamicDefinitionsByEntityConfigClientId={};this._requestHashesByParameterHash={};this._requestParametersByRequestHash={};this._cachedAttributesByRequestHash={}},get:function(entityConfig){var clientId=entityConfig.getClientId();var definition=this._dynamicDefinitionsByEntityConfigClientId[clientId];if(!definition){definition=new this.options.DynamicDefinition({},{entityConfig:entityConfig,provider:this});this._dynamicDefinitionsByEntityConfigClientId[clientId]=definition}return definition},retire:function(entityConfigClientId){var definitionToRetire=this._dynamicDefinitionsByEntityConfigClientId[entityConfigClientId];definitionToRetire.destroy();delete this._dynamicDefinitionsByEntityConfigClientId[entityConfigClientId]},updateResponseForRequestHash:function(requestHash){var requestParameters=this._requestParametersByRequestHash[requestHash];if(requestParameters===null){this._cachedAttributesByRequestHash[requestHash]=_.clone(this.options.customAttributesWhenNotApplicable);this.trigger("change:"+requestHash);return}this._cachedAttributesByRequestHash[requestHash]=_.clone(this.options.customAttributesWhileBeingUpdated);this.trigger("change:"+requestHash);var provider=this;App.DataModule.CliopatriaAPI.request(this.options.apiMethod,requestParameters,function(data,query){var attributes=provider.apiResponseToAttributes(data,query);provider._cachedAttributesByRequestHash[requestHash]=attributes;provider.trigger("change:"+requestHash)})}})})},Logger); "use strict";App.module("DataModule",function(DataModule,App,Backbone,Marionette,$,_,Logger){var logger=null;DataModule.addInitializer(function(){logger=Logger.get("App.DataModule");DataModule.DynamicDefinitionForCollection=DataModule.DynamicDefinition.extend({});DataModule.DynamicDefinitionProviderForCollections=DataModule.DynamicDefinitionProvider.extend({options:{DynamicDefinition:DataModule.DynamicDefinitionForCollection,apiMethod:"getCollectionId",customAttributesWhenNotApplicable:{id:undefined},customAttributesWhileBeingUpdated:{id:null,sampleSize:null,fullSize:null},customAttributesWhenFaulty:{id:false,sampleSize:false,fullSize:false},customAttributesWhenEmpty:{id:"",sampleSize:0,fullSize:0}},definitionIsFaulty:function(definition){return definition.id===false},definitionIsBeingUpdated:function(definition){return definition.id===null},configParametersToRequestParameters:function(config){var rawConfigParameters=config.attributes.parameters.attributes;var requestParameters={};var library=_.str.trim(rawConfigParameters.library).replace(/ /g,"").replace(/,/g,";");if(library){requestParameters.library=library}else{return null}requestParameters.sv=0;var year=_.str.trim(rawConfigParameters.year).replace(/ /g,"");if(year){requestParameters.year=year}requestParameters.sample=1e3;_.each(["genre","composer","performer","title","place","collection"],function(field){var f=_.str.trim(rawConfigParameters[field]);if(f){requestParameters[field]=f}});return requestParameters},apiResponseToAttributes:function(data,query){var attributes={};if(data&&data.cid){attributes.id=data.cid;attributes.sampleSize=data.size;attributes.fullSize=data.full_size}else if(data.errors&&data.errors[0]&&_.isString(data.errors[0].desc)&&data.errors[0].desc.indexOf("empty_dataset")>0){attributes=_.clone(this.options.customAttributesWhenEmpty)}else{attributes=_.clone(this.options.customAttributesWhenFaulty);attributes.errors=data.errors;logger.warn("An error occured when attempting to obtain collection definition. Query / response:",query,data)}attributes.query=query;return attributes}})})},Logger); "use strict";App.module("DataModule",function(DataModule,App,Backbone,Marionette,$,_,Logger){var logger=null;DataModule.addInitializer(function(){logger=Logger.get("App.DataModule");DataModule.DynamicDefinitionForRecording=DataModule.DynamicDefinition.extend({});DataModule.DymanicDefinitionProviderForRecordings=DataModule.DynamicDefinitionProvider.extend({options:{DynamicDefinition:DataModule.DynamicDefinitionForRecording,apiMethod:"getRecordingPerspective",customAttributesWhenNotApplicable:{label:undefined},customAttributesWhileBeingUpdated:{label:null},customAttributesWhenFaulty:{label:false}},isFaulty:function(dynamicDefinition){return dynamicDefinition.attributes.label===false},isBeingUpdated:function(dynamicDefinition){return dynamicDefinition.attributes.label===null},configParametersToRequestParameters:function(config){var rawConfigParameters=config.attributes.parameters.attributes;if(rawConfigParameters.recordingURI){return{uri:rawConfigParameters.recordingURI,pid:"properties"}}else{return null}},apiResponseToAttributes:function(data,query){var attributes={};if(data&&data.label){attributes=data}else{attributes={label:false};if(data.errors){attributes=_.clone(this.options.customAttributesWhenFaulty);attributes.errors=data.errors}logger.warn("An error occured when attempting to obtain new recording definition. Query / response:",query,data)}attributes.query=query;return attributes}})})},Logger); "use strict";App.module("GraphicsRenderingModule",function(GraphicsRenderingModule,App,Backbone,Marionette,$,_,Logger){GraphicsRenderingModule.addInitializer(function(options){GraphicsRenderingModule.logger=Logger.get("GraphicsRenderingModule");GraphicsRenderingModule._formatNumberForTooltip=function(number){var nDigits=2;if(Math.abs(number)>1e3||Math.floor(number)==number){nDigits=0}else if(Math.abs(number)>100){nDigits=1}return _.str.numberFormat(number,nDigits)},GraphicsRenderingModule.__handleVegaMouseEvent=function(){var pointerEventType=arguments[0].type;if(pointerEventType=="mouseover"||pointerEventType=="mouseout"){var $vegaNode=$(arguments[0].target).closest("div");if(pointerEventType=="mouseover"){$vegaNode.data("vegaHoveredItem",arguments[1])}else{$vegaNode.removeData("vegaHoveredItem")}}var data=null;if(arguments[1]&&arguments[1].datum){data=arguments[1].datum}if(_.isObject(data)&&data.tooltip){App.TooltipModule.tooltipView.update(arguments[0],_.isArray(data.tooltip)?data.tooltip[2]:data.tooltip,data)}else if(_.isArray(data)){var tooltip=data[0];if(tooltip){var labelParts=[];if(data[0]=="tooltip_range"){labelParts.push(GraphicsRenderingModule._formatNumberForTooltip(data[2]));labelParts.push(" ... ");labelParts.push(GraphicsRenderingModule._formatNumberForTooltip(data[3]));labelParts.push(" → ");labelParts.push(GraphicsRenderingModule._formatNumberForTooltip(data[1]).replace("-","−"))}else if(data[0]=="tooltip_point"){if(data[2]*1===data[2]){labelParts.push(GraphicsRenderingModule._formatNumberForTooltip(data[2]))}else{labelParts.push(data[2])}labelParts.push(" → ");labelParts.push(GraphicsRenderingModule._formatNumberForTooltip(data[1]))}else if(data[0]=="tooltip_value"){labelParts.push(GraphicsRenderingModule._formatNumberForTooltip(data[1]).replace("-","−"))}if(data[4]){labelParts.unshift(data[4])}if(data[5]){labelParts.push(data[5])}App.TooltipModule.tooltipView.update(arguments[0],labelParts.join(""),data)}}else{App.TooltipModule.tooltipView.update()}},GraphicsRenderingModule.vegaIsReady=function($domNode){return $domNode.hasClass("vega")};GraphicsRenderingModule.vegaAsync=function($domNode,spec,renderer,callback){var rand=Math.random();$domNode.data("vega-async-rand",rand);var $tempNode=$("<div/>");setTimeout(function(){vg.parse.spec(spec,function(chart){var vegaObj=chart({el:$tempNode.get(0),renderer:App.options.vegaRenderer?App.options.vegaRenderer:renderer}).on("mouseover",GraphicsRenderingModule.__handleVegaMouseEvent).on("mousemove",GraphicsRenderingModule.__handleVegaMouseEvent).on("mouseout",GraphicsRenderingModule.__handleVegaMouseEvent).update();var $vegaNode=$tempNode.children(0);$vegaNode.data("vegaObj",vegaObj);var vegaIsReadyInterval=setInterval(function(){if($domNode.data("vega-async-rand")!==rand){clearInterval(vegaIsReadyInterval);return}if(GraphicsRenderingModule.vegaIsReady($vegaNode)){$vegaNode.addClass("vic-vega");$domNode.empty().append($vegaNode);clearInterval(vegaIsReadyInterval)}},50)})},10)}})},Logger); "use strict";App.module("GraphicsRenderingModule",function(GraphicsRenderingModule,App,Backbone,Marionette,$,_,Logger){GraphicsRenderingModule.addInitializer(function(options){GraphicsRenderingModule.RendererPrototypes={};GraphicsRenderingModule.renderers={};GraphicsRenderingModule.registerRenderer=function(rendererDefinition){var RendererPrototype;var inheritId=rendererDefinition.inherit?rendererDefinition.inherit:"";var id=rendererDefinition.id;if(!id){throw _.str.sprintf("Renderer definition does not contain an id")}var rendererWithThisId=null;try{rendererWithThisId=GraphicsRenderingModule.getRendererById(id)}catch(e){}if(rendererWithThisId){throw _.str.sprintf('Renderer with id "%s" already exists',id)}var prototypeOptions={};var prototypeDefaultVegaConfig={};if(!inheritId){RendererPrototype=Marionette.Object}else{try{RendererPrototype=GraphicsRenderingModule.getRendererPrototypeById(inheritId);var parentRenderer=GraphicsRenderingModule.getRendererById(inheritId);prototypeOptions=parentRenderer.options;prototypeDefaultVegaConfig=parentRenderer.defaultVegaConfig}catch(e){throw _.str.sprintf('Renderer with id "%s" could not be inherited from renderer with id "%s" (it does not exist)',id,inheritId)}}var combinedOptions=rendererDefinition.options?_.defaults({},rendererDefinition.options,prototypeOptions):_.clone(prototypeOptions);var combinedDefaultVegaConfig=rendererDefinition.defaultVegaConfig?_.defaults({},rendererDefinition.defaultVegaConfig,prototypeDefaultVegaConfig):_.clone(prototypeDefaultVegaConfig);for(var key in rendererDefinition.options){if(rendererDefinition.options.hasOwnProperty(key)&&rendererDefinition.options[key]===undefined){delete combinedOptions[key]}}rendererDefinition.options=combinedOptions;for(var key in rendererDefinition.defaultVegaConfig){if(rendererDefinition.defaultVegaConfig.hasOwnProperty(key)&&rendererDefinition.defaultVegaConfig[key]===undefined){delete combinedDefaultVegaConfig[key]}}rendererDefinition.defaultVegaConfig=combinedDefaultVegaConfig;var Renderer=RendererPrototype.extend(rendererDefinition);GraphicsRenderingModule.RendererPrototypes[id]=Renderer;GraphicsRenderingModule.renderers[id]=new Renderer};GraphicsRenderingModule.getRendererPrototypeById=function(id){var RendererPrototype=GraphicsRenderingModule.RendererPrototypes[id];if(!RendererPrototype){throw _.str.sprintf('RendererPrototype with id "%s" not found.',id)}return RendererPrototype};GraphicsRenderingModule.getRendererById=function(id){var renderer=GraphicsRenderingModule.renderers[id];if(!renderer){throw _.str.sprintf('Renderer with id "%s" not found.',id)}return renderer};GraphicsRenderingModule.render=function(id,$element,data,options){GraphicsRenderingModule.getRendererById(id).render($element,data,options)}})},Logger); "use strict";App.module("GraphicsRenderingModule",function(GraphicsRenderingModule,App,Backbone,Marionette,$,_,Logger){GraphicsRenderingModule.addInitializer(function(options){GraphicsRenderingModule.registerRenderer({id:"_",defaultVegaConfig:{colorForBackground:"#fff",colorForAxisLabels:"#999",colorForAxes:"#ccc",colorForBackgroundFill:"#f0f0f0",fontFace:"'Web Open Sans', Verdana, sans-serif",fontSize:10,fontSizeForLabelsInAxis:10,fontSizeForLabelsInSecondaryAxis:8,data:[],scales:[],axes:[],marks:[],xdata:[],xscales:[],xaxes:[],xmarks:[]},render:function($element,data,options){var vc=_.mapObject(this.defaultVegaConfig,_.clone);vc=_.extend(vc,options);vc.totalWidth=$element.width();vc.totalHeight=$element.height();this._formVC(vc,data);var vegaSpec={background:vc.colorForBackground,width:vc.width,height:vc.height,padding:vc.padding,data:vc.data,scales:vc.scales,axes:vc.axes,marks:vc.marks};var $cover=$.bem.generateElement("vis-instance","cover",["category_process","visible"]);var $coverMessage=$.bem.generateElement("vis-instance","cover-message").text("Drawing...");$cover.append($coverMessage);$element.append($cover);GraphicsRenderingModule.vegaAsync($element,vegaSpec,"svg")},_formVC:function(vc,data,options){}})})},Logger); "use strict";App.module("GraphicsRenderingModule",function(GraphicsRenderingModule,App,Backbone,Marionette,$,_,Logger){GraphicsRenderingModule.addInitializer(function(options){GraphicsRenderingModule.registerRenderer({id:"chord-seq._",inherit:"_",defaultVegaConfig:{modesOfPiece:[undefined,"major","minor"],relativeRootNotes:_.range(1,13),relativeRootNotesInMajor:["I","#I","II","#II","III","IV","#IV","V","#V","VI","#VI","VII"],relativeRootNotesInMinor:["I","#I","II","III","#III","IV","#IV","V","VI","#VI","VII","#VII"],chordTypes:["","6","7","m","m6","m7","maj7","m7b5","dim","dim7","aug"],chordTypesWithM:["M","6","7","m","m6","m7","maj7","m7b5","dim","dim7","aug"],sequenceOfUsedRootNotes:_.range(12),sequenceOfUsedChordTypes:_.range(11),chordGrouppingIsByType:false,nIsIncluded:true,guidesAreVisible:true},parseEncodedChord:function(encodedChord){if(encodedChord=="0"){return 0}if(_.isString(encodedChord)&&encodedChord.length==7){return[encodedChord[0]*1,encodedChord[1]*10+encodedChord[2]*1-1,encodedChord[3]*10+encodedChord[4]*1-1,encodedChord[5]*10+encodedChord[6]*1-1]}throw"could not parse chord "+encodedChord},parsedEncodedChordToBin:function(vc,parsedEncodedChord){if(!_.isArray(parsedEncodedChord)){return vc.nIsIncluded?vc.numberOfChords-1:null}var indexOfRootNote=_.indexOf(vc.sequenceOfUsedRootNotes,parsedEncodedChord[1]);var indexOfChordType=_.indexOf(vc.sequenceOfUsedChordTypes,parsedEncodedChord[2]);if(indexOfRootNote==-1||indexOfChordType==-1){return null}if(vc.chordGrouppingIsByType){return vc.numberOfRootNotes*indexOfChordType+indexOfRootNote}else{return vc.numberOfChordTypes*indexOfRootNote+indexOfChordType}},chordBinToCoordinate:function(vc,chordBin){if(chordBin===null){throw"cannot convert null bin to a coordinate"}var nGaps=Math.floor(chordBin/(vc.chordGrouppingIsByType?vc.numberOfRootNotes:vc.numberOfChordTypes));return chordBin*vc.chordSize+nGaps*vc.chordGroupGapSize},titleOfParsedEncodedChord:function(vc,parsedEncodedChord){if(parsedEncodedChord===0){return"N"}else{return vc.titlesForRootNotes[parsedEncodedChord[1]]+" "+vc.titlesForChordTypes[parsedEncodedChord[2]]}}})})},Logger); "use strict";App.module("GraphicsRenderingModule",function(GraphicsRenderingModule,App,Backbone,Marionette,$,_,Logger){GraphicsRenderingModule.addInitializer(function(options){GraphicsRenderingModule.registerRenderer({id:"chord-seq.od-grid",inherit:"chord-seq._",defaultVegaConfig:{},_formVC:function(vc,data,options){throw"not implemented"}})})},Logger); "use strict";App.module("GraphicsRenderingModule",function(GraphicsRenderingModule,App,Backbone,Marionette,$,_,Logger){GraphicsRenderingModule.addInitializer(function(options){GraphicsRenderingModule.registerRenderer({id:"chord-seq.parallel-coordinates",inherit:"chord-seq._",defaultVegaConfig:{sizeOfStepMark:5,stepCount:3,primaryAxisFontSize:11,chordGapSizeToChordSizeRatio:1,paddingWhenAxisLabelsAreHidden:{top:5,left:15,bottom:10,right:15},paddingWhenAxisLabelsAreShownParitally:{top:20,left:15,bottom:10,right:15},paddingWhenAxisLabelsAreShown:{top:NaN,left:15,bottom:10,right:15}},_formVC:function(vc,data){var renderer=this;vc.numberOfRootNotes=vc.sequenceOfUsedRootNotes.length;vc.numberOfChordTypes=vc.sequenceOfUsedChordTypes.length;vc.titlesForChordTypes=vc.chordTypesWithM;vc.titlesForRootNotes=vc.relativeRootNotes;if(vc.recordingsInMajorModeAreIncluded&&!vc.recordingsInMinorModeAreIncluded){vc.titlesForRootNotes=vc.relativeRootNotesInMajor}if(vc.recordingsInMinorModeAreIncluded&&!vc.recordingsInMajorModeAreIncluded){vc.titlesForRootNotes=vc.relativeRootNotesInMinor}vc.numberOfChords=vc.numberOfRootNotes*vc.numberOfChordTypes;vc.numberOfGaps=vc.chordGrouppingIsByType?vc.numberOfChordTypes-1:vc.numberOfRootNotes-1;vc.padding=vc.paddingWhenAxisLabelsAreHidden;vc.width=vc.totalWidth-vc.padding.left-vc.padding.right;vc.labelsForGroupsAreShown=vc.width/(vc.numberOfGaps+1)>30;vc.labelsForChordsAreShown=vc.width/(vc.numberOfChords+vc.numberOfGaps)>10;if(vc.labelsForGroupsAreShown){vc.padding=vc.paddingWhenAxisLabelsAreShownParitally}if(vc.labelsForChordsAreShown){vc.padding=vc.paddingWhenAxisLabelsAreShown;var titles=[];if(vc.chordGrouppingIsByType){titles=_.map(vc.sequenceOfUsedRootNotes,function(index){return vc.titlesForRootNotes[index]})}else{titles=_.map(vc.sequenceOfUsedChordTypes,function(index){return vc.titlesForChordTypes[index]})}var maxTitleLength=0;_.each(titles,function(title){if(title.length>maxTitleLength){maxTitleLength=title.length}});vc.padding.top=maxTitleLength*4+25}if(vc.nIsIncluded){vc.numberOfChords+=1;vc.numberOfGaps+=1}vc.chordSize=1;do{vc.chordSize++;vc.chordGroupGapSize=Math.round(vc.chordSize*vc.chordGapSizeToChordSizeRatio);vc.width=(vc.numberOfChords-1)*vc.chordSize+vc.numberOfGaps*vc.chordGroupGapSize}while(vc.width+vc.padding.left+vc.padding.right<vc.totalWidth);--vc.chordSize;vc.chordGroupGapSize=Math.round(vc.chordSize*vc.chordGapSizeToChordSizeRatio);vc.width=(vc.numberOfChords-1)*vc.chordSize+vc.numberOfGaps*vc.chordGroupGapSize;vc.height=vc.width+vc.padding.left+vc.padding.right-vc.padding.top-vc.padding.bottom;var linksInVegaData=[];var encodedChordSequences=data.self.stats.sequences;var support=data.self.stats.support;var sequenceId=0;_.each(encodedChordSequences,function(encodedChordSequence,i){var recordsToAdd=[];var failed=false;var chordSequenceHasCycles=_.unique(encodedChordSequence).length!==encodedChordSequence.length;if(!vc.chordSequencesWithCyclesAreIncluded&&chordSequenceHasCycles){return}var parsedEncodedChordSequence=[];var chordTitles=[];_.each(encodedChordSequence,function(encodedChord,index){if(index>vc.stepCount){return}var parsedEncodedChord=renderer.parseEncodedChord(encodedChord);parsedEncodedChordSequence.push(parsedEncodedChord);if(index==vc.stepCount){chordTitles.push("...")}else{chordTitles.push(renderer.titleOfParsedEncodedChord(vc,parsedEncodedChord))}});var tooltip=chordTitles.join(" → ")+"<br/>support: "+support[i];_.each(parsedEncodedChordSequence,function(parsedEncodedChord,indexInSequence){if(failed){return}if(parsedEncodedChord!==0&&!(vc.recordingsInMajorModeAreIncluded&&parsedEncodedChord[0]==1||vc.recordingsInMinorModeAreIncluded&&parsedEncodedChord[0]==2)){failed=true;return}var bin=renderer.parsedEncodedChordToBin(vc,parsedEncodedChord);if(bin===null){failed=true;return}recordsToAdd.push({sequenceId:sequenceId,encodedChordSequence:encodedChordSequence,chordSequenceHasCycles:chordSequenceHasCycles,indexInSequence:indexInSequence,support:support[i],chordCoordinate:renderer.chordBinToCoordinate(vc,bin),color:vc.primaryColor,tooltip:tooltip})});if(!failed){linksInVegaData.push.apply(linksInVegaData,recordsToAdd)}++sequenceId});linksInVegaData.reverse();vc.data.push({name:"links",values:linksInVegaData});var chordsInVegaData=[];_.each(vc.sequenceOfUsedRootNotes,function(indexOfRootNote){_.each(vc.sequenceOfUsedChordTypes,function(indexOfChordType){var bin=renderer.parsedEncodedChordToBin(vc,[0,indexOfRootNote,indexOfChordType]);chordsInVegaData.push({rootNoteIndex:indexOfRootNote,rootNoteTitle:vc.titlesForRootNotes[indexOfRootNote],chordTypeIndex:indexOfChordType,chordTypeTitle:vc.titlesForChordTypes[indexOfChordType],chordCoordinate:renderer.chordBinToCoordinate(vc,bin)})})});vc.data.push({name:"chords",values:chordsInVegaData});if(vc.labelsForGroupsAreShown){var groupsForVega=[];if(vc.chordGrouppingIsByType){groupsForVega=chordsInVegaData.filter(function(chord){return chord.rootNoteIndex==vc.sequenceOfUsedRootNotes[0]})}else{groupsForVega=chordsInVegaData.filter(function(chord){return chord.chordTypeIndex==vc.sequenceOfUsedChordTypes[0]})}vc.data.push({name:"groups",values:groupsForVega})}var stepsInVegaData=_.range(0,vc.stepCount);vc.data.push({name:"steps",values:stepsInVegaData});vc.scales.push({name:"indexInSequence",domainMin:0,domainMax:vc.stepCount-1,point:true,round:true,range:[0,vc.height]});vc.scales.push({name:"strokeOpacity",type:"linear",domain:[0,data.self.coverage["ok_count"]*2],point:true,range:[0,1]});if(true||vc.guidesAreVisible){vc.marks.push({type:"rect",from:{data:"chords"},properties:{enter:{x:{field:"chordCoordinate"},y:{value:0},width:{value:1},height:{field:{group:"height"}},fill:{value:vc.colorForAxes}}}})}if(vc.nIsIncluded&&vc.guidesAreVisible){vc.marks.push({type:"rect",properties:{enter:{x:{field:{group:"width"}},y:{value:0},width:{value:"1"},height:{field:{group:"height"}},fill:{value:vc.colorForAxes}}}})}if(vc.guidesAreVisible){for(var right=0;right<2;right++){vc.marks.push({type:"rect",from:{data:"steps"},properties:{enter:{x:right?{field:{group:"width"}}:{value:-vc.sizeOfStepMark},width:{value:vc.sizeOfStepMark},y:{scale:"indexInSequence",field:"data"},height:{value:1},fill:{value:vc.colorForAxes}}}})}}vc.marks.push({type:"group",from:{data:"links",transform:[{type:"facet",groupby:["sequenceId"]}]},marks:[{type:"line",properties:{enter:{x:{field:"chordCoordinate"},y:{scale:"indexInSequence",field:"indexInSequence"},strokeOpacity:{scale:"strokeOpacity",field:"support"},stroke:{field:"color"},strokeWidth:{value:2}},update:{strokeOpacity:{scale:"strokeOpacity",field:"support"},stroke:{field:"color"}},hover:{strokeOpacity:{value:1},stroke:{value:"#000"}}}}]});vc.yOffsetForGroupLabels=-vc.padding.top+15;vc.yOffsetForChordLabels=-3;vc.xOffsetForGroupLabels=.5*vc.chordSize*((vc.chordGrouppingIsByType?vc.numberOfRootNotes:vc.numberOfChordTypes)-1);if(vc.labelsForGroupsAreShown){vc.marks.push({type:"text",from:{data:"groups"},properties:{enter:{x:{field:"chordCoordinate",offset:vc.xOffsetForGroupLabels},y:{value:vc.yOffsetForGroupLabels},text:{field:vc.chordGrouppingIsByType?"chordTypeTitle":"rootNoteTitle"},baseline:{value:"bottom"},align:{value:"center"},fill:{value:vc.colorForAxisLabels},font:{value:vc.fontFace},fontSize:{value:vc.fontSizeForLabelsInAxis}}}})}if(vc.nIsIncluded&&vc.labelsForGroupsAreShown){vc.marks.push({type:"text",properties:{enter:{y:{value:vc.labelsForChordsAreShown?vc.yOffsetForChordLabels:vc.yOffsetForGroupLabels},x:{field:{group:"width"}},text:{value:"N"},align:{value:"center"},baseline:{value:"bottom"},fill:{value:vc.colorForAxisLabels},font:{value:vc.fontFace},fontSize:{value:vc.fontSizeForLabelsInAxis}}}})}if(vc.labelsForChordsAreShown){vc.marks.push({type:"text",from:{data:"chords"},properties:{enter:{x:{field:"data.chordCoordinate",offset:0},y:{value:vc.yOffsetForChordLabels},text:{field:vc.chordGrouppingIsByType?"data.rootNoteTitle":"data.chordTypeTitle"},angle:{value:"-90"},baseline:{value:"middle"},fill:{value:vc.colorForAxisLabels},font:{value:vc.fontFace},fontSize:{value:vc.fontSizeForLabelsInSecondaryAxis}}}})}vc.marks.push({type:"image",from:{data:"dummy"},properties:{enter:{x:{value:0},width:{field:{group:"width"}},y:{field:{group:"height"}},height:{value:vc.padding.bottom+2},url:{value:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQIAAAAMCAYAAACJMrOUAAABFUlEQVRoge2PwW0CQQxFXQEUAoVAYaGT0Ek64Lq5QgMgLVJ4uezBspYsoxnCsPMPT1/y2B4/A5aOhctFqD3ynkvq/tL3yF/+TfobsAZWA2uXj7AK85G4L/bn/pc6X3qf/OU/C38DtglsXG5CrUZK3yt/+c/S34BdBh8ux/A9Y/1T77n7no385T8LfwM+/2Dvch9qJfpT53P3pyJ/+Tfhb8CXEKJtDDgIIdrGgA74vkPnsgu1V5B7T+q8/OXfhL8Bp3/k6PIYai0gf/lX6W/AGbgMnF2OcQn9kTgf+1Pfp/6f2pd7n/zl34S/AT1wHehd9qE29h6Z6s/dF6n9XvnL/y38Dfhx3FzeQq0Ez95f+33yl3+V/r9d8S8/zvVSHwAAAABJRU5ErkJggg=="},fill:{value:"#F00"}}}})}})})},Logger); "use strict";App.module("GraphicsRenderingModule",function(GraphicsRenderingModule,App,Backbone,Marionette,$,_,Logger){GraphicsRenderingModule.addInitializer(function(options){GraphicsRenderingModule.registerRenderer({id:"geography",inherit:"_",defaultVegaConfig:{comparisonMode:null,transformPropertiesByRegion:{planet:{defaultScale:500,translateProportionX:1/2,translateProportionY:1/2,circleSizeMult:20},africa:{defaultScale:100,translateProportionX:.2,translateProportionY:.5,circleSizeMult:50},europe:{defaultScale:70,translateProportionX:.2,translateProportionY:1.9,circleSizeMult:50}},symbolSize:20,internalSpaceOffset:6,colorForData:"#3182bd",padding:{top:10,left:10,bottom:10,right:10}},_formVC:function(vc,data){vc.width=vc.totalWidth-vc.padding.left-vc.padding.right;vc.height=vc.totalHeight-vc.padding.top-vc.padding.bottom;var countryStatsByCountryNumericCode={};var hist=data.self.stats?data.self.stats.hist:null;if(!hist){hist={counts:[],places:[]}}var countTotal=data.self.coverage.errors_count+data.self.coverage.failed_count;var countFailures=countTotal;for(var i=hist.counts.length-1;i>=0;--i){var countryNumericCode=vc.placeCountryNumericCodes[hist.places[i]];countTotal+=hist.counts[i];if(!countryNumericCode){countFailures+=hist.counts[i];continue}var country=vc.countriesByCountryNumericCode[countryNumericCode];var countryStats=countryStatsByCountryNumericCode[countryNumericCode];if(!countryStats){countryStats={numericCode:country[1],name:country[2],count:0};countryStatsByCountryNumericCode[countryNumericCode]=countryStats}countryStats.count+=hist.counts[i]}var countryStats=_.values(countryStatsByCountryNumericCode);for(var i=countryStats.length-1;i>=0;--i){var count=countryStats[i].count;var percentage=100*count/countTotal;countryStats[i].percentage=percentage}vc.data.push({name:"countries",values:vc.countries});vc.data.push({name:"countryOutlines",values:vc.countryOutlines,format:{type:"topojson",feature:"countries"}});vc.data.push({name:"countryStats",values:countryStats});var transformProperties=vc.transformPropertiesByRegion[vc.region];vc.data.push({name:"countrySummary",source:"countryOutlines",transform:[{type:"geopath",value:"data",projection:"eckert3",scale:100/transformProperties.defaultScale*vc.width,translate:[vc.width*transformProperties.translateProportionX,vc.height*transformProperties.translateProportionY]},{type:"lookup",on:"countryStats",onKey:"numericCode",keys:["id"],as:["cs"],"default":{count:0,percentage:0}},{type:"lookup",on:"countries",onKey:"1",keys:["id"],as:["tooltip"],"default":null}]});vc.scales.push({name:"color",type:"linear",domain:[0,.01,50],clamp:true,range:["#ccc","#c6dbef","#055893"]});vc.marks.push({type:"rect",properties:{enter:{x:{value:-vc.padding.left},y:{value:-vc.padding.top},fill:{value:"#fff"},y2:{field:{group:"height"},offset:vc.padding.left+vc.padding.right},x2:{field:{group:"width"},offset:vc.padding.top+vc.padding.bottom}}}});if(!vc.showCountriesAsCircles){vc.marks.push({type:"path",from:{data:"countrySummary"},properties:{enter:{stroke:{value:"#fff"},path:{field:"layout_path"}},update:{fill:{scale:"color",field:"cs.percentage"}},hover:{fill:{value:"#000"}}}})}else{vc.marks.push({type:"path",from:{data:"countrySummary"},properties:{enter:{stroke:{value:"#fff"},path:{field:"layout_path"}},update:{fill:{value:"#f0f0f0"}}}});vc.marks.push({type:"symbol",from:{data:"countrySummary",transform:[{type:"centroid",field:"layout_path"}]},properties:{enter:{size:{field:"cs.percentage",mult:transformProperties.circleSizeMult},opacity:{value:.5},x:{field:"centroid_x"},y:{field:"centroid_y"}},update:{fill:{value:vc.colorForData}},hover:{fill:{value:"#000"}}}})}}})})},Logger); "use strict";App.module("GraphicsRenderingModule",function(GraphicsRenderingModule,App,Backbone,Marionette,$,_,Logger){GraphicsRenderingModule.addInitializer(function(options){GraphicsRenderingModule.registerRenderer({id:"histogram",inherit:"_",defaultVegaConfig:{comparisonMode:null,dataDefinition:null,colorForFlats:"#666",colorForBars:0,ylabelDX:3,xlabelDY:-3,paddingWhenAxisLabelsAreShown:{top:5,left:40,bottom:20,right:10},paddingWhenAxisLabelsAreHidden:{top:5,left:10,bottom:1,right:10}},_formVC:function(vc,data){vc.enoughSpaceForAxisLabels=vc.totalWidth>200;vc.padding=vc.enoughSpaceForAxisLabels?vc.paddingWhenAxisLabelsAreShown:vc.paddingWhenAxisLabelsAreHidden;vc.width=vc.totalWidth-vc.padding.left-vc.padding.right;vc.height=vc.totalHeight-vc.padding.top-vc.padding.bottom;var xs;var valuesForBars0=[];var valuesForBars1=[];var valuesForBars2=[];var valuesForFlats0=[];var valuesForFlats1=[];var valuesForFlats2=[];var valueForHoris0=null;var valuesForOverlays0=[];var xsAreEdges=false;var xsAreCategories=false;if(vc.comparisonMode){xs=_.isFunction(vc.dataDefinition.forXs)?vc.dataDefinition.forXs(data.left):data.left[vc.dataDefinition.forXs]}else{xs=_.isFunction(vc.dataDefinition.forXs)?vc.dataDefinition.forXs(data.self):data.self[vc.dataDefinition.forXs]}if(vc.comparisonMode){valuesForBars1=_.isFunction(vc.dataDefinition.forBars)?vc.dataDefinition.forBars(data.left):data.left[vc.dataDefinition.forBars];valuesForBars2=_.isFunction(vc.dataDefinition.forBars)?vc.dataDefinition.forBars(data.right):data.right[vc.dataDefinition.forBars];if(vc.dataDefinition.forFlats){valuesForFlats1=_.isFunction(vc.dataDefinition.forFlats)?vc.dataDefinition.forFlats(data.left):data.left[vc.dataDefinition.forFlats];valuesForFlats2=_.isFunction(vc.dataDefinition.forFlats)?vc.dataDefinition.forFlats(data.right):data.right[vc.dataDefinition.forFlats]}}else{valuesForBars0=_.isFunction(vc.dataDefinition.forBars)?vc.dataDefinition.forBars(data.self):data.self[vc.dataDefinition.forBars];if(vc.dataDefinition.forFlats){valuesForFlats0=_.isFunction(vc.dataDefinition.forFlats)?vc.dataDefinition.forFlats(data.self):data.self[vc.dataDefinition.forFlats]}}if(vc.comparisonMode=="direct"){for(var i=0;i<valuesForBars1.length;i++){valuesForBars0.push(valuesForBars2[i]-valuesForBars1[i])}for(var i=0;i<valuesForFlats1.length;i++){valuesForFlats0.push(valuesForFlats2[i]-valuesForFlats1[i])}valuesForBars1=[];valuesForFlats1=[];valuesForBars2=[];valuesForFlats2=[]}try{if(valuesForBars0.length==xs.length-1){xsAreEdges=true}if(valuesForBars1.length==xs.length-1){xsAreEdges=true}if(vc.dataDefinition.forceXsAreEdges){xsAreEdges=true}}catch(e){throw new App.RepresentationModule.Error({type:"ok-count-0"})}if(_.isString(xs[0])){xsAreCategories=true}var xMean=undefined;if(vc.dataDefinition.forXMean&&data.self){xMean=_.isFunction(vc.dataDefinition.forXMean)?vc.dataDefinition.forXMean(data.self):data.self[vc.dataDefinition.forXMean]}var xStdDev=undefined;if(vc.dataDefinition.forXStdDev&&data.self){xStdDev=_.isFunction(vc.dataDefinition.forXStdDev)?vc.dataDefinition.forXStdDev(data.self):data.self[vc.dataDefinition.forXStdDev]}var generateVegaData=function(name,values,remarkPrefix,remarkSuffix){var vegaValues=[];var tooltipType=xsAreEdges?"tooltip_range":"tooltip_point";var maxI=values.length;for(var i=0;i<maxI;i++){var nextX=xs[i+1];if(nextX!==undefined||xsAreCategories){vegaValues.push([tooltipType,values[i],xs[i],nextX,remarkPrefix,remarkSuffix])}}return{name:name,values:vegaValues}};var generateVegaDataForHoris=function(name,values){return{name:name,values:["tooltip_horis",value]}};if(valuesForBars0.length){vc.data.push(generateVegaData("bars0",valuesForBars0))}if(valuesForBars1.length){vc.data.push(generateVegaData("bars1",valuesForBars1,"left: "))}if(valuesForBars2.length){vc.data.push(generateVegaData("bars2",valuesForBars2,"right: "))}if(valuesForFlats0.length){vc.data.push(generateVegaData("flats0",valuesForFlats0))}if(valuesForFlats1.length){vc.data.push(generateVegaData("flats1",valuesForFlats0,"left: "))}if(valuesForFlats2.length){vc.data.push(generateVegaData("flats2",valuesForFlats0,"right: "))}if(valueForHoris0!==null){vc.data.push(generateVegaDataForHoris("horis0",valuesForOverlays0))}var scalex={name:"scalex",range:"width",zero:false,round:false};if(xsAreCategories){scalex["domain"]={data:valuesForBars0.length?"bars0":"bars1",field:"2"};scalex["type"]="ordinal";scalex["padding"]=.2}else if(xsAreEdges){scalex["type"]="linear";scalex["domain"]=[_.first(xs),_.last(xs)];scalex["points"]=true}else{scalex["domain"]={data:valuesForBars0.length?"bars0":"bars1",field:"2"};scalex["domain"]=[_.first(xs),_.last(xs)]}var scalexRound=_.clone(scalex);scalexRound.name="scalex_round";scalexRound.round=true;vc.scales.push(scalex);vc.scales.push(scalexRound);var mult=1.1;var generateVegaYScale=function(name,valuesForBars){var min=_.min(valuesForBars);if(min<0){min=min*mult}var max=_.max(valuesForBars);if(max>0){max=max*mult}return{name:name,range:"height",round:true,nice:false,domain:[Math.min(0,min),Math.max(0,max)]}};if(valuesForBars0.length){vc.scales.push(generateVegaYScale("scale0",valuesForBars0))}if(valuesForBars1.length){vc.scales.push(generateVegaYScale("scale1",valuesForBars1))}if(valuesForBars2.length){vc.scales.push(generateVegaYScale("scale2",valuesForBars2))}var barWidth=vc.width/xs.length+.5;var offsetForXRight=.5;var generateVegaMark=function(dataName,scale,type,color,opacity){var markProperties={opacity:{value:opacity},y:{scale:scale,field:"1"}};if(type=="bar"){markProperties["y2"]={scale:scale,value:0}}else{markProperties["height"]={value:2}}if(xsAreCategories){markProperties["x"]={scale:"scalex",field:"2"};markProperties["width"]={value:1};markProperties["width"]={scale:"scalex",band:true}}else if(xsAreEdges){markProperties["x"]={scale:"scalex",field:"2"};markProperties["x2"]={scale:"scalex",field:"3",offset:offsetForXRight}}else{markProperties["x"]={scale:"scalex",field:"2",offset:offsetForXRight/2};markProperties["width"]={value:barWidth}}return{type:"rect",from:{data:dataName},properties:{enter:markProperties,update:{fill:{value:color}},hover:{fill:{value:"black"}}}}};vc.marks.push({type:"rect",properties:{enter:{x:{value:-vc.padding.left},y:{value:-vc.padding.top},fill:{value:"#fff"},y2:{field:{group:"height"},offset:vc.padding.left+vc.padding.right},x2:{field:{group:"width"},offset:vc.padding.top+vc.padding.bottom}}}});if(valuesForBars0.length){vc.marks.push(generateVegaMark("bars0","scale0","bar",vc.colorForBars,1))}if(valuesForBars1.length){vc.marks.push(generateVegaMark("bars1","scale1","bar",vc.colorForBars,.5))}if(valuesForBars2.length){vc.marks.push(generateVegaMark("bars2","scale2","bar",vc.colorForBars,.5))}if(valuesForFlats0.length){vc.marks.push(generateVegaMark("flats0","scale0","flat",vc.colorForFlats,1))}if(valuesForFlats1.length){vc.marks.push(generateVegaMark("flats1","scale1","flat",vc.colorForFlats,.5))}if(valuesForFlats2.length){vc.marks.push(generateVegaMark("flats2","scale2","flat",vc.colorForFlats,.5))}vc.marks.push({type:"rect",properties:{enter:{fill:{value:vc.colorForAxes},x:{value:0},x2:{field:{group:"width"}},height:{value:1},y:{scale:valuesForBars0.length?"scale0":"scale1",value:0}}}});var generateVegaVerticalMark=function(x,color,dataName,strokeDash){return{type:"rect",from:{data:dataName},properties:{enter:{stroke:{value:vc.colorForAxisLabels},strokeWidth:{value:1},y:{value:-99},y2:{field:{group:"height"}},x:{scale:"scalex_round",value:x},width:{value:1},strokeDash:{value:strokeDash}}}}};if(xStdDev!==undefined&&xMean!==undefined){vc.data.push({name:"stdDev",values:[["tooltip_value",xStdDev,0,0,"standard deviation: "]]});vc.marks.push(generateVegaVerticalMark(xMean-xStdDev,"#ccc","stdDev",[1,1]));vc.marks.push(generateVegaVerticalMark(xMean+xStdDev,"#ccc","stdDev",[1,1]))}if(xMean!==undefined){vc.data.push({name:"mean",values:[["tooltip_value",xMean,0,0,"mean: ",xStdDev===0?" (standard deviation is zero)":undefined]]});vc.marks.push(generateVegaVerticalMark(xMean,"#666","mean",0))}var axisOpacity=vc.enoughSpaceForAxisLabels?{value:1}:{value:0};vc.axes.push({type:"x",scale:"scalex",properties:{axis:{stroke:{value:"#fff"},strokeWidth:{value:0}},grid:{stroke:{value:"#fff"},strokeOpacity:{value:.4},strokeWidth:{value:1}},ticks:{stroke:{value:"#fff"},strokeWidth:{value:0},opacity:axisOpacity},labels:{fill:{value:vc.colorForAxisLabels},dy:{value:vc.xlabelDY},font:{value:vc.fontFace},fontSize:{value:vc.fontSizeForLabelsInAxis},opacity:axisOpacity}}});if(valuesForBars0.length){vc.axes.push({type:"y",scale:"scale0",grid:vc.enoughSpaceForAxisLabels,zero:false,properties:{axis:{stroke:{value:"#fff"},strokeWidth:{value:0}},grid:{stroke:{value:"#fff"},strokeOpacity:{value:.4},opacity:{value:1}},ticks:{stroke:{value:"#fff"},strokeWidth:{value:0},opacity:axisOpacity},labels:{fill:{value:vc.colorForAxisLabels},fontSize:{value:vc.fontSizeForLabelsInAxis},dx:{value:vc.ylabelDX},font:{value:vc.fontFace},opacity:axisOpacity}}})}}})})},Logger); "use strict";App.module("GraphicsRenderingModule",function(GraphicsRenderingModule,App,Backbone,Marionette,$,_,Logger){GraphicsRenderingModule.addInitializer(function(options){GraphicsRenderingModule.registerRenderer({id:"similarity-matrix",inherit:"_",defaultVegaConfig:{comparisonMode:null,colorForData:"#3182bd",padding:{top:5,left:0,bottom:0,right:0}},_formVC:function(vc,data){vc.enoughSpaceForAxisLabels=vc.totalWidth>200;vc.width=vc.totalWidth-vc.padding.left-vc.padding.right;vc.height=vc.totalHeight-vc.padding.top-vc.padding.bottom;var stats={list:[],distance:[]};if(data.self.stats){data.self.stats=stats}var recordingCount=stats.list.length;var distance=stats.distance;var list=stats.list;var cellsInVegaData=[];var maxDistance=0;for(var column=0;column<recordingCount;++column){for(var row=0;row<recordingCount;++row){var currentDistance=distance[row][column];if(currentDistance<1e-5){currentDistance=0}var cellInVegaData={column:column,row:row,nextColumn:column+1,nextRow:row+1,distance:currentDistance};if(column!=row){cellInVegaData.tooltip="↔ "+list[row].label+"<br/>↕ "+list[column].label+"<br/>"+GraphicsRenderingModule._formatNumberForTooltip(cellInVegaData.distance)}else{cellInVegaData.tooltip=list[row].label}cellsInVegaData.push(cellInVegaData);if(cellInVegaData.distance>maxDistance){maxDistance=cellInVegaData.distance}}}vc.data.push({name:"cells",values:cellsInVegaData});vc.scales.push({name:"column",domainMin:0,domainMax:recordingCount,point:true,round:true,range:[0,vc.width]});vc.scales.push({name:"row",domainMin:0,domainMax:recordingCount,point:true,round:true,range:[0,vc.height]});vc.scales.push({name:"fillOpacity",type:"linear",domain:[0,maxDistance],point:true,range:[0,1]});vc.marks.push({type:"rect",properties:{enter:{x:{value:-vc.padding.left},y:{value:-vc.padding.top},fill:{value:"#fff"},y2:{field:{group:"height"},offset:vc.padding.left+vc.padding.right},x2:{field:{group:"width"},offset:vc.padding.top+vc.padding.bottom}}}});vc.marks.push({type:"rect",from:{data:"cells"},properties:{enter:{x:{field:"column",scale:"column"},x2:{field:"nextColumn",scale:"column",offset:-1},y:{field:"row",scale:"row"},y2:{field:"nextRow",scale:"row",offset:-1},fill:{value:vc.colorForData},fillOpacity:{field:"distance",scale:"fillOpacity"}}}})}})})},Logger); "use strict";App.module("GraphicsRenderingModule",function(GraphicsRenderingModule,App,Backbone,Marionette,$,_,Logger){GraphicsRenderingModule.addInitializer(function(options){GraphicsRenderingModule.registerRenderer({id:"similarity-plane",inherit:"_",defaultVegaConfig:{comparisonMode:null,symbolSize:20,internalSpaceOffset:6,colorForData:"#3182bd",padding:{top:10,left:10,bottom:10,right:10}},_formVC:function(vc,data){vc.enoughSpaceForAxisLabels=vc.totalWidth>200;vc.width=vc.totalWidth-vc.padding.left-vc.padding.right;vc.height=vc.totalHeight-vc.padding.top-vc.padding.bottom;var stats={mds:[],list:[]};if(data.self.stats){data.self.stats=stats}var recordingCount=stats.list.length;var mds=stats.mds;var list=stats.list;var pointsInVegaData=[];for(var i=0;i<recordingCount;++i){var pointInVegaData={x:mds[i][0],y:mds[i][1]};pointInVegaData.tooltip=list[i].label;pointsInVegaData.push(pointInVegaData)}vc.data.push({name:"points",values:pointsInVegaData});vc.scales.push({name:"x",domain:{data:"points",field:"x"},point:true,round:true,zero:true,range:[vc.internalSpaceOffset,vc.width-vc.internalSpaceOffset]});vc.scales.push({name:"y",domain:{data:"points",field:"y"},point:true,round:true,zero:true,inverse:true,range:[vc.internalSpaceOffset,vc.height-vc.internalSpaceOffset]});vc.marks.push({type:"rect",properties:{enter:{x:{value:-vc.padding.left},y:{value:-vc.padding.top},fill:{value:"#fff"},y2:{field:{group:"height"},offset:vc.padding.left+vc.padding.right},x2:{field:{group:"width"},offset:vc.padding.top+vc.padding.bottom}}}});vc.marks.push({type:"rect",properties:{enter:{y:{value:0,offset:.5},y2:{field:{group:"height"},offset:-.5},x:{value:0,offset:.5},x2:{field:{group:"width"},offset:-.5},stroke:{value:vc.colorForAxes},strokeWidth:{value:1}}}});vc.marks.push({type:"symbol",from:{data:"points"},properties:{enter:{x:{field:"x",scale:"x"},y:{field:"y",scale:"y"},size:{value:vc.symbolSize},fill:{value:vc.colorForData}}}})}})})},Logger); "use strict";App.module("MainMenuModule",function(MainMenuModule,App,Backbone,Marionette,$,_,Logger){MainMenuModule.MainMenuBarView=Backbone.View.extend({options:{flashingSpeed:100},el:".main-menu-bar",_$itemHelp:null,_$aHelp:null,_$itemUndo:null,_$aUndo:null,_$itemRedo:null,_$aRedo:null,_$itemShare:null,_$aShare:null,_$itemBookmarks:null,_$aBookmarks:null,_$itemDownloads:null,_$aDownloads:null,initialize:function(options){var _this=this;_this.$el.disableSelection();_this._$itemHelp=_this.$(".main-menu-bar__item_action_help");_this._$aHelp=_this._$itemHelp.children().first();_this._$itemHelp.setMod("main-menu-bar__item","state","enabled");_this._$aHelp.click(function(event){App.showHelp();event.preventDefault();return false});_this._$itemUndo=_this.$(".main-menu-bar__item_action_undo");_this._$aUndo=_this._$itemUndo.children().first();_this._$itemRedo=_this.$(".main-menu-bar__item_action_redo");_this._$aRedo=_this._$itemRedo.children().first();var stateHistory=App.context.get("stateHistory");App.context.get("stateHistory").bind("change",_this.render,_this);_this._$aUndo.click(function(event){App.undo();event.preventDefault()});_this._$aRedo.click(function(event){App.redo();event.preventDefault()});_this._$itemShare=_this.$(".main-menu-bar__item_action_share");_this._$aShare=_this._$itemShare.children().first();_this._$itemBookmarks=_this.$(".main-menu-bar__item_action_bookmarks");_this._$aBookmarks=_this._$itemBookmarks.children().first();_this._$itemDownloads=_this.$(".main-menu-bar__item_action_downloads");_this._$aDownloads=_this._$itemDownloads.children().first();_this._$aShare.click(function(event){App.showStateSharing();event.preventDefault()});_this._$aBookmarks.click(function(event){App.showStateBookmarks();event.preventDefault()});_this._$itemChangeMode=_this.$(".main-menu-bar__item_action_change-mode");_this._$aChangeModeToRecordings=_this._$itemChangeMode.children().first();_this._$aChangeModeToCollections=_this._$itemChangeMode.children().last();_this._$aChangeModeToRecordings.click(function(event){App.context.attributes.state.set("musicRecordingsGridIsShown",true);event.preventDefault()});_this._$aChangeModeToCollections.click(function(event){App.context.attributes.state.set("musicRecordingsGridIsShown",false);event.preventDefault()});_this.render(false,true)},render:function(deep,instant){var _this=this;_this._updateUndoRedo();_this._updateModeChanger()},flashItem:function(itemActionToFlash,times,callback){var _this=this;var $item=_this.$(".main-menu-bar__item_action_"+itemActionToFlash);$item.addClass("main-menu-bar__item_flashing");var currentCheckNumber=Math.random();$item.data("randomNumberForFlashCheck",currentCheckNumber);var timerCounter=times>1?times*2-1:1;var interval=setInterval(function(){if(currentCheckNumber==$item.data("randomNumberForFlashCheck")){if(timerCounter%2){$item.removeClass("main-menu-bar__item_flashing")}else{$item.addClass("main-menu-bar__item_flashing")}}else{if(_.isFunction(callback)){callback.call($item,true)}clearInterval(interval)}if(!--timerCounter){if(_.isFunction(callback)){callback.call($item,false)}clearInterval(interval)}},_this.options.flashingSpeed)},_flashModeChangerThreeTimes:function(){var _this=this;_this.flashItem("change-mode",3)},_updateUndoRedo:function(){var _this=this;var stateHistory=App.context.get("stateHistory");_this._$itemUndo.setMod("main-menu-bar","item","state",stateHistory.canUndo()?"enabled":false);_this._$itemRedo.setMod("main-menu-bar","item","state",stateHistory.canRedo()?"enabled":false)},_updateModeChanger:function(){var _this=this;var state=App.context.get("state");var musicRecordingsGridIsShown=!!state.get("musicRecordingsGridIsShown");if(_this._cachedMusicRecordingsGridIsShown!==musicRecordingsGridIsShown){_this._$itemChangeMode.setMod("main-menu-bar","item","mode",musicRecordingsGridIsShown?"2collections":"2recordings");if(musicRecordingsGridIsShown){_this.stopListening(state.get("musicRecordingGrid"));_this.listenTo(state.get("musicCollectionGrid"),"change",_this._flashModeChangerThreeTimes)}else{_this.stopListening(state.get("musicCollectionGrid"));_this.listenTo(state.get("musicRecordingGrid"),"change",_this._flashModeChangerThreeTimes)}_this._cachedMusicRecordingsGridIsShown=musicRecordingsGridIsShown}}})},Logger); "use strict";App.module("MainMenuModule",function(MainMenuModule,App,Backbone,Marionette,$,_,Logger){MainMenuModule.startWithParent=false;var defaultModuleOptions={};var moduleOptions;var assertModuleIsInitialized=function(){if(!$bar){throw"MainMenuModule has not been initialized"}};MainMenuModule.addInitializer(function(options){moduleOptions=_.extend(defaultModuleOptions,options);MainMenuModule.logger=Logger.get("MainMenuModule");MainMenuModule.logger.setLevel(Logger.DEBUG);this.barView=new App.MainMenuModule.MainMenuBarView});MainMenuModule.flashItem=function(item,times,callback){this.barView.flashItem(item,times,callback)}},Logger); "use strict";App.module("MainRegionModule",function(MainRegionModule,App,Backbone,Marionette,$,_,Logger){MainRegionModule.startWithParent=false;var defaultModuleOptions={};var assertModuleIsInitialized=function(){if(!logger){throw"MainRegionModule has not been initialized"}};MainRegionModule.addInitializer(function(options){MainRegionModule.moduleOptions=_.extend(defaultModuleOptions,options);MainRegionModule.logger=Logger.get("MainRegionModule");MainRegionModule.logger.setLevel(Logger.DEBUG)})},Logger); "use strict";App.module("MainRegionModule",function(MainRegionModule,App,Backbone,Marionette,$,_,Logger){MainRegionModule.MainRegionView=Backbone.View.extend({initialize:function(options){var _this=this;_this.options=_.defaults(options||{},this.options);var $collectionsGridEl=_this.$(".config-grid");var $recordingsGridEl=$collectionsGridEl.clone();$recordingsGridEl.appendTo(_this.el);_this.options.state.on("change",function(){_this.render()});_this._musicCollectionConfigGridView=new MainRegionModule.ConfigGridView({el:$collectionsGridEl,state:_this.options.state,configGrid:_this.options.state.get("musicCollectionGrid"),parentState:_this.options.state,parentContainerElement:_this.el});_this._musicRecordingConfigGridView=new MainRegionModule.ConfigGridView({el:$recordingsGridEl,state:_this.options.state,configGrid:_this.options.state.get("musicRecordingGrid"),parentState:_this.options.state,parentContainerElement:_this.el});_this._$flipper=$.bem.generateElement("main-region","flipper");_this._$flipper.append(_this._musicRecordingConfigGridView.$ghost,_this._musicCollectionConfigGridView.$ghost);_this._$flipperContainer=$.bem.generateElement("main-region","flipper-container");_this._$flipperContainer.append(_this._$flipper);_this._$flipper.on("transitionend MSTransitionEnd webkitTransitionEnd oTransitionEnd",function(){_this._stopFlipping()});_this.render(true,true)},render:function(deep,instant){var _this=this;var musicRecordingsGridNeedsToBeShown=!!_this.options.state.get("musicRecordingsGridIsShown");var gridViewToShow=musicRecordingsGridNeedsToBeShown?_this._musicRecordingConfigGridView:_this._musicCollectionConfigGridView;var gridViewToHide=!musicRecordingsGridNeedsToBeShown?_this._musicRecordingConfigGridView:_this._musicCollectionConfigGridView;if(!gridViewToShow.el.getAttribute("data-active")){if(!instant){if(!_this.isSwitchingBetweenGrids()){_this._$flipper.removeClass("main-region__flipper_animating");_this._$flipper.setMod("main-region","flipper","to",!musicRecordingsGridNeedsToBeShown?"recording":"collection");_this._$flipper.addClass("main-region__flipper_animating");_this._$flipperContainer.appendTo(_this.el)}setTimeout(function(){_this._$flipper.setMod("main-region","flipper","to",musicRecordingsGridNeedsToBeShown?"recording":"collection")},10)}gridViewToHide.$el.attr("data-active",null).detach();gridViewToShow.$el.attr("data-active","1").appendTo(_this.$el);gridViewToShow.render(true,true)}else if(deep){gridViewToShow.render(deep,instant)}},isSwitchingBetweenGrids:function(){var _this=this;return _this._$flipperContainer.parent().length},_stopFlipping:function(){var _this=this;_this._$flipperContainer.detach()}})},Logger); "use strict";App.module("MainRegionModule",function(MainRegionModule,App,Backbone,Marionette,$,_,Logger){MainRegionModule.ConfigGridView=Backbone.View.extend({options:{state:null,configGrid:null,parentState:null,parentContainerElement:null},_cachedConfigGridType:null,initialize:function(options){var _this=this;_this.options=_.defaults(options||{},this.options);_this._cachedConfigGridType=_this.options.configGrid.getType();_this.$el.setMod("config-grid","type",_this._cachedConfigGridType);_this.$(".config-grid__utils").empty();_this._$header=_this.$(".config-grid__header");_this._$header.html($("#config-grid__header_type_"+_this._cachedConfigGridType).text());_this._$header.click(function(){_this.options.configGrid.set({selectedEntityConfigClientId:null,selectedViewConfigClientId:null})});_this.$ghost=_this.$el.clone();_this.cellsView=new MainRegionModule.ConfigGridCellsView({state:_this.options.state,configGrid:_this.options.configGrid,el:_this.$(".config-grid-cells"),parentConfigGridView:_this});_this.entityPanelView=new MainRegionModule.ConfigGridPanelView({el:_this.$(".config-grid-panel_dimension_entity"),state:_this.options.state,configGrid:_this.options.configGrid,dimension:"entity",parentConfigGridView:_this});_this.viewPanelView=new MainRegionModule.ConfigGridPanelView({el:_this.$(".config-grid-panel_dimension_view"),state:_this.options.state,configGrid:_this.options.configGrid,dimension:"view",parentConfigGridView:_this});_this.cellsView.on("change-positions-of-selected-headers",_.throttle(function(entityHeaderLeft,entityHeaderWidth,viewHeaderTop,viewHeaderHeight){_this.entityPanelView.updateRadiusFixer(entityHeaderLeft,entityHeaderWidth);_this.viewPanelView.updateRadiusFixer(viewHeaderTop,viewHeaderHeight)},100))},render:function(deep,instant){var _this=this;if(deep){_this.cellsView.render(deep,instant);_this.entityPanelView.render(deep,instant);_this.viewPanelView.render(deep,instant)}},isVisible:function(){return!!this.el.getAttribute("data-active")},scrollAccordingToSelection:function(deep,instant){this.cellsView.scrollAccordingToSelection(deep,instant)},ignoreAxisOnNextScroll:function(x,y){this.cellsView._ignoreXOnNextScroll=!!x;this.cellsView._ignoreYOnNextScroll=!!y}})},Logger); "use strict";App.module("MainRegionModule",function(MainRegionModule,App,Backbone,Marionette,$,_,Logger){MainRegionModule.ConfigGridChildView=Backbone.View.extend({renderIfParentConfigGridIsVisible:function(){if(this.options.parentConfigGridView.isVisible()){this.render()}}})},Logger); "use strict";App.module("MainRegionModule",function(MainRegionModule,App,Backbone,Marionette,$,_,Logger){MainRegionModule.ConfigGridCellsView=MainRegionModule.ConfigGridChildView.extend({options:{state:null,configGrid:null,parentConfigGridView:null,scrollAnimationMinSpeed:100,scrollAnimationBaseSpeed:400,scrollAnimationBaseDistance:500,desiredPaddingAroundVisInstanceOnScroll:{left:35,top:20,right:35,bottom:33},enableFixedHeaders:true},_logger:null,_$entityHeadersContainer:null,_$entityHeadersBlind:null,_$viewHeadersContainer:null,_$viewHeadersBlind:null,_$visInstancesContainer:null,_$cornerBlind:null,_$fixedContainer:null,_$entityAdder:null,_$viewAdder:null,_distanceBetweenEntities:10,_distanceBetweenViews:10,_viewHeaderHeight:0,_entityAdderWidth:0,_viewAdderHeight:0,_cachedMinSpaceWidth:0,_cachedMinSpaceHeight:0,_spacePadding:null,_scrollLeftBeforeLatestSelectionUpdate:0,_scrollTopBeforeLatestSelectionUpdate:0,_ignoreXOnNextScroll:false,_ignoreYOnNextScroll:false,_latestChangeWasAReset:false,_cachedScrollPosGridHash:null,_cachedScrollPosSelection:null,_cachedScrollPosX:null,_cachedScrollPosY:null,_cachedSelectedEntityConfigClientId:null,_cachedSelectedViewConfigClientId:null,_cachedEntityHeaderViewsByClientId:{},_cachedViewHeaderViewsByClientId:{},_cachedVisInstanceViewsByClientIdPair:{},_cachedEntityConfigClientIds:null,_cachedViewConfigClientIds:null,_cachedEntityWidth:null,_cachedViewContentHeights:null,initialize:function(options){var _this=this;_this._logger=Logger.get("ConfigGridCellsView");_this.options=_.defaults(options||{},this.options);if(_this.options.enableFixedHeaders===null){_this.options.enableFixedHeaders=navigator.userAgent.indexOf("afari")>=0&&navigator.userAgent.indexOf("Chrom")==-1||navigator.userAgent.indexOf("MSIE")>=0||navigator.userAgent.indexOf("MATM")>=0||navigator.userAgent.indexOf("Trident")>=0}var configGridType=_this.options.configGrid.getType();_this.$el.empty();_this._$entityHeadersContainer=$.bem.generateElement("config-grid-cells","entity-headers-container");_this._$entityHeadersBlind=$.bem.generateElement("config-grid-cells","entity-headers-blind");_this._$entityHeadersContainer.append(_this._$entityHeadersBlind);_this._$viewHeadersContainer=$.bem.generateElement("config-grid-cells","view-headers-container");_this._$viewHeadersBlind=$.bem.generateElement("config-grid-cells","view-headers-blind");_this._$viewAdder=$.bem.generateElement("config-grid-cells","view-header",["kind_adder"]);_this._$viewHeadersContainer.append(_this._$viewHeadersBlind,_this._$viewAdder);_this._$visInstancesContainer=$.bem.generateElement("config-grid-cells","vis-instances-container");_this._$cornerBlind=$.bem.generateElement("config-grid-cells","corner-blind");_this._$space=$.bem.generateElement("config-grid-cells","space");_this._$containerOfScrollable=$.bem.generateElement("config-grid-cells","container",["position_scrollable"]);_this._$containerOfFixed=$.bem.generateElement("config-grid-cells","container",["position_fixed"]);if(configGridType=="collection"){_this._$entityAdder=$.bem.generateElement("config-grid-cells","entity-header",["kind_adder"]);var $entityAdderBackground=$.bem.generateElement("config-grid-cells","entity-header-background");var $entityAdderLabel=$.bem.generateElement("config-grid-cells","entity-header-label");$entityAdderLabel.html(Backbone.Marionette.TemplateCache.get("#config-grid_collection__entity-adder-label"));_this._$entityAdder.append($entityAdderBackground,$entityAdderLabel);_this._$entityHeadersContainer.append(_this._$entityAdder);_this._$entityAdder.click(function(){_this.options.configGrid.addEntityAndSelectIt(new App.ContextModule.Config)})}else{_this._$entityAdder=$()}_this._$viewAdder=$.bem.generateElement("config-grid-cells","view-header",["kind_adder"]);var $viewAdderBackground=$.bem.generateElement("config-grid-cells","view-header-background");var $viewAdderLabel=$.bem.generateElement("config-grid-cells","view-header-label");$viewAdderLabel.html(Backbone.Marionette.TemplateCache.get("#config-grid__view-adder-label"));_this._$viewAdder.append($viewAdderBackground,$viewAdderLabel);_this._$viewHeadersContainer.append(_this._$viewAdder);_this._$viewAdder.click(function(){_this.options.configGrid.addViewAndSelectIt(new App.ContextModule.Config)});_this._$entityHeadersContainer.append();_this._$viewHeadersContainer.append();_this._$space.append(_this._$visInstancesContainer,_this._$entityHeadersContainer,_this._$viewHeadersContainer,_this._$cornerBlind);_this._$containerOfScrollable.append(_this._$space);_this.$el.append(_this._$containerOfScrollable,_this._$containerOfFixed);_this._viewHeaderHeight=_this._$viewAdder.height();_this._entityAdderWidth=_this._$entityAdder.width();_this._viewAdderHeight=_this._viewHeaderHeight;if(!_this._entityAdderWidth){_this._entityAdderWidth=-_this._distanceBetweenEntities}_this._spacePadding={};var interval;var setSpaceInterval=function(){if(_this._$space.css("padding-top")){_this._spacePadding.top=parseInt(_this._$space.css("padding-top"),10);_this._spacePadding.right=parseInt(_this._$space.css("padding-right"),10);_this._spacePadding.bottom=parseInt(_this._$space.css("padding-bottom"),10);_this._spacePadding.left=parseInt(_this._$space.css("padding-left"),10);_this._spacePadding.h=_this._spacePadding.left+_this._spacePadding.right;_this._spacePadding.v=_this._spacePadding.top+_this._spacePadding.bottom;_this._updateDemensionsForContainerOfFixed();clearInterval(interval)}};if(_this._$space.css("padding-top")){setSpaceInterval()}else{interval=setInterval(setSpaceInterval,50)}_this.listenTo(_this.options.configGrid,"change",_this.renderIfParentConfigGridIsVisible);var isSafari=navigator.userAgent.indexOf("afari")>=0;var isChrome=navigator.userAgent.indexOf("rome")>=0;var isScrolling=false;if(_this.options.enableFixedHeaders){_this._$containerOfScrollable.mousewheel(_.debounce(function(event){_this._toggleFixedHeadersIfNeeded(true);var visInstanceViews=_.values(_this._cachedVisInstanceViewsByClientIdPair);for(var i=visInstanceViews.length-1;i>=0;--i){visInstanceViews[i].cancelPointerHighlights()}App.TooltipModule.update();if(isSafari||isChrome){_this._$containerOfScrollable.scrollLeft(_this._$containerOfScrollable.scrollLeft()+event.deltaX);_this._$containerOfScrollable.scrollTop(_this._$containerOfScrollable.scrollTop()-event.deltaY);event.preventDefault()}},50,true));_this._$containerOfScrollable.mousewheel(_.debounce(function(event){if(!isScrolling){_this._toggleFixedHeadersIfNeeded(false)}},200))}_this._$containerOfScrollable.scroll(function(event){if(!isScrolling){isScrolling=true}_this._toggleFixedHeadersIfNeeded(true)});_this._$containerOfScrollable.scroll(_.debounce(function(event){_this._toggleFixedHeadersIfNeeded(false);_this._reviseSpaceSize();isScrolling=false;_this._updateCachedScroll()},200));$(window).resize(_.throttle(function(){_this._reviseSpaceSize();_this._updateDemensionsForContainerOfFixed()},100));_this._toggleFixedHeadersIfNeeded(false);_this._updateDemensionsForContainerOfFixed();_this._cachedScrollPosGridHash=App.DataModule.Storage.getStrCache(MainRegionModule,_.str.sprintf("scroll-pos-grid-hash_%s",configGridType));_this._cachedScrollPosSelection=App.DataModule.Storage.getStrCache(MainRegionModule,_.str.sprintf("scroll-pos-selection_%s",configGridType));_this._cachedScrollPosX=1*App.DataModule.Storage.getStrCache(MainRegionModule,_.str.sprintf("scroll-pos-x_%s",configGridType));_this._cachedScrollPosY=1*App.DataModule.Storage.getStrCache(MainRegionModule,_.str.sprintf("scroll-pos-y_%s",configGridType));$(window).unload(function(){App.DataModule.Storage.setStrCache(MainRegionModule,_.str.sprintf("scroll-pos-grid-hash_%s",configGridType),_this._cachedScrollPosGridHash);App.DataModule.Storage.setStrCache(MainRegionModule,_.str.sprintf("scroll-pos-selection_%s",configGridType),_this._cachedScrollPosSelection);App.DataModule.Storage.setStrCache(MainRegionModule,_.str.sprintf("scroll-pos-x_%s",configGridType),""+_this._cachedScrollPosX);App.DataModule.Storage.setStrCache(MainRegionModule,_.str.sprintf("scroll-pos-y_%s",configGridType),""+_this._cachedScrollPosY)})},render:function(deep,instant){var _this=this;_this._updateLayout(deep,instant);_this._updateSelection(deep,instant);if(deep){_this._reviseSpaceSize();_this._updateDemensionsForContainerOfFixed()}_this._adjustToScrollPos(deep,instant);_this.scrollAccordingToSelection(deep,instant);if(deep){var entityHeaderViews=_.values(_this._cachedEntityHeaderViewsByClientId);for(var i=entityHeaderViews.length-1;i>=0;--i){entityHeaderViews[i].render(deep,instant)}var viewHeaderViews=_.values(_this._cachedViewHeaderViewsByClientId);for(var i=viewHeaderViews.length-1;i>=0;--i){viewHeaderViews[i].render(deep,instant)}var visInstanceViews=_.values(_this._cachedVisInstanceViewsByClientIdPair);for(var i=visInstanceViews.length-1;i>=0;--i){visInstanceViews[i].render(deep,instant)}}},getEntityWidth:function(){var _this=this;return(_this.options.configGrid.get("entityWidth")||App.options.defaultEntityWidth)*1},_updateLayout:function(deep,instant){var _this=this;var entityListHasChanged=false;var viewListHasChanged=false;var newEntityConfigs=_this.options.configGrid.get("entityConfigs");var newViewConfigs=_this.options.configGrid.get("viewConfigs");var newEntityConfigClientIds=_.pluck(newEntityConfigs.models,"cid");var newViewConfigClientIds=_.pluck(newViewConfigs.models,"cid");_this._scrollLeftBeforeLatestLayoutUpdate=_this.$el.scrollLeft();_this._scrollTopBeforeLatestLayoutUpdate=_this.$el.scrollTop();if(_this._cachedEntityConfigClientIds===null){entityListHasChanged=true;viewListHasChanged=true;_this._cachedEntityConfigClientIds=[];_this._cachedViewConfigClientIds=[]}var createdEntityConfigClientIds=_.difference(newEntityConfigClientIds,_this._cachedEntityConfigClientIds);var createdViewConfigClientIds=_.difference(newViewConfigClientIds,_this._cachedViewConfigClientIds);var removedEntityConfigClientIds=_.difference(_this._cachedEntityConfigClientIds,newEntityConfigClientIds);var removedViewConfigClientIds=_.difference(_this._cachedViewConfigClientIds,newViewConfigClientIds);_this._latestChangeWasAReset=false;if(createdEntityConfigClientIds.length+removedEntityConfigClientIds.length==1){_this._ignoreYOnNextScroll=true}if(createdViewConfigClientIds.length+removedViewConfigClientIds.length==1){_this._ignoreXOnNextScroll=true}if(!_.isEqual(newEntityConfigClientIds,_this._cachedEntityConfigClientIds)){entityListHasChanged=true}if(!_.isEqual(newViewConfigClientIds,_this._cachedViewConfigClientIds)){viewListHasChanged=true}if(entityListHasChanged&&createdEntityConfigClientIds.length+removedEntityConfigClientIds.length>1||viewListHasChanged&&createdViewConfigClientIds.length+removedViewConfigClientIds.length>1){_this._latestChangeWasAReset=true;_this._ignoreXOnNextScroll=false;_this._ignoreYOnNextScroll=false}var newEntityHeaderViewsByClientId=_this._cachedEntityHeaderViewsByClientId;var newViewHeaderViewsByClientId=_this._cachedViewHeaderViewsByClientId;var newVisInstanceViewsByClientIdPair=_this._cachedVisInstanceViewsByClientIdPair;var viewHeaderViewsToRender=[];var entityHeaderViewsToRender=[];var visInstanceViewsToRender=[];if(entityListHasChanged){newEntityHeaderViewsByClientId={};for(var i=0;i<newEntityConfigClientIds.length;i++){var currentEntityClientId=newEntityConfigClientIds[i];var entityHeaderView=_this._cachedEntityHeaderViewsByClientId[currentEntityClientId];if(!entityHeaderView){_this._logger.debug("generate entity header ",currentEntityClientId);entityHeaderView=_this._generateEntityHeaderView(newEntityConfigs.get(currentEntityClientId));entityHeaderViewsToRender.push(entityHeaderView);_this._$entityHeadersContainer.append(entityHeaderView.el)}newEntityHeaderViewsByClientId[currentEntityClientId]=entityHeaderView}for(var i=removedEntityConfigClientIds.length-1;i>=0;--i){_this._cachedEntityHeaderViewsByClientId[removedEntityConfigClientIds[i]].remove();App.dynamicDerivedConfigDataProvider.retire(removedEntityConfigClientIds[i])}}else{newEntityHeaderViewsByClientId=_this._cachedEntityHeaderViewsByClientId}if(viewListHasChanged){newViewHeaderViewsByClientId={};for(var i=0;i<newViewConfigClientIds.length;i++){var currentViewClientId=newViewConfigClientIds[i];var viewHeaderView=_this._cachedViewHeaderViewsByClientId[currentViewClientId];if(!viewHeaderView){_this._logger.debug("generate view header ",currentViewClientId);viewHeaderView=_this._generateViewHeaderView(newViewConfigs.get(currentViewClientId));viewHeaderViewsToRender.push(viewHeaderView);_this._$viewHeadersContainer.append(viewHeaderView.el)}newViewHeaderViewsByClientId[currentViewClientId]=viewHeaderView}for(var i=removedViewConfigClientIds.length-1;i>=0;--i){_this._cachedViewHeaderViewsByClientId[removedViewConfigClientIds[i]].remove();App.dynamicDerivedConfigDataProvider.retire(removedViewConfigClientIds[i])}}else{newViewHeaderViewsByClientId=_this._cachedViewHeaderViewsByClientId}if(viewListHasChanged||entityListHasChanged){newVisInstanceViewsByClientIdPair={};for(var i=0;i<newEntityConfigClientIds.length;i++){var currentEntityClientId=newEntityConfigClientIds[i];for(var j=0;j<newViewConfigClientIds.length;j++){var currentViewClientId=newViewConfigClientIds[j];var currentClientIdPair=currentEntityClientId+currentViewClientId;var visInstanceView=_this._cachedVisInstanceViewsByClientIdPair[currentClientIdPair];if(!visInstanceView){_this._logger.debug("generate vis instance",currentEntityClientId,currentViewClientId);visInstanceView=_this._generateVisInstanceView(newEntityConfigs.get(currentEntityClientId),newViewConfigs.get(currentViewClientId));visInstanceViewsToRender.push(visInstanceView);_this._$visInstancesContainer.append(visInstanceView.el)}newVisInstanceViewsByClientIdPair[currentClientIdPair]=visInstanceView}}for(var i=this._cachedEntityConfigClientIds.length-1;i>=0;--i){for(var j=removedViewConfigClientIds.length-1;j>=0;--j){var visInstanceToRemove=_this._cachedVisInstanceViewsByClientIdPair[this._cachedEntityConfigClientIds[i]+removedViewConfigClientIds[j]];visInstanceToRemove.remove()}}for(var i=removedEntityConfigClientIds.length-1;i>=0;--i){for(var j=this._cachedViewConfigClientIds.length-1;j>=0;--j){var visInstanceToRemove=_this._cachedVisInstanceViewsByClientIdPair[removedEntityConfigClientIds[i]+this._cachedViewConfigClientIds[j]];if(visInstanceToRemove){visInstanceToRemove.remove()}}}}var viewHeightsHaveChanged=false;var entityWidthHasChanged=false;var entityWidth=_this.getEntityWidth();var viewContentHeights=[];for(var row=0;row<newViewConfigClientIds.length;row++){var currentViewConfigClientId=newViewConfigClientIds[row];var viewConfig=newViewConfigs.get(currentViewConfigClientId);var viewContentHeight=App.RepresentationModule.getMasterForConfig(viewConfig).calculateVisInstanceContentHeight(viewConfig,entityWidth);viewContentHeights.push(viewContentHeight)}if(entityWidth!==_this._cachedEntityWidth){entityWidthHasChanged=true;_this._cachedEntityWidth=entityWidth}if(!_.isEqual(viewContentHeights,_this._cachedViewContentHeights)){viewHeightsHaveChanged=true;_this._cachedViewContentHeights=viewContentHeights}if(viewListHasChanged||entityListHasChanged||entityWidthHasChanged||viewHeightsHaveChanged){var newEntityDimensions=[];var newViewDimensions=[];var x=0;var configGridType=_this.options.configGrid.getType();for(var col=0;col<newEntityConfigClientIds.length;col++){var currentEntityConfigClientId=newEntityConfigClientIds[col];newEntityDimensions.push([currentEntityConfigClientId,x,entityWidth]);x+=entityWidth+_this._distanceBetweenEntities}var y=0;var viewHeaderHeight=_this._viewHeaderHeight;for(var row=0;row<newViewConfigClientIds.length;row++){var currentViewConfigClientId=newViewConfigClientIds[row];newViewDimensions.push([currentViewConfigClientId,y,_this._cachedViewContentHeights[row]]);y+=viewHeaderHeight+_this._cachedViewContentHeights[row]+_this._distanceBetweenViews}for(var row=newViewDimensions.length-1;row>=0;--row){var currentViewDimensions=newViewDimensions[row];var viewHeaderView=newViewHeaderViewsByClientId[currentViewDimensions[0]];viewHeaderView.$el.css("top",currentViewDimensions[1]).attr("data-top",currentViewDimensions[1]).attr("data-total-height",currentViewDimensions[2]+_this._viewHeaderHeight);viewHeaderView.setSize(currentViewDimensions[2])}for(var col=newEntityDimensions.length-1;col>=0;--col){var currentEntityDimensions=newEntityDimensions[col];var entityHeaderView=newEntityHeaderViewsByClientId[currentEntityDimensions[0]];entityHeaderView.$el.css("left",currentEntityDimensions[1]).attr("data-left",currentEntityDimensions[1]).attr("data-width",currentEntityDimensions[2]);entityHeaderView.setSize(currentEntityDimensions[2]);for(var row=newViewDimensions.length-1;row>=0;--row){var currentViewDimensions=newViewDimensions[row];var visInstanceView=newVisInstanceViewsByClientIdPair[currentEntityDimensions[0]+currentViewDimensions[0]];visInstanceView.$el.css({left:currentEntityDimensions[1],top:currentViewDimensions[1]+viewHeaderHeight});visInstanceView.setSize(currentEntityDimensions[2],currentViewDimensions[2])}}var needToResizeSpace=false;if(x!=_this._$entityAdder.css("left")){_this._$entityAdder.css("left",x);needToResizeSpace=true}if(y!=_this._$viewAdder.css("top")){_this._$viewAdder.css("top",y);needToResizeSpace=true}if(needToResizeSpace){_this._cachedMinSpaceWidth=x+_this._entityAdderWidth;_this._cachedMinSpaceHeight=y+_this._viewAdderHeight;_this._reviseSpaceSize(!_this._latestChangeWasAReset)}}if(entityListHasChanged){_this._cachedEntityHeaderViewsByClientId=newEntityHeaderViewsByClientId;_this._cachedEntityConfigClientIds=newEntityConfigClientIds}if(viewListHasChanged){_this._cachedViewHeaderViewsByClientId=newViewHeaderViewsByClientId;_this._cachedViewConfigClientIds=newViewConfigClientIds}if(viewListHasChanged||entityListHasChanged){_this._cachedVisInstanceViewsByClientIdPair=newVisInstanceViewsByClientIdPair}if(!deep&&entityHeaderViewsToRender){for(var i=entityHeaderViewsToRender.length-1;i>=0;--i){entityHeaderViewsToRender[i].render()}}if(!deep&&viewHeaderViewsToRender){for(var i=viewHeaderViewsToRender.length-1;i>=0;--i){viewHeaderViewsToRender[i].render()}}if(!deep&&visInstanceViewsToRender){for(var i=visInstanceViewsToRender.length-1;i>=0;--i){visInstanceViewsToRender[i].render()}}if(viewListHasChanged||entityListHasChanged){var destroyedVisInstanceViews=_.difference(_.values(this._cachedVisInstanceViewsByClientIdPair),_.values(newVisInstanceViewsByClientIdPair));for(var i=destroyedVisInstanceViews.length-1;i>=0;--i){destroyedVisInstanceViews[i].remove()}}},_updateSelection:function(deep,instant){var _this=this;var selectedEntityConfig=_this.options.configGrid.getSelectedEntityConfig();var selectedViewConfig=_this.options.configGrid.getSelectedViewConfig();var selectedEntityConfigClientId=selectedEntityConfig?selectedEntityConfig.getClientId():null;var selectedViewConfigClientId=selectedViewConfig?selectedViewConfig.getClientId():null;if(_this._cachedSelectedEntityConfigClientId!==selectedEntityConfigClientId){_this._cachedSelectedEntityConfigClientId=selectedEntityConfigClientId}if(_this._cachedSelectedViewConfigClientId!==selectedViewConfigClientId){_this._cachedSelectedViewConfigClientId=selectedViewConfigClientId}},scrollAccordingToSelection:function(deep,instant){var _this=this;return;var entityConfigClientId=_this._cachedSelectedEntityConfigClientId;var viewConfigClientId=_this._cachedSelectedViewConfigClientId;var dimensions={left:0,top:0,width:0,height:0};if(entityConfigClientId){dimensions.left=parseInt(_this._cachedEntityHeaderViewsByClientId[entityConfigClientId].el.getAttribute("data-left"),10);dimensions.width=parseInt(_this._cachedEntityHeaderViewsByClientId[entityConfigClientId].el.getAttribute("data-width"),10)}if(viewConfigClientId){dimensions.top=parseInt(_this._cachedViewHeaderViewsByClientId[viewConfigClientId].el.getAttribute("data-top"),10);dimensions.height=parseInt(_this._cachedViewHeaderViewsByClientId[viewConfigClientId].el.getAttribute("data-total-height"),10)}var desiredPaddingAroundVisInstanceOnScroll=_this.options.desiredPaddingAroundVisInstanceOnScroll;var spacePadding=_this._spacePadding;var targetScrollRange={leftMax:dimensions.left-desiredPaddingAroundVisInstanceOnScroll.left,topMax:dimensions.top-desiredPaddingAroundVisInstanceOnScroll.top-_this._viewHeaderHeight,leftMin:dimensions.left+desiredPaddingAroundVisInstanceOnScroll.right+dimensions.width-_this._$containerOfScrollable[0].clientWidth+spacePadding.left,topMin:dimensions.top+desiredPaddingAroundVisInstanceOnScroll.bottom+dimensions.height-_this._$containerOfScrollable[0].clientHeight+spacePadding.top};var currentScroll={left:_this._scrollLeftBeforeLatestLayoutUpdate==null?_this._$containerOfScrollable.scrollLeft():_this._scrollLeftBeforeLatestLayoutUpdate,top:_this._scrollTopBeforeLatestLayoutUpdate==null?_this._$containerOfScrollable.scrollTop():_this._scrollTopBeforeLatestLayoutUpdate};var targetScrollLeft=currentScroll.left;var targetScrollTop=currentScroll.top;if(_this._latestChangeWasAReset){_this._cachedScrollPosSelection=null;targetScrollLeft=0;targetScrollTop=0}var currentGridHash=_this.getEntityWidth()+"~"+_this._cachedEntityConfigClientIds.join("|")+"~"+_this._cachedViewConfigClientIds.join("|");if(_this._cachedScrollPosGridHash===currentGridHash&&_this._cachedScrollPosSelection===""+entityConfigClientId+viewConfigClientId){targetScrollLeft=_this._cachedScrollPosX;targetScrollTop=_this._cachedScrollPosY;_this._cachedScrollPosSelection=""}else{if(!_this._ignoreXOnNextScroll){if(targetScrollLeft<targetScrollRange.leftMin){targetScrollLeft=targetScrollRange.leftMin}if(targetScrollLeft>targetScrollRange.leftMax){targetScrollLeft=targetScrollRange.leftMax}}if(!_this._ignoreYOnNextScroll){if(targetScrollTop<targetScrollRange.topMin){targetScrollTop=targetScrollRange.topMin}if(targetScrollTop>targetScrollRange.topMax){targetScrollTop=targetScrollRange.topMax}}if(targetScrollLeft<0){targetScrollLeft=0}if(targetScrollTop<0){targetScrollTop=0}}var scrollDiffX=targetScrollLeft-currentScroll.left;var scrollDiffY=targetScrollTop-currentScroll.top;if(!entityConfigClientId&&!viewConfigClientId&&!_this._latestChangeWasAReset){_this._updateCachedScroll()}else if(instant||_this._latestChangeWasAReset){_this._$containerOfScrollable.stop(true,true);_this._$containerOfScrollable.scrollLeft(targetScrollLeft);_this._$containerOfScrollable.scrollTop(targetScrollTop);_this._updateCachedScroll();_this._reviseSpaceSize()}else{_this._$containerOfScrollable.stop(true,false);if(_this._scrollLeftBeforeLatestLayoutUpdate!==null){_this._$containerOfScrollable.scrollLeft(_this._scrollLeftBeforeLatestLayoutUpdate);_this._$containerOfScrollable.scrollTop(_this._scrollTopBeforeLatestLayoutUpdate)}_this._$containerOfScrollable.animate({scrollLeft:targetScrollLeft,scrollTop:targetScrollTop},_this.options.scrollAnimationMinSpeed+Math.min(Math.max(Math.abs(scrollDiffX),Math.abs(scrollDiffY)),_this.options.scrollAnimationBaseDistance)/_this.options.scrollAnimationBaseDistance*_this.options.scrollAnimationBaseSpeed,function(){_this._reviseSpaceSize()})}_this._ignoreXOnNextScroll=false;_this._ignoreYOnNextScroll=false},getPositionsOfSelectedHeaders:function(){var _this=this;var result=[];var selectedEntityHeaderView=_this._cachedEntityHeaderViewsByClientId[_this._cachedSelectedEntityConfigClientId];var selectedViewHeaderView=_this._cachedViewHeaderViewsByClientId[_this._cachedSelectedViewConfigClientId];if(selectedEntityHeaderView){var $selectedEntityHeader=selectedEntityHeaderView.$el;result.push(parseInt($selectedEntityHeader.css("left"),10)-_this._$containerOfScrollable.scrollLeft(),parseInt($selectedEntityHeader[0].style.width,10))}else{result.push(null,null)}if(selectedViewHeaderView){var $selectedViewHeader=selectedViewHeaderView.$el;result.push(parseInt($selectedViewHeader.css("top"),10)-_this._$containerOfScrollable.scrollTop(),_this._viewHeaderHeight)}else{result.push(null,null)}return result},_updateCachedScroll:function(){var _this=this;_this._cachedScrollPosGridHash=_this.getEntityWidth()+"~"+_this._cachedEntityConfigClientIds.join("|")+"~"+_this._cachedViewConfigClientIds.join("|");_this._cachedScrollPosSelection=""+_this._cachedSelectedEntityConfigClientId+_this._cachedSelectedViewConfigClientId;_this._cachedScrollPosX=_this._$containerOfScrollable.scrollLeft();_this._cachedScrollPosY=_this._$containerOfScrollable.scrollTop()},_toggleFixedHeadersIfNeeded:function(trueOrFalse){var _this=this;if(_this.options.enableFixedHeaders&&trueOrFalse==true){if(!_this._$containerOfFixed[0].childNodes.length){_this._$containerOfFixed.append(_this._$visInstancesContainer,_this._$entityHeadersContainer,_this._$viewHeadersContainer,_this._$cornerBlind);_this._$cornerBlind.css({transform:"translate(0px, 0px)"});_this._$containerOfFixed.show()}}else{_this._$containerOfFixed.hide();_this._$space.append(_this._$visInstancesContainer,_this._$entityHeadersContainer,_this._$viewHeadersContainer,_this._$cornerBlind);_this._$entityHeadersBlind.css({transform:"translate(0px, 0px)"});_this._$visInstancesContainer.css({transform:"translate(0px, 0px)"})}_this._adjustToScrollPos()},_adjustToScrollPos:function(){var _this=this;if(_this._scrollLeftBeforeLatestLayoutUpdate!==null){_this._scrollLeftBeforeLatestLayoutUpdate=null;_this._scrollTopBeforeLatestLayoutUpdate=null}var scrollLeft=_this._$containerOfScrollable.scrollLeft();var scrollTop=_this._$containerOfScrollable.scrollTop();if(_this._$containerOfFixed[0].childNodes.length){_this._$entityHeadersContainer.css({transform:"translate("+-scrollLeft+"px, 0px)"});_this._$entityHeadersBlind.css({transform:"translate("+scrollLeft+"px, 0px)"});_this._$visInstancesContainer.css({transform:"translate("+-scrollLeft+"px, "+-scrollTop+"px)"});_this._$viewHeadersContainer.css({transform:"translate(0px, "+-scrollTop+"px)"})}else{_this._$entityHeadersContainer.css({transform:"translate(0, "+scrollTop+"px)"});_this._$viewHeadersContainer.css({transform:"translate("+scrollLeft+"px, 0)"});_this._$cornerBlind.css({transform:"translate("+scrollLeft+"px, "+scrollTop+"px)"})}_this._reportPositionsOfSelectedHeaders()},_reportPositionsOfSelectedHeaders:function(){var _this=this;var positionsOfSelectedHeaders=_this.getPositionsOfSelectedHeaders();_this.trigger("change-positions-of-selected-headers",positionsOfSelectedHeaders[0],positionsOfSelectedHeaders[1],positionsOfSelectedHeaders[2],positionsOfSelectedHeaders[3])},_reviseSpaceSize:function(increaseOnly){var _this=this;var elInnerWidth=_this._$containerOfScrollable[0].clientWidth;var elInnerHeight=_this._$containerOfScrollable[0].clientHeight;var elScrollLeft=_this._$containerOfScrollable.scrollLeft();var elScrollTop=_this._$containerOfScrollable.scrollTop();var spaceWidth=_this._cachedMinSpaceWidth;var spaceHeight=_this._cachedMinSpaceHeight;var missingWidth=elScrollLeft+elInnerWidth-_this._spacePadding.h-spaceWidth;var missingHeight=elScrollTop+elInnerHeight-_this._spacePadding.v-spaceHeight;spaceWidth+=Math.max(0,missingWidth);spaceHeight+=Math.max(0,missingHeight);if(!increaseOnly||spaceWidth>=_this._$space.width()&&spaceHeight>=_this._$space.height()){_this._$space.css({width:spaceWidth,height:spaceHeight});_this._$viewHeadersBlind.height(spaceHeight)}},_updateDemensionsForContainerOfFixed:function(){var _this=this;_this._$containerOfFixed.width(_this._$containerOfScrollable[0].clientWidth);_this._$containerOfFixed.height(_this._$containerOfScrollable[0].clientHeight)},_generateEntityHeaderView:function(entityConfig){var _this=this;var $el=$.bem.generateElement("config-grid-cells","entity-header");var result=new App.MainRegionModule.ConfigHeaderView({dimension:"entity",el:$el,state:_this.options.state,configGrid:_this.options.configGrid,config:entityConfig,parentConfigGridView:_this.options.parentConfigGridView});result.$el.dblclick(function(){if(entityConfig.getParameterValue("kind")){return}if(_this.options.configGrid.getSelectedEntityConfig()==entityConfig){_this.options.configGrid.addEntityAndSelectIt(new App.ContextModule.Config({parameters:{kind:"pair",comparisonMode:"superposition"}}),_this.options.configGrid.getNextEntityNeighbour(entityConfig))}});return result},_generateViewHeaderView:function(viewConfig){var _this=this;var $el=$.bem.generateElement("config-grid-cells","view-header");var result=new App.MainRegionModule.ConfigHeaderView({dimension:"view",el:$el,state:_this.options.state,configGrid:_this.options.configGrid,config:viewConfig,parentConfigGridView:_this.options.parentConfigGridView});return result},_generateVisInstanceView:function(entityConfig,viewConfig){var _this=this;var $el=$.bem.generateElement("config-grid-cells","vis-instance").addClass("vis-instance");var result=new App.MainRegionModule.VisInstanceView({el:$el,state:_this.options.state,configGrid:_this.options.configGrid,entityConfig:entityConfig,viewConfig:viewConfig,parentConfigGridView:_this.options.parentConfigGridView});return result}})},Logger); "use strict";App.module("MainRegionModule",function(MainRegionModule,App,Backbone,Marionette,$,_,Logger){MainRegionModule.ConfigGridPanelView=MainRegionModule.ConfigGridChildView.extend({options:{dimension:null,configGrid:null,parentState:null,parentConfigGridView:null},_cachedConfigGridType:null,_cachedConfig:null,_cachedBorderRadiusFixerSize:null,initialize:function(options){var _this=this;_this.options=_.defaults(options||{},this.options);_this.listenTo(_this.options.configGrid,"change_selection",_this.renderIfParentConfigGridIsVisible);_this._cachedConfigGridType=this.options.configGrid.getType();_this._$borderRadiusFixer=$.bem.generateElement("config-grid-panel","border-radius-fixer");_this._$borderRadiusFixerContainer=$.bem.generateElement("config-grid-panel","border-radius-fixer-container");_this._$borderRadiusFixerContainer.append(_this._$borderRadiusFixer);_this.$el.prepend(_this._$borderRadiusFixerContainer);_this._cachedBorderRadiusFixerSize=_this._$borderRadiusFixerContainer.width();_this.updateRadiusFixer(null,null);_this._$mainAreaWrapper=$.bem.generateElement("config-grid-panel","main-area-wrapper");_this._$mainArea=$.bem.generateElement("config-grid-panel","main-area");_this._$mainArea.addClass("cgpma");_this._$mainArea.appendTo(_this._$mainAreaWrapper);_this._$mainAreaWrapper.appendTo(_this.$el);_this._$commands=_this.$(".config-grid-panel__commands");_this._$commandClone=_this.$(".config-grid-panel__command_action_clone");_this._$commandDelete=_this.$(".config-grid-panel__command_action_delete");_this._$commandApply=_this.$(".config-grid-panel__command_action_apply");_this._$commandDiscard=_this.$(".config-grid-panel__command_action_discard");_this._$commandClone.click(function(){if(_this._cachedConfig&&_this._$commandClone.hasClass("config-grid-panel__command_state_enabled")){var clonedConfig=_this._cachedConfig.clone();if(_this.options.dimension=="entity"){_this.options.configGrid.addEntityAndSelectIt(clonedConfig,_this.options.configGrid.getNextEntityNeighbour(_this._cachedConfig))}else{_this.options.configGrid.addViewAndSelectIt(clonedConfig,_this.options.configGrid.getNextViewNeighbour(_this._cachedConfig))}}});_this._$commandDelete.click(function(){if(_this._cachedConfig&&_this._$commandDelete.hasClass("config-grid-panel__command_state_enabled")){if(_this.options.dimension=="entity"){_this.options.configGrid.removeEntityAndSelectNeighbour(_this._cachedConfig)}else{_this.options.configGrid.removeViewAndSelectNeighbour(_this._cachedConfig)}}});_this._$commandApply.click(function(){if(_this._cachedConfig&&_this._$commandApply.hasClass("config-grid-panel__command_state_enabled")){_this._masterBehindMainArea.cleanConfigPlannedParameterValuesAndApplyThem(_this._cachedConfig)}});_this._$commandDiscard.click(function(){if(_this._cachedConfig&&_this._$commandDiscard.hasClass("config-grid-panel__command_state_enabled")){_this._cachedConfig.cancelPlannedParameterUpdates()}});_this._$commandClone.attr("title"," ");_this._$commandDelete.attr("title"," ");_this._$commandApply.attr("title"," ");_this._$commandDiscard.attr("title"," ");App.TooltipModule.convertTitlesToTooltips(_this.$el);_this._updateTooltips();_this._$commands.disableSelection()},render:function(deep,instant){var _this=this;var selectedConfig=null;if(_this.options.dimension=="entity"){selectedConfig=_this.options.configGrid.getSelectedEntityConfig()}else{selectedConfig=_this.options.configGrid.getSelectedViewConfig()}var configWasReplaced=false;if(_this._cachedConfig!=selectedConfig){if(_this._cachedConfig){_this.stopListening(_this._cachedConfig,"change",_this.renderIfParentConfigGridIsVisible)}_this._cachedConfig=selectedConfig;if(_this._cachedConfig){_this.listenTo(_this._cachedConfig,"change",_this.renderIfParentConfigGridIsVisible)}configWasReplaced=true;_this._updateTooltips()}var dynamicDerivedConfigData=App.dynamicDerivedConfigDataProvider.get(_this._cachedConfig);if(_this._cachedDynamicDerivedConfigData!=dynamicDerivedConfigData){if(_this._cachedDynamicDerivedConfigData){this.stopListening(_this._cachedDynamicDerivedConfigData,"change",_this.renderIfParentConfigGridIsVisible)}_this._cachedDynamicDerivedConfigData=dynamicDerivedConfigData;if(_this._cachedDynamicDerivedConfigData){_this.listenTo(_this._cachedDynamicDerivedConfigData,"change",_this.renderIfParentConfigGridIsVisible)}}_this._setupMainArea(deep,instant);var hashForData=null;if(_this._cachedConfig){hashForData=_this._cachedConfig.getHash()+_this._cachedDynamicDerivedConfigData.getHash()}if(configWasReplaced||_this._cachedHashForData!==hashForData){_this._cachedHashForData=hashForData;if(_this._masterBehindMainArea){_this._masterBehindMainArea.syncConfigGridPanelMainArea(_this,instant)}_this._renderApplyDiscardCommands(deep,instant)}if(configWasReplaced||deep){_this._renderCloneDeleteCommands(deep,instant)}},updateRadiusFixer:function(selectedConfigGridOffsetStart,selectedConfigGridSize){var _this=this;var coordinate=selectedConfigGridOffsetStart;var size=selectedConfigGridSize;if(_.isNumber(size)&&!_.isNaN(size)&&size>0){if(coordinate+size<=0){coordinate=null}if(coordinate>_this._cachedBorderRadiusFixerSize){coordinate=null}else if(coordinate<0){coordinate=0}else if(coordinate+size>_this._cachedBorderRadiusFixerSize){size=_this._cachedBorderRadiusFixerSize-coordinate}}else{coordinate=null;size=null}if(coordinate!==null){if(_this.options.dimension=="entity"){_this._$borderRadiusFixer.css({left:coordinate,width:size})}else{_this._$borderRadiusFixer.css({top:coordinate,height:size})}}else{if(_this.options.dimension=="entity"){_this._$borderRadiusFixer.css({left:0,width:0})}else{_this._$borderRadiusFixer.css({top:0,height:0})}}},_updateTooltips:function(){var _this=this;if(!this._cachedConfig){_this._$commandClone.attr("tooltip-title","");_this._$commandDelete.attr("tooltip-title","");_this._$commandApply.attr("tooltip-title","");_this._$commandDiscard.attr("tooltip-title","")}else{var tooltipTemplate=null;try{tooltipTemplate=Marionette.TemplateCache.get("#config-grid-panel__command-titles_"+_this._cachedConfigGridType+"_"+this._cachedConfig.getDimension()+"_"+_.str.trim(this._cachedConfig.getParameterValue("kind")))}catch(e){tooltipTemplate=Marionette.TemplateCache.get("#config-grid-panel__command-titles_"+_this._cachedConfigGridType+"_"+this._cachedConfig.getDimension())}var tooltips=tooltipTemplate().split("|");_this._$commandClone.attr("tooltip-title",tooltips[0]);_this._$commandDelete.attr("tooltip-title",tooltips[1]);_this._$commandApply.attr("tooltip-title",tooltips[2]);_this._$commandDiscard.attr("tooltip-title",tooltips[3])}},_renderCloneDeleteCommands:function(deep,instant){var _this=this;var cloneEnabled=!!_this._cachedConfig;var deleteEnabled=!!_this._cachedConfig;_this._$commandClone.toggleClass("config-grid-panel__command_state_enabled",cloneEnabled);_this._$commandDelete.toggleClass("config-grid-panel__command_state_enabled",deleteEnabled)},_renderApplyDiscardCommands:function(deep,instant){var _this=this;var enabled=!!(_this._cachedConfig&&_this._cachedConfig.hasPlannedParameterUpdates());_this._$commandApply.toggleClass("config-grid-panel__command_state_enabled",enabled);_this._$commandDiscard.toggleClass("config-grid-panel__command_state_enabled",enabled)},_setupMainArea:function(deep,instant){var _this=this;var master=null;if(_this._cachedConfig){master=App.RepresentationModule.getMasterForConfig(_this._cachedConfig,true)}var configHasChanged=_this._configBehindMainArea!==_this._cachedConfig;var masterHasChanged=_this._masterBehindMainArea!==master;if(configHasChanged||masterHasChanged){if(_this._masterBehindMainArea){_this._masterBehindMainArea.destroyConfigGridPanelMainArea(this)}if(!_this._cachedConfig){_this._configBehindMainArea=null;_this._masterBehindMainArea=null;_this._$mainArea.html(Backbone.Marionette.TemplateCache.get("#cgpma_"+_this._cachedConfigGridType+"_"+this.options.dimension+"__empty"))}else{_this._configBehindMainArea=_this._cachedConfig;_this._masterBehindMainArea=master;_this._$mainArea.empty();_this._$mainArea.removeData();try{_this._$mainArea.html(Backbone.Marionette.TemplateCache.get("#cgpma_"+_this._cachedConfigGridType+"_"+this.options.dimension+"_"+master.id.split(".")[2]))}catch(e){_this._$mainArea.html(Backbone.Marionette.TemplateCache.get("#cgpma_"+_this._cachedConfigGridType+"_"+this.options.dimension+"__unknown"))}_this._masterBehindMainArea.prepareConfigGridPanelMainArea(_this)}var masterKind=undefined;if(_this._masterBehindMainArea){masterKind=_this._masterBehindMainArea.id.split(".")[2]}this.$el.setMod("config-grid-panel","master-kind",masterKind?masterKind:false)}}})},Logger); "use strict";App.module("MainRegionModule",function(MainRegionModule,App,Backbone,Marionette,$,_,Logger){MainRegionModule.ConfigHeaderView=MainRegionModule.ConfigGridChildView.extend({options:{dimension:null,parentState:null,configGrid:null,config:null,parentConfigGridView:null},_dimensionIsEntity:false,_dimensionIsView:false,initialize:function(options){var _this=this;_this.options=_.defaults(options||{},_this.options);_this._cachedConfigGridType=options.configGrid.getType();_this._cachedKind="-";_this._cachedMaster=null;_this.$el.disableSelection();_this.dynamicDerivedConfigData=null;if(_this.options.dimension==="entity"){_this._dimensionIsEntity=true}else{_this._dimensionIsView=true}_this._debouncedRenderIfParentConfigGridIsVisible=_this.renderIfParentConfigGridIsVisible;_this.listenTo(_this.options.configGrid,"change_selection",_this._debouncedRenderIfParentConfigGridIsVisible);_this.listenTo(_this.options.configGrid,"change_layout",_this._debouncedRenderIfParentConfigGridIsVisible);_this.listenTo(_this.options.config,"change:parametersOrPlannedParameterUpdates",_this._debouncedRenderIfParentConfigGridIsVisible);_this._$background=$.bem.generateElement("config-grid-cells",_this._dimensionIsEntity?"entity-header-background":"view-header-background");_this.$el.append(_this._$background);_this.$el.click(function(event){if(_this._dimensionIsEntity){_this.options.parentConfigGridView.ignoreAxisOnNextScroll(false,true)}else{_this.options.parentConfigGridView.ignoreAxisOnNextScroll(true,false)}if(_this._cachedSelected){_this.options.parentConfigGridView.scrollAccordingToSelection()}else{_this.options.configGrid.set(_this._dimensionIsEntity?"selectedEntityConfigClientId":"selectedViewConfigClientId",_this.options.config.getClientId())}event.stopPropagation();event.preventDefault()});_this._cachedSelected=false;_this._cachedHashForParameters=null},setSize:function(widthOrHeight){var _this=this;var $el=_this.$el;var changed=false;if(_this._dimensionIsEntity){if(widthOrHeight!=$el.width()){$el.width(widthOrHeight);changed=true}}else{return;if(widthOrHeight!=$el.height()){$el.height(widthOrHeight);changed=true}}if(changed){_this._debouncedRenderIfParentConfigGridIsVisible()}},render:function(deep,instant){var _this=this;if(!_this.options.config.getConfigGridType()){return}var newSelected=_this._dimensionIsEntity?_this.options.configGrid.getSelectedEntityConfig()==_this.options.config:_this.options.configGrid.getSelectedViewConfig()==_this.options.config;if(newSelected!==_this._cachedSelected){if(newSelected){_this.$el.addClass(_this._dimensionIsEntity?"config-grid-cells__entity-header_selected":"config-grid-cells__view-header_selected")}else{_this.$el.removeClass(_this._dimensionIsEntity?"config-grid-cells__entity-header_selected":"config-grid-cells__view-header_selected")}_this._cachedSelected=newSelected}var newKind=_this.options.config.getParameterValue("kind");if(newKind!==_this._cachedKind){_this._cachedKind=newKind;_this._cachedMaster=App.RepresentationModule.getMasterForConfig(_this.options.config);if(_this.dynamicDerivedConfigData){_this.stopListening(_this.dynamicDerivedConfigData)}_this.dynamicDerivedConfigData=App.dynamicDerivedConfigDataProvider.get(_this.options.config);_this.listenTo(_this.dynamicDerivedConfigData,"change",_this._debouncedRenderIfParentConfigGridIsVisible);_this.$el.setMod("config-grid-cells","entity-header","kind",newKind?newKind:false)}_this._cachedMaster.renderHeaderContent(this,instant)}})},Logger); "use strict";App.module("MainRegionModule",function(MainRegionModule,App,Backbone,Marionette,$,_,Logger){MainRegionModule.VisInstanceView=MainRegionModule.ConfigGridChildView.extend({options:{state:null,configGrid:null,entityConfig:null,viewConfig:null,parentConfigGridView:null},initialize:function(options){var _this=this;_this.options=_.defaults(options||{},_this.options);_this._configGridType=_this.options.configGrid.getType();_this.$el.attr("data-entity-id",_this.options.entityConfig.getClientId());_this.$el.attr("data-view-id",_this.options.viewConfig.getClientId());_this.$content=$.bem.generateElement("vis-instance","content");_this.$cover=$.bem.generateElement("vis-instance","cover");_this.$coverMessage=$.bem.generateElement("vis-instance","cover-message");_this.$cover.append(_this.$coverMessage);_this.$el.append(_this.$content,_this.$cover);_this._cachedEntityKind="-";_this._cachedViewKind="-";_this.dynamicDerivedConfigDataForEntity=null;_this.dynamicDerivedConfigDataForView=null;_this.dynamicDerivedVisInstanceDataForBase=null;_this.dynamicDerivedVisInstanceDataForOverlay=null;_this.dynamicDerivedVisInstanceDataForTemp=null;_this._debouncedRenderIfParentConfigGridIsVisible=_.debounce(function(){_this.renderIfParentConfigGridIsVisible()},50);_this.listenTo(_this.options.entityConfig,"change:parameters",_this._debouncedRenderIfParentConfigGridIsVisible);_this.listenTo(_this.options.viewConfig,"change:parameters",_this._debouncedRenderIfParentConfigGridIsVisible);_this.listenTo(_this.options.entityConfig,"change:tempParameters",_this._debouncedRenderIfParentConfigGridIsVisible);_this.listenTo(_this.options.viewConfig,"change:tempParameters",_this._debouncedRenderIfParentConfigGridIsVisible);_this.$el.click(function(){var entityClientId=_this.options.entityConfig.getClientId();var viewClientId=_this.options.viewConfig.getClientId();if(_this.options.configGrid.get("selectedEntityConfigClientId")!==entityClientId||_this.options.configGrid.get("selectedViewConfigClientId")!==viewClientId){_this.options.configGrid.set({selectedEntityConfigClientId:entityClientId,selectedViewConfigClientId:viewClientId})}else{_this.options.parentConfigGridView.scrollAccordingToSelection()}})},remove:function(){var _this=this;if(_this.dynamicDerivedVisInstanceDataForBase){_this.dynamicDerivedVisInstanceDataForBase.destroy()}if(_this.dynamicDerivedVisInstanceDataForOverlay){_this.dynamicDerivedVisInstanceDataForOverlay.destroy()}if(_this.dynamicDerivedVisInstanceDataForTemp){_this.dynamicDerivedVisInstanceDataForTemp.destroy()}MainRegionModule.ConfigGridChildView.prototype.remove.apply(this,arguments)},setSize:function(width,height){var _this=this;var $el=_this.$el;var changed=false;if(width!=$el.width()){$el.width(width);changed=true}if(height!=$el.height()){$el.height(height);changed=true}if(changed){_this._cachedSizeHash=width+"|"+height;_this._debouncedRenderIfParentConfigGridIsVisible()}},render:function(deep,instant){var _this=this;if(!this.options.entityConfig.getConfigGridType()||!this.options.viewConfig.getConfigGridType()){return}var newEntityKind=_.str.trim(_this.options.entityConfig.getParameterValue("kind"));var newViewKind=_.str.trim(_this.options.viewConfig.getParameterValue("kind"));var entityKindHasChanged=_this._cachedEntityKind!==newEntityKind;var viewKindHasChanged=_this._cachedViewKind!==newViewKind;if(entityKindHasChanged||viewKindHasChanged){_this._cachedEntityKind=newEntityKind;_this._cachedViewKind=newViewKind;if(_this.cachedViewMaster){_this.stopListening(_this.cachedViewMaster)}_this._cachedEntityMaster=App.RepresentationModule.getMasterForConfig(_this.options.entityConfig);_this._cachedViewMaster=App.RepresentationModule.getMasterForConfig(_this.options.viewConfig);_this.$content.empty();_this.listenTo(_this._cachedViewMaster,"change:auxiliaryResourcesStatus",_this._debouncedRenderIfParentConfigGridIsVisible)}if(entityKindHasChanged){if(_this.dynamicDerivedConfigDataForEntity){_this.stopListening(_this.dynamicDerivedConfigDataForEntity)}_this.dynamicDerivedConfigDataForEntity=App.dynamicDerivedConfigDataProvider.get(_this.options.entityConfig);_this.listenTo(_this.dynamicDerivedConfigDataForEntity,"change",_this._debouncedRenderIfParentConfigGridIsVisible)}if(viewKindHasChanged){if(_this.dynamicDerivedConfigDataForView){_this.stopListening(_this.dynamicDerivedConfigDataForView)}_this.dynamicDerivedConfigDataForView=App.dynamicDerivedConfigDataProvider.get(_this.options.viewConfig);_this.listenTo(_this.dynamicDerivedConfigDataForView,"change",_this._debouncedRenderIfParentConfigGridIsVisible)}if(entityKindHasChanged||viewKindHasChanged){var dynamicDataTypes=["Base","Overlay","Temp"];for(var i=0;i<3;i++){var propertyName="dynamicDerivedVisInstanceDataFor"+dynamicDataTypes[i];var generatorFunctionName="generateDynamicDerivedVisInstanceDataFor"+dynamicDataTypes[i];if(_this[propertyName]){_this.stopListening(_this[propertyName]);_this[propertyName].destroy()}_this[propertyName]=_this._cachedEntityMaster[generatorFunctionName](_this);_this.listenTo(_this[propertyName],"change",_this._debouncedRenderIfParentConfigGridIsVisible)}}_this._cachedViewMaster.renderVisInstance(_this,deep,instant)},cancelPointerHighlights:function(){var _this=this;if(_this._cachedViewMaster){_this._cachedViewMaster.cancelVisInstancePointerHighlights(_this)}}})},Logger); "use strict";(function($){$.widget("cgpma.textfield",{options:{value:"",baseValue:"",autocompleteMaxItemCount:15,autocompleteSort:false,autocompleteSuggestions:null,autocompleteIsAdvisory:false,autocompleteCSSClasses:""},isFocused:function(){var widget=this;return widget.$input.is(":focus")},focus:function(){var widget=this;return widget.$input.focus()},getTextRange:function(){var widget=this;return widget.$input.textrange()},setTextRange:function(textRange){var widget=this;if(textRange.start!=textRange.end){return widget.$input.textrange("set",textRange.start,textRange.end)}return widget.$input.textrange("setcursor",textRange.position)},_create:function(){var widget=this;widget.$element=this.element;widget.$input=$.bem.generateElement("input","cgpma","textfield-input");widget.$input.appendTo(widget.$element);widget.$input.data("widget",widget);widget._applyAutocompleteSuggestions();widget.$input.bind("input",widget.__handleInputChange);widget.$input.bind("keydown",widget.__handleInputKeyDown);widget.$input.bind("keyup",widget.__handleInputKeyUp);widget.$input.bind("click",widget.__handleInputClick)},_applyAutocompleteSuggestions:function(){var widget=this;if(widget.$input.data("ui-autocomplete")){widget.$input.autocomplete("destroy")}var autocompleteSuggestions=widget.options.autocompleteSuggestions;if(!autocompleteSuggestions){return;delete widget._invertedAutocompleteSuggestions}widget._invertedAutocompleteSuggestions=_.invert(autocompleteSuggestions);widget.$input.autocomplete({delay:0,minLength:0,source:$.proxy(widget,"_autocompleteSource")});widget.$input.autocomplete("widget").addClass(widget.options.autocompleteCSSClasses);widget._on(widget.$input,{autocompleteselect:widget.__handleInputChange,autocompleteopen:widget.__handleAutocompleteOpen,autocompleteclose:widget.__handleAutocompleteClose})},_autocompleteSource:function(request,response){var widget=this;var matcher=new RegExp($.ui.autocomplete.escapeRegex(_.str.trim(request.term)),"i");var responseItems=[];_.each(widget.options.autocompleteSuggestions,function(kindName,kind){if(widget.options.autocompleteAlwaysFull||!request.term||matcher.test(kindName)){responseItems.push({label:kindName,value:kindName})}});if(responseItems.length==1&&responseItems[0].label===request.term){responseItems=[]}if(responseItems.length>widget.options.autocompleteMaxItemCount){responseItems=responseItems.slice(0,widget.options.autocompleteMaxItemCount)}if(widget.options.autocompleteSort){responseItems=_.sortBy(responseItems,"label")}response(responseItems)},_createShowAllButton:function(){return;var input=this.input,wasOpen=false;$("<a>").attr("tabIndex",-1).attr("title","Show All Items").tooltip().appendTo(this.wrapper).button({icons:{primary:"ui-icon-triangle-1-s"},text:false}).removeClass("ui-corner-all").addClass("custom-combobox-toggle ui-corner-right").mousedown(function(){wasOpen=input.autocomplete("widget").is(":visible")}).click(function(){input.focus();if(wasOpen){return}input.autocomplete("search","")})},_isAutocompleteVisible:function(){var widget=this;if(widget.$input.data("ui-autocomplete")){return widget.$input.autocomplete("widget").is(":visible")}else{return false}},_destroy:function(){this.$input.removeData()},_setOption:function(key,value){var widget=this;if(!widget.options.hasOwnProperty(key)){throw"Option "+key+" does not exist"}if(value===widget.options[key]||_.isArray(value)&&_.isEqual(value,widget.options[key])){return}var prev=widget.options[key];this._super(key,value);switch(key){case"value":this._applyValue();break;case"baseValue":this._updateStatus();break;case"autocompleteSuggestions":this._applyAutocompleteSuggestions();break}widget._trigger("change"+key.toLowerCase(),null,{newValue:value,prevValue:prev})},_realValueToInputValue:function(realValue){var widget=this;var value=realValue;var valueInOptionsIsString=_.isString(value);var trimmedValueInOptions=valueInOptionsIsString?_.str.trim(value):value;var trimmedCharsOnLeft=valueInOptionsIsString?value.indexOf(trimmedValueInOptions):null;var trimmedCharsOnRight=valueInOptionsIsString?value.length-trimmedValueInOptions.length-trimmedCharsOnLeft:null;if(valueInOptionsIsString&&widget.options.autocompleteSuggestions&&widget.options.autocompleteSuggestions[trimmedValueInOptions]!==undefined){value=value.substring(0,trimmedCharsOnLeft)+widget.options.autocompleteSuggestions[trimmedValueInOptions]+value.substring(value.length-trimmedCharsOnRight)}if(valueInOptionsIsString&&value.length>=4&&value.substring(0,2)=="__"&&value.substring(value.length-2)=="__"){value=value.substring(2,value.length-2)}return value},_inputValueToRealValue:function(inputValue){var widget=this;var value=inputValue;var trimmedValueInInput=_.str.trim(value);var trimmedCharsOnLeft=value.indexOf(trimmedValueInInput);var trimmedCharsOnRight=value.length-trimmedValueInInput.length-trimmedCharsOnLeft;if(widget.options.autocompleteSuggestions&&widget.options.autocompleteSuggestions[trimmedValueInInput]&&widget.options.autocompleteSuggestions[trimmedValueInInput]!==trimmedValueInInput){value="__"+value+"__"}if(widget._invertedAutocompleteSuggestions&&widget._invertedAutocompleteSuggestions[trimmedValueInInput]!==undefined){value=value.substring(0,trimmedCharsOnLeft)+widget._invertedAutocompleteSuggestions[trimmedValueInInput]+value.substring(value.length-trimmedCharsOnRight)}return value},_applyValue:function(){var widget=this;var inputValue=widget._realValueToInputValue(widget.options.value);if(inputValue!==widget.$input.val()&&!widget._doNotUpdateInputOnValueChange){widget.$input.val(inputValue)}widget._updateStatus()},_updateStatus:function(){var widget=this;widget.$element.toggleClass("cgpma__textfield_status_modified",widget.options.baseValue!==widget.options.value)},__handleInputChange:function(){var $input=null;if(this.element){$input=this.$input}else{$input=$(this)}var widget=$input.data("widget");var valueInInput=$input.val();if(arguments[1]&&arguments[1].item){valueInInput=arguments[1].item.value}var realValue=widget._inputValueToRealValue(valueInInput);widget._setOption("value",realValue)},__handleInputKeyDown:function(event){var $this=$(this);var widget=$this.data("widget");if(event.keyCode==13){}if(event.keyCode==38||event.keyCode==40){if(widget.$input.data("ui-autocomplete")){if(!widget._isAutocompleteVisible()){widget.$input.autocomplete("search","")}else{widget._doNotUpdateInputOnValueChange=true;widget._setOption("value",widget._inputValueToRealValue(widget.$input.val()));delete widget._doNotUpdateInputOnValueChange}}}},__handleInputKeyUp:function(event){var $this=$(this);var widget=$this.data("widget");if(event.keyCode==13){if(widget._lastInputChangeWasCausedByAutocomplete){widget._lastInputChangeWasCausedByAutocomplete=false}else{widget._trigger("apply");if(widget.$input.data("ui-autocomplete")){widget.$input.autocomplete("close")}}}if(event.keyCode==27){if(!widget._isAutocompleteVisible()){widget._trigger("discard")}event.preventDefault()}},__handleAutocompleteOpen:function(event){var widget=this;widget.$element.addClass("cgpma__textfield_autocomplete-is-open")},__handleAutocompleteClose:function(event){var widget=this;widget.$element.removeClass("cgpma__textfield_autocomplete-is-open")},__handleInputClick:function(){var $this=$(this);var widget=$this.data("widget");if(widget.$input.data("ui-autocomplete")){widget.$input.autocomplete("search","")}}})})(jQuery); "use strict";(function($){$.widget("cgpma.tickbox",{options:{value:null,baseValue:null},_create:function(){var widget=this;widget.$element=this.element;widget.$element.disableSelection();widget.$tick=$.bem.generateElement("cgpma","tickbox-tick");widget.$tick.appendTo(widget.$element);widget.$element.data("widget",widget);widget.$element.bind("click",widget.__handleTickClick)},_destroy:function(){this.$element.removeData()},_setOption:function(key,value){var widget=this;if(!widget.options.hasOwnProperty(key)){throw"Option "+key+" does not exist"}if(value===widget.options[key]||_.isArray(value)&&_.isEqual(value,widget.options[key])){return}var prev=widget.options[key];widget._super(key,value);switch(key){case"value":widget._applyValue();break;case"baseValue":widget._updateStatus();break}widget._trigger("change"+key.toLowerCase(),null,{newValue:value,prevValue:prev})},_applyValue:function(){var widget=this;widget.$element.toggleClass("cgpma__tickbox_ticked",!!widget.options.value);widget._updateStatus()},_updateStatus:function(){var widget=this;widget.$element.toggleClass("cgpma__tickbox_status_modified",!!widget.options.baseValue!=!!widget.options.value)},__handleTickClick:function(){var $this=$(this);var widget=$this.data("widget");var newValue=widget.options.value?"":"1";if(newValue==""&&$this.hasClass("cgpma__tickbox_type_radio")){return}widget._setOption("value",newValue)}})})(jQuery); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.logger=Logger.get("RepresentationModule")})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.Error=Marionette.Object.extend({defaults:{type:"unknown"},knownErrorTypes:{drawing:{needToEmptyContent:true},view_default:{needToEmptyContent:true},view_unknown:{needToEmptyContent:true},"data-preparing_entity-derived":{needToEmptyContent:false},"data-preparing_base":{needToEmptyContent:false},"data-preparing_overlay":{needToEmptyContent:false},"api-error_entity-derived":{needToEmptyContent:true},"api-error_base":{needToEmptyContent:true},"api-error_overlay":{needToEmptyContent:true},"api-message_progress_base":{needToEmptyContent:true},"data-error_entity-config":{needToEmptyContent:true},"data-error_view-config":{needToEmptyContent:true},"data-error_entity-derived":{needToEmptyContent:true},"data-error_base":{needToEmptyContent:true},"data-error_overlay":{needToEmptyContent:true},collection_undefined:{needToEmptyContent:true},"collection_no-recordings":{needToEmptyContent:true},pair_incomplete:{needToEmptyContent:true},"comparison_not-supported":{needToEmptyContent:true},"comparison_wrong-type":{needToEmptyContent:true},recording_undefined:{needToEmptyContent:true},"ok-count-0":{needToEmptyContent:true},"auxiliary-resources_pending":{needToEmptyContent:false},"auxiliary-resources_fail":{needToEmptyContent:true},unknown:{needToEmptyContent:true}},initialize:function(options){this.options=_.defaults(options,this.defaults)},needToEmptyContent:function(){return this.knownErrorTypes[this.options.type].needToEmptyContent}});RepresentationModule.Error.protot})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.DynamicDerivedConfigData=App.DataModule.ModelWithHashableAttributes.extend({})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){var logger=null;RepresentationModule.addInitializer(function(){logger=Logger.get("App.RepresentationModule");RepresentationModule.DynanicDerivedConfigDataProvider=Marionette.Object.extend({initialize:function(){this._dynamicDerivedConfigDataByConfigClientId={};this._kindByConfigClientId={}},get:function(config){if(!config){return null}var configClientId=config.getClientId();var configKind=config.getParameterValue("kind");if(this._kindByConfigClientId[configClientId]!==configKind){this.retire(configClientId);this._kindByConfigClientId[configClientId]=configKind}if(!this._dynamicDerivedConfigDataByConfigClientId[configClientId]){var master=App.RepresentationModule.getMasterForConfig(config);var configGrid=this.options.configGridsByType[config.getConfigGridType()];this._dynamicDerivedConfigDataByConfigClientId[configClientId]=master.generateDynamicDerivedConfigData(config,configGrid)}return this._dynamicDerivedConfigDataByConfigClientId[configClientId]},retire:function(configClientId){var dynamicDerivedDataToRetire=this._dynamicDerivedConfigDataByConfigClientId[configClientId];if(dynamicDerivedDataToRetire){dynamicDerivedDataToRetire.destroy()}delete this._dynamicDerivedConfigDataByConfigClientId[configClientId];delete this._kindByConfigClientId[configClientId]}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.DynamicDerivedVisInstanceData=App.DataModule.ModelWithHashableAttributes.extend({})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.MasterPrototypes={};RepresentationModule.masters={};RepresentationModule.registerMaster=function(masterDefinition){var MasterPrototype;var inheritId=masterDefinition.inherit?masterDefinition.inherit:"";var id=masterDefinition.id;if(!id){throw _.str.sprintf("Master definition does not contain an id")}var masterWithThisId=null;try{masterWithThisId=RepresentationModule.getMasterById(id)}catch(e){}if(masterWithThisId){throw _.str.sprintf('Master with id "%s" already exists',id)}var prototypeOptions={};var prototypeDefaultConfigParameterValues={};if(!inheritId){MasterPrototype=Marionette.Object}else{try{MasterPrototype=RepresentationModule.getMasterPrototypeById(inheritId);var parentMaster=RepresentationModule.getMasterById(inheritId);prototypeOptions=parentMaster.options;prototypeDefaultConfigParameterValues=parentMaster.defaultConfigParameterValues}catch(e){throw _.str.sprintf('Master with id "%s" could not be inherited from master with id "%s" (it does not exist)',id,inheritId)}}var combinedOptions=masterDefinition.options?_.defaults({},masterDefinition.options,prototypeOptions):_.clone(prototypeOptions);for(var key in masterDefinition.options){if(masterDefinition.options.hasOwnProperty(key)&&masterDefinition.options[key]===undefined){delete combinedOptions[key]}}masterDefinition.options=combinedOptions;var combinedDefaultConfigParameterValues=masterDefinition.defaultConfigParameterValues?_.defaults({},masterDefinition.defaultConfigParameterValues,prototypeDefaultConfigParameterValues):_.clone(prototypeDefaultConfigParameterValues);for(var key in masterDefinition.defaultConfigParameterValues){if(masterDefinition.defaultConfigParameterValues.hasOwnProperty(key)&&masterDefinition.defaultConfigParameterValues[key]===undefined){delete combinedDefaultConfigParameterValues[key]}}masterDefinition.defaultConfigParameterValues=combinedDefaultConfigParameterValues;var Master=MasterPrototype.extend(masterDefinition);RepresentationModule.MasterPrototypes[id]=Master;RepresentationModule.masters[id]=new Master};RepresentationModule.getMasterPrototypeById=function(id){var MasterPrototype=RepresentationModule.MasterPrototypes[id];if(!MasterPrototype){throw _.str.sprintf('MasterPrototype with id "%s" not found.',id)}return MasterPrototype};RepresentationModule.getMasterById=function(id){var master=RepresentationModule.masters[id];if(!master){throw _.str.sprintf('Master with id "%s" not found.',id)}return master};RepresentationModule.getMasterForConfig=function(config,lookAtPlanned){var dimension=config.getDimension();var configGridType=config.getConfigGridType();var configKind=lookAtPlanned?config.getPlannedParameterValue("kind"):config.getParameterValue("kind");configKind=_.str.trim(configKind);if(!configKind){configKind="default"}var id=[dimension,configGridType,configKind].join(".");var master=RepresentationModule.masters[id];if(!master){try{master=RepresentationModule.getMasterById([dimension,"_unknown"].join("."))}catch(e){throw _.str.sprintf('Master for config "%s" not found (master with id "%s" does not exist).',JSON.stringify(config.serialize()),id)}}return master}})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"_",options:{},defaultConfigParameterValues:{kind:""},initialize:function(){},generateDynamicDerivedConfigData:function(config,configGrid){return new RepresentationModule.DynamicDerivedConfigData},configGridParameterHasDefaultValue:function(config,parameterName){return this.getConfigParameterValueOrDefaultValue(config,parameterName)==this.defaultConfigParameterValues[parameterName]},getConfigParameterValueOrDefaultValue:function(config,parameterName,trimResult){var value=config.getParameterValue(parameterName);if(!_.isUndefined(value)){return trimResult&&_.isString(value)?_.str.trim(value):value}else{return this.defaultConfigParameterValues[parameterName]}},getConfigPlannedParameterValueOrDefaultValue:function(config,parameterName){var value=config.getPlannedParameterValue(parameterName);if(!_.isUndefined(value)){return value}else{return this.defaultConfigParameterValues[parameterName]}},getSupportedKind:function(){if(this._cachedSupportedKind===undefined){this._cachedSupportedKind=this.id.split(".")[2]}return this._cachedSupportedKind},planConfigParameterUpdateWithRespectToValueAndDefaultValue:function(config,parameterName,parameterValue){var defaultParameterValue=this.defaultConfigParameterValues[parameterName];var currentParameterValue=config.getParameterValue(parameterName);var plannedParameterValue=parameterValue;if(currentParameterValue===undefined&&plannedParameterValue===""+defaultParameterValue){config.cancelPlannedParameterUpdate(parameterName)}else{config.planParameterUpdate(parameterName,plannedParameterValue)}},extractCleanedConfigParameterValuesFromPlannedParameterValues:function(config){var result=config.getPlannedParameterValues();for(var key in result){if(result.hasOwnProperty(key)){if(this.defaultConfigParameterValues[key]===undefined){delete result[key]}}}for(var key in this.defaultConfigParameterValues){if(this.defaultConfigParameterValues.hasOwnProperty(key)){if(!result.hasOwnProperty(key)){result[key]=""+this.defaultConfigParameterValues[key]}}}return result},cleanConfigPlannedParameterValuesAndApplyThem:function(config){var newParameterValues=this.extractCleanedConfigParameterValuesFromPlannedParameterValues(config);config.unserialize({parameters:newParameterValues,plannedParameterUpdates:{},tempParameters:{}})},parseAutocompleteSuggestions:function(rawAutocompleteSuggestions){if(!_.isString(rawAutocompleteSuggestions)||!rawAutocompleteSuggestions){return null}var rawAutocompleteAsArray=rawAutocompleteSuggestions.split(";");var result={};_.each(rawAutocompleteAsArray,function(item){var parts=item.split("|");if(parts.length==2){result[parts[0]]=parts[1]}else{result[parts[0]]=parts[0]}});return result},prepareConfigGridPanelMainArea:function(configGridPanelView){var $textfields=configGridPanelView._$mainArea.find(".cgpma__textfield");configGridPanelView._$mainArea.data("$textfields",$textfields);var master=this;$textfields.each(function(){var $textfield=$(this);if(!$textfield.data("cgpma-textfield")){$textfield.textfield({autocompleteSuggestions:master.parseAutocompleteSuggestions($textfield.data("autocomplete-suggestions")),autocompleteIsAdvisory:$textfield.data("autocomplete-is-advisory"),autocompleteSort:$textfield.data("autocomplete-sort"),autocompleteCSSClasses:"ui_config-grid-type_"+configGridPanelView._cachedConfigGridType})}else{$textfield.unbind("textfieldchangevalue");$textfield.unbind("textfieldapply");$textfield.unbind("textfielddiscard")}$textfield.data("configGridPanelView",configGridPanelView);$textfield.bind("textfieldchangevalue",master.__panelInputChangeValueHandler);$textfield.bind("textfieldapply",master.__panelInputApplyHandler);$textfield.bind("textfielddiscard",master.__panelInputDiscardHandler)});var $tickboxes=configGridPanelView._$mainArea.find(".cgpma__tickbox");configGridPanelView._$mainArea.data("$tickboxes",$tickboxes);$tickboxes.each(function(){var $tickbox=$(this);if(!$tickbox.data("cgpma-tickbox")){$tickbox.tickbox()}$tickbox.data("configGridPanelView",configGridPanelView);$tickbox.bind("tickboxchangevalue",master.__panelInputChangeValueHandler)});var $inputBlocks=configGridPanelView._$mainArea.find(".cgpma__input-block");configGridPanelView._$mainArea.data("$inputBlocks",$inputBlocks);$inputBlocks.each(function(){var $inputBlock=$(this);var inputBlockName=$inputBlock.data("name");if(!inputBlockName){var $firstElementWithParameterNameInsideInputBlock=$inputBlock.find("[data-parameter-name]").first();inputBlockName=$firstElementWithParameterNameInsideInputBlock.data("parameter-name")}configGridPanelView._$mainArea.data("$inputBlock_"+inputBlockName,$inputBlock)});var $allInputs=$tickboxes.add($textfields);configGridPanelView._$mainArea.data("$allInputs",$allInputs)},__panelInputChangeValueHandler:function(event){var $this=$(this);var parameterName=$this.data("parameter-name");if(!parameterName){return}var configGridPanelView=$this.data("configGridPanelView");var config=configGridPanelView._cachedConfig;var master=configGridPanelView._masterBehindMainArea;var value=undefined;if($this.data("cgpma-tickbox")){value=$this.tickbox("option","value")}else{value=$this.textfield("option","value")}master.planConfigParameterUpdateWithRespectToValueAndDefaultValue(config,parameterName,value)},__panelInputApplyHandler:function(){var $this=$(this);var configGridPanelView=$this.data("configGridPanelView");configGridPanelView._masterBehindMainArea.cleanConfigPlannedParameterValuesAndApplyThem(configGridPanelView._cachedConfig)},__panelInputDiscardHandler:function(){var $this=$(this);var configGridPanelView=$this.data("configGridPanelView");configGridPanelView._cachedConfig.cancelPlannedParameterUpdates()},syncConfigGridPanelMainArea:function(configGridPanelView,instant){var $inputs=configGridPanelView._$mainArea.data("$allInputs");if($inputs){var _this=this;$inputs.each(function(){var $input=$(this);var parameterName=$input.attr("data-parameter-name");if(parameterName){var widgetType="textfield";if($input.data("cgpma-tickbox")){widgetType="tickbox"}$input[widgetType]("option",{value:""+_this.getConfigPlannedParameterValueOrDefaultValue(configGridPanelView._cachedConfig,parameterName),baseValue:""+_this.getConfigParameterValueOrDefaultValue(configGridPanelView._cachedConfig,parameterName)})}})}},destroyConfigGridPanelMainArea:function(){},renderHeaderContent:function(headerView,instant){var newHashRelatedToOwnData=this._generateHeaderContentHashRelatedToOwnData(headerView);if(newHashRelatedToOwnData!==headerView._cachedContentHashRelatedToOwnData){this._doRenderHeaderContentRelatedToOwnData(headerView,instant);headerView._cachedContentHashRelatedToOwnData=newHashRelatedToOwnData}var newHash=this._generateHeaderContentHashRelatedToGridLayout(headerView);if(newHash!==headerView._cachedContentHashRelatedToGridLayout){this._doRenderHeaderContentRelatedToGridLayout(headerView,instant);headerView._cachedContentHashRelatedToGridLayout=newHash}},_renderHeaderContentRelatedToGridLayout:function(headerView,instant){},_generateHeaderContentHashRelatedToOwnData:function(headerView){return headerView.options.config.getHashForParameters()+(headerView.options.config.hasPlannedParameterUpdates()?"1":"0")+headerView.dynamicDerivedConfigData.getHash()},_generateHeaderContentHashRelatedToGridLayout:function(headerView){}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"entity._",inherit:"_",_generateCollectionConfigTitle:function(config){var rawConfigParameters=config.attributes.parameters.attributes;var labelParts=[];if(rawConfigParameters.library){if(rawConfigParameters.genre){labelParts.push(rawConfigParameters.genre)}if(rawConfigParameters.collection){if(!rawConfigParameters.place){labelParts.push("recordings")}labelParts.push(" in ‘",rawConfigParameters.collection,"’ collection")}if(rawConfigParameters.genre&&(rawConfigParameters.title||rawConfigParameters.composer)){labelParts.push(" / ")}if(rawConfigParameters.composer){labelParts.push(rawConfigParameters.composer)}if(rawConfigParameters.title&&rawConfigParameters.composer){labelParts.push(" – ")}if(rawConfigParameters.title){labelParts.push(rawConfigParameters.title)}if(rawConfigParameters.year){labelParts.push(" (",rawConfigParameters.year,")")}if(rawConfigParameters.place){labelParts.push(" from ",rawConfigParameters.place)}if(labelParts.length){labelParts.unshift(": ")}if(!RepresentationModule.getMasterById("entity._")._cachedLibraryLabelsByLibraryId){var cachedLibraryLabelsByLibraryId={};var $panelContents=$(Marionette.TemplateCache.get("#cgpma_collection_entity_default")());var $tickboxes=$panelContents.find(".cgpma__tickbox");$tickboxes.each(function(){var $tickbox=$(this);var id=$tickbox.getMod("cgpma_","id");cachedLibraryLabelsByLibraryId[id]=$tickbox.text()});RepresentationModule.getMasterById("entity._")._cachedLibraryLabelsByLibraryId=cachedLibraryLabelsByLibraryId}var libraries=rawConfigParameters.library.toLowerCase().split(";");var libraryLabels=[];for(var i=0;i<libraries.length;i++){libraryLabels.push(RepresentationModule.getMasterById("entity._")._cachedLibraryLabelsByLibraryId[_.str.trim(libraries[i])])}labelParts.unshift(libraryLabels.join(", "))}else{labelParts.push("an empty collection")}return labelParts.join("")},_doRenderHeaderContentRelatedToOwnData:function(entityHeaderView,instant){if(!entityHeaderView._$label1){entityHeaderView._$label1=$.bem.generateElement("config-grid-cells","entity-header-label").appendTo(entityHeaderView.$el);entityHeaderView._$label2=$.bem.generateElement("config-grid-cells","entity-header-label",["row2"]).appendTo(entityHeaderView.$el);entityHeaderView._$labelFader=$.bem.generateElement("config-grid-cells","entity-header-label-fader").appendTo(entityHeaderView.$el)}if(entityHeaderView.options.config.hasPlannedParameterUpdates()){entityHeaderView._$label1.html('<span class="config-grid-cells__view-header-label-part_modified">'+this._generateHeaderLabel1(entityHeaderView)+"</span>");entityHeaderView._$label2.html("being modified")}else{entityHeaderView._$label1.html(this._generateHeaderLabel1(entityHeaderView));entityHeaderView._$label2.html(this._generateHeaderLabel2(entityHeaderView))}},_generateHeaderLabel1:function(entityHeaderView){return""},_generateHeaderLabel2:function(entityHeaderView){return""},__coverTapActionThatUpdatesDynamicDerivedData:function(){var $cover=$(this);var visInstanceView=$cover.data("visInstanceView");var derivedDataToUpdate=$cover.data("attachedError").options.derivedDataToUpdate;switch(derivedDataToUpdate){case"entity":visInstanceView.dynamicDerivedConfigDataForEntity.update();break;case"view":visInstanceView.dynamicDerivedConfigDataForView.update();break;case"base":visInstanceView.dynamicDerivedVisInstanceDataForBase.update();break;case"overlay":visInstanceView.dynamicDerivedVisInstanceDataForOverlay.update();break;case"temp":visInstanceView.dynamicDerivedVisInstanceDataForTemp.update();break;default:throw _.str.sprintf("__coverTapActionThatUpdatesDynamicDerivedData cannot be called for derivedDataToUpdate = %s",derivedDataToUpdate)}},_verifyThatViewIsNotEmptyOrUnknown:function(visInstanceView){if(!visInstanceView._cachedViewMaster.options.canHaveBase){if(visInstanceView._cachedViewMaster.id=="view._unknown"){throw new RepresentationModule.Error({type:"view_unknown"})}if(visInstanceView._cachedViewMaster.inherit=="view._default"){throw new RepresentationModule.Error({type:"view_default"})}else throw"Unknown view master without base "+visInstanceView._cachedViewMaster.id}},verifyAllDataForVisInstanceBase:function(visInstanceView){},generateDynamicDerivedVisInstanceDataForBase:function(visInstanceView){return new RepresentationModule.DynamicDerivedVisInstanceData},verifyAllDataForVisInstanceOverlay:function(visInstanceView){},generateDynamicDerivedVisInstanceDataForOverlay:function(visInstanceView){if(visInstanceView._cachedViewMaster.generateDynamicDerivedVisInstanceDataForOverlay){return visInstanceView._cachedViewMaster.generateDynamicDerivedVisInstanceDataForOverlay(visInstanceView)}else{return new RepresentationModule.DynamicDerivedVisInstanceData}},verifyAllDataForVisInstanceTemp:function(visInstanceView){},generateDynamicDerivedVisInstanceDataForTemp:function(visInstanceView){return new RepresentationModule.DynamicDerivedVisInstanceData}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"entity._default",inherit:"entity._",_mapDerivedVisInstanceDataAttributesToDebugAPIQueryBoxes:function(viewMaster){if(viewMaster.options.overlayPerspectiveId){return[["top","base","apiRequestURI","apiResponse"],["bottom","overlay","apiRequestURI","apiResponse"]]}else{return[["everywhere","base","apiRequestURI","apiResponse"]]}}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"entity._pair",inherit:"entity._",defaultConfigParameterValues:{comparisonMode:"superposition"},prepareConfigGridPanelMainArea:function(configGridPanelView){var $comparisonModeTickBoxes=configGridPanelView._$mainArea.find("[data-comparison-mode]");configGridPanelView._$mainArea.data("$tickboxes_comparisonMode",$comparisonModeTickBoxes);$comparisonModeTickBoxes.each(function(){var $tickbox=$(this);var comparisonMode=$tickbox.data("comparison-mode");configGridPanelView._$mainArea.data("$tickbox_comparison-mode_"+comparisonMode,$tickbox)});RepresentationModule.getMasterById("entity._").prepareConfigGridPanelMainArea.apply(this,arguments)},__panelInputChangeValueHandler:function(event){if(event.type=="tickboxchangevalue"){var $thickbox=$(event.target);var comparisonMode=$thickbox.data("comparisonMode");if(comparisonMode){var configGridPanelView=$thickbox.data("configGridPanelView");if(!configGridPanelView._$mainArea.data("ignoreChangesInComparisonModeTickboxes")){var master=$thickbox.data("configGridPanelView")._masterBehindMainArea;master.planConfigParameterUpdateWithRespectToValueAndDefaultValue(configGridPanelView._cachedConfig,"comparisonMode",comparisonMode)}return}}RepresentationModule.getMasterById("entity._").__panelInputChangeValueHandler.apply(this,arguments)},syncConfigGridPanelMainArea:function(configGridPanelView,instant){var comparisonMode=this.getConfigParameterValueOrDefaultValue(configGridPanelView._cachedConfig,"comparisonMode").toLowerCase();var plannedComparisonMode=this.getConfigPlannedParameterValueOrDefaultValue(configGridPanelView._cachedConfig,"comparisonMode").toLowerCase();var comparisonModeHash=comparisonMode+plannedComparisonMode;if(configGridPanelView._$mainArea.data("comparisonModeHash")!=comparisonModeHash){configGridPanelView._$mainArea.data("comparisonModeHash",comparisonModeHash);configGridPanelView._$mainArea.data("ignoreChangesInComparisonModeTickboxes",true);configGridPanelView._$mainArea.data("$tickboxes_comparisonMode").each(function(){var $tickbox=$(this);var value=plannedComparisonMode==$tickbox.data("comparison-mode")?"1":"";var baseValue=comparisonMode!==plannedComparisonMode?value?"":"1":value?"1":"";$tickbox.tickbox("option",{value:value,baseValue:baseValue})});configGridPanelView._$mainArea.removeData("ignoreChangesInComparisonModeTickboxes")}RepresentationModule.getMasterById("entity._").syncConfigGridPanelMainArea.apply(this,arguments)},_mapDerivedVisInstanceDataAttributesToDebugAPIQueryBoxes:function(viewMaster){if(viewMaster.options.visInstanceSupportedComparisonModes.length){return[["left","base","apiRequestURIOnTheLeft","apiResponseOnTheLeft"],["right","base","apiRequestURIOnTheRight","apiResponseOnTheRight"]]}else{return[]}}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"entity.collection.default",inherit:"entity._default",defaultConfigParameterValues:{library:"",year:"",genre:"",composer:"",performer:"",title:"",place:"",collection:""},options:{availableLibraries:["bl","charm","ilm","mazurka"],librarySeparator:";",librarySeparatorAlternatives:/\,/g,presenceOfParameters:{title:["bl","charm","ilm","mazurka"],year:["bl","charm","mazurka"],composer:["bl","charm","mazurka"],performer:["bl","charm","mazurka"],collection:["bl"],genre:["ilm"],place:["bl"]}},extractCleanedConfigParameterValuesFromPlannedParameterValues:function(config){var result=RepresentationModule.getMasterById("entity._default").extractCleanedConfigParameterValuesFromPlannedParameterValues.apply(this,arguments);var presentParameterNames=_.keys(this._getPresentParameterNamesForLibrary(result.library));for(var parameterName in result){if(result.hasOwnProperty(parameterName)&¶meterName!=="library"){if(presentParameterNames.indexOf(parameterName)==-1){delete result[parameterName]}}}return result},_parseLibraryStringToArray:function(library){var fixedLibrary=_.str.trim(library).replace(this.options.librarySeparatorAlternatives,this.options.librarySeparator).toLowerCase();if(!fixedLibrary.length){return[]}else{return _.map(fixedLibrary.split(this.options.librarySeparator),function(v){return _.str.trim(v)})}},_parseLibraryStringToObject:function(library){var result={};var libraryAsArray=this._parseLibraryStringToArray(library);for(var i=0;i<libraryAsArray.length;i++){result[libraryAsArray[i]]=true}return result},_restoreLibraryStringFromArray:function(libraryArray){libraryArray.sort();return libraryArray.length?libraryArray.join(this.options.librarySeparator):""},_restoreLibraryStringFromObject:function(libraryObject){return this._restoreLibraryStringFromArray(_.keys(libraryObject))},_getPresentParameterNamesForLibrary:function(library){if(this._cachedPresentParameterNamesByLibrary===undefined){this._cachedPresentParameterNamesByLibrary={}}if(this._cachedPresentParameterNamesByLibrary[library]===undefined){var libraries=this._parseLibraryStringToArray(library);var result={};if(libraries.length){for(var parameterName in this.options.presenceOfParameters){var fieldPresence=this.options.presenceOfParameters[parameterName];if(_.intersection(libraries,fieldPresence).length==libraries.length){result[parameterName]=true}}}this._cachedPresentParameterNamesByLibrary[library]=result}return this._cachedPresentParameterNamesByLibrary[library]},prepareConfigGridPanelMainArea:function(configGridPanelView){configGridPanelView._$mainArea.data("$libraryLabel_yes",configGridPanelView._$mainArea.find(".cgpma__id_library-label_yes"));configGridPanelView._$mainArea.data("$libraryLabel_no",configGridPanelView._$mainArea.find(".cgpma__id_library-label_no"));for(var i=this.options.availableLibraries.length-1;i>=0;--i){var availableLibrary=this.options.availableLibraries[i];var $tickbox=configGridPanelView._$mainArea.find(".cgpma__id_"+availableLibrary);configGridPanelView._$mainArea.data("$tickbox_library_"+availableLibrary,$tickbox);$tickbox.data("libraryId",availableLibrary)}RepresentationModule.getMasterById("entity._default").prepareConfigGridPanelMainArea.apply(this,arguments)},__panelInputChangeValueHandler:function(event){if(event.type=="tickboxchangevalue"){var $thickbox=$(event.target);var libraryId=$thickbox.data("libraryId");if(libraryId){var configGridPanelView=$thickbox.data("configGridPanelView");var $mainArea=configGridPanelView._$mainArea;var master=$thickbox.data("configGridPanelView")._masterBehindMainArea;if(!$mainArea.data("ignoreChangesInLibraryTickboxes")){var plannedLibraries=[];for(var i=0;i<master.options.availableLibraries.length;i++){var library=master.options.availableLibraries[i];if($mainArea.data("$tickbox_library_"+library).tickbox("option","value")){plannedLibraries.push(library)}}master.planConfigParameterUpdateWithRespectToValueAndDefaultValue(configGridPanelView._cachedConfig,"library",plannedLibraries.join(";"))}return}}RepresentationModule.getMasterById("entity._default").__panelInputChangeValueHandler.apply(this,arguments)},syncConfigGridPanelMainArea:function(configGridPanelView,instant){var library=this.getConfigParameterValueOrDefaultValue(configGridPanelView._cachedConfig,"library").toLowerCase();var plannedLibrary=this.getConfigPlannedParameterValueOrDefaultValue(configGridPanelView._cachedConfig,"library").toLowerCase();var libraryHash=library+plannedLibrary;if(configGridPanelView._$mainArea.data("libraryCache")!=libraryHash){configGridPanelView._$mainArea.data("libraryCache",libraryHash);var plannedLibraryAsArray=this._parseLibraryStringToArray(plannedLibrary);var plannedLibraryAsObject=this._parseLibraryStringToObject(plannedLibrary);configGridPanelView._$mainArea.data("ignoreChangesInLibraryTickboxes",true);for(var i=this.options.availableLibraries.length-1;i>=0;--i){var availableLibrary=this.options.availableLibraries[i];var $tickbox=configGridPanelView._$mainArea.data("$tickbox_library_"+availableLibrary);var value=plannedLibraryAsObject[availableLibrary]!==undefined?"1":"";var baseValue=library!==plannedLibrary?value?"":"1":value?"1":"";$tickbox.tickbox("option",{value:value,baseValue:baseValue})}configGridPanelView._$mainArea.removeData("ignoreChangesInLibraryTickboxes");var presentParameterNames=_.keys(this._getPresentParameterNamesForLibrary(plannedLibrary));var absentParameterNames=_.difference(_.keys(this.options.presenceOfParameters),presentParameterNames);for(var i=0;i<presentParameterNames.length;i++){configGridPanelView._$mainArea.data("$inputBlock_"+presentParameterNames[i]).show()}for(var i=0;i<absentParameterNames.length;i++){configGridPanelView._$mainArea.data("$inputBlock_"+absentParameterNames[i]).hide()}configGridPanelView._$mainArea.data("$libraryLabel_no").toggle(plannedLibraryAsArray.length==0);configGridPanelView._$mainArea.data("$libraryLabel_yes").toggle(plannedLibraryAsArray.length!=0)}RepresentationModule.getMasterById("entity._default").syncConfigGridPanelMainArea.apply(this,arguments)},_generateHeaderLabel1:function(viewHeaderView){return this._generateCollectionConfigTitle(viewHeaderView.options.config)},_generateHeaderLabel2:function(viewHeader){var rawConfigParameters=viewHeader.options.config.attributes.parameters.attributes;var attributesOfDefinitionForCollection=viewHeader.dynamicDerivedConfigData.attributes.dynamicDefinitionForCollection.attributes;var attributesOfDefinitionForOverlayedRecording=viewHeader.dynamicDerivedConfigData.attributes.dynamicDefinitionForOverlayedRecording.attributes;var labelParts=[];var collectionSize=attributesOfDefinitionForCollection.fullSize;var sampleSize=attributesOfDefinitionForCollection.sampleSize;var overlayedRecordingURI=rawConfigParameters.recordingURI;var overlayedRecordingLabel=attributesOfDefinitionForOverlayedRecording.label;if(_.isNumber(collectionSize)){var collectionSizeAsStr=collectionSize?_.str.numberFormat(collectionSize):"no";labelParts.push(_.str.sprintf("%s recording%s",collectionSizeAsStr,collectionSize!==1?"s":""))}else if(collectionSize===null){labelParts.push("updating...")}else{if(attributesOfDefinitionForCollection.id===false){labelParts.push("an error occured")}}if(_.isNumber(sampleSize)&&sampleSize!==collectionSize){labelParts.push(" (",sampleSize," in the sample)")}if(overlayedRecordingURI){if(_.isString(overlayedRecordingLabel)){labelParts.push(", ‘",overlayedRecordingLabel,"’ selected")}else if(overlayedRecordingLabel===null){}else{}}return labelParts.join("")},__upateMethodOfDynamicDerivedConfigData:function(){if(this.attributes.dynamicDefinitionForCollection.attributes.errors){this.attributes.dynamicDefinitionForCollection.update(true)}if(this.attributes.dynamicDefinitionForOverlayedRecording.attributes.errors){this.attributes.dynamicDefinitionForOverlayedRecording.update(true)}},generateDynamicDerivedConfigData:function(config,configGrid){var dynamicDefinitionForCollection=App.dynamicDefinitionProviderForCollections.get(config);var dynamicDefinitionForOverlayedRecording=App.dynamicDefinitionProviderForRecordings.get(config);var dynamicDerivedConfigData=new RepresentationModule.DynamicDerivedConfigData({dynamicDefinitionForCollection:dynamicDefinitionForCollection,dynamicDefinitionForOverlayedRecording:dynamicDefinitionForOverlayedRecording});dynamicDerivedConfigData.listenTo(dynamicDefinitionForCollection,"change",function(){dynamicDerivedConfigData.trigger("change:dynamicDefinitionForCollection");dynamicDerivedConfigData.trigger("change")});dynamicDerivedConfigData.listenTo(dynamicDefinitionForOverlayedRecording,"change",function(){dynamicDerivedConfigData.trigger("change:dynamicDefinitionForOverlayedRecording");dynamicDerivedConfigData.trigger("change")});dynamicDerivedConfigData.update=this.__upateMethodOfDynamicDerivedConfigData;return dynamicDerivedConfigData},__optionsOfDynamicDerivedVisInstanceDataForBase:{attributesToExcludeFromHash:["apiResponse"],customHashSuffixGenerator:function(attributes){if(attributes.apiResponse){return JSON.stringify(attributes.apiResponse.errors)}else{return typeof attributes.apiResponse}}},__upateMethodOfDynamicDerivedVisInstanceDataForBase:function(force){var visInstanceView=this.options.visInstanceView;var dynamicDefinitionForCollection=visInstanceView.dynamicDerivedConfigDataForEntity.attributes.dynamicDefinitionForCollection;if(!dynamicDefinitionForCollection){return}var collectionId=dynamicDefinitionForCollection.attributes.id;var requestParams=_.clone(visInstanceView.dynamicDerivedConfigDataForView.attributes.basePerspectiveRequestParams);if(!requestParams||!collectionId){this.set({apiRequestURI:undefined,apiRequestParamsHash:undefined,apiResponse:undefined});return}requestParams.cid=collectionId;var apiRequestParamsHash=JSON.stringify(requestParams);if(!force&&apiRequestParamsHash==this.attributes.apiRequestParamsHash){return}var _this=this;var apiRequestURI=App.DataModule.CliopatriaAPI.request("getCollectionPerspective",requestParams,function(data){if(JSON.stringify(requestParams)!=_this.attributes.apiRequestParamsHash){return}_this.set({apiRequestParamsHash:undefined,apiResponse:data})});this.set({apiRequestURI:apiRequestURI,apiRequestParamsHash:apiRequestParamsHash,apiResponse:null})},generateDynamicDerivedVisInstanceDataForBase:function(visInstanceView){var optionsForThisDynamicDerivedVisInstanceDataForBase=_.clone(this.__optionsOfDynamicDerivedVisInstanceDataForBase);optionsForThisDynamicDerivedVisInstanceDataForBase.visInstanceView=visInstanceView;var dynamicDerivedVisInstanceDataForBase=new RepresentationModule.DynamicDerivedVisInstanceData({apiRequestURI:undefined,apiRequestParamsHash:undefined,apiResponse:undefined},optionsForThisDynamicDerivedVisInstanceDataForBase);dynamicDerivedVisInstanceDataForBase.update=this.__upateMethodOfDynamicDerivedVisInstanceDataForBase;dynamicDerivedVisInstanceDataForBase.listenTo(visInstanceView.dynamicDerivedConfigDataForEntity,"change:dynamicDefinitionForCollection",dynamicDerivedVisInstanceDataForBase.update);dynamicDerivedVisInstanceDataForBase.listenTo(visInstanceView.dynamicDerivedConfigDataForView,"change:basePerspectiveRequestParams",dynamicDerivedVisInstanceDataForBase.update);dynamicDerivedVisInstanceDataForBase.update();return dynamicDerivedVisInstanceDataForBase},verifyAllDataForVisInstanceBase:function(visInstanceView){this._verifyThatViewIsNotEmptyOrUnknown(visInstanceView);var attributesOfDerivedConfigDataForEntity=visInstanceView.dynamicDerivedConfigDataForEntity.attributes;var dynamicDefinitionForCollection=attributesOfDerivedConfigDataForEntity.dynamicDefinitionForCollection;var attributesOfCollection=dynamicDefinitionForCollection?dynamicDefinitionForCollection.attributes:{};if(attributesOfCollection.id===null){throw new RepresentationModule.Error({type:"data-preparing_entity-derived"})}if(attributesOfCollection.id===false){throw new RepresentationModule.Error({type:"api-error_entity-derived",apiErrors:attributesOfCollection.errors,coverTapAction:this.__coverTapActionThatUpdatesDynamicDerivedData,derivedDataToUpdate:"entity"})}if(attributesOfCollection.id===""){throw new RepresentationModule.Error({type:"collection_no-recordings"})}if(attributesOfCollection.id===undefined){throw new RepresentationModule.Error({type:"collection_undefined"})}var attribytesOfDerivedVisInstanceDataForBase=visInstanceView.dynamicDerivedVisInstanceDataForBase.attributes;if(!attribytesOfDerivedVisInstanceDataForBase.apiResponse){throw new RepresentationModule.Error({type:"data-preparing_base"})}if(attribytesOfDerivedVisInstanceDataForBase.apiResponse.errors){if(attribytesOfDerivedVisInstanceDataForBase.apiResponse.errors&&attribytesOfDerivedVisInstanceDataForBase.apiResponse.errors[0]){var error0=attribytesOfDerivedVisInstanceDataForBase.apiResponse.errors[0];if(error0.code==11||error0.code==12||error0.code==13){var checkEvery=2e3;var checkEveryRandomComponent=500;if(visInstanceView.autoRefreshTimeout){clearTimeout(visInstanceView.autoRefreshTimeout)}visInstanceView.autoRefreshTimeout=setTimeout(function(){if(visInstanceView.dynamicDerivedVisInstanceDataForBase.attributes.apiResponse.errors){var error0=attribytesOfDerivedVisInstanceDataForBase.apiResponse.errors[0];if(error0.code==11||error0.code==12||error0.code==13){visInstanceView.dynamicDerivedVisInstanceDataForBase.update()}}},checkEvery+Math.round(Math.random()*checkEveryRandomComponent));throw new RepresentationModule.Error({type:"api-message_progress_base",apiErrors:attribytesOfDerivedVisInstanceDataForBase.apiResponse.errors,coverTapAction:this.__coverTapActionThatUpdatesDynamicDerivedData,derivedDataToUpdate:"base"})}else if(error0.code==20){throw new RepresentationModule.Error({type:"ok-count-0",apiErrors:attribytesOfDerivedVisInstanceDataForBase.apiResponse.errors})}}throw new RepresentationModule.Error({type:"api-error_base",apiErrors:attribytesOfDerivedVisInstanceDataForBase.apiResponse.errors,coverTapAction:this.__coverTapActionThatUpdatesDynamicDerivedData,derivedDataToUpdate:"base"})}}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"entity.collection.pair",inherit:"entity._pair",_generateHeaderLabel1:function(entityHeaderView){return _.str.sprintf("collection comparison (%s)",this.getConfigParameterValueOrDefaultValue(entityHeaderView.options.config,"comparisonMode"))},_generateHeaderLabel2:function(viewHeader){var configOnTheLeft=viewHeader.dynamicDerivedConfigData.attributes.collectionConfigOnTheLeft;var configOnTheRight=viewHeader.dynamicDerivedConfigData.attributes.collectionConfigOnTheRight;var labelParts=[];if(configOnTheLeft){labelParts.push(this._generateCollectionConfigTitle(configOnTheLeft))}else{labelParts.push("×")}labelParts.push(" ↔ ");if(configOnTheRight){labelParts.push(this._generateCollectionConfigTitle(configOnTheRight))}else{labelParts.push("×")}return labelParts.join("")},__optionsOfDynamicDerivedConfigData:{attributesToExcludeFromHash:["collectionConfigOnTheLeft","collectionConfigOnTheRight"],customHashSuffixGenerator:function(attributes){return(attributes.collectionConfigOnTheLeft?attributes.collectionConfigOnTheLeft.getClientId():"x")+(attributes.collectionConfigOnTheRight?attributes.collectionConfigOnTheRight.getClientId():"x")}},__updateMethodOfDynamicDerivedConfigData:function(force){this._doUpdate(force);if(this.attributes.collectionConfigOnTheLeft&&this.attributes.dynamicDefinitionForCollectionOnTheLeft){return}if(this.attributes.collectionConfigOnTheRight&&this.attributes.dynamicDefinitionForCollectionOnTheRight){return}var _this=this;var interval=setInterval(function(){_this._doUpdate(force);if(_this.attributes.collectionConfigOnTheLeft&&!_this.attributes.dynamicDefinitionForCollectionOnTheLeft){return}if(_this.attributes.collectionConfigOnTheRight&&!_this.attributes.dynamicDefinitionForCollectionOnTheRight){return}clearInterval(interval)},50)},__doUpdateMethodOfDynamicDerivedConfigData:function(force){var entityConfig=this.options.entityConfig;var configGrid=this.options.configGrid;if(!entityConfig.getDimension()){return}var newCollectionConfigOnTheLeft=entityConfig;var newCollectionConfigOnTheRight=entityConfig;do{newCollectionConfigOnTheLeft=configGrid.getPrevEntityNeighbour(newCollectionConfigOnTheLeft)}while(newCollectionConfigOnTheLeft&&newCollectionConfigOnTheLeft.getParameterValue("kind")=="pair");do{newCollectionConfigOnTheRight=configGrid.getNextEntityNeighbour(newCollectionConfigOnTheRight)}while(newCollectionConfigOnTheRight&&newCollectionConfigOnTheRight.getParameterValue("kind")=="pair");var newDynamicDerivedConfigDataOnTheLeft=App.dynamicDerivedConfigDataProvider.get(newCollectionConfigOnTheLeft);var newDynamicDerivedConfigDataOnTheRight=App.dynamicDerivedConfigDataProvider.get(newCollectionConfigOnTheRight);var newDynamicDefinitionForCollectionOnTheLeft=newDynamicDerivedConfigDataOnTheLeft?newDynamicDerivedConfigDataOnTheLeft.attributes.dynamicDefinitionForCollection:null;var newDynamicDefinitionForCollectionOnTheRight=newDynamicDerivedConfigDataOnTheRight?newDynamicDerivedConfigDataOnTheRight.attributes.dynamicDefinitionForCollection:null;var attributesToSet={};var arrayOfShortcuts=[[newCollectionConfigOnTheLeft,"collectionConfigOnTheLeft","change:parameters",this.triggerChange],[newCollectionConfigOnTheRight,"collectionConfigOnTheRight","change:parameters",this.triggerChange],[newDynamicDefinitionForCollectionOnTheLeft,"dynamicDefinitionForCollectionOnTheLeft","change",this.triggerChange],[newDynamicDefinitionForCollectionOnTheRight,"dynamicDefinitionForCollectionOnTheRight","change",this.triggerChange]];for(var i=arrayOfShortcuts.length-1;i>=0;--i){var shortcuts=arrayOfShortcuts[i];var oldAttributeValue=this.attributes[shortcuts[1]];var newAttributeValue=shortcuts[0];if(newAttributeValue!=oldAttributeValue){attributesToSet[shortcuts[1]]=newAttributeValue;if(oldAttributeValue){this.stopListening(oldAttributeValue,shortcuts[2])}if(newAttributeValue){this.listenTo(newAttributeValue,shortcuts[2],shortcuts[3])}}}this.set(attributesToSet)},__triggerChangeMethodOfDynamicDerivedConfigData:function(){this.dropCachedHash();this.trigger("change")},generateDynamicDerivedConfigData:function(entityConfig,configGrid){var optionsOfThisDynamicDerivedConfigData=_.clone(this.__optionsOfDynamicDerivedConfigData);optionsOfThisDynamicDerivedConfigData.entityConfig=entityConfig;optionsOfThisDynamicDerivedConfigData.configGrid=configGrid;var dynamicDerivedConfigData=new RepresentationModule.DynamicDerivedConfigData({collectionConfigOnTheLeft:null,collectionConfigOnTheRight:null,dynamicDefinitionForCollectionOnTheLeft:null,dynamicDefinitionForCollectionOnTheRight:null},optionsOfThisDynamicDerivedConfigData);dynamicDerivedConfigData.update=this.__updateMethodOfDynamicDerivedConfigData;dynamicDerivedConfigData._doUpdate=this.__doUpdateMethodOfDynamicDerivedConfigData;dynamicDerivedConfigData.triggerChange=this.__triggerChangeMethodOfDynamicDerivedConfigData;dynamicDerivedConfigData.listenTo(configGrid,"change_layout",dynamicDerivedConfigData.update);dynamicDerivedConfigData.update();return dynamicDerivedConfigData},__optionsOfDynamicDerivedVisInstanceDataForBase:{attributesToExcludeFromHash:["apiResponseOnTheLeft","apiResponseOnTheRight"],customHashSuffixGenerator:function(attributes){if(attributes.apiResponseOnTheLeft){return JSON.stringify(attributes.apiResponseOnTheLeft.errors)}else{return typeof attributes.apiResponseOnTheLeft}if(attributes.apiResponseOnTheRight){return JSON.stringify(attributes.apiResponseOnTheRight.errors)}else{return typeof attributes.apiResponseOnTheRight}}},__upateMethodOfDynamicDerivedVisInstanceDataForBase:function(force){var visInstanceView=this.options.visInstanceView;var _this=this;_.each(["Right","Left"],function(side){var dynamicDefinitionForCollection=visInstanceView.dynamicDerivedConfigDataForEntity.attributes["dynamicDefinitionForCollectionOnThe"+side];if(!dynamicDefinitionForCollection){return}var collectionId=dynamicDefinitionForCollection.attributes.id;var requestParams=_.clone(visInstanceView.dynamicDerivedConfigDataForView.attributes.basePerspectiveRequestParams);if(!requestParams||!collectionId){var attrs={};attrs["apiRequestURIOnThe"+side]=undefined;attrs["apiRequestParamsHashOnThe"+side]=undefined;attrs["apiResponseOnThe"+side]=undefined;_this.set(attrs);return}requestParams.cid=collectionId;var apiRequestParamsHash=JSON.stringify(requestParams);if(!force&&apiRequestParamsHash==_this.attributes["apiRequestParamsHashOnThe"+side]){return}var apiRequestURI=App.DataModule.CliopatriaAPI.request("getCollectionPerspective",requestParams,function(data){if(JSON.stringify(requestParams)!=_this.attributes["apiRequestParamsHashOnThe"+side]){return}var attrs={};attrs["apiRequestParamsHashOnThe"+side]=undefined;attrs["apiResponseOnThe"+side]=data;_this.set(attrs)});var attrs={};attrs["apiRequestURIOnThe"+side]=apiRequestURI;attrs["apiRequestParamsHashOnThe"+side]=apiRequestParamsHash;attrs["apiResponseOnThe"+side]=null;_this.set(attrs)})},generateDynamicDerivedVisInstanceDataForBase:function(visInstanceView){var viewMaster=visInstanceView._cachedViewMaster;if(!viewMaster.options.visInstanceSupportedComparisonModes.length){return new RepresentationModule.DynamicDerivedVisInstanceData({})}var optionsForThisDynamicDerivedVisInstanceDataForBase=_.clone(this.__optionsOfDynamicDerivedVisInstanceDataForBase);optionsForThisDynamicDerivedVisInstanceDataForBase.visInstanceView=visInstanceView;var dynamicDerivedVisInstanceDataForBase=new RepresentationModule.DynamicDerivedVisInstanceData({apiRequestURIOnTheLeft:undefined,apiRequestParamsHashOnTheLeft:undefined,apiResponseOnTheLeft:undefined,apiRequestURIOnTheRight:undefined,apiRequestParamsHashOnTheRight:undefined,apiResponseOnTheRight:undefined},optionsForThisDynamicDerivedVisInstanceDataForBase);dynamicDerivedVisInstanceDataForBase.update=this.__upateMethodOfDynamicDerivedVisInstanceDataForBase;dynamicDerivedVisInstanceDataForBase.listenTo(visInstanceView.dynamicDerivedConfigDataForEntity,"change",dynamicDerivedVisInstanceDataForBase.update);dynamicDerivedVisInstanceDataForBase.listenTo(visInstanceView.dynamicDerivedConfigDataForView,"change:basePerspectiveRequestParams",dynamicDerivedVisInstanceDataForBase.update);dynamicDerivedVisInstanceDataForBase.update();return dynamicDerivedVisInstanceDataForBase},verifyAllDataForVisInstanceBase:function(visInstanceView){this._verifyThatViewIsNotEmptyOrUnknown(visInstanceView);var viewMaster=visInstanceView._cachedViewMaster;if(!viewMaster.options.canHaveBase){return}var supportedComparisonModes=viewMaster.options.visInstanceSupportedComparisonModes;if(!supportedComparisonModes.length){throw new RepresentationModule.Error({type:"comparison_not-supported"})}if(!_.contains(supportedComparisonModes,viewMaster._getVisInstanceViewComparisonMode(visInstanceView))){throw new RepresentationModule.Error({type:"comparison_wrong-type",supportedTypes:supportedComparisonModes})}var attributesOfDerivedConfigDataForEntityOnTheLeft=visInstanceView.dynamicDerivedConfigDataForEntity.attributes;var attributesOfDerivedConfigDataForEntityOnTheRight=visInstanceView.dynamicDerivedConfigDataForEntity.attributes;var dynamicDefinitionForCollectionOnTheLeft=attributesOfDerivedConfigDataForEntityOnTheLeft.dynamicDefinitionForCollectionOnTheLeft;var dynamicDefinitionForCollectionOnTheRight=attributesOfDerivedConfigDataForEntityOnTheRight.dynamicDefinitionForCollectionOnTheRight;var attributesOfCollectionOnTheLeft=dynamicDefinitionForCollectionOnTheLeft?dynamicDefinitionForCollectionOnTheLeft.attributes:{};var attributesOfCollectionOnTheRight=dynamicDefinitionForCollectionOnTheRight?dynamicDefinitionForCollectionOnTheRight.attributes:{};if(attributesOfCollectionOnTheLeft.id===null||attributesOfCollectionOnTheRight.id===null){throw new RepresentationModule.Error({type:"data-preparing_entity-derived"})}if(attributesOfCollectionOnTheLeft.id===false||attributesOfCollectionOnTheRight.id===false){var apiErrorsOnTheLeft=attributesOfCollectionOnTheLeft.errors||[];var apiErrorsOnTheRight=attributesOfCollectionOnTheRight.errors||[];apiErrors=apiErrorsOnTheLeft.concat(apiErrorsOnTheRight);throw new RepresentationModule.Error({type:"api-error_entity-derived",apiErrors:apiErrors,coverTapAction:this.__coverTapActionThatUpdatesDynamicDerivedData,derivedDataToUpdate:"entity"})}if(attributesOfCollectionOnTheLeft.id===""||attributesOfCollectionOnTheLeft.hasOwnProperty("id")&&attributesOfCollectionOnTheLeft.id===undefined||(attributesOfCollectionOnTheRight.id===""||attributesOfCollectionOnTheRight.hasOwnProperty("id")&&attributesOfCollectionOnTheRight.id===undefined)){throw new RepresentationModule.Error({type:"collection_no-recordings"})}if(attributesOfCollectionOnTheLeft.id===undefined||attributesOfCollectionOnTheRight.id===undefined){throw new RepresentationModule.Error({type:"pair_incomplete"})}var attribytesOfDerivedVisInstanceDataForBase=visInstanceView.dynamicDerivedVisInstanceDataForBase.attributes;if(!attribytesOfDerivedVisInstanceDataForBase.apiResponseOnTheLeft||!attribytesOfDerivedVisInstanceDataForBase.apiResponseOnTheRight){throw new RepresentationModule.Error({type:"data-preparing_base"})}if(attribytesOfDerivedVisInstanceDataForBase.apiResponseOnTheLeft.errors||attribytesOfDerivedVisInstanceDataForBase.apiResponseOnTheRight.errors){var apiErrorsOnTheLeft=attribytesOfDerivedVisInstanceDataForBase.apiResponseOnTheLeft.errors||[];var apiErrorsOnTheRight=attribytesOfDerivedVisInstanceDataForBase.apiResponseOnTheRight.errors||[];var apiErrors=apiErrorsOnTheLeft.concat(apiErrorsOnTheRight);if(apiErrors[0]){var error0=apiErrors[0];if((error0.code==11||error0.code==12)&&!apiErrors[1]||apiErrors[1]&&(apiErrors[1].code==11||apiErrors[1].code==12)){throw new RepresentationModule.Error({type:"api-message_progress_base",apiErrors:apiErrors,coverTapAction:this.__coverTapActionThatUpdatesDynamicDerivedData,derivedDataToUpdate:"base"})}else if(error0.code==20&&!apiErrors[1]||apiErrors[1]&&apiErrors[1].code==20){return}}throw new RepresentationModule.Error({type:"api-error_base",apiErrors:apiErrors,coverTapAction:this.__coverTapActionThatUpdatesDynamicDerivedData,derivedDataToUpdate:"base"})}}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"entity.recording.default",inherit:"entity._default",__domEventHandlerToPlayAudio:function(){var $this=$(this);App.play($this.data("uri"))},prepareConfigGridPanelMainArea:function(configGridPanelView){var $audioLink=configGridPanelView._$mainArea.find(".cgpma__pseudo-link_action_audio");configGridPanelView._$mainArea.data("$audioLink",$audioLink);$audioLink.click(this.__domEventHandlerToPlayAudio);var $affiliationAudio=configGridPanelView._$mainArea.find(".cgpma__element_affiliation_audio");var $affiliationNoAudio=configGridPanelView._$mainArea.find(".cgpma__element_affiliation_no-audio");configGridPanelView._$mainArea.data("$affiliationAudio",$affiliationAudio);configGridPanelView._$mainArea.data("$affiliationNoAudio",$affiliationNoAudio)},syncConfigGridPanelMainArea:function(configGridPanelView,instant){var recordingAttributes=configGridPanelView._cachedDynamicDerivedConfigData.attributes.dynamicDefinitionForRecording.attributes;if(!recordingAttributes.label){configGridPanelView._$mainArea.data("$affiliationAudio").hide();configGridPanelView._$mainArea.data("$affiliationNoAudio").hide()}else{if(recordingAttributes.audio){configGridPanelView._$mainArea.data("$affiliationAudio").show();configGridPanelView._$mainArea.data("$affiliationNoAudio").hide();configGridPanelView._$mainArea.data("$audioLink").data("uri",configGridPanelView._cachedConfig.getParameterValue("recordingURI"))}else{configGridPanelView._$mainArea.data("$affiliationAudio").hide();configGridPanelView._$mainArea.data("$affiliationNoAudio").show()}}},_generateHeaderLabel1:function(viewHeader){var rawConfigParameters=viewHeader.options.config.attributes.parameters.attributes;var attributesOfDefinitionForOverlayedRecording=viewHeader.dynamicDerivedConfigData.attributes.dynamicDefinitionForRecording.attributes;var labelParts=[];var recordingURI=rawConfigParameters.recordingURI;if(recordingURI){var label=attributesOfDefinitionForOverlayedRecording.label;if(_.isString(label)){labelParts.push(label)}else if(label===null){labelParts.push("updating label...")}else{labelParts.push("could not get recording label")}}else{labelParts.push("no recording selected")}return labelParts.join("")},_generateHeaderLabel2:function(viewHeader){var attributesOfDefinitionForOverlayedRecording=viewHeader.dynamicDerivedConfigData.attributes.dynamicDefinitionForRecording.attributes;var labelParts=[];if(attributesOfDefinitionForOverlayedRecording.composer&&attributesOfDefinitionForOverlayedRecording.composer.length){labelParts.push("composed by ",attributesOfDefinitionForOverlayedRecording.composer[0])}return labelParts.join("")},__upateMethodOfDynamicDerivedConfigData:function(){if(this.attributes.dynamicDefinitionForRecording.attributes.errors){this.attributes.dynamicDefinitionForRecording.update(true)}},generateDynamicDerivedConfigData:function(config,configGrid){var dynamicDefinitionForRecording=App.dynamicDefinitionProviderForRecordings.get(config);var dynamicDerivedConfigData=new RepresentationModule.DynamicDerivedConfigData({dynamicDefinitionForRecording:dynamicDefinitionForRecording});dynamicDerivedConfigData.listenTo(dynamicDefinitionForRecording,"change",function(){dynamicDerivedConfigData.trigger("change:dynamicDefinitionForRecording");dynamicDerivedConfigData.trigger("change")});dynamicDerivedConfigData.update=this.__upateMethodOfDynamicDerivedConfigData;return dynamicDerivedConfigData},__optionsOfDynamicDerivedVisInstanceDataForBase:{attributesToExcludeFromHash:["apiResponse"],customHashSuffixGenerator:function(attributes){if(attributes.apiResponse){return JSON.stringify(attributes.apiResponse.errors)}else{return typeof attributes.apiResponse}}},__upateMethodOfDynamicDerivedVisInstanceDataForBase:function(force){var visInstanceView=this.options.visInstanceView;var dynamicDefinitionForRecording=visInstanceView.dynamicDerivedConfigDataForEntity.attributes.dynamicDefinitionForRecording;var entityConfig=visInstanceView.options.entityConfig;if(!dynamicDefinitionForRecording){return}if(this.attributes.apiResponse!==null){var recordingLabel=dynamicDefinitionForRecording.attributes.label;if(recordingLabel===undefined){this.set({apiRequestURI:undefined,apiRequestParamsHash:undefined,apiResponse:undefined});return}var requestParams=_.clone(visInstanceView.dynamicDerivedConfigDataForView.attributes.basePerspectiveRequestParams);if(!requestParams){return}requestParams.uri=entityConfig.attributes.parameters.attributes.recordingURI;var apiRequestParamsHash=JSON.stringify(requestParams);if(!force&&apiRequestParamsHash==this.attributes.apiRequestParamsHash){return}var _this=this;var apiRequestURI=App.DataModule.CliopatriaAPI.request("getRecordingPerspective",requestParams,function(data){if(JSON.stringify(requestParams)!=_this.attributes.apiRequestParamsHash){return}_this.set({apiRequestParamsHash:undefined,apiResponse:data})});this.set({apiRequestURI:apiRequestURI,apiRequestParamsHash:apiRequestParamsHash,apiResponse:null})}},generateDynamicDerivedVisInstanceDataForBase:function(visInstanceView){var optionsOfThisDynamicDerivedVisInstanceDataForBase=_.clone(this.__optionsOfDynamicDerivedVisInstanceDataForBase);optionsOfThisDynamicDerivedVisInstanceDataForBase.visInstanceView=visInstanceView;var dynamicDerivedVisInstanceDataForBase=new RepresentationModule.DynamicDerivedVisInstanceData({apiRequestURI:undefined,apiRequestParamsHash:undefined,apiResponse:undefined},optionsOfThisDynamicDerivedVisInstanceDataForBase);dynamicDerivedVisInstanceDataForBase.update=this.__upateMethodOfDynamicDerivedVisInstanceDataForBase;dynamicDerivedVisInstanceDataForBase.listenTo(visInstanceView.dynamicDerivedConfigDataForEntity,"change:dynamicDefinitionForRecording",dynamicDerivedVisInstanceDataForBase.update);dynamicDerivedVisInstanceDataForBase.listenTo(visInstanceView.dynamicDerivedConfigDataForView,"change:basePerspectiveRequestParams",dynamicDerivedVisInstanceDataForBase.update);dynamicDerivedVisInstanceDataForBase.update();return dynamicDerivedVisInstanceDataForBase},verifyAllDataForVisInstanceBase:function(visInstanceView){this._verifyThatViewIsNotEmptyOrUnknown(visInstanceView);var attributesOfDerivedConfigDataForEntity=visInstanceView.dynamicDerivedConfigDataForEntity.attributes;var dynamicDefinitionForRecording=attributesOfDerivedConfigDataForEntity.dynamicDefinitionForRecording;var attributesOfRecording=dynamicDefinitionForRecording?dynamicDefinitionForRecording.attributes:{};var attributesOfEntityConfig=visInstanceView.options.entityConfig.attributes.parameters.attributes;if(!attributesOfEntityConfig.recordingURI){throw new RepresentationModule.Error({type:"recording_undefined"})}if(attributesOfRecording.label===undefined){throw new RepresentationModule.Error({type:"api-error_entity-derived",apiErrors:attributesOfRecording.errors,coverTapAction:this.__coverTapActionThatUpdatesDynamicDerivedData,derivedDataToUpdate:"entity"})}var attribytesOfDerivedVisInstanceDataForBase=visInstanceView.dynamicDerivedVisInstanceDataForBase.attributes;if(!attribytesOfDerivedVisInstanceDataForBase.apiResponse){throw new RepresentationModule.Error({type:"data-preparing_base"})}if(attribytesOfDerivedVisInstanceDataForBase.apiResponse.errors){throw new RepresentationModule.Error({type:"api-error_base",apiErrors:attribytesOfDerivedVisInstanceDataForBase.apiResponse.errors,coverTapAction:this.__coverTapActionThatUpdatesDynamicDerivedData,derivedDataToUpdate:"base"})}}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"entity.recording.pair",inherit:"entity._pair",_generateHeaderLabel1:function(entityHeaderView){return _.str.sprintf("recording comparison (%s)",this.getConfigParameterValueOrDefaultValue(entityHeaderView.options.config,"comparisonMode"))},_generateHeaderLabel2:function(viewHeader){return""},__optionsOfDynamicDerivedConfigData:{attributesToExcludeFromHash:["recordingConfigOnTheLeft","recordingConfigOnTheRight"],customHashSuffixGenerator:function(attributes){return(attributes.recordingConfigOnTheLeft?attributes.recordingConfigOnTheLeft.getClientId():"x")+(attributes.recordingConfigOnTheRight?attributes.recordingConfigOnTheRight.getClientId():"x")}},__updateMethodOfDynamicDerivedConfigData:function(force){this._doUpdate(force);if(this.attributes.recordingConfigOnTheLeft&&this.attributes.dynamicDefinitionForRecordingOnTheLeft){return}if(this.attributes.recordingConfigOnTheRight&&this.attributes.dynamicDefinitionForRecordingOnTheRight){return}var _this=this;var interval=setInterval(function(){_this._doUpdate(force);if(_this.attributes.recordingConfigOnTheLeft&&!_this.attributes.dynamicDefinitionForRecordingOnTheLeft){return}if(_this.attributes.recordingConfigOnTheRight&&!_this.attributes.dynamicDefinitionForRecordingOnTheRight){return}clearInterval(interval)},50)},__doUpdateMethodOfDynamicDerivedConfigData:function(force){var entityConfig=this.options.entityConfig;var configGrid=this.options.configGrid;if(!entityConfig.getDimension()){return}var newRecordingConfigOnTheLeft=entityConfig;var newRecordingConfigOnTheRight=entityConfig;do{newRecordingConfigOnTheLeft=configGrid.getPrevEntityNeighbour(newRecordingConfigOnTheLeft)}while(newRecordingConfigOnTheLeft&&newRecordingConfigOnTheLeft.getParameterValue("kind")=="pair");do{newRecordingConfigOnTheRight=configGrid.getNextEntityNeighbour(newRecordingConfigOnTheRight)}while(newRecordingConfigOnTheRight&&newRecordingConfigOnTheRight.getParameterValue("kind")=="pair");var newDynamicDerivedConfigDataOnTheLeft=App.dynamicDerivedConfigDataProvider.get(newRecordingConfigOnTheLeft);var newDynamicDerivedConfigDataOnTheRight=App.dynamicDerivedConfigDataProvider.get(newRecordingConfigOnTheRight);var newDynamicDefinitionForRecordingOnTheLeft=newDynamicDerivedConfigDataOnTheLeft?newDynamicDerivedConfigDataOnTheLeft.attributes.dynamicDefinitionForRecording:null;var newDynamicDefinitionForRecordingOnTheRight=newDynamicDerivedConfigDataOnTheRight?newDynamicDerivedConfigDataOnTheRight.attributes.dynamicDefinitionForRecording:null;var attributesToSet={};var arrayOfShortcuts=[[newRecordingConfigOnTheLeft,"recordingConfigOnTheLeft","change:parameters",this.triggerChange],[newRecordingConfigOnTheRight,"recordingConfigOnTheRight","change:parameters",this.triggerChange],[newDynamicDefinitionForRecordingOnTheLeft,"dynamicDefinitionForRecordingOnTheLeft","change",this.triggerChange],[newDynamicDefinitionForRecordingOnTheRight,"dynamicDefinitionForRecordingOnTheRight","change",this.triggerChange]];for(var i=arrayOfShortcuts.length-1;i>=0;--i){var shortcuts=arrayOfShortcuts[i];var oldAttributeValue=this.attributes[shortcuts[1]];var newAttributeValue=shortcuts[0];if(newAttributeValue!=oldAttributeValue){attributesToSet[shortcuts[1]]=newAttributeValue;if(oldAttributeValue){this.stopListening(oldAttributeValue,shortcuts[2])}if(newAttributeValue){this.listenTo(newAttributeValue,shortcuts[2],shortcuts[3])}}}this.set(attributesToSet)},__triggerChangeMethodOfDynamicDerivedConfigData:function(){this.dropCachedHash();this.trigger("change")},generateDynamicDerivedConfigData:function(entityConfig,configGrid){var optionsOfThisDynamicDerivedConfigData=_.clone(this.__optionsOfDynamicDerivedConfigData);optionsOfThisDynamicDerivedConfigData.entityConfig=entityConfig;optionsOfThisDynamicDerivedConfigData.configGrid=configGrid;var dynamicDerivedConfigData=new RepresentationModule.DynamicDerivedConfigData({recordingConfigOnTheLeft:null,recordingConfigOnTheRight:null,dynamicDefinitionForRecordingOnTheLeft:null,dynamicDefinitionForRecordingOnTheRight:null},optionsOfThisDynamicDerivedConfigData);dynamicDerivedConfigData.update=this.__updateMethodOfDynamicDerivedConfigData;dynamicDerivedConfigData._doUpdate=this.__doUpdateMethodOfDynamicDerivedConfigData;dynamicDerivedConfigData.triggerChange=this.__triggerChangeMethodOfDynamicDerivedConfigData;dynamicDerivedConfigData.listenTo(configGrid,"change_layout",dynamicDerivedConfigData.update);dynamicDerivedConfigData.update();return dynamicDerivedConfigData},__optionsOfDynamicDerivedVisInstanceDataForBase:{attributesToExcludeFromHash:["apiResponseOnTheLeft","apiResponseOnTheRight"],customHashSuffixGenerator:function(attributes){if(attributes.apiResponseOnTheLeft){return JSON.stringify(attributes.apiResponseOnTheLeft.errors)}else{return typeof attributes.apiResponseOnTheLeft}if(attributes.apiResponseOnTheRight){return JSON.stringify(attributes.apiResponseOnTheRight.errors)}else{return typeof attributes.apiResponseOnTheRight}}},__upateMethodOfDynamicDerivedVisInstanceDataForBase:function(force){var visInstanceView=this.options.visInstanceView;var _this=this;_.each(["Right","Left"],function(side){var dynamicDefinitionForRecording=visInstanceView.dynamicDerivedConfigDataForEntity.attributes["dynamicDefinitionForRecordingOnThe"+side];if(!dynamicDefinitionForRecording){return}if(_this.attributes["apiResponseOnThe"+side]!==null){var recordingLabel=dynamicDefinitionForRecording.attributes.label;if(!recordingLabel){var attrs={};attrs["apiRequestURIOnThe"+side]=undefined;attrs["apiRequestParamsHashOnThe"+side]=undefined;attrs["apiResponseOnThe"+side]=undefined;_this.set(attrs);return}var requestParams=_.clone(visInstanceView.dynamicDerivedConfigDataForView.attributes.basePerspectiveRequestParams);if(!requestParams){return}requestParams.uri=visInstanceView.dynamicDerivedConfigDataForEntity.attributes["recordingConfigOnThe"+side].getParameterValue("recordingURI");var apiRequestParamsHash=JSON.stringify(requestParams);if(!force&&apiRequestParamsHash==_this.attributes["apiRequestParamsHashOnThe"+side]){return}var apiRequestURI=App.DataModule.CliopatriaAPI.request("getRecordingPerspective",requestParams,function(data){if(JSON.stringify(requestParams)!=_this.attributes["apiRequestParamsHashOnThe"+side]){return}var attrs={};attrs["apiRequestParamsHashOnThe"+side]=undefined;attrs["apiResponseOnThe"+side]=data;_this.set(attrs)});var attrs={};attrs["apiRequestURIOnThe"+side]=apiRequestURI;attrs["apiRequestParamsHashOnThe"+side]=apiRequestParamsHash;attrs["apiResponseOnThe"+side]=null;_this.set(attrs)}})},generateDynamicDerivedVisInstanceDataForBase:function(visInstanceView){var viewMaster=visInstanceView._cachedViewMaster;if(!viewMaster.options.visInstanceSupportedComparisonModes.length){return new RepresentationModule.DynamicDerivedVisInstanceData({})}var optionsForThisDynamicDerivedVisInstanceDataForBase=_.clone(this.__optionsOfDynamicDerivedVisInstanceDataForBase);optionsForThisDynamicDerivedVisInstanceDataForBase.visInstanceView=visInstanceView;var dynamicDerivedVisInstanceDataForBase=new RepresentationModule.DynamicDerivedVisInstanceData({apiRequestURIOnTheLeft:undefined,apiRequestParamsHashOnTheLeft:undefined,apiResponseOnTheLeft:undefined,apiRequestURIOnTheRight:undefined,apiRequestParamsHashOnTheRight:undefined,apiResponseOnTheRight:undefined},optionsForThisDynamicDerivedVisInstanceDataForBase);dynamicDerivedVisInstanceDataForBase.update=this.__upateMethodOfDynamicDerivedVisInstanceDataForBase;dynamicDerivedVisInstanceDataForBase.listenTo(visInstanceView.dynamicDerivedConfigDataForEntity,"change",dynamicDerivedVisInstanceDataForBase.update);dynamicDerivedVisInstanceDataForBase.listenTo(visInstanceView.dynamicDerivedConfigDataForView,"change:basePerspectiveRequestParams",dynamicDerivedVisInstanceDataForBase.update);dynamicDerivedVisInstanceDataForBase.update();return dynamicDerivedVisInstanceDataForBase},verifyAllDataForVisInstanceBase:function(visInstanceView){this._verifyThatViewIsNotEmptyOrUnknown(visInstanceView);var viewMaster=visInstanceView._cachedViewMaster;if(!viewMaster.options.canHaveBase){return}var supportedComparisonModes=viewMaster.options.visInstanceSupportedComparisonModes;if(!supportedComparisonModes.length){throw new RepresentationModule.Error({type:"comparison_not-supported"})}if(!_.contains(supportedComparisonModes,viewMaster._getVisInstanceViewComparisonMode(visInstanceView))){throw new RepresentationModule.Error({type:"comparison_wrong-type",supportedTypes:supportedComparisonModes})}var attributesOfDerivedConfigDataForEntityOnTheLeft=visInstanceView.dynamicDerivedConfigDataForEntity.attributes;var attributesOfDerivedConfigDataForEntityOnTheRight=visInstanceView.dynamicDerivedConfigDataForEntity.attributes;var dynamicDefinitionForRecordingOnTheLeft=attributesOfDerivedConfigDataForEntityOnTheLeft.dynamicDefinitionForRecordingOnTheLeft;var dynamicDefinitionForRecordingOnTheRight=attributesOfDerivedConfigDataForEntityOnTheRight.dynamicDefinitionForRecordingOnTheRight;var attributesOfRecordingOnTheLeft=dynamicDefinitionForRecordingOnTheLeft?dynamicDefinitionForRecordingOnTheLeft.attributes:{};var attributesOfRecordingOnTheRight=dynamicDefinitionForRecordingOnTheRight?dynamicDefinitionForRecordingOnTheRight.attributes:{};if(attributesOfRecordingOnTheLeft.label===null||attributesOfRecordingOnTheRight.label===null){throw new RepresentationModule.Error({type:"data-preparing_entity-derived"})}if(attributesOfRecordingOnTheLeft.label===false||attributesOfRecordingOnTheRight.label===false){var apiErrorsOnTheLeft=attributesOfRecordingOnTheLeft.errors||[];var apiErrorsOnTheRight=attributesOfRecordingOnTheRight.errors||[];apiErrors=apiErrorsOnTheLeft.concat(apiErrorsOnTheRight);throw new RepresentationModule.Error({type:"api-error_entity-derived",apiErrors:apiErrors,coverTapAction:this.__coverTapActionThatUpdatesDynamicDerivedData,derivedDataToUpdate:"entity"})}if(attributesOfRecordingOnTheLeft.label===undefined||attributesOfRecordingOnTheRight.label===undefined){throw new RepresentationModule.Error({type:"pair_incomplete"})}var attribytesOfDerivedVisInstanceDataForBase=visInstanceView.dynamicDerivedVisInstanceDataForBase.attributes;if(!attribytesOfDerivedVisInstanceDataForBase.apiResponseOnTheLeft||!attribytesOfDerivedVisInstanceDataForBase.apiResponseOnTheRight){throw new RepresentationModule.Error({type:"data-preparing_base"})}if(attribytesOfDerivedVisInstanceDataForBase.apiResponseOnTheLeft.errors||attribytesOfDerivedVisInstanceDataForBase.apiResponseOnTheRight.errors){var apiErrorsOnTheLeft=attribytesOfDerivedVisInstanceDataForBase.apiResponseOnTheLeft.errors||[];var apiErrorsOnTheRight=attribytesOfDerivedVisInstanceDataForBase.apiResponseOnTheRight.errors||[];var apiErrors=apiErrorsOnTheLeft.concat(apiErrorsOnTheRight);if(apiErrors[0]){var error0=apiErrors[0];if((error0.code==11||error0.code==12)&&!apiErrors[1]||apiErrors[1]&&(apiErrors[1].code==11||apiErrors[1].code==12)){throw new RepresentationModule.Error({type:"api-message_progress_base",apiErrors:apiErrors,coverTapAction:this.__coverTapActionThatUpdatesDynamicDerivedData,derivedDataToUpdate:"base"})}}throw new RepresentationModule.Error({type:"api-error_base",apiErrors:apiErrors,coverTapAction:this.__coverTapActionThatUpdatesDynamicDerivedData,derivedDataToUpdate:"base"})}}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view._",inherit:"_",options:{canHaveBase:false,canHaveOverlay:false,canHaveTemp:false,visInstanceContentHeightMin:20,visInstanceContentHeightMax:20,visInstanceContentPaddingTop:5,visInstanceContentPaddingBottom:5,visInstanceSupportedComparisonModes:[],auxiliaryAssetsTimeout:2e3,auxiliaryAssetsCheckInterval:500},defaultConfigParameterValues:{widthToHeightRatio:2},initialize:function(){this.obtainAuxiliaryData();this.obtainAuxiliaryAssets()},setAuxiliaryDataStatus:function(status){this.auxiliaryDataStatus=status;this.trigger("change:auxiliaryResourcesStatus")},setAuxiliaryAssetsStatus:function(status){this.auxiliaryAssetsStatus=status;this.trigger("change:auxiliaryResourcesStatus")},getAuxiliaryResourcesStatus:function(){if(this.auxiliaryDataStatus=="fail"||this.auxiliaryAssetsStatus=="fail"){return"fail"}if(this.auxiliaryDataStatus=="pending"||this.auxiliaryAssetsStatus=="pending"){return"pending"}return""},obtainAuxiliaryAssets:function(){if(!this.options.auxiliaryAssets||!this.options.auxiliaryAssets.length){return}if(this.auxiliaryAssetsStatus){return}this.setAuxiliaryAssetsStatus("pending");var $body=$("body");_.each(this.options.auxiliaryAssets,function(assetURL){$body.append("<script/>").attr("script","text/javascript").attr("src",assetURL)});this.auxiliaryAssetsIntervalCount=0;this.auxiliaryAssetsInterval=setInterval($.proxy(this.auxiliaryAssetsInvervalFunction,this),this.options.auxiliaryAssetsCheckInterval)},auxiliaryAssetsInvervalFunction:function(){++this.auxiliaryAssetsIntervalCount;if(this.auxiliaryAssetsIntervalCount*this.options.auxiliaryAssetsCheckInterval>this.options.auxiliaryAssetsTimeout){clearInterval(this.auxiliaryAssetsInterval);this.setAuxiliaryAssetsStatus("fail");return}if(this.checkIfAuxiliaryAssetsAreReady()){clearInterval(this.auxiliaryAssetsInterval);this.setAuxiliaryAssetsStatus("success")}},checkIfAuxiliaryAssetsAreReady:function(){return true},obtainAuxiliaryData:function(){if(!this.options.auxiliaryData){return}if(this.auxiliaryDataStatus){return}this.setAuxiliaryDataStatus("pending");var arrayOfDeferred=[];var keys=[];_.each(this.options.auxiliaryData,function(definition,key){keys.push(key);arrayOfDeferred.push($.ajax(App.generateAssetURL(definition)))});var _this=this;$.when.apply(null,arrayOfDeferred).then(function(){var auxiliaryData={};_.each(arguments,function(argument,i){auxiliaryData[keys[i]]=argument[0]});_this.auxiliaryData=auxiliaryData;_this.setAuxiliaryDataStatus("ready")},function(){_this.setAuxiliaryDataStatus("fail")})},verifyAuxiliaryResources:function(){var status=this.getAuxiliaryResourcesStatus();if(status=="pending"||status=="fail"){throw new RepresentationModule.Error({type:"auxiliary-resources_"+status,derivedDataToUpdate:"base"})}},getViewName:function(viewConfig){if(!App._cachedViewNamesByViewMasterId){var master=this;App._cachedViewNamesByViewMasterId={};_.each(["collection","recording"],function(configGridType){var $featureSelector=$(Marionette.TemplateCache.get("#cgpma_"+configGridType+"_view__feature-selector")());var autocompleteSuggestions=master.parseAutocompleteSuggestions($featureSelector.find("[data-autocomplete-suggestions]").data("autocomplete-suggestions"));_.each(autocompleteSuggestions,function(kindName,kind){var masterIdPart=kind;if(!masterIdPart){masterIdPart="default"}App._cachedViewNamesByViewMasterId["view."+configGridType+"."+masterIdPart]=kindName})})}var viewName=App._cachedViewNamesByViewMasterId[this.id];if(!viewName){viewName=_.str.trim(viewConfig.getParameterValue("kind"))||"an empty view";if(viewName.length>=4&&viewName.substring(0,2)=="__"&&viewName.substring(viewName.length-2)=="__"){viewName=viewName.substring(2,viewName.length-2)}viewName=_.str.trim(viewName)}return viewName},prepareConfigGridPanelMainArea:function(configGridPanelView){if(!App._cached$viewPanelFeatureSelectorsByConfigGridType){App._cached$viewPanelFeatureSelectorsByConfigGridType={};_.each(["collection","recording"],function(configGridType){var $featureSelector=$(Marionette.TemplateCache.get("#cgpma_"+configGridType+"_view__feature-selector")());App._cached$viewPanelFeatureSelectorsByConfigGridType[configGridType]=$featureSelector})}var $featureSelector=App._cached$viewPanelFeatureSelectorsByConfigGridType[configGridPanelView.options.configGrid.getType()];configGridPanelView._$mainArea.data("$featureSelector",$featureSelector);configGridPanelView._$mainArea.prepend($featureSelector);var $inputForKind=$featureSelector.find("[data-parameter-name=kind]");if($inputForKind.data("cgpma-textfield")&&$featureSelector.data("savedTextRange")){$inputForKind.textfield("setTextRange",$featureSelector.data("savedTextRange"));$featureSelector.removeData("savedTextRange")}RepresentationModule.getMasterById("_").prepareConfigGridPanelMainArea.apply(this,arguments)},destroyConfigGridPanelMainArea:function(configGridPanelView){var $featureSelector=configGridPanelView._$mainArea.data("$featureSelector");if($featureSelector){var $inputForKind=configGridPanelView._$mainArea.find("[data-parameter-name=kind]");if($inputForKind.textfield("isFocused")){$featureSelector.data("savedTextRange",$inputForKind.textfield("getTextRange"))}$featureSelector.detach()}},_doRenderHeaderContentRelatedToOwnData:function(headerView,instant){if(!headerView._$label){headerView._$label=$.bem.generateElement("config-grid-cells","view-header-label").appendTo(headerView.$el)}headerView._$label.html(this._generateHeaderLabel(headerView))},_generateHeaderLabel:function(headerView){var labelCore=this.getViewName(headerView.options.config)+this._generateHeaderLabelSuffix(headerView);if(headerView.options.config.hasPlannedParameterUpdates()){return'<span class="config-grid-cells__view-header-label-part_modified">'+labelCore+"</span> – being modified"}else{return labelCore}},_generateHeaderLabelSuffix:function(headerView){return""},__upateMethodOfDynamicDerivedConfigData:function(){var viewConfig=this.options.viewConfig;var viewMaster=this.options.viewMaster;this.set({basePerspectiveRequestParams:viewMaster.generateBasePerspectiveRequestParams(viewConfig),overlayPerspectiveRequestParams:viewMaster.generateOverlayPerspectiveRequestParams(viewConfig)})},generateDynamicDerivedConfigData:function(config,configGrid){var dynamicDerivedConfigData=new RepresentationModule.DynamicDerivedConfigData({basePerspectiveRequestParams:null,overlayPerspectiveRequestParams:null},{viewConfig:config,viewMaster:RepresentationModule.getMasterForConfig(config)});dynamicDerivedConfigData.update=this.__upateMethodOfDynamicDerivedConfigData;dynamicDerivedConfigData.listenTo(config,"change",dynamicDerivedConfigData.update);dynamicDerivedConfigData.update();return dynamicDerivedConfigData},generateBasePerspectiveRequestParams:function(viewConfig){var viewConfigKind=_.str.trim(viewConfig.getParameterValue("kind"));if(!_.isString(viewConfigKind)||this.getSupportedKind()!=viewConfigKind){return null}var result=this._generateCustomParamsForBasePerspectiveRequestParams(viewConfig);if(!result){return null}if(!result.pid){result.pid=viewConfigKind.replace(/-/g,"_")}return result},_generateCustomParamsForBasePerspectiveRequestParams:function(viewConfig){return{}},generateOverlayPerspectiveRequestParams:function(viewConfig){},_groupDataForGraphicsRendering:function(visInstanceView,layer){if(layer=="base"){return{self:visInstanceView.dynamicDerivedVisInstanceDataForBase.attributes.apiResponse,left:visInstanceView.dynamicDerivedVisInstanceDataForBase.attributes.apiResponseOnTheLeft,right:visInstanceView.dynamicDerivedVisInstanceDataForBase.attributes.apiResponseOnTheRight}}else{return null}},_getVisInstanceViewComparisonMode:function(visInstanceView){var comparisonMode=undefined;var kind=visInstanceView.options.entityConfig.getParameterValue("kind");if(kind==="pair"){comparisonMode=RepresentationModule.getMasterById("entity.collection.pair").getConfigParameterValueOrDefaultValue(visInstanceView.options.entityConfig,"comparisonMode")}return comparisonMode},calculateVisInstanceContentHeight:function(viewConfig,entityWidth){var height=0;var widthToHeightRatio=1*this.getConfigParameterValueOrDefaultValue(viewConfig,"widthToHeightRatio");if(widthToHeightRatio){height=Math.round(entityWidth/widthToHeightRatio)}if(height<this.options.visInstanceContentHeightMin){height=this.options.visInstanceContentHeightMin}if(height>this.options.visInstanceContentHeightMax){height=this.options.visInstanceContentHeightMax}return height+this.options.visInstanceContentPaddingTop+this.options.visInstanceContentPaddingBottom},__domEventHandlerToSelectAllTextInTheField:function(event){if(!event.shiftKey){return}var $cover=$(this);var visInstanceView=$cover.data("visInstanceView");var attachedError=$cover.data("attachedError");RepresentationModule.logger.warn(_.str.sprintf("An error behind the clicked vis instance (id %s):",visInstanceView.cid),attachedError)},renderVisInstance:function(visInstanceView,deep,instant){if(deep){visInstanceView._cachedRenderingHashForBase=undefined;visInstanceView._cachedRenderingHashForOverlay=undefined;visInstanceView._cachedRenderingHashForTemp=undefined}var newRenderingHashForBase=/*!this.options.canHaveBase ||*/this._calculateVisInstanceRenderingHashForBase(visInstanceView);var newRenderingHashForOverlay=!this.options.canHaveOverlay||this._calculateVisInstanceRenderingHashForOverlay(visInstanceView);var newRenderingHashForTemp=!this.options.canHaveTemp||this._calculateVisInstanceRenderingHashForTemp(visInstanceView);var baseHasChanged=newRenderingHashForBase!==visInstanceView._cachedRenderingHashForBase;var overlayHasChanged=newRenderingHashForOverlay!==visInstanceView._cachedRenderingHashForOverlay;var tempHasChanged=newRenderingHashForTemp!==visInstanceView._cachedRenderingHashForTemp;var debugMode=App.options.debugAPI;if(!(baseHasChanged||overlayHasChanged||tempHasChanged)){return}try{if(baseHasChanged){try{if(debugMode){this._prepareRenderingVisInstanceViewInDebugModeIfNeeded(visInstanceView);this._doRenderVisInstanceViewInDebugMode(visInstanceView,"base")}else{visInstanceView._cachedEntityMaster.verifyAllDataForVisInstanceBase(visInstanceView);visInstanceView._cachedViewMaster.verifyAuxiliaryResources();this._prepareRenderingVisInstanceViewIfNeeded(visInstanceView);this._doRenderVisInstanceViewBase(visInstanceView)}}catch(e){visInstanceView._cachedRenderingHashForOverlay=undefined;visInstanceView._cachedRenderingHashForTemp=undefined;overlayHasChanged=true;tempHasChanged=true;throw e}}if(overlayHasChanged){try{if(debugMode){this._doRenderVisInstanceViewInDebugMode(visInstanceView,"overlay")}else{if(!baseHasChanged){visInstanceView._cachedEntityMaster.verifyAllDataForVisInstanceBase(visInstanceView)}visInstanceView._cachedEntityMaster.verifyAllDataForVisInstanceOverlay(visInstanceView);this._doRenderVisInstanceViewOverlay(visInstanceView)}}catch(e){visInstanceView._cachedRenderingHashForTemp=undefined;tempHasChanged=true;throw e}}if(tempHasChanged){if(debugMode){this._doRenderVisInstanceViewInDebugMode(visInstanceView,"temp")}else{if(!baseHasChanged){visInstanceView._cachedEntityMaster.verifyAllDataForVisInstanceBase(visInstanceView)}if(!overlayHasChanged){visInstanceView._cachedEntityMaster.verifyAllDataForVisInstanceOverlay(visInstanceView)}this._doRenderVisInstanceViewTemp(visInstanceView)}}if(visInstanceView.$cover.hasClass("vis-instance__cover_visible")){visInstanceView.$cover.removeClass("vis-instance__cover_visible")}}catch(e){var errorType=e instanceof RepresentationModule.Error?e.options.type:"unknown";var coverTapAction=e instanceof RepresentationModule.Error?e.options.coverTapAction:null;var coverContentTemplate=null;try{coverContentTemplate=Marionette.TemplateCache.get("#vicc__"+errorType+"__"+visInstanceView._cachedEntityMaster.id.replace(/\./g,"-"))}catch(e){coverContentTemplate=Marionette.TemplateCache.get("#vicc__"+errorType)}var coverContent=coverContentTemplate(e.options);var coverCategory=coverContent.slice(0,coverContent.indexOf("|"));var coverMessage=coverContent.slice(coverCategory.length+1);if(!(e instanceof RepresentationModule.Error)||e.needToEmptyContent()){visInstanceView.$content.empty()}visInstanceView.$coverMessage.html(coverMessage);visInstanceView.$cover.addClass("vis-instance__cover_visible").unbind("click").bind("click",coverTapAction).bind("click",this.__domEventHandlerToSelectAllTextInTheField).setMod("vis-instance","cover","category",coverCategory).data("attachedError",e).data("visInstanceView",visInstanceView)}if(baseHasChanged){visInstanceView._cachedRenderingHashForBase=newRenderingHashForBase}if(overlayHasChanged){visInstanceView._cachedRenderingHashForOverlay=newRenderingHashForBase}if(tempHasChanged){visInstanceView._cachedRenderingHashForTemp=newRenderingHashForBase}},cancelVisInstancePointerHighlights:function(visInstanceView){var vegaHoveredItem=visInstanceView.$content.children(0).data("vegaHoveredItem");if(vegaHoveredItem){App.TooltipModule.tooltipView.update();var vegaObj=visInstanceView.$content.children(0).data("vegaObj");vegaObj.update({items:vegaHoveredItem})}},_calculateVisInstanceRenderingHashForBase:function(visInstanceView){if(visInstanceView.options.configGrid.getType()=="collection"){if(this._getVisInstanceViewComparisonMode(visInstanceView)){var result=this.getAuxiliaryResourcesStatus()+visInstanceView._cachedSizeHash+visInstanceView.options.entityConfig.getHashForTrimmedParameters()+visInstanceView.options.viewConfig.getHashForTrimmedParameters()+visInstanceView.dynamicDerivedConfigDataForEntity.getHash()+visInstanceView.dynamicDerivedConfigDataForView.getHash()+visInstanceView.dynamicDerivedVisInstanceDataForBase.getHash();return result}else{return this.getAuxiliaryResourcesStatus()+visInstanceView._cachedSizeHash+visInstanceView.options.viewConfig.getHashForTrimmedParameters()+visInstanceView.dynamicDerivedConfigDataForEntity.attributes.dynamicDefinitionForCollection.getHash()+visInstanceView.dynamicDerivedConfigDataForView.getHash()+visInstanceView.dynamicDerivedVisInstanceDataForBase.getHash()}}else{if(this._getVisInstanceViewComparisonMode(visInstanceView)){var result=this.getAuxiliaryResourcesStatus()+visInstanceView._cachedSizeHash+visInstanceView.options.entityConfig.getHashForTrimmedParameters()+visInstanceView.options.viewConfig.getHashForTrimmedParameters()+visInstanceView.dynamicDerivedConfigDataForEntity.getHash()+visInstanceView.dynamicDerivedConfigDataForView.getHash()+visInstanceView.dynamicDerivedVisInstanceDataForBase.getHash();return result}else{return this.getAuxiliaryResourcesStatus()+visInstanceView._cachedSizeHash+visInstanceView.options.viewConfig.getHashForTrimmedParameters()+visInstanceView.dynamicDerivedConfigDataForEntity.attributes.dynamicDefinitionForRecording.getHash()+visInstanceView.dynamicDerivedConfigDataForView.getHash()+visInstanceView.dynamicDerivedVisInstanceDataForBase.getHash()}}},_prepareRenderingVisInstanceViewIfNeeded:function(visInstanceView){},_doRenderVisInstanceViewBase:function(visInstanceView){this._doRenderVisInstanceViewBaseWithKnownComparisonMode(visInstanceView,this._getVisInstanceViewComparisonMode(visInstanceView))},_doRenderVisInstanceViewBaseWithKnownComparisonMode:function(visInstanceView,comparisonMode){},_calculateVisInstanceRenderingHashForOverlay:function(visInstanceView){return visInstanceView._cachedSizeHash+visInstanceView.options.viewConfig.getHashForTrimmedParameters()+visInstanceView.dynamicDerivedConfigDataForEntity.getHash()+visInstanceView.dynamicDerivedConfigDataForView.getHash()+visInstanceView.dynamicDerivedVisInstanceDataForOverlay.getHash()},_doRenderVisInstanceViewOverlay:function(visInstanceView){this._doRenderVisInstanceViewOverlayWithKnownComparisonMode(visInstanceView,this._getVisInstanceViewComparisonMode(visInstanceView))},_doRenderVisInstanceViewOverlayWithKnownComparisonMode:function(visInstanceView,comparisonMode){},_calculateVisInstanceRenderingHashForTemp:function(visInstanceView){return visInstanceView._cachedSizeHash+visInstanceView.options.viewConfig.getHashForParameters()+visInstanceView.dynamicDerivedConfigDataForEntity.getHash()+visInstanceView.dynamicDerivedConfigDataForView.getHash()+visInstanceView.dynamicDerivedVisInstanceDataForTemp.getHash()},_doRenderVisInstanceViewTemp:function(visInstanceView){this._doRenderVisInstanceViewTempWithKnownComparisonMode(visInstanceView,this._getVisInstanceViewComparisonMode(visInstanceView))},_doRenderVisInstanceViewTempWithKnownComparisonMode:function(visInstanceView,comparisonMode){},_selectAllInDebugTextFieldIfNeeded:function(){$(this).select()},_prepareRenderingVisInstanceViewInDebugModeIfNeeded:function(visInstanceView){if(!visInstanceView.$content.children(0).hasClass("vic-api-debug")){visInstanceView.$content.empty();var $apiDebug=$.bem.generateBlock("vic-api-debug");var mappings=visInstanceView._cachedEntityMaster._mapDerivedVisInstanceDataAttributesToDebugAPIQueryBoxes(this);for(var i=0;i<mappings.length;i++){var $queryBox=$.bem.generateElement("vic-api-debug","query-box",["alignment_"+mappings[i][0]]);var $queryURIWrapper=$.bem.generateElement("vic-api-debug","query-uri-wrapper");var $queryResponseWrapper=$.bem.generateElement("vic-api-debug","query-response-wrapper");var $queryURI=$.bem.generateElement("input","vic-api-debug","query-uri").attr("type","text").mouseup(this._avoidDeselectInDebugTextField).focus(this._selectAllInDebugTextFieldIfNeeded).attr("readonly",true);var $queryResponse=$.bem.generateElement("textarea","vic-api-debug","query-response").attr("readonly",true);$queryURIWrapper.append($queryURI);$queryResponseWrapper.append($queryResponse);$queryBox.append($queryURIWrapper,$queryResponseWrapper);$apiDebug.append($queryBox)}$apiDebug.data("mappings",mappings);visInstanceView.$content.append($apiDebug)}},_doRenderVisInstanceViewInDebugMode:function(visInstanceView,layer){var $apiDebug=visInstanceView.$content.children(0);var mappings=$apiDebug.data("mappings");for(var i=0;i<mappings.length;i++){var mapping=mappings[i];if(layer!=mapping[1]){return}var currentDynamicDerivedVisInstanceData=null;switch(layer){case"base":currentDynamicDerivedVisInstanceData=visInstanceView.dynamicDerivedVisInstanceDataForBase;break;case"overlay":currentDynamicDerivedVisInstanceData=visInstanceView.dynamicDerivedVisInstanceDataForOverlay;break;case"temp":currentDynamicDerivedVisInstanceData=visInstanceView.dynamicDerivedVisInstanceDataForTemp;break}var $queryBox=$apiDebug.children().eq(i);var $queryURI=$queryBox.children().eq(0).children();var $queryResponse=$queryBox.children().eq(1).children();var queryURI=currentDynamicDerivedVisInstanceData.attributes[mapping[2]];var queryResponse=currentDynamicDerivedVisInstanceData.attributes[mapping[3]];var queryURIText=queryURI;if(_.isString(queryURI)&&queryURI.indexOf("//")===0){var protocol=window.location.href.slice(0,window.location.href.indexOf(":"));queryURIText=protocol+":"+queryURIText}var queryResponseText="";if(_.isObject(queryResponse)){queryResponseText=JSON.stringify(queryResponse,false," ")}else if(queryResponse===null){queryResponseText="obtaining..."}else{}var status="ok";if(queryResponse&&queryResponse.errors){status="has-errors"}$queryURI.val(queryURIText);$queryResponse.val(queryResponseText);$queryBox.setMod("vic-api-debug","query-box","status",status)}}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view._default",inherit:"view._",options:{visInstanceContentHeightMin:20,visInstanceContentHeightMax:20},defaultConfigParameterValues:{widthToHeightRatio:undefined},_generateCustomParamsForBasePerspectiveRequestParams:function(viewConfig){return null}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view._unknown",inherit:"view._",options:{visInstanceContentHeightMin:20,visInstanceContentHeightMax:20},defaultConfigParameterValues:{widthToHeightRatio:undefined},_generateHeaderLabelSuffix:function(headerView){return" (unknown feature)"},_generateCustomParamsForBasePerspectiveRequestParams:function(viewConfig){return null}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view._histogram",inherit:"view._",options:{canHaveBase:true,visInstanceContentHeightMin:50,visInstanceContentHeightMax:1e3,visInstanceSupportedComparisonModes:["superposition","direct"]},_doRenderVisInstanceViewBaseWithKnownComparisonMode:function(visInstanceView,comparisonMode){var options=this._generateHistogramOptions(_.str.trim(visInstanceView.options.viewConfig.getParameterValue("kind")));options.comparisonMode=comparisonMode;App.GraphicsRenderingModule.render("histogram",visInstanceView.$content,this._groupDataForGraphicsRendering(visInstanceView,"base"),options)},_generateHistogramOptions:function(pid){}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view.collection._histogram",inherit:"view._histogram",options:{},_generateHistogramOptions:function(pid){var options={};options.colorForBars="#3182bd";options.colorForOverlay="#31a354";options.dataDefinition={};options.dataDefinition.forXs=null;options.dataDefinition.forBars=null;options.dataDefinition.forFlats=null;switch(pid){case"tempo-histogram":case"pitch-histogram":options.dataDefinition.forXs="edges";options.dataDefinition.forBars="counts";break;case"midi-pitch-histogram":options.dataDefinition.forXs="values";options.dataDefinition.forBars="counts";break;case"mean-tempo-curve":options.dataDefinition.forXs=function(data){return _.range(0,data.means.length)};options.dataDefinition.forBars="means";options.dataDefinition.forFlats="std_devs";break;case"tuning-stats":options.dataDefinition.forXs=function(data){return data.stats.hist.edges};options.dataDefinition.forBars=function(data){return data.stats.hist.counts};options.dataDefinition.forXMean=function(data){return data.stats.mean};options.dataDefinition.forXStdDev=function(data){return data.stats["std-dev"]};break;case"tonic-histogram":options.dataDefinition.forXs="values";options.dataDefinition.forBars="counts";break;case"pitch-class-histogram":case"tonic-relative-pitch-class-histogram":options.dataDefinition.forXs="values";options.dataDefinition.forBars="counts";break}return options}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view.collection._similarity",inherit:"view._default",options:{canHaveBase:true,widthToHeightRatio:1,headerSuffixesForCompressorValues:{zlib:"normalised",zxd:"differential"}},defaultConfigParameterValues:{measure:"euclidean",simFeaturesIncludeChords:"1",simFeaturesIncludeChromagram:"1",simFeaturesIncludeMFCC:"1",compressor:"zlib",subsampling:"1"},_listSimFeatures:function(viewConfig){var result=[];if(this.getConfigPlannedParameterValueOrDefaultValue(viewConfig,"simFeaturesIncludeChords")){result.push("chords")}if(this.getConfigPlannedParameterValueOrDefaultValue(viewConfig,"simFeaturesIncludeChromagram")){result.push("chromagram")}if(this.getConfigPlannedParameterValueOrDefaultValue(viewConfig,"simFeaturesIncludeMFCC")){result.push("mfcc")}return result},prepareConfigGridPanelMainArea:function(configGridPanelView){configGridPanelView._$mainArea.data("$measure",configGridPanelView._$mainArea.find(".cgpma__id_compressor"));configGridPanelView._$mainArea.data("$subsampling",configGridPanelView._$mainArea.find(".cgpma__id_subsampling"));RepresentationModule.getMasterById("view._default").prepareConfigGridPanelMainArea.apply(this,arguments)},syncConfigGridPanelMainArea:function(configGridPanelView,instant){var measure=this.getConfigPlannedParameterValueOrDefaultValue(configGridPanelView._cachedConfig,"measure").toLowerCase().trim();var toggleValue=measure=="compression";configGridPanelView._$mainArea.data("$measure").toggle(toggleValue);configGridPanelView._$mainArea.data("$subsampling").toggle(toggleValue);RepresentationModule.getMasterById("view._default").syncConfigGridPanelMainArea.apply(this,arguments)},_generateHeaderLabelSuffix:function(headerView){var result=[" ("];var simFeatures=this._listSimFeatures(headerView.options.config);if(simFeatures){result.push("by ");result.push(simFeatures.join(" + "))}else{result.push("no characteristics")}var measure=this.getConfigParameterValueOrDefaultValue(headerView.options.config,"measure",true);if(measure=="euclidean"){result.push("; euclidean measure")}else if(measure=="compression"){var compressor=this.getConfigParameterValueOrDefaultValue(headerView.options.config,"compressor",true);var compressorLabel=this.options.headerSuffixesForCompressorValues[compressor];if(compressorLabel){result.push(_.str.sprintf("; %s compressor",compressorLabel))}else{result.push("; unknown compressor")}var subsampling=this.getConfigParameterValueOrDefaultValue(headerView.options.config,"subsampling",true);if(subsampling){result.push("; subsampling")}}else{result.push("; unknown measure")}result.push(")");return result.join("")},calculateVisInstanceContentHeight:function(viewConfig,entityWidth){var representation=this.getConfigParameterValueOrDefaultValue(viewConfig,"representaton",true);return entityWidth},_generateCustomParamsForBasePerspectiveRequestParams:function(viewConfig){var measure=this.getConfigParameterValueOrDefaultValue(viewConfig,"measure",true);var result={sim_features:this._listSimFeatures(viewConfig).join(","),sim_type:measure,pid:"similarity"};if(measure){result["sim_compressor"]=this.getConfigParameterValueOrDefaultValue(viewConfig,"compressor",true);result["sim_downsample"]=this.getConfigParameterValueOrDefaultValue(viewConfig,"subsampling",true)}return result},_doRenderVisInstanceViewBaseWithKnownComparisonMode:function(visInstanceView,comparisonMode){var viewConfig=visInstanceView.options.viewConfig;var options={};options.comparisonMode=comparisonMode;options.measure=!!this.getConfigParameterValueOrDefaultValue(viewConfig,"measure",true);options.primaryColor="#3182bd";options.secondaryColor="#31a354";var representation=this.getConfigParameterValueOrDefaultValue(viewConfig,"sequenceRepresentation",true);App.GraphicsRenderingModule.render(this.id.split(".")[2],visInstanceView.$content,this._groupDataForGraphicsRendering(visInstanceView,"base"),options)}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view.collection.default",inherit:"view._default"})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view.collection.geography",inherit:"view._default",options:{canHaveBase:true,headerSuffixesForRegionValues:{planet:"whole planet",africa:"Africa",europe:"Europe",_unknown:"unknown region"},widthToHeightRatioByRegion:{planet:.5,africa:1.1,europe:.8},widthToHeightRatio:2,visInstanceContentHeightMin:40,auxiliaryData:{countryOutlines:"views/geography/world-110m.json",countries:"views/geography/countries.json",placeCountryNumericCodes:"views/geography/placeCountryNumericCodes.json"},auxiliaryAssets:[]},defaultConfigParameterValues:{displayRegion:"planet",showCountriesAsCircles:""},checkIfAuxiliaryAssetsAreReady:function(){return!!(d3&&d3.geo&&_.isFunction(d3.geo.projection))},_generateHeaderLabelSuffix:function(headerView){var result=[];var region=this.getConfigParameterValueOrDefaultValue(headerView.options.config,"displayRegion",true);if(region!="planet"){var regionLabel=this.options.headerSuffixesForRegionValues[region];if(!regionLabel){regionLabel=this.options.headerSuffixesForRegionValues["_unknown"]}result.push(_.str.sprintf(" (%s)",regionLabel))}var showCountriesAsCircles=this.getConfigParameterValueOrDefaultValue(headerView.options.config,"showCountriesAsCircles",true);if(showCountriesAsCircles){result.push(", countries are shown as circles")}return result.join("")},calculateVisInstanceContentHeight:function(viewConfig,entityWidth){var displayRegion=this.getConfigParameterValueOrDefaultValue(viewConfig,"displayRegion",true);var height=this.options.widthToHeightRatioByRegion[displayRegion]*entityWidth;if(!height){height=this.options.widthToHeightRatio}if(height<this.options.visInstanceContentHeightMin){height=this.options.visInstanceContentHeightMin}return height},_generateCustomParamsForBasePerspectiveRequestParams:function(viewConfig){var result={pid:"places_hist"};return result},_doRenderVisInstanceViewBaseWithKnownComparisonMode:function(visInstanceView,comparisonMode){var viewConfig=visInstanceView.options.viewConfig;if(!visInstanceView._cachedViewMaster.auxiliaryData.countriesByCountryNumericCode){visInstanceView._cachedViewMaster.auxiliaryData.countriesByCountryNumericCode={};_.each(visInstanceView._cachedViewMaster.auxiliaryData.countries,function(country){visInstanceView._cachedViewMaster.auxiliaryData.countriesByCountryNumericCode[country[1]]=country})}var options={};options.comparisonMode=comparisonMode;options.countryOutlines=visInstanceView._cachedViewMaster.auxiliaryData.countryOutlines;options.countries=visInstanceView._cachedViewMaster.auxiliaryData.countries;options.countriesByCountryNumericCode=visInstanceView._cachedViewMaster.auxiliaryData.countriesByCountryNumericCode;options.placeCountryNumericCodes=visInstanceView._cachedViewMaster.auxiliaryData.placeCountryNumericCodes;options.region=this.getConfigParameterValueOrDefaultValue(viewConfig,"displayRegion",true);options.showCountriesAsCircles=!!this.getConfigParameterValueOrDefaultValue(viewConfig,"showCountriesAsCircles",true);App.GraphicsRenderingModule.render("geography",visInstanceView.$content,this._groupDataForGraphicsRendering(visInstanceView,"base"),options)}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view.collection.key-relative-chord-seq",inherit:"view._default",options:{canHaveBase:true},defaultConfigParameterValues:{sequenceCount:100,sequenceRepresentation:"parallel-coordinates",chordGrouppingIsByType:"",guidesAreVisible:"1",recordingsInMajorModeAreIncluded:"1",recordingsInMinorModeAreIncluded:"1",chordTypesArePopularOnly:"",chordSequencesWithCyclesAreIncluded:"1",nIsIncluded:"",sequenceStepCount:2,minSupport:50},_generateHeaderLabelSuffix:function(headerView){var sequenceCount=this.getConfigParameterValueOrDefaultValue(headerView.options.config,"sequenceCount",true);return _.str.sprintf(" (%s most frequent)",sequenceCount)},calculateVisInstanceContentHeight:function(viewConfig,entityWidth){var representation=this.getConfigParameterValueOrDefaultValue(viewConfig,"representaton",true);return entityWidth},_generateCustomParamsForBasePerspectiveRequestParams:function(viewConfig){var result={spm_maxseqs:this.getConfigParameterValueOrDefaultValue(viewConfig,"sequenceCount",true),spm_minlen:this.getConfigParameterValueOrDefaultValue(viewConfig,"sequenceStepCount",true),spm_ignore_n:this.getConfigParameterValueOrDefaultValue(viewConfig,"nIsIncluded",true)=="1"?"0":"1",spm_minsupport:this.getConfigParameterValueOrDefaultValue(viewConfig,"minSupport",true)};return result},_doRenderVisInstanceViewBaseWithKnownComparisonMode:function(visInstanceView,comparisonMode){var viewConfig=visInstanceView.options.viewConfig;var options={};options.comparisonMode=comparisonMode;options.chordGrouppingIsByType=!!this.getConfigParameterValueOrDefaultValue(viewConfig,"chordGrouppingIsByType",true);options.guidesAreVisible=!!this.getConfigParameterValueOrDefaultValue(viewConfig,"guidesAreVisible",true);options.recordingsInMajorModeAreIncluded=!!this.getConfigParameterValueOrDefaultValue(viewConfig,"recordingsInMajorModeAreIncluded",true);options.recordingsInMinorModeAreIncluded=!!this.getConfigParameterValueOrDefaultValue(viewConfig,"recordingsInMinorModeAreIncluded",true);options.nIsIncluded=!!this.getConfigParameterValueOrDefaultValue(viewConfig,"nIsIncluded",true);options.stepCount=this.getConfigParameterValueOrDefaultValue(viewConfig,"sequenceStepCount",true);options.chordSequencesWithCyclesAreIncluded=!!this.getConfigParameterValueOrDefaultValue(viewConfig,"chordSequencesWithCyclesAreIncluded",true);options.sequenceOfUsedChordTypes=[0,1,2,3,4,6];if(!!this.getConfigParameterValueOrDefaultValue(viewConfig,"chordTypesArePopularOnly",true)){}options.primaryColor="#3182bd";options.secondaryColor="#31a354";var representation=this.getConfigParameterValueOrDefaultValue(viewConfig,"sequenceRepresentation",true);App.GraphicsRenderingModule.render("chord-seq."+representation,visInstanceView.$content,this._groupDataForGraphicsRendering(visInstanceView,"base"),options)}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view.collection.list",inherit:"view._",options:{canHaveBase:true,canHaveOverlay:true,canHaveTemp:false,flyingCircleSpeedMin:200,flyingCircleSpeedMax:500,flyingCircleDistanceForMaxSpeed:500,rowHeight:15},defaultConfigParameterValues:{limit:10,offset:0,sortBy:"label",widthToHeightRatio:undefined},_cachedMusicRecordingsButtonRight:null,_cachedMusicRecordingsButtonTop:null,_generateHeaderLabelSuffix:function(headerView){return""},__upateMethodOfDynamicDerivedVisInstanceDataForOverlay:function(force){this.set({recordingURI:this.options.entityConfigForCollection.getParameterValue("recordingURI"),recordingURIs:this.options.entityConfigsForRecordings.map(function(entityConfigForRecording){return entityConfigForRecording.getParameterValue("recordingURI")})})},generateDynamicDerivedVisInstanceDataForOverlay:function(visInstanceView){if(this._getVisInstanceViewComparisonMode(visInstanceView)){return new RepresentationModule.DynamicDerivedVisInstanceData}var optionsForThisDynamicDerivedVisInstanceDataForOverlay={};optionsForThisDynamicDerivedVisInstanceDataForOverlay.entityConfigForCollection=visInstanceView.options.entityConfig;optionsForThisDynamicDerivedVisInstanceDataForOverlay.entityConfigsForRecordings=visInstanceView.options.state.get("musicRecordingGrid").get("entityConfigs");var dynamicDerivedVisInstanceDataForOverlay=new RepresentationModule.DynamicDerivedVisInstanceData({recordingURI:undefined,recordingURIs:[]},optionsForThisDynamicDerivedVisInstanceDataForOverlay);dynamicDerivedVisInstanceDataForOverlay.update=this.__upateMethodOfDynamicDerivedVisInstanceDataForOverlay;dynamicDerivedVisInstanceDataForOverlay.listenTo(optionsForThisDynamicDerivedVisInstanceDataForOverlay.entityConfigForCollection,"change:properties",dynamicDerivedVisInstanceDataForOverlay.update);dynamicDerivedVisInstanceDataForOverlay.listenTo(visInstanceView.options.state.get("musicRecordingGrid"),"change",dynamicDerivedVisInstanceDataForOverlay.update);dynamicDerivedVisInstanceDataForOverlay.update();return dynamicDerivedVisInstanceDataForOverlay},calculateVisInstanceContentHeight:function(viewConfig,entityWidth){var fixedLimit=Math.max(0,1*this.getConfigParameterValueOrDefaultValue(viewConfig,"limit"));if(!(fixedLimit>0&&Math.floor(fixedLimit)===+fixedLimit)){fixedLimit=0}return fixedLimit*this.options.rowHeight+this.options.visInstanceContentPaddingTop+this.options.visInstanceContentPaddingBottom},_generateCustomParamsForBasePerspectiveRequestParams:function(viewConfig){var result={limit:this.getConfigParameterValueOrDefaultValue(viewConfig,"limit",true),offset:this.getConfigParameterValueOrDefaultValue(viewConfig,"offset",true),sort_by:this.getConfigParameterValueOrDefaultValue(viewConfig,"sortBy",true)};return result},__domEventHandlerToSetSelectedRecording:function(){var $this=$(this);var visInstanceView=$this.data("visInstanceView");var recordingURI=$this.data("recordingURI");if(visInstanceView.options.entityConfig.getParameterValue("recordingURI")==recordingURI){}else{visInstanceView.options.entityConfig.updateParameter("recordingURI",recordingURI)}},__domEventHandlerToPlayAudio:function(event){var $this=$(this);App.play($this.data("recordingURI"));event.preventDefault();return false},__domEventHandlerToAnalyseRecording:function(){var $this=$(this);var _this=$this.data("master");var recordingURI=$this.parent().data("recordingURI");var existingRecordingConfigsByRecordingURI={};var recordingConfigs=App.context.get("state").get("musicRecordingGrid").get("entityConfigs");recordingConfigs.each(function(recordingConfig){existingRecordingConfigsByRecordingURI[recordingConfig.getParameterValue("recordingURI")]=recordingConfig});var nowAdding=!existingRecordingConfigsByRecordingURI[recordingURI];if(nowAdding){recordingConfigs.add(new App.ContextModule.Config({parameters:{recordingURI:recordingURI}}))}else{recordingConfigs.remove(existingRecordingConfigsByRecordingURI[recordingURI])}var $flyingCircle=$.bem.generateElement("vic-list","flying-circle",[nowAdding?"type_adding":"type_removing"]);if(!_this._cachedMusicRecordingsButtonRight){var $modeChanger=$(".main-menu-bar__item_action_change-mode");_this._cachedMusicRecordingsButtonRight=$modeChanger.width()/2;_this._cachedMusicRecordingsButtonTop=$modeChanger.height()/2}$flyingCircle.appendTo(document.body);var initialOffset=$($this[0]).offset();var targetOffset={left:$(window).width()-_this._cachedMusicRecordingsButtonRight,top:_this._cachedMusicRecordingsButtonTop};if(!nowAdding){var bubble=initialOffset;initialOffset=targetOffset;targetOffset=bubble}$flyingCircle.css(initialOffset);var flyingDistance=Math.sqrt(Math.pow(targetOffset.left-initialOffset.left,2)+Math.pow(targetOffset.top-initialOffset.top,2));var speed=(_this.options.flyingCircleSpeedMax-_this.options.flyingCircleSpeedMin)*Math.min(1,flyingDistance/_this.options.flyingCircleDistanceForMaxSpeed)+_this.options.flyingCircleSpeedMin;$flyingCircle.animate(targetOffset,speed,_this.__removeFlyingCircleAfterAnimation);var notificationHasBeenShown=App.DataModule.Storage.getStrCache(RepresentationModule,"master_view.collection.list_flying-square-notification-shown");if(!notificationHasBeenShown){App.showNotification({content:$("#notification-content_flying-circle").html(),id:"flying-circle",modifiers:["ttl_20"]});App.context.get("state").once("change:musicRecordingsGridIsShown",function(){App.hideNotification("flying-circle")});App.DataModule.Storage.setStrCache(RepresentationModule,"master_view.collection.list_flying-square-notification-shown","1")}$this.trigger("mouseup")},__removeFlyingCircleAfterAnimation:function(){$(this).remove()},_doRenderVisInstanceViewBaseWithKnownComparisonMode:function(visInstanceView,comparisonMode){var _this=this;var items=visInstanceView.dynamicDerivedVisInstanceDataForBase.attributes.apiResponse.items;var bankOf$analyzeByRecordingURI={};var $list=$.bem.generateBlock("vic-list");for(var i=0;i<items.length;i++){var item=items[i];var $item=$.bem.generateElement("vic-list","item").data("recordingURI",item.uri).data("visInstanceView",visInstanceView);$.bem.generateElement("vic-list","item-label").text(item.label).appendTo($item);if(item.date){var year=item.date.indexOf("/")>0?item.date.slice(-4):item.date.slice(0,4);$.bem.generateElement("vic-list","item-year").text(year).appendTo($item)}if(item.audio&&item.audio.length){$.bem.generateElement("span","vic-list","item-command",["action_audio"]).data("recordingURI",item.uri).data("master",_this).click(this.__domEventHandlerToPlayAudio).attr("title","play this recording").append("<i/>").appendTo($item)}var $analyse=$.bem.generateElement("vic-list","item-command",["action_analyze"]).click(this.__domEventHandlerToAnalyseRecording).attr("title"," ").data("master",_this).append("<i/>").appendTo($item);bankOf$analyzeByRecordingURI[item.uri]=$analyse;$item.click(this.__domEventHandlerToSetSelectedRecording);$list.append($item)}App.TooltipModule.convertTitlesToTooltips($list);$list.data("bankOf$analyzeByRecordingURI",bankOf$analyzeByRecordingURI);visInstanceView.$content.empty().append($list)},_calculateVisInstanceRenderingHashForOverlay:function(visInstanceView){return visInstanceView._cachedSizeHash+visInstanceView.dynamicDerivedVisInstanceDataForOverlay.getHash()},_doRenderVisInstanceViewOverlayWithKnownComparisonMode:function(visInstanceView,comparisonMode){var recordingURI=visInstanceView.options.entityConfig.getParameterValue("recordingURI");visInstanceView.$content.children(0).children().each(function(){var $listItem=$(this);var listItemRecordingURI=$listItem.data("recordingURI");$listItem.toggleClass("vic-list__item_status_selected",recordingURI==listItemRecordingURI)});var existingRecordingConfigsByRecordingURI={};var recordingConfigs=App.context.get("state").get("musicRecordingGrid").get("entityConfigs");recordingConfigs.each(function(recordingConfig){existingRecordingConfigsByRecordingURI[recordingConfig.getParameterValue("recordingURI")]=recordingConfig});var bankOf$analyzeByRecordingURI=visInstanceView.$content.children(0).data("bankOf$analyzeByRecordingURI");_.each(bankOf$analyzeByRecordingURI,function($analyze,recordingURI){var exists=!!existingRecordingConfigsByRecordingURI[recordingURI];$analyze.toggleClass("vic-list__item-command_status_toggled",exists);$analyze.attr("tooltip-title",exists?"remove this recording from the ‘music recordings’ grid":"add this recording to the ‘music recordings’ grid")})}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view.collection.mean-tempo-curve",inherit:"view.collection._histogram"})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view.collection.midi-pitch-histogram",inherit:"view.collection._histogram",defaultConfigParameterValues:{weighting:"none"},_generateCustomParamsForBasePerspectiveRequestParams:function(viewConfig){var result={weighting:this.getConfigParameterValueOrDefaultValue(viewConfig,"weighting",true)};return result}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view.collection.pitch-class-histogram",inherit:"view.collection._histogram"})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view.collection.pitch-histogram",inherit:"view.collection._histogram",defaultConfigParameterValues:{weighting:"none",pitchMin:20,pitchMax:100},_generateCustomParamsForBasePerspectiveRequestParams:function(viewConfig){var result={weighting:this.getConfigParameterValueOrDefaultValue(viewConfig,"weighting",true),min:this.getConfigParameterValueOrDefaultValue(viewConfig,"pitchMin",true),max:this.getConfigParameterValueOrDefaultValue(viewConfig,"pitchMax",true)};return result}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view.collection.similarity-matrix",inherit:"view.collection._similarity",options:{widthToHeightRatio:1}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view.collection.similarity-plane",inherit:"view.collection._similarity",options:{widthToHeightRatio:1}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view.collection.tempo-histogram",inherit:"view.collection._histogram",defaultConfigParameterValues:{tempoMin:30,tempoMax:300,tempoNumBins:50,tempoPeriod:1},_generateCustomParamsForBasePerspectiveRequestParams:function(viewConfig){var result={min:this.getConfigParameterValueOrDefaultValue(viewConfig,"tempoMin"),max:this.getConfigParameterValueOrDefaultValue(viewConfig,"tempoMax")};return result}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view.collection.tonic-histogram",inherit:"view.collection._histogram"})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view.collection.tonic-relative-pitch-class-histogram",inherit:"view.collection._histogram",getViewName:function(){return"pitch class histogram (tonic-relative)"}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view.collection.tuning-stats",inherit:"view.collection._histogram"})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view.recording._histogram",inherit:"view._histogram",options:{},_generateCustomParamsForBasePerspectiveRequestParams:function(viewConfig){return{}},_generateHistogramOptions:function(pid){var options={};options.colorForBars="#31a354";options.layer="base";options.dataDefinition={};options.dataDefinition.forXs=null;options.dataDefinition.forBars=null;options.dataDefinition.forFlats=null;switch(pid){case"tempo-nonuniform":options.dataDefinition.forceXsAreEdges=true;case"tempo-normalised":options.dataDefinition.forXs="times";options.dataDefinition.forBars="values";break;case"midi-pitch-histogram":options.dataDefinition.forXs="values";options.dataDefinition.forBars="counts";break;case"pitch-histogram":case"tempo-histogram":options.dataDefinition.forXs="edges";options.dataDefinition.forBars="counts";break}return options}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view.recording.default",inherit:"view._default"})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view.recording.midi-pitch-histogram",inherit:"view.recording._histogram"})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view.recording.pitch-histogram",inherit:"view.recording._histogram"})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view.recording.properties",inherit:"view._",options:{canHaveBase:true,visInstanceContentHeightMin:9*15,visInstanceContentHeightMax:9*15},propertyDefinitions:[[null,"library",null,function(fieldValue){return fieldValue.toUpperCase()}],[null,"title"],[null,"genre","genres"],[null,"composer","composers"],[null,"performer","performers",null,"before-divider"],[null,"_divider_"],[null,"place"],[null,"language","languages"],["date","date"]],_doRenderVisInstanceViewBaseWithKnownComparisonMode:function(visInstanceView,comparisonMode){var properties=visInstanceView.dynamicDerivedVisInstanceDataForBase.attributes.apiResponse;var $properties=$.bem.generateBlock("vic-properties");_.each(this.propertyDefinitions,function(propertyDefinition){var propertyName=propertyDefinition[0];if(propertyName==null){propertyName=propertyDefinition[1]}if(propertyName=="_divider_"){$properties.append($.bem.generateElement("vic-properties","property-divider"));return}var propertyValue=properties[propertyName];var propertyCaption=propertyDefinition[1];if(_.isArray(propertyValue)){if(propertyValue.length>1){propertyCaption=propertyDefinition[2]}propertyValue=propertyValue.join(", ")}if(propertyValue&&_.isFunction(propertyDefinition[3])){propertyValue=propertyDefinition[3](propertyValue)}var $property=$.bem.generateElement("vic-properties","property");var $propertyFieldCaption=$.bem.generateElement("vic-properties","property-caption");var $propertyValue=$.bem.generateElement("vic-properties","property-value");$propertyFieldCaption.text(propertyCaption+":");$propertyValue.text(propertyValue);$property.append($propertyFieldCaption,$propertyValue);$properties.append($property);if(propertyDefinition[4]){$property.setMod("vic-properties","property","type",propertyDefinition[4])}});visInstanceView.$content.empty().append($properties)}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view.recording.tempo-histogram",inherit:"view.recording._histogram",defaultConfigParameterValues:{tempoMin:30,tempoMax:300,tempoNumBins:50,tempoPeriod:1},_generateCustomParamsForRecordingPerspectiveRequestParams:function(viewConfig){var result={min:this.getConfigParameterValueOrDefaultValue(viewConfig,"tempoMin"),max:this.getConfigParameterValueOrDefaultValue(viewConfig,"tempoMax")};return result}})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view.recording.tempo-nonuniform",inherit:"view.recording._histogram"})})},Logger); "use strict";App.module("RepresentationModule",function(RepresentationModule,App,Backbone,Marionette,$,_,Logger){RepresentationModule.addInitializer(function(options){RepresentationModule.registerMaster({id:"view.recording.tempo-normalised",inherit:"view.recording._histogram"})})},Logger);