<commit_before>var idrinth = {
        /**
         * @type String
         */
        version: '###VERSION###',
        /**
         * @type Boolean
         */
        windowactive: true,
        /**
         *
         * @type String
         */
        platform: '',
        /**
         *
         * @returns {undefined}
         */
        reload: function ( ) {
            window.clearTimeout ( idrinth.core.timeouts.next );
            idrinth.ui.removeElement ( 'idotd-base' );
            for (var event in idrinth.core.multibind.events) {
                idrinth.ui.base.removeEventListener ( event, idrinth.core.multibind.triggered );
            }
            window.setTimeout ( function () {
                idrinth = { };
                document.getElementById ( 'idotd-loader' ).errorFunction ();
            }, 1 );
        },
        /**
         * initializes the whole script
         * @returns {undefined}
         */
        start: function ( ) {
            /**
             *
             * @returns {undefined}
             */
            var startInternal = function ( ) {
                /**
                 * initializes all modules
                 * @returns {undefined}
                 */
                var init = function () {
                    if ( !idrinth.text.initialized ) {
                        return;
                    }
                    if ( idrinth.platform === 'newgrounds' ) {
                        try {
                            var frame = document.getElementById ( 'iframe_embed' ).getElementsByTagName ( 'iframe' )[0];
                            idrinth.newgrounds.originalUrl = frame.getAttribute ( 'src' );
                            if ( window.location.search ) {
                                frame.setAttribute ( 'src', ( frame.getAttribute ( 'src' ) ).replace ( /&ir=.*/, '' ) + '&' + ( window.location.search ).replace ( /^\?/, '' ) );
                            }
                        } catch ( e ) {
                            idrinth.core.log ( e.message ? e.message : e.getMessage () );
                            return;
                        }
                        idrinth.core.timeouts.add ( 'newgrounds', idrinth.newgrounds.alarmCheck, 3333 );
                    }
                    idrinth.core.timeouts.remove ( 'start' );
                    idrinth.ui.start ( );
                    idrinth.user.start ( );
                    idrinth.names.start ( );
                    idrinth.raids.start ( );
                    idrinth.tier.start ( );
                    idrinth.chat.start ( );
                    idrinth.war.start ( );
                    idrinth.core.timeouts.add ( 'core.multibind', function () {
                        idrinth.core.multibind.add ( 'click', '.clipboard-copy', function ( element, event ) {
                            idrinth.core.copyToClipboard.element ( element );
                            element.parentNode.parentNode.removeChild ( element.parentNode );
                        } );
                    }, 1000 );
                    delete idrinth['start'];
                };
                idrinth.settings.start ( );
                idrinth.text.start ( );
                idrinth.core.timeouts.add ( 'start', init, 123, -1 );
            };
            idrinth.core.log ( 'Starting Idrinth\'s DotD Script' );
            window.onblur = function () {
                idrinth.windowactive = !idrinth.windowactive;
            };
            idrinth.platform = location.hostname.split ( '.' )[location.hostname.split ( '.' ).length - 2];
            if ( idrinth.platform === 'dawnofthedragons' ) {
                idrinth.platform = 'facebook';
            }
            if ( idrinth.platform === 'armorgames' ) {
                return idrinth.core.timeouts.add ( 'start', startInternal, 2222 );
            }
            startInternal ();
        }
    };
    window.setTimeout ( idrinth.start, 6666 );
<commit_msg>reverting change - hopefully fixes loading<commit_after>var idrinth = ( function () {
    'use strict';
    var idrinth = {
        /**
         * @type String
         */
        version: '###VERSION###',
        /**
         * @type Boolean
         */
        windowactive: true,
        /**
         *
         * @type String
         */
        platform: '',
        /**
         *
         * @returns {undefined}
         */
        reload: function ( ) {
            window.clearTimeout ( idrinth.core.timeouts.next );
            idrinth.ui.removeElement ( 'idotd-base' );
            for (var event in idrinth.core.multibind.events) {
                idrinth.ui.base.removeEventListener ( event, idrinth.core.multibind.triggered );
            }
            window.setTimeout ( function () {
                idrinth = { };
                document.getElementById ( 'idotd-loader' ).errorFunction ();
            }, 1 );
        },
        /**
         * initializes the whole script
         * @returns {undefined}
         */
        start: function ( ) {
            /**
             *
             * @returns {undefined}
             */
            var startInternal = function ( ) {
                /**
                 * initializes all modules
                 * @returns {undefined}
                 */
                var init = function () {
                    if ( !idrinth.text.initialized ) {
                        return;
                    }
                    if ( idrinth.platform === 'newgrounds' ) {
                        try {
                            var frame = document.getElementById ( 'iframe_embed' ).getElementsByTagName ( 'iframe' )[0];
                            idrinth.newgrounds.originalUrl = frame.getAttribute ( 'src' );
                            if ( window.location.search ) {
                                frame.setAttribute ( 'src', ( frame.getAttribute ( 'src' ) ).replace ( /&ir=.*/, '' ) + '&' + ( window.location.search ).replace ( /^\?/, '' ) );
                            }
                        } catch ( e ) {
                            idrinth.core.log ( e.message ? e.message : e.getMessage () );
                            return;
                        }
                        idrinth.core.timeouts.add ( 'newgrounds', idrinth.newgrounds.alarmCheck, 3333 );
                    }
                    idrinth.core.timeouts.remove ( 'start' );
                    idrinth.ui.start ( );
                    idrinth.user.start ( );
                    idrinth.names.start ( );
                    idrinth.raids.start ( );
                    idrinth.tier.start ( );
                    idrinth.chat.start ( );
                    idrinth.war.start ( );
                    idrinth.core.timeouts.add ( 'core.multibind', function () {
                        idrinth.core.multibind.add ( 'click', '.clipboard-copy', function ( element, event ) {
                            idrinth.core.copyToClipboard.element ( element );
                            element.parentNode.parentNode.removeChild ( element.parentNode );
                        } );
                    }, 1000 );
                    delete idrinth['start'];
                };
                idrinth.settings.start ( );
                idrinth.text.start ( );
                idrinth.core.timeouts.add ( 'start', init, 123, -1 );
            };
            idrinth.core.log ( 'Starting Idrinth\'s DotD Script' );
            window.onblur = function () {
                idrinth.windowactive = !idrinth.windowactive;
            };
            idrinth.platform = location.hostname.split ( '.' )[location.hostname.split ( '.' ).length - 2];
            if ( idrinth.platform === 'dawnofthedragons' ) {
                idrinth.platform = 'facebook';
            }
            if ( idrinth.platform === 'armorgames' ) {
                return idrinth.core.timeouts.add ( 'start', startInternal, 2222 );
            }
            startInternal ();
        }
    };
    window.setTimeout ( idrinth.start, 6666 );
    return idrinth;
} () );
<|endoftext|>


<commit_before>function WSTab(args){
  var self = this;
  var storageKey = String(args.storageKey);
  this.storageKey = storageKey;
  var wind = new StandardWindow({
    color: args.color || "orange",
  });
  this.asterisk = span('*');
  this.asterisk.e.style.display = 'none';
  wind.title = args.title || "Untitled";
  wind.toolbar.left.append(new Button({
    className: ( args.color2 ? args.color2 : 'orange' ) + ' quiet',
    caption: 'Save',
    action: function(){
      self.save();
    },
  }));
  wind.on('keydown', function(e){
    if(e.keyCode === 83 && e.ctrlKey){
      self.save();
      e.stopPropagation();
      e.preventDefault();
    }
  });
  var cm = CodeMirror(wind.body.e, {
    mode: args.mode || '',
    indentWithTabs: false,
    tabSize: 2,
    lineNumbers: true,
    autoRefresh:true,
    theme: 'neat',
  });
  cm.getWrapperElement().classList.add('full-element');
  wind.on('activated', function(){
    cm.refresh();
  });

  chrome.storage.sync.get(storageKey, function(data){
    if(data[storageKey] !== undefined){
      cm.setValue(String(data[storageKey]));
    }
    else{
      cm.setValue('');
    }
    cm.on('change', function(e){
      wind.tabViewHandle.e.style.fontWeight = 900;
      self.asterisk.e.style.display = null;
    });
    cm.refresh();
  });

  this.main = wind;
  this.cm = cm;
  if(args.tabs instanceof Element){
    args.tabs.append(wind);
    wind.tabViewHandle.append(this.asterisk);
  }
}

WSTab.prototype.save = function(){
  var self = this;
  var value = this.cm.getValue();
  var obj = {};
  obj[this.storageKey] = value;
  chrome.storage.sync.set(obj, function(){
    self.main.tabViewHandle.e.style.fontWeight = null;
    self.asterisk.e.style.display = 'none';
  });
}

var main = new StandardWindow({
  color: "white",
});
main.addClass('full-window');

var tabs = new TabView();
main.append(tabs);

var hostname = window.location.hash;
var cssKey = "CSS_"+hostname;
var jsKey = "js_"+hostname;

title = span(hostname.slice(1));
title.e.style.fontSize = "25px";
main.toolbar.append(title);

var cssTab = new WSTab({
  color: "blue",
  color2: "white",
  title: "CSS",
  tabs: tabs,
  mode: "css",
  storageKey: 'CSS_'+hostname,
});

var jsTab = new WSTab({
  color: "yellow",
  color2: "black",
  title: "JavaScript",
  tabs: tabs,
  mode: "javascript",
  storageKey: "js_"+hostname,
});

document.body.appendChild(main.e);
<commit_msg>Make unsaved changes indicator disappear when recipe value equals saved one<commit_after>function WSTab(args){
  var self = this;
  var storageKey = String(args.storageKey);
  this.storageKey = storageKey;
  var wind = new StandardWindow({
    color: args.color || "orange",
  });
  this.asterisk = span('*');
  this.asterisk.e.style.display = 'none';
  wind.title = args.title || "Untitled";
  wind.toolbar.left.append(new Button({
    className: ( args.color2 ? args.color2 : 'orange' ) + ' quiet',
    caption: 'Save',
    action: function(){
      self.save();
    },
  }));
  wind.on('keydown', function(e){
    if(e.keyCode === 83 && e.ctrlKey){
      self.save();
      e.stopPropagation();
      e.preventDefault();
    }
  });
  var cm = CodeMirror(wind.body.e, {
    mode: args.mode || '',
    indentWithTabs: false,
    tabSize: 2,
    lineNumbers: true,
    autoRefresh:true,
    theme: 'neat',
  });
  cm.getWrapperElement().classList.add('full-element');
  wind.on('activated', function(){
    cm.refresh();
  });

  chrome.storage.sync.get(storageKey, function(data){
    if(data[storageKey] !== undefined){
      cm.setValue(String(data[storageKey]));
      self.savedValue = String(data[storageKey]);
    }
    else{
      cm.setValue('');
      self.savedValue = '';
    }
    cm.on('change', function(e){
      if(self.savedValue !== cm.getValue()){
        wind.tabViewHandle.e.style.fontWeight = 900;
        self.asterisk.e.style.display = null;
      }
      else{
        self.main.tabViewHandle.e.style.fontWeight = null;
        self.asterisk.e.style.display = 'none';
      }
    });
    cm.refresh();
  });

  this.main = wind;
  this.cm = cm;
  if(args.tabs instanceof Element){
    args.tabs.append(wind);
    wind.tabViewHandle.append(this.asterisk);
  }
}

WSTab.prototype.save = function(){
  var self = this;
  var value = this.cm.getValue();
  var obj = {};
  obj[this.storageKey] = value;
  this.savedValue = value;
  chrome.storage.sync.set(obj, function(){
    self.main.tabViewHandle.e.style.fontWeight = null;
    self.asterisk.e.style.display = 'none';
  });
}

var main = new StandardWindow({
  color: "white",
});
main.addClass('full-window');

var tabs = new TabView();
main.append(tabs);

var hostname = window.location.hash;
var cssKey = "CSS_"+hostname;
var jsKey = "js_"+hostname;

title = span(hostname.slice(1));
title.e.style.fontSize = "25px";
main.toolbar.append(title);

var cssTab = new WSTab({
  color: "blue",
  color2: "white",
  title: "CSS",
  tabs: tabs,
  mode: "css",
  storageKey: 'CSS_'+hostname,
});

var jsTab = new WSTab({
  color: "yellow",
  color2: "black",
  title: "JavaScript",
  tabs: tabs,
  mode: "javascript",
  storageKey: "js_"+hostname,
});

document.body.appendChild(main.e);
<|endoftext|>


<commit_before>import React from 'react';

import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';

import ITEMS from 'common/ITEMS';
import ItemLink from 'common/ItemLink';

export const SPELL_CATEGORY = {
  ROTATIONAL: 'Spell',
  COOLDOWNS: 'Cooldown',
};

const CPM_ABILITIES = [
  {
    spell: SPELLS.SPIRIT_BOMB_TALENT,
    isActive: combatant => combatant.hasTalent(SPELLS.SPIRIT_BOMB_TALENT.id),
    category: SPELL_CATEGORY.ROTATIONAL,
    getCooldown: haste => 18,
    recommendedCastEfficiency: 1.0,
    extraSuggestion: This is your core healing ability. Try to refresh it even if you have just one <SpellLink id={SPELLS.SOUL_FRAGMENT.id} /> available. ,
  },
  {
    spell: SPELLS.IMMOLATION_AURA,
    category: SPELL_CATEGORY.ROTATIONAL,
    getCooldown: haste => 15 / (1 + haste),
    recommendedCastEfficiency: 0.9,
    extraSuggestion: This is a great Pain filler spell. Try to always cast it on cooldown, specially when using <ItemLink id={ITEMS.KIREL_NARAK.id} details={ITEMS.KIREL_NARAK}/> legendary to trigger it's passive. ,
  },
  {
    spell: SPELLS.DEMON_SPIKES,
    isActive: combatant => combatant.hasTalent(SPELLS.RAZOR_SPIKES_TALENT.id),
    category: SPELL_CATEGORY.ROTATIONAL,
    getCooldown: haste => 15 / (1 + haste),
    recommendedCastEfficiency: 1.0,
    extraSuggestion: This is a great physical reduction spell and it also provides a great physical damage increase in your case, giving your <SpellLink id={SPELLS.RAZOR_SPIKES_TALENT.id} /> talent choice. Try to always cast it on cooldown. ,
  },
  {
    spell: SPELLS.DEMON_SPIKES,
    isActive: combatant => !(combatant.hasTalent(SPELLS.RAZOR_SPIKES_TALENT.id)),
    category: SPELL_CATEGORY.ROTATIONAL,
    getCooldown: haste => 15 / (1 + haste),
    recommendedCastEfficiency: 0.75,
    extraSuggestion: This is a great physical reduction spell. Try to always cast it as soons as it gets available or when you expect a higher physical damage. ,
  },
  {
    spell: SPELLS.SOUL_CARVER,
    category: SPELL_CATEGORY.COOLDOWNS,
    getCooldown: haste => 40,
    recommendedCastEfficiency: 0.9,
    extraSuggestion: This is your cooldown <SpellLink id={SPELLS.SOUL_FRAGMENT.id} /> generator spell and it does the higher damage / casting time of all your abilities. The only moment you can delay it's cast is if you already have 5 unused <SpellLink id={SPELLS.SOUL_FRAGMENT.id} /> or if you are waiting for a damage burst combo with <SpellLink id={SPELLS.FIERY_BRAND.id} /> (with the <SpellLink id={SPELLS.FIERY_DEMISE.id} /> artifact trait). ,
  },
  {
    spell: SPELLS.FRACTURE_TALENT,
    isActive: combatant => combatant.hasTalent(SPELLS.FRACTURE_TALENT.id),
    category: SPELL_CATEGORY.ROTATIONAL,
    getCooldown: haste => 5,
    recommendedCastEfficiency: 0.90,
    extraSuggestion: This is your main <SpellLink id={SPELLS.SOUL_FRAGMENT.id} /> generator spell and it does a single target DPS increase by just 30 Pain per cast. The only moment you can delay it's cast is if you already have 5 unused <SpellLink id={SPELLS.SOUL_FRAGMENT.id} />. ,
  },
  {
    spell: SPELLS.FELBLADE_TALENT,
    isActive: combatant => combatant.hasTalent(SPELLS.FELBLADE_TALENT.id),
    category: SPELL_CATEGORY.COOLDOWNS,
    getCooldown: haste => 15,
    recommendedCastEfficiency: 0.90,
    extraSuggestion: This is a great Pain generator spell and it does a single target DPS increase by just 30 Pain per cast. The only moment you can delay it's cast is if you already have 5 unused <SpellLink id={SPELLS.SOUL_FRAGMENT.id} />. ,
  },
  {
    spell: SPELLS.FEL_ERUPTION_TALENT,
    isActive: combatant => combatant.hasTalent(SPELLS.FEL_ERUPTION_TALENT.id),
    category: SPELL_CATEGORY.COOLDOWNS,
    getCooldown: haste => 30,
    recommendedCastEfficiency: 0.95,
    extraSuggestion: This is a great Chaos burst damage spell and it does a huge single target DPS increase by just 10 Pain per cast. Should definitively be used as soon as it gets available. ,
  },
  {
    spell: SPELLS.FEL_DEVASTATION_TALENT,
    isActive: combatant => combatant.hasTalent(SPELLS.FEL_DEVASTATION_TALENT.id),
    category: SPELL_CATEGORY.COOLDOWNS,
    getCooldown: haste => 60,
    recommendedCastEfficiency: 0.55,
    extraSuggestion: This is a great healing and AoE damage burst spell. It costs just 30 Pain and should be definitively used as soon as it gets available. The only moment you can delay it's cast is if your <SpellLink id={SPELLS.FIERY_BRAND.id} /> (with the <SpellLink id={SPELLS.FIERY_DEMISE.id} /> artifact trait) is almost available. ,
  },
  {
    spell: SPELLS.SOUL_BARRIER_TALENT,
    isActive: combatant => combatant.hasTalent(SPELLS.SOUL_BARRIER_TALENT.id),
    category: SPELL_CATEGORY.COOLDOWNS,
    getCooldown: haste => 30,
    recommendedCastEfficiency: 0.50,
    extraSuggestion: This usage can be improved with <SpellLink id={SPELLS.SOUL_CARVER.id} /> for maximum efficiency. Also, this can be used more to soak burst instant damage when used with <SpellLink id={SPELLS.DEMON_SPIKES.id} /> for physical damage or with <SpellLink id={SPELLS.EMPOWER_WARDS.id} /> for magical damage. ,
  },
];

export default CPM_ABILITIES;
<commit_msg>Removed Spirit Bomb from CPM abilities and changed the cooldown for fracture<commit_after>import React from 'react';

import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';

import ITEMS from 'common/ITEMS';
import ItemLink from 'common/ItemLink';

export const SPELL_CATEGORY = {
  ROTATIONAL: 'Spell',
  COOLDOWNS: 'Cooldown',
};

const CPM_ABILITIES = [
  {
    spell: SPELLS.IMMOLATION_AURA,
    category: SPELL_CATEGORY.ROTATIONAL,
    getCooldown: haste => 15 / (1 + haste),
    recommendedCastEfficiency: 0.9,
    extraSuggestion: This is a great Pain filler spell. Try to always cast it on cooldown, specially when using <ItemLink id={ITEMS.KIREL_NARAK.id} details={ITEMS.KIREL_NARAK}/> legendary to trigger it's passive. ,
  },
  {
    spell: SPELLS.DEMON_SPIKES,
    isActive: combatant => combatant.hasTalent(SPELLS.RAZOR_SPIKES_TALENT.id),
    category: SPELL_CATEGORY.ROTATIONAL,
    getCooldown: haste => 15 / (1 + haste),
    recommendedCastEfficiency: 1.0,
    extraSuggestion: This is a great physical reduction spell and it also provides a great physical damage increase in your case, giving your <SpellLink id={SPELLS.RAZOR_SPIKES_TALENT.id} /> talent choice. Try to always cast it on cooldown. ,
  },
  {
    spell: SPELLS.DEMON_SPIKES,
    isActive: combatant => !(combatant.hasTalent(SPELLS.RAZOR_SPIKES_TALENT.id)),
    category: SPELL_CATEGORY.ROTATIONAL,
    getCooldown: haste => 15 / (1 + haste),
    recommendedCastEfficiency: 0.75,
    extraSuggestion: This is a great physical reduction spell. Try to always cast it as soons as it gets available or when you expect a higher physical damage. ,
  },
  {
    spell: SPELLS.SOUL_CARVER,
    category: SPELL_CATEGORY.COOLDOWNS,
    getCooldown: haste => 40,
    recommendedCastEfficiency: 0.9,
    extraSuggestion: This is your cooldown <SpellLink id={SPELLS.SOUL_FRAGMENT.id} /> generator spell and it does the higher damage / casting time of all your abilities. The only moment you can delay it's cast is if you already have 5 unused <SpellLink id={SPELLS.SOUL_FRAGMENT.id} /> or if you are waiting for a damage burst combo with <SpellLink id={SPELLS.FIERY_BRAND.id} /> (with the <SpellLink id={SPELLS.FIERY_DEMISE.id} /> artifact trait). ,
  },
  {
    spell: SPELLS.FRACTURE_TALENT,
    isActive: combatant => combatant.hasTalent(SPELLS.FRACTURE_TALENT.id),
    category: SPELL_CATEGORY.ROTATIONAL,
    getCooldown: haste => 6,
    recommendedCastEfficiency: 0.75,
    extraSuggestion: This is your main <SpellLink id={SPELLS.SOUL_FRAGMENT.id} /> generator spell and it does a single target DPS increase by just 30 Pain per cast. The only moment you can delay it's cast is if you already have 5 unused <SpellLink id={SPELLS.SOUL_FRAGMENT.id} />. ,
  },
  {
    spell: SPELLS.FELBLADE_TALENT,
    isActive: combatant => combatant.hasTalent(SPELLS.FELBLADE_TALENT.id),
    category: SPELL_CATEGORY.COOLDOWNS,
    getCooldown: haste => 15,
    recommendedCastEfficiency: 0.90,
    extraSuggestion: This is a great Pain generator spell and it does a single target DPS increase by just 30 Pain per cast. The only moment you can delay it's cast is if you already have 5 unused <SpellLink id={SPELLS.SOUL_FRAGMENT.id} />. ,
  },
  {
    spell: SPELLS.FEL_ERUPTION_TALENT,
    isActive: combatant => combatant.hasTalent(SPELLS.FEL_ERUPTION_TALENT.id),
    category: SPELL_CATEGORY.COOLDOWNS,
    getCooldown: haste => 30,
    recommendedCastEfficiency: 0.95,
    extraSuggestion: This is a great Chaos burst damage spell and it does a huge single target DPS increase by just 10 Pain per cast. Should definitively be used as soon as it gets available. ,
  },
  {
    spell: SPELLS.FEL_DEVASTATION_TALENT,
    isActive: combatant => combatant.hasTalent(SPELLS.FEL_DEVASTATION_TALENT.id),
    category: SPELL_CATEGORY.COOLDOWNS,
    getCooldown: haste => 60,
    recommendedCastEfficiency: 0.55,
    extraSuggestion: This is a great healing and AoE damage burst spell. It costs just 30 Pain and should be definitively used as soon as it gets available. The only moment you can delay it's cast is if your <SpellLink id={SPELLS.FIERY_BRAND.id} /> (with the <SpellLink id={SPELLS.FIERY_DEMISE.id} /> artifact trait) is almost available. ,
  },
  {
    spell: SPELLS.SOUL_BARRIER_TALENT,
    isActive: combatant => combatant.hasTalent(SPELLS.SOUL_BARRIER_TALENT.id),
    category: SPELL_CATEGORY.COOLDOWNS,
    getCooldown: haste => 30,
    recommendedCastEfficiency: 0.50,
    extraSuggestion: This usage can be improved with <SpellLink id={SPELLS.SOUL_CARVER.id} /> for maximum efficiency. Also, this can be used more to soak burst instant damage when used with <SpellLink id={SPELLS.DEMON_SPIKES.id} /> for physical damage or with <SpellLink id={SPELLS.EMPOWER_WARDS.id} /> for magical damage. ,
  },
];

export default CPM_ABILITIES;
<|endoftext|>


<commit_before>'use strict';

/**
 * uischema.org processor
 *
 * @memberof HashBrown.Server.Entity
 */
class UISchemaProcessor extends HashBrown.Entity.Processor.ProcessorBase {
    /**
     * Performs a value check
     *
     * @param {*} value
     * @param {String} schemaId
     * @param {Object} config
     * @param {String} locale
     *
     * @return {*} Value
     */
    async check(value, schemaId, config, locale) {
        if(value === null || value === undefined || value === '') { return null; }

        if(Array.isArray(value)) {
            schemaId = 'array';
        }

        if(!schemaId) { return value; }

        let schema = await HashBrown.Entity.Resource.FieldSchema.get(this.context, schemaId, { withParentFields: true });

        if(!schema) { return value; }

        // Ensure config
        if(!config) {
            config = {};
        }

        // Merge schema config
        if(schema.config) {
            for(let k in schema.config) {
                if(config[k]) { continue; }

                config[k] = schema.config[k];
            }
        }

        // This schema is a struct
        if(config.struct) {
            schemaId = 'struct';
        }

        let parsed = {};

        switch(schemaId) {
            default:
                parsed = value;
                break;

            case 'array':
                parsed['@type'] = 'ItemList';
                parsed['numberOfItems'] = value.length;
                parsed['itemListElement'] = [];

                for(let i in value) {
                    parsed['itemListElement'].push({
                        '@type': 'ItemListElement',
                        'position': i,
                        'item': await this.check(value[i].value, value[i].schemaId, null, locale)
                    });
                }
                break;

            case 'struct':
                parsed['@type'] = schema.id || 'StructuredValue';

                for(let k in value) {
                    if(!value[k] || !config.struct || !config.struct[k] || !config.struct[k].schemaId) { continue; }

                    parsed[k] = await this.check(value[k], config.struct[k].schemaId, config.struct[k].config, locale);
                }
                break;

            case 'mediaReference':
                let media = await HashBrown.Entity.Resource.Media.get(this.context, value);

                if(!media) { return null; }

                if(media.isImage()) {
                    parsed['@type'] = 'ImageObject';
                } else if(media.isAudio()) {
                    parsed['@type'] = 'AudioObject';
                } else if(media.isVideo()) {
                    parsed['@type'] = 'VideoObject';
                } else if(media.isDocument()) {
                    parsed['@type'] = 'DataDownload';
                } else {
                    parsed['@type'] = 'MediaObject';
                }

                parsed['author'] = media.author;

                if(parsed['author']) {
                    parsed['author']['@type'] = 'Person';
                }

                parsed['copyrightHolder'] = media.copyrightHolder;

                if(parsed['copyrightHolder']) {
                    parsed['copyrightHolder']['@type'] = 'Organization';
                }

                parsed['copyrightYear'] = media.copyrightYear;

                parsed['name'] = media.filename;
                parsed['contentUrl'] = await media.getContentUrl(true);
                parsed['thumbnailUrl'] = await media.getThumbnailUrl(true);
                break;

            case 'contentReference':
                let content = await HashBrown.Entity.Resource.Content.get(this.context, value);

                content = await this.process(content, locale);

                for(let key in content) {
                    parsed[key] = content[key];
                }
                break;
        }

        return parsed;
    }

    /**
     * Compiles content as uischema.org JSON
     *
     * @param {Content} content
     * @param {String} locale
     * @param {Array} filter
     *
     * @returns {Promise} Result
     */
    async process(content, locale = 'en', filter = []) {
        checkParam(content, 'content', HashBrown.Entity.Resource.Content, true);
        checkParam(locale, 'locale', String, true);
        checkParam(filter, 'filter', Array, true);

        let schema = await HashBrown.Entity.Resource.ContentSchema.get(this.context, content.schemaId);
        let properties = content.getLocalizedProperties(locale);
        let meta = content.getMeta();

        if(!properties) {
            throw new Error(`No properties for content "${content.getName()}" with locale "${locale}"`);
        }

        let createdBy = await content.getCreatedBy();
        let updatedBy = await content.getUpdatedBy();

        // We'll have to a allow unknown authors, as they could disappear between backups
        if(!createdBy) {
            createdBy = HashBrown.Entity.User.new({
                fullName: 'Unknown',
                username: 'unknown'
            });
        }

        if(!updatedBy) {
            updatedBy = HashBrown.Entity.User.new({
                fullName: 'Unknown',
                username: 'unknown'
            });
        }

        // Combine all data into one
        let data = {};

        data['@type'] = schema.id;
        data['@parentId'] = content.parentId;
        data['identifier'] = content.id;

        // TODO: Include images here?
        data.creator = {
            '@type': 'Person',
            name: createdBy.getName(),
            email: createdBy.email
        };

        data.author = {
            '@type': 'Person',
            name: updatedBy.getName(),
            email: updatedBy.email
        };

        data.inLanguage = locale;

        data.dateCreated = content.createdOn;
        data.dateModified = content.updatedOn;
        data.datePublished = content.createdOn;

        for(let key in schema.config) {
            if(filter.length > 0 && filter.indexOf(key) < 0) { continue; }

            data[key] = await this.check(properties[key], schema.config[key].schemaId, schema.config[key].config, locale);
        }

        return data;
    }
}

module.exports = UISchemaProcessor;
<commit_msg>Ensured name fiwl in uischema processor<commit_after>'use strict';

/**
 * uischema.org processor
 *
 * @memberof HashBrown.Server.Entity
 */
class UISchemaProcessor extends HashBrown.Entity.Processor.ProcessorBase {
    /**
     * Performs a value check
     *
     * @param {*} value
     * @param {String} schemaId
     * @param {Object} config
     * @param {String} locale
     *
     * @return {*} Value
     */
    async check(value, schemaId, config, locale) {
        if(value === null || value === undefined || value === '') { return null; }

        if(Array.isArray(value)) {
            schemaId = 'array';
        }

        if(!schemaId) { return value; }

        let schema = await HashBrown.Entity.Resource.FieldSchema.get(this.context, schemaId, { withParentFields: true });

        if(!schema) { return value; }

        // Ensure config
        if(!config) {
            config = {};
        }

        // Merge schema config
        if(schema.config) {
            for(let k in schema.config) {
                if(config[k]) { continue; }

                config[k] = schema.config[k];
            }
        }

        // This schema is a struct
        if(config.struct) {
            schemaId = 'struct';
        }

        let parsed = {};

        switch(schemaId) {
            default:
                parsed = value;
                break;

            case 'array':
                parsed['@type'] = 'ItemList';
                parsed['numberOfItems'] = value.length;
                parsed['itemListElement'] = [];

                for(let i in value) {
                    parsed['itemListElement'].push({
                        '@type': 'ItemListElement',
                        'position': i,
                        'item': await this.check(value[i].value, value[i].schemaId, null, locale)
                    });
                }
                break;

            case 'struct':
                parsed['@type'] = schema.id || 'StructuredValue';

                for(let k in value) {
                    if(!value[k] || !config.struct || !config.struct[k] || !config.struct[k].schemaId) { continue; }

                    parsed[k] = await this.check(value[k], config.struct[k].schemaId, config.struct[k].config, locale);
                }
                break;

            case 'mediaReference':
                let media = await HashBrown.Entity.Resource.Media.get(this.context, value);

                if(!media) { return null; }

                if(media.isImage()) {
                    parsed['@type'] = 'ImageObject';
                } else if(media.isAudio()) {
                    parsed['@type'] = 'AudioObject';
                } else if(media.isVideo()) {
                    parsed['@type'] = 'VideoObject';
                } else if(media.isDocument()) {
                    parsed['@type'] = 'DataDownload';
                } else {
                    parsed['@type'] = 'MediaObject';
                }

                parsed['author'] = media.author;

                if(parsed['author']) {
                    parsed['author']['@type'] = 'Person';
                }

                parsed['copyrightHolder'] = media.copyrightHolder;

                if(parsed['copyrightHolder']) {
                    parsed['copyrightHolder']['@type'] = 'Organization';
                }

                parsed['copyrightYear'] = media.copyrightYear;

                parsed['name'] = media.filename;
                parsed['contentUrl'] = await media.getContentUrl(true);
                parsed['thumbnailUrl'] = await media.getThumbnailUrl(true);
                break;

            case 'contentReference':
                let content = await HashBrown.Entity.Resource.Content.get(this.context, value);

                content = await this.process(content, locale);

                for(let key in content) {
                    parsed[key] = content[key];
                }
                break;
        }

        return parsed;
    }

    /**
     * Compiles content as uischema.org JSON
     *
     * @param {Content} content
     * @param {String} locale
     * @param {Array} filter
     *
     * @returns {Promise} Result
     */
    async process(content, locale = 'en', filter = []) {
        checkParam(content, 'content', HashBrown.Entity.Resource.Content, true);
        checkParam(locale, 'locale', String, true);
        checkParam(filter, 'filter', Array, true);

        let schema = await HashBrown.Entity.Resource.ContentSchema.get(this.context, content.schemaId);
        let properties = content.getLocalizedProperties(locale);
        let meta = content.getMeta();

        if(!properties) {
            throw new Error(`No properties for content "${content.getName()}" with locale "${locale}"`);
        }

        let createdBy = await content.getCreatedBy();
        let updatedBy = await content.getUpdatedBy();

        // We'll have to a allow unknown authors, as they could disappear between backups
        if(!createdBy) {
            createdBy = HashBrown.Entity.User.new({
                fullName: 'Unknown',
                username: 'unknown'
            });
        }

        if(!updatedBy) {
            updatedBy = HashBrown.Entity.User.new({
                fullName: 'Unknown',
                username: 'unknown'
            });
        }

        // Combine all data into one
        let data = {};

        data['@type'] = schema.id;
        data['@parentId'] = content.parentId;
        data['identifier'] = content.id;

        if(!content.name && content.title) {
            data.name = content.title;
            delete content.title;
        }

        for(let key in schema.config) {
            if(filter.length > 0 && filter.indexOf(key) < 0) { continue; }

            data[key] = await this.check(properties[key], schema.config[key].schemaId, schema.config[key].config, locale);
        }

        data.creator = {
            '@type': 'Person',
            name: createdBy.getName(),
            email: createdBy.email
        };

        data.author = {
            '@type': 'Person',
            name: updatedBy.getName(),
            email: updatedBy.email
        };

        data.inLanguage = locale;

        data.dateCreated = content.createdOn;
        data.dateModified = content.updatedOn;
        data.datePublished = content.createdOn;

        return data;
    }
}

module.exports = UISchemaProcessor;
<|endoftext|>


<commit_before>var config = require.main.require('./config.js');
var server = require.main.require('./utils/socket-server.js');

// Displays a welcome message to the user and then runs bundle "login". This is the default starting bundle that is run when a user first connects to the MUD.
module.exports = {
	// Called when bundle is loaded
	init : function () {
		this.serverStartTime = new Date();
	},

	// Called when bundle is run
	run : function (socket) {
		socket.emit('output', { msg: "Hello adventurer! Welcome to " + config.info.name + ".

" });
		socket.emit('output', { msg: "Server info" });
		socket.emit('output', { msg: "Active players: " + server.activePlayers });
		socket.emit('output', { msg: "Objects in world: " + server.db.getCollection('objects').count() });
		socket.emit('output', { msg: "Uptime: " + getDuration(this.serverStartTime, new Date()) });
		socket.emit('output', { msg: "
" });

		server.runBundle("login", socket);

	},
}

function getDuration(startDate, endDate) {
	return msToHMS(endDate - startDate);
}

function msToHMS( ms ) {
    // 1- Convert to seconds:
    var seconds = ms / 1000;
    // 2- Extract hours:
    var hours = parseInt( seconds / 3600 ); // 3,600 seconds in 1 hour
    seconds = seconds % 3600; // seconds remaining after extracting hours
    // 3- Extract minutes:
    var minutes = parseInt( seconds / 60 ); // 60 seconds in 1 minute
    // 4- Keep only seconds not extracted to minutes:
    seconds = seconds % 60;
    return hours+" hours, "+minutes+" minutes, "+ Math.round(seconds)+ " seconds";
}<commit_msg>Show supported commands count at welcome<commit_after>var config = require.main.require('./config.js');
var server = require.main.require('./utils/socket-server.js');

// Displays a welcome message to the user and then runs bundle "login". This is the default starting bundle that is run when a user first connects to the MUD.
module.exports = {
	// Called when bundle is loaded
	init : function () {
		this.serverStartTime = new Date();
	},

	// Called when bundle is run
	run : function (socket) {
		socket.emit('output', { msg: "Hello adventurer! Welcome to " + config.info.name + ".

" });
		socket.emit('output', { msg: "Server info" });
		socket.emit('output', { msg: "Active players: " + server.activePlayers });
		socket.emit('output', { msg: "Objects in world: " + server.db.getCollection('objects').count() });
		socket.emit('output', { msg: "Commands supported: " + server.commands.length });
		socket.emit('output', { msg: "Uptime: " + getDuration(this.serverStartTime, new Date()) });
		socket.emit('output', { msg: "
" });

		server.runBundle("login", socket);

	},
}

function getDuration(startDate, endDate) {
	return msToHMS(endDate - startDate);
}

function msToHMS( ms ) {
    // 1- Convert to seconds:
    var seconds = ms / 1000;
    // 2- Extract hours:
    var hours = parseInt( seconds / 3600 ); // 3,600 seconds in 1 hour
    seconds = seconds % 3600; // seconds remaining after extracting hours
    // 3- Extract minutes:
    var minutes = parseInt( seconds / 60 ); // 60 seconds in 1 minute
    // 4- Keep only seconds not extracted to minutes:
    seconds = seconds % 60;
    return hours+" hours, "+minutes+" minutes, "+ Math.round(seconds)+ " seconds";
}<|endoftext|>


<commit_before>/*
This file contains the functions for the menu overlay that operates the book.
*/

/*
Prepares the canvas to be drawn on by storing the canvas object, context, width,
and height as well as sets canvasReady to true.
*/
function init()
{

}

function openMenu() {
    document.getElementById("overlay").style.width = "100%";
}

/* Close when someone clicks on the "x" symbol inside the overlay */
function closeMenu() {
    document.getElementById("overlay").style.width = "0%";
}<commit_msg>Update MenuOverlay.js<commit_after>/*
This file contains the functions for the menu overlay that operates the book.
*/

function openMenu() {
    document.getElementById("overlay").style.width = "100%";
}

/* Close when someone clicks on the "x" symbol inside the overlay */
function closeMenu() {
    document.getElementById("overlay").style.width = "0%";
}
<|endoftext|>


<commit_before>var block_outliers, composite_mapping_fields, do_ajax_post, get_progress, mapping_method_fields, open_mapping_results, outlier_text, showalert, submit_special, toggle_enable_disable, update_time_remaining;

update_time_remaining = function(percent_complete) {
  var minutes_remaining, now, period, total_seconds_remaining;
  now = new Date();
  period = now.getTime() - root.start_time;
  console.log("period is:", period);
  if (period > 8000) {
    total_seconds_remaining = (period / percent_complete * (100 - percent_complete)) / 1000;
    minutes_remaining = Math.round(total_seconds_remaining / 60);
    if (minutes_remaining < 3) {
      return $('#time_remaining').text(Math.round(total_seconds_remaining) + " seconds remaining");
    } else {
      return $('#time_remaining').text(minutes_remaining + " minutes remaining");
    }
  }
};

get_progress = function() {
  var params, params_str, temp_uuid, url;
  console.log("temp_uuid:", $("#temp_uuid").val());
  temp_uuid = $("#temp_uuid").val();
  params = {
    key: temp_uuid
  };
  params_str = $.param(params);
  url = "/get_temp_data?" + params_str;
  console.log("url:", url);
  $.ajax({
    type: "GET",
    url: url,
    success: (function(_this) {
      return function(progress_data) {
        var percent_complete;
        percent_complete = progress_data['percent_complete'];
        console.log("in get_progress data:", progress_data);
        $('#marker_regression_progress').css("width", percent_complete + "%");
        if (root.start_time) {
          if (!isNaN(percent_complete)) {
            return update_time_remaining(percent_complete);
          }
        } else {
          return root.start_time = new Date().getTime();
        }
      };
    })(this)
  });
  return false;
};

block_outliers = function() {
  return $('.outlier').each((function(_this) {
    return function(_index, element) {
      return $(element).find('.trait_value_input').val('x');
    };
  })(this));
};

do_ajax_post = function(url, form_data) {
  $.ajax({
    type: "POST",
    url: url,
    data: form_data,
    error: (function(_this) {
      return function(xhr, ajaxOptions, thrownError) {
        alert("Sorry, an error occurred");
        console.log(xhr);
        clearInterval(_this.my_timer);
        $('#progress_bar_container').modal('hide');
        $('#static_progress_bar_container').modal('hide');
        return $("body").html("We got an error.");
      };
    })(this),
    success: (function(_this) {
      return function(data) {
        clearInterval(_this.my_timer);
        $('#progress_bar_container').modal('hide');
        $('#static_progress_bar_container').modal('hide');
        return open_mapping_results(data);
      };
    })(this)
  });
  console.log("settingInterval");
  this.my_timer = setInterval(get_progress, 1000);
  return false;
};

open_mapping_results = function(data) {
  return $.colorbox({
    html: data,
    href: "#mapping_results_holder",
    height: "90%",
    width: "90%",
    onComplete: (function(_this) {
      return function() {
        var filename, getSvgXml;
        root.create_lod_chart();
        filename = "lod_chart_" + js_data.this_trait;
        getSvgXml = function() {
          var svg;
          svg = $("#topchart").find("svg")[0];
          return (new XMLSerializer).serializeToString(svg);
        };
        $("#exportform > #export").click(function() {
          var form, svg_xml;
          svg_xml = getSvgXml();
          form = $("#exportform");
          form.find("#data").val(svg_xml);
          form.find("#filename").val(filename);
          return form.submit();
        });
        return $("#exportpdfform > #export_pdf").click(function() {
          var form, svg_xml;
          svg_xml = getSvgXml();
          form = $("#exportpdfform");
          form.find("#data").val(svg_xml);
          form.find("#filename").val(filename);
          return form.submit();
        });
      };
    })(this)
  });
};

outlier_text = "One or more outliers exist in this data set. Please review values before mapping. Including outliers when mapping may lead to misleading results.";
showalert = function(message, alerttype) {
  return $('#outlier_alert_placeholder').append('
�' + message + '
');
};

$('#suggestive').hide();

$('input[name=display_all]').change((function(_this) {
  return function() {
    console.log("check");
    if ($('input[name=display_all]:checked').val() === "False") {
      return $('#suggestive').show();
    } else {
      return $('#suggestive').hide();
    }
  };
})(this));

//ZS: This is a list of inputs to be passed to the loading page, since not all inputs on the trait page are relevant to mapping
var mapping_input_list = ['temp_uuid', 'trait_id', 'dataset', 'tool_used', 'form_url', 'method', 'transform', 'trimmed_markers', 'selected_chr', 'chromosomes', 'mapping_scale', 'sample_vals',
                          'score_type', 'suggestive', 'significant', 'num_perm', 'permCheck', 'perm_output', 'perm_strata', 'categorical_vars', 'num_bootstrap', 'bootCheck', 'bootstrap_results',
                          'LRSCheck', 'covariates', 'maf', 'use_loco', 'manhattan_plot', 'control_marker', 'do_control', 'genofile',
                          'pair_scan', 'startMb', 'endMb', 'graphWidth', 'lrsMax', 'additiveCheck', 'showSNP', 'showGenes', 'viewLegend', 'haplotypeAnalystCheck',
                          'mapmethod_rqtl_geno', 'mapmodel_rqtl_geno', 'temp_trait', 'group', 'species', 'reaper_version', 'primary_samples']

$(".rqtl-geno-tab, #rqtl_geno_compute").on("click", (function(_this) {
  return function() {
    if ($(this).hasClass('active') || $(this).attr('id') == "rqtl_geno_compute"){
      var form_data, url;
      url = "/loading";
      $('input[name=method]').val("rqtl_geno");
      $('input[name=selected_chr]').val($('#chr_rqtl_geno').val());
      $('input[name=mapping_scale]').val($('#scale_rqtl_geno').val());
      $('input[name=genofile]').val($('#genofile_rqtl_geno').val());
      $('input[name=mapmodel_rqtl]').val($('#mapmodel_rqtl_geno').val());
      $('input[name=mapmethod_rqtl]').val($('#mapmethod_rqtl_geno').val());
      $('input[name=num_perm]').val($('input[name=num_perm_rqtl_geno]').val());
      $('input[name=categorical_vars]').val(js_data.categorical_vars)
      $('input[name=manhattan_plot]').val($('input[name=manhattan_plot_rqtl]:checked').val());
      $('input[name=control_marker]').val($('input[name=control_rqtl_geno]').val());
      $('input[name=do_control]').val($('input[name=do_control_rqtl]:checked').val());
      $('input[name=tool_used]').val("Mapping");
      $('input[name=form_url]').val("/run_mapping");
      $('input[name=wanted_inputs]').val(mapping_input_list.join(","));
      return submit_special(url);
    } else {
      return true
    }
  };
})(this));

$(".rqtl-pair-tab, #rqtl_pair_compute").on("click", (function(_this) {
  return function() {
    if ($(this).hasClass('active') || $(this).attr('id') == "rqtl_pair_compute"){
      var form_data, url;
      url = "/loading";
      $('input[name=method]').val("rqtl_geno");
      $('input[name=pair_scan]').val("");
      $('input[name=genofile]').val($('#genofile_rqtl_pair').val());
      $('input[name=mapmodel_rqtl]').val($('#mapmodel_rqtl_pair').val());
      $('input[name=mapmethod_rqtl]').val($('#mapmethod_rqtl_pair').val());
      $('input[name=num_perm]').val($('input[name=num_perm_rqtl_pair]').val());
      $('input[name=categorical_vars]').val(js_data.categorical_vars)
      $('input[name=control_marker]').val($('input[name=control_rqtl_pair]').val());
      $('input[name=do_control]').val($('input[name=do_control_rqtl_pair]:checked').val());
      $('input[name=tool_used]').val("Mapping");
      $('input[name=form_url]').val("/run_mapping");
      $('input[name=wanted_inputs]').val(mapping_input_list.join(","));
      return submit_special(url);
    } else {
      return true
    }
  };
})(this));

$(".gemma-tab, #gemma_compute").on("click", (function(_this) {
  return function() {
    if ($(this).hasClass('active') || $(this).attr('id') == "gemma_compute"){
      var form_data, url;
      url = "/loading";
      $('input[name=method]').val("gemma");
      $('input[name=selected_chr]').val($('#chr_gemma').val());
      $('input[name=num_perm]').val(0);
      $('input[name=genofile]').val($('#genofile_gemma').val());
      $('input[name=maf]').val($('input[name=maf_gemma]').val());
      $('input[name=tool_used]').val("Mapping");
      $('input[name=form_url]').val("/run_mapping");
      $('input[name=wanted_inputs]').val(mapping_input_list.join(","));
      return submit_special(url);
    } else {
      return true
    }
  };
})(this));

$(".reaper-tab, #interval_mapping_compute").on("click", (function(_this) {
  return function() {
    if ($(this).hasClass('active') || $(this).attr('id') == "interval_mapping_compute"){
      var form_data, url;
      console.log("In interval mapping");
      url = "/loading";
      $('input[name=method]').val("reaper");
      $('input[name=selected_chr]').val($('#chr_reaper').val());
      $('input[name=mapping_scale]').val($('#scale_reaper').val());
      $('input[name=genofile]').val($('#genofile_reaper').val());
      $('input[name=num_perm]').val($('input[name=num_perm_reaper]').val());
      $('input[name=control_marker]').val($('input[name=control_reaper]').val());
      $('input[name=do_control]').val($('input[name=do_control_reaper]:checked').val());
      $('input[name=manhattan_plot]').val($('input[name=manhattan_plot_reaper]:checked').val());
      $('input[name=mapping_display_all]').val($('input[name=display_all_reaper]'));
      $('input[name=suggestive]').val($('input[name=suggestive_reaper]'));
      $('input[name=tool_used]').val("Mapping");
      $('input[name=form_url]').val("/run_mapping");
      $('input[name=wanted_inputs]').val(mapping_input_list.join(","));
      return submit_special(url);
    } else {
      return true
    }
  };
})(this));

$("#interval_mapping_compute, #gemma_compute, rqtl_geno_compute").on("mouseover", (function(_this) {
  return function() {
    if ($(".outlier").length && $(".outlier-alert").length < 1) {
      return showalert(outlier_text, "alert-success outlier-alert");
    }
  };
})(this));

composite_mapping_fields = function() {
  return $(".composite_fields").toggle();
};

mapping_method_fields = function() {
  return $(".mapping_method_fields").toggle();
};

$("#use_composite_choice").change(composite_mapping_fields);

$("#mapping_method_choice").change(mapping_method_fields);

$("#mapmodel_rqtl_geno,#mapmodel_rqtl_pair").change(function() {
  if ($(this).val() == "np"){
    $("#mapmethod_rqtl_geno").attr('disabled', 'disabled');
    $("#mapmethod_rqtl_geno").css('background-color', '#CCC');
    $("#missing_geno,#missing_geno_pair").attr('disabled', 'disabled');
    $("#missing_geno,#missing_geno_pair").css('background-color', '#CCC');
  } else {
    $("#mapmethod_rqtl_geno").removeAttr('disabled');
    $("#mapmethod_rqtl_geno").css('background-color', '#FFF');
    $("#missing_geno,#missing_geno_pair").removeAttr('disabled');
    $("#missing_geno,#missing_geno_pair").css('background-color', '#FFF');
  }
});

$("#mapmethod_rqtl_geno,#mapmethod_rqtl_pair").change(function() {
  console.log("IN IT")
  if ($(this).val() == "mr"){
    $("#missing_geno_div,#missing_geno_pair_div").css('display', 'block');
  } else {
    $("#missing_geno_div,#missing_geno_pair_div").css('display', 'none');
  }
});

$("li.mapping-tab").click(function() {
  if ($(this).hasClass("rqtl")){
    $(".rqtl_description").css("display", "block");
  } else {
    $(".rqtl_description").css("display", "none");
  }
});

toggle_enable_disable = function(elem) {
  return $(elem).prop("disabled", !$(elem).prop("disabled"));
};

$("#choose_closet_control").change(function() {
  return toggle_enable_disable("#control_locus");
});

$("#display_all_lrs").change(function() {
  return toggle_enable_disable("#suggestive_lrs");
});

$('#genofile_rqtl_geno').change(function() {
  geno_location = $(this).children("option:selected").val().split(":")[0]
  $('#scale_rqtl_geno').empty()
  the_scales = js_data.scales_in_geno[geno_location]
  for (var i = 0; i < the_scales.length; i++){
    $('#scale_rqtl_geno').append($("<option></option>").attr("value", the_scales[i][0]).text(the_scales[i][1]));
  }
});
$('#genofile_reaper').change(function() {
  geno_location = $(this).children("option:selected").val().split(":")[0]
  $('#scale_reaper').empty()
  the_scales = js_data.scales_in_geno[geno_location]
  for (var i = 0; i < the_scales.length; i++){
    $('#scale_reaper').append($("<option></option>").attr("value", the_scales[i][0]).text(the_scales[i][1]));
  }
});
<commit_msg>Fixed mapmethod/mapmodel variables names in mapping_input_list<commit_after>var block_outliers, composite_mapping_fields, do_ajax_post, get_progress, mapping_method_fields, open_mapping_results, outlier_text, showalert, submit_special, toggle_enable_disable, update_time_remaining;

update_time_remaining = function(percent_complete) {
  var minutes_remaining, now, period, total_seconds_remaining;
  now = new Date();
  period = now.getTime() - root.start_time;
  console.log("period is:", period);
  if (period > 8000) {
    total_seconds_remaining = (period / percent_complete * (100 - percent_complete)) / 1000;
    minutes_remaining = Math.round(total_seconds_remaining / 60);
    if (minutes_remaining < 3) {
      return $('#time_remaining').text(Math.round(total_seconds_remaining) + " seconds remaining");
    } else {
      return $('#time_remaining').text(minutes_remaining + " minutes remaining");
    }
  }
};

get_progress = function() {
  var params, params_str, temp_uuid, url;
  console.log("temp_uuid:", $("#temp_uuid").val());
  temp_uuid = $("#temp_uuid").val();
  params = {
    key: temp_uuid
  };
  params_str = $.param(params);
  url = "/get_temp_data?" + params_str;
  console.log("url:", url);
  $.ajax({
    type: "GET",
    url: url,
    success: (function(_this) {
      return function(progress_data) {
        var percent_complete;
        percent_complete = progress_data['percent_complete'];
        console.log("in get_progress data:", progress_data);
        $('#marker_regression_progress').css("width", percent_complete + "%");
        if (root.start_time) {
          if (!isNaN(percent_complete)) {
            return update_time_remaining(percent_complete);
          }
        } else {
          return root.start_time = new Date().getTime();
        }
      };
    })(this)
  });
  return false;
};

block_outliers = function() {
  return $('.outlier').each((function(_this) {
    return function(_index, element) {
      return $(element).find('.trait_value_input').val('x');
    };
  })(this));
};

do_ajax_post = function(url, form_data) {
  $.ajax({
    type: "POST",
    url: url,
    data: form_data,
    error: (function(_this) {
      return function(xhr, ajaxOptions, thrownError) {
        alert("Sorry, an error occurred");
        console.log(xhr);
        clearInterval(_this.my_timer);
        $('#progress_bar_container').modal('hide');
        $('#static_progress_bar_container').modal('hide');
        return $("body").html("We got an error.");
      };
    })(this),
    success: (function(_this) {
      return function(data) {
        clearInterval(_this.my_timer);
        $('#progress_bar_container').modal('hide');
        $('#static_progress_bar_container').modal('hide');
        return open_mapping_results(data);
      };
    })(this)
  });
  console.log("settingInterval");
  this.my_timer = setInterval(get_progress, 1000);
  return false;
};

open_mapping_results = function(data) {
  return $.colorbox({
    html: data,
    href: "#mapping_results_holder",
    height: "90%",
    width: "90%",
    onComplete: (function(_this) {
      return function() {
        var filename, getSvgXml;
        root.create_lod_chart();
        filename = "lod_chart_" + js_data.this_trait;
        getSvgXml = function() {
          var svg;
          svg = $("#topchart").find("svg")[0];
          return (new XMLSerializer).serializeToString(svg);
        };
        $("#exportform > #export").click(function() {
          var form, svg_xml;
          svg_xml = getSvgXml();
          form = $("#exportform");
          form.find("#data").val(svg_xml);
          form.find("#filename").val(filename);
          return form.submit();
        });
        return $("#exportpdfform > #export_pdf").click(function() {
          var form, svg_xml;
          svg_xml = getSvgXml();
          form = $("#exportpdfform");
          form.find("#data").val(svg_xml);
          form.find("#filename").val(filename);
          return form.submit();
        });
      };
    })(this)
  });
};

outlier_text = "One or more outliers exist in this data set. Please review values before mapping. Including outliers when mapping may lead to misleading results.";
showalert = function(message, alerttype) {
  return $('#outlier_alert_placeholder').append('
�' + message + '
');
};

$('#suggestive').hide();

$('input[name=display_all]').change((function(_this) {
  return function() {
    console.log("check");
    if ($('input[name=display_all]:checked').val() === "False") {
      return $('#suggestive').show();
    } else {
      return $('#suggestive').hide();
    }
  };
})(this));

//ZS: This is a list of inputs to be passed to the loading page, since not all inputs on the trait page are relevant to mapping
var mapping_input_list = ['temp_uuid', 'trait_id', 'dataset', 'tool_used', 'form_url', 'method', 'transform', 'trimmed_markers', 'selected_chr', 'chromosomes', 'mapping_scale', 'sample_vals',
                          'score_type', 'suggestive', 'significant', 'num_perm', 'permCheck', 'perm_output', 'perm_strata', 'categorical_vars', 'num_bootstrap', 'bootCheck', 'bootstrap_results',
                          'LRSCheck', 'covariates', 'maf', 'use_loco', 'manhattan_plot', 'control_marker', 'do_control', 'genofile',
                          'pair_scan', 'startMb', 'endMb', 'graphWidth', 'lrsMax', 'additiveCheck', 'showSNP', 'showGenes', 'viewLegend', 'haplotypeAnalystCheck',
                          'mapmethod_rqtl', 'mapmodel_rqtl', 'temp_trait', 'group', 'species', 'reaper_version', 'primary_samples']

$(".rqtl-geno-tab, #rqtl_geno_compute").on("click", (function(_this) {
  return function() {
    if ($(this).hasClass('active') || $(this).attr('id') == "rqtl_geno_compute"){
      var form_data, url;
      url = "/loading";
      $('input[name=method]').val("rqtl_geno");
      $('input[name=selected_chr]').val($('#chr_rqtl_geno').val());
      $('input[name=mapping_scale]').val($('#scale_rqtl_geno').val());
      $('input[name=genofile]').val($('#genofile_rqtl_geno').val());
      $('input[name=mapmodel_rqtl]').val($('#mapmodel_rqtl_geno').val());
      $('input[name=mapmethod_rqtl]').val($('#mapmethod_rqtl_geno').val());
      $('input[name=num_perm]').val($('input[name=num_perm_rqtl_geno]').val());
      $('input[name=categorical_vars]').val(js_data.categorical_vars)
      $('input[name=manhattan_plot]').val($('input[name=manhattan_plot_rqtl]:checked').val());
      $('input[name=control_marker]').val($('input[name=control_rqtl_geno]').val());
      $('input[name=do_control]').val($('input[name=do_control_rqtl]:checked').val());
      $('input[name=tool_used]').val("Mapping");
      $('input[name=form_url]').val("/run_mapping");
      $('input[name=wanted_inputs]').val(mapping_input_list.join(","));
      return submit_special(url);
    } else {
      return true
    }
  };
})(this));

$(".rqtl-pair-tab, #rqtl_pair_compute").on("click", (function(_this) {
  return function() {
    if ($(this).hasClass('active') || $(this).attr('id') == "rqtl_pair_compute"){
      var form_data, url;
      url = "/loading";
      $('input[name=method]').val("rqtl_geno");
      $('input[name=pair_scan]').val("");
      $('input[name=genofile]').val($('#genofile_rqtl_pair').val());
      $('input[name=mapmodel_rqtl]').val($('#mapmodel_rqtl_pair').val());
      $('input[name=mapmethod_rqtl]').val($('#mapmethod_rqtl_pair').val());
      $('input[name=num_perm]').val($('input[name=num_perm_rqtl_pair]').val());
      $('input[name=categorical_vars]').val(js_data.categorical_vars)
      $('input[name=control_marker]').val($('input[name=control_rqtl_pair]').val());
      $('input[name=do_control]').val($('input[name=do_control_rqtl_pair]:checked').val());
      $('input[name=tool_used]').val("Mapping");
      $('input[name=form_url]').val("/run_mapping");
      $('input[name=wanted_inputs]').val(mapping_input_list.join(","));
      return submit_special(url);
    } else {
      return true
    }
  };
})(this));

$(".gemma-tab, #gemma_compute").on("click", (function(_this) {
  return function() {
    if ($(this).hasClass('active') || $(this).attr('id') == "gemma_compute"){
      var form_data, url;
      url = "/loading";
      $('input[name=method]').val("gemma");
      $('input[name=selected_chr]').val($('#chr_gemma').val());
      $('input[name=num_perm]').val(0);
      $('input[name=genofile]').val($('#genofile_gemma').val());
      $('input[name=maf]').val($('input[name=maf_gemma]').val());
      $('input[name=tool_used]').val("Mapping");
      $('input[name=form_url]').val("/run_mapping");
      $('input[name=wanted_inputs]').val(mapping_input_list.join(","));
      return submit_special(url);
    } else {
      return true
    }
  };
})(this));

$(".reaper-tab, #interval_mapping_compute").on("click", (function(_this) {
  return function() {
    if ($(this).hasClass('active') || $(this).attr('id') == "interval_mapping_compute"){
      var form_data, url;
      console.log("In interval mapping");
      url = "/loading";
      $('input[name=method]').val("reaper");
      $('input[name=selected_chr]').val($('#chr_reaper').val());
      $('input[name=mapping_scale]').val($('#scale_reaper').val());
      $('input[name=genofile]').val($('#genofile_reaper').val());
      $('input[name=num_perm]').val($('input[name=num_perm_reaper]').val());
      $('input[name=control_marker]').val($('input[name=control_reaper]').val());
      $('input[name=do_control]').val($('input[name=do_control_reaper]:checked').val());
      $('input[name=manhattan_plot]').val($('input[name=manhattan_plot_reaper]:checked').val());
      $('input[name=mapping_display_all]').val($('input[name=display_all_reaper]'));
      $('input[name=suggestive]').val($('input[name=suggestive_reaper]'));
      $('input[name=tool_used]').val("Mapping");
      $('input[name=form_url]').val("/run_mapping");
      $('input[name=wanted_inputs]').val(mapping_input_list.join(","));
      return submit_special(url);
    } else {
      return true
    }
  };
})(this));

$("#interval_mapping_compute, #gemma_compute, rqtl_geno_compute").on("mouseover", (function(_this) {
  return function() {
    if ($(".outlier").length && $(".outlier-alert").length < 1) {
      return showalert(outlier_text, "alert-success outlier-alert");
    }
  };
})(this));

composite_mapping_fields = function() {
  return $(".composite_fields").toggle();
};

mapping_method_fields = function() {
  return $(".mapping_method_fields").toggle();
};

$("#use_composite_choice").change(composite_mapping_fields);

$("#mapping_method_choice").change(mapping_method_fields);

$("#mapmodel_rqtl_geno,#mapmodel_rqtl_pair").change(function() {
  if ($(this).val() == "np"){
    $("#mapmethod_rqtl_geno").attr('disabled', 'disabled');
    $("#mapmethod_rqtl_geno").css('background-color', '#CCC');
    $("#missing_geno,#missing_geno_pair").attr('disabled', 'disabled');
    $("#missing_geno,#missing_geno_pair").css('background-color', '#CCC');
  } else {
    $("#mapmethod_rqtl_geno").removeAttr('disabled');
    $("#mapmethod_rqtl_geno").css('background-color', '#FFF');
    $("#missing_geno,#missing_geno_pair").removeAttr('disabled');
    $("#missing_geno,#missing_geno_pair").css('background-color', '#FFF');
  }
});

$("#mapmethod_rqtl_geno,#mapmethod_rqtl_pair").change(function() {
  if ($(this).val() == "mr"){
    $("#missing_geno_div,#missing_geno_pair_div").css('display', 'block');
  } else {
    $("#missing_geno_div,#missing_geno_pair_div").css('display', 'none');
  }
});

$("li.mapping-tab").click(function() {
  if ($(this).hasClass("rqtl")){
    $(".rqtl_description").css("display", "block");
  } else {
    $(".rqtl_description").css("display", "none");
  }
});

toggle_enable_disable = function(elem) {
  return $(elem).prop("disabled", !$(elem).prop("disabled"));
};

$("#choose_closet_control").change(function() {
  return toggle_enable_disable("#control_locus");
});

$("#display_all_lrs").change(function() {
  return toggle_enable_disable("#suggestive_lrs");
});

$('#genofile_rqtl_geno').change(function() {
  geno_location = $(this).children("option:selected").val().split(":")[0]
  $('#scale_rqtl_geno').empty()
  the_scales = js_data.scales_in_geno[geno_location]
  for (var i = 0; i < the_scales.length; i++){
    $('#scale_rqtl_geno').append($("<option></option>").attr("value", the_scales[i][0]).text(the_scales[i][1]));
  }
});
$('#genofile_reaper').change(function() {
  geno_location = $(this).children("option:selected").val().split(":")[0]
  $('#scale_reaper').empty()
  the_scales = js_data.scales_in_geno[geno_location]
  for (var i = 0; i < the_scales.length; i++){
    $('#scale_reaper').append($("<option></option>").attr("value", the_scales[i][0]).text(the_scales[i][1]));
  }
});
<|endoftext|>


<commit_before>define(function(require, exports, module) {
    "use strict";

    var app = require("app");
    var AbstractView = require("modules/view/AbstractView");
    var ArticleRegistView = require("modules/view/posting/news/ArticleRegistView");
    var DateUtil = require("modules/util/DateUtil");
    var CommonUtil = require("modules/util/CommonUtil");
    var vexDialog = require("vexDialog");

    /**
     * 記事登録確認画面のViewクラス
     *
     * @class 記事登録確認画面のViewクラス
     * @exports ArticleRegistConfirmView
     * @constructor
     */
    var ArticleRegistConfirmView = AbstractView.extend({
        template : require("ldsh!templates/{mode}/news/articleRegistConfirm"),
        beforeRendered : function() {

        },

        afterRendered : function() {
            // 日時
            var dateString = this.model.getDateString();
            $("#articleDateTime").html(dateString);

            // 掲載期間
            var pubDateString = this.model.getPubDateString();
            $("#articlePublishRange").text("掲載期間：" + pubDateString);

            // 内容
            $("#articleDescription").html(CommonUtil.sanitizing(this.model.get("description")));

            // 連絡先
            $("#articleContactInfo").html(CommonUtil.sanitizing(this.model.get("contactInfo")));

            // 画像
            var $figure = this.$el.find('[data-figure]');
            var images = this.model.get('images');
            var imgIndex = 0;

            $figure.each(function (i) {
                var $image = $(this).find('[data-figure-image]');
                var $caption = $(this).find('[data-figure-caption]');
                var image = images[i];

                if (!image) {
                    return true;
                }

                $image.attr('src', image.src);
                $caption.text(image.comment);
            });

            // おすすめ
            $("#articleRecommend").text($("#articleRecommendCheck").is(":checked") ? "する":"しない");
        },

        /**
         *  初期化処理
         */
        initialize : function() {
        },

        events : {
            "click #articleBackButton" : "onClickArticleBackButton",
            "click #articleRegistButton" : "onClickArticleRegistButton"
        },

        /**
         * 戻るボタンを押下された際に呼び出されるコールバック関数。
         */
        onClickArticleBackButton : function(){
            this.$el.remove();
            $("#articleRegistPage").show();
            $("#snap-content").scrollTop(0);
        },

        /**
         * 登録するボタンが押下された際に呼び出されるコールバック関数。
         */
        onClickArticleRegistButton : function() {
            this.showLoading();
            this.saveArticlePicture();
        },
        /**
         * 添付された画像をdavへ登録する
         */
        saveArticlePicture : function() {
            var imageCount = this.model.get("images").length;
            if(imageCount === 0){
                this.hideLoading();
                this.saveModel();
                return;
            }
            _.each(this.model.get("images"), $.proxy(function(image){
                if(image.data){
                    app.box.col("dav").put(image.fileName, {
                        body : image.data,
                        headers : {
                            "Content-Type" : image.contentType,
                            "If-Match" : "*"
                        },
                        success : $.proxy(function(e){
                            if(--imageCount <= 0){
                                this.saveModel();
                            }
                        }, this),
                        error: $.proxy(function(e){
                            this.hideLoading();
                            vexDialog.defaultOptions.className = 'vex-theme-default';
                            vexDialog.alert("保存に失敗しました。");
                            app.logger.error("保存に失敗しました。");
                        }, this)
                    });
                }else{
                    if(--imageCount <= 0){
                        this.saveModel();
                    }
                }
            }, this));
        },
        /**
         * Modelの保存
         */
        saveModel : function(){
            this.model.save(null, {
                success : $.proxy(function() {
                    if (Backbone.history.fragment == 'opeArticleRegist') {
                        app.router.go("ope-top");
                        return;
                    }
                    app.router.go("posting-top");
                }, this),
                error: function(e){
                    this.hideLoading();
                    vexDialog.alert("保存に失敗しました。");
                    app.logger.error("保存に失敗しました。");
                }
            });
        }
    });
    module.exports = ArticleRegistConfirmView;
});
<commit_msg>NAM-503 管理：確認画面が先頭から表示されない<commit_after>define(function(require, exports, module) {
    "use strict";

    var app = require("app");
    var AbstractView = require("modules/view/AbstractView");
    var ArticleRegistView = require("modules/view/posting/news/ArticleRegistView");
    var DateUtil = require("modules/util/DateUtil");
    var CommonUtil = require("modules/util/CommonUtil");
    var vexDialog = require("vexDialog");

    /**
     * 記事登録確認画面のViewクラス
     *
     * @class 記事登録確認画面のViewクラス
     * @exports ArticleRegistConfirmView
     * @constructor
     */
    var ArticleRegistConfirmView = AbstractView.extend({
        template : require("ldsh!templates/{mode}/news/articleRegistConfirm"),
        beforeRendered : function() {

        },

        afterRendered : function() {
            // 日時
            var dateString = this.model.getDateString();
            $("#articleDateTime").html(dateString);

            // 掲載期間
            var pubDateString = this.model.getPubDateString();
            $("#articlePublishRange").text("掲載期間：" + pubDateString);

            // 内容
            $("#articleDescription").html(CommonUtil.sanitizing(this.model.get("description")));

            // 連絡先
            $("#articleContactInfo").html(CommonUtil.sanitizing(this.model.get("contactInfo")));

            // 画像
            var $figure = this.$el.find('[data-figure]');
            var images = this.model.get('images');
            var imgIndex = 0;

            $figure.each(function (i) {
                var $image = $(this).find('[data-figure-image]');
                var $caption = $(this).find('[data-figure-caption]');
                var image = images[i];

                if (!image) {
                    return true;
                }

                $image.attr('src', image.src);
                $caption.text(image.comment);
            });

            // おすすめ
            $("#articleRecommend").text($("#articleRecommendCheck").is(":checked") ? "する":"しない");
        },

        /**
         *  初期化処理
         */
        initialize : function() {
        },

        events : {
            "click #articleBackButton" : "onClickArticleBackButton",
            "click #articleRegistButton" : "onClickArticleRegistButton"
        },

        /**
         * 戻るボタンを押下された際に呼び出されるコールバック関数。
         */
        onClickArticleBackButton : function(){
            this.$el.remove();
            $("#articleRegistPage").show();
            $("#snap-content").scrollTop(0);
            $("#contents__primary").scrollTop(0);
        },

        /**
         * 登録するボタンが押下された際に呼び出されるコールバック関数。
         */
        onClickArticleRegistButton : function() {
            this.showLoading();
            this.saveArticlePicture();
        },
        /**
         * 添付された画像をdavへ登録する
         */
        saveArticlePicture : function() {
            var imageCount = this.model.get("images").length;
            if(imageCount === 0){
                this.hideLoading();
                this.saveModel();
                return;
            }
            _.each(this.model.get("images"), $.proxy(function(image){
                if(image.data){
                    app.box.col("dav").put(image.fileName, {
                        body : image.data,
                        headers : {
                            "Content-Type" : image.contentType,
                            "If-Match" : "*"
                        },
                        success : $.proxy(function(e){
                            if(--imageCount <= 0){
                                this.saveModel();
                            }
                        }, this),
                        error: $.proxy(function(e){
                            this.hideLoading();
                            vexDialog.defaultOptions.className = 'vex-theme-default';
                            vexDialog.alert("保存に失敗しました。");
                            app.logger.error("保存に失敗しました。");
                        }, this)
                    });
                }else{
                    if(--imageCount <= 0){
                        this.saveModel();
                    }
                }
            }, this));
        },
        /**
         * Modelの保存
         */
        saveModel : function(){
            this.model.save(null, {
                success : $.proxy(function() {
                    if (Backbone.history.fragment == 'opeArticleRegist') {
                        app.router.go("ope-top");
                        return;
                    }
                    app.router.go("posting-top");
                }, this),
                error: function(e){
                    this.hideLoading();
                    vexDialog.alert("保存に失敗しました。");
                    app.logger.error("保存に失敗しました。");
                }
            });
        }
    });
    module.exports = ArticleRegistConfirmView;
});
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
(function() {

var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;

var MimeHeaderParser = Cc['@mozilla.org/messenger/headerparser;1']
                         .getService(Ci.nsIMsgHeaderParser);

var { Services } = Cu.import('resource://gre/modules/Services.jsm');

var BASE = 'extensions.send-to-internals@clear-code.com.';

function log(...aArgs) {
  if (Services.prefs.getBoolPref(BASE+'debug'))
    Services.console.logStringMessage('send-to-internals: '+aArgs.join(', '));
}

var SendToInternalsHelper = {
  get bundle() {
    return document.getElementById('sendToInternalsBundle');
  },

  get internalDomains() {
    var internalDomains = Services.prefs.getComplexValue(BASE + 'domains', Ci.nsISupportsString).data;
    log('(raw internalDomains: '+internalDomains+')');
    return internalDomains
             .split(/[,\|\s]+/)
             .map(function(aDomain) {
               return aDomain.trim();
             })
             .filter(function(aDomain) {
               return aDomain;
             });
  },

  get internalMatcher() {
    var expression = this.internalDomains.map(function(aDomain) {
          return '@' + aDomain.replace(/^@^/, '').replace(/\./g, '\\.').replace(/\+/g, '\\+');
        }).join('|')
    return new RegExp(expression);
  },

  get lastField() {
    var dummyRow = awGetNextDummyRow();
    if (dummyRow)
      return dummyRow.previousSibling;

    var listbox = document.getElementById('addressingWidget');
    return listbox.lastChild;
  },

  checkInternals : function()
  {
    log('checkInternals');
    var internalDomains = this.internalDomains;
    log('internalDomains: '+internalDomains);
    var externals = this.getAllRecipients().filter(function(aAddress, aIndex) {
      log('recipient '+aIndex+' / '+aAddress.address);
      var domain = aAddress.address.split('@')[1];
      log('  domain = '+domain);
      var index = internalDomains.indexOf(domain);
      log('  index = '+index);
      return index < 0;
    }, this);

    log('externals = '+externals.length);
    if (externals.length !== 0) {
      this.highlightExternals();
      Services.prompt.alert(
        window,
        this.bundle.getString('alert.haveExternals.title'),
        this.bundle.getFormattedString('alert.haveExternals.text', externals.map(function(aAddress) {
          return aAddress.address;
        }))
      );
      return false;
    }

    return true;
  },

  highlightExternals : function()
  {
    log('highlightExternals');
    var addressFields = document.querySelectorAll('.textbox-addressingWidget');
    log('  addressFields = ' + addressFields.length);
    Array.forEach(addressFields, this.updateExternalHighlight, this);
  },

  HIGHLIGHT : 'data-send-to-internals-external-address',

  updateExternalHighlight : function(aField)
  {
    var matcher = this.internalMatcher;
    var value = aField.value.trim();
    log('updateExternalHighlight ' + aField.id + ' / ' + value + ' (' + matcher.test(value) + ')');
    if (value && (!matcher || !matcher.test(value)))
      aField.setAttribute(this.HIGHLIGHT, true);
    else
      aField.removeAttribute(this.HIGHLIGHT);
  },

  getAllRecipients : function()
  {
    var msgCompFields = gMsgCompose.compFields;
    Recipients2CompFields(msgCompFields);
    gMsgCompose.expandMailingLists();
    return this.splitRecipients(msgCompFields.to, 'To')
    		.concat(this.splitRecipients(msgCompFields.cc, 'Cc'))
            .concat(this.splitRecipients(msgCompFields.bcc, 'Bcc'));
  },

  splitRecipients : function(aAddressesSource, aType)
  {
    var addresses = {};
    var names = {};
    var fullNames = {};
    var numAddresses = MimeHeaderParser.parseHeadersWithArray(
                         aAddressesSource, addresses, names, fullNames);
    var recipients = [];
    for (let i = 0; i < numAddresses; i++) {
      let address = addresses.value[i];
      let domain = address.split('@')[1];
      recipients.push({
        address:  address,
        name:     names.value[i],
        fullName: fullNames.value[i],
        type:     aType
      });
    }
    return recipients;
  },

  swapButtons : function(aIDs)
  {
    return aIDs.replace(/button-sendToInternals/, 'button-to-be-send')
               .replace(/button-send\b/, 'button-sendToInternals')
               .replace(/button-to-be-send/, 'button-send');
  },

  // command controller
  supportsCommand : function(aCommand)
  {
    switch (aCommand)
    {
      case 'cmd_sendToInternals':
      case 'cmd_sendToInternalsNow':
      case 'cmd_sendToInternalsLater':
        return true;

      default:
        return false;
    }
  },
  isCommandEnabled : function(aCommand)
  {
    switch (aCommand)
    {
      case 'cmd_sendToInternals':
        return defaultController.commands.cmd_sendButton.isEnabled();

      case 'cmd_sendToInternalsNow':
        return defaultController.commands.cmd_sendNow.isEnabled();

      case 'cmd_sendToInternalsLater':
        return defaultController.commands.cmd_sendLater.isEnabled();

      default:
        return false;
    }
  },
  doCommand : function(aCommand)
  {
    switch (aCommand)
    {
      case 'cmd_sendToInternals':
        if (this.checkInternals())
          goDoCommand('cmd_sendButton');
        return;

      case 'cmd_sendToInternalsNow':
        if (this.checkInternals())
          goDoCommand('cmd_sendNow');
        return;

      case 'cmd_sendToInternalsLater':
        if (this.checkInternals())
          goDoCommand('cmd_sendLater');
        return;

      default:
        return false;
    }
  },
  onEvent : function(aEvent)
  {
  }
};
window.SendToInternalsHelper = SendToInternalsHelper;

window.addEventListener('DOMContentLoaded', function SendToInternalsOnLoad(aEvent) {
  window.removeEventListener(aEvent.type, SendToInternalsOnLoad, false);

  log('start initialization');

  top.controllers.appendController(SendToInternalsHelper);

  var toolbar = document.getElementById('composeToolbar2');
  var defaultSet = toolbar.getAttribute('defaultset');
  var currentSet = toolbar.getAttribute('currentset');
  var defaultIsInternal = Services.prefs.getBoolPref(BASE + 'defaultIsInternal');

  log('defaultSet: '+defaultSet);
  defaultSet = (defaultSet ? (defaultSet + ',') : '' ) + 'spring,button-sendToInternals';
  if (defaultIsInternal)
    defaultSet = SendToInternalsHelper.swapButtons(defaultSet);
  log('  => '+defaultSet);
  toolbar.setAttribute('defaultset', defaultSet);

  log('currentSet: '+currentSet);
  var currentSetModified = false;
  if (currentSet &&
      !Services.prefs.getBoolPref(BASE + 'initialized')) {
    Services.prefs.setBoolPref(BASE + 'initialized', true);
    currentSet = currentSet + ',spring,button-sendToInternals';
    currentSetModified = true;
  }
  if (currentSet &&
      defaultIsInternal &&
      !Services.prefs.getBoolPref(BASE + 'initiallySwapped')) {
    Services.prefs.setBoolPref(BASE + 'initiallySwapped', true)
    currentSet = SendToInternalsHelper.swapButtons(currentSet);
    currentSetModified = true;
  }
  if (currentSetModified) {
    log('  => '+currentSet);
    toolbar.setAttribute('currentset', currentSet);
  }

  window.addEventListener('input', function SendToInternalsOnInput(aEvent) {
    var field = aEvent.target;
    if (field.__sendToInternals__highlightTimeout)
      clearTimeout(field.__sendToInternals__highlightTimeout);
    field.__sendToInternals__highlightTimeout = setTimeout(function() {
      var id = field.getAttribute('id') || '';
      log('input at '+id+' / '+field.value);
      if (id.indexOf('addressCol') !== 0)
        return;
      SendToInternalsHelper.updateExternalHighlight(field);
    }, 500);
  }, false);
}, false);

window.__sendToInternals__updateSendCommands = window.updateSendCommands;
window.updateSendCommands = function(aHaveController, ...aArgs) {
  this.__sendToInternals__updateSendCommands(aHaveController, ...aArgs);
  if (aHaveController)
    goUpdateCommand('cmd_sendToInternals');
  else
    goUpdateCommand('cmd_sendToInternals', SendToInternalsHelper.isCommandEnabled('cmd_sendToInternals'));

  // update highlighted state after recipient is added from addressbook or others
  SendToInternalsHelper.highlightExternals();
};

window.__sendToInternals__MessageComposeOfflineStateChanged = window.MessageComposeOfflineStateChanged;
window.MessageComposeOfflineStateChanged = function(aGoingOffline, ...aArgs) {
  this.__sendToInternals__MessageComposeOfflineStateChanged(aGoingOffline, ...aArgs);

  log('MessageComposeOfflineStateChanged aGoingOffline='+aGoingOffline);
  var button = document.getElementById('button-sendToInternals');
  if (!button) {
    log('no button');
    return;
  }

  log('button exists, update it');
  if (aGoingOffline) {
    button.label = button.getAttribute('later_label');
    button.setAttribute('tooltiptext', button.getAttribute('later_tooltiptext'))
  }
  else {
    button.label = button.getAttribute('now_label');
    button.setAttribute('tooltiptext', button.getAttribute('now_tooltiptext'))
  }
};

window.__sendToInternals__awAppendNewRow = window.awAppendNewRow;
window.awAppendNewRow = function(aSetFocus, ...aArgs) {
  var result = this.__sendToInternals__awAppendNewRow(aSetFocus, ...aArgs);
  log('awAppendNewRow');
  SendToInternalsHelper.lastField.removeAttribute(SendToInternalsHelper.HIGHLIGHT);
  return result;
};

})();
<commit_msg>List all external addresses<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
(function() {

var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;

var MimeHeaderParser = Cc['@mozilla.org/messenger/headerparser;1']
                         .getService(Ci.nsIMsgHeaderParser);

var { Services } = Cu.import('resource://gre/modules/Services.jsm');

var BASE = 'extensions.send-to-internals@clear-code.com.';

function log(...aArgs) {
  if (Services.prefs.getBoolPref(BASE+'debug'))
    Services.console.logStringMessage('send-to-internals: '+aArgs.join(', '));
}

var SendToInternalsHelper = {
  get bundle() {
    return document.getElementById('sendToInternalsBundle');
  },

  get internalDomains() {
    var internalDomains = Services.prefs.getComplexValue(BASE + 'domains', Ci.nsISupportsString).data;
    log('(raw internalDomains: '+internalDomains+')');
    return internalDomains
             .split(/[,\|\s]+/)
             .map(function(aDomain) {
               return aDomain.trim();
             })
             .filter(function(aDomain) {
               return aDomain;
             });
  },

  get internalMatcher() {
    var expression = this.internalDomains.map(function(aDomain) {
          return '@' + aDomain.replace(/^@^/, '').replace(/\./g, '\\.').replace(/\+/g, '\\+');
        }).join('|')
    return new RegExp(expression);
  },

  get lastField() {
    var dummyRow = awGetNextDummyRow();
    if (dummyRow)
      return dummyRow.previousSibling;

    var listbox = document.getElementById('addressingWidget');
    return listbox.lastChild;
  },

  checkInternals : function()
  {
    log('checkInternals');
    var internalDomains = this.internalDomains;
    log('internalDomains: '+internalDomains);
    var externals = this.getAllRecipients().filter(function(aAddress, aIndex) {
      log('recipient '+aIndex+' / '+aAddress.address);
      var domain = aAddress.address.split('@')[1];
      log('  domain = '+domain);
      var index = internalDomains.indexOf(domain);
      log('  index = '+index);
      return index < 0;
    }, this);

    log('externals = '+externals.length);
    if (externals.length !== 0) {
      this.highlightExternals();
      Services.prompt.alert(
        window,
        this.bundle.getString('alert.haveExternals.title'),
        this.bundle.getFormattedString('alert.haveExternals.text', [externals.map(function(aAddress) {
          return aAddress.address;
        })].join('\n')])
      );
      return false;
    }

    return true;
  },

  highlightExternals : function()
  {
    log('highlightExternals');
    var addressFields = document.querySelectorAll('.textbox-addressingWidget');
    log('  addressFields = ' + addressFields.length);
    Array.forEach(addressFields, this.updateExternalHighlight, this);
  },

  HIGHLIGHT : 'data-send-to-internals-external-address',

  updateExternalHighlight : function(aField)
  {
    var matcher = this.internalMatcher;
    var value = aField.value.trim();
    log('updateExternalHighlight ' + aField.id + ' / ' + value + ' (' + matcher.test(value) + ')');
    if (value && (!matcher || !matcher.test(value)))
      aField.setAttribute(this.HIGHLIGHT, true);
    else
      aField.removeAttribute(this.HIGHLIGHT);
  },

  getAllRecipients : function()
  {
    var msgCompFields = gMsgCompose.compFields;
    Recipients2CompFields(msgCompFields);
    gMsgCompose.expandMailingLists();
    return this.splitRecipients(msgCompFields.to, 'To')
    		.concat(this.splitRecipients(msgCompFields.cc, 'Cc'))
            .concat(this.splitRecipients(msgCompFields.bcc, 'Bcc'));
  },

  splitRecipients : function(aAddressesSource, aType)
  {
    var addresses = {};
    var names = {};
    var fullNames = {};
    var numAddresses = MimeHeaderParser.parseHeadersWithArray(
                         aAddressesSource, addresses, names, fullNames);
    var recipients = [];
    for (let i = 0; i < numAddresses; i++) {
      let address = addresses.value[i];
      let domain = address.split('@')[1];
      recipients.push({
        address:  address,
        name:     names.value[i],
        fullName: fullNames.value[i],
        type:     aType
      });
    }
    return recipients;
  },

  swapButtons : function(aIDs)
  {
    return aIDs.replace(/button-sendToInternals/, 'button-to-be-send')
               .replace(/button-send\b/, 'button-sendToInternals')
               .replace(/button-to-be-send/, 'button-send');
  },

  // command controller
  supportsCommand : function(aCommand)
  {
    switch (aCommand)
    {
      case 'cmd_sendToInternals':
      case 'cmd_sendToInternalsNow':
      case 'cmd_sendToInternalsLater':
        return true;

      default:
        return false;
    }
  },
  isCommandEnabled : function(aCommand)
  {
    switch (aCommand)
    {
      case 'cmd_sendToInternals':
        return defaultController.commands.cmd_sendButton.isEnabled();

      case 'cmd_sendToInternalsNow':
        return defaultController.commands.cmd_sendNow.isEnabled();

      case 'cmd_sendToInternalsLater':
        return defaultController.commands.cmd_sendLater.isEnabled();

      default:
        return false;
    }
  },
  doCommand : function(aCommand)
  {
    switch (aCommand)
    {
      case 'cmd_sendToInternals':
        if (this.checkInternals())
          goDoCommand('cmd_sendButton');
        return;

      case 'cmd_sendToInternalsNow':
        if (this.checkInternals())
          goDoCommand('cmd_sendNow');
        return;

      case 'cmd_sendToInternalsLater':
        if (this.checkInternals())
          goDoCommand('cmd_sendLater');
        return;

      default:
        return false;
    }
  },
  onEvent : function(aEvent)
  {
  }
};
window.SendToInternalsHelper = SendToInternalsHelper;

window.addEventListener('DOMContentLoaded', function SendToInternalsOnLoad(aEvent) {
  window.removeEventListener(aEvent.type, SendToInternalsOnLoad, false);

  log('start initialization');

  top.controllers.appendController(SendToInternalsHelper);

  var toolbar = document.getElementById('composeToolbar2');
  var defaultSet = toolbar.getAttribute('defaultset');
  var currentSet = toolbar.getAttribute('currentset');
  var defaultIsInternal = Services.prefs.getBoolPref(BASE + 'defaultIsInternal');

  log('defaultSet: '+defaultSet);
  defaultSet = (defaultSet ? (defaultSet + ',') : '' ) + 'spring,button-sendToInternals';
  if (defaultIsInternal)
    defaultSet = SendToInternalsHelper.swapButtons(defaultSet);
  log('  => '+defaultSet);
  toolbar.setAttribute('defaultset', defaultSet);

  log('currentSet: '+currentSet);
  var currentSetModified = false;
  if (currentSet &&
      !Services.prefs.getBoolPref(BASE + 'initialized')) {
    Services.prefs.setBoolPref(BASE + 'initialized', true);
    currentSet = currentSet + ',spring,button-sendToInternals';
    currentSetModified = true;
  }
  if (currentSet &&
      defaultIsInternal &&
      !Services.prefs.getBoolPref(BASE + 'initiallySwapped')) {
    Services.prefs.setBoolPref(BASE + 'initiallySwapped', true)
    currentSet = SendToInternalsHelper.swapButtons(currentSet);
    currentSetModified = true;
  }
  if (currentSetModified) {
    log('  => '+currentSet);
    toolbar.setAttribute('currentset', currentSet);
  }

  window.addEventListener('input', function SendToInternalsOnInput(aEvent) {
    var field = aEvent.target;
    if (field.__sendToInternals__highlightTimeout)
      clearTimeout(field.__sendToInternals__highlightTimeout);
    field.__sendToInternals__highlightTimeout = setTimeout(function() {
      var id = field.getAttribute('id') || '';
      log('input at '+id+' / '+field.value);
      if (id.indexOf('addressCol') !== 0)
        return;
      SendToInternalsHelper.updateExternalHighlight(field);
    }, 500);
  }, false);
}, false);

window.__sendToInternals__updateSendCommands = window.updateSendCommands;
window.updateSendCommands = function(aHaveController, ...aArgs) {
  this.__sendToInternals__updateSendCommands(aHaveController, ...aArgs);
  if (aHaveController)
    goUpdateCommand('cmd_sendToInternals');
  else
    goUpdateCommand('cmd_sendToInternals', SendToInternalsHelper.isCommandEnabled('cmd_sendToInternals'));

  // update highlighted state after recipient is added from addressbook or others
  SendToInternalsHelper.highlightExternals();
};

window.__sendToInternals__MessageComposeOfflineStateChanged = window.MessageComposeOfflineStateChanged;
window.MessageComposeOfflineStateChanged = function(aGoingOffline, ...aArgs) {
  this.__sendToInternals__MessageComposeOfflineStateChanged(aGoingOffline, ...aArgs);

  log('MessageComposeOfflineStateChanged aGoingOffline='+aGoingOffline);
  var button = document.getElementById('button-sendToInternals');
  if (!button) {
    log('no button');
    return;
  }

  log('button exists, update it');
  if (aGoingOffline) {
    button.label = button.getAttribute('later_label');
    button.setAttribute('tooltiptext', button.getAttribute('later_tooltiptext'))
  }
  else {
    button.label = button.getAttribute('now_label');
    button.setAttribute('tooltiptext', button.getAttribute('now_tooltiptext'))
  }
};

window.__sendToInternals__awAppendNewRow = window.awAppendNewRow;
window.awAppendNewRow = function(aSetFocus, ...aArgs) {
  var result = this.__sendToInternals__awAppendNewRow(aSetFocus, ...aArgs);
  log('awAppendNewRow');
  SendToInternalsHelper.lastField.removeAttribute(SendToInternalsHelper.HIGHLIGHT);
  return result;
};

})();
<|endoftext|>