<commit_before>var Batch = require('batch');
var debounce = require('debounce');
var geocode = require('geocode');
var Journey = require('journey');
var Location = require('location');
var log = require('./client/log')('plan');
var defaults = require('model-defaults');
var model = require('model');
var ProfileQuery = require('profile-query');
var ProfileScorer = require('otp-profile-score');
var qs = require('querystring');
var get = require('./client/request').get;

var loadPlan = require('./load');
var store = require('./store');
var updateRoutes = require('./update-routes');

/**
 * Debounce updates to once every 50ms
 */

var DEBOUNCE_UPDATES = 5;
var LIMIT = 2;

/**
 * Expose `Plan`
 */

var Plan = module.exports = model('Plan')
  .use(defaults({
    bike: true,
    bikeShare: false,
    bus: true,
    car: false,
    days: 'M—F',
    end_time: (new Date()).getHours() + 4,
    from: '',
    from_valid: false,
    loading: true,
    options: [],
    query: new ProfileQuery(),
    scorer: new ProfileScorer(),
    start_time: (new Date()).getHours() - 1,
    to: '',
    to_valid: false,
    train: true,
    tripsPerYear: 235,
    walk: true
  }))
  .attr('bike')
  .attr('bikeShare')
  .attr('bus')
  .attr('car')
  .attr('days')
  .attr('end_time')
  .attr('from')
  .attr('from_id')
  .attr('from_ll')
  .attr('from_valid')
  .attr('loading')
  .attr('journey')
  .attr('options')
  .attr('query')
  .attr('scorer')
  .attr('start_time')
  .attr('to')
  .attr('to_id')
  .attr('to_ll')
  .attr('to_valid')
  .attr('train')
  .attr('tripsPerYear')
  .attr('walk');

/**
 * Expose `load`
 */

module.exports.load = function(ctx, next) {
  loadPlan(Plan, ctx, next);
};

/**
 * Sync plans with localStorage
 */

Plan.on('change', function(plan, name, val) {
  log('plan.%s changed to %s', name, val);

  // Store in localStorage & track the change
  if (name !== 'options' && name !== 'journey' && name !== 'loading') plan.store();
});

/**
 * Keep start/end times in sync
 */

Plan.on('change start_time', function(plan, val, prev) {
  if (val >= plan.end_time()) plan.end_time(val + 1);
});

Plan.on('change end_time', function(plan, val, prev) {
  if (val <= plan.start_time()) plan.start_time(val - 1);
});

/**
 * Update routes. Restrict to once every 25ms.
 */

Plan.prototype.updateRoutes = debounce(function(opts, callback) {
  updateRoutes(this, opts, callback);
}, DEBOUNCE_UPDATES);

/**
 * Geocode
 */

Plan.prototype.geocode = function(dest, callback) {
  if (!callback) callback = function() {};

  var plan = this;
  var address = plan[dest]();
  var ll = plan[dest + '_ll']();
  if (address && address.length > 0) {
    geocode(address, function(err, ll) {
      if (err) {
        callback(err);
      } else {
        plan[dest + '_ll'](ll);
        callback(null, ll);
      }
    });
  } else {
    callback(null, ll);
  }
};

/**
 * Save Journey
 */

Plan.prototype.saveJourney = function(callback) {
  var opts = {};
  var skipKeys = ['options', 'journey', 'scorer'];
  for (var key in this.attrs) {
    if (skipKeys.indexOf(key) !== -1 || key.indexOf('to') === 0 || key.indexOf('from') === 0) {
      continue;
    }
    opts[key] = this.attrs[key];
  }

  // Create new journey
  var journey = new Journey({
    locations: [{
      _id: this.from_id()
    }, {
      _id: this.to_id()
    }],
    opts: opts
  });

  // Save
  journey.save(callback);
};

/**
 * Valid coordinates
 */

Plan.prototype.validCoordinates = function() {
  return this.coordinateIsValid(this.from_ll()) && this.coordinateIsValid(this.to_ll());
};

/**
 * Set Address
 */

Plan.prototype.setAddress = function(name, address, callback, extra) {

  console.log("name", name);
  console.log("address", address);
  console.log("callback", callback);
  console.log("extra", extra);

  callback = callback || function() {}; // noop callback
  var location = new Location();
  var plan = this;
  var c = address.split(',');
  var isCoordinate = c.length === 2 && !isNaN(parseFloat(c[0])) && !isNaN(parseFloat(c[1]));

  if (!address || address.length < 1) return callback();

    console.log("Location declarada ->", location);

  console.log("HOLA BEBE", geocode.reverseAmigo(c, callback));

    if (isCoordinate) {

      location.coordinate({
        lat: parseFloat(c[1]),
        lng: parseFloat(c[0])
       });
    var callbackAmigo = function (err, reverse) {
        console.log("Ahora si llama", reverse);
        if (reserve) {
            console.log("ejecuta reverse -> ", reverse);
            var geocode_features = reserve.features;
            var changes = {};
            if (isCoordinate)
              changes[name] = geocode_features[0].properties.label;
            else
              changes[name] = address;

            changes[name + '_ll'] = {lat: parseFloat(geocode_features[0].geometry.coordinates[1]), lng: parseFloat(geocode_features[0].geometry.coordinates[0])};
            changes[name + '_id'] = geocode_features[0].properties.id;
            changes[name + '_valid'] = true;

            console.log("CHANGES PLAN SET", changes);

            plan.set(changes);

            callback(null, res.body);
          } else {

            if (isCoordinate) {

              var changes = {};
              changes[name] = extra.properties.label;

              changes[name + '_ll'] = location.coordinate();

              changes[name + '_valid'] = true;

              plan.set(changes);

              callback(null, extra);

            } else {
              callback(err);
            }

          }
    }
     // get("https://www.amigocloud.com/api/v1/me/geocoder/reverse?token=R:DNiePlGOMsw93cEgde88woWAQxm1xzWt7lvVXe&point.lon="+ c[0] + "&point.lat="+c[1], function(err, res) {

     //callbackAmigo();

      var reserve = geocode.reverseAmigo(c, callbackAmigo);

      //});
    }else {

      plan.setAddress('', '', callback);

    }
};

/**
 * Set both addresses
 */

Plan.prototype.setAddresses = function(from, to, callback) {
  // Initialize the default locations
  var plan = this;

  Batch()
    .push(function(done) {
      plan.setAddress('from', from, done);
    })
    .push(function(done) {
      plan.setAddress('to', to, done);
    }).end(callback);
};

/**
 * Rescore Options
 */

Plan.prototype.rescoreOptions = function() {
  var scorer = this.scorer();
  var options = this.options();

  options.forEach(function(o) {
    o.rescore(scorer);
  });

  this.store();
};

/**
 * To Lower Case
 */

function toLowerCase(s) {
  return s ? s.toLowerCase() : '';
}

Plan.prototype.coordinateIsValid = function(c) {
  return !!c && !!parseFloat(c.lat) && !!parseFloat(c.lng) && parseFloat(c.lat) !== 0.0 && parseFloat(c.lng) !== 0.0;
};

/**
 * Modes as a CSV
 */

Plan.prototype.modesCSV = function() {
  var modes = [];
  if (this.bike()) modes.push('BICYCLE');
  if (this.bikeShare()) modes.push('BICYCLE_RENT');
  if (this.bus()) modes.push('BUSISH');
  if (this.train()) modes.push('TRAINISH');
  if (this.walk()) modes.push('WALK');
  if (this.car()) modes.push('CAR');

  return modes.join(',');
};

/**
 * Set modes from string
 */

Plan.prototype.setModes = function(csv) {
  if (!csv || csv.length < 1) return;
  var modes = csv.split ? csv.split(',') : csv;

  this.bike(modes.indexOf('BICYCLE') !== -1);
//  this.bikeShare(modes.indexOf('BICYCLE_RENT') !== -1);
  this.bikeShare(false);
  this.bus(true);
//  this.bus(modes.indexOf('BUSISH') !== -1);
  this.train(modes.indexOf('TRAINISH') !== -1);
  this.car(modes.indexOf('CAR') !== -1);
};

/**
 * Generate Query Parameters for this plan
 */

Plan.prototype.generateQuery = function() {
  var from = this.from_ll() || {};
  var to = this.to_ll() || {};

  // Transit modes
  var modes = [];//['WALK'];

  if (this.bikeShare()) modes.push('BICYCLE_RENT');

  if (this.car()) {
    modes.push('CAR');
  }
  if (this.bike()) {
    modes.push('BICYCLE');
  } else {
    modes.push('WALK');
  }
  if (this.bus()) modes.push('BUSISH');
  if (this.train()) modes.push('TRAINISH');
  if (modes.length==0) modes.push('WALK');

  var startTime = this.start_time();
  var endTime = this.end_time();
  var scorer = this.scorer();

  // Convert the hours into strings
  startTime += ':00';
  endTime = endTime === 24 ? '23:59' : endTime + ':00';

  return {
    date: this.nextDate(),
    mode: modes.join(','),
      time: startTime,
      fromPlace: (from.lat + ',' + from.lng),
      toPlace: (to.lat + ',' + to.lng),
      numItineraries: 3,
      maxWalkDistance: 20000,
      bikeSpeed: 10,
      bikeBoardCost: 15,
      walkReluctance: 10,
      clampInitialWait: 60,
//      waitAtBeginningFactor: 0.5,
      triangleSafetyFactor: 0.9,
      triangleSlopeFactor: 0.5,
      triangleTimeFactor: 0.9,
      optimize: 'QUICK'
  };
};

/**
 * Store in localStorage. Restrict this I/O to once every 25ms.
 */

Plan.prototype.store = debounce(function() {
  store(this);
}, DEBOUNCE_UPDATES);

/**
 * Clear localStorage
 */

Plan.prototype.clearStore = store.clear;

/**
 * Save URL
 */

Plan.prototype.saveURL = function() {
    console.log("Query planer change ciudad -> ", this.generateQueryString());
  window.history.replaceState(null, '', '/planner?' + this.generateQueryString());
};

/**
 * Get next date for day of the week
 */

Plan.prototype.nextDate = function() {
  var now = new Date();
  var date = now.getDate();
  var dayOfTheWeek = now.getDay();
  switch (this.days()) {
    case 'M—F':
      if (dayOfTheWeek === 0) now.setDate(date + 1);
      if (dayOfTheWeek === 6) now.setDate(date + 2);
      break;
    case 'Sat':
      now.setDate(date + (6 - dayOfTheWeek));
      break;
    case 'Sun':
      now.setDate(date + (7 - dayOfTheWeek));
      break;
  }
  return now.toISOString().split('T')[0];
};

/**
 * Generate `places` for transitive
 */

Plan.prototype.generatePlaces = function() {
  var fll = this.from_ll();
  var tll = this.to_ll();
  if (!fll || !tll) return [];

  return [{
    place_id: 'from',
    place_lat: fll.lat,
    place_lon: fll.lng,
    place_name: 'From'
  }, {
    place_id: 'to',
    place_lat: tll.lat,
    place_lon: tll.lng,
    place_name: 'To'
  }];
};

/**
 * Generate QueryString
 */

Plan.prototype.generateQueryString = function() {

  return qs.stringify({
    from: this.from(),
    to: this.to(),
    modes: this.modesCSV(),
    start_time: this.start_time(),
    end_time: this.end_time(),
    days: this.days()
  });
};
<commit_msg>fixed bug reverse geocode<commit_after>var Batch = require('batch');
var debounce = require('debounce');
var geocode = require('geocode');
var Journey = require('journey');
var Location = require('location');
var log = require('./client/log')('plan');
var defaults = require('model-defaults');
var model = require('model');
var ProfileQuery = require('profile-query');
var ProfileScorer = require('otp-profile-score');
var qs = require('querystring');
var get = require('./client/request').get;

var loadPlan = require('./load');
var store = require('./store');
var updateRoutes = require('./update-routes');

/**
 * Debounce updates to once every 50ms
 */

var DEBOUNCE_UPDATES = 5;
var LIMIT = 2;

/**
 * Expose `Plan`
 */

var Plan = module.exports = model('Plan')
  .use(defaults({
    bike: true,
    bikeShare: false,
    bus: true,
    car: false,
    days: 'M—F',
    end_time: (new Date()).getHours() + 4,
    from: '',
    from_valid: false,
    loading: true,
    options: [],
    query: new ProfileQuery(),
    scorer: new ProfileScorer(),
    start_time: (new Date()).getHours() - 1,
    to: '',
    to_valid: false,
    train: true,
    tripsPerYear: 235,
    walk: true
  }))
  .attr('bike')
  .attr('bikeShare')
  .attr('bus')
  .attr('car')
  .attr('days')
  .attr('end_time')
  .attr('from')
  .attr('from_id')
  .attr('from_ll')
  .attr('from_valid')
  .attr('loading')
  .attr('journey')
  .attr('options')
  .attr('query')
  .attr('scorer')
  .attr('start_time')
  .attr('to')
  .attr('to_id')
  .attr('to_ll')
  .attr('to_valid')
  .attr('train')
  .attr('tripsPerYear')
  .attr('walk');

/**
 * Expose `load`
 */

module.exports.load = function(ctx, next) {
  loadPlan(Plan, ctx, next);
};

/**
 * Sync plans with localStorage
 */

Plan.on('change', function(plan, name, val) {
  log('plan.%s changed to %s', name, val);

  // Store in localStorage & track the change
  if (name !== 'options' && name !== 'journey' && name !== 'loading') plan.store();
});

/**
 * Keep start/end times in sync
 */

Plan.on('change start_time', function(plan, val, prev) {
  if (val >= plan.end_time()) plan.end_time(val + 1);
});

Plan.on('change end_time', function(plan, val, prev) {
  if (val <= plan.start_time()) plan.start_time(val - 1);
});

/**
 * Update routes. Restrict to once every 25ms.
 */

Plan.prototype.updateRoutes = debounce(function(opts, callback) {
  updateRoutes(this, opts, callback);
}, DEBOUNCE_UPDATES);

/**
 * Geocode
 */

Plan.prototype.geocode = function(dest, callback) {
  if (!callback) callback = function() {};

  var plan = this;
  var address = plan[dest]();
  var ll = plan[dest + '_ll']();
  if (address && address.length > 0) {
    geocode(address, function(err, ll) {
      if (err) {
        callback(err);
      } else {
        plan[dest + '_ll'](ll);
        callback(null, ll);
      }
    });
  } else {
    callback(null, ll);
  }
};

/**
 * Save Journey
 */

Plan.prototype.saveJourney = function(callback) {
  var opts = {};
  var skipKeys = ['options', 'journey', 'scorer'];
  for (var key in this.attrs) {
    if (skipKeys.indexOf(key) !== -1 || key.indexOf('to') === 0 || key.indexOf('from') === 0) {
      continue;
    }
    opts[key] = this.attrs[key];
  }

  // Create new journey
  var journey = new Journey({
    locations: [{
      _id: this.from_id()
    }, {
      _id: this.to_id()
    }],
    opts: opts
  });

  // Save
  journey.save(callback);
};

/**
 * Valid coordinates
 */

Plan.prototype.validCoordinates = function() {
  return this.coordinateIsValid(this.from_ll()) && this.coordinateIsValid(this.to_ll());
};

/**
 * Set Address
 */

Plan.prototype.setAddress = function(name, address, callback, extra) {

  console.log("name", name);
  console.log("address", address);
  console.log("callback", callback);
  console.log("extra", extra);

  callback = callback || function() {}; // noop callback
  var location = new Location();
  var plan = this;
  var c = address.split(',');
  var isCoordinate = c.length === 2 && !isNaN(parseFloat(c[0])) && !isNaN(parseFloat(c[1]));

  if (!address || address.length < 1) return callback();

    console.log("Location declarada ->", location);

  console.log("HOLA BEBE", geocode.reverseAmigo(c, callback));

    if (isCoordinate) {

      location.coordinate({
        lat: parseFloat(c[1]),
        lng: parseFloat(c[0])
       });

    var callbackAmigo = function (err, reverse) {
        console.log("Ahora si llama", reverse);
        if (reverse) {

            console.log("ejecuta reverse -> ", reverse);

            var geocode_features = reverse.features;
            var changes = {};
            if (isCoordinate)
              changes[name] = geocode_features[0].properties.label;
            else
              changes[name] = address;

            changes[name + '_ll'] = {lat: parseFloat(geocode_features[0].geometry.coordinates[1]), lng: parseFloat(geocode_features[0].geometry.coordinates[0])};
            changes[name + '_id'] = geocode_features[0].properties.id;
            changes[name + '_valid'] = true;

            console.log("CHANGES PLAN SET", changes);

            plan.set(changes);

            callback(null, res.body);
          } else {

            if (isCoordinate) {

              var changes = {};
              changes[name] = extra.properties.label;

              changes[name + '_ll'] = location.coordinate();

              changes[name + '_valid'] = true;

              plan.set(changes);

              callback(null, extra);

            } else {
              callback(err);
            }

          }
    }

    geocode.reverseAmigo(c, callbackAmigo);

      //});
    }else {

      plan.setAddress('', '', callback);

    }
};

/**
 * Set both addresses
 */

Plan.prototype.setAddresses = function(from, to, callback) {
  // Initialize the default locations
  var plan = this;

  Batch()
    .push(function(done) {
      plan.setAddress('from', from, done);
    })
    .push(function(done) {
      plan.setAddress('to', to, done);
    }).end(callback);
};

/**
 * Rescore Options
 */

Plan.prototype.rescoreOptions = function() {
  var scorer = this.scorer();
  var options = this.options();

  options.forEach(function(o) {
    o.rescore(scorer);
  });

  this.store();
};

/**
 * To Lower Case
 */

function toLowerCase(s) {
  return s ? s.toLowerCase() : '';
}

Plan.prototype.coordinateIsValid = function(c) {
  return !!c && !!parseFloat(c.lat) && !!parseFloat(c.lng) && parseFloat(c.lat) !== 0.0 && parseFloat(c.lng) !== 0.0;
};

/**
 * Modes as a CSV
 */

Plan.prototype.modesCSV = function() {
  var modes = [];
  if (this.bike()) modes.push('BICYCLE');
  if (this.bikeShare()) modes.push('BICYCLE_RENT');
  if (this.bus()) modes.push('BUSISH');
  if (this.train()) modes.push('TRAINISH');
  if (this.walk()) modes.push('WALK');
  if (this.car()) modes.push('CAR');

  return modes.join(',');
};

/**
 * Set modes from string
 */

Plan.prototype.setModes = function(csv) {
  if (!csv || csv.length < 1) return;
  var modes = csv.split ? csv.split(',') : csv;

  this.bike(modes.indexOf('BICYCLE') !== -1);
//  this.bikeShare(modes.indexOf('BICYCLE_RENT') !== -1);
  this.bikeShare(false);
  this.bus(true);
//  this.bus(modes.indexOf('BUSISH') !== -1);
  this.train(modes.indexOf('TRAINISH') !== -1);
  this.car(modes.indexOf('CAR') !== -1);
};

/**
 * Generate Query Parameters for this plan
 */

Plan.prototype.generateQuery = function() {
  var from = this.from_ll() || {};
  var to = this.to_ll() || {};

  // Transit modes
  var modes = [];//['WALK'];

  if (this.bikeShare()) modes.push('BICYCLE_RENT');

  if (this.car()) {
    modes.push('CAR');
  }
  if (this.bike()) {
    modes.push('BICYCLE');
  } else {
    modes.push('WALK');
  }
  if (this.bus()) modes.push('BUSISH');
  if (this.train()) modes.push('TRAINISH');
  if (modes.length==0) modes.push('WALK');

  var startTime = this.start_time();
  var endTime = this.end_time();
  var scorer = this.scorer();

  // Convert the hours into strings
  startTime += ':00';
  endTime = endTime === 24 ? '23:59' : endTime + ':00';

  return {
    date: this.nextDate(),
    mode: modes.join(','),
      time: startTime,
      fromPlace: (from.lat + ',' + from.lng),
      toPlace: (to.lat + ',' + to.lng),
      numItineraries: 3,
      maxWalkDistance: 20000,
      bikeSpeed: 10,
      bikeBoardCost: 15,
      walkReluctance: 10,
      clampInitialWait: 60,
//      waitAtBeginningFactor: 0.5,
      triangleSafetyFactor: 0.9,
      triangleSlopeFactor: 0.5,
      triangleTimeFactor: 0.9,
      optimize: 'QUICK'
  };
};

/**
 * Store in localStorage. Restrict this I/O to once every 25ms.
 */

Plan.prototype.store = debounce(function() {
  store(this);
}, DEBOUNCE_UPDATES);

/**
 * Clear localStorage
 */

Plan.prototype.clearStore = store.clear;

/**
 * Save URL
 */

Plan.prototype.saveURL = function() {
    console.log("Query planer change ciudad -> ", this.generateQueryString());
  window.history.replaceState(null, '', '/planner?' + this.generateQueryString());
};

/**
 * Get next date for day of the week
 */

Plan.prototype.nextDate = function() {
  var now = new Date();
  var date = now.getDate();
  var dayOfTheWeek = now.getDay();
  switch (this.days()) {
    case 'M—F':
      if (dayOfTheWeek === 0) now.setDate(date + 1);
      if (dayOfTheWeek === 6) now.setDate(date + 2);
      break;
    case 'Sat':
      now.setDate(date + (6 - dayOfTheWeek));
      break;
    case 'Sun':
      now.setDate(date + (7 - dayOfTheWeek));
      break;
  }
  return now.toISOString().split('T')[0];
};

/**
 * Generate `places` for transitive
 */

Plan.prototype.generatePlaces = function() {
  var fll = this.from_ll();
  var tll = this.to_ll();
  if (!fll || !tll) return [];

  return [{
    place_id: 'from',
    place_lat: fll.lat,
    place_lon: fll.lng,
    place_name: 'From'
  }, {
    place_id: 'to',
    place_lat: tll.lat,
    place_lon: tll.lng,
    place_name: 'To'
  }];
};

/**
 * Generate QueryString
 */

Plan.prototype.generateQueryString = function() {

  return qs.stringify({
    from: this.from(),
    to: this.to(),
    modes: this.modesCSV(),
    start_time: this.start_time(),
    end_time: this.end_time(),
    days: this.days()
  });
};
<|endoftext|>


<commit_before>// remap jQuery to $
(function($) {

  $(function() {

    // Resizable
	var mouseMoveHandler = function(e) {
	  var initial = e.data.initial,
          u = Math.min(Math.max(initial.uHeight + (e.pageY - initial.offTop), initial.min), initial.max),
          b = Math.min(Math.max(initial.bHeight - (e.pageY - initial.offTop), initial.min), initial.max);
      initial.up.height(u);
      initial.below.height(b);

      $('#iframe-cover').height(initial.up.height()); // iframe fix
    };
    var mouseUpHandler = function(e) {
      $(document)
        .unbind('mousemove', mouseMoveHandler)
        .unbind('mouseup', mouseUpHandler);

      $('#iframe-cover').hide(); // iframe fix
      if (e.data.initial.below.height() === 0) {
        $('#main').removeClass('opened');
        Pontoon.common.postMessage("mode", "Advanced");
      } else {
        $('#main').addClass('opened');
        Pontoon.common.postMessage("mode", "Basic");
      }
    };
	$('#logo, #drag').bind('mousedown', function(e) {
      e.preventDefault();

      var up = $('#source'),
          below = $('#entitylist'),
          data = {
            up: up,
            below: below,
            uHeight: up.height(),
            bHeight: below.height(),
            offTop: e.pageY,
            min: 0,
            max: $(document).height()
          };

      // iframe fix: Prevent iframes from capturing the mousemove events during a drag
      $('#iframe-cover').show().height(up.height());

      $(document)
        .bind('mousemove', { initial: data }, mouseMoveHandler)
        .bind('mouseup', { initial: data }, mouseUpHandler);
    });

    // Resize iframe with window
    $(window).resize(function () {
      $('#source').height($(document).height() - $('#main').height());
    });

    // Validate URL
    function checkURL() {
      // Initialize Pontoon only if project code supports it
      function receiveMessage(e) {
        // TODO: Check origin - hardcode Pontoon domain name
        if (e.data === "supported") {
          // Slide up intro page and show iframe
          $('#intro').slideUp("slow", function() {
            $('#source').show();
            Pontoon.init($('#source').get(0).contentWindow, document, "de");
          });
          window.removeEventListener("message", receiveMessage, false);
        }
      }
      window.addEventListener("message", receiveMessage, false);

      // Load project page into iframe
      $('#source').attr('src', url);
      $('#intro .notification')
        .html('Loading...')
        .addClass('message').removeClass('error')
        .css('visibility', 'visible');

      // Show error message if no callback for 5 seconds: Pontoon/iframe not supported, 404…
      var i = 0,
          l = window.location,
          callback = setInterval(function() {
            if (i < 50) {
              i++;
              if (Pontoon._doc) { // Set in Pontoon.init() which is called on "supported"
                clearInterval(callback);
              }
            } else {
              clearInterval(callback);
              $('#intro .notification')
                .html('Oops, website is either not supported by Pontoon or could not be found.')
                .addClass('error').removeClass('message')
                .css('visibility', 'visible');
            }
          }, 100);
    }

    // Update locale selector
    function updateLocale(locale) {
      if (!locale || $('.locale .menu .flag.' + locale).length === 0) {
        locale = $("#intro .menu .flag:first").attr("class").split(" ")[1];
      }
      $('.locale .button')
        .find('.flag').addClass(locale).end()
        .find('.language').html($('.locale .menu .flag.' + locale).siblings('.language').html());
      if (url) {
        checkURL();
      }
    }

    // Set locale using browser language detection
    // TODO: develop internal solution
    // Source: http://stackoverflow.com/questions/1043339/javascript-for-detecting-browser-language-preference
    function guessLocale() {
      $.ajax({
        url: "http://ajaxhttpheaders.appspot.com",
        dataType: 'jsonp',
        success: function(headers) {
          var locale = headers['Accept-Language'].substring(0, 2),
              entry = $('#intro .locale .menu .flag.' + locale);
          updateLocale(locale);
        },
        error: function() {
          updateLocale();
        }
      });
    }

    // Validate locale
    function isValidLocale(locale) {
      var valid = false;
      $("#intro .menu .flag").each(function() {
        if (locale === $(this).attr("class").split(" ")[1]) {
          valid = true;
        }
      });
      return valid;
    }

    // Main code

    // Check for params
    var locale = window.location.search.split("&locale=")[1] || "",
        temp = window.location.search.split("?url=")[1],
        url = temp ? temp.split("&locale=")[0] : "";
    $('.url').val(url);

    // Empty iframe if cached, prepare size and resize it with window
    $('#source').removeAttr("src").height($(document).height() - $('#main').height());

    // Set locale
    if (isValidLocale(locale)) {
      updateLocale(locale);
    } else {
      guessLocale();
    }
  });

}(this.jQuery));

// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function() {
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if (this.console) {
    console.log(Array.prototype.slice.call(arguments));
  }
};

// catch all document.write() calls
(function(doc) {
  var write = doc.write;
  doc.write = function(q) {
    log('document.write(): ', arguments);
    if (/docwriteregexwhitelist/.test(q)) {
      write.apply(doc,arguments);
    }
  };
}(document));
<commit_msg>Auch, remove hardcoded "de" locale<commit_after>// remap jQuery to $
(function($) {

  $(function() {

    // Resizable
	var mouseMoveHandler = function(e) {
	  var initial = e.data.initial,
          u = Math.min(Math.max(initial.uHeight + (e.pageY - initial.offTop), initial.min), initial.max),
          b = Math.min(Math.max(initial.bHeight - (e.pageY - initial.offTop), initial.min), initial.max);
      initial.up.height(u);
      initial.below.height(b);

      $('#iframe-cover').height(initial.up.height()); // iframe fix
    };
    var mouseUpHandler = function(e) {
      $(document)
        .unbind('mousemove', mouseMoveHandler)
        .unbind('mouseup', mouseUpHandler);

      $('#iframe-cover').hide(); // iframe fix
      if (e.data.initial.below.height() === 0) {
        $('#main').removeClass('opened');
        Pontoon.common.postMessage("mode", "Advanced");
      } else {
        $('#main').addClass('opened');
        Pontoon.common.postMessage("mode", "Basic");
      }
    };
	$('#logo, #drag').bind('mousedown', function(e) {
      e.preventDefault();

      var up = $('#source'),
          below = $('#entitylist'),
          data = {
            up: up,
            below: below,
            uHeight: up.height(),
            bHeight: below.height(),
            offTop: e.pageY,
            min: 0,
            max: $(document).height()
          };

      // iframe fix: Prevent iframes from capturing the mousemove events during a drag
      $('#iframe-cover').show().height(up.height());

      $(document)
        .bind('mousemove', { initial: data }, mouseMoveHandler)
        .bind('mouseup', { initial: data }, mouseUpHandler);
    });

    // Resize iframe with window
    $(window).resize(function () {
      $('#source').height($(document).height() - $('#main').height());
    });

    // Validate URL
    function checkURL() {
      // Initialize Pontoon only if project code supports it
      function receiveMessage(e) {
        // TODO: Check origin - hardcode Pontoon domain name
        if (e.data === "supported") {
          // Slide up intro page and show iframe
          $('#intro').slideUp("slow", function() {
            $('#source').show();
            Pontoon.init($('#source').get(0).contentWindow, document, locale);
          });
          window.removeEventListener("message", receiveMessage, false);
        }
      }
      window.addEventListener("message", receiveMessage, false);

      // Load project page into iframe
      $('#source').attr('src', url);
      $('#intro .notification')
        .html('Loading...')
        .addClass('message').removeClass('error')
        .css('visibility', 'visible');

      // Show error message if no callback for 5 seconds: Pontoon/iframe not supported, 404…
      var i = 0,
          l = window.location,
          callback = setInterval(function() {
            if (i < 50) {
              i++;
              if (Pontoon._doc) { // Set in Pontoon.init() which is called on "supported"
                clearInterval(callback);
              }
            } else {
              clearInterval(callback);
              $('#intro .notification')
                .html('Oops, website is either not supported by Pontoon or could not be found.')
                .addClass('error').removeClass('message')
                .css('visibility', 'visible');
            }
          }, 100);
    }

    // Update locale selector
    function updateLocale(locale) {
      if (!locale || $('.locale .menu .flag.' + locale).length === 0) {
        locale = $("#intro .menu .flag:first").attr("class").split(" ")[1];
      }
      $('.locale .button')
        .find('.flag').addClass(locale).end()
        .find('.language').html($('.locale .menu .flag.' + locale).siblings('.language').html());
      if (url) {
        checkURL();
      }
    }

    // Set locale using browser language detection
    // TODO: develop internal solution
    // Source: http://stackoverflow.com/questions/1043339/javascript-for-detecting-browser-language-preference
    function guessLocale() {
      $.ajax({
        url: "http://ajaxhttpheaders.appspot.com",
        dataType: 'jsonp',
        success: function(headers) {
          var locale = headers['Accept-Language'].substring(0, 2),
              entry = $('#intro .locale .menu .flag.' + locale);
          updateLocale(locale);
        },
        error: function() {
          updateLocale();
        }
      });
    }

    // Validate locale
    function isValidLocale(locale) {
      var valid = false;
      $("#intro .menu .flag").each(function() {
        if (locale === $(this).attr("class").split(" ")[1]) {
          valid = true;
        }
      });
      return valid;
    }

    // Main code

    // Check for params
    var locale = window.location.search.split("&locale=")[1] || "",
        temp = window.location.search.split("?url=")[1],
        url = temp ? temp.split("&locale=")[0] : "";
    $('.url').val(url);

    // Empty iframe if cached, prepare size and resize it with window
    $('#source').removeAttr("src").height($(document).height() - $('#main').height());

    // Set locale
    if (isValidLocale(locale)) {
      updateLocale(locale);
    } else {
      guessLocale();
    }
  });

}(this.jQuery));

// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function() {
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if (this.console) {
    console.log(Array.prototype.slice.call(arguments));
  }
};

// catch all document.write() calls
(function(doc) {
  var write = doc.write;
  doc.write = function(q) {
    log('document.write(): ', arguments);
    if (/docwriteregexwhitelist/.test(q)) {
      write.apply(doc,arguments);
    }
  };
}(document));
<|endoftext|>


<commit_before>import React, { Component }  from 'react'
import merge                 from 'merge'
import classnames            from 'classnames'

export class Loader extends Component {

  static propTypes = {
    type: React.PropTypes.string,
    size: React.PropTypes.string,
    active: React.PropTypes.bool
  };

  static defaultProps = {
    type: 'ball-pulse',
    size: 'md',
    active: true
  };

  static removeType(type) {
    delete Types[key]
  }

  static addType(key, nDivs) {
    return Types[key] = nDivs;
  }

  renderDiv(n) {
    return

  }

  render() {
    const nDivs = range(Types[this.props.type]);
    const classes = classnames({
      loader: true,
      ['loader-' + this.props.size]: this.props.size !== 'md',
      'loader-active': this.props.active,
      'loader-hidden': !this.props.active
    }, this.props.className)

    return

      <div className={`loader-inner ${this.props.type}`}>
        { nDivs.map(this.renderDiv) }

  }

}

export default Loader;

export var Types = {
  "ball-pulse"                  : 3,
  "ball-grid-pulse"             : 9,
  "ball-clip-rotate"            : 1,
  "ball-clip-rotate-pulse"      : 2,
  "square-spin"                 : 1,
  "ball-clip-rotate-multiple"   : 2,
  "ball-pulse-rise"             : 5,
  "ball-rotate"                 : 1,
  "cube-transition"             : 2,
  "ball-zig-zag"                : 2,
  "ball-zig-zag-deflect"        : 2,
  "ball-triangle-path"          : 3,
  "ball-scale"                  : 1,
  "line-scale"                  : 5,
  "line-scale-party"            : 4,
  "ball-scale-multiple"         : 3,
  "ball-pulse-sync"             : 3,
  "ball-beat"                   : 3,
  "line-scale-pulse-out"        : 5,
  "line-scale-pulse-out-rapid"  : 5,
  "ball-scale-ripple"           : 1,
  "ball-scale-ripple-multiple"  : 3,
  "ball-spin-fade-loader"       : 8,
  "line-spin-fade-loader"       : 8,
  "triangle-skew-spin"          : 1,
  "pacman"                      : 5,
  "ball-grid-beat"              : 9,
  "semi-circle-spin"            : 1
}

function range(x) {
  let i = -1, arr = [];
  while(++i < x) { arr.push(i) }
  return arr;
}
<commit_msg>Remove extraneous dep<commit_after>import React, { Component }  from 'react'
import classnames            from 'classnames'

export class Loader extends Component {

  static propTypes = {
    type: React.PropTypes.string,
    size: React.PropTypes.string,
    active: React.PropTypes.bool
  };

  static defaultProps = {
    type: 'ball-pulse',
    size: 'md',
    active: true
  };

  static removeType(type) {
    delete Types[key]
  }

  static addType(key, nDivs) {
    return Types[key] = nDivs;
  }

  renderDiv(n) {
    return

  }

  render() {
    const nDivs = range(Types[this.props.type]);
    const classes = classnames({
      loader: true,
      ['loader-' + this.props.size]: this.props.size !== 'md',
      'loader-active': this.props.active,
      'loader-hidden': !this.props.active
    }, this.props.className)

    return

      <div className={`loader-inner ${this.props.type}`}>
        { nDivs.map(this.renderDiv) }

  }

}

export default Loader;

export var Types = {
  "ball-pulse"                  : 3,
  "ball-grid-pulse"             : 9,
  "ball-clip-rotate"            : 1,
  "ball-clip-rotate-pulse"      : 2,
  "square-spin"                 : 1,
  "ball-clip-rotate-multiple"   : 2,
  "ball-pulse-rise"             : 5,
  "ball-rotate"                 : 1,
  "cube-transition"             : 2,
  "ball-zig-zag"                : 2,
  "ball-zig-zag-deflect"        : 2,
  "ball-triangle-path"          : 3,
  "ball-scale"                  : 1,
  "line-scale"                  : 5,
  "line-scale-party"            : 4,
  "ball-scale-multiple"         : 3,
  "ball-pulse-sync"             : 3,
  "ball-beat"                   : 3,
  "line-scale-pulse-out"        : 5,
  "line-scale-pulse-out-rapid"  : 5,
  "ball-scale-ripple"           : 1,
  "ball-scale-ripple-multiple"  : 3,
  "ball-spin-fade-loader"       : 8,
  "line-spin-fade-loader"       : 8,
  "triangle-skew-spin"          : 1,
  "pacman"                      : 5,
  "ball-grid-beat"              : 9,
  "semi-circle-spin"            : 1
}

function range(x) {
  let i = -1, arr = [];
  while(++i < x) { arr.push(i) }
  return arr;
}
<|endoftext|>


<commit_before>var q = require('q');
var uuid = require('node-uuid');

/**
 * Defines a record
 */
module.exports = function(manager, mapper) {

  // record constructor
  var record = function(doc) {
    // reserved field _id
    this._id = false;
    // sets values
    for(var i in doc) {
      if (mapper.options.fields.hasOwnProperty(i)) {
        this[i] = mapper.options.fields[i].unserialize(doc[i]);
      } else {
        this[i] = doc[i];
      }
    }
  };

  // saves the current record
  record.prototype.save = function() {
    var self = this;
    if (!self._id) {
      return recordManager.nextId().then(function(id) {
        self._id = id;
        return self.save();
      });
    } else {
      var result = q.defer();
      try {
        for(var fieldName in mapper.options.fields) {
          var field = mapper.options.fields[fieldName];
          if (!field.validate.type(self[fieldName])) {
            throw new Error('Unable to validate "' + fieldName + '" type');
          }
          if (!field.validate.contents(self[fieldName])) {
            throw new Error('Unable to validate "' + fieldName + '" contents');
          }
        }
        if (!mapper.options.record.beforeSave.apply(self, [])) {
          throw new Error('Unable to save the record');
        }
        // reserved field _type
        self._type = mapper.options.type;
        manager.cb.set(
          mapper.options.autoincrement ? mapper.options.type + '.' + self._id : self._id, self,
          function(err, data) {
            if (err) {
              result.reject(err);
            } else {
              if (!mapper.options.record.afterSave.apply(self, [])) {
                throw new Error('Unable to save the record');
              }
              result.resolve(self);
            }
          }
        );
      } catch(e) {
        result.reject(e);
      }
      return result.promise;
    }
  };

  // removes the current entry
  record.prototype.remove = function() {
    var result = q.defer();
    var self = this;
    if (this._id) {
      if (!mapper.options.record.beforeRemove.apply(self, [])) {
        throw new Error('Unable to remove the record');
      }
      manager.cb.remove(
        mapper.options.autoincrement ? mapper.options.type + '.' + this._id : this._id
        , function(err) {
        if (err) {
          result.reject(err);
        } else {
          mapper.options.record.afterRemove.apply(self, []);
          result.resolve(self);
        }
      });
    } else {
      result.reject(new Error("Can not remove, the entry is not saved yet"));
    }
    return result.promise;
  };

  // manager
  var recordManager = {
    /**
     * Retrieves the next sequence id
     */
    nextId: function() {
      var result = q.defer();
      if (mapper.options.autoincrement == true) {
        manager.cb.incr(
          'seq.' + mapper.options.type,
          {initial: 1, offset: 1},
          function(err, data) {
            if (err) {
              result.reject(err);
            } else {
              result.resolve(data.value);
            }
          }
        );
      } else {
        result.resolve(uuid.v4());
      }
      return result.promise;
    },
    /**
     * Deserialize a document into an active record
     */
    deserialize: function(doc) {
      return new record(doc);
    }
  };
  return recordManager;
};<commit_msg>rewrite the record api<commit_after>var q = require('q');
var util = require('util');
var EventEmitter = require('events').EventEmitter;

/**
 * Defines a record
 */
module.exports = function(manager, mapper) {

  // record constructor
  var record = function(doc) {
    // reserved field _id
    this._id = false;
    // sets values
    for(var i in doc) {
      if (mapper.options.properties.hasOwnProperty(i)) {
        this[i] = mapper.options.properties[i].unserialize(doc[i]);
      } else {
        this[i] = doc[i];
      }
    }
  };
  util.inherits(mapper, EventEmitter);

  // Gets the record ID
  record.prototype.getId = function() {
    return mapper.options.autoincrement ?
      mapper.options.type + '.' + this._id : this._id
  };

  // saves the current record
  record.prototype.save = function() {
    var self = this;
    if (!this._id) {
      return mapper.nextId().then(function(id) {
        self._id = id;
        return self.save();
      });
    } else {
      var result = q.defer();
      try {
        for(var name in mapper.options.properties) {
          var property = mapper.options.properties[name];
          if (this.hasOwnProperty(name) && !property.checkType(this[name])) {
            throw new Error('Unable to validate "' + name + '" type');
          }
          if (!property.checkContents(this[name])) {
            throw new Error('Unable to validate "' + name + '" contents');
          }
        }
        this.emit('save', this);
        mapper.emit('save', this);
        // reserved field _type
        this._type = mapper.options.type;
        manager.cb.set(
          this.getId(), this,
          function(err, data) {
            if (err) {
              result.reject(err);
              self.emit('error', err);
              mapper.emit('error', err);
            } else {
              result.resolve(self);
              self.emit('saved', self);
              mapper.emit('saved', self);
            }
          }
        );
      } catch(err) {
        result.reject(err);
        this.emit('error', err);
        mapper.emit('error', err);
      }
      return result.promise;
    }
  };

  // removes the current entry
  record.prototype.remove = function() {
    var result = q.defer();
    var self = this;
    try {
      if (!this._id) throw new Error(
        "Can not remove, the entry is not saved yet"
      );
      this.emit('remove', this);
      mapper.emit('remove', this);
      manager.cb.remove(this.getId(), function(err) {
        if (err) {
          result.reject(err);
          self.emit('error', err);
          mapper.emit('error', err);
        } else {
          // reset the current field ID
          this._id = false;
          result.resolve(self);
          self.emit('removed', self);
          mapper.emit('removed', self);
        }
      });
    } catch(err) {
      result.reject(err);
      this.emit('error', err);
      mapper.emit('error', err);
    }
    return result.promise;
  };
  // expose the record class
  return record;
};<|endoftext|>


<commit_before>"use strict";
var fs = require("fs");
var watch = require("../efront/watch");
var path = require("path");
var message = require("../message");
var isDevelop = require("../efront/isDevelop");
var versionTree = {};
var loading_queue = [], loading_count = 0;
var runPromiseInQueue = function () {
    if (loading_count > 2) return;
    if (loading_queue.length) {
        loading_count++;
        loading_queue.shift()();
    }
};
var delPromiseInQueue = function (a) {
    loading_count--;
    runPromiseInQueue();
    return a;
};
var getPromiseInQueue = function (runner) {
    var promise = new Promise(function (ok) {
        loading_queue.push(ok);
    }).then(function () {
        return new Promise(runner);
    }).then(delPromiseInQueue, delPromiseInQueue);
    runPromiseInQueue();
    return promise;
};
/**
 * 取文件夹
 * @param {string} pathname
 */
var getdir = function (pathname) {
    var directory = {};
    fs.readdirSync(pathname).forEach(function (name) {
        directory[name] = false;
    });
    return directory;
};
var getdirAsync = function (pathname) {
    return getPromiseInQueue(function (ok, oh) {

        fs.readdir(pathname, function (error, files) {
            if (error) oh(error);
            else {
                var directory = {};
                files.forEach(function (name) {
                    directory[name] = false;
                });
                ok(directory);
            }
        });
    });
};
var getfileAsync = function (pathname, buffer_size) {
    if (isFinite(buffer_size) && getVersion(pathname).size > buffer_size)
        return getFileHeadAsync(pathname, buffer_size);
    return getPromiseInQueue(function (ok, oh) {
        fs.readFile(pathname, function (error, data) {
            if (error) oh(error);
            else ok(data);
        });
    });
};
var getFileHeadAsync = function (pathname, buffer_size) {
    return getPromiseInQueue(function (ok, oh) {
        fs.open(pathname, "r", function (err, h) {
            if (err) {
                return oh(err);
            }
            var chunk = Buffer.alloc(buffer_size);
            fs.read(h, chunk, 0, chunk.length, 0, function (err, length, chunk) {
                if (err) return fs.close(h), oh(err);
                if (length < chunk.length) {
                    chunk = chunk.slice(0, length);
                }
                chunk.location = pathname;
                fs.close(h, function (error) {
                    if (error) return oh(error);
                    ok(chunk);
                });
            });
        });
    });
};

var isdirAsync = function (pathname) {
    return getPromiseInQueue(function (ok, oh) {
        fs.stat(pathname, function (error, stats) {
            if (error) oh(error);
            else if (stats.isDirectory()) ok(true);
            else {
                versionTree[pathname] = stats;
                ok(false);
            }
        });
    });
};

var getVersion = function (pathname) {
    return versionTree[pathname];
};

var asyncLoader = function (curl, temp, key, rebuild) {
    var root = String(this);
    var buffer_size = this.buffer_size;
    var durl = path.resolve(root, curl);
    var durls = [durl];
    var _watch = function (_durls) {
        durls.forEach(durl => watch(durl));
        durls = _durls;
        _durls.forEach(curl => watch(curl, load));
    };
    var pathname = path.join(root, curl);
    var that = this;
    var load = function (loadType) {
        var durls = [durl];
        var is_change = loadType === "change";
        var saved = is_change && temp[key];
        saved = !(saved instanceof Promise || saved instanceof Error) && saved;
        var origin = temp[key];
        var p0 = temp[key] = isdirAsync(pathname).then(function (isdir) {
            if (p0 !== temp[key]) return;
            if (isdir) {
                var p = temp[key] = getdirAsync(pathname).then(function (dirs) {
                    if (p !== temp[key]) return;
                    temp[key] = dirs;
                    if (isDevelop) {
                        is_change = saved && Object.keys(dirs).sort().join(",") !== Object.keys(saved).sort().join(",");
                        if (is_change) message.broadcast('reload');
                    }
                    if (origin) unwatch(pathname, origin);
                    _watch(durls);
                    console.info(root, curl, is_change ? "change" : "load");
                }).catch(function (error) {
                    if (p !== temp[key]) return;
                    if (origin) unwatch(pathname, origin);
                    temp[key] = error;
                    _watch([]);
                });
            } else {
                var p = temp[key] = getfileAsync(pathname, buffer_size).then(function (data) {
                    if (p !== temp[key]) return;
                    try {
                        if (rebuild instanceof Function) {
                            data = rebuild(data, that.getURL(), durl, durls);
                        }
                    } catch (e) {
                        console.warn("Build Faild:", curl, e);
                        data = e;
                    }
                    return data;
                }).then(function (data) {
                    if (p !== temp[key]) return;
                    if (origin) unwatch(pathname, origin);
                    if (typeof data === "string") {
                        data = Buffer.from(data);
                    }
                    temp[key] = data;
                    if (isDevelop) {
                        is_change = saved && (saved instanceof Buffer && Buffer.compare(saved, data) || String(saved) !== String(data));
                        if (is_change) message.broadcast('reload');
                    }
                    console.info(root, curl, is_change ? "change" : "load");
                    _watch(durls);
                }).catch(function (error) {
                    if (p !== temp[key]) return;
                    if (origin) unwatch(pathname, origin);
                    temp[key] = error;
                    console.error(error);
                    _watch([]);
                });
            }
        }).catch(function (error) {
            if (p0 !== temp[key]) return;
            if (origin) unwatch(pathname, origin);
            temp[key] = error;
            console.error(error);
        });
    };
    load();
    return load;
};
var matcherReg = /[A-Z]+/g;
var replaceCase = function (match, index, input) {
    if (match.length === 1) {
        return "-" + match.toLowerCase();
    }
    if (match.length === 2) {
        match = match.toLowerCase();
        return "-" + match[0] + "-" + match[1];
    }
    if (index + match.length === input.length) {
        return "-" + match;
    }
    return '-' + match.slice(0, match.length - 1) + "-" + match[match.length - 1].toLowerCase();
};

var seekAsync = function (url, tree, rebuild) {
    var temp = tree;
    if (!temp) return new Error('file system error');
    var keeys = url.split(/[\\\/]+/);
    var curl = "";
    var that = this;
    var temps = [];

    var research = function () {
        return seekAsync.call(that, url, tree, rebuild);
    };
    search: for (var cx = 0, dx = keeys.length; cx < dx; cx++) {
        var key = keeys[cx];
        if (key === '' || key === '.') continue;
        if (!(key in temp)) {
            let k = key.replace(matcherReg, replaceCase);
            if (k in temp) {
                key = k;
            }
        }
        if (!(key in temp)) {
            if (!that.buffer_size) {
                temp = undefined;
                break;
            }
            for (var cy = temps.length - 1; cy >= 0; cy--) {
                if (key in temps[cy]) {
                    let searched = seekAsync.call(that, keeys.slice(cx).join("/"), temps[cy], rebuild);
                    if (searched instanceof Promise) {
                        return searched.then(research);
                    }
                    if (searched !== undefined) {
                        temp = searched;
                        break search;
                    }
                }
            }
            continue;
        }
        curl = path.join(curl, key);
        if (temp[key] === false) {
            asyncLoader.call(that, curl, temp, key, rebuild);
        }
        temps.push(temp);
        temp = temp[key];
        if (temp instanceof Promise) {
            return temp.then(research);
        }
        if (!temp) break;
    }
    if (!(temp instanceof Object)) {
        return temp;
    }
    if (temp instanceof Function) {
        return temp;
    }
    if (temp instanceof Error) {
        return temp;
    }
    if ((temp instanceof Buffer) && !temp.stat) {
        temp.stat = getVersion(path.join(String(this), curl));
        temp.name = key;
    }
    return temp;
};

/**
 * 取消路径监听
 * @param {string} curl
 * @param {object} temp
 */
var unwatch = function (curl, temp) {
    if (temp instanceof Object) {
        for (var k in temp) {
            var cvrl = path.join(curl, k);
            watch(cvrl);
            unwatch(cvrl, temp[k]);
        }
    }
};
var getExtts = function (extts) {
    if (extts instanceof Array && extts.length <= 1) extts = extts;
    return extts || "";
};
/**
 * 根椐filesroot路径设置文件缓冲
 * @param {string} filesroot
 */
var cache = function (filesroot, rebuild, buffer_size_limit) {
    var sk = function (url, extts) {
    };
    filesroot = filesroot.split(",");
    var tree = filesroot.map((froot, i) => {
        if (fs.existsSync(froot) && fs.statSync(froot).isDirectory()) {
            var roots = getdir(froot);
            watch(froot, function () {
                getdirAsync(froot, function (a) {
                    for (var k in roots) {
                        if (!(k in a)) {
                            delete roots[k];
                            unwatch(path.join(froot, k));
                        }
                    }
                    for (var k in a) {
                        if (!(k in roots)) {
                            roots[k] = false;
                        }
                    }
                    message.broadcast("reload");
                });
            });
            return roots;
        } else {
            return Object.create(null);
        }
    });
    if (isFinite(buffer_size_limit) && buffer_size_limit >= 0) {
        sk.buffer_size = buffer_size_limit | 0;
    }
    var seekerAsync = function (url, extts = "") {
        extts = getExtts(extts);
        if (!Array.isArray(extts)) {
            extts = [extts];
        }
        var seeker = function () { };
        seeker.toString = function () {
            return this;
        }.bind(filesroot[0]);
        seeker.getURL = function () {
            return url;
        };
        seeker.buffer_size = sk.buffer_size;
        return new Promise(function (ok, oh) {
            var cy = 0;
            var cx = 0;
            var result, matchParent;
            var run = function () {
                if (cx >= extts.length) {
                    cy++;
                    if (cy >= tree.length) {
                        if (result === undefined) {
                            if (matchParent) {
                                url = url.replace(/\\/g, '/');
                                if (!/\/$/.test(url)) {
                                    url += '/';
                                    result = url;
                                }
                            }
                        }
                        return ok(result);
                    }
                    seeker.toString = function () {
                        return this;
                    }.bind(filesroot[cy]);
                    cx = 0;
                }
                var tree1 = tree[cy];
                var extt = extts[cx];
                var error;
                var promise = seekAsync.call(seeker, url + extt, tree1, rebuild);
                if (promise instanceof Promise) {
                    promise.catch(function (e) {
                        error = e;
                    }).then(function (result) {
                        if (result instanceof Buffer) return ok(result);
                        if (error) oh(error);
                        else run();
                    });
                } else {

                    if (promise instanceof Buffer || promise instanceof Function) return ok(promise);
                    if (promise instanceof Object && !result) {
                        var package_file = "package.json";
                        if (package_file in promise) {
                            if (promise[package_file] === false) {
                                seekAsync.call(seeker, url + extt + "/" + package_file, tree1, a => JSON.parse(String(a))).catch(oh).then(run);
                                return;
                            } else if (promise[package_file] instanceof Buffer) {
                                promise[package_file] = JSON.parse(promise[package_file].toString());
                            }
                            var package_data = promise[package_file];
                            if (package_data instanceof Object && package_data.main) {
                                var roots = package_data.main.split(/[\/\\]+/).filter(a => a && a !== '.' && !/\:$/.test(a));
                                if (roots[0] in promise) {
                                    result = path.join(url, roots.join('/')).replace(/\\/g, '/');
                                    return ok(result);
                                }
                            }
                        } else {
                            var seek_index = 'index';
                            var index = extts.findIndex(a => seek_index + a in promise);
                            if (~index) {
                                result = path.join(url, seek_index + extts[index]).replace(/\\/g, '/');
                            } else {
                                if (typeof promise === 'string') result = promise;
                            }
                        }
                        matchParent = true;
                    }
                    cx++;
                    run();
                }

            };
            run();
        });
    };
    sk.async = seekerAsync;
    sk.new = cache;
    return sk;
};
var _reload_handlers = [];
cache.onreload = function (handler) {
    if (handler instanceof Function) _reload_handlers.push(handler);
};
module.exports = cache;<commit_msg>不再缓冲巨型文件的数据<commit_after>"use strict";
var fs = require("fs");
var watch = require("../efront/watch");
var path = require("path");
var message = require("../message");
var isDevelop = require("../efront/isDevelop");
var versionTree = {};
var loading_queue = [], loading_count = 0;
var runPromiseInQueue = function () {
    if (loading_count > 2) return;
    if (loading_queue.length) {
        loading_count++;
        loading_queue.shift()();
    }
};
var delPromiseInQueue = function (a) {
    loading_count--;
    runPromiseInQueue();
    return a;
};
var getPromiseInQueue = function (runner) {
    var promise = new Promise(function (ok) {
        loading_queue.push(ok);
    }).then(function () {
        return new Promise(runner);
    }).then(delPromiseInQueue, delPromiseInQueue);
    runPromiseInQueue();
    return promise;
};
/**
 * 取文件夹
 * @param {string} pathname
 */
var getdir = function (pathname) {
    var directory = {};
    fs.readdirSync(pathname).forEach(function (name) {
        directory[name] = false;
    });
    return directory;
};
var getdirAsync = function (pathname) {
    return getPromiseInQueue(function (ok, oh) {

        fs.readdir(pathname, function (error, files) {
            if (error) oh(error);
            else {
                var directory = {};
                files.forEach(function (name) {
                    directory[name] = false;
                });
                ok(directory);
            }
        });
    });
};
var getfileAsync = function (pathname, buffer_size) {
    if (isFinite(buffer_size) && getVersion(pathname).size > buffer_size)
        return getFileHeadAsync(pathname, 0);
    return getPromiseInQueue(function (ok, oh) {
        fs.readFile(pathname, function (error, data) {
            if (error) oh(error);
            else ok(data);
        });
    });
};
var getFileHeadAsync = function (pathname, buffer_size) {
    return getPromiseInQueue(function (ok, oh) {
        fs.open(pathname, "r", function (err, h) {
            if (err) {
                return oh(err);
            }
            var chunk = Buffer.alloc(buffer_size);
            fs.read(h, chunk, 0, chunk.length, 0, function (err, length, chunk) {
                if (err) return fs.close(h), oh(err);
                if (length < chunk.length) {
                    chunk = chunk.slice(0, length);
                }
                chunk.location = pathname;
                fs.close(h, function (error) {
                    if (error) return oh(error);
                    ok(chunk);
                });
            });
        });
    });
};

var isdirAsync = function (pathname) {
    return getPromiseInQueue(function (ok, oh) {
        fs.stat(pathname, function (error, stats) {
            if (error) oh(error);
            else if (stats.isDirectory()) ok(true);
            else {
                versionTree[pathname] = stats;
                ok(false);
            }
        });
    });
};

var getVersion = function (pathname) {
    return versionTree[pathname];
};

var asyncLoader = function (curl, temp, key, rebuild) {
    var root = String(this);
    var buffer_size = this.buffer_size;
    var durl = path.resolve(root, curl);
    var durls = [durl];
    var _watch = function (_durls) {
        durls.forEach(durl => watch(durl));
        durls = _durls;
        _durls.forEach(curl => watch(curl, load));
    };
    var pathname = path.join(root, curl);
    var that = this;
    var load = function (loadType) {
        var durls = [durl];
        var is_change = loadType === "change";
        var saved = is_change && temp[key];
        saved = !(saved instanceof Promise || saved instanceof Error) && saved;
        var origin = temp[key];
        var p0 = temp[key] = isdirAsync(pathname).then(function (isdir) {
            if (p0 !== temp[key]) return;
            if (isdir) {
                var p = temp[key] = getdirAsync(pathname).then(function (dirs) {
                    if (p !== temp[key]) return;
                    temp[key] = dirs;
                    if (isDevelop) {
                        is_change = saved && Object.keys(dirs).sort().join(",") !== Object.keys(saved).sort().join(",");
                        if (is_change) message.broadcast('reload');
                    }
                    if (origin) unwatch(pathname, origin);
                    _watch(durls);
                    console.info(root, curl, is_change ? "change" : "load");
                }).catch(function (error) {
                    if (p !== temp[key]) return;
                    if (origin) unwatch(pathname, origin);
                    temp[key] = error;
                    _watch([]);
                });
            } else {
                var p = temp[key] = getfileAsync(pathname, buffer_size).then(function (data) {
                    if (p !== temp[key]) return;
                    try {
                        if (rebuild instanceof Function) {
                            data = rebuild(data, that.getURL(), durl, durls);
                        }
                    } catch (e) {
                        console.warn("Build Faild:", curl, e);
                        data = e;
                    }
                    return data;
                }).then(function (data) {
                    if (p !== temp[key]) return;
                    if (origin) unwatch(pathname, origin);
                    if (typeof data === "string") {
                        data = Buffer.from(data);
                    }
                    temp[key] = data;
                    if (isDevelop) {
                        is_change = saved && (saved instanceof Buffer && Buffer.compare(saved, data) || String(saved) !== String(data));
                        if (is_change) message.broadcast('reload');
                    }
                    console.info(root, curl, is_change ? "change" : "load");
                    _watch(durls);
                }).catch(function (error) {
                    if (p !== temp[key]) return;
                    if (origin) unwatch(pathname, origin);
                    temp[key] = error;
                    console.error(error);
                    _watch([]);
                });
            }
        }).catch(function (error) {
            if (p0 !== temp[key]) return;
            if (origin) unwatch(pathname, origin);
            temp[key] = error;
            console.error(error);
        });
    };
    load();
    return load;
};
var matcherReg = /[A-Z]+/g;
var replaceCase = function (match, index, input) {
    if (match.length === 1) {
        return "-" + match.toLowerCase();
    }
    if (match.length === 2) {
        match = match.toLowerCase();
        return "-" + match[0] + "-" + match[1];
    }
    if (index + match.length === input.length) {
        return "-" + match;
    }
    return '-' + match.slice(0, match.length - 1) + "-" + match[match.length - 1].toLowerCase();
};

var seekAsync = function (url, tree, rebuild) {
    var temp = tree;
    if (!temp) return new Error('file system error');
    var keeys = url.split(/[\\\/]+/);
    var curl = "";
    var that = this;
    var temps = [];

    var research = function () {
        return seekAsync.call(that, url, tree, rebuild);
    };
    search: for (var cx = 0, dx = keeys.length; cx < dx; cx++) {
        var key = keeys[cx];
        if (key === '' || key === '.') continue;
        if (!(key in temp)) {
            let k = key.replace(matcherReg, replaceCase);
            if (k in temp) {
                key = k;
            }
        }
        if (!(key in temp)) {
            if (!that.buffer_size) {
                temp = undefined;
                break;
            }
            for (var cy = temps.length - 1; cy >= 0; cy--) {
                if (key in temps[cy]) {
                    let searched = seekAsync.call(that, keeys.slice(cx).join("/"), temps[cy], rebuild);
                    if (searched instanceof Promise) {
                        return searched.then(research);
                    }
                    if (searched !== undefined) {
                        temp = searched;
                        break search;
                    }
                }
            }
            continue;
        }
        curl = path.join(curl, key);
        if (temp[key] === false) {
            asyncLoader.call(that, curl, temp, key, rebuild);
        }
        temps.push(temp);
        temp = temp[key];
        if (temp instanceof Promise) {
            return temp.then(research);
        }
        if (!temp) break;
    }
    if (!(temp instanceof Object)) {
        return temp;
    }
    if (temp instanceof Function) {
        return temp;
    }
    if (temp instanceof Error) {
        return temp;
    }
    if ((temp instanceof Buffer) && !temp.stat) {
        temp.stat = getVersion(path.join(String(this), curl));
        temp.name = key;
    }
    return temp;
};

/**
 * 取消路径监听
 * @param {string} curl
 * @param {object} temp
 */
var unwatch = function (curl, temp) {
    if (temp instanceof Object) {
        for (var k in temp) {
            var cvrl = path.join(curl, k);
            watch(cvrl);
            unwatch(cvrl, temp[k]);
        }
    }
};
var getExtts = function (extts) {
    if (extts instanceof Array && extts.length <= 1) extts = extts;
    return extts || "";
};
/**
 * 根椐filesroot路径设置文件缓冲
 * @param {string} filesroot
 */
var cache = function (filesroot, rebuild, buffer_size_limit) {
    var sk = function (url, extts) {
    };
    filesroot = filesroot.split(",");
    var tree = filesroot.map((froot, i) => {
        if (fs.existsSync(froot) && fs.statSync(froot).isDirectory()) {
            var roots = getdir(froot);
            watch(froot, function () {
                getdirAsync(froot, function (a) {
                    for (var k in roots) {
                        if (!(k in a)) {
                            delete roots[k];
                            unwatch(path.join(froot, k));
                        }
                    }
                    for (var k in a) {
                        if (!(k in roots)) {
                            roots[k] = false;
                        }
                    }
                    message.broadcast("reload");
                });
            });
            return roots;
        } else {
            return Object.create(null);
        }
    });
    if (isFinite(buffer_size_limit) && buffer_size_limit >= 0) {
        sk.buffer_size = buffer_size_limit | 0;
    }
    var seekerAsync = function (url, extts = "") {
        extts = getExtts(extts);
        if (!Array.isArray(extts)) {
            extts = [extts];
        }
        var seeker = function () { };
        seeker.toString = function () {
            return this;
        }.bind(filesroot[0]);
        seeker.getURL = function () {
            return url;
        };
        seeker.buffer_size = sk.buffer_size;
        return new Promise(function (ok, oh) {
            var cy = 0;
            var cx = 0;
            var result, matchParent;
            var run = function () {
                if (cx >= extts.length) {
                    cy++;
                    if (cy >= tree.length) {
                        if (result === undefined) {
                            if (matchParent) {
                                url = url.replace(/\\/g, '/');
                                if (!/\/$/.test(url)) {
                                    url += '/';
                                    result = url;
                                }
                            }
                        }
                        return ok(result);
                    }
                    seeker.toString = function () {
                        return this;
                    }.bind(filesroot[cy]);
                    cx = 0;
                }
                var tree1 = tree[cy];
                var extt = extts[cx];
                var error;
                var promise = seekAsync.call(seeker, url + extt, tree1, rebuild);
                if (promise instanceof Promise) {
                    promise.catch(function (e) {
                        error = e;
                    }).then(function (result) {
                        if (result instanceof Buffer) return ok(result);
                        if (error) oh(error);
                        else run();
                    });
                } else {

                    if (promise instanceof Buffer || promise instanceof Function) return ok(promise);
                    if (promise instanceof Object && !result) {
                        var package_file = "package.json";
                        if (package_file in promise) {
                            if (promise[package_file] === false) {
                                seekAsync.call(seeker, url + extt + "/" + package_file, tree1, a => JSON.parse(String(a))).catch(oh).then(run);
                                return;
                            } else if (promise[package_file] instanceof Buffer) {
                                promise[package_file] = JSON.parse(promise[package_file].toString());
                            }
                            var package_data = promise[package_file];
                            if (package_data instanceof Object && package_data.main) {
                                var roots = package_data.main.split(/[\/\\]+/).filter(a => a && a !== '.' && !/\:$/.test(a));
                                if (roots[0] in promise) {
                                    result = path.join(url, roots.join('/')).replace(/\\/g, '/');
                                    return ok(result);
                                }
                            }
                        } else {
                            var seek_index = 'index';
                            var index = extts.findIndex(a => seek_index + a in promise);
                            if (~index) {
                                result = path.join(url, seek_index + extts[index]).replace(/\\/g, '/');
                            } else {
                                if (typeof promise === 'string') result = promise;
                            }
                        }
                        matchParent = true;
                    }
                    cx++;
                    run();
                }

            };
            run();
        });
    };
    sk.async = seekerAsync;
    sk.new = cache;
    return sk;
};
var _reload_handlers = [];
cache.onreload = function (handler) {
    if (handler instanceof Function) _reload_handlers.push(handler);
};
module.exports = cache;<|endoftext|>


<commit_before>

// demo for freewall layout;
// created by Minh Nguyen;
(function($) {

	var setting = {}, wall;

	var colour = [
		"#16A085",
		"#27AE60",
		"#2980B9",
		"#8E44AD",
		"#2C3E50",
		"#F39C12",
		"#D35400",
		"#C0392B",
		"#870000"
	];

	var func = {
		preload: function() {
			var images = []
			for (var i = 1 ; i < 50 ; ++i) {
				images[i] = new Image();
				images[i].src = "example/i/photo/" + i + ".jpg";
				images[i].onload = function() {
					//window["console"] && console.log(this.src);
				}
			}
		},
		color: function(value) {
			$(".free-wall .brick").each(function() {
				var backgroundColor = colour[colour.length * Math.random() << 0];
				var bricks = $(this).find(".nested");
				!bricks.length && (bricks = $(this));
				bricks.css({
					backgroundColor: backgroundColor
				});
				bricks.attr("data-bgcolor", backgroundColor);
			});
		},
		layout: function() {
			var lwidth = $(window).width();
			wall = new freewall('.free-wall');
			//wall.container.width('auto')
			wall.reset({
				selector: '> div',
				animate: true,
				cellW: 160,
				cellH: 160,
				onResize: function() {
					var cwidth = wall.container.width();
					wall.container.find('.full-width')
					.each(function(index, item){
						wall.fixSize({
							block: item,
							width: cwidth
						});
					});
					wall.fitWidth();
				}
			});
			wall.fitWidth();
			$(window).trigger("resize");

			wall.container.find(".brick").each(function() {
				var $item = $(this);
				$item.attr({
					"data-class": $item.attr("class"),
					"data-style": $item.attr("style")
				});
			});

			// for responsive demo;
			$(".reponsive-block li>a").click(function() {
				var viewWidth = $(window).width();
				var preWidth = $(this).data("width");

				if (preWidth != "auto" && (preWidth - viewWidth) > 0) {
					alert('The screen\'s width not enought to test this size');
					return;
				}

				$(".reponsive-block li>a").removeClass("active");
				var preWidth = $(this).data("width");
				var margin = "10px auto";
				preWidth == "auto" && (margin = "10px");
				wall.container.css({
					margin: margin,
					width: preWidth
				});

				$(this).addClass("active");
				var cwidth = wall.container.width();
				wall.container.find('.full-width')
				.each(function(index, item){
					wall.fixSize({
						block: item,
						width: cwidth * 0.88
					});
				});
				wall.fitWidth();
			});

			if ("onhashchange" in window) {
			    window.onhashchange = function () {
			        hashChanged(window.location.hash);
			    }
			} else {
			    var storedHash = window.location.hash;
			   	setInterval(function () {
			        if (window.location.hash != storedHash) {
			            storedHash = window.location.hash;
			            hashChanged(storedHash);
			        }
			    }, 100);
			}

			function hashChanged(hash) {
				if (!hash || hash == "#") {
					wall.container.find(".brick").each(function() {
						var $item = $(this).removeAttr("style");

						$item.removeAttr("data-width");
						$item.removeAttr("data-height");

						$item.attr({
							"class": $item.attr("data-class")
						});

						$item.css({
							backgroundColor: $item.attr("data-bgcolor")
						});
					});

					wall.unFilter();
					$(".back-button").hide();
					$(".free-wall-logo").show();
				} else {
					$(hash).trigger("click");
					$(".back-button").show();
					$(".free-wall-logo").hide();
				}
				$(".header")[0].scrollIntoView(true);
			}

			// for back-button;
			$(".back-button .back-icon").click(function() {
				window.location.hash = "";
			});
		},
		logo: function() {
			var wall = new freewall('.free-wall-logo');
			var temp = "

";
			var colour = [
				"#DAA520",
				"#CD950C",
				"#EEB422",
				"#CD9B1D"
			];

			var w = 1, h = 1, html = '', color = '', limitItem = 820;
			for (var i = 0; i < limitItem; ++i) {
				h = 1;
				w = 2 + 4 * Math.random() << 0;
				color = colour[colour.length * Math.random() << 0];
				html += temp.replace(/\{height\}/g, h*20).replace(/\{width\}/g, w*15).replace("{color}", color);
			}
			wall.container.html(html);
			wall.reset({
				selector: '.cell',
				animate: true,
				cellW: 15,
				cellH: 20,
				gutterX: 2,
				gutterY: 2,
				delay: 10,
				onResize: function() {
					this.refresh();
					var totalCol = this.container.attr('data-total-col');
					var offsetLeft = Math.round(totalCol/2 - 16);
					this.setHoles(getPosition(offsetLeft));
					this.refresh();
				},
				onStartSet: function(block, setting) {
					// check for showing brick;
					if (block != null) {
						$(this).css({
							top: - 10000,
							left: block.left
						});
					} else {
						$(this).css({
							opacity: 0
						})
					}
				},
				onComplete: function() {
					wall.reset({
						delay: 0,
						animate: false,
						onStartSet: function() {}
					})
				}
			});

			function getPosition(offsetLeft) {
				return [
					// F
					{
						top: 3,
						left: offsetLeft,
						width: 9,
						height: 3
					},
					{
						top: 5,
						left: offsetLeft,
						width: 3,
						height: 14
					},
					{
						top: 9,
						left: offsetLeft,
						width: 7,
						height: 3
					},
					// r
					{
						top: 9,
						left: offsetLeft + 11,
						width: 2,
						height: 10
					},
					{
						top: 11,
						left: offsetLeft + 13,
						width: 1,
						height: 2
					},
					{
						top: 10,
						left: offsetLeft + 14,
						width: 1,
						height: 2
					},
					{
						top: 9,
						left: offsetLeft + 15,
						width: 2,
						height: 2
					},
					// e
					{
						top: 9,
						left: offsetLeft + 19,
						width: 2,
						height: 10
					},
					{
						top: 9,
						left: offsetLeft + 19,
						width: 4,
						height: 2
					},
					{
						top: 9,
						left: offsetLeft + 23,
						width: 2,
						height: 6
					},
					{
						top: 13,
						left: offsetLeft + 19,
						width: 4,
						height: 2
					},
					{
						top: 17,
						left: offsetLeft + 19,
						width: 5,
						height: 2
					},
					// e
					{
						top: 9,
						left: offsetLeft + 27,
						width: 2,
						height: 10
					},
					{
						top: 9,
						left: offsetLeft + 27,
						width: 4,
						height: 2
					},
					{
						top: 9,
						left: offsetLeft + 31,
						width: 2,
						height: 6
					},
					{
						top: 13,
						left: offsetLeft + 27,
						width: 4,
						height: 2
					},
					{
						top: 17,
						left: offsetLeft + 27,
						width: 5,
						height: 2
					}
				];
			}
			wall.fitZone();
			var totalCol = wall.container.attr('data-total-col');
			var offsetLeft = Math.round(totalCol/2 - 16);
			wall.setHoles(getPosition(offsetLeft));
			wall.refresh();
		},
		options: function() {
			$('.free-wall .options').click(function() {
				var cwidth = wall.container.width() - 10;
				var dna = $(this);
				if (!dna.hasClass('full-width')) {
					dna.addClass('full-width');
					wall.fixSize({
						block: dna,
						width: cwidth,
						height: 2000
					});
					wall.filter('.options');
					window.location.hash = "options";
				}
			});
		},
		events: function() {
			$('.free-wall .events').click(function() {
				var cwidth = wall.container.width() - 10;
				var dna = $(this);
				if (!dna.hasClass('full-width')) {
					dna.addClass('full-width');
					wall.fixSize({
						block: dna,
						width: cwidth,
						height: 720
					});
					wall.filter('.events');
					window.location.hash = "events";
				}
			});
		},
		methods: function() {
			$('.free-wall .methods').click(function() {
				var cwidth = wall.container.width() - 10;
				var dna = $(this);
				if (!dna.hasClass('full-width')) {
					dna.addClass('full-width');
					wall.fixSize({
						block: dna,
						width: cwidth,
						height: 2100
					});
					wall.filter('.methods');
					window.location.hash = "methods";
				}
			});
		},
		share: function() {
			var leftPosition, topPosition, width = 500, height = 300;
				leftPosition = (window.screen.width / 2) - ((width / 2) + 10);
				topPosition = (window.screen.height / 2) - ((height / 2) + 50);
			var windowFeatures = "status=no, height=" + height + ", width=" + width + ", resizable=yes, left=" + leftPosition + ", top=" + topPosition + ", screenX=" + leftPosition + ", screenY=" + topPosition + ", toolbar=no, menubar=no, scrollbars=no, location=no, directories=no";

			$(".free-wall .facebook-share").click(function() {
				window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(location.href), 'sharer', windowFeatures);
			});

			$(".free-wall .google-share").click(function() {
				window.open('https://plus.google.com/share?url=' + encodeURIComponent(location.href), 'sharer', windowFeatures);
			});

			$(".free-wall .twitter-share").click(function() {
				window.open("https://twitter.com/intent/tweet?original_referer=''&url=''&text=" + encodeURIComponent(location.href) , '_blank', windowFeatures);
			});
		},
		finish: function() {
			if (window.location.hash && $(window.location.hash).length) {
				$(window.location.hash).trigger("click");
				$('.back-button').show();
				$(".free-wall-logo").hide();
			}
		}
	};

	window.app = {
		config: function(key, data) {
			setting[key] = data;
		},
		setup: function(options) {
			for (var i in options) {
				if (options.hasOwnProperty(i)) {
					func[i](options[i]);
				}
			}
			func['finish']();
		}
	};

})(window.Zepto || window.jQuery);
<commit_msg>add the "wall"<commit_after>

// demo for freewall layout;
// created by Minh Nguyen;
(function($) {

	var setting = {}, wall;

	var colour = [
		"#16A085",
		"#27AE60",
		"#2980B9",
		"#8E44AD",
		"#2C3E50",
		"#F39C12",
		"#D35400",
		"#C0392B",
		"#870000"
	];

	var func = {
		preload: function() {
			var images = []
			for (var i = 1 ; i < 50 ; ++i) {
				images[i] = new Image();
				images[i].src = "example/i/photo/" + i + ".jpg";
				images[i].onload = function() {
					//window["console"] && console.log(this.src);
				}
			}
		},
		color: function(value) {
			$(".free-wall .brick").each(function() {
				var backgroundColor = colour[colour.length * Math.random() << 0];
				var bricks = $(this).find(".nested");
				!bricks.length && (bricks = $(this));
				bricks.css({
					backgroundColor: backgroundColor
				});
				bricks.attr("data-bgcolor", backgroundColor);
			});
		},
		layout: function() {
			var lwidth = $(window).width();
			wall = new freewall('.free-wall');
			//wall.container.width('auto')
			wall.reset({
				selector: '> div',
				animate: true,
				cellW: 160,
				cellH: 160,
				onResize: function() {
					var cwidth = wall.container.width();
					wall.container.find('.full-width')
					.each(function(index, item){
						wall.fixSize({
							block: item,
							width: cwidth
						});
					});
					wall.fitWidth();
				}
			});
			wall.fitWidth();
			$(window).trigger("resize");

			wall.container.find(".brick").each(function() {
				var $item = $(this);
				$item.attr({
					"data-class": $item.attr("class"),
					"data-style": $item.attr("style")
				});
			});

			// for responsive demo;
			$(".reponsive-block li>a").click(function() {
				var viewWidth = $(window).width();
				var preWidth = $(this).data("width");

				if (preWidth != "auto" && (preWidth - viewWidth) > 0) {
					alert('The screen\'s width not enought to test this size');
					return;
				}

				$(".reponsive-block li>a").removeClass("active");
				var preWidth = $(this).data("width");
				var margin = "10px auto";
				preWidth == "auto" && (margin = "10px");
				wall.container.css({
					margin: margin,
					width: preWidth
				});

				$(this).addClass("active");
				var cwidth = wall.container.width();
				wall.container.find('.full-width')
				.each(function(index, item){
					wall.fixSize({
						block: item,
						width: cwidth * 0.88
					});
				});
				wall.fitWidth();
			});

			if ("onhashchange" in window) {
			    window.onhashchange = function () {
			        hashChanged(window.location.hash);
			    }
			} else {
			    var storedHash = window.location.hash;
			   	setInterval(function () {
			        if (window.location.hash != storedHash) {
			            storedHash = window.location.hash;
			            hashChanged(storedHash);
			        }
			    }, 100);
			}

			function hashChanged(hash) {
				if (!hash || hash == "#") {
					wall.container.find(".brick").each(function() {
						var $item = $(this).removeAttr("style");

						$item.removeAttr("data-width");
						$item.removeAttr("data-height");

						$item.attr({
							"class": $item.attr("data-class")
						});

						$item.css({
							backgroundColor: $item.attr("data-bgcolor")
						});
					});

					wall.unFilter();
					$(".back-button").hide();
					$(".free-wall-logo").show();
				} else {
					$(hash).trigger("click");
					$(".back-button").show();
					$(".free-wall-logo").hide();
				}
				$(".header")[0].scrollIntoView(true);
			}

			// for back-button;
			$(".back-button .back-icon").click(function() {
				window.location.hash = "";
			});
		},
		logo: function() {
			var wall = new freewall('.free-wall-logo');
			var temp = "

";
			var colour = [
				"#DAA520",
				"#CD950C",
				"#EEB422",
				"#CD9B1D"
			];

			var w = 1, h = 1, html = '', color = '', limitItem = 820;
			for (var i = 0; i < limitItem; ++i) {
				h = 1;
				w = 2 + 4 * Math.random() << 0;
				color = colour[colour.length * Math.random() << 0];
				html += temp.replace(/\{height\}/g, h*20).replace(/\{width\}/g, w*15).replace("{color}", color);
			}
			wall.container.html(html);
			wall.reset({
				selector: '.cell',
				animate: true,
				cellW: 15,
				cellH: 20,
				gutterX: 2,
				gutterY: 2,
				delay: 20,
				onResize: function() {
					this.refresh();
					var totalCol = this.container.attr('data-total-col');
					var offsetLeft = Math.round(totalCol/2 - 31);
					this.setHoles(getPosition(offsetLeft));
					this.refresh();
				},
				onStartSet: function(block, setting) {
					// check for showing brick;
					if (block != null) {
						$(this).css({
							top: - 10000,
							left: block.left
						});
					} else {
						$(this).css({
							opacity: 0
						})
					}
				},
				onComplete: function() {
					wall.reset({
						delay: 0,
						animate: false,
						onStartSet: function() {}
					})
				}
			});

			function getPosition(offsetLeft) {
				return [
					// F
					{
						top: 3,
						left: offsetLeft,
						width: 9,
						height: 3
					},
					{
						top: 5,
						left: offsetLeft,
						width: 3,
						height: 14
					},
					{
						top: 9,
						left: offsetLeft,
						width: 7,
						height: 3
					},
					// r
					{
						top: 9,
						left: offsetLeft + 11,
						width: 2,
						height: 10
					},
					{
						top: 11,
						left: offsetLeft + 13,
						width: 1,
						height: 2
					},
					{
						top: 10,
						left: offsetLeft + 14,
						width: 1,
						height: 2
					},
					{
						top: 9,
						left: offsetLeft + 15,
						width: 2,
						height: 2
					},
					// e
					{
						top: 9,
						left: offsetLeft + 19,
						width: 2,
						height: 10
					},
					{
						top: 9,
						left: offsetLeft + 19,
						width: 4,
						height: 2
					},
					{
						top: 9,
						left: offsetLeft + 23,
						width: 2,
						height: 6
					},
					{
						top: 13,
						left: offsetLeft + 19,
						width: 4,
						height: 2
					},
					{
						top: 17,
						left: offsetLeft + 19,
						width: 5,
						height: 2
					},
					// e
					{
						top: 9,
						left: offsetLeft + 27,
						width: 2,
						height: 10
					},
					{
						top: 9,
						left: offsetLeft + 27,
						width: 4,
						height: 2
					},
					{
						top: 9,
						left: offsetLeft + 31,
						width: 2,
						height: 6
					},
					{
						top: 13,
						left: offsetLeft + 27,
						width: 4,
						height: 2
					},
					{
						top: 17,
						left: offsetLeft + 27,
						width: 5,
						height: 2
					},

					// W
					{
						top: 6,
						left: offsetLeft + 37,
						width: 2,
						height: 12
					},
					{
						top: 17,
						left: offsetLeft + 39,
						width: 6,
						height: 2
					},
					{
						top: 12,
						left: offsetLeft + 41,
						width: 2,
						height: 5
					},
					{
						top: 6,
						left: offsetLeft + 45,
						width: 2,
						height: 12
					},
					//a
					{
						top: 9,
						left: offsetLeft + 50,
						width: 3,
						height: 2
					},
					{
						top: 9,
						left: offsetLeft + 53,
						width: 2,
						height: 10
					},
					{
						top: 13,
						left: offsetLeft + 49,
						width: 4,
						height: 2
					},
					{
						top: 15,
						left: offsetLeft + 49,
						width: 2,
						height: 2
					},
					{
						top: 17,
						left: offsetLeft + 49,
						width: 4,
						height: 2
					},
					//l
					{
						top: 6,
						left: offsetLeft + 57,
						width: 2,
						height: 13
					},
					//l
					{
						top: 6,
						left: offsetLeft + 61,
						width: 2,
						height: 13
					},

				];
			}
			wall.fitZone();
			var totalCol = wall.container.attr('data-total-col');
			var offsetLeft = Math.round(totalCol/2 - 31);
			wall.setHoles(getPosition(offsetLeft));
			wall.refresh();
		},
		options: function() {
			$('.free-wall .options').click(function() {
				var cwidth = wall.container.width() - 10;
				var dna = $(this);
				if (!dna.hasClass('full-width')) {
					dna.addClass('full-width');
					wall.fixSize({
						block: dna,
						width: cwidth,
						height: 2000
					});
					wall.filter('.options');
					window.location.hash = "options";
				}
			});
		},
		events: function() {
			$('.free-wall .events').click(function() {
				var cwidth = wall.container.width() - 10;
				var dna = $(this);
				if (!dna.hasClass('full-width')) {
					dna.addClass('full-width');
					wall.fixSize({
						block: dna,
						width: cwidth,
						height: 720
					});
					wall.filter('.events');
					window.location.hash = "events";
				}
			});
		},
		methods: function() {
			$('.free-wall .methods').click(function() {
				var cwidth = wall.container.width() - 10;
				var dna = $(this);
				if (!dna.hasClass('full-width')) {
					dna.addClass('full-width');
					wall.fixSize({
						block: dna,
						width: cwidth,
						height: 2100
					});
					wall.filter('.methods');
					window.location.hash = "methods";
				}
			});
		},
		share: function() {
			var leftPosition, topPosition, width = 500, height = 300;
				leftPosition = (window.screen.width / 2) - ((width / 2) + 10);
				topPosition = (window.screen.height / 2) - ((height / 2) + 50);
			var windowFeatures = "status=no, height=" + height + ", width=" + width + ", resizable=yes, left=" + leftPosition + ", top=" + topPosition + ", screenX=" + leftPosition + ", screenY=" + topPosition + ", toolbar=no, menubar=no, scrollbars=no, location=no, directories=no";

			$(".free-wall .facebook-share").click(function() {
				window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(location.href), 'sharer', windowFeatures);
			});

			$(".free-wall .google-share").click(function() {
				window.open('https://plus.google.com/share?url=' + encodeURIComponent(location.href), 'sharer', windowFeatures);
			});

			$(".free-wall .twitter-share").click(function() {
				window.open("https://twitter.com/intent/tweet?original_referer=''&url=''&text=" + encodeURIComponent(location.href) , '_blank', windowFeatures);
			});
		},
		finish: function() {
			if (window.location.hash && $(window.location.hash).length) {
				$(window.location.hash).trigger("click");
				$('.back-button').show();
				$(".free-wall-logo").hide();
			}
		}
	};

	window.app = {
		config: function(key, data) {
			setting[key] = data;
		},
		setup: function(options) {
			for (var i in options) {
				if (options.hasOwnProperty(i)) {
					func[i](options[i]);
				}
			}
			func['finish']();
		}
	};

})(window.Zepto || window.jQuery);
<|endoftext|>


<commit_before>'use strict'

// implementation-state main module

// require implementation-state modules
const impStateModelValidation = require('./impStateModelValidation.js')
const impStateOverview = require('./impStateOverview.js')
const addImpStateComponent = require('./addImpStateComponent.js')
const addImpStateEdge = require('./addImpStateEdge.js')

// require global modules
const totalNodes = require('../totalNodes')

// add imp-state nodes
const addNode = (cy) => {
  const addNode = document.getElementById('add-component-id')
  addNode.addEventListener('change', (e) => {
    addImpStateComponent(cy, e.target.value) // imp-state module
    cy.nodes().addClass('label-nodes')
    // reset moduleGroup selection
    document.getElementById('add-component-id').selectedIndex = ''
    totalNodes(cy) // global module
  })
}

// add imp-state edges
const addEdge = (cy, srcNode, trgNode, srcNodeCpt, trgNodeCpt) => {
  const buttonAddEdge = document.getElementById('add-edge')
  buttonAddEdge.addEventListener('click', () => {
    addImpStateEdge(cy, srcNode, trgNode, srcNodeCpt, trgNodeCpt)
    cy.edges().addClass('label-edges')
    totalNodes(cy) // global module
  })
}

// validate model
const validate = (cy) => {
  const buttonModelValidate = document.getElementById('model-validate-button')
  buttonModelValidate.addEventListener('click', () => {
    impStateModelValidation(cy) // imp-state module
  })
}

// model overview
const overview = (cy) => {
  const buttonOverview = document.getElementById('overview-button')
  buttonOverview.addEventListener('click', () => {
    impStateOverview(cy) // imp-state module
  })
}

module.exports = {
  addNode: addNode,
  addEdge: addEdge,
  validate: validate,
  overview: overview
}
<commit_msg>typos<commit_after>'use strict'

// implementation-state main module

// require implementation-state modules
const impStateModelValidation = require('./impStateModelValidation.js')
const impStateOverview = require('./impStateOverview.js')
const addImpStateComponent = require('./addImpStateComponent.js')
const addImpStateEdge = require('./addImpStateEdge.js')

// require global modules
const totalNodes = require('../totalNodes.js')

// add imp-state nodes
const addNode = (cy) => {
  const addNode = document.getElementById('add-component-id')
  addNode.addEventListener('change', (e) => {
    addImpStateComponent(cy, e.target.value) // imp-state module
    cy.nodes().addClass('label-nodes')
    // reset moduleGroup selection
    document.getElementById('add-component-id').selectedIndex = ''
    totalNodes(cy) // global module
  })
}

// add imp-state edges
const addEdge = (cy, srcNode, trgNode, srcNodeCpt, trgNodeCpt) => {
  const buttonAddEdge = document.getElementById('add-edge')
  buttonAddEdge.addEventListener('click', () => {
    addImpStateEdge(cy, srcNode, trgNode, srcNodeCpt, trgNodeCpt)
    cy.edges().addClass('label-edges')
    totalNodes(cy) // global module
  })
}

// validate model
const validate = (cy) => {
  const buttonModelValidate = document.getElementById('model-validate-button')
  buttonModelValidate.addEventListener('click', () => {
    impStateModelValidation(cy) // imp-state module
  })
}

// model overview
const overview = (cy) => {
  const buttonOverview = document.getElementById('overview-button')
  buttonOverview.addEventListener('click', () => {
    impStateOverview(cy) // imp-state module
  })
}

module.exports = {
  addNode: addNode,
  addEdge: addEdge,
  validate: validate,
  overview: overview
}
<|endoftext|>