<commit_before>import { computed } from '@ember/object';
import { inject as service } from '@ember/service';
import Component from '@ember/component';

export default Component.extend({
  classNames: ['exercise-workspace'],
  persistirSolucionEnURL: false,
  showCode: false,
  blocksGallery: service(),
  cargando: true,
  canvasWidth: 0,
  canvasHeight: 0,

  debeMostrarPasoHabilitado: computed('debeMostrarPasoHabilitado', function () {
    return this.get('model.debugging');
  }),

  estaPausadoEnUnBreackpoint: computed('pausadoEnBreakpoint', function () {
    return this.get('pausadoEnBreakpoint');
  }),

  modoLecturaSimple: computed('model', function () {
    return this.get('model.grupo.capitulo.libro.modoLecturaSimple');
  }),

  debeMostarReiniciar: computed('ejecutando', 'terminoDeEjecutar', function () {
    return this.get('ejecutando') || this.get('terminoDeEjecutar');
  }),

  didInsertElement() {
    this.blocksGallery.start();
  },

  setPilasBlockly(pilasBlockly) {
    this.set('pilasBlockly', pilasBlockly);
  },

  actions: {

    onReady(pilas) {
      if (this.onReady) {
        this.onReady(pilas)
      }
      this.set('cargando', false);

      if (this.modoLecturaSimple) {
        pilas.cambiarAModoDeLecturaSimple();
      }
    },

    hideScene() {
      let canvas = document.getElementsByClassName("pilas-canvas")[0];
      let elmnt = document.getElementById("draggable");
      elmnt.style.display = 'none';
      canvas.style.display = 'none';
    },

    showScene() {
      let canvas = document.getElementsByClassName("pilas-canvas")[0];
      let elmnt = document.getElementById("draggable");
      elmnt.style.display = 'block';
      canvas.style.display = 'block';
    },

    changeScreenMode() {
      this.set("shouldUseFloatingMode", !this.get("shouldUseFloatingMode"));
      this.send("updateBlockyWorkspaceBounds");

      if (this.get("shouldUseFloatingMode")) {
        this.send("makeDraggable");
        this.send("hideScene");
      }

      else {
        this.send("showScene");
        this.send("makeNotDraggable");
      }

    },

    makeDraggable() {
      let elmnt = document.getElementById("draggable");
      let canvas = document.getElementsByClassName("pilas-canvas")[0];
      let exerciseCard = document.getElementsByClassName("exercise-card")[0];
      let blocklyFlyout = document.getElementsByClassName("blocklyFlyout")[0];

      var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;

      canvas.style.height = 240 + "px";
      canvas.style.width = 210 + "px";
      exerciseCard.style.height = 240 + "px";
      exerciseCard.style.width = 210 + "px";

      elmnt.style.top = (blocklyFlyout.height.baseVal.value - 50) + "px";
      elmnt.style.left = (blocklyFlyout.width.baseVal.value + 25) + "px";
      elmnt.style.position = "fixed";

      elmnt.onmousedown = onMouseDown;
      elmnt.ontouchstart = onTouchStart;

      function onMouseDown(e) {
        e = e || window.event;
        e.preventDefault();

        // get the mouse cursor position at startup:
        pos3 = e.clientX;
        pos4 = e.clientY;

        document.onmouseup = onMouseUp;
        // call a function whenever the cursor moves:
        document.onmousemove = onMouseMove;
      }

      function onTouchStart(e) {
        e = e || window.event;
        pos3 = e.touches[0].pageX;
        pos4 = e.touches[0].pageY;

        elmnt.ontouchend = onTouchEnd;
        // call a function whenever the cursor moves:
        elmnt.ontouchmove = onTouchMove;
      }

      function onMouseMove(e) {
        e = e || window.event;
        e.preventDefault();

        // calculate the new cursor position:
        pos1 = pos3 - e.clientX;
        pos2 = pos4 - e.clientY;
        pos3 = e.clientX;
        pos4 = e.clientY;

        // set the element's new position:
        elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
        elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
      }

      function onTouchMove(e) {
        e = e || window.event;
        e.preventDefault();

        // calculate the new cursor position:
        pos1 = pos3 - e.touches[0].pageX;
        pos2 = pos4 - e.touches[0].pageY;
        pos3 = e.touches[0].pageX;
        pos4 = e.touches[0].pageY;

        // set the element's new position:
        elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
        elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
      }

      function onMouseUp() {
        // stop moving when mouse button is released:
        document.onmouseup = null;
        document.onmousemove = null;
      }

      function onTouchEnd() {
        // stop moving when mouse button is released:
        elmnt.ontouchend = null;
        elmnt.ontouchmove = null;
      }

    },

    makeNotDraggable() {
      let elmnt = document.getElementById("draggable");
      let canvas = document.getElementsByClassName("pilas-canvas")[0];
      let exerciseCard = document.getElementsByClassName("exercise-card")[0];
      elmnt.style.position = "inherit";
      canvas.style.width = "";
      canvas.style.height = "";
      exerciseCard.style.width = "";
      exerciseCard.style.height = "";
    },

    updateBlockyWorkspaceBounds() {
      // This make blocky workspaces render correctly after container resize.
      // This is a WORKAROUND, i cant get it work without this.
      Blockly.mainWorkspace.getAllBlocks()[0].select()
      Blockly.mainWorkspace.getAllBlocks()[0].unselect()
    },

    ejecutar(pasoAPaso = false) {
      this.pilasBlockly.send('ejecutar', pasoAPaso);
      this.send("showScene");
    },

    step() {
      this.pilasBlockly.send('step');
      this.send("showScene");
    },

    reiniciar() {
      this.pilasBlockly.send('reiniciar');
    },

  }

});
<commit_msg>miniature initial appearance and position<commit_after>import { computed } from '@ember/object';
import { inject as service } from '@ember/service';
import Component from '@ember/component';

export default Component.extend({
  classNames: ['exercise-workspace'],
  persistirSolucionEnURL: false,
  showCode: false,
  blocksGallery: service(),
  cargando: true,
  canvasWidth: 0,
  canvasHeight: 0,

  debeMostrarPasoHabilitado: computed('debeMostrarPasoHabilitado', function () {
    return this.get('model.debugging');
  }),

  estaPausadoEnUnBreackpoint: computed('pausadoEnBreakpoint', function () {
    return this.get('pausadoEnBreakpoint');
  }),

  modoLecturaSimple: computed('model', function () {
    return this.get('model.grupo.capitulo.libro.modoLecturaSimple');
  }),

  debeMostarReiniciar: computed('ejecutando', 'terminoDeEjecutar', function () {
    return this.get('ejecutando') || this.get('terminoDeEjecutar');
  }),

  didInsertElement() {
    this.blocksGallery.start();
  },

  setPilasBlockly(pilasBlockly) {
    this.set('pilasBlockly', pilasBlockly);
  },

  actions: {

    onReady(pilas) {
      if (this.onReady) {
        this.onReady(pilas)
      }
      this.set('cargando', false);

      if (this.modoLecturaSimple) {
        pilas.cambiarAModoDeLecturaSimple();
      }
    },

    hideScene() {
      let canvas = document.getElementsByClassName("pilas-canvas")[0];
      let elmnt = document.getElementById("draggable");
      elmnt.style.display = 'none';
      canvas.style.display = 'none';
    },

    showScene() {
      let canvas = document.getElementsByClassName("pilas-canvas")[0];
      let elmnt = document.getElementById("draggable");
      elmnt.style.display = 'block';
      canvas.style.display = 'block';
    },

    changeScreenMode() {
      this.set("shouldUseFloatingMode", !this.get("shouldUseFloatingMode"));
      this.send("updateBlockyWorkspaceBounds");

      this.send("showScene");
      if (this.get("shouldUseFloatingMode"))
        this.send("makeDraggable");
      else
        this.send("makeNotDraggable");

    },

    makeDraggable() {
      let elmnt = document.getElementById("draggable");
      let canvas = document.getElementsByClassName("pilas-canvas")[0];
      let exerciseCard = document.getElementsByClassName("exercise-card")[0];
      let pilasBlockly = document.getElementsByClassName("pilas-blockly")[0].getBoundingClientRect();

      var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;

      const miniature = {height: 240, width: 210}

      canvas.style.height = miniature.height + "px";
      canvas.style.width = miniature.width + "px";
      exerciseCard.style.height = miniature.height + "px";
      exerciseCard.style.width = miniature.width + "px";

      elmnt.style.top = (pilasBlockly.bottom - miniature.height) + "px";
      elmnt.style.left = (pilasBlockly.left + 15) + "px";
      elmnt.style.position = "fixed";

      elmnt.onmousedown = onMouseDown;
      elmnt.ontouchstart = onTouchStart;

      function onMouseDown(e) {
        e = e || window.event;
        e.preventDefault();

        // get the mouse cursor position at startup:
        pos3 = e.clientX;
        pos4 = e.clientY;

        document.onmouseup = onMouseUp;
        // call a function whenever the cursor moves:
        document.onmousemove = onMouseMove;
      }

      function onTouchStart(e) {
        e = e || window.event;
        pos3 = e.touches[0].pageX;
        pos4 = e.touches[0].pageY;

        elmnt.ontouchend = onTouchEnd;
        // call a function whenever the cursor moves:
        elmnt.ontouchmove = onTouchMove;
      }

      function onMouseMove(e) {
        e = e || window.event;
        e.preventDefault();

        // calculate the new cursor position:
        pos1 = pos3 - e.clientX;
        pos2 = pos4 - e.clientY;
        pos3 = e.clientX;
        pos4 = e.clientY;

        // set the element's new position:
        elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
        elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
      }

      function onTouchMove(e) {
        e = e || window.event;
        e.preventDefault();

        // calculate the new cursor position:
        pos1 = pos3 - e.touches[0].pageX;
        pos2 = pos4 - e.touches[0].pageY;
        pos3 = e.touches[0].pageX;
        pos4 = e.touches[0].pageY;

        // set the element's new position:
        elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
        elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
      }

      function onMouseUp() {
        // stop moving when mouse button is released:
        document.onmouseup = null;
        document.onmousemove = null;
      }

      function onTouchEnd() {
        // stop moving when mouse button is released:
        elmnt.ontouchend = null;
        elmnt.ontouchmove = null;
      }

    },

    makeNotDraggable() {
      let elmnt = document.getElementById("draggable");
      let canvas = document.getElementsByClassName("pilas-canvas")[0];
      let exerciseCard = document.getElementsByClassName("exercise-card")[0];
      elmnt.style.position = "inherit";
      canvas.style.width = "";
      canvas.style.height = "";
      exerciseCard.style.width = "";
      exerciseCard.style.height = "";
    },

    updateBlockyWorkspaceBounds() {
      // This make blocky workspaces render correctly after container resize.
      // This is a WORKAROUND, i cant get it work without this.
      Blockly.mainWorkspace.getAllBlocks()[0].select()
      Blockly.mainWorkspace.getAllBlocks()[0].unselect()
    },

    ejecutar(pasoAPaso = false) {
      this.pilasBlockly.send('ejecutar', pasoAPaso);
      this.send("showScene");
    },

    step() {
      this.pilasBlockly.send('step');
      this.send("showScene");
    },

    reiniciar() {
      this.pilasBlockly.send('reiniciar');
    },

  }

});
<|endoftext|>


<commit_before>const MBContract          = require('./mb_contract');
const MBDisplayCurrencies = require('./mb_currency');
const MBDefaults          = require('./mb_defaults');
const MBTradingEvents     = require('./mb_event');
const MBPrice             = require('./mb_price');
const MBProcess           = require('./mb_process');
const cleanupChart        = require('../trade/charts/webtrader_chart').cleanupChart;
const BinaryPjax          = require('../../base/binary_pjax');
const Client              = require('../../base/client');
const BinarySocket        = require('../../base/socket');
const jpClient            = require('../../common/country_base').jpClient;
const JapanPortfolio      = require('../../japan/portfolio');
const localize            = require('../../../_common/localize').localize;
const State               = require('../../../_common/storage').State;
const urlFor              = require('../../../_common/url').urlFor;

const MBTradePage = (() => {
    let events_initialized = 0;
    State.remove('is_mb_trading');

    const onLoad = () => {
        State.set('is_mb_trading', true);
        BinarySocket.wait('authorize').then(init);
    };

    const init = () => {
        if (Client.get('landing_company_shortcode') === 'malta') {
            BinaryPjax.load(urlFor('trading'));
            return;
        }
        if (jpClient()) {
            disableTrading();
            $('#panel').remove();
        } else {
            MBDefaults.set('disable_trading', 0);
            $('#ja-panel').remove();
        }

        if (events_initialized === 0) {
            events_initialized = 1;
            MBTradingEvents.init();
        }

        BinarySocket.send({ payout_currencies: 1 }).then(() => {
            MBDisplayCurrencies();
            MBProcess.getSymbols();
        });

        $('#tab_portfolio').find('a').text(localize('Portfolio'));
        $('#tab_graph').find('a').text(localize('Chart'));
        $('#tab_explanation').find('a').text(localize('Explanation'));
        State.set('is_chart_allowed', true);
        State.set('ViewPopup.onDisplayed', MBPrice.hidePriceOverlay);
        $('.container').css('max-width', '1200px');
    };

    const disableTrading = () => {
        MBDefaults.set('disable_trading', 1);
        $('#allow').removeClass('selected');
        $('#disallow').addClass('selected');
    };

    const reload = () => {
        window.location.reload();
    };

    const onUnload = () => {
        cleanupChart();
        State.set('is_chart_allowed', false);
        JapanPortfolio.hide();
        State.remove('is_mb_trading');
        events_initialized = 0;
        MBContract.onUnload();
        MBPrice.onUnload();
        MBProcess.onUnload();
        BinarySocket.clear('active_symbols');
        State.remove('ViewPopup.onDisplayed');
        $('.container').css('max-width', '');
    };

    const onDisconnect = () => {
        MBPrice.showPriceOverlay();
        cleanupChart();
        onLoad();
    };

    return {
        onLoad,
        reload,
        onUnload,
        onDisconnect,
    };
})();

module.exports = MBTradePage;
<commit_msg>redirect iom too<commit_after>const MBContract          = require('./mb_contract');
const MBDisplayCurrencies = require('./mb_currency');
const MBDefaults          = require('./mb_defaults');
const MBTradingEvents     = require('./mb_event');
const MBPrice             = require('./mb_price');
const MBProcess           = require('./mb_process');
const cleanupChart        = require('../trade/charts/webtrader_chart').cleanupChart;
const BinaryPjax          = require('../../base/binary_pjax');
const Client              = require('../../base/client');
const BinarySocket        = require('../../base/socket');
const jpClient            = require('../../common/country_base').jpClient;
const JapanPortfolio      = require('../../japan/portfolio');
const localize            = require('../../../_common/localize').localize;
const State               = require('../../../_common/storage').State;
const urlFor              = require('../../../_common/url').urlFor;

const MBTradePage = (() => {
    let events_initialized = 0;
    State.remove('is_mb_trading');

    const onLoad = () => {
        State.set('is_mb_trading', true);
        BinarySocket.wait('authorize').then(init);
    };

    const init = () => {
        if (/^(malta|iom)$/.test(Client.get('landing_company_shortcode'))) {
            BinaryPjax.load(urlFor('trading'));
            return;
        }
        if (jpClient()) {
            disableTrading();
            $('#panel').remove();
        } else {
            MBDefaults.set('disable_trading', 0);
            $('#ja-panel').remove();
        }

        if (events_initialized === 0) {
            events_initialized = 1;
            MBTradingEvents.init();
        }

        BinarySocket.send({ payout_currencies: 1 }).then(() => {
            MBDisplayCurrencies();
            MBProcess.getSymbols();
        });

        $('#tab_portfolio').find('a').text(localize('Portfolio'));
        $('#tab_graph').find('a').text(localize('Chart'));
        $('#tab_explanation').find('a').text(localize('Explanation'));
        State.set('is_chart_allowed', true);
        State.set('ViewPopup.onDisplayed', MBPrice.hidePriceOverlay);
        $('.container').css('max-width', '1200px');
    };

    const disableTrading = () => {
        MBDefaults.set('disable_trading', 1);
        $('#allow').removeClass('selected');
        $('#disallow').addClass('selected');
    };

    const reload = () => {
        window.location.reload();
    };

    const onUnload = () => {
        cleanupChart();
        State.set('is_chart_allowed', false);
        JapanPortfolio.hide();
        State.remove('is_mb_trading');
        events_initialized = 0;
        MBContract.onUnload();
        MBPrice.onUnload();
        MBProcess.onUnload();
        BinarySocket.clear('active_symbols');
        State.remove('ViewPopup.onDisplayed');
        $('.container').css('max-width', '');
    };

    const onDisconnect = () => {
        MBPrice.showPriceOverlay();
        cleanupChart();
        onLoad();
    };

    return {
        onLoad,
        reload,
        onUnload,
        onDisconnect,
    };
})();

module.exports = MBTradePage;
<|endoftext|>


<commit_before>// Copyright (c) Visual Data Solutions, Inc. All rights reserved. This source code is distributed under the terms of the MIT license. See LICENSE file in the project root for complete license information.

var extend = require('./extend.js');

var extendProperty = function(base, mixin, p) {
    "use strict";

    if (typeof mixin[p] === 'function') {
        base[p] = function() {
            return mixin[p].apply(this, arguments);
        }
    }
    else if (p != 'mixinName' && p != 'mixins') {
        base[p] = mixin[p];
    }
};

var extendOverrides = function(obj, overrides) {

    for(var p in overrides) {
        var func = overrides[p];
        var _super = obj[p];

        var self = this;

        (function(fnc, spr) {
            obj[p] = function () {

                [].unshift.call(arguments, spr.bind(this));
                return fnc.apply(this, arguments);
            }
        })(func, _super);
    }
};

var extendProperties = function(base, mixin) {
    "use strict";

    for(var p in mixin) {
        if (mixin.hasOwnProperty(p)) {

            if (p === 'override') {
                extendOverrides(base, mixin[p]);
            }
            else {
                var prop = mixin[p];
                extendProperty(base, mixin, p);
            }
        }
    }
};

var extendMixin = function(base, mixin) {
    "use strict";

    if (!base)
        throw new Error('base object must be supplied.');

    if (!mixin)
        throw new Error('mixin object must be supplied.');

    extendProperties(base, mixin);
};

//create a constructor that will create an object that will combine a list of mixins
var makeCtor = function(superClass) {
    "use strict";

    var addMixins = function(obj, mixins) {

        mixins.forEach( function(mixin) {
            if (mixin.mixinName) {
                obj.mixins[mixin.mixinName] = mixin;
            }
            else if (mixin.className) {
                obj.mixins[mixin.className] = mixin;
            }
            if (mixin.mixins) {
                addMixins(obj, mixin.mixins);
            }
            extendMixin(obj, mixin);
        });
    };

    var NewClass = function(mixins) {

        var self = {};

        self.mixins = {};

        addMixins(self, mixins);

        return self;
    };

    NewClass.mixins = [];
    NewClass.static_mixins = [];

    //initialize the constructor with all mixins from the super class
    if (superClass.mixins) {
        superClass.mixins.forEach( function(mixin) {
            NewClass.mixins.push(mixin);
        });
    }

    if (superClass.static_mixins) {
        superClass.static_mixins.forEach( function(mixin) {
            NewClass.static_mixins.push(mixin);

            extend(newClass, mixin);
        });
    }
    NewClass.SuperClass = superClass;

    return NewClass;
};

var CoreObject = {

    extend: function(mixin_in, mixin_static) {
        "use strict";

        var NewClass = makeCtor(this);

        if (mixin_in) {
            if (mixin_in.mixins) {
                mixin_in.mixins.forEach( function(m) {
                    NewClass.mixins.push(m);
                }, this);
                delete mixin_in.mixins;
            }
            NewClass.mixins.push(mixin_in);
        }

        if (mixin_static) {
            extend(NewClass, mixin_static);
        }

        var realClass = function(mixin) {

            var obj;

            var mixins = NewClass.mixins.slice(0);
            obj = new NewClass(mixins);
            obj.classType = this.classType;

            if (obj.mixins) {
                for( var p in obj.mixins) {
                    if (obj.mixins.hasOwnProperty(p)) {
                        var m = obj.mixins[p];
                        if (m.init)
                        {
                            if (!m.className || m.className != obj.className) {
                                m.init.call(obj, mixin);
                            }
                        }
                    }
                }
            }
            if (obj.init) {
                obj.init(mixin);
            }
            return obj;
        };

        extend(realClass, NewClass);

        realClass.extend = this.extend;

        //realClass.prototype.constructor = realClass;
        realClass.prototype.classType = realClass;
        return realClass;
    }
};

module.exports = CoreObject;
<commit_msg>publish<commit_after>// Copyright (c) Visual Data Solutions, Inc. All rights reserved. This source code is distributed under the terms of the MIT license. See LICENSE file in the project root for complete license information.

var extend = require('./extend.js');

var extendProperty = function(base, mixin, p) {
    "use strict";

    if (typeof mixin[p] === 'function') {
        base[p] = function() {
            return mixin[p].apply(this, arguments);
        }
    }
    else if (p != 'mixinName' && p != 'mixins') {
        base[p] = mixin[p];
    }
};

var extendOverrides = function(obj, overrides) {

    for(var p in overrides) {
        var func = overrides[p];
        var _super = obj[p];

        var self = this;

        (function(fnc, spr) {
            obj[p] = function () {

                [].unshift.call(arguments, spr.bind(this));
                return fnc.apply(this, arguments);
            }
        })(func, _super);
    }
};

var extendProperties = function(base, mixin) {
    "use strict";

    for(var p in mixin) {
        if (mixin.hasOwnProperty(p)) {

            if (p === 'override') {
                extendOverrides(base, mixin[p]);
            }
            else {
                var prop = mixin[p];
                extendProperty(base, mixin, p);
            }
        }
    }
};

var extendMixin = function(base, mixin) {
    "use strict";

    if (!base)
        throw new Error('base object must be supplied.');

    if (!mixin)
        throw new Error('mixin object must be supplied.');

    extendProperties(base, mixin);
};

//create a constructor that will create an object that will combine a list of mixins
var makeCtor = function(superClass) {
    "use strict";

    var addMixins = function(obj, mixins) {

        mixins.forEach( function(mixin) {
            if (mixin.mixinName) {
                obj.mixins[mixin.mixinName] = mixin;
            }
            else if (mixin.className) {
                obj.mixins[mixin.className] = mixin;
            }
            if (mixin.mixins) {
                addMixins(obj, mixin.mixins);
            }
            extendMixin(obj, mixin);
        });
    };

    var NewClass = function(mixins) {

        var self = {};

        self.mixins = {};

        addMixins(self, mixins);

        return self;
    };

    NewClass.mixins = [];
    NewClass.static_mixins = [];

    //initialize the constructor with all mixins from the super class
    if (superClass.mixins) {
        superClass.mixins.forEach( function(mixin) {
            NewClass.mixins.push(mixin);
        });
    }

    if (superClass.static_mixins) {
        superClass.static_mixins.forEach( function(mixin) {
            NewClass.static_mixins.push(mixin);

            extend(newClass, mixin);
        });
    }
    NewClass.SuperClass = superClass;

    return NewClass;
};

var CoreObject = {

    extend: function(mixin_in, mixin_static) {
        "use strict";

        var NewClass = makeCtor(this);

        if (mixin_in) {
            if (mixin_in.mixins) {
                mixin_in.mixins.forEach( function(m) {
                    NewClass.mixins.push(m);
                }, this);
                delete mixin_in.mixins;
            }
            NewClass.mixins.push(mixin_in);
        }

        if (mixin_static) {
            extend(NewClass, mixin_static);
        }

        var realClass = function(mixin) {

            var obj;

            var mixins = NewClass.mixins.slice(0);
            obj = new NewClass(mixins);
            obj.classType = this.classType;

            if (obj.mixins) {
                for( var p in obj.mixins) {
                    if (obj.mixins.hasOwnProperty(p)) {
                        var m = obj.mixins[p];
                        if (m.init)
                        {
                            if (!m.className || m.className != obj.className) {
                                m.init.call(obj, mixin);
                            }
                        }
                    }
                }
            }
            if (obj.init) {
                obj.init(mixin);
            }
            return obj;
        };

        extend(realClass, NewClass);

        realClass.extend = this.extend;

        //realClass.prototype.constructor = realClass;
        realClass.prototype.classType = realClass;
        return realClass;
    }
};

module.exports = CoreObject;
<|endoftext|>


<commit_before>function CookieStore (name, minCustomers, maxCustomers, avgCookiesPerCust) {
    this.name = name;
    this.minCustomers = minCustomers;
    this.maxCustomers = maxCustomers;
    this.avgCookiesPerCust = avgCookiesPerCust;
    this.elementId = this.name; //TO DO: replace constructor instances of this.elementId with this.name
    this.staticCookies = [];
    this.cookieSum = 0;
    this.addToDom();
};

CookieStore.prototype.randomCust = function () {
    return (Math.floor(Math.random() * (this.maxCustomers - this.minCustomers + 1)) + this.minCustomers);
};

CookieStore.prototype.avgCookiesPerHour = function () {
    return this.randomCust() * this.avgCookiesPerCust;
};

CookieStore.prototype.cookieDataArray = function () {
    for (var i = 0; i < 15; i++){
        this.staticCookies.push(Math.floor(this.avgCookiesPerHour()));
    }
};

//Cookie tosser requirement formula
CookieStore.prototype.cookieTossers = function (input) {
    if (input < 40){
        return 2;
    }
    else if (input % 20 == 0){
        return input / 20;
    }
    else {
        return Math.floor(input / 20) + 1;
    }
};

//Method to make new table element with optional id
CookieStore.prototype.makeTableElement = function (elementName, elementType, newElementId) {
    var container = document.getElementById(elementName);
    var createNewElement = document.createElement(elementType);
    createNewElement.id = newElementId;
    container.appendChild( createNewElement );
};

//Method to make new TD element with inner HTML content **DOESNT WORK YET**
CookieStore.prototype.makeHTMLelement = function (container,elementType, innerHTML, tosser) {
    if (tosser) {
        var createTosserElement = document.createElement( elementType );
        createTosserElement.innerHTML = innerHTML;
        container.appendChild( createTosserElement );
    }
    else {
        var createNewElement = document.createElement(elementType);
        createNewElement.innerHTML = innerHTML;
        container.appendChild( createNewElement );
    }
};

CookieStore.prototype.addToDom = function () {
    this.cookieDataArray();
    //Create TR element with id as this.elementId
    this.makeTableElement('masterTable','tr',this.elementId);
    //cookietosser code - create same code as above in cookieTosser table
    this.makeTableElement('cookieTossers','tr',this.elementId + 'tosser','');

    //Create TD Element with location name
    var container = document.getElementById(this.elementId);
    this.makeHTMLelement(container, 'td','' + this.name + '');

    //cookietosser code - apply the same code to the "elementID+tosser" element
    var tosserContainer = document.getElementById(this.elementId + 'tosser');
    this.makeHTMLelement(tosserContainer,'td','' + this.name + '', true);

    for (var i = 0; i < this.staticCookies.length; i++) { //populate table row with td elements containing each element from staticCookies array
        this.makeHTMLelement(container,'td',this.staticCookies[i]);
        //cookietosser code- does the same as above, but numbers are run through the cookieTossers method
        this.makeHTMLelement(tosserContainer,'td',this.cookieTossers(this.staticCookies[i]),true);
    }
    //calculate total
    for (var i = 0; i < this.staticCookies.length; i++){
        this.cookieSum = this.cookieSum + this.staticCookies[i];
    }
    this.makeHTMLelement(container,'td','' + this.cookieSum + '');
};

//create table headers populated with openHours elements
CookieStore.prototype.tableHeaders = function(){
    var openHours = ['6:00am','7:00am','8:00am','9:00am','10:00am','11:00am','12:00am','1:00pm','2:00pm','3:00pm','4:00pm','5:00pm','6:00pm','7:00pm','8:00pm', 'Total'];

    //create new row for main table, inserting before all other child elements
    var headers = document.getElementById('masterTable');
    var headerTableRow = document.createElement( 'tr' );
    headerTableRow.id = 'headerRow';
    headers.insertBefore(headerTableRow, headers.childNodes[0]);

    //create empty TH element
    var tableHeader = document.getElementById('headerRow');
    var createTableHead = document.createElement( 'th' );
    tableHeader.appendChild( createTableHead );

    //cookietosser code - create cookietosser headers
    var tosserHeaders = document.getElementById('cookieTossers');
    var headerTableRow = document.createElement( 'tr' );
    headerTableRow.id = 'tosserRow';
    tosserHeaders.insertBefore(headerTableRow, tosserHeaders.childNodes[0]);
    //create empty TH element
    var tosserHeader = document.getElementById('tosserRow');
    var createTosserHead = document.createElement( 'th' );
    tosserHeader.appendChild( createTosserHead );

    for (var i = 0; i < openHours.length; i++) {
        var createTableHead = document.createElement( 'th' );
        createTableHead.innerHTML = openHours[i];
        tableHeader.appendChild( createTableHead );
        //cookietosser code - nested if conditional to prevent cookietosser table from loading "Total" column
        if ( i < openHours.length - 1 ){
            var createTosserHead = document.createElement( 'th' );
            createTosserHead.innerHTML = openHours[i];
            tosserHeader.appendChild( createTosserHead );
        }
    }
}; // End of tableHeaders method

//Calculate total cookies in all stores
CookieStore.prototype.totalCookies = function () {

    //create new table row to display column totals
    var container = document.getElementById('masterTable');
    var newTableRow = document.createElement( 'tr' );
    newTableRow.id = 'totals' ;
    container.appendChild( newTableRow );

    //create blank table header
    container = document.getElementById( 'totals' );
    var totalTableHeader = document.createElement( 'th' );
    totalTableHeader.innerHTML = 'Totals';
    container.appendChild( totalTableHeader );

    for (var rowNumber = 0; rowNumber < cookieStoreArray[0].staticCookies.length; rowNumber++){
        var totalCookieTD = document.createElement( 'td' );
        var trackyMcVariable = 0;
        for (var colNumber = 0; colNumber < cookieStoreArray.length; colNumber++){
            trackyMcVariable += cookieStoreArray[colNumber].staticCookies[rowNumber];
        }
        totalCookieTD.innerHTML = '' + trackyMcVariable + '';
        container.appendChild( totalCookieTD );
    }
    //calculate cookie total per td
    var totalCounter = 0;
    for (var i = 0; i < cookieStoreArray.length; i++){ //TO DO: change length to be based on number of children of 'masterTable' element
        totalCounter = totalCounter + cookieStoreArray[i].cookieSum;
    }
    // var container = document.getElementById('total');
    var totalHeader = document.createElement('td');
    totalHeader.innerHTML = '' + totalCounter + '';
    container.appendChild( totalHeader );
};

var cookieStoreArray = [
    new CookieStore('PDX Airport', 23, 65, 6.3),
    new CookieStore('Pioneer Square', 3, 24, 1.2),
    new CookieStore('Powell\'s', 11, 38, 3.7),
    new CookieStore('St Johns', 20, 38, 2.3),
    new CookieStore('Waterfront', 2, 16, 4.6)
];
// cookieStoreArray[0].tableHeaders();
cookieStoreArray[0].totalCookies();
cookieStoreArray[0].tableHeaders();

//Form & Event Sorcery

var form = document.getElementById( 'store-entry' ); //.this referrs to form (html element that is listening )
form.addEventListener( 'submit', function(){
    event.preventDefault();

    //ALTERNATIVE WAY TO WRITE THIS PART
    // var name = event.target.storeName.value;
    // var minCustomers = parseInt(event.target.minCustomers.value);
    // var maxCustomers = parseInt(event.target.maxCustomers.value);
    // var avgCookiesPerCust = parseInt(event.target.avgCookies.value);
    // var newQuestion = new CookieStore (name, minCustomers, maxCustomers, avgCookiesPerCust);

    var removeTotal = document.getElementById( 'totals' );
    removeTotal.outerHTML = '';
    cookieStoreArray.push(new CookieStore ( this.storeName.value, parseInt(this.minCustomers.value), parseInt(this.maxCustomers.value), this.avgCookies.value));
    cookieStoreArray[0].totalCookies();
    // document.form.reset();   TO DO: MAKE THE TEXT FIELDS CLEAR ON SUBMIT

    //DEBUGGING HELPER GARBAGE
    // console.log('submitted store name is ' + this.storeName );
    // console.log('submitted mincustomers is ' + this.minCustomers );
    // console.log('submitted max customers is ' + this.maxCustomers.value );
    // console.log('submitted avg is ' + this.avgCookies.value );
});<commit_msg>begin redundnacy check for addToDom method<commit_after>function CookieStore (name, minCustomers, maxCustomers, avgCookiesPerCust) {
    this.name = name;
    this.minCustomers = minCustomers;
    this.maxCustomers = maxCustomers;
    this.avgCookiesPerCust = avgCookiesPerCust;
    this.elementId = this.name; //TO DO: replace constructor instances of this.elementId with this.name
    this.staticCookies = [];
    this.cookieSum = 0;
    this.addToDom();
};

CookieStore.prototype.randomCust = function () {
    return (Math.floor(Math.random() * (this.maxCustomers - this.minCustomers + 1)) + this.minCustomers);
};

CookieStore.prototype.avgCookiesPerHour = function () {
    return this.randomCust() * this.avgCookiesPerCust;
};

CookieStore.prototype.cookieDataArray = function () {
    for (var i = 0; i < 15; i++){
        this.staticCookies.push(Math.floor(this.avgCookiesPerHour()));
    }
};

//Cookie tosser requirement formula
CookieStore.prototype.cookieTossers = function (input) {
    if (input < 40){
        return 2;
    }
    else if (input % 20 == 0){
        return input / 20;
    }
    else {
        return Math.floor(input / 20) + 1;
    }
};

//Method to make new table element with optional id
CookieStore.prototype.makeTableElement = function (elementName, elementType, newElementId) {
    var container = document.getElementById(elementName);
    var createNewElement = document.createElement(elementType);
    createNewElement.id = newElementId;
    container.appendChild( createNewElement );
};

//Method to make new TD element with inner HTML content
CookieStore.prototype.makeHTMLelement = function (container,elementType, innerHTML, tosser) {
    if (tosser) {
        var createTosserElement = document.createElement( elementType );
        createTosserElement.innerHTML = innerHTML;
        container.appendChild( createTosserElement );
    }
    else {
        var createNewElement = document.createElement(elementType);
        createNewElement.innerHTML = innerHTML;
        container.appendChild( createNewElement );
    }
};

CookieStore.prototype.addToDom = function () {
    //check if store name is already present in master table
    for (var i = 1; i < document.getElementById('masterTable').children.length - 1; i++){
        if (this.name == document.getElementById('masterTable').children[i].id){
            console.log('is ' + this.name + 'equal to ' + document.getElementById('masterTable').children[i].id + ' ?');
            alert ('REDUNDANT NAME DETECTED');
            break;
        }
    }

    this.cookieDataArray();
    //Create TR element with id as this.elementId
    this.makeTableElement('masterTable','tr',this.elementId);
    //cookietosser code - create same code as above in cookieTosser table
    this.makeTableElement('cookieTossers','tr',this.elementId + 'tosser','');

    //Create TD Element with location name
    var container = document.getElementById(this.elementId);
    this.makeHTMLelement(container, 'td','' + this.name + '');

    //cookietosser code - apply the same code to the "elementID+tosser" element
    var tosserContainer = document.getElementById(this.elementId + 'tosser');
    this.makeHTMLelement(tosserContainer,'td','' + this.name + '', true);

    for (var i = 0; i < this.staticCookies.length; i++) { //populate table row with td elements containing each element from staticCookies array
        this.makeHTMLelement(container,'td',this.staticCookies[i]);
        //cookietosser code- does the same as above, but numbers are run through the cookieTossers method
        this.makeHTMLelement(tosserContainer,'td',this.cookieTossers(this.staticCookies[i]),true);
    }
    //calculate total
    for (var i = 0; i < this.staticCookies.length; i++){
        this.cookieSum = this.cookieSum + this.staticCookies[i];
    }
    this.makeHTMLelement(container,'td','' + this.cookieSum + '');
};

//create table headers populated with openHours elements
CookieStore.prototype.tableHeaders = function(){
    var openHours = ['6:00am','7:00am','8:00am','9:00am','10:00am','11:00am','12:00am','1:00pm','2:00pm','3:00pm','4:00pm','5:00pm','6:00pm','7:00pm','8:00pm', 'Total'];

    //create new row for main table, inserting before all other child elements
    var headers = document.getElementById('masterTable');
    var headerTableRow = document.createElement( 'tr' );
    headerTableRow.id = 'headerRow';
    headers.insertBefore(headerTableRow, headers.childNodes[0]);

    //create empty TH element
    var tableHeader = document.getElementById('headerRow');
    var createTableHead = document.createElement( 'th' );
    tableHeader.appendChild( createTableHead );

    //cookietosser code - create cookietosser headers
    var tosserHeaders = document.getElementById('cookieTossers');
    var headerTableRow = document.createElement( 'tr' );
    headerTableRow.id = 'tosserRow';
    tosserHeaders.insertBefore(headerTableRow, tosserHeaders.childNodes[0]);
    //create empty TH element
    var tosserHeader = document.getElementById('tosserRow');
    var createTosserHead = document.createElement( 'th' );
    tosserHeader.appendChild( createTosserHead );

    for (var i = 0; i < openHours.length; i++) {
        var createTableHead = document.createElement( 'th' );
        createTableHead.innerHTML = openHours[i];
        tableHeader.appendChild( createTableHead );
        //cookietosser code - nested if conditional to prevent cookietosser table from loading "Total" column
        if ( i < openHours.length - 1 ){
            var createTosserHead = document.createElement( 'th' );
            createTosserHead.innerHTML = openHours[i];
            tosserHeader.appendChild( createTosserHead );
        }
    }
}; // End of tableHeaders method

//Calculate total cookies in all stores
CookieStore.prototype.totalCookies = function () {

    //create new table row to display column totals
    var container = document.getElementById('masterTable');
    var newTableRow = document.createElement( 'tr' );
    newTableRow.id = 'totals' ;
    container.appendChild( newTableRow );

    //create blank table header
    container = document.getElementById( 'totals' );
    var totalTableHeader = document.createElement( 'th' );
    totalTableHeader.innerHTML = 'Totals';
    container.appendChild( totalTableHeader );

    for (var rowNumber = 0; rowNumber < cookieStoreArray[0].staticCookies.length; rowNumber++){
        var totalCookieTD = document.createElement( 'td' );
        var trackyMcVariable = 0;
        for (var colNumber = 0; colNumber < cookieStoreArray.length; colNumber++){
            trackyMcVariable += cookieStoreArray[colNumber].staticCookies[rowNumber];
        }
        totalCookieTD.innerHTML = '' + trackyMcVariable + '';
        container.appendChild( totalCookieTD );
    }
    //calculate cookie total per td
    var totalCounter = 0;
    for (var i = 0; i < cookieStoreArray.length; i++){ //TO DO: change length to be based on number of children of 'masterTable' element
        totalCounter = totalCounter + cookieStoreArray[i].cookieSum;
    }
    // var container = document.getElementById('total');
    var totalHeader = document.createElement('td');
    totalHeader.innerHTML = '' + totalCounter + '';
    container.appendChild( totalHeader );
};

var cookieStoreArray = [
    new CookieStore('PDX Airport', 23, 65, 6.3),
    new CookieStore('Pioneer Square', 3, 24, 1.2),
    new CookieStore('Powell\'s', 11, 38, 3.7),
    new CookieStore('St Johns', 20, 38, 2.3),
    new CookieStore('Waterfront', 2, 16, 4.6)
];
// cookieStoreArray[0].tableHeaders();
cookieStoreArray[0].totalCookies();
cookieStoreArray[0].tableHeaders();

//Form & Event Sorcery

var form = document.getElementById( 'store-entry' ); //.this referrs to form (html element that is listening )
form.addEventListener( 'submit', function(){
    event.preventDefault();

    //ALTERNATIVE WAY TO WRITE THIS PART
    // var name = event.target.storeName.value;
    // var minCustomers = parseInt(event.target.minCustomers.value);
    // var maxCustomers = parseInt(event.target.maxCustomers.value);
    // var avgCookiesPerCust = parseInt(event.target.avgCookies.value);
    // var newQuestion = new CookieStore (name, minCustomers, maxCustomers, avgCookiesPerCust);

    var removeTotal = document.getElementById( 'totals' );
    removeTotal.outerHTML = '';
    cookieStoreArray.push(new CookieStore ( this.storeName.value, parseInt(this.minCustomers.value), parseInt(this.maxCustomers.value), this.avgCookies.value));
    cookieStoreArray[0].totalCookies();
    // document.form.reset();   TO DO: MAKE THE TEXT FIELDS CLEAR ON SUBMIT

    //DEBUGGING HELPER GARBAGE
    // console.log('submitted store name is ' + this.storeName );
    // console.log('submitted mincustomers is ' + this.minCustomers );
    // console.log('submitted max customers is ' + this.maxCustomers.value );
    // console.log('submitted avg is ' + this.avgCookies.value );
});<|endoftext|>


<commit_before>/**
 * Copyright 2015-2016, Google, Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

const config = require('../config/config');
const Memcached = require('memcached');
const memcachedAddr = process.env.MEMCACHE_PORT_11211_TCP_ADDR ||
  config.get('MEMCACHED_SERVER') || 'localhost';
const memcachedPort = process.env.MEMCACHE_PORT_11211_TCP_PORT || '11211';
const memcached = new Memcached(memcachedAddr + ':' + memcachedPort, {timeout: 1000, retries: 3});

const PAGELIST_URLS = 'PAGELIST_URLS';
const CACHE_LIFETIME = 60 * 60 * 6; // 6 hours

/**
 * Gets a value from memcached using.
 *
 * @param {object} a key.
 * @returns a Promise
 */
function get(key) {
  return new Promise((resolve, reject) => {
    memcached.get(key, (err, value) => {
      if (err) {
        return reject(err);
      }

      if (!value) {
        return reject('Not Found. Key: ' + key);
      }

      return resolve(value);
    });
  });
}

/**
 * Deletes a value from memcached.
 *
 * @param {object} a key.
 * @returns a Promise
 */
function del(key) {
  return new Promise((resolve, reject) => {
    memcached.del(key, (err, value) => {
      if (err) {
        return reject(err);
      }

      if (!value) {
        return reject('Not Found. Key: ' + key);
      }

      return resolve(value);
    });
  });
}

/**
 * Sets a value in Memcached.
 *
 * @param {object} the key.
 * @param {object} the value.
 * @param {Number} a lifetime.
 * @returns a Promise
 */
function set(key, value, lifetime) {
  return new Promise((resolve, reject) => {
    memcached.set(key, value, lifetime, err => {
      if (err) {
        console.error(err);
        return reject(err);
      }
      return resolve();
    });
  });
}

/**
 * Replaces a value in Memcached.
 *
 * @param {object} the key.
 * @param {object} the value.
 * @param {Number} a lifetime.
 * @returns a Promise
 */
function replace(key, value, lifetime) {
  return new Promise((resolve, reject) => {
    memcached.replace(key, value, lifetime, err => {
      if (err) {
        console.error(err);
        return reject(err);
      }
      return resolve();
    });
  });
}

function getMulti(keys) {
  return new Promise((resolve, reject) => {
    memcached.getMulti(keys, (err, data) => {
      if (err) {
        console.error(err);
        return reject(err);
      }
      return resolve(data);
    });
  });
}

/**
 * Flushes memcache
 */
function flush() {
  memcached.flush();
}

/**
 * Stores URLs in PAGELIST_URLS that need to be removed from cache.
 */
function storeCachedUrls(url) {
  // Stores list PWA pages (the ones without '/pwas/' in the URL)
  if (url.indexOf('/pwas/') < 0) {
    this.get(PAGELIST_URLS)
      .then(array => {
        let urlSet = new Set(array);
        urlSet.add(url);
        this.set(PAGELIST_URLS, Array.from(urlSet), CACHE_LIFETIME);
      })
      .catch(_ => {
        let urlSet = new Set();
        urlSet.add(url);
        this.set(PAGELIST_URLS, Array.from(urlSet), CACHE_LIFETIME);
      });
  }
}

/**
 * Flush URLs from PAGELIST_URLS list.
 */
function flushCacheUrls() {
  this.get(PAGELIST_URLS)
    .then(array => {
      array.forEach(url => {
        this.del(url);
      });
      this.del(PAGELIST_URLS);
    });
}

module.exports = {
  get: get,
  del: del,
  set: set,
  replace: replace,
  flush: flush,
  getMulti: getMulti,
  storeCachedUrls: storeCachedUrls,
  flushCacheUrls: flushCacheUrls
};
<commit_msg>Reduce memcached timeout<commit_after>/**
 * Copyright 2015-2016, Google, Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

const config = require('../config/config');
const Memcached = require('memcached');
const memcachedAddr = process.env.MEMCACHE_PORT_11211_TCP_ADDR ||
  config.get('MEMCACHED_SERVER') || 'localhost';
const memcachedPort = process.env.MEMCACHE_PORT_11211_TCP_PORT || '11211';
const memcached = new Memcached(memcachedAddr + ':' + memcachedPort, {timeout: 600, retries: 1});

const PAGELIST_URLS = 'PAGELIST_URLS';
const CACHE_LIFETIME = 60 * 60 * 6; // 6 hours

/**
 * Gets a value from memcached using.
 *
 * @param {object} a key.
 * @returns a Promise
 */
function get(key) {
  return new Promise((resolve, reject) => {
    memcached.get(key, (err, value) => {
      if (err) {
        return reject(err);
      }

      if (!value) {
        return reject('Not Found. Key: ' + key);
      }

      return resolve(value);
    });
  });
}

/**
 * Deletes a value from memcached.
 *
 * @param {object} a key.
 * @returns a Promise
 */
function del(key) {
  return new Promise((resolve, reject) => {
    memcached.del(key, (err, value) => {
      if (err) {
        return reject(err);
      }

      if (!value) {
        return reject('Not Found. Key: ' + key);
      }

      return resolve(value);
    });
  });
}

/**
 * Sets a value in Memcached.
 *
 * @param {object} the key.
 * @param {object} the value.
 * @param {Number} a lifetime.
 * @returns a Promise
 */
function set(key, value, lifetime) {
  return new Promise((resolve, reject) => {
    memcached.set(key, value, lifetime, err => {
      if (err) {
        console.error(err);
        return reject(err);
      }
      return resolve();
    });
  });
}

/**
 * Replaces a value in Memcached.
 *
 * @param {object} the key.
 * @param {object} the value.
 * @param {Number} a lifetime.
 * @returns a Promise
 */
function replace(key, value, lifetime) {
  return new Promise((resolve, reject) => {
    memcached.replace(key, value, lifetime, err => {
      if (err) {
        console.error(err);
        return reject(err);
      }
      return resolve();
    });
  });
}

function getMulti(keys) {
  return new Promise((resolve, reject) => {
    memcached.getMulti(keys, (err, data) => {
      if (err) {
        console.error(err);
        return reject(err);
      }
      return resolve(data);
    });
  });
}

/**
 * Flushes memcache
 */
function flush() {
  memcached.flush();
}

/**
 * Stores URLs in PAGELIST_URLS that need to be removed from cache.
 */
function storeCachedUrls(url) {
  // Stores list PWA pages (the ones without '/pwas/' in the URL)
  if (url.indexOf('/pwas/') < 0) {
    this.get(PAGELIST_URLS)
      .then(array => {
        let urlSet = new Set(array);
        urlSet.add(url);
        this.set(PAGELIST_URLS, Array.from(urlSet), CACHE_LIFETIME);
      })
      .catch(_ => {
        let urlSet = new Set();
        urlSet.add(url);
        this.set(PAGELIST_URLS, Array.from(urlSet), CACHE_LIFETIME);
      });
  }
}

/**
 * Flush URLs from PAGELIST_URLS list.
 */
function flushCacheUrls() {
  this.get(PAGELIST_URLS)
    .then(array => {
      array.forEach(url => {
        this.del(url);
      });
      this.del(PAGELIST_URLS);
    });
}

module.exports = {
  get: get,
  del: del,
  set: set,
  replace: replace,
  flush: flush,
  getMulti: getMulti,
  storeCachedUrls: storeCachedUrls,
  flushCacheUrls: flushCacheUrls
};
<|endoftext|>


<commit_before>// namespace
var MPLAY = MPLAY || {};

(function() {
	"use_strict";

	/**
	 *
	 * @class Page1
	 * @augments GNOVEL.Page
	 */
	var Page1 = function() {
		GNOVEL.Page.call(this);
	};

	Page1.prototype = Object.create(GNOVEL.Page.prototype);
	Page1.prototype.constructor = Page1;

	/**
	 * @override
	 */
	Page1.prototype._onLoad = function() {
		GNOVEL.Page.prototype._onLoad.call(this);
		this._state = 0;

		this._parentPosX = 0;

		this.setBackground("/static/gnovel/res/textures/steven_universeXworlds8.jpg");

		//create images
		this._professorImg = this.createImage("/static/gnovel/res/textures/char/prof sweeney- thoughtful.png", new THREE.Vector3(75, -130, 180), 600, 750);
		this._juliImg = this.createImage("/static/gnovel/res/textures/char/thoughtful-julia.png", new THREE.Vector3(-300, -140, 120), 600, 750);
		this._ryanImg = this.createImage("/static/gnovel/res/textures/char/ryan-happy.png", new THREE.Vector3(0, -80, 140), 600, 750);
		this._catImg = this.createImage("/static/gnovel/res/textures/char/cat-annoyed.png", new THREE.Vector3(450, -130, 100), 600, 750);

		this._professorImg.material.opacity = 0;
		this._juliImg.material.opacity = 0;
		this._ryanImg.material.opacity = 0;
		this._catImg.material.opacity = 0;

		this._professor = "professor";
		this._juli = "juli";
		this._ryan = "ryan";
		this._cat = "cat";

		// add object tags
		this._setObjectTag(this._professor, this._professorImg);
		this._setObjectTag(this._juli, this._juliImg);
		this._setObjectTag(this._ryan, this._ryanImg);
		this._setObjectTag(this._cat, this._catImg);
	};

	MPLAY.Page1 = Page1;
}());
<commit_msg>Implemented scene 2 in page1.js.<commit_after>// namespace
var MPLAY = MPLAY || {};

(function() {
	"use_strict";

	/**
	 *
	 * @class Page1
	 * @augments GNOVEL.Page
	 */
	var Page1 = function() {
		GNOVEL.Page.call(this);
	};

	Page1.prototype = Object.create(GNOVEL.Page.prototype);
	Page1.prototype.constructor = Page1;

	/**
	 * @override
	 */
	Page1.prototype._onLoad = function() {
		GNOVEL.Page.prototype._onLoad.call(this);
		this._state = 0;

		this._parentPosX = 0;

		this.setBackground("/static/gnovel/res/textures/steven_universeXworlds8.jpg");

		//create images
		this._professorImg = this.createImage("/static/gnovel/res/textures/char/prof sweeney- thoughtful.png", new THREE.Vector3(75, -130, 180), 600, 750);
		this._priyaImg = this.createImage("/static/gnovel/res/textures/char/thoughtful-julia.png", new THREE.Vector3(-300, -140, 120), 600, 750);
		this._ryanImg = this.createImage("/static/gnovel/res/textures/char/ryan-happy.png", new THREE.Vector3(0, -80, 140), 600, 750);
		this._catImg = this.createImage("/static/gnovel/res/textures/char/cat-annoyed.png", new THREE.Vector3(450, -130, 100), 600, 750);

		this._talked = 0;

		var pageObj = this;
		var io1 = this.createInteractableObject(
			"/static/gnovel/res/textures/Perspective-Button-Stop-icon.png",
			{x: -100, y: 200, width : 64, height : 64, onClick: function() {
				pageObj._talked = 1;
				pageObj._runFlow();
			}});

		var io2 = this.createInteractableObject(
			"/static/gnovel/res/textures/Perspective-Button-Stop-icon.png",
			{x: 100, y: 200, width : 64, height : 64, onClick: function() {
				pageObj._talked = 2;
				pageObj._runFlow();
			}});

		this._professorImg.material.opacity = 0;
		this._priyaImg.material.opacity = 0;
		this._ryanImg.material.opacity = 0;
		this._catImg.material.opacity = 0;

		this._professor = "professor";
		this._priya = "priya";
		this._ryan = "ryan";
		this._cat = "cat";

		// add object tags
		this._setObjectTag(this._professor, this._professorImg);
		this._setObjectTag(this._priya, this._priyaImg);
		this._setObjectTag(this._ryan, this._ryanImg);
		this._setObjectTag(this._cat, this._catImg);

	};

	Page1.prototype._createFlowElements = function() {
		var professor = "%professor";
		var priya = "%priya";
		var ryan = "%ryan";
		var cat = "%cat";
		var o = null;
		var isPhonePickedUp = 1;
		var isPhoneWithYou = 0;
		var player = "Lindsey";
		// this._talked = 1;

		if(this._talked == 0) {
			o = [
				{type: "show", img: professor, position: "center"},
				{type: "dialog", speaker: "professor", text: "My aim in Programming and Society is to help you become a better programmer. Technology impacts how society operates. I will challenge you to look deeper into the programs, apps, and technologies that you use."},
				{type: "dialog", speaker: "professor", text: "The second half of each lesson will break into your assigned study groups. Please use this time wisely, you’ll have a group project later in the semester."},
				{type: "hide", img: professor},
				{type: "show", img: ryan, position: "center"},
				{type: "dialog", speaker: "ryan", text: "Awesome! Both you and Priya are in my group. This is Priya. She’s super smart, speaks like a bajillion languages. Too cool for me."},
				{type: "hide", img: ryan},
				{type: "show", img: priya, position: "left"},
				{type: "dialog", speaker: "priya", text: "RYAN here helped me with some of my writing last semester. Always willing to be my study partner. I think I annoyed him most of the time. Anyway, nice to meet you"},
				{type: "show", img: cat, position: "right"},
				{type: "dialog", speaker: "cat", text: "Hey I’m Cat. I’m in Tepper. I think I’m going to be in over my head a little here in a CS class It’s been an adjustment coming back to school."},
				{type: "show", img: ryan, position: "center"},
				{type: "dialog", speaker: "ryan", text: "Oh, don’t sweat it, Cat. We’ll help you out if you get stuck."},
				{type: "dialog", speaker: "cat", text: "Sorry - I’m a little all over the place. I lost my phone yesterday."},
				{type: "compare", leftop: isPhonePickedUp, operator: "equal", rightop: 1, goTrue: "#phone_picked", goFalse: "#phone_notpicked"},
				{type: "dialog", speaker: "ryan", text: "Were you at Scottie’s Bar yesterday? " + player +" found a phone there.", label: "phone_picked"},
				{type: "dialog", speaker: "cat", text: "Oh my God, do you guys have it with you?"},
				{type: "compare", leftop: isPhoneWithYou, operator: "equal", rightop: 1, goTrue: "#phone_withyou", goFalse: "#phone_notwithyou"},
				{type: "dialog", speaker: "ryan", text: "Yeah, " + player + " has it, right?", label: "phone_withyou"},
				{type: "dialog", speaker: "cat", text: "Oh my God - you charged it too? You’ve totally restored my faith in humanity."},
				{type: "jump", condition: true, goTrue: "#choices", goFalse: 1000},
				{type: "dialog", speaker: "ryan", text: "We left it with the bartender.", label: "phone_notwithyou"},
				{type: "dialog", speaker: "cat", text: "Thank you! I’ll run over there after this. Lifesaver!"},
				{type: "choices", choices : [{text: "No Problem.", go: "#choice_number_1"}, {text : "Happy to help.", go : "#choice_number_2"}], label: "choices"},
				{type: "jump", condition: true, goTrue: 1000, goFalse: 1000},
				{type: "dialog", speaker: "ryan", text: "I think we saw a phone on the bar at Scotties, right? Maybe it’s yours.", label: "phone_notpicked"},
				{type: "dialog", speaker: "cat", text: "Oh, uh thanks. I’ll call them."},
			];
		}
		else if(this._talked == 1) {
			o = [
				{type: "dialog", speaker: "ryan", text: "What did I tell you, that karma!"},
				{type: "dialog", speaker: "ryan", text: "test"},
			];
		}
		else if(this._talked == 2) {
			o = [
				{type: "dialog", speaker: "priya", text: "What are the chances!"},
			];
		}
		return o;
	}

	MPLAY.Page1 = Page1;
}());
<|endoftext|>


<commit_before>import React from 'react';
import { browserHistory } from 'react-router';

import SidebarMenuWrapper from '../../../lib/sidebar/SidebarMenuWrapper';
import SidebarMenuHeader from '../../../lib/sidebar/SidebarMenuHeader';
import TreeMenu from '../../../lib/sidebar/TreeMenu';

const mainMenus = [
  {
    key: 1,
    id: 1,
    icon: 'fa fa-dashboard',
    title: 'Dashboard',
    items: [
      { key: 11, id: 11, title: 'Dashboard v1', url: '/dashboard/v1' },
      { key: 12, id: 12, title: 'Dashboard v2', url: '/dashboard/v2' },
    ],
  },
  {
    key: 2,
    id: 2,
    icon: 'fa fa-files-o',
    title: 'Layout Options',
    label: '4',
    items: [
      { key: 21, id: 21, title: 'Top Navigation' },
      { key: 22, id: 22, title: 'Boxed' },
      { key: 23, id: 23, title: 'Fixed' },
      { key: 24, id: 24, title: 'Collapsed Sidebar' },
    ],
  },
  {
    key: 3,
    id: 3,
    icon: 'fa fa-th',
    title: 'Widgets',
    label: 'new',
    labelColor: 'green',
    url: '/widgets',
  },
  {
    key: 4,
    id: 4,
    icon: 'fa fa-pie-chart',
    title: 'Charts',
    items: [
      { key: 41, id: 41, title: 'ChartJS' },
      { key: 42, id: 42, title: 'Morris' },
      { key: 43, id: 43, title: 'Flot' },
      { key: 44, id: 44, title: 'Inline charts' },
    ],
  },
  {
    key: 5,
    id: 5,
    icon: 'fa fa-laptop',
    title: 'UI Elements',
    items: [
      { key: 51, id: 51, title: 'General' },
      { key: 52, id: 52, title: 'Icons' },
      { key: 53, id: 53, title: 'Buttons' },
      { key: 54, id: 54, title: 'Sliders' },
      { key: 55, id: 55, title: 'Timeline' },
      { key: 56, id: 56, title: 'Modals' },
    ],
  },
  {
    key: 6,
    id: 6,
    icon: 'fa fa-edit',
    title: 'Forms',
    items: [
      { key: 61, id: 61, title: 'General Elements' },
      { key: 62, id: 62, title: 'Advanced Elements' },
      { key: 63, id: 63, title: 'Editors' },
    ],
  },
  {
    key: 7,
    id: 7,
    icon: 'fa fa-table',
    title: 'Tables',
    items: [
      { key: 71, id: 71, title: 'Simple tables' },
      { key: 72, id: 72, title: 'Data tables' },
    ],
  },
  {
    key: 8,
    id: 8,
    icon: 'fa fa-calendar',
    title: 'Calendar',
    label: '3',
    labelColor: 'red',
  },
  {
    key: 9,
    id: 9,
    icon: 'fa fa-envelope',
    title: 'Mailbox',
    label: '12',
    labelColor: 'yellow',
    items: [
      {
        key: 91,
        id: 91,
        noIcon: true,
        title: 'Inbox',
        label: '13',
        labelColor: 'blue',
      },
      {
        key: 92,
        id: 92,
        noIcon: true,
        title: 'Compose',
      },
      {
        key: 93,
        id: 93,
        noIcon: true,
        title: 'Read',
      },
    ],
  },
  {
    key: 10,
    id: 10,
    icon: 'fa fa-folder',
    title: 'Examples',
    items: [
      { key: 101, id: 101, title: 'Invoice' },
      { key: 102, id: 102, title: 'Profile' },
      { key: 103, id: 103, title: 'Login' },
      { key: 104, id: 104, title: 'Register' },
      { key: 105, id: 105, title: 'Lockscreen' },
      { key: 106, id: 106, title: '404 Error' },
      { key: 107, id: 107, title: '500 Error' },
      { key: 108, id: 108, title: 'Blank Page', url: '/examples/blank-page' },
      { key: 109, id: 109, title: 'Pace Page' },
    ],
  },
  {
    key: 11,
    id: 11,
    icon: 'fa fa-share',
    title: 'Multilevel',
    items: [
      { key: 111, id: 111, title: 'Level One', url: '/level-one' },
      {
        key: 112,
        id: 112,
        title: 'Level One',
        items: [
          { key: 1121, id: 1121, title: 'Level Two', url: '/level-two' },
          { key: 1122, id: 1122,
            title: 'Level Two',
            items: [
              {
                key: 112201,
                id: 112201,
                title: 'Level Three',
                url: '/level-three',
              },
              {
                key: 112202,
                id: 112202,
                title: 'Level Three',
                url: '/level-three',
              },
            ],
          },
        ],
      },
      { key: 113, id: 113, title: 'Level One', url: '/level-one' },
    ],
  },
  {
    key: 12,
    id: 12,
    icon: 'fa fa-book',
    title: 'Documentation',
    url: '/documentation',
  },
];

function onClick(item) {
  if (item.url) {
    browserHistory.push(item.url);
  }
}

function onItemClick(item) {
  if (item.url) {
    browserHistory.push(item.url);
  }
}

export default function SidebarMenu() {
  return (
    <SidebarMenuWrapper>
      <SidebarMenuHeader title="MAIN NAVIGATION" />
      {mainMenus.map((menu) =>
        <TreeMenu
          {...menu}
          onClick={() => onClick(menu)}
          onItemClick={onItemClick}
        />
      )}
      <SidebarMenuHeader title="LABELS" />
    </SidebarMenuWrapper>
  );
}
<commit_msg>add showLabel: false for Documentation menu item<commit_after>import React from 'react';
import { browserHistory } from 'react-router';

import SidebarMenuWrapper from '../../../lib/sidebar/SidebarMenuWrapper';
import SidebarMenuHeader from '../../../lib/sidebar/SidebarMenuHeader';
import TreeMenu from '../../../lib/sidebar/TreeMenu';

const mainMenus = [
  {
    key: 1,
    id: 1,
    icon: 'fa fa-dashboard',
    title: 'Dashboard',
    items: [
      { key: 11, id: 11, title: 'Dashboard v1', url: '/dashboard/v1' },
      { key: 12, id: 12, title: 'Dashboard v2', url: '/dashboard/v2' },
    ],
  },
  {
    key: 2,
    id: 2,
    icon: 'fa fa-files-o',
    title: 'Layout Options',
    label: '4',
    items: [
      { key: 21, id: 21, title: 'Top Navigation' },
      { key: 22, id: 22, title: 'Boxed' },
      { key: 23, id: 23, title: 'Fixed' },
      { key: 24, id: 24, title: 'Collapsed Sidebar' },
    ],
  },
  {
    key: 3,
    id: 3,
    icon: 'fa fa-th',
    title: 'Widgets',
    label: 'new',
    labelColor: 'green',
    url: '/widgets',
  },
  {
    key: 4,
    id: 4,
    icon: 'fa fa-pie-chart',
    title: 'Charts',
    items: [
      { key: 41, id: 41, title: 'ChartJS' },
      { key: 42, id: 42, title: 'Morris' },
      { key: 43, id: 43, title: 'Flot' },
      { key: 44, id: 44, title: 'Inline charts' },
    ],
  },
  {
    key: 5,
    id: 5,
    icon: 'fa fa-laptop',
    title: 'UI Elements',
    items: [
      { key: 51, id: 51, title: 'General' },
      { key: 52, id: 52, title: 'Icons' },
      { key: 53, id: 53, title: 'Buttons' },
      { key: 54, id: 54, title: 'Sliders' },
      { key: 55, id: 55, title: 'Timeline' },
      { key: 56, id: 56, title: 'Modals' },
    ],
  },
  {
    key: 6,
    id: 6,
    icon: 'fa fa-edit',
    title: 'Forms',
    items: [
      { key: 61, id: 61, title: 'General Elements' },
      { key: 62, id: 62, title: 'Advanced Elements' },
      { key: 63, id: 63, title: 'Editors' },
    ],
  },
  {
    key: 7,
    id: 7,
    icon: 'fa fa-table',
    title: 'Tables',
    items: [
      { key: 71, id: 71, title: 'Simple tables' },
      { key: 72, id: 72, title: 'Data tables' },
    ],
  },
  {
    key: 8,
    id: 8,
    icon: 'fa fa-calendar',
    title: 'Calendar',
    label: '3',
    labelColor: 'red',
  },
  {
    key: 9,
    id: 9,
    icon: 'fa fa-envelope',
    title: 'Mailbox',
    label: '12',
    labelColor: 'yellow',
    items: [
      {
        key: 91,
        id: 91,
        noIcon: true,
        title: 'Inbox',
        label: '13',
        labelColor: 'blue',
      },
      {
        key: 92,
        id: 92,
        noIcon: true,
        title: 'Compose',
      },
      {
        key: 93,
        id: 93,
        noIcon: true,
        title: 'Read',
      },
    ],
  },
  {
    key: 10,
    id: 10,
    icon: 'fa fa-folder',
    title: 'Examples',
    items: [
      { key: 101, id: 101, title: 'Invoice' },
      { key: 102, id: 102, title: 'Profile' },
      { key: 103, id: 103, title: 'Login' },
      { key: 104, id: 104, title: 'Register' },
      { key: 105, id: 105, title: 'Lockscreen' },
      { key: 106, id: 106, title: '404 Error' },
      { key: 107, id: 107, title: '500 Error' },
      { key: 108, id: 108, title: 'Blank Page', url: '/examples/blank-page' },
      { key: 109, id: 109, title: 'Pace Page' },
    ],
  },
  {
    key: 11,
    id: 11,
    icon: 'fa fa-share',
    title: 'Multilevel',
    items: [
      { key: 111, id: 111, title: 'Level One', url: '/level-one' },
      {
        key: 112,
        id: 112,
        title: 'Level One',
        items: [
          { key: 1121, id: 1121, title: 'Level Two', url: '/level-two' },
          { key: 1122, id: 1122,
            title: 'Level Two',
            items: [
              {
                key: 112201,
                id: 112201,
                title: 'Level Three',
                url: '/level-three',
              },
              {
                key: 112202,
                id: 112202,
                title: 'Level Three',
                url: '/level-three',
              },
            ],
          },
        ],
      },
      { key: 113, id: 113, title: 'Level One', url: '/level-one' },
    ],
  },
  {
    key: 12,
    id: 12,
    icon: 'fa fa-book',
    title: 'Documentation',
    url: '/documentation',
    showLabel: false,
  },
];

function onClick(item) {
  if (item.url) {
    browserHistory.push(item.url);
  }
}

function onItemClick(item) {
  if (item.url) {
    browserHistory.push(item.url);
  }
}

export default function SidebarMenu() {
  return (
    <SidebarMenuWrapper>
      <SidebarMenuHeader title="MAIN NAVIGATION" />
      {mainMenus.map((menu) =>
        <TreeMenu
          {...menu}
          onClick={() => onClick(menu)}
          onItemClick={onItemClick}
        />
      )}
      <SidebarMenuHeader title="LABELS" />
    </SidebarMenuWrapper>
  );
}
<|endoftext|>


<commit_before>Ext.define('Hackathon.HierarchicalCardBoard', {
    extend: 'Rally.app.App',
    componentCls: 'app',

    layout: 'border',

    style: {
        backgroundColor: '#FFF'
    },

    defaults: {
        padding: 5
    },

    items: [
        {
            xtype: 'container',
            cls: 'leftSide',
            itemId: 'leftSide',
            region: 'west',
            width: 350,
            collapsible: true
        },
        {
            xtype: 'container',
            cls: 'rightSide',
            itemId: 'rightSide',
            region: 'center',
            items: [

            ]
        }
    ],

    launch: function() {
        this.buildStoryTree();
        this.buildCardBoard();
    },

    buildStoryTree: function(){
        var portfolioHierarchyConfig = {
            xtype: 'hackathonportfoliohierarchy',
            context: this.getContext(),
            listeners: {
                scope: this,
                treeitemselected: this.onTreeItemSelected
            }
        };
        this.down('#leftSide').add(portfolioHierarchyConfig);
    },

    onTreeItemSelected: function(record){
        // debugger;
        this.cardBoard = this.down('#rightSide').removeAll();

        var selectedRef = record.get('_ref');
        var parentType = record.get('_type');
        var children = record.get('Children');
        if(children && children.length === 0){
            this.cardBoardConfig.storeConfig.filters = [
                { property: "ObjectID", value: 0}
            ];
        }
        else{
            var typePath = children[0]._type;
            this.cardBoardConfig.types = [ typePath ];
            this.cardBoardConfig.storeConfig.filters = [
                {
                    property: "Parent",
                    value: selectedRef
                }
            ];

            if(parentType.indexOf("portfolioitem") === 0) {
                this.cardBoardConfig.attribute = "State";
                var me = this;
                this._buildColumns(typePath, function(columns) {
                    me.cardBoardConfig.columns = columns;
                    me.cardBoard = me.down('#rightSide').add(me.cardBoardConfig);
                });
            }
            else {
                this.cardBoardConfig.columns = undefined;
                this.cardBoardConfig.attribute = "ScheduleState";
                this.cardBoard = this.down('#rightSide').add(this.cardBoardConfig);
                this.cardBoardConfig.storeConfig.filters = [
                    {
                        property: "PortfolioItem",
                        value: selectedRef
                    }
                ];
                // debugger;
                this.cardBoard = this.down('#rightSide').add(this.cardBoardConfig);
            }

        }

    },

    _buildColumns: function(typePath, callback) {
        var me = this;
        this._getTypeDefRefFor(typePath, function(typeRef) {
            me._getStates(typeRef, function(states) {
                var columns = [
                        {
                            displayValue:'No Entry',
                            value:null
                        }
                    ];

                Ext.Array.each(states, function (state) {
                    console.log(state.get('Name'), state.get('_ref'));
                    columns.push({
                        value:state.get('_ref'),
                        displayValue:state.get('Name'),
                        stateRecord:state
                    });
                });

                callback(columns);
            });
        });
    },

    _getTypeDefRefFor: function(typePath, callback) {
        Ext.create('Rally.data.WsapiDataStore', {
            model:'TypeDefinition',
            context: this.getNotStupidContext(),
            autoLoad:true,
            filters:[
                {
                    property: 'TypePath',
                    value: typePath
                }
            ],
            listeners: {
                load: function(store, records) {
                    callback(records[0].get('_ref'));
                }
            }
        });
    },

    _getStates: function(typeRef, callback) {
        Ext.create('Rally.data.WsapiDataStore', {
            model:'State',
            context: this.getNotStupidContext(),
            autoLoad:true,
            fetch:['Name', 'WIPLimit', 'Description'],
            filters:[
                {
                    property: 'TypeDef',
                    value: typeRef
                },
                {
                    property:'Enabled',
                    value:true
                }
            ],
            sorters:[
                {
                    property:'OrderIndex',
                    direction:'ASC'
                }
            ],
            listeners:{
                load:function (store, records) {
                    callback(records);
                }
            }
        });
    },

    buildCardBoard: function(){
        this.cardBoardConfig = {
            xtype: 'rallycardboard',
            types: ['User Story'],
            attribute: 'ScheduleState',
            storeConfig: {
                filters: [
                    { property: "ObjectID", value: 0}
                ],
                autoLoad: true,
                context: this.getNotStupidContext()
            },
            //enableRanking: this.getContext().getWorkspace().WorkspaceConfiguration.DragDropRankingEnabled,

            cardConfig: {
                componentCls: 'iterationtrackingboard-card',
                //fields: ['Tasks'],
                editable: true,
                showHeaderMenu: true
            }

        };
        this.cardBoard = this.down('#rightSide').add(this.cardBoardConfig);
    },

    getNotStupidContext: function() {
        return {
            workspace: this.getContext().getWorkspace()._ref,
            project: null
       };
    }
});
<commit_msg>Now works for User Story children<commit_after>Ext.define('Hackathon.HierarchicalCardBoard', {
    extend: 'Rally.app.App',
    componentCls: 'app',

    layout: 'border',

    style: {
        backgroundColor: '#FFF'
    },

    defaults: {
        padding: 5
    },

    items: [
        {
            xtype: 'container',
            cls: 'leftSide',
            itemId: 'leftSide',
            region: 'west',
            width: 350,
            collapsible: true
        },
        {
            xtype: 'container',
            cls: 'rightSide',
            itemId: 'rightSide',
            region: 'center',
            items: [

            ]
        }
    ],

    launch: function() {
        this.buildStoryTree();
        this.buildCardBoard();
    },

    buildStoryTree: function(){
        var portfolioHierarchyConfig = {
            xtype: 'hackathonportfoliohierarchy',
            context: this.getContext(),
            listeners: {
                scope: this,
                treeitemselected: this.onTreeItemSelected
            }
        };
        this.down('#leftSide').add(portfolioHierarchyConfig);
    },

    onTreeItemSelected: function(record){
        this.cardBoard = this.down('#rightSide').removeAll();

        if( !this._hasChildren(record) ){
            this.cardBoardConfig.storeConfig.filters = [
                { property: "ObjectID", value: 0}
            ];
            this.cardBoardConfig.types = [ "User Story" ];
            this.cardBoardConfig.columns = undefined;
            this.cardBoardConfig.attribute = "ScheduleState";

            this.cardBoard = this.down('#rightSide').add(this.cardBoardConfig);
        }
        else{
            var selectedRef = record.get('_ref');
            var parentType = record.get('_type');

            var child = this._getFirstChild(record);
            var typePath = child._type;
            this.cardBoardConfig.types = [ typePath ];
            this.cardBoardConfig.storeConfig.filters = [
                {
                    property: "Parent",
                    value: selectedRef
                }
            ];

            if(typePath.indexOf("PortfolioItem") === 0) {
                this.cardBoardConfig.attribute = "State";
                var me = this;
                this._buildColumns(typePath, function(columns) {
                    me.cardBoardConfig.columns = columns;
                    me.cardBoard = me.down('#rightSide').add(me.cardBoardConfig);
                });
            }
            else {
                this.cardBoardConfig.columns = undefined;
                this.cardBoardConfig.attribute = "ScheduleState";
                this.cardBoardConfig.storeConfig.filters = [
                    {
                        property: "PortfolioItem",
                        value: selectedRef
                    }
                ];
                this.cardBoard = this.down('#rightSide').add(this.cardBoardConfig);
            }

        }
    },

    _hasChildren: function(record){
        var children = record.get('Children')||[];
        var userStories = record.get('UserStories')||[];
        return (children.length + userStories.length) > 0;
    },

    _getFirstChild: function(record){
        var children = record.get('Children')||[];
        children = children.concat( record.get('UserStories')||[] );
        return children[0];
    },

    _buildColumns: function(typePath, callback) {
        var me = this;
        this._getTypeDefRefFor(typePath, function(typeRef) {
            me._getStates(typeRef, function(states) {
                var columns = [
                        {
                            displayValue:'No Entry',
                            value:null
                        }
                    ];

                Ext.Array.each(states, function (state) {
                    console.log(state.get('Name'), state.get('_ref'));
                    columns.push({
                        value:state.get('_ref'),
                        displayValue:state.get('Name'),
                        stateRecord:state
                    });
                });

                callback(columns);
            });
        });
    },

    _getTypeDefRefFor: function(typePath, callback) {
        Ext.create('Rally.data.WsapiDataStore', {
            model:'TypeDefinition',
            context: this.getNotStupidContext(),
            autoLoad:true,
            filters:[
                {
                    property: 'TypePath',
                    value: typePath
                }
            ],
            listeners: {
                load: function(store, records) {
                    callback(records[0].get('_ref'));
                }
            }
        });
    },

    _getStates: function(typeRef, callback) {
        Ext.create('Rally.data.WsapiDataStore', {
            model:'State',
            context: this.getNotStupidContext(),
            autoLoad:true,
            fetch:['Name', 'WIPLimit', 'Description'],
            filters:[
                {
                    property: 'TypeDef',
                    value: typeRef
                },
                {
                    property:'Enabled',
                    value:true
                }
            ],
            sorters:[
                {
                    property:'OrderIndex',
                    direction:'ASC'
                }
            ],
            listeners:{
                load:function (store, records) {
                    callback(records);
                }
            }
        });
    },

    buildCardBoard: function(){
        this.cardBoardConfig = {
            xtype: 'rallycardboard',
            types: ['User Story'],
            attribute: 'ScheduleState',
            storeConfig: {
                filters: [
                    { property: "ObjectID", value: 0}
                ],
                autoLoad: true,
                context: this.getNotStupidContext()
            },
            //enableRanking: this.getContext().getWorkspace().WorkspaceConfiguration.DragDropRankingEnabled,

            cardConfig: {
                componentCls: 'iterationtrackingboard-card',
                //fields: ['Tasks'],
                editable: true,
                showHeaderMenu: true
            }

        };
        this.cardBoard = this.down('#rightSide').add(this.cardBoardConfig);
    },

    getNotStupidContext: function() {
        return {
            workspace: this.getContext().getWorkspace()._ref,
            project: null
       };
    }
});
<|endoftext|>