<commit_before>

// Results
//  s: success
//  a: advantage
//  T: triumph
//  f: failure
//  t: threat
//  D: despair
//  l: light side F
//  k: dark side F

var BOOST_DIE = [ '', '', 's', 'sa', 'aa', 'a' ];
var SETBACK_DIE = [ '', '', 'f', 'f', 't', 't' ];
var ABILITY_DIE = [ '', 's', 's', 'ss', 'a', 'a', 'sa', 'aa' ];
var DIFFICULTY_DIE = [ '', 'f', 'ff', 't', 't', 't', 'tt', 'ft' ];
var PROFICIENCY_DIE = [ '', 's', 's', 'ss', 'ss', 'a', 'sa', 'sa',
                        'sa', 'aa', 'aa', 'T' ];
var CHALLENGE_DIE = [ '', 'f', 'f', 'ff', 'ff', 't', 't', 'ft',
                      'ft', 'tt', 'tt', 'D' ];
var FORCE_DIE = [ 'l', 'l', 'l', 'l', 'l', 'l', 'll', 'k',
                  'k', 'kk', 'kk', 'kk' ];

var DiceRoller = {

  dice: {
    boost: BOOST_DIE,
    setback: SETBACK_DIE,
    ability: ABILITY_DIE,
    difficulty: DIFFICULTY_DIE,
    proficiency: PROFICIENCY_DIE,
    challenge: CHALLENGE_DIE,
    force: FORCE_DIE
  },

  dice_img: {
    boost:       'img/dice-boost.svg',
    setback:     'img/dice-setback.svg',
    ability:     'img/dice-ability.svg',
    difficulty:  'img/dice-difficulty.svg',
    proficiency: 'img/dice-proficiency.svg',
    challenge:   'img/dice-challenge.svg',
    force:       'img/dice-force.svg'
  },

  result_img: {
    s: 'img/result-s.svg',
    a: 'img/result-a.svg',
    T: 'img/result-T.svg',
    f: 'img/result-f.svg',
    t: 'img/result-t.svg',
    D: 'img/result-D.svg',
    l: 'img/result-l.svg',
    k: 'img/result-k.svg',
  },

  pool: [],

  Selectors: {
    dice: '#dice',
    pool: '#pool',
    result: '#result',
    rollbutton: '#rollbutton',
    clearbutton: '#clearbutton'
  },

  // output an image for the die symbol
  _addPrettyResult: function(node, symbol) {
    var src = this.result_img[symbol];
    if (src) {
      var img = document.createElement('img');
      img.src = src;
      img.height = 20;
      node.appendChild(img);
    }
  },

  // output an image for the die.
  _addPrettyDie: function(node, die) {
    var src = this.dice_img[die];
    if (src) {
      var img = document.createElement('img');
      img.src = src;
      img.height = 30;
      node.appendChild(img);
    }
  },

  init: function() {
    this.setupDice();
    this.setupUI();
  },

  clearDicePool: function() {
    var resultElement = document.querySelector(this.Selectors.result);
    resultElement.innerHTML = '';
    console.log('before', this.pool.length);
    this.pool = [];
    console.log('after', this.pool.length);
    var poolElement = document.querySelector(this.Selectors.pool);
    while(poolElement.firstChild) {
      poolElement.removeChild(poolElement.firstChild);
    }
  },

  prettyResult: function(element, result) {
    // clear result
    while(element.firstChild) {
      element.removeChild(element.firstChild);
    }
    var first = true;
    result.forEach((e) => {
      if(!first) {
        element.appendChild(document.createTextNode('/'));
      }
      for(var i = 0; i < e.length; i++) {
        this._addPrettyResult(element, e.charAt(i));
      }
      first = false;
    });
  },

  rollDicePool: function() {
    var resultElement = document.querySelector(this.Selectors.result);
    var result = [];
    this.pool.forEach((die) => {
      result.push(this.rollDie(die));
    });
    this.prettyResult(resultElement, result);
  },

  rollDie: function(dieName) {
    var die = this.dice[dieName];
    // XXX shall we use window.crypto.getRandomValues() ?
    var idx = Math.floor(Math.random() * die.length);
    return die[idx];
  },

  setupUI: function() {
    var button = document.querySelector(this.Selectors.rollbutton);
    button.onclick = this.rollDicePool.bind(this);
    button = document.querySelector(this.Selectors.clearbutton);
    button.onclick = this.clearDicePool.bind(this);
  },

  setupDice: function() {
    var element = document.querySelector(this.Selectors.dice);
    var newElement;

    Object.keys(this.dice).forEach((k) => {
      newElement = document.createElement('div');
      newElement.dataset.die = k;
      newElement.id = 'die-' + k;

      this._addPrettyDie(newElement, k);

      var p = document.createElement('span');
      newElement.appendChild(p);
      p.appendChild(document.createTextNode(k));
      var b = document.createElement('button');
      b.onclick = this.addToPool.bind(this, k)
      b.appendChild(document.createTextNode('+'));
      newElement.appendChild(b);

      element.appendChild(newElement);
    });
  },

  addToPool: function(die) {
    this.pool.push(die);
    this.addToPoolUI(die);
  },

  removeFromPool: function(die, div) {
    var parent = div.parentNode;
    parent.removeChild(div);
    var idx = this.pool.indexOf(die);
    this.pool.splice(idx, 1);
  },

  addToPoolUI: function(die) {
    var element = document.querySelector(this.Selectors.pool);
    var newElement;

    var div = document.createElement('div');
    div.dataset.die = die;

    this._addPrettyDie(div, die);

    var p = document.createElement('span');
    div.appendChild(p);
    p.appendChild(document.createTextNode(die));
    var b = document.createElement('button');
    b.onclick = this.removeFromPool.bind(this, die, div)
    b.appendChild(document.createTextNode('-'));
    div.appendChild(b);

    element.appendChild(div);
  },
};

DiceRoller.init();

<commit_msg>Try to keep the dice ordered. And grouped.<commit_after>

// Results
//  s: success
//  a: advantage
//  T: triumph
//  f: failure
//  t: threat
//  D: despair
//  l: light side F
//  k: dark side F

var BOOST_DIE = [ '', '', 's', 'sa', 'aa', 'a' ];
var SETBACK_DIE = [ '', '', 'f', 'f', 't', 't' ];
var ABILITY_DIE = [ '', 's', 's', 'ss', 'a', 'a', 'sa', 'aa' ];
var DIFFICULTY_DIE = [ '', 'f', 'ff', 't', 't', 't', 'tt', 'ft' ];
var PROFICIENCY_DIE = [ '', 's', 's', 'ss', 'ss', 'a', 'sa', 'sa',
                        'sa', 'aa', 'aa', 'T' ];
var CHALLENGE_DIE = [ '', 'f', 'f', 'ff', 'ff', 't', 't', 'ft',
                      'ft', 'tt', 'tt', 'D' ];
var FORCE_DIE = [ 'l', 'l', 'l', 'l', 'l', 'l', 'll', 'k',
                  'k', 'kk', 'kk', 'kk' ];

var DiceRoller = {

  // order for the dice.
  dice_order: [
    'boost', 'ability', 'proficiency',
    'setback', 'difficulty', 'challenge',
    'force'
  ],

  dice: {
    boost: BOOST_DIE,
    setback: SETBACK_DIE,
    ability: ABILITY_DIE,
    difficulty: DIFFICULTY_DIE,
    proficiency: PROFICIENCY_DIE,
    challenge: CHALLENGE_DIE,
    force: FORCE_DIE
  },

  dice_img: {
    boost:       'img/dice-boost.svg',
    setback:     'img/dice-setback.svg',
    ability:     'img/dice-ability.svg',
    difficulty:  'img/dice-difficulty.svg',
    proficiency: 'img/dice-proficiency.svg',
    challenge:   'img/dice-challenge.svg',
    force:       'img/dice-force.svg'
  },

  result_img: {
    s: 'img/result-s.svg',
    a: 'img/result-a.svg',
    T: 'img/result-T.svg',
    f: 'img/result-f.svg',
    t: 'img/result-t.svg',
    D: 'img/result-D.svg',
    l: 'img/result-l.svg',
    k: 'img/result-k.svg',
  },

  pool: {},

  Selectors: {
    dice: '#dice',
    pool: '#pool',
    result: '#result',
    rollbutton: '#rollbutton',
    clearbutton: '#clearbutton'
  },

  // output an image for the die symbol
  _addPrettyResult: function(node, symbol) {
    var src = this.result_img[symbol];
    if (src) {
      var img = document.createElement('img');
      img.src = src;
      img.height = 20;
      node.appendChild(img);
    }
  },

  // output an image for the die.
  _addPrettyDie: function(node, die) {
    var src = this.dice_img[die];
    if (src) {
      var img = document.createElement('img');
      img.src = src;
      img.height = 30;
      node.appendChild(img);
    }
  },

  init: function() {
    this.setupDice();
    this.setupUI();
  },

  clearDicePool: function() {
    var resultElement = document.querySelector(this.Selectors.result);
    resultElement.innerHTML = '';
    this.pool = {};
    var poolElement = document.querySelector(this.Selectors.pool);
    while(poolElement.firstChild) {
      poolElement.removeChild(poolElement.firstChild);
    }
  },

  prettyResult: function(element, result) {
    // clear result
    while(element.firstChild) {
      element.removeChild(element.firstChild);
    }
    var first = true;
    result.forEach((e) => {
      if(!first) {
        element.appendChild(document.createTextNode('/'));
      }
      for(var i = 0; i < e.length; i++) {
        this._addPrettyResult(element, e.charAt(i));
      }
      first = false;
    });
  },

  rollDicePool: function() {
    var resultElement = document.querySelector(this.Selectors.result);
    var result = [];
    Object.keys(this.pool).forEach((die) => {
      var count = this.pool[die];
      for(var i = 0; i < count; i++) {
        result.push(this.rollDie(die));
      }
    });
    this.prettyResult(resultElement, result);
  },

  rollDie: function(dieName) {
    var die = this.dice[dieName];
    // XXX shall we use window.crypto.getRandomValues() ?
    var idx = Math.floor(Math.random() * die.length);
    return die[idx];
  },

  setupUI: function() {
    var button = document.querySelector(this.Selectors.rollbutton);
    button.onclick = this.rollDicePool.bind(this);

    button = document.querySelector(this.Selectors.clearbutton);
    button.onclick = this.clearDicePool.bind(this);
  },

  setupDice: function() {
    var element = document.querySelector(this.Selectors.dice);
    var newElement;

    this.dice_order.forEach((k) => {
      newElement = document.createElement('div');
      newElement.dataset.die = k;
      newElement.id = 'die-' + k;

      this._addPrettyDie(newElement, k);

      var p = document.createElement('span');
      newElement.appendChild(p);
      p.appendChild(document.createTextNode(k));
      var b = document.createElement('button');
      b.onclick = this.addToPool.bind(this, k)
      b.appendChild(document.createTextNode('+'));
      newElement.appendChild(b);

      element.appendChild(newElement);
    });
  },

  addToPool: function(die) {
    if (this.pool[die] === undefined || Number.isNaN(this.pool[die])) {
      this.pool[die] = 1;
    } else {
      this.pool[die]++;
    }
    this._addToPoolUI(die);
  },

  removeFromPool: function(div) {
    var die = div.dataset.die;
    if (die) {
      if (div.dataset.count <= 1) {
        var parent = div.parentNode;
        parent.removeChild(div);
      } else {
        div.dataset.count--;
        this._setPooledDieCount(div);
      }
      if (this.pool[die] > 0) {
        this.pool[die]--;
      } else {
        console.error('this.pool inconsistent for ', die, this.pool[die]);
      }
    } else {
      console.error('inconsistent data: unkown die');
    }
  },

  _setPooledDieCount: function(node) {
    node.firstChild.textContent = node.dataset.count + 'x';
  },

  _addToPoolUI: function(die) {
    var element = document.querySelector(this.Selectors.pool);

    var div = element.querySelector('div[data-die=' + die);
    if (div) {
      div.dataset.count++;
      this._setPooledDieCount(div);
    } else {
      div = document.createElement('div');
      div.dataset.die = die;
      div.dataset.count = this.pool[die];
      var p = document.createElement('span');
      div.appendChild(p);
      this._setPooledDieCount(div);

      this._addPrettyDie(div, die);

      p = document.createElement('span');
      div.appendChild(p);
      p.appendChild(document.createTextNode(die));
      var b = document.createElement('button');
      b.onclick = this.removeFromPool.bind(this, div)
      b.appendChild(document.createTextNode('-'));
      div.appendChild(b);

      element.appendChild(div);
    }
  },
};

DiceRoller.init();

<|endoftext|>


<commit_before>// ==========================================================================
// Project:   Ember Handlebar Views
// Copyright: ©2011 Strobe Inc. and contributors.
// License:   Licensed under MIT license (see license.js)
// ==========================================================================
/*globals Handlebars */

require('ember-handlebars/ext');
require('ember-handlebars/views/bindable_span');
require('ember-handlebars/views/metamorph_view');

var get = Ember.get, getPath = Ember.getPath, set = Ember.set, fmt = Ember.String.fmt;

(function() {
  // Binds a property into the DOM. This will create a hook in DOM that the
  // KVO system will look for and upate if the property changes.
  var bind = function(property, options, preserveContext, shouldDisplay) {
    var data = options.data,
        fn = options.fn,
        inverse = options.inverse,
        view = data.view,
        ctx  = this;

    // Set up observers for observable objects
    if ('object' === typeof this) {
      // Create the view that will wrap the output of this template/property
      // and add it to the nearest view's childViews array.
      // See the documentation of Ember._BindableSpanView for more.
      var bindView = view.createChildView(Ember._BindableSpanView, {
        preserveContext: preserveContext,
        shouldDisplayFunc: shouldDisplay,
        displayTemplate: fn,
        inverseTemplate: inverse,
        property: property,
        previousContext: ctx,
        isEscaped: options.hash.escaped
      });

      view.appendChild(bindView);

      var observer, invoker;

      /** @private */
      observer = function(){
        // Double check since sometimes the view gets destroyed after this observer is already queued
        if (!get(bindView, 'isDestroyed')) { bindView.rerender(); }
      };

      /** @private */
      invoker = function() {
        Ember.run.once(observer);
      };

      // Observes the given property on the context and
      // tells the Ember._BindableSpan to re-render. If property
      // is an empty string, we are printing the current context
      // object ({{this}}) so updating it is not our responsibility.
      if (property !== '') {
        Ember.addObserver(ctx, property, invoker);
      }
    } else {
      // The object is not observable, so just render it out and
      // be done with it.
      data.buffer.push(getPath(this, property));
    }
  };

  /**
    `bind` can be used to display a value, then update that value if it
    changes. For example, if you wanted to print the `title` property of
    `content`:

        {{bind "content.title"}}

    This will return the `title` property as a string, then create a new
    observer at the specified path. If it changes, it will update the value in
    DOM. Note that if you need to support IE7 and IE8 you must modify the
    model objects properties using Ember.get() and Ember.set() for this to work as
    it relies on Ember's KVO system.  For all other browsers this will be handled
    for you automatically.

    @private
    @name Handlebars.helpers.bind
    @param {String} property Property to bind
    @param {Function} fn Context to provide for rendering
    @returns {String} HTML string
  */
  Ember.Handlebars.registerHelper('bind', function(property, fn) {
    ember_assert("You cannot pass more than one argument to the bind helper", arguments.length <= 2);

    var context = (fn.contexts && fn.contexts[0]) || this;

    return bind.call(context, property, fn, false, function(result) {
      return !Ember.none(result);
    });
  });

  /**
    Use the `boundIf` helper to create a conditional that re-evaluates
    whenever the bound value changes.

        {{#boundIf "content.shouldDisplayTitle"}}
          {{content.title}}
        {{/boundIf}}

    @private
    @name Handlebars.helpers.boundIf
    @param {String} property Property to bind
    @param {Function} fn Context to provide for rendering
    @returns {String} HTML string
  */
  Ember.Handlebars.registerHelper('boundIf', function(property, fn) {
    var context = (fn.contexts && fn.contexts[0]) || this;

    return bind.call(context, property, fn, true, function(result) {
      if (Ember.typeOf(result) === 'array') {
        return get(result, 'length') !== 0;
      } else {
        return !!result;
      }
    } );
  });
})();

/**
  @name Handlebars.helpers.with
  @param {Function} context
  @param {Hash} options
  @returns {String} HTML string
*/
Ember.Handlebars.registerHelper('with', function(context, options) {
  ember_assert("You must pass exactly one argument to the with helper", arguments.length == 2);
  ember_assert("You must pass a block to the with helper", options.fn && options.fn !== Handlebars.VM.noop);

  return Ember.Handlebars.helpers.bind.call(options.contexts[0], context, options);
});

/**
  @name Handlebars.helpers.if
  @param {Function} context
  @param {Hash} options
  @returns {String} HTML string
*/
Ember.Handlebars.registerHelper('if', function(context, options) {
  ember_assert("You must pass exactly one argument to the if helper", arguments.length == 2);
  ember_assert("You must pass a block to the if helper", options.fn && options.fn !== Handlebars.VM.noop);

  return Ember.Handlebars.helpers.boundIf.call(options.contexts[0], context, options);
});

/**
  @name Handlebars.helpers.unless
  @param {Function} context
  @param {Hash} options
  @returns {String} HTML string
*/
Ember.Handlebars.registerHelper('unless', function(context, options) {
  ember_assert("You must pass exactly one argument to the unless helper", arguments.length == 2);
  ember_assert("You must pass a block to the unless helper", options.fn && options.fn !== Handlebars.VM.noop);

  var fn = options.fn, inverse = options.inverse;

  options.fn = inverse;
  options.inverse = fn;

  return Ember.Handlebars.helpers.boundIf.call(options.contexts[0], context, options);
});

/**
  `bindAttr` allows you to create a binding between DOM element attributes and
  Ember objects. For example:

      <img {{bindAttr src="imageUrl" alt="imageTitle"}}>

  @name Handlebars.helpers.bindAttr
  @param {Hash} options
  @returns {String} HTML string
*/
Ember.Handlebars.registerHelper('bindAttr', function(options) {

  var attrs = options.hash;

  ember_assert("You must specify at least one hash argument to bindAttr", !!Ember.keys(attrs).length);

  var view = options.data.view;
  var ret = [];
  var ctx = this;

  // Generate a unique id for this element. This will be added as a
  // data attribute to the element so it can be looked up when
  // the bound property changes.
  var dataId = ++jQuery.uuid;

  // Handle classes differently, as we can bind multiple classes
  var classBindings = attrs['class'];
  if (classBindings !== null && classBindings !== undefined) {
    var classResults = Ember.Handlebars.bindClasses(this, classBindings, view, dataId);
    ret.push('class="' + classResults.join(' ') + '"');
    delete attrs['class'];
  }

  var attrKeys = Ember.keys(attrs);

  // For each attribute passed, create an observer and emit the
  // current value of the property as an attribute.
  attrKeys.forEach(function(attr) {
    var property = attrs[attr];

    ember_assert(fmt("You must provide a String for a bound attribute, not %@", [property]), typeof property === 'string');

    var value = getPath(ctx, property);

    ember_assert(fmt("Attributes must be numbers, strings or booleans, not %@", [value]), value == null || typeof value === 'number' || typeof value === 'string' || typeof value === 'boolean');

    var observer, invoker;

    /** @private */
    observer = function observer() {
      var result = getPath(ctx, property);

      ember_assert(fmt("Attributes must be numbers, strings or booleans, not %@", [result]), result == null || typeof result === 'number' || typeof result === 'string' || typeof result === 'boolean');

      var elem = view.$("[data-bindAttr-" + dataId + "='" + dataId + "']");

      // If we aren't able to find the element, it means the element
      // to which we were bound has been removed from the view.
      // In that case, we can assume the template has been re-rendered
      // and we need to clean up the observer.
      if (elem.length === 0) {
        Ember.removeObserver(ctx, property, invoker);
        return;
      }

      Ember.View.applyAttributeBindings(elem, attr, result);
    };

    /** @private */
    invoker = function() {
      Ember.run.once(observer);
    };

    // Add an observer to the view for when the property changes.
    // When the observer fires, find the element using the
    // unique data id and update the attribute to the new value.
    Ember.addObserver(ctx, property, invoker);

    var type = typeof value;

    if ((type === 'string' || (type === 'number' && !isNaN(value)))) {
      ret.push(attr + '="' + value + '"');
    } else if (value && type === 'boolean') {
      ret.push(attr + '="' + attr + '"');
    }
  }, this);

  // Add the unique identifier
  ret.push('data-bindAttr-' + dataId + '="' + dataId + '"');
  return new Ember.Handlebars.SafeString(ret.join(' '));
});

/**
  Helper that, given a space-separated string of property paths and a context,
  returns an array of class names. Calling this method also has the side
  effect of setting up observers at those property paths, such that if they
  change, the correct class name will be reapplied to the DOM element.

  For example, if you pass the string "fooBar", it will first look up the
  "fooBar" value of the context. If that value is YES, it will add the
  "foo-bar" class to the current element (i.e., the dasherized form of
  "fooBar"). If the value is a string, it will add that string as the class.
  Otherwise, it will not add any new class name.

  @param {Ember.Object} context
    The context from which to lookup properties

  @param {String} classBindings
    A string, space-separated, of class bindings to use

  @param {Ember.View} view
    The view in which observers should look for the element to update

  @param {Srting} bindAttrId
    Optional bindAttr id used to lookup elements

  @returns {Array} An array of class names to add
*/
Ember.Handlebars.bindClasses = function(context, classBindings, view, bindAttrId) {
  var ret = [], newClass, value, elem;

  // Helper method to retrieve the property from the context and
  // determine which class string to return, based on whether it is
  // a Boolean or not.
  var classStringForProperty = function(property) {
    var split = property.split(':'),
        property = split[0],
        className = split[1];

    var val = getPath(context, property);

    // If value is a Boolean and true, return the dasherized property
    // name.
    if (val === YES) {
      if (className) { return className; }

      // Normalize property path to be suitable for use
      // as a class name. For exaple, content.foo.barBaz
      // becomes bar-baz.
      var parts = property.split('.');
      return Ember.String.dasherize(parts[parts.length-1]);

    // If the value is not NO, undefined, or null, return the current
    // value of the property.
    } else if (val !== NO && val !== undefined && val !== null) {
      return val;

    // Nothing to display. Return null so that the old class is removed
    // but no new class is added.
    } else {
      return null;
    }
  };

  // For each property passed, loop through and setup
  // an observer.
  classBindings.split(' ').forEach(function(binding) {

    // Variable in which the old class value is saved. The observer function
    // closes over this variable, so it knows which string to remove when
    // the property changes.
    var oldClass;

    var observer, invoker;

    // Set up an observer on the context. If the property changes, toggle the
    // class name.
    /** @private */
    observer = function() {
      // Get the current value of the property
      newClass = classStringForProperty(binding);
      elem = bindAttrId ? view.$("[data-bindAttr-" + bindAttrId + "='" + bindAttrId + "']") : view.$();

      // If we can't find the element anymore, a parent template has been
      // re-rendered and we've been nuked. Remove the observer.
      if (elem.length === 0) {
        Ember.removeObserver(context, binding, invoker);
      } else {
        // If we had previously added a class to the element, remove it.
        if (oldClass) {
          elem.removeClass(oldClass);
        }

        // If necessary, add a new class. Make sure we keep track of it so
        // it can be removed in the future.
        if (newClass) {
          elem.addClass(newClass);
          oldClass = newClass;
        } else {
          oldClass = null;
        }
      }
    };

    /** @private */
    invoker = function() {
      Ember.run.once(observer);
    };

    property = binding.split(':')[0];
    Ember.addObserver(context, property, invoker);

    // We've already setup the observer; now we just need to figure out the
    // correct behavior right now on the first pass through.
    value = classStringForProperty(binding);

    if (value) {
      ret.push(value);

      // Make sure we save the current value so that it can be removed if the
      // observer fires.
      oldClass = value;
    }
  });

  return ret;
};

<commit_msg>Add note warning future travelers to abandon all hope, ye who enter here<commit_after>// ==========================================================================
// Project:   Ember Handlebar Views
// Copyright: ©2011 Strobe Inc. and contributors.
// License:   Licensed under MIT license (see license.js)
// ==========================================================================
/*globals Handlebars */

require('ember-handlebars/ext');
require('ember-handlebars/views/bindable_span');
require('ember-handlebars/views/metamorph_view');

var get = Ember.get, getPath = Ember.getPath, set = Ember.set, fmt = Ember.String.fmt;

(function() {
  // Binds a property into the DOM. This will create a hook in DOM that the
  // KVO system will look for and upate if the property changes.
  var bind = function(property, options, preserveContext, shouldDisplay) {
    var data = options.data,
        fn = options.fn,
        inverse = options.inverse,
        view = data.view,
        ctx  = this;

    // Set up observers for observable objects
    if ('object' === typeof this) {
      // Create the view that will wrap the output of this template/property
      // and add it to the nearest view's childViews array.
      // See the documentation of Ember._BindableSpanView for more.
      var bindView = view.createChildView(Ember._BindableSpanView, {
        preserveContext: preserveContext,
        shouldDisplayFunc: shouldDisplay,
        displayTemplate: fn,
        inverseTemplate: inverse,
        property: property,
        previousContext: ctx,
        isEscaped: options.hash.escaped
      });

      view.appendChild(bindView);

      var observer, invoker;

      /** @private */
      observer = function(){
        // Double check since sometimes the view gets destroyed after this observer is already queued
        if (!get(bindView, 'isDestroyed')) { bindView.rerender(); }
      };

      /** @private */
      invoker = function() {
        Ember.run.once(observer);
      };

      // Observes the given property on the context and
      // tells the Ember._BindableSpan to re-render. If property
      // is an empty string, we are printing the current context
      // object ({{this}}) so updating it is not our responsibility.
      if (property !== '') {
        Ember.addObserver(ctx, property, invoker);
      }
    } else {
      // The object is not observable, so just render it out and
      // be done with it.
      data.buffer.push(getPath(this, property));
    }
  };

  /**
    `bind` can be used to display a value, then update that value if it
    changes. For example, if you wanted to print the `title` property of
    `content`:

        {{bind "content.title"}}

    This will return the `title` property as a string, then create a new
    observer at the specified path. If it changes, it will update the value in
    DOM. Note that if you need to support IE7 and IE8 you must modify the
    model objects properties using Ember.get() and Ember.set() for this to work as
    it relies on Ember's KVO system.  For all other browsers this will be handled
    for you automatically.

    @private
    @name Handlebars.helpers.bind
    @param {String} property Property to bind
    @param {Function} fn Context to provide for rendering
    @returns {String} HTML string
  */
  Ember.Handlebars.registerHelper('bind', function(property, fn) {
    ember_assert("You cannot pass more than one argument to the bind helper", arguments.length <= 2);

    var context = (fn.contexts && fn.contexts[0]) || this;

    return bind.call(context, property, fn, false, function(result) {
      return !Ember.none(result);
    });
  });

  /**
    Use the `boundIf` helper to create a conditional that re-evaluates
    whenever the bound value changes.

        {{#boundIf "content.shouldDisplayTitle"}}
          {{content.title}}
        {{/boundIf}}

    @private
    @name Handlebars.helpers.boundIf
    @param {String} property Property to bind
    @param {Function} fn Context to provide for rendering
    @returns {String} HTML string
  */
  Ember.Handlebars.registerHelper('boundIf', function(property, fn) {
    var context = (fn.contexts && fn.contexts[0]) || this;

    return bind.call(context, property, fn, true, function(result) {
      if (Ember.typeOf(result) === 'array') {
        return get(result, 'length') !== 0;
      } else {
        return !!result;
      }
    } );
  });
})();

/**
  @name Handlebars.helpers.with
  @param {Function} context
  @param {Hash} options
  @returns {String} HTML string
*/
Ember.Handlebars.registerHelper('with', function(context, options) {
  ember_assert("You must pass exactly one argument to the with helper", arguments.length == 2);
  ember_assert("You must pass a block to the with helper", options.fn && options.fn !== Handlebars.VM.noop);

  return Ember.Handlebars.helpers.bind.call(options.contexts[0], context, options);
});

/**
  @name Handlebars.helpers.if
  @param {Function} context
  @param {Hash} options
  @returns {String} HTML string
*/
Ember.Handlebars.registerHelper('if', function(context, options) {
  ember_assert("You must pass exactly one argument to the if helper", arguments.length == 2);
  ember_assert("You must pass a block to the if helper", options.fn && options.fn !== Handlebars.VM.noop);

  return Ember.Handlebars.helpers.boundIf.call(options.contexts[0], context, options);
});

/**
  @name Handlebars.helpers.unless
  @param {Function} context
  @param {Hash} options
  @returns {String} HTML string
*/
Ember.Handlebars.registerHelper('unless', function(context, options) {
  ember_assert("You must pass exactly one argument to the unless helper", arguments.length == 2);
  ember_assert("You must pass a block to the unless helper", options.fn && options.fn !== Handlebars.VM.noop);

  var fn = options.fn, inverse = options.inverse;

  options.fn = inverse;
  options.inverse = fn;

  return Ember.Handlebars.helpers.boundIf.call(options.contexts[0], context, options);
});

/**
  `bindAttr` allows you to create a binding between DOM element attributes and
  Ember objects. For example:

      <img {{bindAttr src="imageUrl" alt="imageTitle"}}>

  @name Handlebars.helpers.bindAttr
  @param {Hash} options
  @returns {String} HTML string
*/
Ember.Handlebars.registerHelper('bindAttr', function(options) {

  var attrs = options.hash;

  ember_assert("You must specify at least one hash argument to bindAttr", !!Ember.keys(attrs).length);

  var view = options.data.view;
  var ret = [];
  var ctx = this;

  // Generate a unique id for this element. This will be added as a
  // data attribute to the element so it can be looked up when
  // the bound property changes.
  var dataId = ++jQuery.uuid;

  // Handle classes differently, as we can bind multiple classes
  var classBindings = attrs['class'];
  if (classBindings !== null && classBindings !== undefined) {
    var classResults = Ember.Handlebars.bindClasses(this, classBindings, view, dataId);
    ret.push('class="' + classResults.join(' ') + '"');
    delete attrs['class'];
  }

  var attrKeys = Ember.keys(attrs);

  // For each attribute passed, create an observer and emit the
  // current value of the property as an attribute.
  attrKeys.forEach(function(attr) {
    var property = attrs[attr];

    ember_assert(fmt("You must provide a String for a bound attribute, not %@", [property]), typeof property === 'string');

    var value = getPath(ctx, property);

    ember_assert(fmt("Attributes must be numbers, strings or booleans, not %@", [value]), value == null || typeof value === 'number' || typeof value === 'string' || typeof value === 'boolean');

    var observer, invoker;

    /** @private */
    observer = function observer() {
      var result = getPath(ctx, property);

      ember_assert(fmt("Attributes must be numbers, strings or booleans, not %@", [result]), result == null || typeof result === 'number' || typeof result === 'string' || typeof result === 'boolean');

      var elem = view.$("[data-bindAttr-" + dataId + "='" + dataId + "']");

      // If we aren't able to find the element, it means the element
      // to which we were bound has been removed from the view.
      // In that case, we can assume the template has been re-rendered
      // and we need to clean up the observer.
      if (elem.length === 0) {
        Ember.removeObserver(ctx, property, invoker);
        return;
      }

      Ember.View.applyAttributeBindings(elem, attr, result);
    };

    /** @private */
    invoker = function() {
      Ember.run.once(observer);
    };

    // Add an observer to the view for when the property changes.
    // When the observer fires, find the element using the
    // unique data id and update the attribute to the new value.
    Ember.addObserver(ctx, property, invoker);

    // if this changes, also change the logic in ember-views/lib/views/view.js
    var type = typeof value;

    if ((type === 'string' || (type === 'number' && !isNaN(value)))) {
      ret.push(attr + '="' + value + '"');
    } else if (value && type === 'boolean') {
      ret.push(attr + '="' + attr + '"');
    }
  }, this);

  // Add the unique identifier
  ret.push('data-bindAttr-' + dataId + '="' + dataId + '"');
  return new Ember.Handlebars.SafeString(ret.join(' '));
});

/**
  Helper that, given a space-separated string of property paths and a context,
  returns an array of class names. Calling this method also has the side
  effect of setting up observers at those property paths, such that if they
  change, the correct class name will be reapplied to the DOM element.

  For example, if you pass the string "fooBar", it will first look up the
  "fooBar" value of the context. If that value is YES, it will add the
  "foo-bar" class to the current element (i.e., the dasherized form of
  "fooBar"). If the value is a string, it will add that string as the class.
  Otherwise, it will not add any new class name.

  @param {Ember.Object} context
    The context from which to lookup properties

  @param {String} classBindings
    A string, space-separated, of class bindings to use

  @param {Ember.View} view
    The view in which observers should look for the element to update

  @param {Srting} bindAttrId
    Optional bindAttr id used to lookup elements

  @returns {Array} An array of class names to add
*/
Ember.Handlebars.bindClasses = function(context, classBindings, view, bindAttrId) {
  var ret = [], newClass, value, elem;

  // Helper method to retrieve the property from the context and
  // determine which class string to return, based on whether it is
  // a Boolean or not.
  var classStringForProperty = function(property) {
    var split = property.split(':'),
        property = split[0],
        className = split[1];

    var val = getPath(context, property);

    // If value is a Boolean and true, return the dasherized property
    // name.
    if (val === YES) {
      if (className) { return className; }

      // Normalize property path to be suitable for use
      // as a class name. For exaple, content.foo.barBaz
      // becomes bar-baz.
      var parts = property.split('.');
      return Ember.String.dasherize(parts[parts.length-1]);

    // If the value is not NO, undefined, or null, return the current
    // value of the property.
    } else if (val !== NO && val !== undefined && val !== null) {
      return val;

    // Nothing to display. Return null so that the old class is removed
    // but no new class is added.
    } else {
      return null;
    }
  };

  // For each property passed, loop through and setup
  // an observer.
  classBindings.split(' ').forEach(function(binding) {

    // Variable in which the old class value is saved. The observer function
    // closes over this variable, so it knows which string to remove when
    // the property changes.
    var oldClass;

    var observer, invoker;

    // Set up an observer on the context. If the property changes, toggle the
    // class name.
    /** @private */
    observer = function() {
      // Get the current value of the property
      newClass = classStringForProperty(binding);
      elem = bindAttrId ? view.$("[data-bindAttr-" + bindAttrId + "='" + bindAttrId + "']") : view.$();

      // If we can't find the element anymore, a parent template has been
      // re-rendered and we've been nuked. Remove the observer.
      if (elem.length === 0) {
        Ember.removeObserver(context, binding, invoker);
      } else {
        // If we had previously added a class to the element, remove it.
        if (oldClass) {
          elem.removeClass(oldClass);
        }

        // If necessary, add a new class. Make sure we keep track of it so
        // it can be removed in the future.
        if (newClass) {
          elem.addClass(newClass);
          oldClass = newClass;
        } else {
          oldClass = null;
        }
      }
    };

    /** @private */
    invoker = function() {
      Ember.run.once(observer);
    };

    property = binding.split(':')[0];
    Ember.addObserver(context, property, invoker);

    // We've already setup the observer; now we just need to figure out the
    // correct behavior right now on the first pass through.
    value = classStringForProperty(binding);

    if (value) {
      ret.push(value);

      // Make sure we save the current value so that it can be removed if the
      // observer fires.
      oldClass = value;
    }
  });

  return ret;
};

<|endoftext|>


<commit_before>/**
@module ember
@submodule ember-views
*/

var get = Ember.get, set = Ember.set;
var indexOf = Ember.ArrayPolyfills.indexOf;

var ClassSet = function() {
  this.seen = {};
  this.list = [];
};

ClassSet.prototype = {
  add: function(string) {
    if (string in this.seen) { return; }
    this.seen[string] = true;

    this.list.push(string);
  },

  toDOM: function() {
    return this.list.join(" ");
  }
};

/**
  `Ember.RenderBuffer` gathers information regarding the a view and generates the
  final representation. `Ember.RenderBuffer` will generate HTML which can be pushed
  to the DOM.

  @class RenderBuffer
  @namespace Ember
  @constructor
*/
Ember.RenderBuffer = function(tagName) {
  return new Ember._RenderBuffer(tagName);
};

Ember._RenderBuffer = function(tagName) {
  this.tagNames = [tagName || null];
  this.buffer = [];
};

Ember._RenderBuffer.prototype =
/** @scope Ember.RenderBuffer.prototype */ {

  // The root view's element
  _element: null,

  /**
    @private

    An internal set used to de-dupe class names when `addClass()` is
    used. After each call to `addClass()`, the `classes` property
    will be updated.

    @property elementClasses
    @type Array
    @default []
  */
  elementClasses: null,

  /**
    Array of class names which will be applied in the class attribute.

    You can use `setClasses()` to set this property directly. If you
    use `addClass()`, it will be maintained for you.

    @property classes
    @type Array
    @default []
  */
  classes: null,

  /**
    The id in of the element, to be applied in the id attribute.

    You should not set this property yourself, rather, you should use
    the `id()` method of `Ember.RenderBuffer`.

    @property elementId
    @type String
    @default null
  */
  elementId: null,

  /**
    A hash keyed on the name of the attribute and whose value will be
    applied to that attribute. For example, if you wanted to apply a
    `data-view="Foo.bar"` property to an element, you would set the
    elementAttributes hash to `{'data-view':'Foo.bar'}`.

    You should not maintain this hash yourself, rather, you should use
    the `attr()` method of `Ember.RenderBuffer`.

    @property elementAttributes
    @type Hash
    @default {}
  */
  elementAttributes: null,

  /**
    The tagname of the element an instance of `Ember.RenderBuffer` represents.

    Usually, this gets set as the first parameter to `Ember.RenderBuffer`. For
    example, if you wanted to create a `p` tag, then you would call

    ```javascript
    Ember.RenderBuffer('p')
    ```

    @property elementTag
    @type String
    @default null
  */
  elementTag: null,

  /**
    A hash keyed on the name of the style attribute and whose value will
    be applied to that attribute. For example, if you wanted to apply a
    `background-color:black;` style to an element, you would set the
    elementStyle hash to `{'background-color':'black'}`.

    You should not maintain this hash yourself, rather, you should use
    the `style()` method of `Ember.RenderBuffer`.

    @property elementStyle
    @type Hash
    @default {}
  */
  elementStyle: null,

  /**
    Nested `RenderBuffers` will set this to their parent `RenderBuffer`
    instance.

    @property parentBuffer
    @type Ember._RenderBuffer
  */
  parentBuffer: null,

  /**
    Adds a string of HTML to the `RenderBuffer`.

    @method push
    @param {String} string HTML to push into the buffer
    @chainable
  */
  push: function(string) {
    this.buffer.push(string);
    return this;
  },

  /**
    Adds a class to the buffer, which will be rendered to the class attribute.

    @method addClass
    @param {String} className Class name to add to the buffer
    @chainable
  */
  addClass: function(className) {
    // lazily create elementClasses
    var elementClasses = this.elementClasses = (this.elementClasses || new ClassSet());
    this.elementClasses.add(className);
    this.classes = this.elementClasses.list;

    return this;
  },

  setClasses: function(classNames) {
    this.classes = classNames;
  },

  /**
    Sets the elementID to be used for the element.

    @method id
    @param {String} id
    @chainable
  */
  id: function(id) {
    this.elementId = id;
    return this;
  },

  // duck type attribute functionality like jQuery so a render buffer
  // can be used like a jQuery object in attribute binding scenarios.

  /**
    Adds an attribute which will be rendered to the element.

    @method attr
    @param {String} name The name of the attribute
    @param {String} value The value to add to the attribute
    @chainable
    @return {Ember.RenderBuffer|String} this or the current attribute value
  */
  attr: function(name, value) {
    var attributes = this.elementAttributes = (this.elementAttributes || {});

    if (arguments.length === 1) {
      return attributes[name];
    } else {
      attributes[name] = value;
    }

    return this;
  },

  /**
    Remove an attribute from the list of attributes to render.

    @method removeAttr
    @param {String} name The name of the attribute
    @chainable
  */
  removeAttr: function(name) {
    var attributes = this.elementAttributes;
    if (attributes) { delete attributes[name]; }

    return this;
  },

  /**
    Adds a style to the style attribute which will be rendered to the element.

    @method style
    @param {String} name Name of the style
    @param {String} value
    @chainable
  */
  style: function(name, value) {
    var style = this.elementStyle = (this.elementStyle || {});

    this.elementStyle[name] = value;
    return this;
  },

  begin: function(tagName) {
    this.tagNames.push(tagName || null);
    return this;
  },

  pushOpeningTag: function() {
    var tagName = this.currentTagName();
    if (!tagName) { return; }

    if (!this._element && this.buffer.length === 0) {
      this._element = this.generateElement();
      return;
    }

    var buffer = this.buffer,
        id = this.elementId,
        classes = this.classes,
        attrs = this.elementAttributes,
        style = this.elementStyle,
        prop;

    buffer.push('<' + tagName);

    if (id) {
      buffer.push(' id="' + this._escapeAttribute(id) + '"');
      this.elementId = null;
    }
    if (classes) {
      buffer.push(' class="' + this._escapeAttribute(classes.join(' ')) + '"');
      this.classes = null;
    }

    if (style) {
      buffer.push(' style="');

      for (prop in style) {
        if (style.hasOwnProperty(prop)) {
          buffer.push(prop + ':' + this._escapeAttribute(style[prop]) + ';');
        }
      }

      buffer.push('"');

      this.elementStyle = null;
    }

    if (attrs) {
      for (prop in attrs) {
        if (attrs.hasOwnProperty(prop)) {
          buffer.push(' ' + prop + '="' + this._escapeAttribute(attrs[prop]) + '"');
        }
      }

      this.elementAttributes = null;
    }

    buffer.push('>');
  },

  pushClosingTag: function() {
    var tagName = this.tagNames.pop();
    if (tagName) { this.buffer.push('</' + tagName + '>'); }
  },

  currentTagName: function() {
    return this.tagNames[this.tagNames.length-1];
  },

  generateElement: function() {
    var tagName = this.tagNames.pop(), // pop since we don't need to close
        element = document.createElement(tagName),
        $element = Ember.$(element),
        id = this.elementId,
        classes = this.classes,
        attrs = this.elementAttributes,
        style = this.elementStyle,
        styleBuffer = '', prop;

    if (id) {
      $element.attr('id', id);
      this.elementId = null;
    }
    if (classes) {
      $element.attr('class', classes.join(' '));
      this.classes = null;
    }

    if (style) {
      for (prop in style) {
        if (style.hasOwnProperty(prop)) {
          styleBuffer += (prop + ':' + style[prop] + ';');
        }
      }

      $element.attr('style', styleBuffer);

      this.elementStyle = null;
    }

    if (attrs) {
      for (prop in attrs) {
        if (attrs.hasOwnProperty(prop)) {
          $element.attr(prop, attrs[prop]);
        }
      }

      this.elementAttributes = null;
    }

    return element;
  },

  /**
    @method element
    @return {DOMElement} The element corresponding to the generated HTML
      of this buffer
  */
  element: function() {
    var element = this._element,
        html = this.innerString();

    if (!Ember.$.support.htmlSerialize) { // work around IE zero-scope bug by inserting a script tag
      html = '' + html;
    }

    element.innerHTML = html;

    if (!Ember.$.support.htmlSerialize) {
      // This code is copied from Metamorph
      var shyElement = element.firstChild;
      while (shyElement.nodeType === 1 && !shyElement.nodeName) {
        shyElement = shyElement.firstChild;
      }
      if (shyElement.nodeType === 3 && shyElement.nodeValue.charAt(0) === "\u00AD") {
        shyElement.nodeValue = shyElement.nodeValue.slice(1);
      }
    }

    return element;
  },

  /**
    Generates the HTML content for this buffer.

    @method string
    @return {String} The generated HTML
  */
  string: function() {
    if (this._element) {
      return this.element().outerHTML;
    } else {
      return this.innerString();
    }
  },

  innerString: function() {
    return this.buffer.join('');
  },

  _escapeAttribute: function(value) {
    // Stolen shamelessly from Handlebars

    var escape = {
      "<": "<",
      ">": ">",
      '"': """,
      "'": "'",
      "`": "`"
    };

    var badChars = /&(?!\w+;)|[<>"'`]/g;
    var possible = /[&<>"'`]/;

    var escapeChar = function(chr) {
      return escape[chr] || "&";
    };

    var string = value.toString();

    if(!possible.test(string)) { return string; }
    return string.replace(badChars, escapeChar);
  }

};
<commit_msg>Handle more Metamorph special cases for old IE<commit_after>/**
@module ember
@submodule ember-views
*/

var get = Ember.get, set = Ember.set;
var indexOf = Ember.ArrayPolyfills.indexOf;

/*** BEGIN METAMORPH HELPERS ***/

// Internet Explorer prior to 9 does not allow setting innerHTML if the first element
// is a "zero-scope" element. This problem can be worked around by making
// the first node an invisible text node. We, like Modernizr, use
var needsShy = (function(){
  var testEl = document.createElement('div');
  testEl.innerHTML = "

";
  testEl.firstChild.innerHTML = "";
  return testEl.firstChild.innerHTML === '';
})();

// IE 8 (and likely earlier) likes to move whitespace preceeding
// a script tag to appear after it. This means that we can
// accidentally remove whitespace when updating a morph.
var movesWhitespace = (function() {
  var testEl = document.createElement('div');
  testEl.innerHTML = "Test: Value";
  return testEl.childNodes[0].nodeValue === 'Test:' &&
          testEl.childNodes[2].nodeValue === ' Value';
})();

// Use this to find children by ID instead of using jQuery
var findChildById = function(element, id) {
  if (element.getAttribute('id') === id) { return element; }

  var len = element.childNodes.length, idx, node, found;
  for (idx=0; idx<len; idx++) {
    node = element.childNodes[idx];
    found = node.nodeType === 1 && findChildById(node, id);
    if (found) { return found; }
  }
};

var setInnerHTML = function(element, html) {
  if (needsShy) {
    html = '' + html;
  }

  var matches = [];
  if (movesWhitespace) {
    // Right now we only check for script tags with ids with the
    // goal of targeting morphs.
    html = html.replace(/(\s+)(


<commit_before>function getCidade(el){
	try{
		var cidade = $(el).val();
		var raiz = location.origin;
		$.ajax({
			type     : "GET",
			dataType : "json",
			url      : raiz+"/OfertaAki/ajax/getCidade.php",
			data     : { q : cidade},
			async    : true,
			success  : function (resp){
				var retorno = "
";
				for(row in resp){
					retorno += "
"
						+resp[row].nome_cid+" - "+resp[row].sigla_est+"
";
				}
				retorno += "
";
				$("#returnCidade").empty().append(retorno);
			}
		});
	}catch($e){
		alert('Erro na getCidade : '+$e);
	}
}
function getCidade2(el){
	try{
		var cidade = $(el).val();
		var raiz = location.origin;
		$.ajax({
			type     : "GET",
			dataType : "json",
			url      : raiz+"/OfertaAki/ajax/getCidade.php",
			data     : { q : cidade},
			async    : true,
			success  : function (resp){
				var retorno = "
";
				for(row in resp){
					retorno += "
"+
					resp[row].nome_cid+" - "+resp[row].sigla_est+"
";
				}
				retorno += "
";
				$("#returnCidade").empty().append(retorno);
			}
		});
	}catch($e){
		alert('Erro na getCidade2 : '+$e);
	}
}
function setReturnCidade(){
	setTimeout('$("#returnCidade").empty();', 3000);
}
function setCidade(id_cid){
	window.location = '/OfertaAki/config/connection/loginUsuario.php?id_cid='+id_cid;
}
function setCidade2(id_cid, nome_cid, sigla_est){
	$('#id_cid_com2').val(nome_cid+' - '+sigla_est);
	$('#id_cid_com').val(id_cid);
}
function opcoesComerciante(){
	var raiz = location.origin+'/OfertaAki/ajax/opcoesComerciante.html #load';
	$(".content-home > .row").load(raiz);
}
function logarComerciante(){
	var raiz = location.origin+'/OfertaAki/ajax/logarComerciante.html #load';
	$(".content-home > .row").load(raiz);
}
function cadastroComerciante(){
	var raiz = location.origin+'/OfertaAki/ajax/cadastroComerciante.html #load';
	$(".content-home > .row").load(raiz);
}
function indexGeral(){
	var raiz = location.origin+'/OfertaAki/ajax/indexGeral.html #load';
	$(".content-home > .row").load(raiz);
}
function verificaComerciante(email_com){
	try{
		var raiz = location.origin;
		$.ajax({
			type     : "GET",
			dataType : "json",
			url      : raiz+"/OfertaAki/ajax/verificaComerciante.php",
			data     : { email_com : email_com},
			async    : true,
			success  : function(resp){
				if(resp.verificaComerciante == 'cadastrado'){
					alert(true);
					return true;
				}else{
					alert(false);
					return false;
				}
			}
		});
	}catch($e){
		alert('Erro na verificaComerciante : '+$e);
	}
}
function validaCadastroComerciante(){
	try{
		if($('#cnpj_com').val()==''){
			alert("Informe seu CNPJ!");
			$('#cnpj_com').val("");
			$('#cnpj_com').focus();
			return false;
		}else if($('#email_com').val()==''){
			alert("Informe seu EMAIL!");
			$('#email_com').val("");
			$('#email_com').focus();
			return false;
		}else if($('#senha_com').val()==''){
			alert("Informe sua SENHA!");
			$('#senha_com').val("");
			$('#senha_com').focus();
			return false;
		}else if($('#senha_com2').val()!=
			$('#senha_com').val()){
			alert("Senhas informadas são invalidas!");
			$('#senha_com2').val("");
			$('#senha_com2').focus();
			return false;
		}else if($('#id_cid_com').val()==''){
			alert("Informe sua CIDADE!");
			$('#id_cid_com2').val("");
			$('#id_cid_com2').focus();
			return false;
		}else if($('#razaoSocial_com').val()==''){
			alert("Informe sua RAZÃO SOCIAL!");
			$('#razaoSocial_com').val("");
			$('#razaoSocial_com').focus();
			return false;
		}else if($('#responsavel_com').val()==''){
			alert("Informe o RESPONSAVEL pela Empresa!");
			$('#responsavel_com').val("");
			$('#responsavel_com').focus();
			return false;
		}else if($('#bairro_com').val()==''){
			alert("Informe seu BAIRRO!");
			$('#bairro_com').val("");
			$('#bairro_com').focus();
			return false;
		}else if($('#endereco_com').val()==''){
			alert("Informe seu ENDEREÇO!");
			$('#endereco_com').val("");
			$('#endereco_com').focus();
			return false;
		}else{
			var teste = verificaComerciante($('#email_com').val());
			if(teste){
				alert("EMAIL '"+$('#email_com').val()+"' já cadastrado, favor informe outro EMAIL!");
				$('#email_com').val("");
				$('#email_com').focus();
				return false;
			}
		}
	}catch($e){
		alert('Erro na validação do cadastro!');
	}
}

$(document).ready(function(){
	indexGeral();
});
<commit_msg>update 30/05/2016<commit_after>//VARIAVEIS GLOBAIS
	var retornoVerificaComerciante = null;
//FIM VARIAVEIS GLOBAIS

function getCidade(el){
	try{
		var cidade = $(el).val();
		var raiz = location.origin;
		$.ajax({
			type     : "GET",
			dataType : "json",
			url      : raiz+"/OfertaAki/ajax/getCidade.php",
			data     : { q : cidade},
			async    : true,
			success  : function (resp){
				var retorno = "
";
				for(row in resp){
					retorno += "
"
						+resp[row].nome_cid+" - "+resp[row].sigla_est+"
";
				}
				retorno += "
";
				$("#returnCidade").empty().append(retorno);
			}
		});
	}catch($e){
		alert('Erro na getCidade : '+$e);
	}
}
function getCidade2(el){
	try{
		var cidade = $(el).val();
		var raiz = location.origin;
		$.ajax({
			type     : "GET",
			dataType : "json",
			url      : raiz+"/OfertaAki/ajax/getCidade.php",
			data     : { q : cidade},
			async    : true,
			success  : function (resp){
				var retorno = "
";
				for(row in resp){
					retorno += "
"+
					resp[row].nome_cid+" - "+resp[row].sigla_est+"
";
				}
				retorno += "
";
				$("#returnCidade").empty().append(retorno);
			}
		});
	}catch($e){
		alert('Erro na getCidade2 : '+$e);
	}
}
function setReturnCidade(){
	setTimeout('$("#returnCidade").empty();', 3000);
}
function setCidade(id_cid){
	window.location = '/OfertaAki/config/connection/loginUsuario.php?id_cid='+id_cid;
}
function setCidade2(id_cid, nome_cid, sigla_est){
	$('#id_cid_com2').val(nome_cid+' - '+sigla_est);
	$('#id_cid_com').val(id_cid);
}
function opcoesComerciante(){
	var raiz = location.origin+'/OfertaAki/ajax/opcoesComerciante.html #load';
	$(".content-home > .row").load(raiz);
}
function logarComerciante(){
	var raiz = location.origin+'/OfertaAki/ajax/logarComerciante.html #load';
	$(".content-home > .row").load(raiz);
}
function cadastroComerciante(){
	var raiz = location.origin+'/OfertaAki/ajax/cadastroComerciante.html #load';
	$(".content-home > .row").load(raiz);
}
function indexGeral(){
	var raiz = location.origin+'/OfertaAki/ajax/indexGeral.html #load';
	$(".content-home > .row").load(raiz);
}
function verificaComerciante(email_com){
	try{
		var raiz = location.origin;
		$.ajax({
			type     : "GET",
			dataType : "json",
			url      : raiz+"/OfertaAki/ajax/verificaComerciante.php",
			data     : { email_com : email_com},
			async    : true,
			success  : function(resp){
				if(resp.verificaComerciante == 'cadastrado'){
					retornoVerificaComerciante = true;
				}else{
					retornoVerificaComerciante = false;
				}
			}
		});
	}catch($e){
		alert('Erro na verificaComerciante : '+$e);
	}
}
function validaCadastroComerciante(){
	try{
		if($('#cnpj_com').val()==''){
			alert("Informe seu CNPJ!");
			$('#cnpj_com').val("");
			$('#cnpj_com').focus();
			return false;
		}else if($('#email_com').val()==''){
			alert("Informe seu EMAIL!");
			$('#email_com').val("");
			$('#email_com').focus();
			return false;
		}else if($('#senha_com').val()==''){
			alert("Informe sua SENHA!");
			$('#senha_com').val("");
			$('#senha_com').focus();
			return false;
		}else if($('#senha_com2').val()!=
			$('#senha_com').val()){
			alert("Senhas informadas são invalidas!");
			$('#senha_com2').val("");
			$('#senha_com2').focus();
			return false;
		}else if($('#id_cid_com').val()==''){
			alert("Informe sua CIDADE!");
			$('#id_cid_com2').val("");
			$('#id_cid_com2').focus();
			return false;
		}else if($('#razaoSocial_com').val()==''){
			alert("Informe sua RAZÃO SOCIAL!");
			$('#razaoSocial_com').val("");
			$('#razaoSocial_com').focus();
			return false;
		}else if($('#responsavel_com').val()==''){
			alert("Informe o RESPONSAVEL pela Empresa!");
			$('#responsavel_com').val("");
			$('#responsavel_com').focus();
			return false;
		}else if($('#bairro_com').val()==''){
			alert("Informe seu BAIRRO!");
			$('#bairro_com').val("");
			$('#bairro_com').focus();
			return false;
		}else if($('#endereco_com').val()==''){
			alert("Informe seu ENDEREÇO!");
			$('#endereco_com').val("");
			$('#endereco_com').focus();
			return false;
		}else{
			verificaComerciante($('#email_com').val());
			if(retornoVerificaComerciante){
				alert("EMAIL '"+$('#email_com').val()+"' já cadastrado, favor informe outro EMAIL!");
				$('#email_com').val("");
				$('#email_com').focus();
				retornoVerificaComerciante = null;
				return false;
			}
		}
	}catch($e){
		alert('Erro na validação do cadastro!');
	}
}

$(document).ready(function(){
	indexGeral();
});
<|endoftext|>


<commit_before>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        var moves = {
            u: [0,-1],
            d: [0,1],
            l: [-1,0],
            r: [1,0]
        };
        document.getElementById("paintbtn").onclick = paint;

        function shuffle(array) {
          var currentIndex = array.length, temporaryValue, randomIndex ;

          // While there remain elements to shuffle...
          while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
          }

          return array;
        }

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
        }

        function walk(start, stop, steps){
            var distX = stop.x - start.x;
            var distY = stop.y - start.y;

            var walkSteps = [];
            for(var i = 0; i< Math.abs(distX); i++){
                if(distX < 0){
                    walkSteps.push(moves.l);
                } else {
                    walkSteps.push(moves.r);
                }
            }
            for(var i = 0; i< Math.abs(distY); i++){
                if(distY < 0){
                    walkSteps.push(moves.u);
                } else {
                    walkSteps.push(moves.d);
                }
            }

            //add a number of random pairs based on how big our grid is
            for(var i = 0; i< steps; i++){
                var rand = Math.floor(Math.random() * 2);
                if(rand < 1){
                    walkSteps.push(moves.u);
                    walkSteps.push(moves.d);
                } else{
                    walkSteps.push(moves.l);
                    walkSteps.push(moves.r);
                }
            }

            return shuffle(walkSteps);
        }

        function createRoom(x, y, pw, ph){
            var randw = Math.floor((Math.random() * ((pw/2) - 1 + 1) + 1) );
            var randh = Math.floor((Math.random() * ((ph/2) - 1 + 1) + 1) );
            //alert(randw + ", " + randh);

            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = widthSelect.options[widthSelect.selectedIndex].value;

            var heightSelect = document.getElementById("height");
            var pathHeight = heightSelect.options[heightSelect.selectedIndex].value;
            //alert(pathWidth + ", " + pathHeight);

            //create a start and endpoint based on the grid size
            var startpoint = {
               x: -1,
               y: -1
            }
           var endpoint = {
               x: -1,
               y: -1
            }
            startpoint.x = 0;
            startpoint.y = pathHeight - 1;

            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                for(var j = 0; j< pathHeight; j++){

                    c.beginPath();
                    //c.lineWidth = 1;
                    c.fillStyle = "#000000";
                    c.fillRect(i*30, j*30, 30, 30);
                    c.stroke();
               }
           }

           var randsteps = 2* Math.floor((pathWidth/2) * (pathHeight/2));

           //create a random path that we will walk
           var walkArray = walk(startpoint, endpoint, randsteps);

           //create two moving points representing where we are and where we were
           var movingpoint = {
               x: -1,
               y: -1
           };
           var movingpointold = {
               x: -1,
               y: -1
           };
           movingpoint.x = startpoint.x;
           movingpoint.y = startpoint.y;
           movingpointold.x = startpoint.x;
           movingpointold.y = startpoint.y;

           //follow the path and paint along the way
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }

               var movedirX = movingpoint.x - movingpointold.x;
               var movedirY = movingpoint.y - movingpointold.y;

               for(var l = 0; l< 30; l++){
                   c.fillStyle = "#FFFFFF";
                   c.fillRect(movingpointold.x*30 + l*movedirX + 9, movingpointold.y*30 + l*movedirY + 9, 6, 6);
               }

               c.fillStyle = "#FFFFFF";
               c.fillRect(movingpoint.x*30, movingpoint.y*30, 24, 24);

               movingpointold.x = movingpoint.x;
               movingpointold.y = movingpoint.y;
           }

            for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
                for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
                    var randRoom = Math.floor((Math.random() * 9));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        c.beginPath();
                        //c.lineWidth = 3;
                        c.fillStyle = "#FFFFFF";
                        c.fillRect(i*30 , j*30, roomDim[0]*30 - 6, roomDim[1]*30 - 6);
                        c.stroke();
                    }
                }
            }

            //paint the start and end points.
            c.fillStyle = "#33CC33";
            c.fillRect(startpoint.x*30, startpoint.y*30, 24, 24);
            c.fillStyle = "#CC0000";
            c.fillRect(endpoint.x*30, endpoint.y*30, 24 ,24);
        }
    }
})(window, document, undefined);
<commit_msg>Update script.js<commit_after>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        var moves = {
            u: [0,-1],
            d: [0,1],
            l: [-1,0],
            r: [1,0]
        };
        document.getElementById("paintbtn").onclick = paint;

        function shuffle(array) {
          var currentIndex = array.length, temporaryValue, randomIndex ;

          // While there remain elements to shuffle...
          while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
          }

          return array;
        }

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
        }

        function walk(start, stop, steps){
            var distX = stop.x - start.x;
            var distY = stop.y - start.y;

            var walkSteps = [];
            for(var i = 0; i< Math.abs(distX); i++){
                if(distX < 0){
                    walkSteps.push(moves.l);
                } else {
                    walkSteps.push(moves.r);
                }
            }
            for(var i = 0; i< Math.abs(distY); i++){
                if(distY < 0){
                    walkSteps.push(moves.u);
                } else {
                    walkSteps.push(moves.d);
                }
            }

            //add a number of random pairs based on how big our grid is
            for(var i = 0; i< steps; i++){
                var rand = Math.floor(Math.random() * 2);
                if(rand < 1){
                    walkSteps.push(moves.u);
                    walkSteps.push(moves.d);
                } else{
                    walkSteps.push(moves.l);
                    walkSteps.push(moves.r);
                }
            }

            return shuffle(walkSteps);
        }

        function createRoom(x, y, pw, ph){
            var randw = Math.floor((Math.random() * ((pw/2) - 1 + 1) + 1) );
            var randh = Math.floor((Math.random() * ((ph/2) - 1 + 1) + 1) );
            //alert(randw + ", " + randh);

            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = widthSelect.options[widthSelect.selectedIndex].value;

            var heightSelect = document.getElementById("height");
            var pathHeight = heightSelect.options[heightSelect.selectedIndex].value;
            //alert(pathWidth + ", " + pathHeight);

            //create a start and endpoint based on the grid size
            var startpoint = {
               x: -1,
               y: -1
            }
           var endpoint = {
               x: -1,
               y: -1
            }
            startpoint.x = 0;
            startpoint.y = pathHeight - 1;

            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                for(var j = 0; j< pathHeight; j++){

                    c.beginPath();
                    //c.lineWidth = 1;
                    c.fillStyle = "#000000";
                    c.fillRect(i*30, j*30, 30, 30);
                    c.stroke();
               }
           }

           var randsteps = 2* Math.floor((pathWidth/2) * (pathHeight/2));

           //create a random path that we will walk
           var walkArray = walk(startpoint, endpoint, randsteps);

           //create two moving points representing where we are and where we were
           var movingpoint = {
               x: -1,
               y: -1
           };
           var movingpointold = {
               x: -1,
               y: -1
           };
           movingpoint.x = startpoint.x;
           movingpoint.y = startpoint.y;
           movingpointold.x = startpoint.x;
           movingpointold.y = startpoint.y;

           //follow the path and paint along the way
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }

               var movedirX = movingpoint.x - movingpointold.x;
               var movedirY = movingpoint.y - movingpointold.y;

               for(var l = 0; l< 30; l++){
                   c.fillStyle = "#FFFFFF";
                   c.fillRect(movingpointold.x*30 + l*movedirX + 9, movingpointold.y*30 + l*movedirY + 9, 6, 6);
               }

               c.fillStyle = "#FFFFFF";
               c.fillRect(movingpoint.x*30, movingpoint.y*30, 24, 24);

               movingpointold.x = movingpoint.x;
               movingpointold.y = movingpoint.y;
           }

            for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
                for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
                    var randRoom = Math.floor((Math.random() * 4));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        c.beginPath();
                        //c.lineWidth = 3;
                        c.fillStyle = "#FFFFFF";
                        c.fillRect(i*30 , j*30, roomDim[0]*30 - 6, roomDim[1]*30 - 6);
                        c.stroke();
                    }
                }
            }

            //paint the start and end points.
            c.fillStyle = "#33CC33";
            c.fillRect(startpoint.x*30, startpoint.y*30, 24, 24);
            c.fillStyle = "#CC0000";
            c.fillRect(endpoint.x*30, endpoint.y*30, 24 ,24);
        }
    }
})(window, document, undefined);
<|endoftext|>


<commit_before>
  var width = 0;
  var height = 700;
  var border = 100;
  var nodesize = 40;

  var canvas = d3.select(".container").append("svg")
    .append("g")
    .attr("transform", "translate("+border+","+border+")");

  width = $("svg").parent().width();
  d3.select("svg")
    .attr("width", width)
    .attr("height", height);

  // FILTERS
  var filter = canvas.append("defs")
    .append("filter")
      .attr("id", "glowing")
      .attr("filterUnits", "userSpaceOnUse")
      .attr("width", "150%")
      .attr("height", "150%");

  filter.append("feGaussianBlur")
    .attr("in", "SourceAlpha")
    .attr("stdDeviation", 2)
    .attr("result", "blur");

  filter.append("feOffset")
    .attr("in", "blur")
    .attr("dx", 0)
    .attr("dy", 0)
    .attr("result", "offsetBlur");

  filter.append("feFlood")
    .attr("flood-color", "#0067ff")
    .attr("result", "color");
  filter.append("feComposite")
    .attr("in2", "offsetBlur")
    .attr("operator", "in");

  var feMerge = filter.append("feMerge");
  feMerge.append("feMergeNode");
  feMerge.append("feMergeNode")
    .attr("in", "SourceGraphic");

  // TREE DEFINITION
  var tree = d3.layout.tree()
    .nodeSize(32)
    .separation(function(a,b){return 1;})
    .size([height-2*border,width-2*border]);

  d3.json("https://gist.githubusercontent.com/nshadov/0e087575e131691d481d1b3b0cd6a2d6/raw/7376fd840c2c153cf76639062319e45094c1338d/skill-tree.json", function(data){

    //alert(JSON.stringify(data));

    var nodes = tree.nodes(data);
    var links = tree.links(nodes);

    // Unused
    var diagonal = d3.svg.diagonal()
      .projection(function(d){
        return [d.y, d.x];
      });

    var step_line = d3.svg.line().interpolate("step")
      .x(function(d){ return d.ly })
      .y(function(d){ return d.lx });

    function diagonal_step(d){
      var points = [
          {lx: d.source.x, ly: d.source.y},
          {lx: d.target.x, ly: d.target.y}
      ];
      return step_line(points);
    }

    // EDGES
    canvas.selectAll(".link")
      .data(links)
      .enter()
      .append("path")
        .attr("class", "link glowing")
        .attr("stroke", "black")
        .attr("fill", "none")
        .attr("d", diagonal_step);

    // NODES
    var node = canvas.selectAll(".node")
      .data(nodes)
      .enter()
      .append("g")
        .attr("class", "node")
        .attr("transform", function (d) {
          return "translate(" +d.y+ "," +d.x+ ")";
        });

    node.append("circle")
      .attr("r", nodesize/2)
      .attr("class", "glowing")
      .attr("fill", "blue");

    node.append("image")
      .attr("xlink:href", function(d) { return "img/icons/skill.png"; })
      .attr("class", "skill-img glowing")
      .attr("x", "-"+nodesize/2+"px")
      .attr("y", "-"+nodesize/2+"px")
      .attr("width", nodesize+"px")
      .attr("height", nodesize+"px");

    node.append("text")
      .text(function(d) {
        return d.name;
      });
  });
<commit_msg>better separation<commit_after>
  var width = 0;
  var height = 700;
  var border = 100;
  var nodesize = 40;

  var canvas = d3.select(".container").append("svg")
    .append("g")
    .attr("transform", "translate("+border+","+border+")");

  width = $("svg").parent().width();
  d3.select("svg")
    .attr("width", width)
    .attr("height", height);

  // FILTERS
  var filter = canvas.append("defs")
    .append("filter")
      .attr("id", "glowing")
      .attr("filterUnits", "userSpaceOnUse")
      .attr("width", "150%")
      .attr("height", "150%");

  filter.append("feGaussianBlur")
    .attr("in", "SourceAlpha")
    .attr("stdDeviation", 2)
    .attr("result", "blur");

  filter.append("feOffset")
    .attr("in", "blur")
    .attr("dx", 0)
    .attr("dy", 0)
    .attr("result", "offsetBlur");

  filter.append("feFlood")
    .attr("flood-color", "#0067ff")
    .attr("result", "color");
  filter.append("feComposite")
    .attr("in2", "offsetBlur")
    .attr("operator", "in");

  var feMerge = filter.append("feMerge");
  feMerge.append("feMergeNode");
  feMerge.append("feMergeNode")
    .attr("in", "SourceGraphic");

  // TREE DEFINITION
  var tree = d3.layout.tree()
    .nodeSize(nodesize)
    .separation(function(a,b){return 10;})
    .size([height-2*border,width-2*border]);

  d3.json("https://gist.githubusercontent.com/nshadov/0e087575e131691d481d1b3b0cd6a2d6/raw/7376fd840c2c153cf76639062319e45094c1338d/skill-tree.json", function(data){

    //alert(JSON.stringify(data));

    var nodes = tree.nodes(data);
    var links = tree.links(nodes);

    // Unused
    var diagonal = d3.svg.diagonal()
      .projection(function(d){
        return [d.y, d.x];
      });

    var step_line = d3.svg.line().interpolate("step")
      .x(function(d){ return d.ly })
      .y(function(d){ return d.lx });

    function diagonal_step(d){
      var points = [
          {lx: d.source.x, ly: d.source.y},
          {lx: d.target.x, ly: d.target.y}
      ];
      return step_line(points);
    }

    // EDGES
    canvas.selectAll(".link")
      .data(links)
      .enter()
      .append("path")
        .attr("class", "link glowing")
        .attr("stroke", "black")
        .attr("fill", "none")
        .attr("d", diagonal_step);

    // NODES
    var node = canvas.selectAll(".node")
      .data(nodes)
      .enter()
      .append("g")
        .attr("class", "node")
        .attr("transform", function (d) {
          return "translate(" +d.y+ "," +d.x+ ")";
        });

    node.append("circle")
      .attr("r", nodesize/2)
      .attr("class", "glowing")
      .attr("fill", "blue");

    node.append("image")
      .attr("xlink:href", function(d) { return "img/icons/skill.png"; })
      .attr("class", "skill-img glowing")
      .attr("x", "-"+nodesize/2+"px")
      .attr("y", "-"+nodesize/2+"px")
      .attr("width", nodesize+"px")
      .attr("height", nodesize+"px");

    node.append("text")
      .text(function(d) {
        return d.name;
      });
  });
<|endoftext|>


<commit_before>import {
  manifest,
  TAB_QUERY,
  ALL,
  EACH,
  CLOSE_PAGES,
  URLS,
  isExtensionURL,
} from '../util'

describe('The Extension page should', () => {
  beforeAll(ALL)
  beforeEach(EACH)

  afterEach(CLOSE_PAGES)

  it('have title ends with the extension name', async () => {
    await expect(page.title()).resolves.toMatch(manifest.name)
  })

  it('render correct number of windows & tabs', async () => {
    const wins = await page.$$('.shadow-2xl,.shadow-sm')
    expect(wins).toHaveLength(1)
    let tabs = await page.$$(TAB_QUERY)
    expect(tabs).toHaveLength(1)

    const N = 10
    await Promise.all(
      [...Array(10)].map(async () => {
        const newPage = await browser.newPage()
        await newPage.goto('https://google.com')
      })
    )
    tabs = await page.$$(TAB_QUERY)
    expect(tabs).toHaveLength(N + 1)
    const pages = await browser.pages()
    expect(pages).toHaveLength(N + 1)
    await page.bringToFront()
  })

  it('sort the tabs', async () => {
    const wins = await page.$$('.shadow-2xl,.shadow-sm')
    expect(wins).toHaveLength(1)
    let tabs = await page.$$(TAB_QUERY)
    expect(tabs).toHaveLength(1)
    await Promise.all(
      URLS.map(async (url) => {
        const newPage = await browser.newPage()
        await newPage.goto(url)
      })
    )
    await page.bringToFront()
    tabs = await page.$$eval(TAB_QUERY, (nodes) =>
      nodes.map((node) => node.querySelector('.text-xs').innerText)
    )
    expect(tabs).toHaveLength(URLS.length + 1)
    expect(tabs.filter((tab) => !isExtensionURL(tab))).toEqual([
      'https://www.google.com/',
      'https://github.com/',
      'https://www.google.com/',
    ])
    let pages = await browser.pages()
    let urls = await Promise.all(pages.map(async (page) => await page.url()))
    expect(urls.filter((x) => !isExtensionURL(x))).toEqual([
      'https://www.google.com/',
      'https://github.com/',
      'https://www.google.com/',
    ])
    expect(pages).toHaveLength(URLS.length + 1)
    const sortTabsButton = await page.$('button[title="Sort tabs"]')
    await sortTabsButton.click()
    await page.waitForTimeout(100)

    tabs = await page.$$eval(TAB_QUERY, (nodes) =>
      nodes.map((node) => node.querySelector('.text-xs').innerText)
    )
    expect(tabs).toHaveLength(URLS.length + 1)
    expect(tabs.filter((x) => !isExtensionURL(x))).toEqual([
      'https://github.com/',
      'https://www.google.com/',
      'https://www.google.com/',
    ])
  })

  it('close tab when click close button', async () => {
    await Promise.all(
      URLS.map(async (url) => {
        const newPage = await browser.newPage()
        await newPage.goto(url)
      })
    )
    await page.bringToFront()
    let tabs = await page.$$(TAB_QUERY)

    const pages = await browser.pages()
    expect(tabs.length).toBe(pages.length)
    let buttons = await tabs[tabs.length - 1].$$('button')
    expect(buttons).toHaveLength(3)
    await buttons[2].click()
    await page.waitForTimeout(100)

    tabs = await page.$$(TAB_QUERY)
    expect(tabs.length).toBe(pages.length - 1)

    buttons = await tabs[tabs.length - 1].$$('button')
    expect(buttons).toHaveLength(3)
    await buttons[2].click()
    await page.waitForTimeout(100)

    tabs = await page.$$(TAB_QUERY)
    expect(tabs.length).toBe(pages.length - 2)

    buttons = await tabs[tabs.length - 1].$$('button')
    expect(buttons).toHaveLength(3)
    await buttons[2].click()
    await page.waitForTimeout(100)

    tabs = await page.$$(TAB_QUERY)
    expect(tabs.length).toBe(pages.length - 3)
  })
})
<commit_msg>Set integration test timeout to 10 seconds<commit_after>import {
  manifest,
  TAB_QUERY,
  ALL,
  EACH,
  CLOSE_PAGES,
  URLS,
  isExtensionURL,
} from '../util'

describe('The Extension page should', () => {
  beforeAll(async () => {
    jest.setTimeout(10000)
    await ALL()
  })
  beforeEach(EACH)

  afterEach(CLOSE_PAGES)

  it('have title ends with the extension name', async () => {
    await expect(page.title()).resolves.toMatch(manifest.name)
  })

  it('render correct number of windows & tabs', async () => {
    const wins = await page.$$('.shadow-2xl,.shadow-sm')
    expect(wins).toHaveLength(1)
    let tabs = await page.$$(TAB_QUERY)
    expect(tabs).toHaveLength(1)

    const N = 10
    await Promise.all(
      [...Array(10)].map(async () => {
        const newPage = await browser.newPage()
        await newPage.goto('https://google.com')
      })
    )
    tabs = await page.$$(TAB_QUERY)
    expect(tabs).toHaveLength(N + 1)
    const pages = await browser.pages()
    expect(pages).toHaveLength(N + 1)
    await page.bringToFront()
  })

  it('sort the tabs', async () => {
    const wins = await page.$$('.shadow-2xl,.shadow-sm')
    expect(wins).toHaveLength(1)
    let tabs = await page.$$(TAB_QUERY)
    expect(tabs).toHaveLength(1)
    await Promise.all(
      URLS.map(async (url) => {
        const newPage = await browser.newPage()
        await newPage.goto(url)
      })
    )
    await page.bringToFront()
    tabs = await page.$$eval(TAB_QUERY, (nodes) =>
      nodes.map((node) => node.querySelector('.text-xs').innerText)
    )
    expect(tabs).toHaveLength(URLS.length + 1)
    expect(tabs.filter((tab) => !isExtensionURL(tab))).toEqual([
      'https://www.google.com/',
      'https://github.com/',
      'https://www.google.com/',
    ])
    let pages = await browser.pages()
    let urls = await Promise.all(pages.map(async (page) => await page.url()))
    expect(urls.filter((x) => !isExtensionURL(x))).toEqual([
      'https://www.google.com/',
      'https://github.com/',
      'https://www.google.com/',
    ])
    expect(pages).toHaveLength(URLS.length + 1)
    const sortTabsButton = await page.$('button[title="Sort tabs"]')
    await sortTabsButton.click()
    await page.waitForTimeout(100)

    tabs = await page.$$eval(TAB_QUERY, (nodes) =>
      nodes.map((node) => node.querySelector('.text-xs').innerText)
    )
    expect(tabs).toHaveLength(URLS.length + 1)
    expect(tabs.filter((x) => !isExtensionURL(x))).toEqual([
      'https://github.com/',
      'https://www.google.com/',
      'https://www.google.com/',
    ])
  })

  it('close tab when click close button', async () => {
    await Promise.all(
      URLS.map(async (url) => {
        const newPage = await browser.newPage()
        await newPage.goto(url)
      })
    )
    await page.bringToFront()
    let tabs = await page.$$(TAB_QUERY)

    const pages = await browser.pages()
    expect(tabs.length).toBe(pages.length)
    let buttons = await tabs[tabs.length - 1].$$('button')
    expect(buttons).toHaveLength(3)
    await buttons[2].click()
    await page.waitForTimeout(100)

    tabs = await page.$$(TAB_QUERY)
    expect(tabs.length).toBe(pages.length - 1)

    buttons = await tabs[tabs.length - 1].$$('button')
    expect(buttons).toHaveLength(3)
    await buttons[2].click()
    await page.waitForTimeout(100)

    tabs = await page.$$(TAB_QUERY)
    expect(tabs.length).toBe(pages.length - 2)

    buttons = await tabs[tabs.length - 1].$$('button')
    expect(buttons).toHaveLength(3)
    await buttons[2].click()
    await page.waitForTimeout(100)

    tabs = await page.$$(TAB_QUERY)
    expect(tabs.length).toBe(pages.length - 3)
  })
})
<|endoftext|>


<commit_before>// Foundation JavaScript
// Documentation can be found at: http://foundation.zurb.com/docs
$(document).foundation().ready(function() {

  var draftdata = {};

  $.getJSON( 'http://daigofuji.github.io/draft-war-visualization/json/data/mlb_draft_rounds.json' ).done(function( data ) {
    draftdata = data;
    drawchart("1999", data);
  });

  function drawchart(year, data) {
    var overallpickdata = [],
      wardata = [],
      namedata = [],
      players = [];

    // update title
    $('.js-title-year').text(year);
    // process data
    $.each( data, function( i, item ) {
      if(item.year === year) {
        console.log(item.name.replace(' (minors)',''), item.war);
        // list preparation
        players.push( "
" + item.pos + " " + item.name.replace(' (minors)','') + " (" + item.team + ", " + item.round + ")" + "" + item.war + "
" );
        // chart preparation
        overallpickdata.push(item.overall_pick);
        wardata.push(item.war ? item.war : 0);
        namedata.push(item.name.replace(' (minors)',''));
      }
    });

    //update the list
    $( "
", {
      "class": "my-new-list",
      html: players.join( "" )
    }).appendTo( ".js-player-list" );

    // chartist chart
    new Chartist.Line('.ct-chart', {
      labels: overallpickdata,
      series: [
        {
          name: 'WAR',
          data: wardata
        }
      ]
    },
    {showLine: false});

     // creating tool tips -- out of box
    var $chart = $('.ct-chart');
    var $toolTip = $chart
      .append('

')
      .find('.tooltip')
      .hide();
    $chart.on('mouseenter', '.ct-point', function() {
      var $point = $(this),
        value = $point.attr('ct:value'),
        seriesName = $point.parent().attr('ct:series-name');
      $toolTip.html(seriesName + '
' + value).show();
    });
    $chart.on('mouseleave', '.ct-point', function() {
      $toolTip.hide();
    });
    $chart.on('mousemove', function(event) {
      $toolTip.css({
        left: (event.offsetX || event.originalEvent.layerX) - $toolTip.width() / 2 - 10,
        top: (event.offsetY || event.originalEvent.layerY) - $toolTip.height() - 40
      });
    });
  }

  // Drop down to redraw the chart
  $('.js-dropdown').change(function(event) {
    console.log(event.currentTarget.value);
    $('.js-chart, .js-player-list').empty();
    drawchart(event.currentTarget.value, draftdata);
  });

});<commit_msg>more styles<commit_after>// Foundation JavaScript
// Documentation can be found at: http://foundation.zurb.com/docs
$(document).foundation().ready(function() {

  var draftdata = {};

  $.getJSON( '../json/data/mlb_draft_rounds.json' ).done(function( data ) {
    draftdata = data;
    drawchart("1999", data);
  });

  function drawchart(year, data) {
    var overallpickdata = [],
      wardata = [],
      namedata = [],
      players = [];

    // update title
    $('.js-title-year').text(year);
    // process data
    $.each( data, function( i, item ) {
      if(item.year === year) {
        console.log(item.name.replace(' (minors)',''), item.war);
        // list preparation
        var li = "
";
        li += item.pos + " ";
        li += item.war ? "" : "";
        li += item.name.replace(' (minors)','');
        li += item.war ? "" : "";
        li += " (" + item.team + ", " + item.round + ")";
        li += "" + item.war + "
"
        players.push( li );
        // chart preparation
        overallpickdata.push(item.overall_pick);
        wardata.push(item.war ? item.war : 0);
        namedata.push(item.name.replace(' (minors)',''));
      }
    });

    //update the list
    $( "
", {
      "class": "my-new-list",
      html: players.join( "" )
    }).appendTo( ".js-player-list" );

    // chartist chart
    new Chartist.Line('.ct-chart', {
      labels: overallpickdata,
      series: [
        {
          name: 'WAR',
          data: wardata
        }
      ]
    },
    {showLine: false});

     // creating tool tips -- out of box
    var $chart = $('.ct-chart');
    var $toolTip = $chart
      .append('

')
      .find('.tooltip')
      .hide();
    $chart.on('mouseenter', '.ct-point', function() {
      var $point = $(this),
        value = $point.attr('ct:value'),
        seriesName = $point.parent().attr('ct:series-name');
      $toolTip.html(seriesName + '
' + value).show();
    });
    $chart.on('mouseleave', '.ct-point', function() {
      $toolTip.hide();
    });
    $chart.on('mousemove', function(event) {
      $toolTip.css({
        left: (event.offsetX || event.originalEvent.layerX) - $toolTip.width() / 2 - 10,
        top: (event.offsetY || event.originalEvent.layerY) - $toolTip.height() - 40
      });
    });
  }

  // Drop down to redraw the chart
  $('.js-dropdown').change(function(event) {
    console.log(event.currentTarget.value);
    $('.js-chart, .js-player-list').empty();
    drawchart(event.currentTarget.value, draftdata);
  });

});<|endoftext|>


<commit_before>$(document).ready(function() {

	$('.scroll-link').on('click', function(event){
		event.preventDefault();
		var sectionID = $(this).attr("data-id");
		scrollToID('#' + sectionID, 750);
	});

	$(".timeline-text-container").on("mouseenter", function () {
		$(this).children(".timeline-hover-notice").hide();
		$(this).children(".timeline-class-desc").slideToggle();
	});

	$(".timeline-text-container").on("mouseleave", function () {
		$(this).children(".timeline-class-desc").slideToggle(function () {
			//$(this).parent().children(".timeline-hover-notice").show();
		});

	});

	if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
		$(".timeline-text-container").on("click", function () {
			$(this).children(".timeline-class-desc").slideToggle(function () {
			//$(this).parent().children(".timeline-hover-notice").show();
			});
		});
	}

	navSetter('main');
	navSetter('timeline');
	navSetter('portfolio');

});
// scroll function
function scrollToID(id, speed){
	var targetOffset = $(id).offset().top -40;
	$('html,body').animate({scrollTop:targetOffset}, speed);
}

function navSetter(id) {

	var target = $("#"+id).offset().top -50,
	    timeout = null;

	$(window).scroll(function () {
	    if (!timeout) {
	        timeout = setTimeout(function () {
	            console.log('scroll');
	            clearTimeout(timeout);
	            timeout = null;
	            if ($(window).scrollTop() >= target) {
	            	$(".nav").children().removeClass('active');
	                $("#nav-"+id).addClass('active');
	            }
	        }, 250);
	    }
	});

}
<commit_msg>fixed mobile click<commit_after>$(document).ready(function() {

	$('.scroll-link').on('click', function(event){
		event.preventDefault();
		var sectionID = $(this).attr("data-id");
		scrollToID('#' + sectionID, 750);
	});

	if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
		$(".timeline-text-container").on("click", function () {
			$(this).children(".timeline-class-desc").slideToggle();
		});
	} else {
		$(".timeline-text-container").on("mouseenter", function () {
			$(this).children(".timeline-hover-notice").hide();
			$(this).children(".timeline-class-desc").slideToggle();
		});

		$(".timeline-text-container").on("mouseleave", function () {
			$(this).children(".timeline-class-desc").slideToggle(function () {
				//$(this).parent().children(".timeline-hover-notice").show();
			});
		});
	}

	navSetter('main');
	navSetter('timeline');
	navSetter('portfolio');

});
// scroll function
function scrollToID(id, speed){
	var targetOffset = $(id).offset().top -40;
	$('html,body').animate({scrollTop:targetOffset}, speed);
}

function navSetter(id) {

	var target = $("#"+id).offset().top -50,
	    timeout = null;

	$(window).scroll(function () {
	    if (!timeout) {
	        timeout = setTimeout(function () {
	            console.log('scroll');
	            clearTimeout(timeout);
	            timeout = null;
	            if ($(window).scrollTop() >= target) {
	            	$(".nav").children().removeClass('active');
	                $("#nav-"+id).addClass('active');
	            }
	        }, 250);
	    }
	});

}
<|endoftext|>


<commit_before>if (window.location.href.indexOf('yukiblog.tw')!=-1) {
	$('.adsbygoogle').remove();$('.postad').remove();$("iframe").remove();
}

else if (window.location.href.indexOf('pixnet')!=-1) {
	jQuery('#pixad1101d').css('overflow', 'hidden');jQuery('.sticky-box').remove();
	jQuery('#main').css('overflow', 'hidden');jQuery('.article-body iframe').remove();
	jQuery('.article-body .adsbygoogle').remove();jQuery('.article-body').removeClass('show-summary');
	jQuery('.article-header .adsbygoogle').remove();
	jQuery('.header-ad').css({height: '120px'});

	jQuery('a img').parent().css('pointer-events', 'none');
	jQuery("iframe[src*='maps.google.com']").remove();
	jQuery("iframe[src*='www.google.com/maps']").remove();
	jQuery("iframe[src*='facebook.com']").remove();
	jQuery('#main .relative-article').remove();jQuery('.article-body').css('overflow-x', 'hidden');
	jQuery('#recommend-tools').remove();jQuery('#main .comment-form').remove();
	jQuery('#main .article-comments').remove(); jQuery('#header-bar__share-tools').remove();
	jQuery('#header .bar--reading span').remove();

	jQuery('#sb-site #logo').remove(); jQuery('#wrapper #toggleMenu').remove(); jQuery('#float_fb_plugin').remove();
	var sssheet = (function() {
		var style = document.createElement("style");
		style.appendChild(document.createTextNode(""));
		document.head.appendChild(style);
		return style.sheet;
	})();
	sssheet.insertRule("#scupio_interstitialad { display: none !important; }", 0);
	sssheet.insertRule(".pop-ad-cover { display: none !important; }", 0);
}

// Yuki
// jQuery('.article-header .adsbygoogle').css({height: '120px', overflow: 'hidden'});<commit_msg>update script<commit_after>if (window.location.href.indexOf('pixnet')!=-1) {
	jQuery('#pixad1101d').css('overflow', 'hidden');jQuery('.sticky-box').remove();
	jQuery('#main').css('overflow', 'hidden');jQuery('.article-body iframe').remove();
	jQuery('.article-body .adsbygoogle').remove();jQuery('.article-body').removeClass('show-summary');
	jQuery('.article-header .adsbygoogle').remove();
	jQuery('.header-ad').css({height: '120px'});

	jQuery('a img').parent().css('pointer-events', 'none');
	jQuery("iframe[src*='maps.google.com']").remove();
	jQuery("iframe[src*='www.google.com/maps']").remove();
	jQuery("iframe[src*='facebook.com']").remove();
	jQuery('#main .relative-article').remove();jQuery('.article-body').css('overflow-x', 'hidden');
	jQuery('#recommend-tools').remove();jQuery('#main .comment-form').remove();
	jQuery('#main .article-comments').remove(); jQuery('#header-bar__share-tools').remove();
	jQuery('#header .bar--reading span').remove();

	jQuery('#sb-site #logo').remove(); jQuery('#wrapper #toggleMenu').remove(); jQuery('#float_fb_plugin').remove();
	var sssheet = (function() {
		var style = document.createElement("style");
		style.appendChild(document.createTextNode(""));
		document.head.appendChild(style);
		return style.sheet;
	})();
	sssheet.insertRule("#scupio_interstitialad { display: none !important; }", 0);
	sssheet.insertRule(".pop-ad-cover { display: none !important; }", 0);

	if (window.location.href.indexOf('bluehero.pixnet')!=-1) {
		jQuery('table,embed').width('100%');
	}
}
else if (window.location.href.indexOf('yukiblog.tw')!=-1) {
	$('.adsbygoogle').remove();$('.postad').remove();$("iframe").remove();
}
else if (window.location.href.indexOf('wiselyview.cc')!=-1) {
	jQuery("iframe").remove();jQuery("#aswift_0_expand").remove();jQuery("#aswift_3_expand").remove();
}
else if (window.location.href.indexOf('candicecity.com')!=-1) {
	jQuery('.adsbygoogle, .sharedaddy').remove();
}
else if (window.location.href.indexOf('yuann.tw')!=-1) {
	jQuery("a[href='http://radarurl.com/monitor']").remove();
}

// Yuki
// jQuery('.article-header .adsbygoogle').css({height: '120px', overflow: 'hidden'});<|endoftext|>