<commit_before>define([
           'dojo/_base/declare',
           'dojo/on',
           'dojo/dom-construct',
           'dojo/Deferred',
           'JBrowse/View/Track/BlockBased',
           'JBrowse/View/Track/HTMLFeatures',
           'JBrowse/Store/SeqFeature/Combination/TreeNode',
            'dojo/dnd/move',
           'dojo/dnd/Source',
           'dojo/dnd/Manager',
           'JBrowse/Util'],
       function(
           declare,
           on,
           dom,
           Deferred,
           BlockBased,
           HTMLFeaturesTrack,
           TreeNode,
           dndMove,
           dndSource,
           dndManager,
           Util
       ) {
return declare(BlockBased,
 /**
  * @lends JBrowse.View.Track.Combination.prototype
  */
{

    /**
     *
     *
     * @constructs
     */

    constructor: function( args ) {
        this.loaded = true;
        this.divClass = args.divClass || "combination";

        this.tracks = [];
        this.defaultOp = "AND";
        this.opTree = new TreeNode({ Value: this.defaultOp });
        this.currentDndSource = undefined;
        this.sourceWasCopyOnly = undefined;

        // This is used to avoid creating a feedback loop in the height-updating process.
        this.onlyRefreshOuter = false;
        // Height of the top and bottom divs (when there is an inner track)
        this.topHeight = 20;
        this.bottomHeight = 20;
        this.heightInner = 0;

        // Height of the track (when there is no inner track)
        this.heightNoInner = 50;

        this.height = args.height || this.heightNoInner;

        this.keyToStore = {};
        this.storeToKey = {};

        this.innerTrack = undefined;
        this.innerDiv = undefined;
        this.counter = 0;
    },

    setViewInfo: function(genomeView, heightUpdate, numBlocks,
                         trackDiv,
                         widthPct, widthPx, scale) {
        this.inherited( arguments );
        this.scale = scale;

        this.dnd = new dndSource( this.div,
        {
          accept: ["track"], //Accepts only tracks
          withHandles: true,
          creator: dojo.hitch( this, function( trackConfig, hint ) {
              return {
                  data: trackConfig,
                  type: ["track"],
                  node: hint == 'avatar'
                                 ? dojo.create('div', { innerHTML: "Inner Track", className: 'track-label dragging' })
                                 : this.addTrack(trackConfig)
              };
          })
        });

        this._attachDndEvents();
    },

    _attachDndEvents: function() {
        var thisB = this;
        dojo.connect(thisB.dnd, "onDndStart", function(source, nodes, copy) {
                                                if(source == thisB.dnd && nodes[0] && thisB.innerTrack) {
                                                  source.getItem(nodes[0].id).data = thisB.innerTrack.config;
                                                  source.getItem(nodes[0].id).data.label = "combination_inner_track" + thisB.browser.innerTrackCount;
                                                  thisB.onlyRefreshOuter = true;
                                                }
                                                thisB.currentDndSource = source;
                                                thisB.sourceWasCopyOnly = source.copyOnly;
                                            });
        dojo.connect(thisB.dnd, "onDraggingOver", function() {

                                                if(thisB.currentDndSource) {
                                                  thisB.currentDndSource.copyOnly = true;
                                                }
                                            });
        var allCopyEndingEvents = ["onDraggingOut", "onDndDrop", "onDndCancel"];

        for(var eventName in allCopyEndingEvents)
          dojo.connect(thisB.dnd, allCopyEndingEvents[eventName], function() {
                                                if(thisB.currentDndSource) {
                                                  thisB.currentDndSource.copyOnly = thisB.sourceWasCopyOnly;
                                                }
                                            });
        dojo.connect(thisB.dnd, "onDndDrop", function(source, nodes, copy, target) {
          if(source == thisB.dnd && nodes[0]) {
            thisB.browser.innerTrackCount++;
            thisB.onlyRefreshOuter = false;
          }
          if(!copy && nodes[0] && source == thisB.dnd && target != thisB.dnd) {
            thisB.reinitialize();
            thisB.refresh();
          }
        });
        dojo.connect(thisB.dnd, "onDndCancel", function() {
            thisB.onlyRefreshOuter = false;
        });
        dojo.connect(thisB.dnd, "onOutEvent", function() {
            dndManager.manager().overSource(thisB.genomeView.trackDndWidget);
        });
    },

    reinitialize: function() {
      this.innerDiv = undefined;
      this.innerTrack = undefined;
      this.store = undefined;
      this.opTree = undefined;
      this.storeToKey = {};
      this.keyToStore = {};
    },

    addTrack: function(trackConfig) {
      var thisB = this;
      // There's probably a better way to store this data.  We'll do it this way since it's easily bidirectional (for read/write).
      thisB.storeToKey[trackConfig.store] = trackConfig.key;
      thisB.keyToStore[trackConfig.key] = trackConfig.store;

      if(!this.innerDiv) {
        this.innerDiv = document.createElement("div");
        this.innerDiv.className = "track";
        this.innerDiv.id = this.name + "_innerDiv";
        this.innerDiv.style.top = this.topHeight + "px"; //Alter this.
        //this.div.appendChild(this.innerDiv);
      } else { // Otherwise we'll have to remove whatever track is currently in the div
        thisB.innerTrack.clear();
        thisB.innerTrack.destroy();

        while(thisB.innerDiv.firstChild) { // Use dojo.empty instead?
          thisB.innerDiv.removeChild(thisB.innerDiv.firstChild);
        }

        thisB.innerDiv.parentNode.removeChild(thisB.innerDiv);
      }

      thisB._addTrackStore(trackConfig.store);
      /*
      var nothing = document.createTextNode("");
      return nothing;
      */
      return thisB.innerDiv;
    },

    treeIterate: function(tree) {
      if(!tree || tree === undefined){ return "NULL";}
      if(tree.isLeaf()){
        return tree.get().name ? (this.storeToKey[tree.get().name] ? this.storeToKey[tree.get().name] : tree.get().name)
         : tree.get();
      }
      return "( " + this.treeIterate(tree.left()) +" "+ tree.get() +" " + this.treeIterate(tree.right()) +" )";
    },

    _addTrackStore: function(storeName) {
      var thisB = this;
      var haveStore = (function() {
        var d = new Deferred();
        thisB.browser.getStore(storeName, function(store) {
          if(store) {
            var storeNode = new TreeNode({Value: store});
            if(!thisB.opTree) { thisB.opTree = new TreeNode({Value: thisB.defaultOp});}
            if(!(thisB.opTree.add( storeNode ) ) ) {
              var opNode = new TreeNode({Value: thisB.defaultOp});
              opNode.add(thisB.opTree);
              opNode.add(storeNode);
              thisB.opTree = opNode;
            }
            d.resolve(store,true);
          } else {
            d.reject("store " + storeName + " not found", true);
          }
        });
        return d.promise;
      })();
      haveStore.then(function(store){
        thisB._createCombinationStore();
      });
    },

    _createCombinationStore: function() {
      var d = new Deferred();
      var thisB = this;
      if(thisB.store) {
        d.resolve(true);
      } else {
        var storeConf = {
            browser: thisB.browser,
            refSeq: thisB.browser.refSeq,
            type: 'JBrowse/Store/SeqFeature/Combination',
            op: thisB.defaultOp,
          };
        var storeName = thisB.browser._addStoreConfig(undefined, storeConf);
        storeConf.name = storeName;
        thisB.browser.getStore(storeName, function(store) {
          thisB.store = store;
          d.resolve(true);
        });
      }
      d.promise.then(function(){ thisB._renderInnerTrack(); });
    },

    _renderInnerTrack: function() {
      var thisB = this;
      if(thisB.store) {
        thisB.innerTrack = new HTMLFeaturesTrack({
            config: thisB._innerTrackConfig(),
            browser: thisB.browser,
            refSeq: thisB.refSeq,
            store: thisB.store,
            trackPadding: 0
        });

        var innerHeightUpdate = function(height) {
          thisB.heightInner = height;
          thisB.height = thisB.topHeight + height + thisB.bottomHeight;
          thisB.onlyRefreshOuter = true;
          thisB.refresh();
          thisB.onlyRefreshOuter = false;

          thisB.heightUpdate(thisB.height);
          thisB.div.style.height = thisB.height + "px";
        }

        thisB.innerTrack.setViewInfo (thisB.genomeView, innerHeightUpdate,
            thisB.numBlocks, thisB.innerDiv, thisB.widthPct, thisB.widthPx, thisB.scale);

        thisB._redefineCloseButton();

        thisB.refresh();

      }

    },

    _redefineCloseButton: function() {
        var closeButton = this.innerTrack.label.childNodes[0];
        if(closeButton.className == "track-close-button") {
          this.innerTrack.label.removeChild(closeButton);
          var closeButton = dojo.create('div',{
                                                className: 'track-close-button'
                                              },this.innerTrack.label, "first");

          this.innerTrack.own( on( closeButton, 'click', dojo.hitch(this,function(evt){
                this.browser.view.suppressDoubleClick( 100 );
                this.div.removeChild(this.innerDiv);
                this.reinitialize();
                this.refresh();
                evt.stopPropagation();
          })));

        }
    },

    _innerTrackConfig: function() {
      return {
                  store: this.store.name,
                  feature: ["match"],
                  key: "Inner Track",
                  label: this.name + "_inner",
                  metadata: {Description: "This track was created from a combination track."},
                  type: "JBrowse/View/Track/HTMLFeatures"
              };
    },

    refresh: function(track) {
      //console.log(this.name + " refresh")
      var thisB = this;
      if(!track) track = thisB;
      if(this.store && !this.onlyRefreshOuter) this.store.reload(thisB.opTree);
      if(this.range) {
        track.clear();
        track.showRange(thisB.range.f, thisB.range.l, thisB.range.st, thisB.range.b,
          thisB.range.sc, thisB.range.cs, thisB.range.ce);
      }
    },

    showRange: function(first, last, startBase, bpPerBlock, scale,
                        containerStart, containerEnd) {
      //console.log(this.name + " sr " + this.dnd.getAllNodes().length);
      this.range = {f: first, l: last, st: startBase,
                    b: bpPerBlock, sc: scale,
                    cs: containerStart, ce: containerEnd};
      if(this.innerTrack && !this.onlyRefreshOuter) {
          this.innerTrack.clear();
          this.innerTrack.showRange(first, last, startBase, bpPerBlock, scale, containerStart, containerEnd);
        }
      //console.log("sr 2");
      this.inherited(arguments);
      this.height = (this.innerTrack ? (this.topHeight + this.heightInner + this.bottomHeight) : this.heightNoInner);
      this.heightUpdate(this.height);
      this.div.style.height = this.height + "px";
      //console.log("sr 3");
    },

    moveBlocks: function(delta) {
        this.inherited(arguments);
        if(this.innerTrack) this.innerTrack.moveBlocks(delta);
    },

    fillBlock: function( args ) {
        var blockIndex = args.blockIndex;
        var block = args.block;
        var leftBase = args.leftBase;

        var text = "Add tracks here";
        if(this.innerTrack) {
          var topDiv = document.createElement("div");
          topDiv.className = "combination";
          topDiv.style.height = this.topHeight + "px";
          topDiv.appendChild( document.createTextNode( text ) );
          block.domNode.appendChild( topDiv );

          var bottomDiv = document.createElement("div");
          bottomDiv.className = "combination";
          bottomDiv.style.height = this.bottomHeight + "px";
          bottomDiv.style.top = (this.topHeight + this.heightInner) + "px";
          bottomDiv.appendChild( document.createTextNode( text ) );
          block.domNode.appendChild( bottomDiv );
        } else {
          var textDiv = document.createElement("div");
          textDiv.className = "combination";
          var text = "Add tracks here";
          textDiv.style.height = this.heightNoInner + "px";
          textDiv.appendChild( document.createTextNode( text ) );
          block.domNode.appendChild( textDiv );
        }

        var highlight = this.browser.getHighlight();
        if( highlight && highlight.ref == this.refSeq.name )
            this.renderRegionHighlight( args, highlight );

        this.heightUpdate( this.height, blockIndex);
        this.div.style.height = this.height + "px";
        args.finishCallback();
    },

    endZoom: function(destScale, destBlockBases) {
        this.clear(); // Necessary?
        if(this.innerTrack) this.innerTrack.endZoom();
    },

    msgLoop: function(list) {
      var msg = "";
      for(var item in list) msg = msg + " " + item +": " + list[item];
      alert(msg);
    },

    _trackMenuOptions: function() {
      var o = this.inherited(arguments);
      var combTrack = this;

      var allowedOps = ["AND", "OR", "XOR", "MINUS"];
      var menuItems = allowedOps.map(
                        function(op) {
                          return {
                            label: op,
                            title: "change operation of last track to " + op,
                            action: function() {
                              if(combTrack.opTree) {
                                combTrack.opTree.set(op);
                                combTrack.refresh();
                              }
                            }
                          }
                        });

      o.push.apply(
        o,
        [
          { type: 'dijit/MenuSeparator' },
          { label: 'Edit formula',
            title: 'change the formula specifying this combination track',
            action: function() {
                        if(combTrack.opTree) alert(combTrack.treeIterate(combTrack.opTree));
                        else alert("No operation formula defined");
                    }
          },
          { children: menuItems,
            label: "Change last operation",
            title: "change the operation applied to the last track added"
          }
        ]);

      return o;
    }

});
});<commit_msg>Modify combination track to use dojo/on<commit_after>define([
           'dojo/_base/declare',
           'dojo/on',
           'dojo/dom-construct',
           'dojo/Deferred',
           'JBrowse/View/Track/BlockBased',
           'JBrowse/View/Track/HTMLFeatures',
           'JBrowse/Store/SeqFeature/Combination/TreeNode',
            'dojo/dnd/move',
           'dojo/dnd/Source',
           'dojo/dnd/Manager',
           'JBrowse/Util'],
       function(
           declare,
           on,
           dom,
           Deferred,
           BlockBased,
           HTMLFeaturesTrack,
           TreeNode,
           dndMove,
           dndSource,
           dndManager,
           Util
       ) {
return declare(BlockBased,
 /**
  * @lends JBrowse.View.Track.Combination.prototype
  */
{

    /**
     *
     *
     * @constructs
     */

    constructor: function( args ) {
        this.loaded = true;
        this.divClass = args.divClass || "combination";

        this.tracks = [];
        this.defaultOp = "AND";
        this.opTree = new TreeNode({ Value: this.defaultOp });
        this.currentDndSource = undefined;
        this.sourceWasCopyOnly = undefined;

        // This is used to avoid creating a feedback loop in the height-updating process.
        this.onlyRefreshOuter = false;
        // Height of the top and bottom divs (when there is an inner track)
        this.topHeight = 20;
        this.bottomHeight = 20;
        this.heightInner = 0;

        // Height of the track (when there is no inner track)
        this.heightNoInner = 50;

        this.height = args.height || this.heightNoInner;

        this.keyToStore = {};
        this.storeToKey = {};

        this.innerTrack = undefined;
        this.innerDiv = undefined;
        this.counter = 0;
    },

    setViewInfo: function(genomeView, heightUpdate, numBlocks,
                         trackDiv,
                         widthPct, widthPx, scale) {
        this.inherited( arguments );
        this.scale = scale;

        this.dnd = new dndSource( this.div,
        {
          accept: ["track"], //Accepts only tracks
          withHandles: true,
          creator: dojo.hitch( this, function( trackConfig, hint ) {
              return {
                  data: trackConfig,
                  type: ["track"],
                  node: hint == 'avatar'
                                 ? dojo.create('div', { innerHTML: "Inner Track", className: 'track-label dragging' })
                                 : this.addTrack(trackConfig)
              };
          })
        });

        this._attachDndEvents();
    },

    _attachDndEvents: function() {
        var thisB = this;
        on(thisB.dnd, "DndStart", function(source, nodes, copy) {
                                                if(source == thisB.dnd && nodes[0] && thisB.innerTrack) {
                                                  source.getItem(nodes[0].id).data = thisB.innerTrack.config;
                                                  source.getItem(nodes[0].id).data.label = "combination_inner_track" + thisB.browser.innerTrackCount;
                                                  thisB.onlyRefreshOuter = true;
                                                }
                                                thisB.currentDndSource = source;
                                                thisB.sourceWasCopyOnly = source.copyOnly;
                                            });
        on(thisB.dnd, "DraggingOver", function() {

                                                if(thisB.currentDndSource) {
                                                  thisB.currentDndSource.copyOnly = true;
                                                }
                                            });
        var allCopyEndingEvents = ["DraggingOut", "DndDrop", "DndCancel"];

        for(var eventName in allCopyEndingEvents)
          on(thisB.dnd, allCopyEndingEvents[eventName], function() {
                                                if(thisB.currentDndSource) {
                                                  thisB.currentDndSource.copyOnly = thisB.sourceWasCopyOnly;
                                                }
                                            });
        on(thisB.dnd, "DndDrop", function(source, nodes, copy, target) {
          if(source == thisB.dnd && nodes[0]) {
            thisB.browser.innerTrackCount++;
            thisB.onlyRefreshOuter = false;
          }
          if(!copy && nodes[0] && source == thisB.dnd && target != thisB.dnd) {
            thisB.reinitialize();
            thisB.refresh();
          }
        });
        on(thisB.dnd, "DndCancel", function() {
            thisB.onlyRefreshOuter = false;
        });
        on(thisB.dnd, "OutEvent", function() {
            dndManager.manager().overSource(thisB.genomeView.trackDndWidget);
        });
    },

    reinitialize: function() {
      this.innerDiv = undefined;
      this.innerTrack = undefined;
      this.store = undefined;
      this.opTree = undefined;
      this.storeToKey = {};
      this.keyToStore = {};
    },

    addTrack: function(trackConfig) {
      var thisB = this;
      // There's probably a better way to store this data.  We'll do it this way since it's easily bidirectional (for read/write).
      thisB.storeToKey[trackConfig.store] = trackConfig.key;
      thisB.keyToStore[trackConfig.key] = trackConfig.store;

      if(!this.innerDiv) {
        this.innerDiv = document.createElement("div");
        this.innerDiv.className = "track";
        this.innerDiv.id = this.name + "_innerDiv";
        this.innerDiv.style.top = this.topHeight + "px"; //Alter this.
        //this.div.appendChild(this.innerDiv);
      } else { // Otherwise we'll have to remove whatever track is currently in the div
        thisB.innerTrack.clear();
        thisB.innerTrack.destroy();

        while(thisB.innerDiv.firstChild) { // Use dojo.empty instead?
          thisB.innerDiv.removeChild(thisB.innerDiv.firstChild);
        }

        thisB.innerDiv.parentNode.removeChild(thisB.innerDiv);
      }

      thisB._addTrackStore(trackConfig.store);
      /*
      var nothing = document.createTextNode("");
      return nothing;
      */
      return thisB.innerDiv;
    },

    treeIterate: function(tree) {
      if(!tree || tree === undefined){ return "NULL";}
      if(tree.isLeaf()){
        return tree.get().name ? (this.storeToKey[tree.get().name] ? this.storeToKey[tree.get().name] : tree.get().name)
         : tree.get();
      }
      return "( " + this.treeIterate(tree.left()) +" "+ tree.get() +" " + this.treeIterate(tree.right()) +" )";
    },

    _addTrackStore: function(storeName) {
      var thisB = this;
      var haveStore = (function() {
        var d = new Deferred();
        thisB.browser.getStore(storeName, function(store) {
          if(store) {
            var storeNode = new TreeNode({Value: store});
            if(!thisB.opTree) { thisB.opTree = new TreeNode({Value: thisB.defaultOp});}
            if(!(thisB.opTree.add( storeNode ) ) ) {
              var opNode = new TreeNode({Value: thisB.defaultOp});
              opNode.add(thisB.opTree);
              opNode.add(storeNode);
              thisB.opTree = opNode;
            }
            d.resolve(store,true);
          } else {
            d.reject("store " + storeName + " not found", true);
          }
        });
        return d.promise;
      })();
      haveStore.then(function(store){
        thisB._createCombinationStore();
      });
    },

    _createCombinationStore: function() {
      var d = new Deferred();
      var thisB = this;
      if(thisB.store) {
        d.resolve(true);
      } else {
        var storeConf = {
            browser: thisB.browser,
            refSeq: thisB.browser.refSeq,
            type: 'JBrowse/Store/SeqFeature/Combination',
            op: thisB.defaultOp,
          };
        var storeName = thisB.browser._addStoreConfig(undefined, storeConf);
        storeConf.name = storeName;
        thisB.browser.getStore(storeName, function(store) {
          thisB.store = store;
          d.resolve(true);
        });
      }
      d.promise.then(function(){ thisB._renderInnerTrack(); });
    },

    _renderInnerTrack: function() {
      var thisB = this;
      if(thisB.store) {
        thisB.innerTrack = new HTMLFeaturesTrack({
            config: thisB._innerTrackConfig(),
            browser: thisB.browser,
            refSeq: thisB.refSeq,
            store: thisB.store,
            trackPadding: 0
        });

        var innerHeightUpdate = function(height) {
          thisB.heightInner = height;
          thisB.height = thisB.topHeight + height + thisB.bottomHeight;
          thisB.onlyRefreshOuter = true;
          thisB.refresh();
          thisB.onlyRefreshOuter = false;

          thisB.heightUpdate(thisB.height);
          thisB.div.style.height = thisB.height + "px";
        }

        thisB.innerTrack.setViewInfo (thisB.genomeView, innerHeightUpdate,
            thisB.numBlocks, thisB.innerDiv, thisB.widthPct, thisB.widthPx, thisB.scale);

        thisB._redefineCloseButton();

        thisB.refresh();

      }

    },

    _redefineCloseButton: function() {
        var closeButton = this.innerTrack.label.childNodes[0];
        if(closeButton.className == "track-close-button") {
          this.innerTrack.label.removeChild(closeButton);
          var closeButton = dojo.create('div',{
                                                className: 'track-close-button'
                                              },this.innerTrack.label, "first");

          this.innerTrack.own( on( closeButton, 'click', dojo.hitch(this,function(evt){
                this.browser.view.suppressDoubleClick( 100 );
                this.div.removeChild(this.innerDiv);
                this.reinitialize();
                this.refresh();
                evt.stopPropagation();
          })));

        }
    },

    _innerTrackConfig: function() {
      return {
                  store: this.store.name,
                  feature: ["match"],
                  key: "Inner Track",
                  label: this.name + "_inner",
                  metadata: {Description: "This track was created from a combination track."},
                  type: "JBrowse/View/Track/HTMLFeatures"
              };
    },

    refresh: function(track) {
      //console.log(this.name + " refresh")
      var thisB = this;
      if(!track) track = thisB;
      if(this.store && !this.onlyRefreshOuter) this.store.reload(thisB.opTree);
      if(this.range) {
        track.clear();
        track.showRange(thisB.range.f, thisB.range.l, thisB.range.st, thisB.range.b,
          thisB.range.sc, thisB.range.cs, thisB.range.ce);
      }
    },

    showRange: function(first, last, startBase, bpPerBlock, scale,
                        containerStart, containerEnd) {
      //console.log(this.name + " sr " + this.dnd.getAllNodes().length);
      this.range = {f: first, l: last, st: startBase,
                    b: bpPerBlock, sc: scale,
                    cs: containerStart, ce: containerEnd};
      if(this.innerTrack && !this.onlyRefreshOuter) {
          this.innerTrack.clear();
          this.innerTrack.showRange(first, last, startBase, bpPerBlock, scale, containerStart, containerEnd);
        }
      //console.log("sr 2");
      this.inherited(arguments);
      this.height = (this.innerTrack ? (this.topHeight + this.heightInner + this.bottomHeight) : this.heightNoInner);
      this.heightUpdate(this.height);
      this.div.style.height = this.height + "px";
      //console.log("sr 3");
    },

    moveBlocks: function(delta) {
        this.inherited(arguments);
        if(this.innerTrack) this.innerTrack.moveBlocks(delta);
    },

    fillBlock: function( args ) {
        var blockIndex = args.blockIndex;
        var block = args.block;
        var leftBase = args.leftBase;

        var text = "Add tracks here";
        if(this.innerTrack) {
          var topDiv = document.createElement("div");
          topDiv.className = "combination";
          topDiv.style.height = this.topHeight + "px";
          topDiv.appendChild( document.createTextNode( text ) );
          block.domNode.appendChild( topDiv );

          var bottomDiv = document.createElement("div");
          bottomDiv.className = "combination";
          bottomDiv.style.height = this.bottomHeight + "px";
          bottomDiv.style.top = (this.topHeight + this.heightInner) + "px";
          bottomDiv.appendChild( document.createTextNode( text ) );
          block.domNode.appendChild( bottomDiv );
        } else {
          var textDiv = document.createElement("div");
          textDiv.className = "combination";
          var text = "Add tracks here";
          textDiv.style.height = this.heightNoInner + "px";
          textDiv.appendChild( document.createTextNode( text ) );
          block.domNode.appendChild( textDiv );
        }

        var highlight = this.browser.getHighlight();
        if( highlight && highlight.ref == this.refSeq.name )
            this.renderRegionHighlight( args, highlight );

        this.heightUpdate( this.height, blockIndex);
        this.div.style.height = this.height + "px";
        args.finishCallback();
    },

    endZoom: function(destScale, destBlockBases) {
        this.clear(); // Necessary?
        if(this.innerTrack) this.innerTrack.endZoom();
    },

    msgLoop: function(list) {
      var msg = "";
      for(var item in list) msg = msg + " " + item +": " + list[item];
      alert(msg);
    },

    _trackMenuOptions: function() {
      var o = this.inherited(arguments);
      var combTrack = this;

      var allowedOps = ["AND", "OR", "XOR", "MINUS"];
      var menuItems = allowedOps.map(
                        function(op) {
                          return {
                            label: op,
                            title: "change operation of last track to " + op,
                            action: function() {
                              if(combTrack.opTree) {
                                combTrack.opTree.set(op);
                                combTrack.refresh();
                              }
                            }
                          }
                        });

      o.push.apply(
        o,
        [
          { type: 'dijit/MenuSeparator' },
          { label: 'Edit formula',
            title: 'change the formula specifying this combination track',
            action: function() {
                        if(combTrack.opTree) alert(combTrack.treeIterate(combTrack.opTree));
                        else alert("No operation formula defined");
                    }
          },
          { children: menuItems,
            label: "Change last operation",
            title: "change the operation applied to the last track added"
          }
        ]);

      return o;
    }

});
});<|endoftext|>


<commit_before>import Ember from 'ember';
import { task } from 'ember-concurrency';

const { get, String: { capitalize, camelize } } = Ember;

export default Ember.Service.extend({

  resource: '',

  beforeSend(){},

  afterSend(){},

  send(store, model, action, ...options){
    const task = get(this, `${action}Task`);
    const callback = `on${capitalize(action)}${capitalize(camelize(get(this, 'resource')))}`;

    Ember.assert(`Invalid actions-service resource name.`, !Ember.isEmpty( get(this, 'resource') ));
    Ember.assert(`Store invalid for ${get(this, 'resource')} actions-service.`, Ember.typeOf(action) === 'string');
    Ember.assert(`Must provide a valid action for ${get(this, 'resource')}.`,  Ember.typeOf(action) === 'string');
    Ember.assert(`Task ${action} not found for ${get(this, 'resource')}.`, task);

    this.beforeSend(...arguments);

    return task.perform(store, callback, model, ...options);
  },

  findTask: task(function * (store, callback, model, id){
    model = yield store.findRecord( get(this, 'resource'), id );
    return { callback, model };
  }),

  findAllTask: task(function * (store, callback){
    const model = yield store.findAll( get(this, 'resource') );
    return { callback, model };
  }),

  createTask: task(function * (store, callback){
    const model = yield store.createRecord( get(this, 'resource') );
    return { callback, model };
  }),

  saveTask: task(function * (store, callback, model){
    yield model.save();
    return { callback, model };
  }),

  deleteTask: task(function * (store, callback, model){
    yield model.destroy();
    return { callback, model };
  }),

  unloadTask: task(function * (store, callback, model){
    yield store.unloadRecord(model);
    return { callback, model };
  }),

  rollbackTask: task(function * (store, callback, model){
    yield model.rollbackAttributes();
    return { callback, model };
  })

});
<commit_msg>Peek record before find<commit_after>import Ember from 'ember';
import { task } from 'ember-concurrency';

const { get, String: { capitalize, camelize } } = Ember;

export default Ember.Service.extend({

  resource: '',

  beforeSend(){},

  afterSend(){},

  send(store, model, action, ...options){
    const task = get(this, `${action}Task`);
    const callback = `on${capitalize(action)}${capitalize(camelize(get(this, 'resource')))}`;

    Ember.assert(`Invalid actions-service resource name.`, !Ember.isEmpty( get(this, 'resource') ));
    Ember.assert(`Store invalid for ${get(this, 'resource')} actions-service.`, Ember.typeOf(action) === 'string');
    Ember.assert(`Must provide a valid action for ${get(this, 'resource')}.`,  Ember.typeOf(action) === 'string');
    Ember.assert(`Task ${action} not found for ${get(this, 'resource')}.`, task);

    this.beforeSend(...arguments);

    return task.perform(store, callback, model, ...options);
  },

  findTask: task(function * (store, callback, model, id){
    model = yield store.findRecord( get(this, 'resource'), id );
    return { callback, model };
  }),

  findAllTask: task(function * (store, callback){
    const model = yield store.findAll( get(this, 'resource') );
    return { callback, model };
  }),

  createTask: task(function * (store, callback){
    const model = yield store.createRecord( get(this, 'resource') );
    return { callback, model };
  }),

  saveTask: task(function * (store, callback, _model){
    const model = store.peekRecord( get(this, 'resource'), get(_model, 'id') );
    yield model.save();
    return { callback, model };
  }),

  deleteTask: task(function * (store, callback, model){
    yield model.destroy();
    return { callback, model };
  }),

  unloadTask: task(function * (store, callback, model){
    yield store.unloadRecord(model);
    return { callback, model };
  }),

  rollbackTask: task(function * (store, callback, model){
    yield model.rollbackAttributes();
    return { callback, model };
  })

});
<|endoftext|>


<commit_before>'use strict';

var MultiTenantSession = require("../../classes/MultiTenantSession");
var async = require("async");
var uracDriver = require("../mt/urac.js");

var regEnvironment = (process.env.SOAJS_ENV || "dev");
regEnvironment = regEnvironment.toLowerCase();

/**
 *
 * @param configuration
 * @returns {Function}
 */
module.exports = function (configuration) {
	var soajs = configuration.soajs;
	var param = configuration.param;
	var app = configuration.app;

	function mapInjectedObject(req) {

		var input = req.headers['soajsinjectobj'];
		if(typeof input === 'string'){
			input = JSON.parse(input);
		}

		var output = {};

		if (!input) {
			return output;
		}

		if (input.tenant) {
			output.tenant = {
				id: input.tenant.id,
				code: input.tenant.code
			};
		}

		if (input.key) {
			output.key = {
				config: input.key.config,
				iKey: input.key.iKey,
				eKey: input.key.eKey
			};
		}

		if (input.application) {
			output.application = {
				product: input.application.product,
				package: input.application.package,
				appId: input.application.appId,
				acl: input.application.acl,
				acl_all_env: input.application.acl_all_env
			};
		}

		if (input.package) {
			output.package = {
				acl: input.package.acl,
				acl_all_env: input.package.acl_all_env
			};
		}

		if(input.device){
			output.device = input.device || {};
		}

		if(input.geo){
			output.geo = input.geo || {};
		}

		return output;
	}

	/**
	 *
	 * @param obj
	 * @param cb
	 * @returns {*}
	 */
	function sessionCheck(obj, cb) {
		var mtSessionParam = {
			'session': obj.req.session,
			'tenant': {
				'id': obj.req.soajs.tenant.id,
				'key': obj.req.soajs.tenant.key.iKey,
				'extKey': obj.req.soajs.tenant.key.extKey
			},
			'product': {
				'product': obj.req.soajs.tenant.application.product,
				'package': obj.req.soajs.tenant.application.package,
				'appId': obj.req.soajs.tenant.application.appId
			},
			'request': {'service': obj.app.soajs.param.serviceName, 'api': obj.req.route.path},
			'device': obj.req.soajs.device,
			'geo': obj.req.soajs.geo,
			'req': obj.req
		};
		var mtSession = new MultiTenantSession(mtSessionParam);
		obj.req.soajs.session = mtSession;
		return cb(null, obj);
	}

    /**
	 *
     * @param obj
     * @param cb
     */
	function uracCheck(obj, cb){
		var urac_id = null;
		if (obj.req.urac && obj.req.urac._id)
            urac_id = obj.req.urac._id;
        obj.req.soajs.uracDriver = new uracDriver({"soajs": obj.req.soajs, "_id": urac_id});
        obj.req.soajs.uracDriver.init(function (error, uracProfile) {
            if (error)
                obj.req.soajs.log.error(error);

            return cb(null, obj);
        });
	}

	return function (req, res, next) {

		var injectObj = mapInjectedObject(req);
		if (injectObj && injectObj.application && injectObj.application.package && injectObj.key && injectObj.tenant) {
			req.soajs.tenant = injectObj.tenant;
			req.soajs.tenant.key = {
				"iKey": injectObj.key.iKey,
				"eKey": injectObj.key.eKey
			};
			req.soajs.tenant.application = injectObj.application;

			if (injectObj.package) {
				//req.soajs.tenant.application.package_acl = injectObj.package.acl;
				//req.soajs.tenant.application.package_acl_all_env = injectObj.package.acl_all_env;
				req.soajs.urac = injectObj.urac || null;
				req.soajs.servicesConfig = injectObj.key.config;
				req.soajs.device = injectObj.device;
				req.soajs.geo = injectObj.geo;

				var serviceCheckArray = [function (cb) {
					cb(null, {
						"app": app,
						"res": res,
						"req": req
					});
				}];

				if (param.session)
					serviceCheckArray.push(sessionCheck);
				if(param.uracDriver && req.soajs.urac)
					serviceCheckArray.push(uracCheck);

				async.waterfall(serviceCheckArray, function (err, data) {
					if (err)
						return next(err);
					else
						return next();
				});
			}
			else
				return next(152);
		}
		else
			return next(153);
	};
}
;
<commit_msg>mapper function is checking for urac<commit_after>'use strict';

var MultiTenantSession = require("../../classes/MultiTenantSession");
var async = require("async");
var uracDriver = require("../mt/urac.js");

var regEnvironment = (process.env.SOAJS_ENV || "dev");
regEnvironment = regEnvironment.toLowerCase();

/**
 *
 * @param configuration
 * @returns {Function}
 */
module.exports = function (configuration) {
	var soajs = configuration.soajs;
	var param = configuration.param;
	var app = configuration.app;

	function mapInjectedObject(req) {

		var input = req.headers['soajsinjectobj'];
		if(typeof input === 'string'){
			input = JSON.parse(input);
		}

		var output = {};

		if (!input) {
			return output;
		}

		if (input.tenant) {
			output.tenant = {
				id: input.tenant.id,
				code: input.tenant.code
			};
		}

		if (input.key) {
			output.key = {
				config: input.key.config,
				iKey: input.key.iKey,
				eKey: input.key.eKey
			};
		}

		if (input.application) {
			output.application = {
				product: input.application.product,
				package: input.application.package,
				appId: input.application.appId,
				acl: input.application.acl,
				acl_all_env: input.application.acl_all_env
			};
		}

		if (input.package) {
			output.package = {
				acl: input.package.acl,
				acl_all_env: input.package.acl_all_env
			};
		}

		if(input.device){
			output.device = input.device || {};
		}

		if(input.geo){
			output.geo = input.geo || {};
		}

        if(input.urac){
            output.urac = input.urac || null;
        }

		return output;
	}

	/**
	 *
	 * @param obj
	 * @param cb
	 * @returns {*}
	 */
	function sessionCheck(obj, cb) {
		var mtSessionParam = {
			'session': obj.req.session,
			'tenant': {
				'id': obj.req.soajs.tenant.id,
				'key': obj.req.soajs.tenant.key.iKey,
				'extKey': obj.req.soajs.tenant.key.extKey
			},
			'product': {
				'product': obj.req.soajs.tenant.application.product,
				'package': obj.req.soajs.tenant.application.package,
				'appId': obj.req.soajs.tenant.application.appId
			},
			'request': {'service': obj.app.soajs.param.serviceName, 'api': obj.req.route.path},
			'device': obj.req.soajs.device,
			'geo': obj.req.soajs.geo,
			'req': obj.req
		};
		var mtSession = new MultiTenantSession(mtSessionParam);
		obj.req.soajs.session = mtSession;
		return cb(null, obj);
	}

    /**
	 *
     * @param obj
     * @param cb
     */
	function uracCheck(obj, cb){
		var urac_id = null;
		if (obj.req.urac && obj.req.urac._id)
            urac_id = obj.req.urac._id;
        obj.req.soajs.uracDriver = new uracDriver({"soajs": obj.req.soajs, "_id": urac_id});
        obj.req.soajs.uracDriver.init(function (error, uracProfile) {
            if (error)
                obj.req.soajs.log.error(error);

            return cb(null, obj);
        });
	}

	return function (req, res, next) {

		var injectObj = mapInjectedObject(req);
		if (injectObj && injectObj.application && injectObj.application.package && injectObj.key && injectObj.tenant) {
			req.soajs.tenant = injectObj.tenant;
			req.soajs.tenant.key = {
				"iKey": injectObj.key.iKey,
				"eKey": injectObj.key.eKey
			};
			req.soajs.tenant.application = injectObj.application;

			if (injectObj.package) {
				//req.soajs.tenant.application.package_acl = injectObj.package.acl;
				//req.soajs.tenant.application.package_acl_all_env = injectObj.package.acl_all_env;
				req.soajs.urac = injectObj.urac;
				req.soajs.servicesConfig = injectObj.key.config;
				req.soajs.device = injectObj.device;
				req.soajs.geo = injectObj.geo;

				var serviceCheckArray = [function (cb) {
					cb(null, {
						"app": app,
						"res": res,
						"req": req
					});
				}];

				if (param.session)
					serviceCheckArray.push(sessionCheck);
				if(param.uracDriver && req.soajs.urac)
					serviceCheckArray.push(uracCheck);

				async.waterfall(serviceCheckArray, function (err, data) {
					if (err)
						return next(err);
					else
						return next();
				});
			}
			else
				return next(152);
		}
		else
			return next(153);
	};
}
;
<|endoftext|>


<commit_before>import classic from 'ember-classic-decorator';
import FastBootAwareEventManagerService from 'ember-user-activity/services/-private/fastboot-aware-event-manager';
import { run } from '@ember/runloop';
import getScroll from 'ember-user-activity/utils/get-scroll';

/*
 * Polling uses rAF and/or a setTimeout at 16ms, however rAF will run in the
 * microtask queue and might fire just after Ember's render step occurred.
 * By enforcing that the interval between a poll and the previous must be
 * below a reasonable number, we can be reasonably sure the main UI
 * thread didn't just do a lot of work.
 *
 * This number should be above the minimum polling period (16ms)
 */
const MAX_POLL_PERIOD = 32;
const SCROLL_EVENT_TYPE_VERTICAL = 'vertical';
const SCROLL_EVENT_TYPE_HORIZONTAL = 'horizontal';
const SCROLL_EVENT_TYPE_DIAGONAL = 'diagonal';

@classic
export default class ScrollActivityService extends FastBootAwareEventManagerService {
  init() {
    super.init(...arguments);

    if (this._isFastBoot) {
      return;
    }

    this._animationFrame = null;
    this._subscribers = [];
    this._lastCheckAt = new Date();
    this.subscribe(document, document, () => {}, false);

    this._pollScroll();
  }

  subscribe(target, element, callback = () => {}, highPriority = true) {
    this._subscribers.push({
      target,
      element,
      callback,
      highPriority,
      scrollTop: null,
      scrollLeft: null,
    });
  }

  unsubscribe(target) {
    let { _subscribers: subscribers } = this;
    for (let i = 0; i < subscribers.length; i++) {
      let subscriber = subscribers[i];
      if (subscriber.target === target) {
        subscribers.splice(i, 1);
        break;
      }
    }
  }

  _pollScroll() {
    if (this._isFastBoot) {
      return;
    }
    if (window.requestAnimationFrame) {
      this._animationFrame = requestAnimationFrame(() => this._checkScroll());
    } else {
      this._animationFrame = setTimeout(() => this._checkScroll(), 16);
    }
  }

  _checkScroll() {
    let { _subscribers: subscribers } = this;
    let now = new Date();
    if (subscribers.length) {
      if (this._hasScrolled(now)) {
        this.trigger('scroll');
        run.end();
      }
    }
    this._lastCheckAt = now;
    this._pollScroll();
  }

  _updateScroll(subscriber) {
    subscriber.scrollTop = getScroll(subscriber.element);
    subscriber.scrollLeft = getScroll(subscriber.element, 'left');
  }

  _hasScrolled(now) {
    let { _subscribers: subscribers, _lastCheckAt: lastCheckAt } = this;
    let lowPriorityFrame = now - lastCheckAt < MAX_POLL_PERIOD;
    let hasScrolled = false;
    for (let i = 0; i < subscribers.length; i++) {
      let subscriber = subscribers[i];
      if (subscriber.highPriority || lowPriorityFrame) {
        let scrollTop = getScroll(subscriber.element);
        let scrollLeft = getScroll(subscriber.element, 'left');
        if (
          scrollTop !== subscriber.scrollTop &&
          scrollLeft !== subscriber.scrollLeft
        ) {
          hasScrolled = this._handleAllScrollChanged(subscriber, hasScrolled);
        } else if (scrollTop !== subscriber.scrollTop) {
          hasScrolled = this._handleScrollTopChanged(subscriber, hasScrolled);
        } else if (scrollLeft !== subscriber.scrollLeft) {
          hasScrolled = this._handleScrollLeftChanged(subscriber, hasScrolled);
        }
      }
    }
    return hasScrolled;
  }

  _handleAllScrollChanged(subscriber, hasScrolled) {
    // If the values are changing from an initial null state to first-time values, do not treat it like a change.
    if (subscriber.scrollTop !== null && subscriber.scrollLeft !== null) {
      if (!hasScrolled) {
        run.begin();
        hasScrolled = true;
      }

      let scrollTop = getScroll(subscriber.element);
      let scrollLeft = getScroll(subscriber.element, 'left');
      subscriber.callback(
        scrollTop,
        subscriber.scrollTop,
        SCROLL_EVENT_TYPE_DIAGONAL,
        scrollLeft,
        subscriber.scrollLeft
      );
    }
    this._updateScroll(subscriber);
    return hasScrolled;
  }

  _handleScrollLeftChanged(subscriber, hasScrolled) {
    // If the value is changing from an initial null state to a first
    // time value, do not treat it like a change.
    if (subscriber.scrollLeft !== null) {
      if (!hasScrolled) {
        run.begin();
        hasScrolled = true;
      }
      subscriber.callback(
        getScroll(subscriber.element, 'left'),
        subscriber.scrollLeft,
        SCROLL_EVENT_TYPE_HORIZONTAL
      );
    }
    this._updateScroll(subscriber);
    return hasScrolled;
  }

  _handleScrollTopChanged(subscriber, hasScrolled) {
    // If the value is changing from an initial null state to a first
    // time value, do not treat it like a change.
    if (subscriber.scrollTop !== null) {
      if (!hasScrolled) {
        run.begin();
        hasScrolled = true;
      }
      subscriber.callback(
        getScroll(subscriber.element),
        subscriber.scrollTop,
        SCROLL_EVENT_TYPE_VERTICAL
      );
    }
    this._updateScroll(subscriber);
    return hasScrolled;
  }

  willDestroy() {
    if (this._isFastBoot) {
      return;
    }
    if (window.requestAnimationFrame) {
      cancelAnimationFrame(this._animationFrame);
    } else {
      clearTimeout(this._animationFrame);
    }
    this._subscribers.length = 0;

    super.willDestroy(...arguments);
  }
}
<commit_msg>Fixed runloop import deprecations in scroll-activity-service<commit_after>import classic from 'ember-classic-decorator';
import FastBootAwareEventManagerService from 'ember-user-activity/services/-private/fastboot-aware-event-manager';
import { begin as beginRunloop, end as endRunloop } from '@ember/runloop';
import getScroll from 'ember-user-activity/utils/get-scroll';

/*
 * Polling uses rAF and/or a setTimeout at 16ms, however rAF will run in the
 * microtask queue and might fire just after Ember's render step occurred.
 * By enforcing that the interval between a poll and the previous must be
 * below a reasonable number, we can be reasonably sure the main UI
 * thread didn't just do a lot of work.
 *
 * This number should be above the minimum polling period (16ms)
 */
const MAX_POLL_PERIOD = 32;
const SCROLL_EVENT_TYPE_VERTICAL = 'vertical';
const SCROLL_EVENT_TYPE_HORIZONTAL = 'horizontal';
const SCROLL_EVENT_TYPE_DIAGONAL = 'diagonal';

@classic
export default class ScrollActivityService extends FastBootAwareEventManagerService {
  init() {
    super.init(...arguments);

    if (this._isFastBoot) {
      return;
    }

    this._animationFrame = null;
    this._subscribers = [];
    this._lastCheckAt = new Date();
    this.subscribe(document, document, () => {}, false);

    this._pollScroll();
  }

  subscribe(target, element, callback = () => {}, highPriority = true) {
    this._subscribers.push({
      target,
      element,
      callback,
      highPriority,
      scrollTop: null,
      scrollLeft: null,
    });
  }

  unsubscribe(target) {
    let { _subscribers: subscribers } = this;
    for (let i = 0; i < subscribers.length; i++) {
      let subscriber = subscribers[i];
      if (subscriber.target === target) {
        subscribers.splice(i, 1);
        break;
      }
    }
  }

  _pollScroll() {
    if (this._isFastBoot) {
      return;
    }
    if (window.requestAnimationFrame) {
      this._animationFrame = requestAnimationFrame(() => this._checkScroll());
    } else {
      this._animationFrame = setTimeout(() => this._checkScroll(), 16);
    }
  }

  _checkScroll() {
    let { _subscribers: subscribers } = this;
    let now = new Date();
    if (subscribers.length) {
      if (this._hasScrolled(now)) {
        this.trigger('scroll');
        endRunloop();
      }
    }
    this._lastCheckAt = now;
    this._pollScroll();
  }

  _updateScroll(subscriber) {
    subscriber.scrollTop = getScroll(subscriber.element);
    subscriber.scrollLeft = getScroll(subscriber.element, 'left');
  }

  _hasScrolled(now) {
    let { _subscribers: subscribers, _lastCheckAt: lastCheckAt } = this;
    let lowPriorityFrame = now - lastCheckAt < MAX_POLL_PERIOD;
    let hasScrolled = false;
    for (let i = 0; i < subscribers.length; i++) {
      let subscriber = subscribers[i];
      if (subscriber.highPriority || lowPriorityFrame) {
        let scrollTop = getScroll(subscriber.element);
        let scrollLeft = getScroll(subscriber.element, 'left');
        if (
          scrollTop !== subscriber.scrollTop &&
          scrollLeft !== subscriber.scrollLeft
        ) {
          hasScrolled = this._handleAllScrollChanged(subscriber, hasScrolled);
        } else if (scrollTop !== subscriber.scrollTop) {
          hasScrolled = this._handleScrollTopChanged(subscriber, hasScrolled);
        } else if (scrollLeft !== subscriber.scrollLeft) {
          hasScrolled = this._handleScrollLeftChanged(subscriber, hasScrolled);
        }
      }
    }
    return hasScrolled;
  }

  _handleAllScrollChanged(subscriber, hasScrolled) {
    // If the values are changing from an initial null state to first-time values, do not treat it like a change.
    if (subscriber.scrollTop !== null && subscriber.scrollLeft !== null) {
      if (!hasScrolled) {
        beginRunloop();
        hasScrolled = true;
      }

      let scrollTop = getScroll(subscriber.element);
      let scrollLeft = getScroll(subscriber.element, 'left');
      subscriber.callback(
        scrollTop,
        subscriber.scrollTop,
        SCROLL_EVENT_TYPE_DIAGONAL,
        scrollLeft,
        subscriber.scrollLeft
      );
    }
    this._updateScroll(subscriber);
    return hasScrolled;
  }

  _handleScrollLeftChanged(subscriber, hasScrolled) {
    // If the value is changing from an initial null state to a first
    // time value, do not treat it like a change.
    if (subscriber.scrollLeft !== null) {
      if (!hasScrolled) {
        beginRunloop();
        hasScrolled = true;
      }
      subscriber.callback(
        getScroll(subscriber.element, 'left'),
        subscriber.scrollLeft,
        SCROLL_EVENT_TYPE_HORIZONTAL
      );
    }
    this._updateScroll(subscriber);
    return hasScrolled;
  }

  _handleScrollTopChanged(subscriber, hasScrolled) {
    // If the value is changing from an initial null state to a first
    // time value, do not treat it like a change.
    if (subscriber.scrollTop !== null) {
      if (!hasScrolled) {
        beginRunloop();
        hasScrolled = true;
      }
      subscriber.callback(
        getScroll(subscriber.element),
        subscriber.scrollTop,
        SCROLL_EVENT_TYPE_VERTICAL
      );
    }
    this._updateScroll(subscriber);
    return hasScrolled;
  }

  willDestroy() {
    if (this._isFastBoot) {
      return;
    }
    if (window.requestAnimationFrame) {
      cancelAnimationFrame(this._animationFrame);
    } else {
      clearTimeout(this._animationFrame);
    }
    this._subscribers.length = 0;

    super.willDestroy(...arguments);
  }
}
<|endoftext|>


<commit_before>'use strict';

(function () {

  var validateRegex = function (value, regex) {
    if (value) {
      return !!value.match(regex);
    } else {
      return true;
    }
  };

  angular.module('mwFormValidators', [])

  /**
   * @ngdoc directive
   * @name mwFormValidators.directive:mwValidatePhone
   * @element input
   * @description
   *
   * Adds validation for phone numbers.
   * Valid Examples are: +491234567 or 00491234567
   *
   * Note: this directive requires `ngModel` to be present.
   *
   */
    .directive('mwValidatePhone', function () {
      return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, elm, attr, ngModel) {
          var regex = /^(00[1-9]\d{8,}|^\+[1-9]\d{8,})$/;

          var removeNonDigitValues = function (value) {
            if (value) {
              value = value.replace(/[^ 0-9+]/g, '');
            }
            return value;
          };

          var validateNumber = function (value) {
            return validateRegex(value, regex);
          };

          ngModel.$validators.phone = validateNumber;
          ngModel.$formatters.push(removeNonDigitValues);
        }
      };
    })

    .directive('mwValidateHex', function () {
      return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, elm, attr, ngModel) {
          var regex = /^(0x)?([0-9A-Fa-f])+$/;

          var validateHex = function (value) {
            ngModel.$setValidity('hex', validateRegex(value, regex));
            return value;
          };

          ngModel.$formatters.push(validateHex);
          ngModel.$parsers.push(validateHex);
        }
      };
    })

    .directive('mwValidateCollectionOrModel', function () {
      return {
        restrict: 'A',
        scope: {
          mwModel: '=mwValidateCollectionOrModel',
          mwRequired: '=',
          mwKey: '@'
        },
        template: '<input type="text" ng-required="mwRequired" ng-model="model.tmp" name="{{uId}}" style="display: none">',
        link: function (scope) {

          var key = scope.mwKey || 'uuid';

          scope.model = {};
          scope.uId = _.uniqueId('validator_');

          var unwatch = scope.$watch('mwModel', function () {
            var val = scope.mwModel;
            if (val) {
              if (val instanceof window.Backbone.Collection) {
                val.on('add remove reset', function () {
                  if(val.length > 0){
                    scope.model.tmp = val.first().get(key);
                  } else {
                    scope.model.tmp = undefined;
                  }
                });
                if(val.length > 0){
                  scope.model.tmp = val.first().get(key);
                } else {
                  scope.model.tmp = undefined;
                }
              } else if (val instanceof window.Backbone.Model) {
                val.on('change:' + key, function () {
                  scope.model.tmp = val.get(key);
                });
                scope.model.tmp = val.get(key);
              } else {
                throw new Error('Value is neither a model nor a collection! Make its one of them', val);
              }
              unwatch();
            }
          });
        }
      };
    })

    .directive('mwValidatePlaceholder', function () {
      return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, elm, attr, ngModel) {
          var regex = /\$\{.*\}/;

          var validatePlaceholder = function (value) {
            ngModel.$setValidity('placeholder', validateRegex(value, regex));
            return value;
          };

          ngModel.$formatters.push(validatePlaceholder);
          ngModel.$parsers.push(validatePlaceholder);
        }
      };
    })

    .directive('mwValidatePlaceholderOrMail', function () {
      return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, elm, attr, ngModel) {
          var mailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+([.][a-zA-Z0-9_-]+)*[.][a-zA-Z0-9._-]+$/,
            placeholderRegex = /\$\{.+\}/;

          ngModel.$validators.emailOrPlaceholder = function(value){
            return !!(validateRegex(value, mailRegex) || validateRegex(value, placeholderRegex));
          };
        }
      };
    })

    .directive('mwValidateMatch', function () {
      return {
        require: 'ngModel',
        link: function (scope, elm, attr, ctrl) {
          var pwdWidget = elm.inheritedData('$formController')[attr.mwValidateMatch];

          ctrl.$parsers.push(function (value) {
            var isValid = false;
            if (value === pwdWidget.$viewValue) {
              isValid = true;
            }
            ctrl.$setValidity('match', isValid);
            return value;
          });

          pwdWidget.$parsers.push(function (value) {
            var isValid = false;
            if (value === ctrl.$viewValue) {
              isValid = true;
            }
            ctrl.$setValidity('match', isValid);
            return value;
          });
        }
      };
    })

  /**
   * @ngdoc directive
   * @name mwFormValidators.directive:mwValidateUniqueness
   * @element input
   * @description
   *
   * Adds validation of uniqueness for a given array of strings.
   *
   * @param {Array.<String>} mwValidateUniqueness Array of existing items to validate against
   *
   * Note: this directive requires `ngModel` to be present.
   *
   */
    .directive('mwValidateUniqueness', function () {
      return {
        require: 'ngModel',
        link: function (scope, elm, attr, ngModel) {
          var existingValues;

          scope.$watch(attr.mwValidateUniqueness, function (value) {
            existingValues = value;
          });

          /**
           * Add parser/formatter to model which checks if the model value is
           * a value that already exists and set validation state accordingly
           */
          var validateUniqueness = function (value) {
            var isValid = true;
            if (angular.isArray(existingValues) && existingValues.length > 0 && value && ngModel.$dirty) {
              isValid = (existingValues.indexOf(value) === -1);
            }
            ngModel.$setValidity('unique', isValid);
            return value;
          };
          ngModel.$parsers.unshift(validateUniqueness);
          ngModel.$formatters.unshift(validateUniqueness);
        }
      };
    });

})();<commit_msg>uses idAtttribute of model when no key is defined<commit_after>'use strict';

(function () {

  var validateRegex = function (value, regex) {
    if (value) {
      return !!value.match(regex);
    } else {
      return true;
    }
  };

  angular.module('mwFormValidators', [])

  /**
   * @ngdoc directive
   * @name mwFormValidators.directive:mwValidatePhone
   * @element input
   * @description
   *
   * Adds validation for phone numbers.
   * Valid Examples are: +491234567 or 00491234567
   *
   * Note: this directive requires `ngModel` to be present.
   *
   */
    .directive('mwValidatePhone', function () {
      return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, elm, attr, ngModel) {
          var regex = /^(00[1-9]\d{8,}|^\+[1-9]\d{8,})$/;

          var removeNonDigitValues = function (value) {
            if (value) {
              value = value.replace(/[^ 0-9+]/g, '');
            }
            return value;
          };

          var validateNumber = function (value) {
            return validateRegex(value, regex);
          };

          ngModel.$validators.phone = validateNumber;
          ngModel.$formatters.push(removeNonDigitValues);
        }
      };
    })

    .directive('mwValidateHex', function () {
      return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, elm, attr, ngModel) {
          var regex = /^(0x)?([0-9A-Fa-f])+$/;

          var validateHex = function (value) {
            ngModel.$setValidity('hex', validateRegex(value, regex));
            return value;
          };

          ngModel.$formatters.push(validateHex);
          ngModel.$parsers.push(validateHex);
        }
      };
    })

    .directive('mwValidateCollectionOrModel', function () {
      return {
        restrict: 'A',
        scope: {
          mwModel: '=mwValidateCollectionOrModel',
          mwRequired: '=',
          mwKey: '@'
        },
        template: '<input type="text" ng-required="mwRequired" ng-model="model.tmp" name="{{uId}}" style="display: none">',
        link: function (scope) {

          var key = scope.mwKey || 'uuid';

          scope.model = {};
          scope.uId = _.uniqueId('validator_');

          var unwatch = scope.$watch('mwModel', function () {
            var val = scope.mwModel;
            if (val) {
              if (val instanceof window.Backbone.Collection) {
                val.on('add remove reset', function () {
                  if(val.length > 0){
                    scope.model.tmp = val.first().get(key);
                  } else {
                    scope.model.tmp = undefined;
                  }
                });
                if(val.length > 0){
                  scope.model.tmp = val.first().get(key);
                } else {
                  scope.model.tmp = undefined;
                }
              } else if (val instanceof window.Backbone.Model) {
                key = scope.mwKey || val.idAttribute;
                val.on('change:'+key, function () {
                  scope.model.tmp = val.get(key);
                });
                scope.model.tmp = val.get(key);
              } else {
                throw new Error('Value is neither a model nor a collection! Make its one of them', val);
              }
              unwatch();
            }
          });
        }
      };
    })

    .directive('mwValidatePlaceholder', function () {
      return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, elm, attr, ngModel) {
          var regex = /\$\{.*\}/;

          var validatePlaceholder = function (value) {
            ngModel.$setValidity('placeholder', validateRegex(value, regex));
            return value;
          };

          ngModel.$formatters.push(validatePlaceholder);
          ngModel.$parsers.push(validatePlaceholder);
        }
      };
    })

    .directive('mwValidatePlaceholderOrMail', function () {
      return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, elm, attr, ngModel) {
          var mailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+([.][a-zA-Z0-9_-]+)*[.][a-zA-Z0-9._-]+$/,
            placeholderRegex = /\$\{.+\}/;

          ngModel.$validators.emailOrPlaceholder = function(value){
            return !!(validateRegex(value, mailRegex) || validateRegex(value, placeholderRegex));
          };
        }
      };
    })

    .directive('mwValidateMatch', function () {
      return {
        require: 'ngModel',
        link: function (scope, elm, attr, ctrl) {
          var pwdWidget = elm.inheritedData('$formController')[attr.mwValidateMatch];

          ctrl.$parsers.push(function (value) {
            var isValid = false;
            if (value === pwdWidget.$viewValue) {
              isValid = true;
            }
            ctrl.$setValidity('match', isValid);
            return value;
          });

          pwdWidget.$parsers.push(function (value) {
            var isValid = false;
            if (value === ctrl.$viewValue) {
              isValid = true;
            }
            ctrl.$setValidity('match', isValid);
            return value;
          });
        }
      };
    })

  /**
   * @ngdoc directive
   * @name mwFormValidators.directive:mwValidateUniqueness
   * @element input
   * @description
   *
   * Adds validation of uniqueness for a given array of strings.
   *
   * @param {Array.<String>} mwValidateUniqueness Array of existing items to validate against
   *
   * Note: this directive requires `ngModel` to be present.
   *
   */
    .directive('mwValidateUniqueness', function () {
      return {
        require: 'ngModel',
        link: function (scope, elm, attr, ngModel) {
          var existingValues;

          scope.$watch(attr.mwValidateUniqueness, function (value) {
            existingValues = value;
          });

          /**
           * Add parser/formatter to model which checks if the model value is
           * a value that already exists and set validation state accordingly
           */
          var validateUniqueness = function (value) {
            var isValid = true;
            if (angular.isArray(existingValues) && existingValues.length > 0 && value && ngModel.$dirty) {
              isValid = (existingValues.indexOf(value) === -1);
            }
            ngModel.$setValidity('unique', isValid);
            return value;
          };
          ngModel.$parsers.unshift(validateUniqueness);
          ngModel.$formatters.unshift(validateUniqueness);
        }
      };
    });

})();<|endoftext|>


<commit_before>(function() {
  function createCosmicSigModel(sigId, destination, region, status){
    return {
      signatureId: sigId,
      destination: destination,
      region: region,
      status: status
    };
  }

  function getSigIds(input){
    var inputSplit = input.match(/^.*((\r\n|\n|\r)|$)/gm);
    var sigIds = inputSplit.map(function(obj){
      return obj.slice(0,3).toUpperCase();
    })
    return sigIds;
  }

  module.exports.createCosmicSigModel = createCosmicSigModel;
  module.exports.getSigIds = getSigIds;

}());
<commit_msg>feat: update js<commit_after>(function() {
  function createCosmicSigModel(sigId, destination, region, status){
    return {
      signatureId: sigId,
      destination: destination,
      region: region,
      status: status
    };
  }

  function getSigIds(input){
    var inputSplit = input.match(/^.*((\r\n|\n|\r)|$)/gm);
    var sigIds = inputSplit.map(function(obj){
      return obj.slice(0,3).toUpperCase();
    })
    return sigIds;
  }

  module.exports.createCosmicSigModel = createCosmicSigModel;
  module.exports.getSigIds = getSigIds;
}());
<|endoftext|>


<commit_before>function planetTab(){
    planet_todo_count.todo = planet_todo_count.todo ? planet_todo_count.todo:0;
    planet_todo_count.done = planet_todo_count.done ? planet_todo_count.done:0;
    if($('planet_tab')) $('planet_tab').innerHTML += '

ToDo'+ planet_todo_count.todo + '/' + planet_todo_count.done + '
';
}
xAddEventListener(window,'load',planetTab);

function planetTabOff(){
    $Element('planetex_Tab').leave();
}

function planet_showTodoList(o){
    $ElementList('#planetex_Tab li').removeClass('active');
    $Element(o).parent().addClass('active');
    $ElementList('#planet_myTab li').removeClass('active');

    planet_reload_todo();
}

function planet_reload_todo(){
    $('commentList').innerHTML = '

TODO

\n

\n

\n

DONE

\n

\n

\n\n';
    planet_getTodo();
    planet_getDone();
}

function planet_getTodo(page){
    $('todoList').innerHTML ='';
    _getPlanetTagSeachResult('todo',page,result_planet_getTodo);
}

function planet_getDone(page){
    $('doneList').innerHTML ='';
    _getPlanetTagSeachResult('done',page,result_planet_getDone);
}

function _getPlanetTagSeachResult(tag,page,func){
    var response_tags = new Array('error','message','contentList','pageNavigation');
    exec_xml('planet','dispPlanetContentTagSearch',{keyword:tag,page:page,mid:current_mid},func,response_tags);
}

function result_planet_getTodo(ret_obj,response_tags, params, fo_obj) {

    if(ret_obj['error'] == 0 && ret_obj.contentList){
        var o = new Array();
        var it = new Array();
        var items = ret_obj['contentList']['item'];

        if(typeof(items[0]) == 'undefined'){
            it[0] = items;
        }else{
            it = items;
        }

        o.push('
');
        for(var i=0,c=it.length;i<c;i++){

            it[i]['regdate'] += '';
            it[i]['regdate'] = it[i]['regdate'].substr(0,4) + '/' + it[i]['regdate'].substr(4,2) + '/' + it[i]['regdate'].substr(6,2);

            var tag = $A();
            if(typeof(it[i]['tag_list']['item'])=='string'){
                tag.push(it[i]['tag_list']['item']);
            }else{
                tag = $A(it[i]['tag_list']['item']);
            }

            tag = tag.filter(function(v){return !/todo/i.test(v);});
            tag.push('done');
            tag = tag.$value().join(',');

            o.push('<input type="hidden" id="tag:'+it[i]['document_srl']+'"  value="'+tag+'" />
');
                    o.push(it[i]['content']);
                o.push('<button type="button" id="document_srl:'+it[i]['document_srl']+'"  onclick="planet_todo_setDone(this)">√ DONE</button>');
                o.push('');
                    o.push(it[i]['regdate']);
                o.push('');
            o.push("
\n");
        }

        o.push('
');
        o.push('');

        $('todoList').innerHTML = o.join('');

        var pageNavigation = ret_obj['pageNavigation'];
        $('planet_todo_count').innerHTML = pageNavigation.total_count ? pageNavigation.total_count : 0;

        if(pageNavigation.total_page > 1){

            var str = "";
            if(pageNavigation.first_page>1) str += 'Prev';

            for(var i=pageNavigation.first_page;i<=pageNavigation.page_count;i++){
                if(i== pageNavigation.cur_page){
                    str += ""+i+"";
                }else{
                    str += ''+ i +'';
                }
            }

            if(pageNavigation.total_page != pageNavigation.last_page) str += 'next';
            $('doneList_page').innerHTML = str;
        }
        window.location.href="#planet_tab";
    }else{
        $('planet_todo_count').innerHTML = 0;
    }
}

function result_planet_getDone(ret_obj,response_tags, params, fo_obj) {

    if(ret_obj['error'] == 0 && ret_obj.contentList){
        var o = new Array();
        var it = new Array();
        var items = ret_obj['contentList']['item'];

        if(typeof(items[0]) == 'undefined'){
            it[0] = items;
        }else{
            it = items;
        }

        o.push('
');
        for(var i=0,c=it.length;i<c;i++){

            it[i]['regdate'] += '';
            it[i]['regdate'] = it[i]['regdate'].substr(0,4) + '/' + it[i]['regdate'].substr(4,2) + '/' + it[i]['regdate'].substr(6,2);

            var tag = $A();
            if(typeof(it[i]['tag_list']['item'])=='string'){
                tag.push(it[i]['tag_list']['item']);
            }else{
                tag = $A(it[i]['tag_list']['item']);
            }

            tag = tag.filter(function(v){return !/done/i.test(v);});
            tag.push('todo');
            tag = tag.$value().join(',');

            o.push('<input type="hidden" id="tag:'+it[i]['document_srl']+'"  value="'+tag+'" />
');
                    o.push(it[i]['content']);
                o.push('<button type="button" id="document_srl:'+it[i]['document_srl']+'" onclick="planet_todo_setDone(this)">REDO</button>');
                o.push('<button type="button" onclick="planet_todo_setDel('+it[i]['document_srl']+')">Delete</button>');
            o.push("
\n");
        }

        o.push('
');
        o.push('');

        $('doneList').innerHTML = o.join('');

        var pageNavigation = ret_obj['pageNavigation'];
        $('planet_done_count').innerHTML = pageNavigation.total_count ? pageNavigation.total_count : 0;

        if(pageNavigation.total_page > 1){
            var str = "";

            if(pageNavigation.first_page>1) str += 'Prev';

            for(var i=pageNavigation.first_page;i<=pageNavigation.page_count;i++){
                if(i== pageNavigation.cur_page){
                    str += ""+i+"";
                }else{
                    str += ''+ i +'';
                }
            }

            if(pageNavigation.total_page != pageNavigation.last_page) str += 'next';
            $('doneList_page').innerHTML = str;
        }
        window.location.href="#planet_tab";
    }else{
        $('planet_done_count').innerHTML = 0;
    }
}

function planet_todo_setDone(o){
    var document_srl = o.id.replace(/.*:/,'');
    var tag = $('tag:'+document_srl).value;
    var params = {};
    params['document_srl'] = document_srl;
    params['planet_content_tag'] = tag;

    exec_xml('planet','procPlanetContentTagModify',params,planet_reload_todo);
    return false;
}

function planet_todo_setDel(document_srl){
//    var tag = $A($('document_srl:'+document_srl).value.split(','));
    var tag = $A($('tag:'+document_srl).value.split(','));

    tag = tag.filter(function(v){return !/todo/i.test(v);});
    tag.push('hide');
    tag = tag.$value().join(',');

    var params = {};
    params['document_srl'] = document_srl;
    params['planet_content_tag'] = tag;

    exec_xml('planet','procPlanetContentTagModify',params,planet_reload_todo);
    return false;
}

function showWritePostTodo(tag){
    tag = tag||'todo';
    $Element($('writePostForm').about_tag).hide();
    $Element($('writePostForm').content_tag).show();
    $('writePostForm').content_tag.value = tag;
    showWritePost();
}
<commit_msg>ToDo List HTML.<commit_after>function planetTab(){
    planet_todo_count.todo = planet_todo_count.todo ? planet_todo_count.todo:0;
    planet_todo_count.done = planet_todo_count.done ? planet_todo_count.done:0;
    if($('planet_tab')) $('planet_tab').innerHTML += '

ToDo'+ planet_todo_count.todo + '/' + planet_todo_count.done + '
';
}
xAddEventListener(window,'load',planetTab);

function planetTabOff(){
    $Element('planetex_Tab').leave();
}

function planet_showTodoList(o){
    $ElementList('#planetex_Tab li').removeClass('active');
    $Element(o).parent().addClass('active');
    $ElementList('#planet_myTab li').removeClass('active');

    planet_reload_todo();
}

function planet_reload_todo(){
    $('commentList').innerHTML = '

TODO
<button type="button">TODO </button>
\n

\n

\n

DONE

\n

\n

\n\n';
    planet_getTodo();
    planet_getDone();
}

function planet_getTodo(page){
    $('todoList').innerHTML ='';
    _getPlanetTagSeachResult('todo',page,result_planet_getTodo);
}

function planet_getDone(page){
    $('doneList').innerHTML ='';
    _getPlanetTagSeachResult('done',page,result_planet_getDone);
}

function _getPlanetTagSeachResult(tag,page,func){
    var response_tags = new Array('error','message','contentList','pageNavigation');
    exec_xml('planet','dispPlanetContentTagSearch',{keyword:tag,page:page,mid:current_mid},func,response_tags);
}

function result_planet_getTodo(ret_obj,response_tags, params, fo_obj) {

    if(ret_obj['error'] == 0 && ret_obj.contentList){
        var o = new Array();
        var it = new Array();
        var items = ret_obj['contentList']['item'];

        if(typeof(items[0]) == 'undefined'){
            it[0] = items;
        }else{
            it = items;
        }

        o.push('
');
        for(var i=0,c=it.length;i<c;i++){

            it[i]['regdate'] += '';
            it[i]['regdate'] = it[i]['regdate'].substr(0,4) + '/' + it[i]['regdate'].substr(4,2) + '/' + it[i]['regdate'].substr(6,2);

            var tag = $A();
            if(typeof(it[i]['tag_list']['item'])=='string'){
                tag.push(it[i]['tag_list']['item']);
            }else{
                tag = $A(it[i]['tag_list']['item']);
            }

            tag = tag.filter(function(v){return !/todo/i.test(v);});
            tag.push('done');
            tag = tag.$value().join(',');

            o.push('<input type="hidden" id="tag:'+it[i]['document_srl']+'"  value="'+tag+'" />
');
			o.push(it[i]['content']);
			o.push('<button type="button" id="document_srl:'+it[i]['document_srl']+'"  onclick="planet_todo_setDone(this)">DONE</button>');
			o.push('');
			o.push(it[i]['regdate']);
			o.push('');
            o.push("
\n");
        }

        o.push('
');
        o.push('');

        $('todoList').innerHTML = o.join('');

        var pageNavigation = ret_obj['pageNavigation'];
        $('planet_todo_count').innerHTML = pageNavigation.total_count ? pageNavigation.total_count : 0;

        if(pageNavigation.total_page > 1){

            var str = "";
            if(pageNavigation.first_page>1) str += 'Prev';

            for(var i=pageNavigation.first_page;i<=pageNavigation.page_count;i++){
                if(i== pageNavigation.cur_page){
                    str += ""+i+"";
                }else{
                    str += ''+ i +'';
                }
            }

            if(pageNavigation.total_page != pageNavigation.last_page) str += 'next';
            $('todoList_page').innerHTML = str;
        }
        window.location.href="#planet_tab";
    }else{
        $('planet_todo_count').innerHTML = 0;
    }
}

function result_planet_getDone(ret_obj,response_tags, params, fo_obj) {

    if(ret_obj['error'] == 0 && ret_obj.contentList){
        var o = new Array();
        var it = new Array();
        var items = ret_obj['contentList']['item'];

        if(typeof(items[0]) == 'undefined'){
            it[0] = items;
        }else{
            it = items;
        }

        o.push('
');
        for(var i=0,c=it.length;i<c;i++){

            it[i]['regdate'] += '';
            it[i]['regdate'] = it[i]['regdate'].substr(0,4) + '/' + it[i]['regdate'].substr(4,2) + '/' + it[i]['regdate'].substr(6,2);

            var tag = $A();
            if(typeof(it[i]['tag_list']['item'])=='string'){
                tag.push(it[i]['tag_list']['item']);
            }else{
                tag = $A(it[i]['tag_list']['item']);
            }

            tag = tag.filter(function(v){return !/done/i.test(v);});
            tag.push('todo');
            tag = tag.$value().join(',');

            o.push('<input type="hidden" id="tag:'+it[i]['document_srl']+'"  value="'+tag+'" />
');
			o.push(it[i]['content']);
			o.push('<button type="button" id="document_srl:'+it[i]['document_srl']+'" onclick="planet_todo_setDone(this)">REDO</button>');
			o.push('<button type="button" onclick="planet_todo_setDel('+it[i]['document_srl']+')">Delete</button>');
            o.push("
\n");
        }

        o.push('
');
        o.push('');

        $('doneList').innerHTML = o.join('');

        var pageNavigation = ret_obj['pageNavigation'];
        $('planet_done_count').innerHTML = pageNavigation.total_count ? pageNavigation.total_count : 0;

        if(pageNavigation.total_page > 1){
            var str = "";

            if(pageNavigation.first_page>1) str += 'Prev';

            for(var i=pageNavigation.first_page;i<=pageNavigation.page_count;i++){
                if(i== pageNavigation.cur_page){
                    str += ""+i+"";
                }else{
                    str += ''+ i +'';
                }
            }

            if(pageNavigation.total_page != pageNavigation.last_page) str += 'next';
            $('doneList_page').innerHTML = str;
        }
        window.location.href="#planet_tab";
    }else{
        $('planet_done_count').innerHTML = 0;
    }
}

function planet_todo_setDone(o){
    var document_srl = o.id.replace(/.*:/,'');
    var tag = $('tag:'+document_srl).value;
    var params = {};
    params['document_srl'] = document_srl;
    params['planet_content_tag'] = tag;

    exec_xml('planet','procPlanetContentTagModify',params,planet_reload_todo);
    return false;
}

function planet_todo_setDel(document_srl){
//    var tag = $A($('document_srl:'+document_srl).value.split(','));
    var tag = $A($('tag:'+document_srl).value.split(','));

    tag = tag.filter(function(v){return !/todo/i.test(v);});
    tag.push('hide');
    tag = tag.$value().join(',');

    var params = {};
    params['document_srl'] = document_srl;
    params['planet_content_tag'] = tag;

    exec_xml('planet','procPlanetContentTagModify',params,planet_reload_todo);
    return false;
}

function showWritePostTodo(tag){
    tag = tag||'todo';
    $Element($('writePostForm').about_tag).hide();
    $Element($('writePostForm').content_tag).show();
    $('writePostForm').content_tag.value = tag;
    showWritePost();
}
<|endoftext|>


<commit_before>define([
  'underscore',
  'backbone'
], function(_, Backbone) {

  var initialize = Backbone.View.initialize;
  Backbone.View.prototype.initialize = function(){
    if (this.events) this.events = this.mapEvents(this.events);
    this.refreshElements();
    initialize.apply(this, arguments);
  }

  _.extend(Backbone.View.prototype, {

    // Convention based event binding
    mapEvents: function(events){
      var eventStack = {};
      _.each(events, function(event, object){
        _.extend(eventStack, this._formatElementEvents(object, event));
      }, this);

      return eventStack;
    },

    // Util to get element jQuery object
    $get: function (element) {
      if (!element) return $(this.el);
      this._ensureElementExist(element);

      return $(this.el).find(this.elements[element]);
    },

    // Set cached version of elements jQuery objects
    refreshElements: function(elements){
      elements = elements || this.elements;
      for (var element in elements) {
        this['$' + element] = $(this.el).find(this.elements[element]);
      }
    },

    isElement: function(element){
      if (element === '') return true;
      return (this.elements) && (this.elements[element]);
    },

    _formatElementEvents: function(element, eventString){
      this._ensureElementExist(element);
      var events = eventString.split(' '),
          eventStack = {};

      _.each(events, function(event, index){

        this._pushFormattedEvent(eventStack, element, event);

      }, this);

      return eventStack;
    },

    _pushFormattedEvent: function(stack, element, event){
      var selector = this._getElementSelector(element),
          key = event + (selector === '') ? '' : ' ' + selector;

      stack[key] = _getEventMethod(element, event);
      return stack;
    },

    _getElementSelector: function(element){
      return (element === '')
          ? ''
          : this.elements[element];
    },

    _ensureElementExist: function(element){
      if (!this.isElement(element)) {
        throw "Element '" + element + "' does not exist.";
      }
    }

  });

  //|---------|
  //| HELPERS |
  //|---------|

  function _getEventMethod(){
    return _.toArray(arguments).join('_');
  }

  return Backbone;

});<commit_msg>Fixed bug with selector buiding.<commit_after>define([
  'underscore',
  'backbone'
], function(_, Backbone) {

  var initialize = Backbone.View.prototype.initialize;

  _.extend(Backbone.View.prototype, {

    initialize: function(){
      if (this.events) this.events = this.mapEvents(this.events);
      this.refreshElements();
      initialize.apply(this, arguments);
    },

    // Convention based event binding
    mapEvents: function(elements){
      var eventStack = {};
      _.each(elements, function(events, element){
        _.extend(eventStack, this._formatElementEvents(element, events));
      }, this);

      return eventStack;
    },

    // Util to get element jQuery object
    $get: function (element) {
      if (!element) return $(this.el);
      this._ensureElementExist(element);

      return $(this.el).find(this.elements[element]);
    },

    // Set cached version of elements jQuery objects
    refreshElements: function(elements){
      elements = elements || this.elements;
      for (var element in elements) {
        this['$' + element] = $(this.el).find(this.elements[element]);
      }
    },

    isElement: function(element){
      if (element === '') return true;
      return (this.elements) && (this.elements[element]);
    },

    _formatElementEvents: function(element, eventString){
      this._ensureElementExist(element);
      var events = eventString.split(' '),
          eventStack = {};

      _.each(events, function(event, index){

        this._pushFormattedEvent(eventStack, element, event);

      }, this);

      return eventStack;
    },

    _pushFormattedEvent: function(stack, element, event){
      var selector = this._getElementSelector(element),
          key = event + ((selector === '') ? '' : (' ' + selector));

      stack[key] = _getEventMethod(element, event);
      return stack;
    },

    _getElementSelector: function(element){
      return (element === '')
          ? ''
          : this.elements[element];
    },

    _ensureElementExist: function(element){
      if (!this.isElement(element)) {
        throw "Element '" + element + "' does not exist.";
      }
    }

  });

  //|---------|
  //| HELPERS |
  //|---------|

  function _getEventMethod(){
    // Remove empty then join with underscore. Replace colon of attribute with underscore
    return _.compact(_.toArray(arguments)).join('_').replace(':', '_');
  }

  return Backbone;

});<|endoftext|>