<commit_before>!(function (W, D) {
  function isBody(el) {
    return el.toString && el.toString() === '[object HTMLBodyElement]'
  }
  class Biu {
    constructor(text, options) {
      this.text = text
      this.options = options
      this.el = D.createElement('div')
      this.el.className = `biu-instance biu-${options.type}`
      this.el.style.textAlign = this.options.align

      if (this.options.pop) {
        this.el.classList.add('biu-pop')
      }

      if (!isBody(this.options.el)) {
        this.options.el.style.overflow = 'hidden'
        this.options.el.style.position = 'relative'
        this.el.style.position = 'absolute'
      }

      // initial events
      this.events = {}

      // inner element
      this.insert()

      // auto hide animation
      if (this.options.autoHide !== false) {
        this.startTimeout()
      }

      // mouse events
      this.registerEvents()
    }

    insert() {
      // close button
      this.closeButton = D.createElement('div')
      this.closeButton.className = 'biu-close'
      this.closeButton.innerHTML = this.options.closeButton
      this.el.appendChild(this.closeButton)

      // main
      const elMain = D.createElement('div')
      elMain.className = 'biu-main'
      elMain.innerHTML = this.text
      this.el.appendChild(elMain)

      this.options.el.appendChild(this.el)
      setTimeout(() => {
        this.el.classList.add('biu-shown')
      }, 200)
    }

    registerEvents() {
      if (this.options.autoHide !== false) {
        this.events.mouseover = () => {
          clearTimeout(this.timeout)
          this.timeout = null
        }
        this.events.mouseleave = () => this.startTimeout()
        this.el.addEventListener('mouseover', this.events.mouseover, false)
        this.el.addEventListener('mouseleave', this.events.mouseleave, false)
      }

      this.events.hide = () => this.hide()
      this.closeButton.addEventListener('click', this.events.hide, false)
    }

    startTimeout(timeout = this.options.timeout) {
      this.timeout = setTimeout(() => {
        this.hide()
      }, timeout)
    }

    hide() {
      if (this.options.pop) {
        this.el.style.transform = 'translateX(-50%) translateY(-110%)'
      } else {
        this.el.style.transform = 'translateY(-100%)'
      }
      setTimeout(() => {
        if (this.options.onHidden) {
          this.options.onHidden.call(this)
        }
        this.options.el.removeChild(this.el)
        this.el = null
      }, 300)
    }
  }

  function biu(text = '', {
    type = 'default',
    timeout = 3000,
    autoHide = true,
    closeButton = '×',
    el = document.body,
    align = 'center',
    pop = false,
    onHidden
  } = {}) {
    return new Biu(text, {
      type,
      timeout,
      autoHide,
      closeButton,
      el,
      align,
      pop,
      onHidden
    })
  }

  if (typeof module !== 'undefined') {
    module.exports = biu
  } else if (typeof window !== 'undefined') {
    window.biu = biu
  }
})(window, document);
<commit_msg>Don't try to hide if `el` is missing. (#9)<commit_after>!(function (W, D) {
  function isBody(el) {
    return el.toString && el.toString() === '[object HTMLBodyElement]'
  }
  class Biu {
    constructor(text, options) {
      this.text = text
      this.options = options
      this.el = D.createElement('div')
      this.el.className = `biu-instance biu-${options.type}`
      this.el.style.textAlign = this.options.align

      if (this.options.pop) {
        this.el.classList.add('biu-pop')
      }

      if (!isBody(this.options.el)) {
        this.options.el.style.overflow = 'hidden'
        this.options.el.style.position = 'relative'
        this.el.style.position = 'absolute'
      }

      // initial events
      this.events = {}

      // inner element
      this.insert()

      // auto hide animation
      if (this.options.autoHide !== false) {
        this.startTimeout()
      }

      // mouse events
      this.registerEvents()
    }

    insert() {
      // close button
      this.closeButton = D.createElement('div')
      this.closeButton.className = 'biu-close'
      this.closeButton.innerHTML = this.options.closeButton
      this.el.appendChild(this.closeButton)

      // main
      const elMain = D.createElement('div')
      elMain.className = 'biu-main'
      elMain.innerHTML = this.text
      this.el.appendChild(elMain)

      this.options.el.appendChild(this.el)
      setTimeout(() => {
        this.el.classList.add('biu-shown')
      }, 200)
    }

    registerEvents() {
      if (this.options.autoHide !== false) {
        this.events.mouseover = () => {
          clearTimeout(this.timeout)
          this.timeout = null
        }
        this.events.mouseleave = () => this.startTimeout()
        this.el.addEventListener('mouseover', this.events.mouseover, false)
        this.el.addEventListener('mouseleave', this.events.mouseleave, false)
      }

      this.events.hide = () => this.hide()
      this.closeButton.addEventListener('click', this.events.hide, false)
    }

    startTimeout(timeout = this.options.timeout) {
      this.timeout = setTimeout(() => {
        this.hide()
      }, timeout)
    }

    hide() {
      if (!this.el) return

      if (this.options.pop) {
        this.el.style.transform = 'translateX(-50%) translateY(-110%)'
      } else {
        this.el.style.transform = 'translateY(-100%)'
      }
      setTimeout(() => {
        if (this.options.onHidden) {
          this.options.onHidden.call(this)
        }
        this.options.el.removeChild(this.el)
        this.el = null
      }, 300)
    }
  }

  function biu(text = '', {
    type = 'default',
    timeout = 3000,
    autoHide = true,
    closeButton = '×',
    el = document.body,
    align = 'center',
    pop = false,
    onHidden
  } = {}) {
    return new Biu(text, {
      type,
      timeout,
      autoHide,
      closeButton,
      el,
      align,
      pop,
      onHidden
    })
  }

  if (typeof module !== 'undefined') {
    module.exports = biu
  } else if (typeof window !== 'undefined') {
    window.biu = biu
  }
})(window, document);
<|endoftext|>


<commit_before>/* ======= Default Directives ======= */

specialDirectives[Moon.config.prefix + "if"] = {
  afterGenerate: function(value, code, vnode) {
    return `(${compileTemplate(value, false)}) ? ${code} : ''`;
  }
}

specialDirectives[Moon.config.prefix + "for"] = {
  afterGenerate: function(value, code, vnode) {
    var parts = value.split(" in ");
    var aliases = parts[0].split(",");

    var iteratable = `instance.get("${parts[1]}")`;

    var params = aliases.join(",");

    code.replace(/instance\.get\("([^"]+)"\)/g, function(match, alias) {
      if(aliases.indexOf(alias) !== -1) {
        code = code.replace(new RegExp(`instance.get\\("${alias}"\\)`, "g"), alias);
      }
    });

    return `instance.renderLoop(${iteratable}, function(${params}) { return ${code}; })`;
  }
}

specialDirectives[Moon.config.prefix + "on"] = {
  beforeGenerate: function(value, vnode) {
    var eventModifiersCode = {
      stop: 'event.stopPropagation();',
      prevent: 'event.preventDefault();',
      ctrl: 'if(!event.ctrlKey) {return;};',
      shift: 'if(!event.shiftKey) {return;};',
      alt: 'if(!event.altKey) {return;};'
    };

    value = compileTemplate(value, false);

    var splitVal = value.split(":");
    // Extract modifiers and the event
    var rawModifiers = splitVal[0].split(".");
    var eventToCall = rawModifiers[0];
    var methodToCall = splitVal[1];
    var params = "(event)";
    var rawParams = methodToCall.split("(")[1];
    if(rawParams) {
      params = "";
    }
    var modifiers = "";

    rawModifiers.shift();

    for(var i = 0; i < rawModifiers.length; i++) {
      modifiers += eventModifiersCode[rawModifiers[i]];
    }

    var code = `function(event) {${modifiers}instance.$methods.${methodToCall}${params}}`;
    if(!vnode.meta.eventListeners[eventToCall]) {
      vnode.meta.eventListeners[eventToCall] = [code]
    } else {
      vnode.meta.eventListeners[eventToCall].push(code);
    }
  }
}

specialDirectives[Moon.config.prefix + "model"] = {
  beforeGenerate: function(value, vnode) {
    var code = `function(event) {instance.set("${value}", event.target.value)}`;
    if(!vnode.meta.eventListeners["input"]) {
      vnode.meta.eventListeners["input"] = [code]
    } else {
      vnode.meta.eventListeners["input"].push(code);
    }
  }
};

specialDirectives[Moon.config.prefix + "once"] = {
  beforeGenerate: function(value, vnode) {
    vnode.meta.shouldRender = "instance.$initialRender";
  }
};

specialDirectives[Moon.config.prefix + "pre"] = {
  beforeGenerate: function(value, vnode) {
    vnode.meta.shouldRender = false;
  }
}

directives[Moon.config.prefix + "show"] = function(el, val, vnode) {
  var evaluated = new Function("return " + val);
  if(!evaluated()) {
    el.style.display = 'none';
  } else {
    el.style.display = 'block';
  }
}

directives[Moon.config.prefix + "text"] = function(el, val, vnode) {
  el.textContent = val;
  for(var i = 0; i < vnode.children.length; i++) {
    vnode.children[i].meta.shouldRender = false;
  }
}

directives[Moon.config.prefix + "html"] = function(el, val, vnode) {
  el.innerHTML = val;
  for(var i = 0; i < vnode.children.length; i++) {
    vnode.children[i].meta.shouldRender = false;
  }
}

directives[Moon.config.prefix + "mask"] = function(el, val, vnode) {

}
<commit_msg>add 'enter' keycode utility<commit_after>/* ======= Default Directives ======= */

specialDirectives[Moon.config.prefix + "if"] = {
  afterGenerate: function(value, code, vnode) {
    return `(${compileTemplate(value, false)}) ? ${code} : ''`;
  }
}

specialDirectives[Moon.config.prefix + "for"] = {
  afterGenerate: function(value, code, vnode) {
    var parts = value.split(" in ");
    var aliases = parts[0].split(",");

    var iteratable = `instance.get("${parts[1]}")`;

    var params = aliases.join(",");

    code.replace(/instance\.get\("([^"]+)"\)/g, function(match, alias) {
      if(aliases.indexOf(alias) !== -1) {
        code = code.replace(new RegExp(`instance.get\\("${alias}"\\)`, "g"), alias);
      }
    });

    return `instance.renderLoop(${iteratable}, function(${params}) { return ${code}; })`;
  }
}

specialDirectives[Moon.config.prefix + "on"] = {
  beforeGenerate: function(value, vnode) {
    var eventModifiersCode = {
      stop: 'event.stopPropagation();',
      prevent: 'event.preventDefault();',
      ctrl: 'if(!event.ctrlKey) {return;};',
      shift: 'if(!event.shiftKey) {return;};',
      alt: 'if(!event.altKey) {return;};',
      enter: 'if(event.keyCode !== 13) {return;};'
    };

    value = compileTemplate(value, false);

    var splitVal = value.split(":");
    // Extract modifiers and the event
    var rawModifiers = splitVal[0].split(".");
    var eventToCall = rawModifiers[0];
    var methodToCall = splitVal[1];
    var params = "(event)";
    var rawParams = methodToCall.split("(")[1];
    if(rawParams) {
      params = "";
    }
    var modifiers = "";

    rawModifiers.shift();

    for(var i = 0; i < rawModifiers.length; i++) {
      modifiers += eventModifiersCode[rawModifiers[i]];
    }

    var code = `function(event) {${modifiers}instance.$methods.${methodToCall}${params}}`;
    if(!vnode.meta.eventListeners[eventToCall]) {
      vnode.meta.eventListeners[eventToCall] = [code]
    } else {
      vnode.meta.eventListeners[eventToCall].push(code);
    }
  }
}

specialDirectives[Moon.config.prefix + "model"] = {
  beforeGenerate: function(value, vnode) {
    var code = `function(event) {instance.set("${value}", event.target.value)}`;
    if(!vnode.meta.eventListeners["input"]) {
      vnode.meta.eventListeners["input"] = [code]
    } else {
      vnode.meta.eventListeners["input"].push(code);
    }
  }
};

specialDirectives[Moon.config.prefix + "once"] = {
  beforeGenerate: function(value, vnode) {
    vnode.meta.shouldRender = "instance.$initialRender";
  }
};

specialDirectives[Moon.config.prefix + "pre"] = {
  beforeGenerate: function(value, vnode) {
    vnode.meta.shouldRender = false;
  }
}

directives[Moon.config.prefix + "show"] = function(el, val, vnode) {
  var evaluated = new Function("return " + val);
  if(!evaluated()) {
    el.style.display = 'none';
  } else {
    el.style.display = 'block';
  }
}

directives[Moon.config.prefix + "text"] = function(el, val, vnode) {
  el.textContent = val;
  for(var i = 0; i < vnode.children.length; i++) {
    vnode.children[i].meta.shouldRender = false;
  }
}

directives[Moon.config.prefix + "html"] = function(el, val, vnode) {
  el.innerHTML = val;
  for(var i = 0; i < vnode.children.length; i++) {
    vnode.children[i].meta.shouldRender = false;
  }
}

directives[Moon.config.prefix + "mask"] = function(el, val, vnode) {

}
<|endoftext|>


<commit_before>/* List Element Highlighting */
var highlightElement = function(element) {
    var allElements = [].slice.call(document.querySelectorAll('#' + element.parentNode.id +' p'));
	var neighborPart;
	if(element.parentNode.id === 'easy-starts') {
		neighborPart = [].slice.call(document.querySelectorAll('#easy-ends p'));
	}
	else {
		neighborPart = [].slice.call(document.querySelectorAll('#easy-starts p'));
	}
	// Line-though Value that in the Start/Finish table if they have been chosen in the other one
	neighborPart.map(function (neighborElement) {
		neighborElement.classList.remove('line-through');
		if(neighborElement.getAttribute('onclick') === null) {
			neighborElement.setAttribute('onclick', 'highlightElement(this)');
		}
		if(neighborElement.getAttribute('data-id') === element.getAttribute('data-id')) {
			neighborElement.className += ' line-through';
			neighborElement.removeAttribute('onclick');
		}
	});
    allElements.map(function(element) {
        element.classList.remove('clicked');
    });
	// Highlight element
     element.className += ' clicked';
 };

/* Transition Effects for Sections */

var openSection = (function(section) {
    section = document.querySelector('#' + section);
    name = section.id;

    ([].slice.call(document.querySelectorAll('section'))).map(function(row, index) {
  row.className = '';
 });
    ([].slice.call(document.querySelectorAll('section'))).map(function(row, index) {
        row.className = '';
    });
    document.querySelector('#' + name).className = 'active';
});

openSection('success-screen');

/* Difficulty Selection Description Popup */
var beginnerButton = document.querySelector('#difficulty-selection-mode .button.button-green');
var expertButton = document.querySelector('#difficulty-selection-mode .button.button-red');
var challengeButton = document.querySelector('#difficulty-selection-mode .button.button-darkblue');

var beginnerDescription = document.querySelector('#difficulty-selection-mode #beginner-mode-info');
var expertDescription = document.querySelector('#difficulty-selection-mode #expert-mode-info');
var challengeDescription = document.querySelector('#difficulty-selection-mode #challenge-mode-info');

var triangleUp = document.querySelector('#difficulty-selection-mode .triangle-up');

beginnerButton.onmouseenter = function() {
    beginnerDescription.className += ' active';
    triangleUp.className += ' challenge-triangle';
};
beginnerButton.onmouseleave = function() {
    beginnerDescription.classList.remove('active');
    triangleUp.classList.remove('challenge-triangle');
};
expertButton.onmouseenter = function() {
    expertDescription.className += ' active';
    triangleUp.className += ' challenge-triangle';
};
expertButton.onmouseleave = function() {
    expertDescription.classList.remove('active');
    triangleUp.classList.remove('challenge-triangle');
};
challengeButton.onmouseenter = function() {
    challengeDescription.className += ' active';
    triangleUp.className += ' challenge-triangle';
};
challengeButton.onmouseleave = function() {
    challengeDescription.classList.remove('active');
    triangleUp.classList.remove('challenge-triangle');
};

var accordion = document.getElementsByClassName('accordion');
var i;
for (i = 0; i < accordion.length; i++) {
    accordion[i].onclick = function() {
        this.classList.toggle('active');
        var panel = this.nextElementSibling;
        if (panel.style.display) {
            panel.style.display = null;
        } else {
            panel.style.display = 'block';
        }
    }
}

/* Game Rule Slides and Popup*/
var closePopUp = document.querySelector('#game-rules-popup #popup-close');
var popup = document.querySelector('#game-rules-popup');
var rulesButton = document.querySelector('#title-screen-button #game-rules');

closePopUp.onclick = function() {
	popup.classList.remove('active');
	popup.classList.remove('active');
};

rulesButton.onclick = function() {
    popup.className += ' active';
};

var rules = [].slice.call(document.querySelectorAll('.game-rules'));
rules.map(function(rule) {
	rule.style.display = 'none';
});

var sliderButtonLeft = document.querySelector('.slide-left');
var sliderButtonRight = document.querySelector('.slide-right');

var currentRuleIndex = 0;
var ruleSlide = function(direction) {
	currentRuleIndex += direction;
	rules.map(function(rule) {
		rule.style.display = 'none';
	});
	if(currentRuleIndex === 0) {
		sliderButtonLeft.classList.remove('active');
		sliderButtonRight.className += ' active';
	}
	if(currentRuleIndex === 1) {
		sliderButtonRight.classList.remove('active');
		sliderButtonLeft.className += ' active';
	}
	rules[currentRuleIndex].style.display = 'block';
};
ruleSlide(currentRuleIndex);
<commit_msg>minor mistake<commit_after>/* List Element Highlighting */
var highlightElement = function(element) {
    var allElements = [].slice.call(document.querySelectorAll('#' + element.parentNode.id +' p'));
	var neighborPart;
	if(element.parentNode.id === 'easy-starts') {
		neighborPart = [].slice.call(document.querySelectorAll('#easy-ends p'));
	}
	else {
		neighborPart = [].slice.call(document.querySelectorAll('#easy-starts p'));
	}
	// Line-though Value that in the Start/Finish table if they have been chosen in the other one
	neighborPart.map(function (neighborElement) {
		neighborElement.classList.remove('line-through');
		if(neighborElement.getAttribute('onclick') === null) {
			neighborElement.setAttribute('onclick', 'highlightElement(this)');
		}
		if(neighborElement.getAttribute('data-id') === element.getAttribute('data-id')) {
			neighborElement.className += ' line-through';
			neighborElement.removeAttribute('onclick');
		}
	});
    allElements.map(function(element) {
        element.classList.remove('clicked');
    });
	// Highlight element
     element.className += ' clicked';
 };

/* Transition Effects for Sections */

var openSection = (function(section) {
    section = document.querySelector('#' + section);
    name = section.id;

    ([].slice.call(document.querySelectorAll('section'))).map(function(row, index) {
  row.className = '';
 });
    ([].slice.call(document.querySelectorAll('section'))).map(function(row, index) {
        row.className = '';
    });
    document.querySelector('#' + name).className = 'active';
});

openSection('title-screen');

/* Difficulty Selection Description Popup */
var beginnerButton = document.querySelector('#difficulty-selection-mode .button.button-green');
var expertButton = document.querySelector('#difficulty-selection-mode .button.button-red');
var challengeButton = document.querySelector('#difficulty-selection-mode .button.button-darkblue');

var beginnerDescription = document.querySelector('#difficulty-selection-mode #beginner-mode-info');
var expertDescription = document.querySelector('#difficulty-selection-mode #expert-mode-info');
var challengeDescription = document.querySelector('#difficulty-selection-mode #challenge-mode-info');

var triangleUp = document.querySelector('#difficulty-selection-mode .triangle-up');

beginnerButton.onmouseenter = function() {
    beginnerDescription.className += ' active';
    triangleUp.className += ' challenge-triangle';
};
beginnerButton.onmouseleave = function() {
    beginnerDescription.classList.remove('active');
    triangleUp.classList.remove('challenge-triangle');
};
expertButton.onmouseenter = function() {
    expertDescription.className += ' active';
    triangleUp.className += ' challenge-triangle';
};
expertButton.onmouseleave = function() {
    expertDescription.classList.remove('active');
    triangleUp.classList.remove('challenge-triangle');
};
challengeButton.onmouseenter = function() {
    challengeDescription.className += ' active';
    triangleUp.className += ' challenge-triangle';
};
challengeButton.onmouseleave = function() {
    challengeDescription.classList.remove('active');
    triangleUp.classList.remove('challenge-triangle');
};

var accordion = document.getElementsByClassName('accordion');
var i;
for (i = 0; i < accordion.length; i++) {
    accordion[i].onclick = function() {
        this.classList.toggle('active');
        var panel = this.nextElementSibling;
        if (panel.style.display) {
            panel.style.display = null;
        } else {
            panel.style.display = 'block';
        }
    }
}

/* Game Rule Slides and Popup*/
var closePopUp = document.querySelector('#game-rules-popup #popup-close');
var popup = document.querySelector('#game-rules-popup');
var rulesButton = document.querySelector('#title-screen-button #game-rules');

closePopUp.onclick = function() {
	popup.classList.remove('active');
	popup.classList.remove('active');
};

rulesButton.onclick = function() {
    popup.className += ' active';
};

var rules = [].slice.call(document.querySelectorAll('.game-rules'));
rules.map(function(rule) {
	rule.style.display = 'none';
});

var sliderButtonLeft = document.querySelector('.slide-left');
var sliderButtonRight = document.querySelector('.slide-right');

var currentRuleIndex = 0;
var ruleSlide = function(direction) {
	currentRuleIndex += direction;
	rules.map(function(rule) {
		rule.style.display = 'none';
	});
	if(currentRuleIndex === 0) {
		sliderButtonLeft.classList.remove('active');
		sliderButtonRight.className += ' active';
	}
	if(currentRuleIndex === 1) {
		sliderButtonRight.classList.remove('active');
		sliderButtonLeft.className += ' active';
	}
	rules[currentRuleIndex].style.display = 'block';
};
ruleSlide(currentRuleIndex);
<|endoftext|>


<commit_before>'use strict';

/*!
 * Snakeskin
 * https://github.com/SnakeskinTpl/Snakeskin
 *
 * Released under the MIT license
 * https://github.com/SnakeskinTpl/Snakeskin/blob/master/LICENSE
 */

import Snakeskin from '../core';

Snakeskin.addDirective(
	'literal',

	{
		group: ['literal', 'escape', 'output'],
		notEmpty: true,
		placement: 'template',
		shorthands: {'{': 'literal {'},
		text: true
	},

	function (command) {
		console.log(command);

		this.append(this.wrap(
			`'${this.literalBounds[0]}${this.replaceTplVars(command.replace(/^\s*\{|}\s*$/g, ''))}${this.literalBounds[1]}'`
		));
	}
);
<commit_msg>:wrench:<commit_after>'use strict';

/*!
 * Snakeskin
 * https://github.com/SnakeskinTpl/Snakeskin
 *
 * Released under the MIT license
 * https://github.com/SnakeskinTpl/Snakeskin/blob/master/LICENSE
 */

import Snakeskin from '../core';

Snakeskin.addDirective(
	'literal',

	{
		group: ['literal', 'escape', 'output'],
		notEmpty: true,
		placement: 'template',
		shorthands: {'{': 'literal {'},
		text: true
	},

	function (command) {
		this.append(this.wrap(
			`'${this.literalBounds[0]}${this.replaceTplVars(command.replace(/^\s*\{|}\s*$/g, ''))}${this.literalBounds[1]}'`
		));
	}
);
<|endoftext|>


<commit_before>/*global define, amplify*/
define([
    'jquery',
    'require',
    'underscore',
    'loglevel',
    'fx-m-c/config/errors',
    'fx-m-c/config/events',
    'fx-m-c/config/config',
    'fx-m-c/config/config-default',
    'fenix-ui-map',
    'fx-common/pivotator/start',
    'fx-common/pivotator/fenixtool',
    'amplify'
], function ($, require, _, log, ERR, EVT,
    C, CD,
    FMMap,
    Pivotator,
    Fenixtool
    ) {

    'use strict';

    function MapCreator(o) {

        log.info("FENIX MapCreator");
        log.info(o);

        _.extend(this, CD, C, {initial: o});

        this._parseInput(o);

        this.fenix_ui_mapConfig = o.fenix_ui_map;

        var valid = this._validateInput();

        if (valid === true) {

            this._initVariables();

            this._bindEventListeners();

            this._renderMap();

            return this;

        } else {
            log.error("Impossible to create MapCreator");
            log.error(valid)
        }

    }

    // API

    /**
     * pub/sub
     * @return {Object} MapCreator instance
     */
    MapCreator.prototype.on = function (channel, fn) {
        if (!this.channels[channel]) {
            this.channels[channel] = [];
        }
        this.channels[channel].push({context: this, callback: fn});
        return this;
    };

    /**
     * Add a base layer to map
     */
    MapCreator.prototype.addBaseLayer = function (layer) {

        this.fenixMap.addTileLayer(layer, true);

        return this;
    };

    /**
     * Add a layer to map
     */
    MapCreator.prototype.addLayer = function (model) {

        var layer;

        //support simple Leaflet layer
        if(model instanceof L.TileLayer)
            return this.fenixMap.map.addLayer(model);

        // TODO: switch to check if it's a fenix layer
        if (!model.hasOwnProperty("metadata")) {
            this.errors.metadata = "Model does not contain 'metadata' attribute.";
            throw new Error("FENIX Map creator has not a valid configuration");
        }

        if (model.hasOwnProperty('data'))
            layer = this.createLayerFenixJoin(model);
        else
            layer = this.createLayerFenix(model);

        layer = new FM.layer(layer);

        if(model['metadata'] && model['metadata']['title'] && model['metadata']['title']['EN'])
            layer.layer.layertitle = model['metadata']['title']['EN'];

        this.fenixMap.addLayer(layer);

        return layer;
    };

    /**
     * Remove a layer from map
     */
    MapCreator.prototype.removeLayer = function (layer) {

        if (this.status.ready !== true) {
            return;
        }

        return this;
    };

    /**
     * Invalidate map size
     */
    MapCreator.prototype.invalidateSize = function () {

        if (this.status.ready !== true) {
            return;
        }

        this.fenixMap.invalidateSize()

        return this;
    };

    // end API

    MapCreator.prototype._parseInput = function () {

        this.id = this.initial.id;
        this.$el = $(this.initial.el);
        this.model = this.initial.model;

        //pivotator config
        var pc = {};

        pc.aggregationFn = this.initial.aggregationFn;

        pc.aggregations = this.initial.aggregations || [];
        pc.hidden = this.initial.hidden || [];
        pc.columns = this.initial.x;
        pc.values = this.initial.y || ["value"];
        pc.rows = this.initial.series;

        pc.formatter = this.initial.formatter || "value";
        pc.valueOutputType = this.initial.valueOutputType;
        pc.showRowHeaders = this.initial.showRowHeaders || false;
        pc.decimals = this.initial.decimals || 2;

        pc.showCode = this.initial.showCode || false;
        pc.showFlag = this.initial.showFlag || false;
        pc.showUnit = this.initial.showUnit || false;

        // add more pivotator config

        this.pivotatorConfig = pc;

    };

    MapCreator.prototype._validateInput = function () {

        var valid = true,
            errors = [];

        //set MapCreator id
        if (!this.id) {

            window.fx_map_id >= 0 ? window.fx_map_id++ : window.fx_map_id = 0;
            this.id = String(window.fx_map_id);
            log.warn("Impossible to find MapCreator id. Set auto id to: " + this.id);
        }

        //Check if $el exist
        if (this.$el.length === 0) {
            errors.push({code: ERR.MISSING_CONTAINER});
            log.warn("Impossible to find box container");
        }

        return errors.length > 0 ? errors : valid;

    };

    MapCreator.prototype._initVariables = function () {

        //pub/sub
        this.channels = {};

        this.status = {};
        this.status.ready = false;

        this.pivotator = new Pivotator();
        this.fenixTool = new Fenixtool();
    };

    MapCreator.prototype._bindEventListeners = function () {

        amplify.subscribe(this._getEventName(EVT.WINDOW_RESIZE), this, this.invalidateSize);
    };

    MapCreator.prototype._renderMap = function () {

        var self = this;

        //var myPivotatorConfig=this.fenixTool.parseInut(this.initial.model.metadata.dsd, this.pivotatorConfig);
        //var model = this.pivotator.pivot(this.model, this.pivotatorConfig);

        self.fenixMap = new FM.Map(self.$el, self.fenix_ui_mapConfig);
        self.fenixMap.createMap();

        self.leafletMap = self.fenixMap.map;

        self.addLayer(this.model)

         //TODO bind to Leaflet whenReady
        self.status.ready = true;  //To be set on map ready event

        setTimeout(_.bind(function () {
            self._trigger('ready');
        }, self), 0);
    };

    MapCreator.prototype._trigger = function (channel) {

        if (!this.channels[channel]) {
            return false;
        }
        var args = Array.prototype.slice.call(arguments, 1);
        for (var i = 0, l = this.channels[channel].length; i < l; i++) {
            var subscription = this.channels[channel][i];
            subscription.callback.apply(subscription.context, args);
        }

        return this;
    };

    MapCreator.prototype._getEventName = function (evt) {

        return this.id.concat(evt);

    };

    MapCreator.prototype._unbindEventListeners = function () {

        amplify.unsubscribe(this._getEventName(EVT.WINDOW_RESIZE), this.invalidateSize);
    };

    MapCreator.prototype.dispose = function () {

        //unbind event listeners
        this._unbindEventListeners();

        if (this.status.ready === true) {
            this.fenixMap.destroyMap();
        }

        this.$el.empty();

    };

    MapCreator.prototype.createLayerFenix = function (model, options) {
        var metadata = model.metadata;
        var layer = {};
        // Define the layer
        if (metadata.hasOwnProperty("dsd")) {
            layer.layers = "";
            if (metadata.dsd.hasOwnProperty("workspace"))
                layer.layers += metadata.dsd.workspace + ":";

            layer.layers += metadata.dsd.layerName;
        }
        else {
            this.errors['dsd'] = "Model['metadata'] does not contain 'dsd' attribute.";
            throw new Error("FENIX Map creator has not a valid configuration");
        }

        //TODO
        //if (model.hasOwnProperty("datasource"))
        //  layer.urlWMS = metadata["datasource"];

        layer.urlWMS = this.fenix_ui_map.DEFAULT_WMS_SERVER;
        layer.layertitle = {
            en: 'Data Layer'
        };
        layer.opacity = '0.9';
        return layer;
    };

    // JOIN
    MapCreator.prototype.createLayerFenixJoin = function (model) {
        if (this._validateJoinInput(model) === true) {

            // create the join layer
            var layer = this.getJoinLayer(model);

            _.extend(layer, this.join.style);

            var defPopup = "
{{"+ layer.joincolumnlabel +"}}"+
                "
{{{"+ layer.joincolumn + "}}} "+
                "{{measurementunit}}"+
                "

";

            // Layer title TODO: Add title if exist (check in the validator)
            if (model['metadata'].hasOwnProperty("title")) {
                if (model['metadata']['title'][this.lang]) {
                    layer.layertitle = model['metadata']['title'][this.lang];
                    console.log('title',this.lang, layer.layertitle)
                }
            }
            else {
                layer.layertitle = model['metadata']['uid'];
            }

            // getting a title from the options
            if ( this.hasOwnProperty('layer') && this.layer.hasOwnProperty('layertitle')) {
                layer.layertitle = this.layer.layertitle;
            }

            if ( this.hasOwnProperty('layer') && this.layer.hasOwnProperty('popupBuilder')) {
                layer.popupBuilder = this.layer.popupBuilder;
            }

            layer.customgfi = {
                showpopup: true,
                content: {
                    EN: _.isFunction(layer.popupBuilder) ? layer.popupBuilder(layer.joincolumnlabel, layer.joincolumn) : defPopup
                }
            };

            // TODO: add check on the zoomto data (move it to a function)
            var codes = [];
            layer.joindata.forEach(function (code) {
                _.keys(code).forEach(function (key) {
                    codes.push(key);
                });
            });

            var zoomlayer = layer.layers.split(":");

            zoomlayer = zoomlayer.length > 1? zoomlayer[1]: zoomlayer[0];

            this.fenixMap.zoomTo(zoomlayer, layer.joincolumn, codes);

            return layer;
        } else {
            console.error(this.errors);
            throw new Error("FENIX Map creator has not a valid JOIN configuration");
        }
    };

    MapCreator.prototype.getJoinLayer = function (model) {

        var metadata = model['metadata'],
            geoColumn = {},
            valueColumn = {},
            muColumn = {};

        metadata['dsd']['columns'].forEach(_.bind(function (col, index) {
            if (col.subject === this.geoSubject || col.id === this.geoSubject ) {
                geoColumn = col;
                geoColumn.index = index;
            }
            if (col.subject === this.valueSubject || col.id === this.valueSubject ) {
                valueColumn = col;
                valueColumn.index = index;
            }
            if (col.subject === this.muSubject) {
                muColumn = col;
                muColumn.index = index;
            }
        }, this));

        // getting the right measurement unit if the new label exists
        metadata['dsd']['columns'].forEach(_.bind(function (column, index) {
            if (muColumn.id + '_' + this.lang) {
                muColumn = column;
                muColumn.index = index;
            }
        }, this));

        if (this._validateJoinColumnInput(geoColumn)) {

            var layer = null;
            var codelist = geoColumn['domain']['codes'][0]['idCodeList'].toLowerCase();

            if (this.join.layerMapping[codelist]) {
                layer = this.join.layerMapping[codelist];
            }
            else {
                geoColumn['domain']['codes'][0].idCodeList.toLowerCase();
                // TODO: Handle reference Area
                var referenceArea = metadata["meContent"]["seReferencePopulation"]["referenceArea"]['codes'][0].code.toLowerCase();
                layer = this.join.layerMapping[codelist + "_" + referenceArea];
            }

            // check measurementunit
            // TODO: Add measurement unit to the layer definition (using label column of the mu)
            //

            // get joinData
            layer.joindata = this.getJoinData(model['data'], geoColumn.index, valueColumn.index);

            // TODO: check on the column index
            layer.measurementunit = model['data'][0][muColumn.index];

            // TODO: check if is the right legendtitle
            layer.legendtitle = layer.measurementunit;

            return layer;

        } else{
            console.error('Error JoinColumnInput not valid')
        }
    };

    MapCreator.prototype.getJoinData = function (data, geoColumnIndex, valueColumnIhdex) {
        var joindata = [];

        // TODO: remove cachedValues on final version. Check on join data consistency?
        var cachedValues = {}
        // TODO: add on check
        data.forEach(_.bind(function (row) {
            var obj = {}
            var code = row[geoColumnIndex];
            var value = row[valueColumnIhdex];
            if (code && value) {
                obj[code] = value ;
                if (!cachedValues.hasOwnProperty(code)) {
                    // check null values
                    cachedValues[code] = true;
                    joindata.push(obj);
                }
            }
        }, this));

        return joindata;
    };

    MapCreator.prototype.iso3Boundaries = function(code) {
        var self = this;
            /*geoUrl = "http://fenix.fao.org:20200/geoserver/fenix/ows"+
                "?service=WFS&version=1.0.0&request=GetFeature&typeName=fenix:gaul0_bounds&maxFeatures=50&outputFormat=application/json&"+
                "viewparams=iso3_code:"+code;
        */
        var rootUrl = "http://fenix.fao.org:20200/geoserver/fenix/ows";

        var defaultParameters = {
            service: 'WFS',
            version: '1.0.0',
            request: 'GetFeature',
            typeName: 'fenix:gaul0_bounds',
            maxFeatures: 50,
            outputFormat: 'text/javascript',
            format_options: 'callback: getJson',
            srsName: 'EPSG:4326',
            viewparams: 'iso3_code:'+code
        };

        var parameters = L.Util.extend(defaultParameters);

        $.ajax({
            url: rootUrl + L.Util.getParamString(parameters),
            dataType: 'jsonp',
            jsonpCallback: 'getJson',
            success: function(json) {

                //console.log('iso3Boundaries',json);

                var gLayer = L.geoJson(json, {
                    style: function (feature) {
                        return {
                            color: '#f00',
                            fillColor: '#f00'
                        };
                    }
                });
                self.fenixMap.map.addLayer( gLayer );

                self.fenixMap.map.fitBounds( gLayer.getBounds() );

            }
        });
    };

    MapCreator.prototype._validateJoinInput = function (model) {
        this.errors = {};

        //Metadata TODO: add all metadata checks
        if (!model.hasOwnProperty("metadata")) {
            this.errors.metadata = "'metadata' attribute not present.";
        }

        //Data
        if (!model.hasOwnProperty("data")) {
            this.errors.data = "'data' attribute not present.";
        }

        return (_.keys(this.errors).length === 0);
    };

    MapCreator.prototype._validateJoinColumnInput = function (column) {
        this.errors = {};

        //Metadata TODO: add all metadata checks
        if (!column.hasOwnProperty('key')) {
            this.errors.column = "'key' attribute not present.";
        }
        else {
            if (column.key !== true) {
                this.errors.column = "'key' is not true.";
            }
        }

        if (!column.hasOwnProperty('dataType')) {
            this.errors.column = "'dataType' attribute not present.";
        }
        else {
            if (column.dataType !== 'code') {
                this.errors.column = "'dataType' attribute is not a coding system.";
            }
        }

        // TODO: check domain and referencearea if needed

        return (Object.keys(this.errors).length === 0);
    };

    return MapCreator;
});<commit_msg>self this<commit_after>/*global define, amplify*/
define([
    'jquery',
    'require',
    'underscore',
    'loglevel',
    'fx-m-c/config/errors',
    'fx-m-c/config/events',
    'fx-m-c/config/config',
    'fx-m-c/config/config-default',
    'fenix-ui-map',
    'fx-common/pivotator/start',
    'fx-common/pivotator/fenixtool',
    'amplify'
], function ($, require, _, log, ERR, EVT,
    C, CD,
    FMMap,
    Pivotator,
    Fenixtool
    ) {

    'use strict';

    function MapCreator(o) {

        log.info("FENIX MapCreator");
        log.info(o);

        _.extend(this, CD, C, {initial: o});

        this._parseInput(o);

        this.fenix_ui_mapConfig = o.fenix_ui_map;

        var valid = this._validateInput();

        if (valid === true) {

            this._initVariables();

            this._bindEventListeners();

            this._renderMap();

            return this;

        } else {
            log.error("Impossible to create MapCreator");
            log.error(valid)
        }

    }

    // API

    /**
     * pub/sub
     * @return {Object} MapCreator instance
     */
    MapCreator.prototype.on = function (channel, fn) {
        if (!this.channels[channel]) {
            this.channels[channel] = [];
        }
        this.channels[channel].push({context: this, callback: fn});
        return this;
    };

    /**
     * Add a base layer to map
     */
    MapCreator.prototype.addBaseLayer = function (layer) {

        this.fenixMap.addTileLayer(layer, true);

        return this;
    };

    /**
     * Add a layer to map
     */
    MapCreator.prototype.addLayer = function (model) {

        var layer;

        //support simple Leaflet layer
        if(model instanceof L.TileLayer)
            return this.fenixMap.map.addLayer(model);

        // TODO: switch to check if it's a fenix layer
        if (!model.hasOwnProperty("metadata")) {
            this.errors.metadata = "Model does not contain 'metadata' attribute.";
            throw new Error("FENIX Map creator has not a valid configuration");
        }

        if (model.hasOwnProperty('data'))
            layer = this.createLayerFenixJoin(model);
        else
            layer = this.createLayerFenix(model);

        layer = new FM.layer(layer);

        if(model['metadata'] && model['metadata']['title'] && model['metadata']['title']['EN'])
            layer.layer.layertitle = model['metadata']['title']['EN'];

        this.fenixMap.addLayer(layer);

        return layer;
    };

    /**
     * Remove a layer from map
     */
    MapCreator.prototype.removeLayer = function (layer) {

        if (this.status.ready !== true) {
            return;
        }

        return this;
    };

    /**
     * Invalidate map size
     */
    MapCreator.prototype.invalidateSize = function () {

        if (this.status.ready !== true) {
            return;
        }

        this.fenixMap.invalidateSize()

        return this;
    };

    // end API

    MapCreator.prototype._parseInput = function () {

        this.id = this.initial.id;
        this.$el = $(this.initial.el);
        this.model = this.initial.model;

        //pivotator config
        var pc = {};

        pc.aggregationFn = this.initial.aggregationFn;

        pc.aggregations = this.initial.aggregations || [];
        pc.hidden = this.initial.hidden || [];
        pc.columns = this.initial.x;
        pc.values = this.initial.y || ["value"];
        pc.rows = this.initial.series;

        pc.formatter = this.initial.formatter || "value";
        pc.valueOutputType = this.initial.valueOutputType;
        pc.showRowHeaders = this.initial.showRowHeaders || false;
        pc.decimals = this.initial.decimals || 2;

        pc.showCode = this.initial.showCode || false;
        pc.showFlag = this.initial.showFlag || false;
        pc.showUnit = this.initial.showUnit || false;

        // add more pivotator config

        this.pivotatorConfig = pc;

    };

    MapCreator.prototype._validateInput = function () {

        var valid = true,
            errors = [];

        //set MapCreator id
        if (!this.id) {

            window.fx_map_id >= 0 ? window.fx_map_id++ : window.fx_map_id = 0;
            this.id = String(window.fx_map_id);
            log.warn("Impossible to find MapCreator id. Set auto id to: " + this.id);
        }

        //Check if $el exist
        if (this.$el.length === 0) {
            errors.push({code: ERR.MISSING_CONTAINER});
            log.warn("Impossible to find box container");
        }

        return errors.length > 0 ? errors : valid;

    };

    MapCreator.prototype._initVariables = function () {

        //pub/sub
        this.channels = {};

        this.status = {};
        this.status.ready = false;

        this.pivotator = new Pivotator();
        this.fenixTool = new Fenixtool();
    };

    MapCreator.prototype._bindEventListeners = function () {

        amplify.subscribe(this._getEventName(EVT.WINDOW_RESIZE), this, this.invalidateSize);
    };

    MapCreator.prototype._renderMap = function () {

        var self = this;

        //var myPivotatorConfig=this.fenixTool.parseInut(this.initial.model.metadata.dsd, this.pivotatorConfig);
        //var model = this.pivotator.pivot(this.model, this.pivotatorConfig);

        self.fenixMap = new FM.Map(self.$el, self.fenix_ui_mapConfig);
        self.fenixMap.createMap();

        self.leafletMap = self.fenixMap.map;

        self.addLayer(self.model)

         //TODO bind to Leaflet whenReady
        self.status.ready = true;  //To be set on map ready event

        setTimeout(_.bind(function () {
            self._trigger('ready');
        }, self), 0);
    };

    MapCreator.prototype._trigger = function (channel) {

        if (!this.channels[channel]) {
            return false;
        }
        var args = Array.prototype.slice.call(arguments, 1);
        for (var i = 0, l = this.channels[channel].length; i < l; i++) {
            var subscription = this.channels[channel][i];
            subscription.callback.apply(subscription.context, args);
        }

        return this;
    };

    MapCreator.prototype._getEventName = function (evt) {

        return this.id.concat(evt);

    };

    MapCreator.prototype._unbindEventListeners = function () {

        amplify.unsubscribe(this._getEventName(EVT.WINDOW_RESIZE), this.invalidateSize);
    };

    MapCreator.prototype.dispose = function () {

        //unbind event listeners
        this._unbindEventListeners();

        if (this.status.ready === true) {
            this.fenixMap.destroyMap();
        }

        this.$el.empty();

    };

    MapCreator.prototype.createLayerFenix = function (model, options) {
        var metadata = model.metadata;
        var layer = {};
        // Define the layer
        if (metadata.hasOwnProperty("dsd")) {
            layer.layers = "";
            if (metadata.dsd.hasOwnProperty("workspace"))
                layer.layers += metadata.dsd.workspace + ":";

            layer.layers += metadata.dsd.layerName;
        }
        else {
            this.errors['dsd'] = "Model['metadata'] does not contain 'dsd' attribute.";
            throw new Error("FENIX Map creator has not a valid configuration");
        }

        //TODO
        //if (model.hasOwnProperty("datasource"))
        //  layer.urlWMS = metadata["datasource"];

        layer.urlWMS = this.fenix_ui_map.DEFAULT_WMS_SERVER;
        layer.layertitle = {
            en: 'Data Layer'
        };
        layer.opacity = '0.9';
        return layer;
    };

    // JOIN
    MapCreator.prototype.createLayerFenixJoin = function (model) {
        if (this._validateJoinInput(model) === true) {

            // create the join layer
            var layer = this.getJoinLayer(model);

            _.extend(layer, this.join.style);

            var defPopup = "
{{"+ layer.joincolumnlabel +"}}"+
                "
{{{"+ layer.joincolumn + "}}} "+
                "{{measurementunit}}"+
                "

";

            // Layer title TODO: Add title if exist (check in the validator)
            if (model['metadata'].hasOwnProperty("title")) {
                if (model['metadata']['title'][this.lang]) {
                    layer.layertitle = model['metadata']['title'][this.lang];
                    console.log('title',this.lang, layer.layertitle)
                }
            }
            else {
                layer.layertitle = model['metadata']['uid'];
            }

            // getting a title from the options
            if ( this.hasOwnProperty('layer') && this.layer.hasOwnProperty('layertitle')) {
                layer.layertitle = this.layer.layertitle;
            }

            if ( this.hasOwnProperty('layer') && this.layer.hasOwnProperty('popupBuilder')) {
                layer.popupBuilder = this.layer.popupBuilder;
            }

            layer.customgfi = {
                showpopup: true,
                content: {
                    EN: _.isFunction(layer.popupBuilder) ? layer.popupBuilder(layer.joincolumnlabel, layer.joincolumn) : defPopup
                }
            };

            // TODO: add check on the zoomto data (move it to a function)
            var codes = [];
            layer.joindata.forEach(function (code) {
                _.keys(code).forEach(function (key) {
                    codes.push(key);
                });
            });

            var zoomlayer = layer.layers.split(":");

            zoomlayer = zoomlayer.length > 1? zoomlayer[1]: zoomlayer[0];

            this.fenixMap.zoomTo(zoomlayer, layer.joincolumn, codes);

            return layer;
        } else {
            console.error(this.errors);
            throw new Error("FENIX Map creator has not a valid JOIN configuration");
        }
    };

    MapCreator.prototype.getJoinLayer = function (model) {

        var metadata = model['metadata'],
            geoColumn = {},
            valueColumn = {},
            muColumn = {};

        metadata['dsd']['columns'].forEach(_.bind(function (col, index) {
            if (col.subject === this.geoSubject || col.id === this.geoSubject ) {
                geoColumn = col;
                geoColumn.index = index;
            }
            if (col.subject === this.valueSubject || col.id === this.valueSubject ) {
                valueColumn = col;
                valueColumn.index = index;
            }
            if (col.subject === this.muSubject) {
                muColumn = col;
                muColumn.index = index;
            }
        }, this));

        // getting the right measurement unit if the new label exists
        metadata['dsd']['columns'].forEach(_.bind(function (column, index) {
            if (muColumn.id + '_' + this.lang) {
                muColumn = column;
                muColumn.index = index;
            }
        }, this));

        if (this._validateJoinColumnInput(geoColumn)) {

            var layer = null;
            var codelist = geoColumn['domain']['codes'][0]['idCodeList'].toLowerCase();

            if (this.join.layerMapping[codelist]) {
                layer = this.join.layerMapping[codelist];
            }
            else {
                geoColumn['domain']['codes'][0].idCodeList.toLowerCase();
                // TODO: Handle reference Area
                var referenceArea = metadata["meContent"]["seReferencePopulation"]["referenceArea"]['codes'][0].code.toLowerCase();
                layer = this.join.layerMapping[codelist + "_" + referenceArea];
            }

            // check measurementunit
            // TODO: Add measurement unit to the layer definition (using label column of the mu)
            //

            // get joinData
            layer.joindata = this.getJoinData(model['data'], geoColumn.index, valueColumn.index);

            // TODO: check on the column index
            layer.measurementunit = model['data'][0][muColumn.index];

            // TODO: check if is the right legendtitle
            layer.legendtitle = layer.measurementunit;

            return layer;

        } else{
            console.error('Error JoinColumnInput not valid')
        }
    };

    MapCreator.prototype.getJoinData = function (data, geoColumnIndex, valueColumnIhdex) {
        var joindata = [];

        // TODO: remove cachedValues on final version. Check on join data consistency?
        var cachedValues = {}
        // TODO: add on check
        data.forEach(_.bind(function (row) {
            var obj = {}
            var code = row[geoColumnIndex];
            var value = row[valueColumnIhdex];
            if (code && value) {
                obj[code] = value ;
                if (!cachedValues.hasOwnProperty(code)) {
                    // check null values
                    cachedValues[code] = true;
                    joindata.push(obj);
                }
            }
        }, this));

        return joindata;
    };

    MapCreator.prototype.iso3Boundaries = function(code) {
        var self = this;
            /*geoUrl = "http://fenix.fao.org:20200/geoserver/fenix/ows"+
                "?service=WFS&version=1.0.0&request=GetFeature&typeName=fenix:gaul0_bounds&maxFeatures=50&outputFormat=application/json&"+
                "viewparams=iso3_code:"+code;
        */
        var rootUrl = "http://fenix.fao.org:20200/geoserver/fenix/ows";

        var defaultParameters = {
            service: 'WFS',
            version: '1.0.0',
            request: 'GetFeature',
            typeName: 'fenix:gaul0_bounds',
            maxFeatures: 50,
            outputFormat: 'text/javascript',
            format_options: 'callback: getJson',
            srsName: 'EPSG:4326',
            viewparams: 'iso3_code:'+code
        };

        var parameters = L.Util.extend(defaultParameters);

        $.ajax({
            url: rootUrl + L.Util.getParamString(parameters),
            dataType: 'jsonp',
            jsonpCallback: 'getJson',
            success: function(json) {

                //console.log('iso3Boundaries',json);

                var gLayer = L.geoJson(json, {
                    style: function (feature) {
                        return {
                            color: '#f00',
                            fillColor: '#f00'
                        };
                    }
                });
                self.fenixMap.map.addLayer( gLayer );

                self.fenixMap.map.fitBounds( gLayer.getBounds() );

            }
        });
    };

    MapCreator.prototype._validateJoinInput = function (model) {
        this.errors = {};

        //Metadata TODO: add all metadata checks
        if (!model.hasOwnProperty("metadata")) {
            this.errors.metadata = "'metadata' attribute not present.";
        }

        //Data
        if (!model.hasOwnProperty("data")) {
            this.errors.data = "'data' attribute not present.";
        }

        return (_.keys(this.errors).length === 0);
    };

    MapCreator.prototype._validateJoinColumnInput = function (column) {
        this.errors = {};

        //Metadata TODO: add all metadata checks
        if (!column.hasOwnProperty('key')) {
            this.errors.column = "'key' attribute not present.";
        }
        else {
            if (column.key !== true) {
                this.errors.column = "'key' is not true.";
            }
        }

        if (!column.hasOwnProperty('dataType')) {
            this.errors.column = "'dataType' attribute not present.";
        }
        else {
            if (column.dataType !== 'code') {
                this.errors.column = "'dataType' attribute is not a coding system.";
            }
        }

        // TODO: check domain and referencearea if needed

        return (Object.keys(this.errors).length === 0);
    };

    return MapCreator;
});<|endoftext|>


<commit_before>ngGridDirectives.directive('ngGrid', ['$compile', '$filter', '$templateCache', '$sortService', '$domUtilityService', '$utilityService', '$timeout', '$parse', function ($compile, $filter, $templateCache, sortService, domUtilityService, $utils, $timeout, $parse) {
    var ngGridDirective = {
        scope: true,
        compile: function() {
            return {
                pre: function($scope, iElement, iAttrs) {
                    var $element = $(iElement);
                    var options = $scope.$eval(iAttrs.ngGrid);
                    options.gridDim = new ngDimension({ outerHeight: $($element).height(), outerWidth: $($element).width() });
                    var grid = new ngGrid($scope, options, sortService, domUtilityService, $filter, $templateCache, $utils, $timeout, $parse);

                    // if columndefs are a string of a property ont he scope watch for changes and rebuild columns.
                    if (typeof options.columnDefs == "string") {
                        $scope.$parent.$watch(options.columnDefs, function (a) {
                            if (!a) {
                                grid.refreshDomSizes();
                                grid.buildColumns();
                                return;
                            }
                            // we have to set this to false in case we want to autogenerate columns with no initial data.
                            grid.lateBoundColumns = false;
                            $scope.columns = [];
                            grid.config.columnDefs = a;
                            grid.buildColumns();
                            grid.configureColumnWidths();
                            grid.eventProvider.assignEvents();
                            domUtilityService.RebuildGrid($scope, grid);
                        }, true);
                    } else {
						grid.buildColumns();
					}

                    // if it is a string we can watch for data changes. otherwise you won't be able to update the grid data
                    if (typeof options.data == "string") {
                        var dataWatcher = function (a) {
                            // make a temporary copy of the data
                            grid.data = $.extend([], a);
                            grid.rowFactory.fixRowCache();
                            angular.forEach(grid.data, function (item, j) {
                                var indx = grid.rowMap[j] || j;
                                if (grid.rowCache[indx]) {
                                    grid.rowCache[indx].ensureEntity(item);
                                }
                                grid.rowMap[indx] = j;
                            });
                            grid.searchProvider.evalFilter();
                            grid.configureColumnWidths();
                            grid.refreshDomSizes();
                            if (grid.config.sortInfo.fields.length > 0) {
                                grid.getColsFromFields();
                                grid.sortActual();
                                grid.searchProvider.evalFilter();
                                $scope.$emit('ngGridEventSorted', grid.config.sortInfo);
                            }
                            $scope.$emit("ngGridEventData", grid.gridId);
                        };
                        $scope.$parent.$watch(options.data, dataWatcher);
                        $scope.$parent.$watch(options.data + '.length', function() {
                            dataWatcher($scope.$eval(options.data));
                        });
                    }

                    grid.footerController = new ngFooter($scope, grid);
                    //set the right styling on the container
                    iElement.addClass("ngGrid").addClass(grid.gridId.toString());
                    if (!options.enableHighlighting) {
                        iElement.addClass("unselectable");
                    }
                    if (options.jqueryUITheme) {
                        iElement.addClass('ui-widget');
                    }
                    iElement.append($compile($templateCache.get('gridTemplate.html'))($scope)); // make sure that if any of these change, we re-fire the calc logic
                    //walk the element's graph and the correct properties on the grid
                    domUtilityService.AssignGridContainers($scope, iElement, grid);
                    //now use the manager to assign the event handlers
                    grid.eventProvider = new ngEventProvider(grid, $scope, domUtilityService, $timeout);

                    // method for user to select a specific row programatically
                    options.selectRow = function (rowIndex, state) {
                        if (grid.rowCache[rowIndex]) {
                            if (grid.rowCache[rowIndex].clone) {
                                grid.rowCache[rowIndex].clone.setSelection(state ? true : false);
                            }
                            grid.rowCache[rowIndex].setSelection(state ? true : false);
                        }
                    };
                    // method for user to select the row by data item programatically
                    options.selectItem = function (itemIndex, state) {
                        options.selectRow(grid.rowMap[itemIndex], state);
                    };
                    // method for user to set the select all state.
                    options.selectAll = function (state) {
                        $scope.toggleSelectAll(state);
                    };
                    // method for user to set the groups programatically
                    options.groupBy = function (field) {
                        if (field) {
                            $scope.groupBy($scope.columns.filter(function(c) {
                                return c.field == field;
                            })[0]);
                        } else {
                            var arr = $.extend(true, [], $scope.configGroups);
                            angular.forEach(arr, $scope.groupBy);
                        }
                    };
                    // method for user to set the sort field programatically
                    options.sortBy = function (field) {
                        var col = $scope.columns.filter(function (c) {
                            return c.field == field;
                        })[0];
                        if (col) col.sort();
                    };
                    // the grid Id, entity, scope for convenience
					options.gridId = grid.gridId;
					options.ngGrid = grid;
					options.$gridScope = $scope;
                    options.$gridServices = { SortService: sortService, DomUtilityService: domUtilityService };
					$scope.$on('ngGridEventDigestGrid', function(){
						domUtilityService.digest($scope.$parent);
					});

					$scope.$on('ngGridEventDigestGridParent', function(){
						domUtilityService.digest($scope.$parent);
					});
                    // set up the columns
                    $scope.$evalAsync(function() {
                        $scope.adjustScrollLeft(0);
                    });
                    //initialize plugins.
                    angular.forEach(options.plugins, function (p) {
                        if (typeof p === 'function') {
                            p = p.call(this);
                        }
                        p.init($scope.$new(), grid, options.$gridServices);
                        options.plugins[$utils.getInstanceType(p)] = p;
                    });
                    //send initi finalize notification.
                    if (options.init == "function") {
                        options.init(grid, $scope);
                    }
                    return null;
                }
            };
        }
    };
    return ngGridDirective;
}]);<commit_msg>Wait for grid.init() to complete, then continue<commit_after>ngGridDirectives.directive('ngGrid', ['$compile', '$filter', '$templateCache', '$sortService', '$domUtilityService', '$utilityService', '$timeout', '$parse', '$http', '$q', function ($compile, $filter, $templateCache, sortService, domUtilityService, $utils, $timeout, $parse, $http, $q) {
    var ngGridDirective = {
        scope: true,
        compile: function() {
            return {
                pre: function($scope, iElement, iAttrs) {
                    var $element = $(iElement);
                    var options = $scope.$eval(iAttrs.ngGrid);
                    options.gridDim = new ngDimension({ outerHeight: $($element).height(), outerWidth: $($element).width() });

                    var grid = new ngGrid($scope, options, sortService, domUtilityService, $filter, $templateCache, $utils, $timeout, $parse, $http, $q);
                    return grid.init().then(function() {
                        // if columndefs are a string of a property ont he scope watch for changes and rebuild columns.
                        if (typeof options.columnDefs == "string") {
                            $scope.$parent.$watch(options.columnDefs, function (a) {
                                if (!a) {
                                    grid.refreshDomSizes();
                                    grid.buildColumns();
                                    return;
                                }
                                // we have to set this to false in case we want to autogenerate columns with no initial data.
                                grid.lateBoundColumns = false;
                                $scope.columns = [];
                                grid.config.columnDefs = a;
                                grid.buildColumns();
                                grid.configureColumnWidths();
                                grid.eventProvider.assignEvents();
                                domUtilityService.RebuildGrid($scope, grid);
                            }, true);
                        } else {
    						grid.buildColumns();
    					}

                        // if it is a string we can watch for data changes. otherwise you won't be able to update the grid data
                        if (typeof options.data == "string") {
                            var dataWatcher = function (a) {
                                // make a temporary copy of the data
                                grid.data = $.extend([], a);
                                grid.rowFactory.fixRowCache();
                                angular.forEach(grid.data, function (item, j) {
                                    var indx = grid.rowMap[j] || j;
                                    if (grid.rowCache[indx]) {
                                        grid.rowCache[indx].ensureEntity(item);
                                    }
                                    grid.rowMap[indx] = j;
                                });
                                grid.searchProvider.evalFilter();
                                grid.configureColumnWidths();
                                grid.refreshDomSizes();
                                if (grid.config.sortInfo.fields.length > 0) {
                                    grid.getColsFromFields();
                                    grid.sortActual();
                                    grid.searchProvider.evalFilter();
                                    $scope.$emit('ngGridEventSorted', grid.config.sortInfo);
                                }
                                $scope.$emit("ngGridEventData", grid.gridId);
                            };
                            $scope.$parent.$watch(options.data, dataWatcher);
                            $scope.$parent.$watch(options.data + '.length', function() {
                                dataWatcher($scope.$eval(options.data));
                            });
                        }

                        grid.footerController = new ngFooter($scope, grid);
                        //set the right styling on the container
                        iElement.addClass("ngGrid").addClass(grid.gridId.toString());
                        if (!options.enableHighlighting) {
                            iElement.addClass("unselectable");
                        }
                        if (options.jqueryUITheme) {
                            iElement.addClass('ui-widget');
                        }
                        iElement.append($compile($templateCache.get('gridTemplate.html'))($scope)); // make sure that if any of these change, we re-fire the calc logic
                        //walk the element's graph and the correct properties on the grid
                        domUtilityService.AssignGridContainers($scope, iElement, grid);
                        //now use the manager to assign the event handlers
                        grid.eventProvider = new ngEventProvider(grid, $scope, domUtilityService, $timeout);

                        // method for user to select a specific row programatically
                        options.selectRow = function (rowIndex, state) {
                            if (grid.rowCache[rowIndex]) {
                                if (grid.rowCache[rowIndex].clone) {
                                    grid.rowCache[rowIndex].clone.setSelection(state ? true : false);
                                }
                                grid.rowCache[rowIndex].setSelection(state ? true : false);
                            }
                        };
                        // method for user to select the row by data item programatically
                        options.selectItem = function (itemIndex, state) {
                            options.selectRow(grid.rowMap[itemIndex], state);
                        };
                        // method for user to set the select all state.
                        options.selectAll = function (state) {
                            $scope.toggleSelectAll(state);
                        };
                        // method for user to set the groups programatically
                        options.groupBy = function (field) {
                            if (field) {
                                $scope.groupBy($scope.columns.filter(function(c) {
                                    return c.field == field;
                                })[0]);
                            } else {
                                var arr = $.extend(true, [], $scope.configGroups);
                                angular.forEach(arr, $scope.groupBy);
                            }
                        };
                        // method for user to set the sort field programatically
                        options.sortBy = function (field) {
                            var col = $scope.columns.filter(function (c) {
                                return c.field == field;
                            })[0];
                            if (col) col.sort();
                        };
                        // the grid Id, entity, scope for convenience
    					options.gridId = grid.gridId;
    					options.ngGrid = grid;
    					options.$gridScope = $scope;
                        options.$gridServices = { SortService: sortService, DomUtilityService: domUtilityService };
    					$scope.$on('ngGridEventDigestGrid', function(){
    						domUtilityService.digest($scope.$parent);
    					});

    					$scope.$on('ngGridEventDigestGridParent', function(){
    						domUtilityService.digest($scope.$parent);
    					});
                        // set up the columns
                        $scope.$evalAsync(function() {
                            $scope.adjustScrollLeft(0);
                        });
                        //initialize plugins.
                        angular.forEach(options.plugins, function (p) {
                            if (typeof p === 'function') {
                                p = p.call(this);
                            }
                            p.init($scope.$new(), grid, options.$gridServices);
                            options.plugins[$utils.getInstanceType(p)] = p;
                        });
                        //send initi finalize notification.
                        if (options.init == "function") {
                            options.init(grid, $scope);
                        }
                        return null;
                    });
                }
            };
        }
    };
    return ngGridDirective;
}]);<|endoftext|>


<commit_before>/**
 * PackageVersionController
 *
 * @description :: Server-side logic for managing packageversions
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

module.exports = {

  postDescription: function(req, res) {
    var result = PackageVersion.createWithDescriptionFile({input: req.body});
    result.then(function(value) {
      //console.log(value.dependencies);
      res.json(value);
    }).catch(function(err){
        return res.negotiate(err);
    });
  },

  /**
  * @api {get} /packages/:name/versions/:version Request PackageVersion information
  * @apiName Get PackageVersion
  * @apiGroup PackageVersion
  *
  * @apiParam {String} name Name of the package
  * @apiParam {String} version Version of the package
  *
  * @apiUse Timestamps
  * @apiSuccess {String}   url              Url to this package version
  * @apiSuccess {String}   package_url      Url to the package of this version
  * @apiSuccess {String}   id               Id of this version
  * @apiSuccess {String}   package_name     Name of the package of this version
  * @apiSuccess {String}   version          String describing the version of the package
  * @apiSuccess {String}   title            Title of the version
  * @apiSuccess {String}   description      Description of the package version
  * @apiSuccess {Date}     release_date     Release date of the package version
  * @apiSuccess {String}   license          License of the package version
  * @apiSuccess {String}   maintainer_id    Id of the maintainer of the package version
  * @apiSuccess {Object}   maintainer       Description of the maintainer of this package version
  * @apiSuccess {String}   maintainer.name  Name of the maintainer of the package version
  * @apiSuccess {String}   maintainer.email Email of the maintainer of the package version
  * @apiSuccess {Object[]} authors          List of the authors of this package version
  * @apiSuccess {String}   authors.name     Name of this author of the package version
  * @apiSuccess {String}   authors.email    Email of this author of the package version

  */
  findByNameVersion: function(req, res) {
    var packageName = req.param('name');
    var packageVersion = req.param('version');

    PackageVersion.findOne({
      where: {
        package_name: packageName,
        version: packageVersion
      },
      include: [
        { model: Collaborator, as: 'maintainer', attributes: ['name', 'email'] },
        { model: Collaborator, as: 'authors', attributes: ['name', 'email'] }
      ]
    }).then(function(version) {
      if(version === null) return res.notFound();
      else return res.json(version);
    }).catch(function(err) {
      return res.negotiate(err);
    });

  }

};

<commit_msg>Apidoc for POST PackageVersion<commit_after>/**
 * PackageVersionController
 *
 * @description :: Server-side logic for managing packageversions
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

module.exports = {

  /**
  * @api {post} /versions Create a new PackageVersion
  * @apiName Create PackageVersion
  * @apiGroup PackageVersion
  *
  * @apiDescription Create a new PackageVersion from a parsed DESCRIPTION file, for more information
  * about the fields and their semantic, visit https://cran.r-project.org/doc/manuals/r-release/R-exts.html#The-DESCRIPTION-file
  *
  * @apiParam {String}  PackageName  Name of the package.
  * @apiParam {String}  Title        Title of the package version.
  * @apiParam {String}  Version      String representation of the version of the package
  * @apiParam {Date}    [Date]         ISO8601 Date formatted representing the release date of the version
  * @apiParam {String}  Maintainer   Name and email of the maintainer, email is mandatory and must be delimited by `<>`, `<email></email>` or `()`
  * @apiParam {String}  Description  Description of the package version
  * @apiParam {String}  License      License used for the package version
  * @apiParam {String}  [URL]        Comma separated list of url pointing to useful resources
  * @apiParam {String}  [Copyright]  Information about copyright
  * @apiParam {String}  [Author]     Comma separated list of package author, email are optional but must be delimited by `<>`, `<email></email>` or `()`
  * @apiParam {String}  [Depends]    Comma separated list of packages dependencies
  * @apiParam {String}  [Import]     Comma separated list of imported packages
  * @apiParam {String}  [Suggests]   Comma separated list of suggested packages
  * @apiParam {String}  [Enhances]   Comma separated list of enhanced packages

  @apiError 400 ValidationError
  @apiError 409 ConflictError A package version with the same package name and version already exists

  */
  postDescription: function(req, res) {
    var result = PackageVersion.createWithDescriptionFile({input: req.body});
    result.then(function(value) {
      //console.log(value.dependencies);
      res.json(value);
    }).catch(function(err){
        return res.negotiate(err);
    });
  },

  /**
  * @api {get} /packages/:name/versions/:version Request PackageVersion information
  * @apiName Get PackageVersion
  * @apiGroup PackageVersion
  *
  * @apiParam {String} name Name of the package
  * @apiParam {String} version Version of the package
  *
  * @apiUse Timestamps
  * @apiSuccess {String}   url              Url to this package version
  * @apiSuccess {String}   package_url      Url to the package of this version
  * @apiSuccess {String}   id               Id of this version
  * @apiSuccess {String}   package_name     Name of the package of this version
  * @apiSuccess {String}   version          String describing the version of the package
  * @apiSuccess {String}   title            Title of the version
  * @apiSuccess {String}   description      Description of the package version
  * @apiSuccess {Date}     release_date     Release date of the package version
  * @apiSuccess {String}   license          License of the package version
  * @apiSuccess {String}   maintainer_id    Id of the maintainer of the package version
  * @apiSuccess {Object}   maintainer       Description of the maintainer of this package version
  * @apiSuccess {String}   maintainer.name  Name of the maintainer of the package version
  * @apiSuccess {String}   maintainer.email Email of the maintainer of the package version
  * @apiSuccess {Object[]} authors          List of the authors of this package version
  * @apiSuccess {String}   authors.name     Name of this author of the package version
  * @apiSuccess {String}   authors.email    Email of this author of the package version

  */
  findByNameVersion: function(req, res) {
    var packageName = req.param('name');
    var packageVersion = req.param('version');

    PackageVersion.findOne({
      where: {
        package_name: packageName,
        version: packageVersion
      },
      include: [
        { model: Collaborator, as: 'maintainer', attributes: ['name', 'email'] },
        { model: Collaborator, as: 'authors', attributes: ['name', 'email'] }
      ]
    }).then(function(version) {
      if(version === null) return res.notFound();
      else return res.json(version);
    }).catch(function(err) {
      return res.negotiate(err);
    });

  }

};

<|endoftext|>


<commit_before>angular.module("oxymoron.notifier", [])
  .run(['$rootScope', 'ngNotify', 'Validate', '$state', '$http', '$location', function ($rootScope, ngNotify, Validate, $state, $http, $location) {
    ngNotify.config({
        theme: 'pure',
        position: 'top',
        duration: 2000,
        type: 'info'
    });

    $rootScope.$on('loading:finish', function (h, res) {
      if (res.headers()['x-csrf-token']) {
        $http.defaults.headers.common['X-CSRF-Token'] = res.headers()['x-csrf-token'];
      }

      if (res.data && res.data.msg) {
        ngNotify.set(res.data.msg, 'success');
      }

      if (res.data && res.data.redirect_to_url) {
        $location.path(res.data.redirect_to_url);
      }
      else if (res.data && res.data.redirect_to) {
        $state.go(res.data.redirect_to, res.data.redirect_options || {});
      }
    })

    $rootScope.$on('loading:error', function (h, res, p) {
      if (angular.isObject(res.data)) {
        if (res.data.msg) {
          ngNotify.set(res.data.msg, 'error');
        }
        if (res.data.errors) {
          Validate(res.data.form_name || res.config.data.form_name, res.data.errors)
        }
        if (res.data && res.data.redirect_to) {
          $state.go(res.data.redirect_to)
        }
      } else {
        if ([-1, 304].indexOf(res.status) == -1) {
          ngNotify.set(res.statusText, 'error');
        }
      }
    })
  }])<commit_msg>reload parameter<commit_after>angular.module("oxymoron.notifier", [])
  .run(['$rootScope', 'ngNotify', 'Validate', '$state', '$http', '$location', function ($rootScope, ngNotify, Validate, $state, $http, $location) {
    ngNotify.config({
        theme: 'pure',
        position: 'top',
        duration: 2000,
        type: 'info'
    });

    $rootScope.$on('loading:finish', function (h, res) {
      if (res.headers()['x-csrf-token']) {
        $http.defaults.headers.common['X-CSRF-Token'] = res.headers()['x-csrf-token'];
      }

      if (res.data && res.data.msg) {
        ngNotify.set(res.data.msg, 'success');
      }

      if (res.data && res.data.redirect_to_url) {
        $location.path(res.data.redirect_to_url);
      }
      else if (res.data && res.data.redirect_to) {
        $state.go(res.data.redirect_to, res.data.redirect_options || {});
      }

      if (res.data.reload) {
        window.location.reload();
      }
    })

    $rootScope.$on('loading:error', function (h, res, p) {
      if (angular.isObject(res.data)) {
        if (res.data.msg) {
          ngNotify.set(res.data.msg, 'error');
        }
        if (res.data.errors) {
          Validate(res.data.form_name || res.config.data.form_name, res.data.errors)
        }
        if (res.data && res.data.redirect_to) {
          $state.go(res.data.redirect_to)
        }
      } else {
        if ([-1, 304].indexOf(res.status) == -1) {
          ngNotify.set(res.statusText, 'error');
        }
      }
    })
  }])<|endoftext|>


<commit_before>Whitelab.metadata = {
	filterTokenSafeLimit : 0,

	init : function() {
		var filter = $('#metadata-filters').data('filter');
		if (filter.length > 0) {
			filter = filter.substr(1,filter.length - 2);
			var parts = filter.split(')AND(');
			for (var i = 0; i < parts.length; i++) {
				var match = parts[i].match(/^([A-Za-z0-9]+)_([A-Za-z0-9_]+)(\!*=|\>=*|\<=*)(.+)$/);
				Whitelab.metadata.addMetadataRule(match[1],match[2],Whitelab.search.operatorToValue(match[3]),match[4].replace(/"/g, ''));
			}
		} else {
			Whitelab.metadata.addMetadataRule(null,null,null,null);
		}

		$(document).on('change', '.metadata-key-select', function(e) {
			var vals = $(this).val().split('_');
			var group = vals[0];
			var key = $(this).val().replace(group+'_','');
			var rule_id = $(this).parent().parent().attr('id');
			if (group.length > 0 && key.length > 0 && rule_id.length > 0)
				$.getScript('/metadata/'+group+'/'+key+'/values.js?rule_id='+rule_id);
			else
				$(this).parent().parent().find('select.metadata-input').first().replaceWith('<input class="metadata-input" type="text">');
		});
		$(document).on('change', 'select.metadata-input', function(e) {
			Whitelab.metadata.updateCoverage();
		});
		$(document).on('change', 'select.metadata-operator', function(e) {
			Whitelab.metadata.updateCoverage();
		});
	},

	addMetadataRule : function(group,key,operator,value) {
		var i = $('.metadata-rule').length;
		while ($('#rule'+i).length > 0) {
			i++;
		}
		if (group && key && operator && value)
			$.getScript('/metadata/rule/new.js?rule_id='+i+'&group='+group+'&key='+key+'&operator='+operator+'&value='+value);
		else
			$.getScript('/metadata/rule/new.js?rule_id='+i);
	},

	getFilterString : function() {
		var filters = new Array();
		$("#metadata-rules .rule").each(function( index ) {
			var label = $(this).find(".metadata-key-select").val();
			var input = $(this).find(".metadata-input").val().replace(/&/g,"%26");
			var op = $(this).find(".metadata-operator").val();
			if (op === 'not') {
				op = '!=';
			} else {
				op = '=';
			}
			if (label && input && input.length > 0) {
				var f = label+op+"\""+input+"\"";
				f = f.replace(/field\:/g,"");
				filters.push(f);
			}
		});
		if (filters.length > 0) {
			var filterQuery = "("+filters.join(")AND(")+")";
			return filterQuery;
		}
		return "";
	},

	updateCoverage : function() {
		var filterString = Whitelab.metadata.getFilterString();
		if (filterString.length > 0) {
			$('span.metadata-selected-percentage').html('

');
			$('span.metadata-selected-absolute').html('

');
			$.getScript('/metadata/coverage.js?filter='+filterString);
		} else {
			$('span.metadata-selected-percentage').html('100');
			$('span.metadata-selected-absolute').html($('#metadata-filters').data('total-tokens'));
		}
		Whitelab.metadata.updateTabLinks(filterString);
	},

	updateTabLinks : function(filter) {
		var link_ids = [];
		if (Whitelab.namespace === 'search') {
			link_ids = ['extended','advanced','expert'];
		} else if (Whitelab.namespace === 'explore') {
			link_ids = ['corpora','statistics','ngrams'];
		}
		for (var i = 0; i < link_ids.length; i++) {
			if (!$('li#'+link_ids[i]+'_link').hasClass('active')) {
				$('li#'+link_ids[i]+'_link > a').attr('href','/'+Whitelab.namespace+'/'+link_ids[i]+'?filter='+filter);
			}
		}
	}

};<commit_msg>Bugfix<commit_after>Whitelab.metadata = {
	filterTokenSafeLimit : 0,

	init : function() {
		var filter = $('#metadata-filters').data('filter');
		if (filter.length > 0) {
			filter = filter.substr(1,filter.length - 2);
			var parts = filter.split(')AND(');
			for (var i = 0; i < parts.length; i++) {
				var match = parts[i].match(/^(([A-Za-z0-9]+)_)*([A-Za-z0-9_]+)(\!*=|\>=*|\<=*)(.+)$/);
				Whitelab.metadata.addMetadataRule(match[1],match[3],Whitelab.search.operatorToValue(match[4]),match[5].replace(/"/g, ''));
			}
		} else {
			Whitelab.metadata.addMetadataRule(null,null,null,null);
		}

		$(document).on('change', '.metadata-key-select', function(e) {
			var vals = $(this).val().split('_');
			var group = vals[0];
			var key = $(this).val().replace(group+'_','');
			var rule_id = $(this).parent().parent().attr('id');
			if (group.length > 0 && key.length > 0 && rule_id.length > 0)
				$.getScript('/metadata/'+group+'/'+key+'/values.js?rule_id='+rule_id);
			else
				$(this).parent().parent().find('select.metadata-input').first().replaceWith('<input class="metadata-input" type="text">');
		});
		$(document).on('change', 'select.metadata-input', function(e) {
			Whitelab.metadata.updateCoverage();
		});
		$(document).on('change', 'select.metadata-operator', function(e) {
			Whitelab.metadata.updateCoverage();
		});
	},

	addMetadataRule : function(group,key,operator,value) {
		var i = $('.metadata-rule').length;
		while ($('#rule'+i).length > 0) {
			i++;
		}
		if (group && key && operator && value)
			$.getScript('/metadata/rule/new.js?rule_id='+i+'&group='+group+'&key='+key+'&operator='+operator+'&value='+value);
		else
			$.getScript('/metadata/rule/new.js?rule_id='+i);
	},

	getFilterString : function() {
		var filters = new Array();
		$("#metadata-rules .rule").each(function( index ) {
			var label = $(this).find(".metadata-key-select").val();
			var input = $(this).find(".metadata-input").val().replace(/&/g,"%26");
			var op = $(this).find(".metadata-operator").val();
			if (op === 'not') {
				op = '!=';
			} else {
				op = '=';
			}
			if (label && input && input.length > 0) {
				var f = label+op+"\""+input+"\"";
				f = f.replace(/field\:/g,"");
				filters.push(f);
			}
		});
		if (filters.length > 0) {
			var filterQuery = "("+filters.join(")AND(")+")";
			return filterQuery;
		}
		return "";
	},

	updateCoverage : function() {
		var filterString = Whitelab.metadata.getFilterString();
		if (filterString.length > 0) {
			$('span.metadata-selected-percentage').html('

');
			$('span.metadata-selected-absolute').html('

');
			$.getScript('/metadata/coverage.js?filter='+filterString);
		} else {
			$('span.metadata-selected-percentage').html('100');
			$('span.metadata-selected-absolute').html($('#metadata-filters').data('total-tokens'));
		}
		Whitelab.metadata.updateTabLinks(filterString);
	},

	updateTabLinks : function(filter) {
		var link_ids = [];
		if (Whitelab.namespace === 'search') {
			link_ids = ['extended','advanced','expert'];
		} else if (Whitelab.namespace === 'explore') {
			link_ids = ['corpora','statistics','ngrams'];
		}
		for (var i = 0; i < link_ids.length; i++) {
			if (!$('li#'+link_ids[i]+'_link').hasClass('active')) {
				$('li#'+link_ids[i]+'_link > a').attr('href','/'+Whitelab.namespace+'/'+link_ids[i]+'?filter='+filter);
			}
		}
	}

};<|endoftext|>


<commit_before>import React from 'react';
import _ from 'lodash';
import ColumnHeader from './road-table-column-header';
import Row from '../containers/road-table-row-container';
import CreateRoadForm from '../containers/create-road-form-container';
import RoadPagination from './road-pagination';
import RoadProgressBar from './road-progress-bar';
import T from './t';

const RoadTable = ({
  adminRoadProperties, fieldRoads, roadsPage, roadsPageStatus,
  roadCount, roadPageCount, roadCountStatus,
  page, sortOrder,
  sortColumnAction, setPage
}) => (

    {
      roadCountStatus === 'complete' && roadCount > 0 &&
        <RoadProgressBar
          fieldCount={fieldRoads.length}
          roadCount={roadCount}
        />
    }
    <CreateRoadForm />

    {roadsPageStatus === 'pending' ?

<T>Loading</T>

 :

                <ColumnHeader
                  columnKey="id"
                  label="VPRoMMS ID"
                  sortField="id"
                  sortOrder={sortOrder}
                  sortColumnAction={sortColumnAction}
                />
                <T>Field Data</T>
                <T>Properties</T>

              {_.map(roadsPage, (vpromm) => (
                <Row
                  key={vpromm}
                  vpromm={vpromm}
                  adminRoadProperties={adminRoadProperties}
                  vprommFieldInDB={fieldRoads.includes(vpromm)}
                />
              ))}

        {
          roadCountStatus === 'complete' &&
            <RoadPagination
              page={page}
              roadPageCount={roadPageCount}
              setPage={setPage}
            />
        }

    }

);

RoadTable.propTypes = {
  roadsPage: React.PropTypes.array,
  roadPageCount: React.PropTypes.number
};

export default RoadTable;
<commit_msg>simplify table markdown<commit_after>import React from 'react';
import _ from 'lodash';
import ColumnHeader from './road-table-column-header';
import Row from '../containers/road-table-row-container';
import CreateRoadForm from '../containers/create-road-form-container';
import RoadPagination from './road-pagination';
import RoadProgressBar from './road-progress-bar';
import T from './t';

const RoadTable = ({
  adminRoadProperties, fieldRoads, roadsPage, roadsPageStatus,
  roadCount, roadPageCount, roadCountStatus,
  page, sortOrder,
  sortColumnAction, setPage
}) => (

    {
      roadCountStatus === 'complete' && roadCount > 0 &&
        <RoadProgressBar
          fieldCount={fieldRoads.length}
          roadCount={roadCount}
        />
    }

    <CreateRoadForm />

    {roadsPageStatus === 'pending' ?

<T>Loading</T>

 :

              <ColumnHeader
                columnKey="id"
                label="VPRoMMS ID"
                sortField="id"
                sortOrder={sortOrder}
                sortColumnAction={sortColumnAction}
              />
              <T>Field Data</T>
              <T>Properties</T>

            {_.map(roadsPage, (vpromm) => (
              <Row
                key={vpromm}
                vpromm={vpromm}
                adminRoadProperties={adminRoadProperties}
                vprommFieldInDB={fieldRoads.includes(vpromm)}
              />
            ))}

    }
    {
      roadCountStatus === 'complete' &&
        <RoadPagination
          page={page}
          roadPageCount={roadPageCount}
          setPage={setPage}
        />
    }

);

RoadTable.propTypes = {
  roadsPage: React.PropTypes.array,
  roadPageCount: React.PropTypes.number
};

export default RoadTable;
<|endoftext|>


<commit_before>
//Questa funzione serve a generare dinamicamente il codice del menu che compare al passaggio del mouse sopra una iApi
function getActions(iapiclass, iapiid){

codeactions="";
codeactions = codeactions.concat('Use data
');
var classes=iapiclass.split(" ");
for(i=0;i<classes.length;i++){
if(classes[i].slice(0,4)==("rss:")){
codeactions=codeactions.concat('getRss \n');
}
}
$("div[class~=iapiactions]").html(codeactions);
}

//Bidimensional target (Div,Table .. )
function generate(data, idTemplate) {

    template = $('#' + idTemplate);  // select the template

    var txt = "";
    $.each(data, function (key, value) {

        var subtemplate = template.find('[class*=data]');  //get the dataitem

        $.each(value, function (key, value) {

            //   subtemplate.prop('id',key);    //set an Id for the current..

            var tmpChild = subtemplate.children();

            var i = 0;  // counter dipends on the object element (dataattribute of each dataitem)
            for (var j = 0 ; j < 3; j++) {
                console.log($(tmpChild).eq(j).html());
                $(tmpChild).eq(j).html(function () {

                    for (var key in value) {

                        if ($(tmpChild).eq(j).attr("class").substr(14) === key)
                            return value[key];
                    }
                });
            }
            i++;
            txt = txt.concat($(subtemplate)[0].outerHTML);
        });

    });
    template.find('[class*=data]').remove();
    $(template).append(txt);

}

function middlewareAction(msg,id, callback) {
    var messageReturn = "done";
    console.log("LIBGEN:message:" + msg + " id:" + id);

    callback(messageReturn);
}<commit_msg>rendering of a template (drag&drop / prefilled )<commit_after>
//Questa funzione serve a generare dinamicamente il codice del menu che compare al passaggio del mouse sopra una iApi
function getActions(iapiclass, iapiid){

codeactions="";
codeactions = codeactions.concat('Use data
');
var classes=iapiclass.split(" ");
for(i=0;i<classes.length;i++){
if(classes[i].slice(0,4)==("rss:")){
codeactions=codeactions.concat('getRss \n');
}
}
$("div[class~=iapiactions]").html(codeactions);
}

//Bidimensional target (Div,Table .. )
function generate(data, idTemplate) {

    template = $('#' + idTemplate);  // select the template

    var txt = "";

    $.each(data, function (key, value) {

        var subtemplate = template.find('[class*=data]');  //get the dataitem

        // checks whether the template is auto implemented or given by the developer  "Presence of iapitemplate "
        var SplitDataAttribute = subtemplate.attr("class").split(" ");
        var iapiTemplatePresence;
        for (i = 0; i < SplitDataAttribute.length; i++) {
            if (SplitDataAttribute[i].slice(0, 12) == ("iapitemplate")) {
                iapiTemplatePresence = SplitDataAttribute[i].substr(0,12);
            }

        }

//rendering based on developer template (prefilled template)
        if(iapiTemplatePresence){
        $.each(value, function (key, value) {

            //   subtemplate.prop('id',key);    //set an Id for the current..

            var  tmpChild=subtemplate.children();

            for(var j=0 ;j<3;j++ ){
                console.log( $(tmpChild).eq(j).html());
                $(tmpChild).eq(j).html(function(){

                    // $.each(value,function(key,values){
                    for(var key in value){
                        //console.log(key+"  "+$(tmpChild).eq(j).attr("class").substr(14));
                        if($(tmpChild).eq(j).attr("class").substr(14) === key){

                            return value[key] ;

                        }
                    }

                });
            }

            txt=txt.concat($(subtemplate)[0].outerHTML);
        });
        }

   //autogenerated template (injected from the template file or default one )
  else if(!iapiTemplatePresence){
        $.each(value, function (key, value) {

            var tmpChild = subtemplate.children();

            var i = 0;  // counter dipends on the object element (dataattribute of each dataitem)
            var txt2="";
            for (var key in value) {
               var td= $(tmpChild).clone();
                td.html(value[key]);
                txt2=txt2.concat($(td)[0].outerHTML);
                   i++;
            }

            $(subtemplate).html(txt2);

            txt = txt.concat($(subtemplate)[0].outerHTML);
        });
        }
    });
    template.find('[class*=data]').remove();
    $(template).append(txt);

}

function middlewareAction(msg,id, callback) {
    var messageReturn = "done";
    console.log("LIBGEN:message:" + msg + " id:" + id);

    callback(messageReturn);
}<|endoftext|>


<commit_before>module.exports = function (req, res, next) {
  const ua = req.get("User-Agent");

  // This is used to auto-crawl links in Outlook
  // and renders the one-time code unusable. We could
  // work around this but for now, let's do this.
  if (ua && ua.indexOf("BingPreview") === -1) {
    return next();
  }

  res.status(403);
  res.send("Forbidden: link must be clicked by user, not crawled by bot");
};
<commit_msg>Updates ua logic<commit_after>module.exports = function (req, res, next) {
  // ua can sometimes be undefined
  const ua = req.get("User-Agent") || "";

  // This is used to auto-crawl links in Outlook
  // and renders the one-time code unusable. We could
  // work around this but for now, let's do this.
  if (ua.indexOf("BingPreview") === -1) {
    return next();
  }

  res.status(403);
  res.send("Forbidden: link must be clicked by user, not crawled by bot");
};
<|endoftext|>