<commit_before>d3.sankey = function() {
 "use strict";
  var sankey = {},
      nodeWidth = 24,
      nodePadding = 8,
      size = [1, 1],
      nodes = [],
      links = [],
      sinksRight = true;

  // Accessor-land:
  sankey.nodeWidth = function(x) {
    if (x === undefined) { return nodeWidth; }
    nodeWidth = +x;
    return sankey;
  };

  sankey.nodePadding = function(x) {
    if (x === undefined) { return nodePadding; }
    nodePadding = +x;
    return sankey;
  };

  sankey.nodes = function(x) {
    if (x === undefined) { return nodes; }
    nodes = x;
    return sankey;
  };

  sankey.links = function(x) {
    if (x === undefined) { return links; }
    links = x;
    return sankey;
  };

  sankey.size = function(x) {
    if (x === undefined) { return size; }
    size = x;
    return sankey;
  };

 sankey.sinksRight = function (x) {
    if (x === undefined) { return sinksRight; }
    sinksRight = x;
    return sankey;
 };

  // valueSum: Add up all the 'value' keys from a list of objects (happens a lot):
  function valueSum(nodelist) {
    return d3.sum(nodelist, function(d) { return d.value; });
  }

  // center: Y-position of the middle of a node.
  function center(node) { return node.y + node.dy / 2; }

  // Populate the sourceLinks and targetLinks for each node.
  // Also, if the source and target are not objects, assume they are indices.
  function computeNodeLinks() {
    nodes.forEach(function(node) {
      // Links that have this node as source.
      node.sourceLinks = [];
      // Links that have this node as target.
      node.targetLinks = [];
    });
    links.forEach(function(link) {
      var source = link.source,
          target = link.target;
      if (typeof source === "number") { source = link.source = nodes[link.source]; }
      if (typeof target === "number") { target = link.target = nodes[link.target]; }
      source.sourceLinks.push(link);
      target.targetLinks.push(link);
    });
  }

  // Compute the value (size) of each node by summing the associated links.
  function computeNodeValues() {
    // Each node will equal the greater of the flows coming in or out:
    nodes.forEach(function(node) {
      node.value = Math.max( valueSum(node.sourceLinks), valueSum(node.targetLinks) );
    });
  }

  function moveSourcesRight() {
    nodes.forEach(function(node) {
      if (!node.targetLinks.length) {
        node.x = d3.min(node.sourceLinks, function(d) { return d.target.x; }) - 1;
      }
    });
  }

  function moveSinksRight(x) {
    nodes.forEach(function(node) {
      if (!node.sourceLinks.length) {
        node.x = x - 1;
      }
    });
  }

  function scaleNodeBreadths(kx) {
    nodes.forEach(function(node) {
      node.x *= kx;
    });
  }

  // Compute y-offset of the source endpoint (sy) and target endpoints (ty) of links,
  // relative to the source/target node's y-position.
  function computeLinkDepths() {
    function ascendingSourceDepth(a, b) { return a.source.y - b.source.y; }
    function ascendingTargetDepth(a, b) { return a.target.y - b.target.y; }

    nodes.forEach(function(node) {
      node.sourceLinks.sort(ascendingTargetDepth);
      node.targetLinks.sort(ascendingSourceDepth);
    });
    nodes.forEach(function(node) {
      var sy = 0, ty = 0;
      node.sourceLinks.forEach(function(link) {
        link.sy = sy;
        sy += link.dy;
      });
      node.targetLinks.forEach(function(link) {
        link.ty = ty;
        ty += link.dy;
      });
    });
  }

  // Iteratively assign the breadth (x-position) for each node.
  // Nodes are assigned the maximum breadth of incoming neighbors plus one;
  // nodes with no incoming links are assigned breadth zero, while
  // nodes with no outgoing links are assigned the maximum breadth.
  function computeNodeBreadths() {
    var remainingNodes = nodes,
        nextNodes,
        x = 0;

    function updateNode(node) {
        // Set x-position and width:
        node.x = x;
        node.dx = nodeWidth;
        node.sourceLinks.forEach(function(link) {
          // Only add it to the nextNodes list if it is not already present:
          if (nextNodes.indexOf(link.target) === -1) {
            nextNodes.push(link.target);
          }
        });
    }

    // Work from left to right.
    // Keep updating the breadth (x-position) of nodes that are targets of
    // recently-updated nodes.
    while (remainingNodes.length && x < nodes.length) {
      nextNodes = [];
      remainingNodes.forEach(updateNode);
      remainingNodes = nextNodes;
      x += 1;
    }

    // Optionally move pure sinks always to the right.
    if (sinksRight) {
      moveSinksRight(x);
    }

    scaleNodeBreadths((size[0] - nodeWidth) / (x - 1));
  }

  // Compute the depth (y-position) for each node.
  function computeNodeDepths(iterations) {
    var alpha = 1,
        // Group nodes by breadth:
        nodesByBreadth = d3.nest()
        .key(function(d) { return d.x; })
        .sortKeys(d3.ascending)
        .entries(nodes)
        .map(function(d) { return d.values; });

    function initializeNodeDepth() {
      // Calculate vertical scaling factor.
      var ky = d3.min(nodesByBreadth, function(nodes) {
        return (size[1] - (nodes.length - 1) * nodePadding) / valueSum(nodes);
      });

      nodesByBreadth.forEach(function(nodes) {
        nodes.forEach(function(node, i) {
          node.y = i;
          node.dy = node.value * ky;
        });
      });

      links.forEach(function(link) {
        link.dy = link.value * ky;
      });
    }

    function resolveCollisions() {
      nodesByBreadth.forEach(function(nodes) {
        var node,
            dy,
            y0 = 0,
            n = nodes.length,
            i;

        function ascendingDepth(a, b) { return a.y - b.y; }

        // Push any overlapping nodes down.
        nodes.sort(ascendingDepth);
        for (i = 0; i < n; i += 1) {
          node = nodes[i];
          dy = y0 - node.y;
          if (dy > 0) { node.y += dy; }
          y0 = node.y + node.dy + nodePadding;
        }

        // If the bottommost node goes outside the bounds, push it back up.
        dy = y0 - nodePadding - size[1];
        if (dy > 0) {
          y0 = node.y -= dy;

          // Push any overlapping nodes back up.
          for (i = n - 2; i >= 0; i -= 1) {
            node = nodes[i];
            dy = node.y + node.dy + nodePadding - y0;
            if (dy > 0) { node.y -= dy; }
            y0 = node.y;
          }
        }
      });
    }

    function relaxLeftToRight(alpha) {
      function weightedSource(link) {
        return (link.source.y + link.sy + link.dy / 2) * link.value;
      }

      nodesByBreadth.forEach(function(nodes) {
        nodes.forEach(function(node) {
          if (node.targetLinks.length) {
            // Value-weighted average of the y-position of source node centers linked to this node.
            var y = d3.sum(node.targetLinks, weightedSource) / valueSum(node.targetLinks);
            node.y += (y - center(node)) * alpha;
          }
        });
      });
    }

    function relaxRightToLeft(alpha) {
      function weightedTarget(link) {
        return (link.target.y + link.ty + link.dy / 2) * link.value;
      }

      nodesByBreadth.slice().reverse().forEach(function(nodes) {
        nodes.forEach(function(node) {
          if (node.sourceLinks.length) {
            // Value-weighted average of the y-positions of target nodes linked to this node.
            var y = d3.sum(node.sourceLinks, weightedTarget) / valueSum(node.sourceLinks);
            node.y += (y - center(node)) * alpha;
          }
        });
      });
    }

    //
    initializeNodeDepth();
    resolveCollisions();
    computeLinkDepths();

    while (iterations > 0) {
      iterations -= 1;

      // Make each round of moves progressively weaker:
      alpha *= 0.99;
      relaxRightToLeft(alpha);
      resolveCollisions();
      computeLinkDepths();

      relaxLeftToRight(alpha);
      resolveCollisions();
      computeLinkDepths();
    }
  }

  // SVG path data generator, to be used as "d" attribute on "path" element selection.
  sankey.link = function() {
    var curvature = 0.5;

    function link(d) {
      var x0 = d.source.x + d.source.dx,
          x1 = d.target.x,
          xi = d3.interpolateNumber(x0, x1),
          x2 = xi(curvature),
          x3 = xi(1 - curvature),
          y0 = d.source.y + d.sy + d.dy / 2,
          y1 = d.target.y + d.ty + d.dy / 2;
      return "M" + x0 + "," + y0
           + "C" + x2 + "," + y0
           + " " + x3 + "," + y1
           + " " + x1 + "," + y1;
    }

    link.curvature = function(x) {
      if (x === undefined) { return curvature; }
      curvature = +x;
      return link;
    };

    return link;
  };

  sankey.layout = function(iterations) {
    computeNodeLinks();
    computeNodeValues();
    computeNodeBreadths();
    computeNodeDepths(iterations);
    return sankey;
  };

  sankey.relayout = function() {
    computeLinkDepths();
    return sankey;
  };

  return sankey;
};
<commit_msg>Hoist 'curvature' to be a top-level variable.<commit_after>d3.sankey = function() {
 "use strict";
  var sankey = {},
      nodeWidth = 24,
      nodePadding = 8,
      size = [1, 1],
      nodes = [],
      links = [],
      sinksRight = true,
      curvature = 0.5;

  // Accessor-land:
  sankey.curvature = function(x) {
    if (x === undefined) { return curvature; }
    curvature = +x;
    return sankey;
  };

  sankey.nodeWidth = function(x) {
    if (x === undefined) { return nodeWidth; }
    nodeWidth = +x;
    return sankey;
  };

  sankey.nodePadding = function(x) {
    if (x === undefined) { return nodePadding; }
    nodePadding = +x;
    return sankey;
  };

  sankey.nodes = function(x) {
    if (x === undefined) { return nodes; }
    nodes = x;
    return sankey;
  };

  sankey.links = function(x) {
    if (x === undefined) { return links; }
    links = x;
    return sankey;
  };

  sankey.size = function(x) {
    if (x === undefined) { return size; }
    size = x;
    return sankey;
  };

 sankey.sinksRight = function (x) {
    if (x === undefined) { return sinksRight; }
    sinksRight = x;
    return sankey;
 };

  // valueSum: Add up all the 'value' keys from a list of objects (happens a lot):
  function valueSum(nodelist) {
    return d3.sum(nodelist, function(d) { return d.value; });
  }

  // center: Y-position of the middle of a node.
  function center(node) { return node.y + node.dy / 2; }

  // Populate the sourceLinks and targetLinks for each node.
  // Also, if the source and target are not objects, assume they are indices.
  function computeNodeLinks() {
    nodes.forEach(function(node) {
      // Links that have this node as source.
      node.sourceLinks = [];
      // Links that have this node as target.
      node.targetLinks = [];
    });
    links.forEach(function(link) {
      var source = link.source,
          target = link.target;
      if (typeof source === "number") { source = link.source = nodes[link.source]; }
      if (typeof target === "number") { target = link.target = nodes[link.target]; }
      source.sourceLinks.push(link);
      target.targetLinks.push(link);
    });
  }

  // Compute the value (size) of each node by summing the associated links.
  function computeNodeValues() {
    // Each node will equal the greater of the flows coming in or out:
    nodes.forEach(function(node) {
      node.value = Math.max( valueSum(node.sourceLinks), valueSum(node.targetLinks) );
    });
  }

  function moveSourcesRight() {
    nodes.forEach(function(node) {
      if (!node.targetLinks.length) {
        node.x = d3.min(node.sourceLinks, function(d) { return d.target.x; }) - 1;
      }
    });
  }

  function moveSinksRight(x) {
    nodes.forEach(function(node) {
      if (!node.sourceLinks.length) {
        node.x = x - 1;
      }
    });
  }

  function scaleNodeBreadths(kx) {
    nodes.forEach(function(node) {
      node.x *= kx;
    });
  }

  // Compute y-offset of the source endpoint (sy) and target endpoints (ty) of links,
  // relative to the source/target node's y-position.
  function computeLinkDepths() {
    function ascendingSourceDepth(a, b) { return a.source.y - b.source.y; }
    function ascendingTargetDepth(a, b) { return a.target.y - b.target.y; }

    nodes.forEach(function(node) {
      node.sourceLinks.sort(ascendingTargetDepth);
      node.targetLinks.sort(ascendingSourceDepth);
    });
    nodes.forEach(function(node) {
      var sy = 0, ty = 0;
      node.sourceLinks.forEach(function(link) {
        link.sy = sy;
        sy += link.dy;
      });
      node.targetLinks.forEach(function(link) {
        link.ty = ty;
        ty += link.dy;
      });
    });
  }

  // Iteratively assign the breadth (x-position) for each node.
  // Nodes are assigned the maximum breadth of incoming neighbors plus one;
  // nodes with no incoming links are assigned breadth zero, while
  // nodes with no outgoing links are assigned the maximum breadth.
  function computeNodeBreadths() {
    var remainingNodes = nodes,
        nextNodes,
        x = 0;

    function updateNode(node) {
        // Set x-position and width:
        node.x = x;
        node.dx = nodeWidth;
        node.sourceLinks.forEach(function(link) {
          // Only add it to the nextNodes list if it is not already present:
          if (nextNodes.indexOf(link.target) === -1) {
            nextNodes.push(link.target);
          }
        });
    }

    // Work from left to right.
    // Keep updating the breadth (x-position) of nodes that are targets of
    // recently-updated nodes.
    while (remainingNodes.length && x < nodes.length) {
      nextNodes = [];
      remainingNodes.forEach(updateNode);
      remainingNodes = nextNodes;
      x += 1;
    }

    // Optionally move pure sinks always to the right.
    if (sinksRight) {
      moveSinksRight(x);
    }

    scaleNodeBreadths((size[0] - nodeWidth) / (x - 1));
  }

  // Compute the depth (y-position) for each node.
  function computeNodeDepths(iterations) {
    var alpha = 1,
        // Group nodes by breadth:
        nodesByBreadth = d3.nest()
        .key(function(d) { return d.x; })
        .sortKeys(d3.ascending)
        .entries(nodes)
        .map(function(d) { return d.values; });

    function initializeNodeDepth() {
      // Calculate vertical scaling factor.
      var ky = d3.min(nodesByBreadth, function(nodes) {
        return (size[1] - (nodes.length - 1) * nodePadding) / valueSum(nodes);
      });

      nodesByBreadth.forEach(function(nodes) {
        nodes.forEach(function(node, i) {
          node.y = i;
          node.dy = node.value * ky;
        });
      });

      links.forEach(function(link) {
        link.dy = link.value * ky;
      });
    }

    function resolveCollisions() {
      nodesByBreadth.forEach(function(nodes) {
        var node,
            dy,
            y0 = 0,
            n = nodes.length,
            i;

        function ascendingDepth(a, b) { return a.y - b.y; }

        // Push any overlapping nodes down.
        nodes.sort(ascendingDepth);
        for (i = 0; i < n; i += 1) {
          node = nodes[i];
          dy = y0 - node.y;
          if (dy > 0) { node.y += dy; }
          y0 = node.y + node.dy + nodePadding;
        }

        // If the bottommost node goes outside the bounds, push it back up.
        dy = y0 - nodePadding - size[1];
        if (dy > 0) {
          y0 = node.y -= dy;

          // Push any overlapping nodes back up.
          for (i = n - 2; i >= 0; i -= 1) {
            node = nodes[i];
            dy = node.y + node.dy + nodePadding - y0;
            if (dy > 0) { node.y -= dy; }
            y0 = node.y;
          }
        }
      });
    }

    function relaxLeftToRight(alpha) {
      function weightedSource(link) {
        return (link.source.y + link.sy + link.dy / 2) * link.value;
      }

      nodesByBreadth.forEach(function(nodes) {
        nodes.forEach(function(node) {
          if (node.targetLinks.length) {
            // Value-weighted average of the y-position of source node centers linked to this node.
            var y = d3.sum(node.targetLinks, weightedSource) / valueSum(node.targetLinks);
            node.y += (y - center(node)) * alpha;
          }
        });
      });
    }

    function relaxRightToLeft(alpha) {
      function weightedTarget(link) {
        return (link.target.y + link.ty + link.dy / 2) * link.value;
      }

      nodesByBreadth.slice().reverse().forEach(function(nodes) {
        nodes.forEach(function(node) {
          if (node.sourceLinks.length) {
            // Value-weighted average of the y-positions of target nodes linked to this node.
            var y = d3.sum(node.sourceLinks, weightedTarget) / valueSum(node.sourceLinks);
            node.y += (y - center(node)) * alpha;
          }
        });
      });
    }

    //
    initializeNodeDepth();
    resolveCollisions();
    computeLinkDepths();

    while (iterations > 0) {
      iterations -= 1;

      // Make each round of moves progressively weaker:
      alpha *= 0.99;
      relaxRightToLeft(alpha);
      resolveCollisions();
      computeLinkDepths();

      relaxLeftToRight(alpha);
      resolveCollisions();
      computeLinkDepths();
    }
  }

  // SVG path data generator, to be used as "d" attribute on "path" element selection.
  sankey.link = function() {
    function link(d) {
      var x0 = d.source.x + d.source.dx,
          x1 = d.target.x,
          xi = d3.interpolateNumber(x0, x1),
          // pick two points given the curvature and its converse:
          x2 = xi(curvature),
          x3 = xi(1 - curvature),
          y0 = d.source.y + d.sy + d.dy / 2,
          y1 = d.target.y + d.ty + d.dy / 2;
      return "M" + x0 + "," + y0
           + "C" + x2 + "," + y0
           + " " + x3 + "," + y1
           + " " + x1 + "," + y1;
    }

    return link;
  };

  sankey.layout = function(iterations) {
    computeNodeLinks();
    computeNodeValues();
    computeNodeBreadths();
    computeNodeDepths(iterations);
    return sankey;
  };

  sankey.relayout = function() {
    computeLinkDepths();
    return sankey;
  };

  return sankey;
};
<|endoftext|>


<commit_before>var GHRoute = require('./GHRoute.js');
var GHInput = require('./GHInput.js');
var graphhopperTools = require('./tools.js');

// compatibility script taken from http://stackoverflow.com/a/11054570/194609
if (!Function.prototype.bind) {
    Function.prototype.bind = function (oThis) {
        if (typeof this !== 'function') {
            // closest thing possible to the ECMAScript 5
            // internal IsCallable function
            throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
        }

        var aArgs = Array.prototype.slice.call(arguments, 1),
                fToBind = this,
                fNOP = function () {
                },
                fBound = function () {
                    return fToBind.apply(this instanceof fNOP && oThis ? this : oThis,
                            aArgs.concat(Array.prototype.slice.call(arguments)));
                };

        fNOP.prototype = this.prototype;
        fBound.prototype = new fNOP();

        return fBound;
    };
}

var GHRequest = function (host, api_key) {
    this.host = host;
    this.key = api_key;
    this.route = new GHRoute(new GHInput(), new GHInput());
    this.from = this.route.first();
    this.to = this.route.last();

    this.features = {};

    this.do_zoom = true;
    this.useMiles = false;
    // use jsonp here if host allows CORS
    this.dataType = "json";
    this.api_params = {"locale": "en", "vehicle": "car", "weighting": "fastest", "elevation": false, "ascendAvoidance": 0.0, "niceLevel": 3.0, "algorithm": "", "alternative_route": {"max_paths" : 1}, "round_trip" : {"distance" : 0}, "heading" : 180};

    // register events
    this.route.addListener('route.add', function (evt) {
        this.to = this.route.last();
    }.bind(this));
    this.route.addListener('route.remove', function (evt) {
        this.from = this.route.first();
        this.to = this.route.last();
    }.bind(this));
    this.route.addListener('route.move', function (evt) {
        this.from = this.route.first();
        this.to = this.route.last();
    }.bind(this));

    this.route.addListener('route.reverse', function (evt) {
        this.from = this.route.first();
        this.to = this.route.last();
    }.bind(this));
};

GHRequest.prototype.init = function (params) {

    for (var key in params) {
        var val = params[key];
        if (val === "false")
            val = false;
        else if (val === "true")
            val = true;

        if (key === "point" || key === "mathRandom" || key === "do_zoom" || key === "layer" || key === "use_miles")
            continue;

        if ( key.indexOf('.') === -1 )
        {
            this.api_params[key] = val;
        }
    }

    if ('do_zoom' in params)
        this.do_zoom = params.do_zoom;

    if ('use_miles' in params)
        this.useMiles = params.use_miles;

    // overwrite elevation e.g. important if not supported from feature set
    this.api_params.elevation = false;
    var featureSet = this.features[this.api_params.vehicle];
    if (featureSet && featureSet.elevation) {
        if ('elevation' in params)
            this.api_params.elevation = params.elevation;
        else
            this.api_params.elevation = true;
    }
    this.api_params.CHEnabled =false;
    if (featureSet && featureSet.CHEnabled) {
        if ('CHEnabled' in params)
            this.api_params.CHEnabled = params.CHEnabled;
        else
            this.api_params.CHEnabled = true;
    }

    if (params.q) {
        var qStr = params.q;
        if (!params.point)
            params.point = [];
        var indexFrom = qStr.indexOf("from:");
        var indexTo = qStr.indexOf("to:");
        if (indexFrom >= 0 && indexTo >= 0) {
            // google-alike query schema
            if (indexFrom < indexTo) {
                params.point.push(qStr.substring(indexFrom + 5, indexTo).trim());
                params.point.push(qStr.substring(indexTo + 3).trim());
            } else {
                params.point.push(qStr.substring(indexTo + 3, indexFrom).trim());
                params.point.push(qStr.substring(indexFrom + 5).trim());
            }
        } else {
            var points = qStr.split("p:");
            for (var i = 0; i < points.length; i++) {
                var str = points[i].trim();
                if (str.length === 0)
                    continue;

                params.point.push(str);
            }
        }
    }
};

GHRequest.prototype.initVehicle = function (vehicle) {
    this.api_params.vehicle = vehicle;
    var featureSet = this.features[vehicle];

    if (featureSet && !featureSet.CHEnabled) {
        this.api_params.CHEnabled = false;
        $('#niceLevelcontrol').show();
        $("#niceLevelcontrol").css("visibility","visible");
        $("#alternativeRoutecontrol").show();
        $("#alternativeRoutecontrol").css("visibility","visible");
        $("#roundtripcontrol").show();
        $("#roundtripcontrol").css("visibility","visible");
        $("#roundtripdistance").show();
        $("#roundtripdistance").css("visibility","visible");
    }
    else
        this.api_params.CHEnabled = true;

    if (featureSet && featureSet.elevation) {
        this.api_params.elevation = true;
        if (!this.api_params.CHEnabled)
        {
            $('#ascendcontrol').show();
            $("#ascendcontrol").css("visibility","visible");
        }
    }
    else
        this.api_params.elevation = false;

};

GHRequest.prototype.hasCHEnabled = function () {
    return this.api_params.CHEnabled;
};

GHRequest.prototype.hasElevation = function () {
    return this.api_params.elevation;
};

GHRequest.prototype.getVehicle = function () {
    return this.api_params.vehicle;
};

GHRequest.prototype.createGeocodeURL = function (host, prevIndex) {
    var tmpHost = this.host;
    if (host)
        tmpHost = host;

    var path = this.createPath(tmpHost + "/geocode?limit=6&type=" + this.dataType + "&key=" + this.key);
    if (prevIndex >= 0 && prevIndex < this.route.size()) {
        var point = this.route.getIndex(prevIndex);
        if (point.isResolved()) {
            path += "&point=" + point.lat + "," + point.lng;
        }
    }
    return path;
};

GHRequest.prototype.createURL = function () {
    return this.createPath(this.host + "/route?" + this.createPointParams(false) + "&type=" + this.dataType + "&key=" + this.key);
};

GHRequest.prototype.createGPXURL = function (withRoute, withTrack, withWayPoints) {
    return this.createPath(this.host + "/route?" + this.createPointParams(false) + "&type=gpx&key=" + this.key + "&gpx.route=" + withRoute + "&gpx.track=" + withTrack + "&gpx.waypoints=" + withWayPoints);
};

GHRequest.prototype.createHistoryURL = function () {
    return this.createPath("?" + this.createPointParams(true)) + "&use_miles=" + !!this.useMiles;
};

GHRequest.prototype.createPointParams = function (useRawInput) {
    var str = "", point, i, l;

    for (i = 0, l = this.route.size(); i < l; i++) {
        point = this.route.getIndex(i);
        if (i > 0)
            str += "&";
        if (useRawInput)
            str += "point=" + encodeURIComponent(point.input);
        else
            str += "point=" + encodeURIComponent(point.toString());
    }
    return (str);
};

GHRequest.prototype.createPath = function (url) {
    for (var key in this.api_params) {
        var val = this.api_params[key];
        if ( val.toString() !== "[object Object]" )
        {
            if (GHRoute.isArray(val)) {
                for (var keyIndex in val) {
                    url += "&" + encodeURIComponent(key) + "=" + encodeURIComponent(val[keyIndex]);
                }
            } else {
                url += "&" + encodeURIComponent(key) + "=" + encodeURIComponent(val);
            }
        }
        else
        {
            for (var subkey in val) {
                url += "&" + encodeURIComponent(key) + "." + encodeURIComponent(subkey) + "=" + encodeURIComponent(val[subkey]);
            }
        }
    }
    return url;
};

GHRequest.prototype.doRequest = function (url, callback) {
    var that = this;
    $.ajax({
        timeout: 30000,
        url: url,
        success: function (json) {
            if (json.paths) {
                for (var i = 0; i < json.paths.length; i++) {
                    var path = json.paths[i];
                    // convert encoded polyline to geo json
                    if (path.points_encoded) {
                        var tmpArray = graphhopperTools.decodePath(path.points, that.hasElevation());
                        path.points = {
                            "type": "LineString",
                            "coordinates": tmpArray
                        };

                        var tmpSnappedArray = graphhopperTools.decodePath(path.snapped_waypoints, that.hasElevation());
                        path.snapped_waypoints = {
                            "type": "MultiPoint",
                            "coordinates": tmpSnappedArray
                        };
                    }
                }
            }
            callback(json);
        },
        error: function (err) {
            // problematic: this callback is not invoked when using JSONP!
            // http://stackoverflow.com/questions/19035557/jsonp-request-error-handling
            var msg = "API did not respond! ";
            var json;

            if (err && err.responseText && err.responseText.indexOf('{') >= 0) {
                json = JSON.parse(err.responseText);
            } else if (err && err.statusText && err.statusText !== "OK") {
                msg += err.statusText;
                var details = "Error for " + url;
                json = {
                    message: msg,
                    hints: [{"message": msg, "details": details}]
                };
            }
            console.log(msg + " " + JSON.stringify(err));

            callback(json);
        },
        type: "GET",
        dataType: this.dataType,
        crossDomain: true
    });
};

GHRequest.prototype.getInfo = function () {
    var url = this.host + "/info?type=" + this.dataType + "&key=" + this.key;
    // console.log(url);
    return $.ajax({
        url: url,
        timeout: 3000,
        type: "GET",
        dataType: this.dataType,
        crossDomain: true
    });
};

GHRequest.prototype.setLocale = function (locale) {
    if (locale)
        this.api_params.locale = locale;
};

GHRequest.prototype.fetchTranslationMap = function (urlLocaleParam) {
    if (!urlLocaleParam)
        // let servlet figure out the locale from the Accept-Language header
        urlLocaleParam = "";
    console.log("GHRequest.prototype.fetchTranslationMap host="+this.host);
    if (this.host === undefined)
        this.host = "http://localhost:8989";
    var keyparam = "";
    if (this.key !== undefined)
        var keyparam= "&key=" + this.key;
    var url = this.host + "/i18n/" + urlLocaleParam + "?type=" + this.dataType + keyparam;
    // console.log(url);
    return $.ajax({
        url: url,
        timeout: 3000,
        type: "GET",
        dataType: this.dataType,
        crossDomain: true
    });
};

module.exports = GHRequest;
<commit_msg>Typo fix.<commit_after>var GHRoute = require('./GHRoute.js');
var GHInput = require('./GHInput.js');
var graphhopperTools = require('./tools.js');

// compatibility script taken from http://stackoverflow.com/a/11054570/194609
if (!Function.prototype.bind) {
    Function.prototype.bind = function (oThis) {
        if (typeof this !== 'function') {
            // closest thing possible to the ECMAScript 5
            // internal IsCallable function
            throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
        }

        var aArgs = Array.prototype.slice.call(arguments, 1),
                fToBind = this,
                fNOP = function () {
                },
                fBound = function () {
                    return fToBind.apply(this instanceof fNOP && oThis ? this : oThis,
                            aArgs.concat(Array.prototype.slice.call(arguments)));
                };

        fNOP.prototype = this.prototype;
        fBound.prototype = new fNOP();

        return fBound;
    };
}

var GHRequest = function (host, api_key) {
    this.host = host;
    this.key = api_key;
    this.route = new GHRoute(new GHInput(), new GHInput());
    this.from = this.route.first();
    this.to = this.route.last();

    this.features = {};

    this.do_zoom = true;
    this.useMiles = false;
    // use jsonp here if host allows CORS
    this.dataType = "json";
    this.api_params = {"locale": "en", "vehicle": "car", "weighting": "fastest", "elevation": false, "ascendAvoidance": 0.0, "niceLevel": 3.0, "algorithm": "", "alternative_route": {"max_paths" : 1}, "round_trip" : {"distance" : 0}, "heading" : 180};

    // register events
    this.route.addListener('route.add', function (evt) {
        this.to = this.route.last();
    }.bind(this));
    this.route.addListener('route.remove', function (evt) {
        this.from = this.route.first();
        this.to = this.route.last();
    }.bind(this));
    this.route.addListener('route.move', function (evt) {
        this.from = this.route.first();
        this.to = this.route.last();
    }.bind(this));

    this.route.addListener('route.reverse', function (evt) {
        this.from = this.route.first();
        this.to = this.route.last();
    }.bind(this));
};

GHRequest.prototype.init = function (params) {

    for (var key in params) {
        var val = params[key];
        if (val === "false")
            val = false;
        else if (val === "true")
            val = true;

        if (key === "point" || key === "mathRandom" || key === "do_zoom" || key === "layer" || key === "use_miles")
            continue;

        if ( key.indexOf('.') === -1 )
        {
            this.api_params[key] = val;
        }
    }

    if ('do_zoom' in params)
        this.do_zoom = params.do_zoom;

    if ('use_miles' in params)
        this.useMiles = params.use_miles;

    // overwrite elevation e.g. important if not supported from feature set
    this.api_params.elevation = false;
    var featureSet = this.features[this.api_params.vehicle];
    if (featureSet && featureSet.elevation) {
        if ('elevation' in params)
            this.api_params.elevation = params.elevation;
        else
            this.api_params.elevation = true;
    }
    this.api_params.CHEnabled =false;
    if (featureSet && featureSet.CHEnabled) {
        if ('CHEnabled' in params)
            this.api_params.CHEnabled = params.CHEnabled;
        else
            this.api_params.CHEnabled = true;
    }

    if (params.q) {
        var qStr = params.q;
        if (!params.point)
            params.point = [];
        var indexFrom = qStr.indexOf("from:");
        var indexTo = qStr.indexOf("to:");
        if (indexFrom >= 0 && indexTo >= 0) {
            // google-alike query schema
            if (indexFrom < indexTo) {
                params.point.push(qStr.substring(indexFrom + 5, indexTo).trim());
                params.point.push(qStr.substring(indexTo + 3).trim());
            } else {
                params.point.push(qStr.substring(indexTo + 3, indexFrom).trim());
                params.point.push(qStr.substring(indexFrom + 5).trim());
            }
        } else {
            var points = qStr.split("p:");
            for (var i = 0; i < points.length; i++) {
                var str = points[i].trim();
                if (str.length === 0)
                    continue;

                params.point.push(str);
            }
        }
    }
};

GHRequest.prototype.initVehicle = function (vehicle) {
    this.api_params.vehicle = vehicle;
    var featureSet = this.features[vehicle];

    if (featureSet && !featureSet.CHEnabled) {
        this.api_params.CHEnabled = false;
        $('#niceLevelcontrol').show();
        $("#niceLevelcontrol").css("visibility","visible");
        $("#alternativeRoutecontrol").show();
        $("#alternativeRoutecontrol").css("visibility","visible");
        $("#roundtripcontrol").show();
        $("#roundtripcontrol").css("visibility","visible");
        $("#roundtripdistance").show();
        $("#roundtripdistance").css("visibility","visible");
    }
    else
        this.api_params.CHEnabled = true;

    if (featureSet && featureSet.elevation) {
        this.api_params.elevation = true;
        if (!this.api_params.CHEnabled)
        {
            $('#ascendcontrol').show();
            $("#ascendcontrol").css("visibility","visible");
        }
    }
    else
        this.api_params.elevation = false;

};

GHRequest.prototype.hasCHEnabled = function () {
    return this.api_params.CHEnabled;
};

GHRequest.prototype.hasElevation = function () {
    return this.api_params.elevation;
};

GHRequest.prototype.getVehicle = function () {
    return this.api_params.vehicle;
};

GHRequest.prototype.createGeocodeURL = function (host, prevIndex) {
    var tmpHost = this.host;
    if (host)
        tmpHost = host;

    var path = this.createPath(tmpHost + "/geocode?limit=6&type=" + this.dataType + "&key=" + this.key);
    if (prevIndex >= 0 && prevIndex < this.route.size()) {
        var point = this.route.getIndex(prevIndex);
        if (point.isResolved()) {
            path += "&point=" + point.lat + "," + point.lng;
        }
    }
    return path;
};

GHRequest.prototype.createURL = function () {
    return this.createPath(this.host + "/route?" + this.createPointParams(false) + "&type=" + this.dataType + "&key=" + this.key);
};

GHRequest.prototype.createGPXURL = function (withRoute, withTrack, withWayPoints) {
    return this.createPath(this.host + "/route?" + this.createPointParams(false) + "&type=gpx&key=" + this.key + "&gpx.route=" + withRoute + "&gpx.track=" + withTrack + "&gpx.waypoints=" + withWayPoints);
};

GHRequest.prototype.createHistoryURL = function () {
    return this.createPath("?" + this.createPointParams(true)) + "&use_miles=" + !!this.useMiles;
};

GHRequest.prototype.createPointParams = function (useRawInput) {
    var str = "", point, i, l;

    for (i = 0, l = this.route.size(); i < l; i++) {
        point = this.route.getIndex(i);
        if (i > 0)
            str += "&";
        if (useRawInput)
            str += "point=" + encodeURIComponent(point.input);
        else
            str += "point=" + encodeURIComponent(point.toString());
    }
    return (str);
};

GHRequest.prototype.createPath = function (url) {
    for (var key in this.api_params) {
        var val = this.api_params[key];
        if ( val.toString() !== "[object Object]" )
        {
            if (GHRoute.isArray(val)) {
                for (var keyIndex in val) {
                    url += "&" + encodeURIComponent(key) + "=" + encodeURIComponent(val[keyIndex]);
                }
            } else {
                url += "&" + encodeURIComponent(key) + "=" + encodeURIComponent(val);
            }
        }
        else
        {
            for (var subkey in val) {
                url += "&" + encodeURIComponent(key) + "." + encodeURIComponent(subkey) + "=" + encodeURIComponent(val[subkey]);
            }
        }
    }
    return url;
};

GHRequest.prototype.doRequest = function (url, callback) {
    var that = this;
    $.ajax({
        timeout: 30000,
        url: url,
        success: function (json) {
            if (json.paths) {
                for (var i = 0; i < json.paths.length; i++) {
                    var path = json.paths[i];
                    // convert encoded polyline to geo json
                    if (path.points_encoded) {
                        var tmpArray = graphhopperTools.decodePath(path.points, that.hasElevation());
                        path.points = {
                            "type": "LineString",
                            "coordinates": tmpArray
                        };

                        var tmpSnappedArray = graphhopperTools.decodePath(path.snapped_waypoints, that.hasElevation());
                        path.snapped_waypoints = {
                            "type": "MultiPoint",
                            "coordinates": tmpSnappedArray
                        };
                    }
                }
            }
            callback(json);
        },
        error: function (err) {
            // problematic: this callback is not invoked when using JSONP!
            // http://stackoverflow.com/questions/19035557/jsonp-request-error-handling
            var msg = "API did not respond! ";
            var json;

            if (err && err.responseText && err.responseText.indexOf('{') >= 0) {
                json = JSON.parse(err.responseText);
            } else if (err && err.statusText && err.statusText !== "OK") {
                msg += err.statusText;
                var details = "Error for " + url;
                json = {
                    message: msg,
                    hints: [{"message": msg, "details": details}]
                };
            }
            console.log(msg + " " + JSON.stringify(err));

            callback(json);
        },
        type: "GET",
        dataType: this.dataType,
        crossDomain: true
    });
};

GHRequest.prototype.getInfo = function () {
    var url = this.host + "/info?type=" + this.dataType + "&key=" + this.key;
    // console.log(url);
    return $.ajax({
        url: url,
        timeout: 3000,
        type: "GET",
        dataType: this.dataType,
        crossDomain: true
    });
};

GHRequest.prototype.setLocale = function (locale) {
    if (locale)
        this.api_params.locale = locale;
};

GHRequest.prototype.fetchTranslationMap = function (urlLocaleParam) {
    if (!urlLocaleParam)
        // let servlet figure out the locale from the Accept-Language header
        urlLocaleParam = "";
    console.log("GHRequest.prototype.fetchTranslationMap host="+this.host);
    if (this.host === undefined)
        this.host = "http://localhost:8989";
    var keyparam = "";
    if (this.key !== undefined)
        var keyparam = "&key=" + this.key;
    var url = this.host + "/i18n/" + urlLocaleParam + "?type=" + this.dataType + keyparam;
    // console.log(url);
    return $.ajax({
        url: url,
        timeout: 3000,
        type: "GET",
        dataType: this.dataType,
        crossDomain: true
    });
};

module.exports = GHRequest;
<|endoftext|>


<commit_before>'use strict';

//  ---------------------------------------------------------------------------

const hitbtc = require ('./hitbtc.js');

//  ---------------------------------------------------------------------------

module.exports = class fmfwio extends hitbtc {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'fmfwio',
            'alias': true,
            'name': 'FMFW.io',
            'countries': [ 'KN' ],
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/159177712-b685b40c-5269-4cea-ac83-f7894c49525d.jpg',
                'api': {
                    'public': 'https://api.fmfw.io',
                    'private': 'https://api.fmfw.io',
                },
                'www': 'https://fmfw.io',
                'doc': 'https://api.fmfw.io/api/2/explore/',
                'fees': 'https://fmfw.io/fees-and-limits',
                'referral': 'https://fmfw.io/referral/da948b21d6c92d69',
            },
            'fees': {
                'trading': {
                    'maker': this.parseNumber ('0.005'),
                    'taker': this.parseNumber ('0.005'),
                },
            },
        });
    }
};
<commit_msg>Update fmfwio.js<commit_after>'use strict';

//  ---------------------------------------------------------------------------

const hitbtc = require ('./hitbtc.js');

//  ---------------------------------------------------------------------------

module.exports = class fmfwio extends hitbtc {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'fmfwio',
            'name': 'FMFW.io',
            'countries': [ 'KN' ],
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/159177712-b685b40c-5269-4cea-ac83-f7894c49525d.jpg',
                'api': {
                    'public': 'https://api.fmfw.io',
                    'private': 'https://api.fmfw.io',
                },
                'www': 'https://fmfw.io',
                'doc': 'https://api.fmfw.io/api/2/explore/',
                'fees': 'https://fmfw.io/fees-and-limits',
                'referral': 'https://fmfw.io/referral/da948b21d6c92d69',
            },
            'fees': {
                'trading': {
                    'maker': this.parseNumber ('0.005'),
                    'taker': this.parseNumber ('0.005'),
                },
            },
        });
    }
};
<|endoftext|>


<commit_before>define(['jquery', 'underscore', 'backbone',
	'text!./app/views/templates/search-empty.html',
	'text!./app/views/templates/search-listing.html',
	'text!./app/views/templates/search-listings.html',
	'text!./app/views/templates/add-listing.html',
	'models', 'utils'], function($, _, Backbone, emptySearchTemplate, searchListingTemplate, searchContainerTemplate, addListingTemplate, Models, Utils) {
	Views.AddItemModal = Backbone.View.extend({
		template: _.template(addListingTemplate),

		initialize: function() {
			this.render();
		},

		render: function() {
			this.$el.html(this.template(this.model.attributes));
		},

		events: {
			"click button.btn-success": "submitRequest",
			"click button.btn-danger": "closeModal"
		},

		submitRequest: function() {
			var country = $('select.form-control').val();
			var city = $('#inputPickupCity').val();
			var locationCombined = city + ", " + country;

			// JS uses milliseconds, we need seconds.
			var dateStart = Math.floor(Date.now() / 1000);

			var inputDate = $('#inputExpiryDate').val();
			var dateEnd = (new Date(inputDate)).getTime() / 1000;

			var that = this;
			$.ajax({
				url: '/service/listings/create',
				dataType: 'json',
				type: 'POST',
				data: {
					product_id: this.model.attributes.id,
					date_start: dateStart,
					date_expire: dateEnd,
					location: locationCombined
				},
				success: function() {
					$('#add-listing-modal').modal('hide');
					that.trigger("viewClosed");
				},
				error: function() {
					alert("Oops, something went wrong. Try sending your request again!");
				}
			});
		},

		closeModal: function() {
			this.trigger("viewClosed");
		}
	});

	Views.SearchResult = Backbone.View.extend({
		template: _.template(searchListingTemplate),

		events: {
			"click a.search-result": "clickResult"
		},

		clickResult: function() {
			if (this.modal) {
				this.disposeModal();
			}

			this.modal = new Views.AddItemModal({
				model: this.model,
				el: '#modal-container'
			});
			this.listenTo(this.modal, 'viewClosed', this.disposeModal);
			$('#add-listing-modal').modal('show');
		},

		initialize: function() {
			this.listenTo(this.model, "change", this.render);
			this.id = "search-" + this.model.attributes.id;
		},

		render: function() {
			this.$el.html(this.template(this.model.attributes));
			return this;
		},

		disposeModal: function() {
			this.modal.undelegateEvents();
		}
	});

	Views.SearchResultListing = Backbone.View.extend({
		initialize: function() {
			this.listenTo(this.collection, 'add', this.collectionAdded);
			this.listenTo(this.collection, 'change', this.collectionChanged);
			this.listenTo(this.collection, 'remove', this.collectionRemoved);

			this.childViews = [];

			this._addAllModels();
		},

		render: function() {
			var fragment = document.createDocumentFragment();

			if (this.childViews.length > 0) {
				_(this.childViews).each(function(currentView) {
					fragment.appendChild(currentView.render().el);
				});
			} else {
				$(emptySearchTemplate).appendTo(fragment);
			}

			this.$el.html(fragment);
			return this;
		},

		collectionAdded: function(item) {
			this._addViewForModel(item);
			this.render();
		},

		collectionRemoved: function(item) {
			this.childViews = this.childViews.filter(function(view) {
				return view.model.id !== item.id;
			});
			this.render();
		},

		collectionChanged: function() {
			this.childViews = [];
			this._addAllModels();
		},

		_addViewForModel: function(item) {
			this.childViews.push(new Views.SearchResult({
				model: item
			}));
		},

		_addAllModels: function() {
			var that = this;
			this.collection.each(function(item) {
				that._addViewForModel(item);
			});
			this.render();
		}
	});

	Views.SearchSession = Backbone.View.extend({
		events: {
			"click button.close": "clickClose"
		},
		initialize: function() {
			var escapedSearchTerm = Utils.urlencode(Utils.urlencode(this.options.searchTerm));
			var productSearchUrl = '/service/products/search/' + escapedSearchTerm;
			var productResultCollection = new Models.ProductSearchResults([], {
				url: productSearchUrl
			});
			this.productSearchResultView = new Views.SearchResultListing({
				collection: productResultCollection
			});

			var listingSearchUrl = '/service/listings/search/' + escapedSearchTerm;
			var listingResultCollection = new Models.Wants([], {
				url: listingSearchUrl
			});
			this.listingSearchResultView = new Views.ListingView({
				collection: listingResultCollection
			});

			this.render();
		},

		render: function() {
			this.$el.html(_.template(searchContainerTemplate, {
				searchTerm: this.options.searchTerm
			}));

			this.productSearchResultView.setElement('#product-listing');
			this.productSearchResultView.render();

			this.listingSearchResultView.setElement('#request-listing');
			this.listingSearchResultView.render();

			$('#search-section').fadeIn();
		},

		clickClose: function() {
			this.trigger("goHome");
		}
	});

	Views.SearchForm = Backbone.View.extend({
		events: {
			"click a#btn-search": "searchClick",
            "keypress input[type=text]": "keypress"
		},

        keypress: function(e) {
            switch (e.keyCode) {
                case 13:
                this.searchClick();
            }
        },

		searchClick: function() {
			var searchListingView = new Views.SearchSession({
				searchTerm: $('#txt-search').val()
			});

			this.trigger('changeView', searchListingView);
		},

		initialize: function() {}
	});

	return Views;
});<commit_msg>And again.<commit_after>define(['jquery', 'underscore', 'backbone',
	'text!./app/views/templates/search-empty.html',
	'text!./app/views/templates/search-listing.html',
	'text!./app/views/templates/search-listings.html',
	'text!./app/views/templates/add-listing.html',
	'models', 'utils', 'view_main'], function($, _, Backbone, emptySearchTemplate, searchListingTemplate, searchContainerTemplate, addListingTemplate, Models, Utils, Views) {
	Views.AddItemModal = Backbone.View.extend({
		template: _.template(addListingTemplate),

		initialize: function() {
			this.render();
		},

		render: function() {
			this.$el.html(this.template(this.model.attributes));
		},

		events: {
			"click button.btn-success": "submitRequest",
			"click button.btn-danger": "closeModal"
		},

		submitRequest: function() {
			var country = $('select.form-control').val();
			var city = $('#inputPickupCity').val();
			var locationCombined = city + ", " + country;

			// JS uses milliseconds, we need seconds.
			var dateStart = Math.floor(Date.now() / 1000);

			var inputDate = $('#inputExpiryDate').val();
			var dateEnd = (new Date(inputDate)).getTime() / 1000;

			var that = this;
			$.ajax({
				url: '/service/listings/create',
				dataType: 'json',
				type: 'POST',
				data: {
					product_id: this.model.attributes.id,
					date_start: dateStart,
					date_expire: dateEnd,
					location: locationCombined
				},
				success: function() {
					$('#add-listing-modal').modal('hide');
					that.trigger("viewClosed");
				},
				error: function() {
					alert("Oops, something went wrong. Try sending your request again!");
				}
			});
		},

		closeModal: function() {
			this.trigger("viewClosed");
		}
	});

	Views.SearchResult = Backbone.View.extend({
		template: _.template(searchListingTemplate),

		events: {
			"click a.search-result": "clickResult"
		},

		clickResult: function() {
			if (this.modal) {
				this.disposeModal();
			}

			this.modal = new Views.AddItemModal({
				model: this.model,
				el: '#modal-container'
			});
			this.listenTo(this.modal, 'viewClosed', this.disposeModal);
			$('#add-listing-modal').modal('show');
		},

		initialize: function() {
			this.listenTo(this.model, "change", this.render);
			this.id = "search-" + this.model.attributes.id;
		},

		render: function() {
			this.$el.html(this.template(this.model.attributes));
			return this;
		},

		disposeModal: function() {
			this.modal.undelegateEvents();
		}
	});

	Views.SearchResultListing = Backbone.View.extend({
		initialize: function() {
			this.listenTo(this.collection, 'add', this.collectionAdded);
			this.listenTo(this.collection, 'change', this.collectionChanged);
			this.listenTo(this.collection, 'remove', this.collectionRemoved);

			this.childViews = [];

			this._addAllModels();
		},

		render: function() {
			var fragment = document.createDocumentFragment();

			if (this.childViews.length > 0) {
				_(this.childViews).each(function(currentView) {
					fragment.appendChild(currentView.render().el);
				});
			} else {
				$(emptySearchTemplate).appendTo(fragment);
			}

			this.$el.html(fragment);
			return this;
		},

		collectionAdded: function(item) {
			this._addViewForModel(item);
			this.render();
		},

		collectionRemoved: function(item) {
			this.childViews = this.childViews.filter(function(view) {
				return view.model.id !== item.id;
			});
			this.render();
		},

		collectionChanged: function() {
			this.childViews = [];
			this._addAllModels();
		},

		_addViewForModel: function(item) {
			this.childViews.push(new Views.SearchResult({
				model: item
			}));
		},

		_addAllModels: function() {
			var that = this;
			this.collection.each(function(item) {
				that._addViewForModel(item);
			});
			this.render();
		}
	});

	Views.SearchSession = Backbone.View.extend({
		events: {
			"click button.close": "clickClose"
		},
		initialize: function() {
			var escapedSearchTerm = Utils.urlencode(Utils.urlencode(this.options.searchTerm));
			var productSearchUrl = '/service/products/search/' + escapedSearchTerm;
			var productResultCollection = new Models.ProductSearchResults([], {
				url: productSearchUrl
			});
			this.productSearchResultView = new Views.SearchResultListing({
				collection: productResultCollection
			});

			var listingSearchUrl = '/service/listings/search/' + escapedSearchTerm;
			var listingResultCollection = new Models.Wants([], {
				url: listingSearchUrl
			});
			this.listingSearchResultView = new Views.ListingView({
				collection: listingResultCollection
			});

			this.render();
		},

		render: function() {
			this.$el.html(_.template(searchContainerTemplate, {
				searchTerm: this.options.searchTerm
			}));

			this.productSearchResultView.setElement('#product-listing');
			this.productSearchResultView.render();

			this.listingSearchResultView.setElement('#request-listing');
			this.listingSearchResultView.render();

			$('#search-section').fadeIn();
		},

		clickClose: function() {
			this.trigger("goHome");
		}
	});

	Views.SearchForm = Backbone.View.extend({
		events: {
			"click a#btn-search": "searchClick",
            "keypress input[type=text]": "keypress"
		},

        keypress: function(e) {
            switch (e.keyCode) {
                case 13:
                this.searchClick();
            }
        },

		searchClick: function() {
			var searchListingView = new Views.SearchSession({
				searchTerm: $('#txt-search').val()
			});

			this.trigger('changeView', searchListingView);
		},

		initialize: function() {}
	});

	return Views;
});<|endoftext|>


<commit_before>import ContextMenu from 'src/client/contextmenu.js';
import Morph from 'src/components/widgets/lively-morph.js';

export default class MovieListing extends Morph {

  initialize() {

  }

  attachedCallback() {
    this.get("#content").innerHTML = ""
    var container = lively.query(this, "lively-container");
    this.createView(container).then(view => {
      this.get("#content").appendChild(view)
    })
  }

  get moviesSrc() {
    return this.getAttribute("movies")
  }

  get selectedMoviesSrc() {
    return this.getAttribute("selected") ||  "selected_movies"
  }

  get playlistSrc() {
    return this.getAttribute("playlists") ||  "_playlists"
  }

  bag(key, map, object) {
    let bag = map.get(key) || []
    bag.push(object)
    map.set(key, bag)
  }

  async createView(container) {

    this.directory = container.getDir();
    // "cached://" +
    var listSource = await fetch(this.directory + "/" + this.moviesSrc).then(r => r.text())
    this.selectedMoviesURL = this.directory + "/" + this.selectedMoviesSrc
    this.playlistsURL = this.directory + "/" + this.playlistSrc

    await this.loadSelectedMovies()
    await this.loadPlaylists()

    var files  = listSource.split("\n").map(ea => {
      try {
        return JSON.parse(ea)
      } catch(e) {
        return null
      }
    }).filter(ea => ea)

    var movies = files
        .filter(ea => ea.imdb)
        .map(ea => ea.imdb)
        .uniq().map(ea => {
          var all =files.filter(file => file.imdb == ea)
          var first = all[0]
          first.files = all
          return first
        })
        .filter(ea => ea.year)

    this.genres = new Map()
    this.collections = new Map()
    this.playlists = new Map()
    this.ratings = new Map()
    this.directors = new Map()
    this.actors = new Map()

    for(let movie of movies) {
      for(let genre of (movie.genre || "").split(/, /)) {
        this.bag(genre, this.genres, movie)
      }
      if (movie.filename.match(/\//)) {
        var collection = movie.filename.replace(/\/.*/,"")
      } else {
        collection = "none"
      }
      this.bag(collection, this.collections, movie)

      debugger
      for (let playlistName of this.playlistsSets.keys()) {
        var set  = this.playlistsSets.get(playlistName)
        if (set.has(movie.filename)) {
           this.bag(playlistName, this.playlists, movie)
        }
      }

      var rating = new Number(movie.rating || 0)
      rating = Math.floor(rating)
      this.bag("" + rating, this.ratings, movie)

      for(let director of (movie.director || "").split(/, /)) {
        this.bag(director, this.directors, movie)
      }
      for(let actor of (movie.actors || "").split(/, /)) {
        this.bag(actor, this.actors, movie)
      }

    }

  this.serverURL = lively.files.serverURL(this.directory)
          // does only make sense when accessing a localhost server,
          // otherwise a pdf viewer would be opened on a remote machine?

  this.movieItems = movies.map(movie => {
        var title =  {
            lively.openInspector(movie)
          }}>
        title.innerHTML = movie.files[0].title // contains HTML

        if (movie.year == movie.extract_year) {
          var year = ({movie.year})
        } else {
          year = ({movie.extract_year})
        }

        var item =
 this.onMovieItemClick(movie, item)}>

           window.open("https://www.imdb.com/title/" + movie.imdb)}
          >

          {title}
          {year}
          ({movie.rating})

          {movie.files[0].genre || ""}
          {... movie.files.map(file => {
            var checkbox = <input class="checkbox" type="checkbox"></input>
            if (this.selectedMovies.has(file.filename)) {
              checkbox.checked = true
            }

            checkbox.addEventListener("click", evt => this.selectFile(file, checkbox))

            var fileItem =
{checkbox} {
              this.playFile(file)
            }}>{file.filename.replace(/.*\//,"")}

            fileItem.addEventListener('contextmenu',  evt => {
              if (!evt.shiftKey) {
                evt.stopPropagation();
                evt.preventDefault();
                var menu = new ContextMenu(fileItem, [
                      ["open", () => this.playFile(file)],
                      [`rename`, () => container.renameFile(this.directory + file.filename, false)],
                    ]);
                menu.openIn(document.body, evt, fileItem);
                return true;
              }

            }, false);

            return fileItem

          })}

        item.movie = movie
        return item
      });
    this.currentMovieItems = this.movieItems

    this.pane =

      {...this.movieItems}

    this.currentReverse=true

    this.navbar = container.get("lively-container-navbar")
    this.navbarDetails = this.navbar.get("#details")
    this.navbarDetails.querySelector("ul").innerHTML = "" // #TODO, be nicer to other content?

    this.createNavbarItem("Filter", 1)

    this.createSelectedMoviesFilter()
    this.createConflictingYearMoviesFilter()
    this.createShowAllMoviesFilter()

    this.createFilters("Genre", this.genres)
    this.createFilters("Collections", this.collections)
    this.createFilters("Playlists", this.playlists)

    this.createFilters("Ratings", this.ratings, {reverse: true})
    this.createFilters("Director", this.directors, {
      filter: name => this.directors.get(name).length > 2,
      sortBy: name => this.directors.get(name).length,
      reverse: true
    })
    this.createFilters("Actors", this.actors, {
      filter: name => this.actors.get(name).length > 2,
      sortBy: name => this.actors.get(name).length,
      reverse: true
    })

    var view =

        <button click={() => this.sortByYear()}>by year</button>
        <button click={() => this.sortByRating()}>by rating</button>
        <button click={() => this.deselectAll()}>deselect all</button>
        <button click={() => this.addToPlaylist()}>add to playlist</button>

      {this.pane}

    view.model = this
    return view
  }

  onMovieItemClick(movie, item) {
    if(this.currentMovieItem && this.currentMovieItem.classList.contains("selected")) {
      this.currentMovieItem.classList.remove("selected")
    }
    let details = this.get("#details")
    if(this.currentMovieItem == item) {
      this.currentMovieItem = null;
      details.style.display = "none"
    } else {
      this.currentMovieItem = item;
      item.classList.add("selected")
      details.style.display = "block"
      lively.setGlobalPosition(details, lively.getGlobalBounds(item).bottomLeft())
      details.innerHTML = ""
      details.appendChild(

actors: {
              ...movie.actors.split(", ")
                .map(ea =>  this.filter(ea, this.actors, "Actors")}>{ea})
                .joinElements((a,b) => new Text(", "))}

director: {
              ...movie.director.split(", ")
                .map(ea =>  this.filter(ea, this.directors, "Directors")}>{ea})
                .joinElements((a,b) => new Text(", "))}

)
    }

  }

  async loadPlaylists() {

    var base = this.playlistsURL
    var stats = await fetch(base, {method: "OPTIONS"}).then(r => r.json())

    this.playlistsSets = new Map()
    for (let file of stats.contents) {
      var url = base + "/" + file.name
      this.playlistsSets.set(file.name, await this.loadMovieSet(url))
    }
  }

  async loadMovieSet(url) {
    var resp = await fetch(url)
    if (resp.status == 200) {
      try {
        var source = await resp.text()
        return new Set(source.split("\n"))
      } catch(e) {
        lively.error("Error loading movies set ", e)
      }
    } else {
        lively.notify("could not load movie set")
    }
    return new Set()
  }

  async loadSelectedMovies() {
    this.selectedMovies = await this.loadMovieSet(this.selectedMoviesURL)
  }

  toggleFilters(expandButton, className) {
    if (expandButton.textContent == "+") {
      expandButton.textContent = "-"
      for(let ea of this.navbarDetails.querySelectorAll("." + className)) {
        ea.style.display = "block"
      }
    } else {
      expandButton.textContent = "+"
      for(let ea of this.navbarDetails.querySelectorAll("." + className)) {
        ea.style.display = "none"
      }
    }
  }

  createFilters(name, groups, options={}) {
    var action = ea => this.filter(ea, groups, name)
    var nameList = Array.from(groups.keys()).sort()
    if (options.filter) nameList = nameList.filter(options.filter)
    if (options.sortBy) nameList = nameList.sortBy(options.sortBy)
    if (options.reverse) nameList = nameList.reverse()
    var item = this.createNavbarItem(name, 1)
    var className =  name + "Filter"
    var expandButton =  this.toggleFilters(expandButton, className)}>-
    item.childNodes[0].appendChild( {expandButton})
    for(let ea of nameList) {
      var bag = groups.get(ea)
      let li = this.createFilter(bag, ea, action)
      li.classList.add(className)
    }
  }

  createNavbarItem(name, level=1) {
    var detailsItem = this.navbar.createDetailsItem(name)
    detailsItem.classList.add("subitem")
    detailsItem.classList.add("level" + level)
    this.navbarDetails.querySelector("ul").appendChild(detailsItem)
    return detailsItem
  }

  deselectAll() {
    this.selectedMovies = new Set()
    this.saveSelectedMovies()
  }

  async addToPlaylist() {
    var name = await lively.prompt("Playlist name","playlist")
    var url = this.playlistsURL + "/" + name

    var set = this.playlistsSets.get(name) || new Set()
    for(var ea of this.selectedMovies) {
      set.add(ea)
    }
    var newSource =  Array.from(set).sort().join("\n") + "\n"
    await lively.files.saveFile(url, newSource)
    lively.notify("added to movies to playlist", name)
  }

  playFile(file) {
    var url = this.directory + "/"+ encodeURI(file.filename)
    let playPath = url.replace(this.serverURL,"").replace(/^\//,"")
    var openURL = this.serverURL + "/_open/" + playPath
    lively.notify("open " + openURL)
    fetch(openURL)
  }

  async selectFile(file, checkbox) {
    if (checkbox.checked) {
      this.selectedMovies.add(file.filename)
    } else {
      this.selectedMovies.delete(file.filename)
    }
    this.saveSelectedMovies()
  }

  async saveSelectedMovies() {
    var newSource = Array.from(this.selectedMovies).sort().join("\n") + "\n"
    await lively.files.saveFile(this.selectedMoviesURL, newSource)
    lively.notify("updated  selected movies")
  }

  createFilter(bag, name, action) {
    var detailsItem = this.createNavbarItem(name + " (" + bag.length+")", 2)
    detailsItem.addEventListener("click", () => action(name))
    return detailsItem
  }

  hideDetails() {
    var detials = this.get("#details")
    detials.style.display = "none"
  }

  filter(name, map, filterName) {
    this.hideDetails()
    this.get("#filters").innerHTML = ""
    this.get("#filters").appendChild({name} ({filterName}))
    var movies = map.get(name)
    this.setCurrentMovieItems(this.movieItems
      .sortBy(ea => ea.movie.year)
      .reverse()
      .filter(ea => movies.includes(ea.movie)))
  }

  sortByYear() {
      this.sortBy(ea => ea.movie.year, this.currentReverse)
  }

  sortByRating() {
      this.sortBy(ea => Number(ea.movie.rating) || 0 , this.currentReverse)
  }

  sortBy(func, reverse) {
      this.pane.innerHTML = ""
      let items = this.currentMovieItems.sortBy(func)
      if(reverse) {
        items = items.reverse()
      }
      items.forEach(ea => {
        this.pane.appendChild(ea)
      })
  }

  setCurrentMovieItems(items) {
    this.currentMovieItems = items
    this.pane.innerHTML = ""
    this.currentMovieItems.forEach(ea => {
        this.pane.appendChild(ea)
      })
  }

  createSelectedMoviesFilter() {
    var detailsItem = this.createNavbarItem("_selected", 2)
    detailsItem.addEventListener("click", () => this.filterSelected())
  }

  filterSelected() {
    this.setCurrentMovieItems(this.movieItems
        .sortBy(ea => ea.movie.year)
        .reverse()
        .filter(ea => {
          return ea.movie.files.find(file => this.selectedMovies.has(file.filename))
    }))
  }

  filterConflictingYear() {
    this.setCurrentMovieItems(this.movieItems
      .sortBy(ea => ea.movie.year)
      .reverse()
      .filter(ea => ea.movie.year != ea.movie.extract_year))
  }

  showAllMovies() {
    this.setCurrentMovieItems(this.movieItems
      .sortBy(ea => ea.movie.filename)
      .reverse())
  }

  createConflictingYearMoviesFilter() {
    var detailsItem = this.createNavbarItem("_conflicting", 2)
    detailsItem.addEventListener("click", () => this.filterConflictingYear())
  }

  createShowAllMoviesFilter(){
    var detailsItem = this.createNavbarItem("_all", 2)
    detailsItem.addEventListener("click", () => this.showAllMovies())
  }
}
<commit_msg>[movie_listing] show movies with no id<commit_after>import ContextMenu from 'src/client/contextmenu.js';
import Morph from 'src/components/widgets/lively-morph.js';

export default class MovieListing extends Morph {

  initialize() {

  }

  attachedCallback() {
    this.get("#content").innerHTML = ""
    var container = lively.query(this, "lively-container");
    this.createView(container).then(view => {
      this.get("#content").appendChild(view)
    })
  }

  get moviesSrc() {
    return this.getAttribute("movies")
  }

  get selectedMoviesSrc() {
    return this.getAttribute("selected") ||  "selected_movies"
  }

  get playlistSrc() {
    return this.getAttribute("playlists") ||  "_playlists"
  }

  bag(key, map, object) {
    let bag = map.get(key) || []
    bag.push(object)
    map.set(key, bag)
  }

  async createView(container) {

    this.directory = container.getDir();
    // "cached://" +
    var listSource = await fetch(this.directory + "/" + this.moviesSrc).then(r => r.text())
    this.selectedMoviesURL = this.directory + "/" + this.selectedMoviesSrc
    this.playlistsURL = this.directory + "/" + this.playlistSrc

    await this.loadSelectedMovies()
    await this.loadPlaylists()

    var files  = listSource.split("\n").map(ea => {
      try {
        return JSON.parse(ea)
      } catch(e) {
        return null
      }
    }).filter(ea => ea)

    var noidcounter = 0
    for(let file of files) {
      if (!file.imdb) {
            file.imdb = "noid" + noidcounter++
      }
      file.shortName = file.filename.replace(/.*\//,"").replace(/\].*/,"]")
      if (!file.title) {
        file.title = file.shortName.replace(/\[.*/,"")
        file.genre = "n/a"
        file.actors = ""
        file.director = ""
        file.extract_year = file.year
        file.rating  = "n/a"
        file.noposter = true
      }
    }

    var movies = files
        .map(ea => ea.imdb)
        .uniq().map(ea => {
          var all =files.filter(file => file.imdb == ea)
          var first = all[0]
          first.files = all
          return first
        })
        .filter(ea => ea.year)

    this.genres = new Map()
    this.collections = new Map()
    this.playlists = new Map()
    this.ratings = new Map()
    this.directors = new Map()
    this.actors = new Map()

    for(let movie of movies) {
      for(let genre of (movie.genre || "").split(/, /)) {
        this.bag(genre, this.genres, movie)
      }
      if (movie.filename.match(/\//)) {
        var collection = movie.filename.replace(/\/.*/,"")
      } else {
        collection = "none"
      }
      this.bag(collection, this.collections, movie)

      for (let playlistName of this.playlistsSets.keys()) {
        var set  = this.playlistsSets.get(playlistName)
        if (set.has(movie.shortName)) {
           this.bag(playlistName, this.playlists, movie)
        }
      }

      var rating = new Number(movie.rating || 0)
      rating = Math.floor(rating)
      this.bag("" + rating, this.ratings, movie)

      for(let director of (movie.director || "").split(/, /)) {
        this.bag(director, this.directors, movie)
      }
      for(let actor of (movie.actors || "").split(/, /)) {
        this.bag(actor, this.actors, movie)
      }

    }

  this.serverURL = lively.files.serverURL(this.directory)
          // does only make sense when accessing a localhost server,
          // otherwise a pdf viewer would be opened on a remote machine?

  this.movieItems = movies.map(movie => {
        var title =  {
            lively.openInspector(movie)
          }}>
        title.innerHTML = movie.files[0].title // contains HTML

        if (movie.year == movie.extract_year) {
          var year = ({movie.year})
        } else {
          year = ({movie.extract_year})
        }

        var item =
 this.onMovieItemClick(movie, item)}>

           window.open("https://www.imdb.com/title/" + movie.imdb)}
          >

          {title}
          {year}
          ({movie.rating})

          {movie.files[0].genre || ""}
          {... movie.files.map(file => {
            var checkbox = <input class="checkbox" type="checkbox"></input>
            if (this.selectedMovies.has(file.filename)) {
              checkbox.checked = true
            }

            checkbox.addEventListener("click", evt => this.selectFile(file, checkbox))

            var fileItem =
{checkbox} {
              this.playFile(file)
            }}>{file.filename.replace(/.*\//,"")}

            fileItem.addEventListener('contextmenu',  evt => {
              if (!evt.shiftKey) {
                evt.stopPropagation();
                evt.preventDefault();
                var menu = new ContextMenu(fileItem, [
                      ["open", () => this.playFile(file)],
                      [`rename`, () => container.renameFile(this.directory + file.filename, false)],
                    ]);
                menu.openIn(document.body, evt, fileItem);
                return true;
              }

            }, false);

            return fileItem

          })}

        item.movie = movie
        return item
      });
    this.currentMovieItems = this.movieItems

    this.pane =

      {...this.movieItems}

    this.currentReverse=false

    this.navbar = container.get("lively-container-navbar")
    this.navbarDetails = this.navbar.get("#details")
    this.navbarDetails.querySelector("ul").innerHTML = "" // #TODO, be nicer to other content?

    this.createNavbarItem("Filter", 1)

    this.createSelectedMoviesFilter()
    this.createConflictingYearMoviesFilter()
    this.createShowAllMoviesFilter()

    this.createFilters("Genre", this.genres)
    this.createFilters("Collections", this.collections)
    this.createFilters("Playlists", this.playlists)

    this.createFilters("Ratings", this.ratings, {reverse: true})
    this.createFilters("Director", this.directors, {
      filter: name => this.directors.get(name).length > 2,
      sortBy: name => this.directors.get(name).length,
      reverse: true
    })
    this.createFilters("Actors", this.actors, {
      filter: name => this.actors.get(name).length > 2,
      sortBy: name => this.actors.get(name).length,
      reverse: true
    })

    var view =

        <button click={() => this.sortByYear()}>by year</button>
        <button click={() => this.sortByRating()}>by rating</button>
        <button click={() => this.sortByTitle()}>by title</button>
        <button click={() => this.deselectAll()}>deselect all</button>
        <button click={() => this.addToPlaylist()}>add to playlist</button>

      {this.pane}

    view.model = this
    return view
  }

  onMovieItemClick(movie, item) {
    if(this.currentMovieItem && this.currentMovieItem.classList.contains("selected")) {
      this.currentMovieItem.classList.remove("selected")
    }
    let details = this.get("#details")
    if(this.currentMovieItem == item) {
      this.currentMovieItem = null;
      details.style.display = "none"
    } else {
      this.currentMovieItem = item;
      item.classList.add("selected")
      details.style.display = "block"
      lively.setGlobalPosition(details, lively.getGlobalBounds(item).bottomLeft())
      details.innerHTML = ""
      details.appendChild(

actors: {
              ...movie.actors.split(", ")
                .map(ea =>  this.filter(ea, this.actors, "Actors")}>{ea})
                .joinElements((a,b) => new Text(", "))}

director: {
              ...movie.director.split(", ")
                .map(ea =>  this.filter(ea, this.directors, "Directors")}>{ea})
                .joinElements((a,b) => new Text(", "))}

)
    }

  }

  async loadPlaylists() {

    var base = this.playlistsURL
    var stats = await fetch(base, {method: "OPTIONS"}).then(r => r.json())

    this.playlistsSets = new Map()
    for (let file of stats.contents) {
      var url = base + "/" + file.name
      this.playlistsSets.set(file.name, await this.loadMovieSet(url))
    }
  }

  async loadMovieSet(url) {
    var resp = await fetch(url)
    if (resp.status == 200) {
      try {
        var source = await resp.text()
        return new Set(source.split("\n"))
      } catch(e) {
        lively.error("Error loading movies set ", e)
      }
    } else {
        lively.notify("could not load movie set")
    }
    return new Set()
  }

  async loadSelectedMovies() {
    this.selectedMovies = await this.loadMovieSet(this.selectedMoviesURL)
  }

  toggleFilters(expandButton, className) {
    if (expandButton.textContent == "+") {
      expandButton.textContent = "-"
      for(let ea of this.navbarDetails.querySelectorAll("." + className)) {
        ea.style.display = "block"
      }
    } else {
      expandButton.textContent = "+"
      for(let ea of this.navbarDetails.querySelectorAll("." + className)) {
        ea.style.display = "none"
      }
    }
  }

  createFilters(name, groups, options={}) {
    var action = ea => this.filter(ea, groups, name)
    var nameList = Array.from(groups.keys()).sort()
    if (options.filter) nameList = nameList.filter(options.filter)
    if (options.sortBy) nameList = nameList.sortBy(options.sortBy)
    if (options.reverse) nameList = nameList.reverse()
    var item = this.createNavbarItem(name, 1)
    var className =  name + "Filter"
    var expandButton =  this.toggleFilters(expandButton, className)}>-
    item.childNodes[0].appendChild( {expandButton})
    for(let ea of nameList) {
      var bag = groups.get(ea)
      let li = this.createFilter(bag, ea, action)
      li.addEventListener('contextmenu',  evt => {
              if (!evt.shiftKey) {
                evt.stopPropagation();
                evt.preventDefault();
                var menuitems = []
                if (name == "Playlists") {
                  menuitems.push(["show missing", () => {
                    var names = this.playlists.get(ea).map(ea => ea.shortName)
                    var missing = Array.from(this.playlistsSets.get(ea)).filter(ea => !names.includes(ea))
                    lively.openWorkspace(missing.join("\n"))
                  }])
                }

                var menu = new ContextMenu(li, menuitems );
                menu.openIn(document.body, evt, li);
                return true;
              }

            }, false);

      li.classList.add(className)
    }
  }

  createNavbarItem(name, level=1) {
    var detailsItem = this.navbar.createDetailsItem(name)
    detailsItem.classList.add("subitem")
    detailsItem.classList.add("level" + level)
    this.navbarDetails.querySelector("ul").appendChild(detailsItem)
    return detailsItem
  }

  deselectAll() {
    this.selectedMovies = new Set()
    this.saveSelectedMovies()
  }

  async addToPlaylist() {
    var name = await lively.prompt("Playlist name","playlist")
    var url = this.playlistsURL + "/" + name

    var set = this.playlistsSets.get(name) || new Set()
    for(var ea of this.selectedMovies) {
      set.add(ea)
    }
    var newSource =  Array.from(set).sort().join("\n") + "\n"
    await lively.files.saveFile(url, newSource)
    lively.notify("added to movies to playlist", name)
  }

  playFile(file) {
    var url = this.directory + "/"+ encodeURI(file.filename)
    let playPath = url.replace(this.serverURL,"").replace(/^\//,"")
    var openURL = this.serverURL + "/_open/" + playPath
    lively.notify("open " + openURL)
    fetch(openURL)
  }

  async selectFile(file, checkbox) {
    if (checkbox.checked) {
      this.selectedMovies.add(file.filename)
    } else {
      this.selectedMovies.delete(file.filename)
    }
    this.saveSelectedMovies()
  }

  async saveSelectedMovies() {
    var newSource = Array.from(this.selectedMovies).sort().join("\n") + "\n"
    await lively.files.saveFile(this.selectedMoviesURL, newSource)
    lively.notify("updated  selected movies")
  }

  createFilter(bag, name, action) {
    var detailsItem = this.createNavbarItem(name + " (" + bag.length+")", 2)
    detailsItem.addEventListener("click", () => action(name))
    return detailsItem
  }

  hideDetails() {
    var detials = this.get("#details")
    detials.style.display = "none"
  }

  filter(name, map, filterName) {
    this.hideDetails()
    this.get("#filters").innerHTML = ""
    this.get("#filters").appendChild({name} ({filterName}))
    var movies = map.get(name)
    this.setCurrentMovieItems(this.movieItems
      .sortBy(ea => ea.movie.year)
      .reverse()
      .filter(ea => movies.includes(ea.movie)))
  }

  sortByYear() {
      this.sortBy(ea => ea.movie.year, this.currentReverse)
  }

  sortByRating() {
      this.sortBy(ea => Number(ea.movie.rating) || 0 , this.currentReverse)
  }

  sortByTitle() {
      this.sortBy(ea => ea.movie.title , this.currentReverse)
  }

  sortBy(func, reverse) {
      this.pane.innerHTML = ""
      let items = this.currentMovieItems.sortBy(func)
      if(reverse) {
        items = items.reverse()
      }
      items.forEach(ea => {
        this.pane.appendChild(ea)
      })
  }

  setCurrentMovieItems(items) {
    this.currentMovieItems = items
    this.pane.innerHTML = ""
    this.currentMovieItems.forEach(ea => {
        this.pane.appendChild(ea)
      })
  }

  createSelectedMoviesFilter() {
    var detailsItem = this.createNavbarItem("_selected", 2)
    detailsItem.addEventListener("click", () => this.filterSelected())
  }

  filterSelected() {
    this.setCurrentMovieItems(this.movieItems
        .sortBy(ea => ea.movie.year)
        .reverse()
        .filter(ea => {
          return ea.movie.files.find(file => this.selectedMovies.has(file.filename))
    }))
  }

  filterConflictingYear() {
    this.setCurrentMovieItems(this.movieItems
      .sortBy(ea => ea.movie.year)
      .reverse()
      .filter(ea => ea.movie.year != ea.movie.extract_year))
  }

  showAllMovies() {
    this.setCurrentMovieItems(this.movieItems
      .sortBy(ea => ea.movie.filename)
      .reverse())
  }

  createConflictingYearMoviesFilter() {
    var detailsItem = this.createNavbarItem("_conflicting", 2)
    detailsItem.addEventListener("click", () => this.filterConflictingYear())
  }

  createShowAllMoviesFilter(){
    var detailsItem = this.createNavbarItem("_all", 2)
    detailsItem.addEventListener("click", () => this.showAllMovies())
  }
}
<|endoftext|>


<commit_before>
function whichTransitionEvent() {

    var e = $('<div>')[0];

    var transitions = {
      'transition': 'transitionEnd',
      'OTransition': 'oTransitionEnd',
      'MSTransition': 'msTransitionEnd',
      'MozTransition': 'transitionend',
      'WebkitTransition': 'webkitTransitionEnd'
    }

    for (var t in transitions) {
        if(e.style[t] !== undefined) {
            return transitions[t];
        }
    }
};

$.fn.transit = function(params, duration, delay, easing, callback) {

    var origin = undefined;
    var style = undefined;

    if (typeof duration === 'function') {
        callback = duration;
        duration = undefined;
    }

    if (typeof delay === 'function') {
        callback = delay;
        delay = undefined;
    }

    if (typeof easing === 'function') {
        callback = easing;
        easing = undefined;
    }

    if (params.duration) {
        duration = params.duration;
        delete params.duration;
    }

    if (params.delay) {
        delay = params.delay;
        delete params.delay;
    }

    if (params.easing) {
        easing = params.easing;
        delete params.easing;
    }

    if (params.origin) {
        origin = params.origin;
        delete params.origin;
    }

    if (params.style) {
        origin = params.style;
        delete params.style;
    }

    if (params.perspective) {
        this.parent().css('-webkit-perspective', params.perspective);
        delete params.perspective;
    } else {
        this.parent().css('-webkit-perspective', 'none');
    }

    var css = new Style(params, duration, delay, easing, origin, style);
    var onTransitionEvent = whichTransitionEvent();
    var end = function(e) {

        this.unbind(onTransitionEvent);
        this.trigger('onTransitionEnd');

        if (typeof callback === 'function') {
            ($.proxy(callback, this))(e);
        }
    };

    this.bind(event, $.proxy(onTransitionEvent, this))
        .css(css.build())

    return this;
};<commit_msg>debug. params.perspective = 0<commit_after>
function whichTransitionEvent() {

    var e = $('<div>')[0];

    var transitions = {
      'transition': 'transitionEnd',
      'OTransition': 'oTransitionEnd',
      'MSTransition': 'msTransitionEnd',
      'MozTransition': 'transitionend',
      'WebkitTransition': 'webkitTransitionEnd'
    }

    for (var t in transitions) {
        if(e.style[t] !== undefined) {
            return transitions[t];
        }
    }
};

$.fn.transit = function(params, duration, delay, easing, callback) {

    var origin = undefined;
    var style = undefined;

    if (typeof duration === 'function') {
        callback = duration;
        duration = undefined;
    }

    if (typeof delay === 'function') {
        callback = delay;
        delay = undefined;
    }

    if (typeof easing === 'function') {
        callback = easing;
        easing = undefined;
    }

    if (params.duration) {
        duration = params.duration;
        delete params.duration;
    }

    if (params.delay) {
        delay = params.delay;
        delete params.delay;
    }

    if (params.easing) {
        easing = params.easing;
        delete params.easing;
    }

    if (params.origin) {
        origin = params.origin;
        delete params.origin;
    }

    if (params.style) {
        origin = params.style;
        delete params.style;
    }

    if (params.perspective != undefined) {
        this.parent().css('-webkit-perspective', params.perspective);
        delete params.perspective;
    } else {
        this.parent().css('-webkit-perspective', 'none');
    }

    var css = new Style(params, duration, delay, easing, origin, style);
    var onTransitionEvent = whichTransitionEvent();
    var end = function(e) {

        this.unbind(onTransitionEvent);
        this.trigger('onTransitionEnd');

        if (typeof callback === 'function') {
            ($.proxy(callback, this))(e);
        }
    };

    this.bind(event, $.proxy(onTransitionEvent, this))
        .css(css.build())

    return this;
};<|endoftext|>


<commit_before>/**
 * @module myModule
 * @summary: This module's purpose is to:
 *
 * @description:
 *
 * Author: Justin Mooser
 * Created On: 2015-05-15.
 * @license Apache-2.0
 */

"use strict";

module.exports = function construct(config, $http) {
  var m = {};
  config = config ? config : {};
  config = _.defaults(config, {});

  m.login = function(params) {
    return $http.post('/token', params)
      .success(function(res) {
        var user = JSON.parse(res.body);
        return p.resolve(user);
      })
      .error(function(err) {
        return p.reject(err);
      });
  };

  m.logout = function() {
    return p.resolve();
  };

  m.reauthenticate = function(params) {
    return m.login(params);
  };

  return m;
};<commit_msg>fix issue where user seems to be logged in if html is returned.<commit_after>/**
 * @module myModule
 * @summary: This module's purpose is to:
 *
 * @description:
 *
 * Author: Justin Mooser
 * Created On: 2015-05-15.
 * @license Apache-2.0
 */

"use strict";

module.exports = function construct(config, $http) {
  var m = {};
  config = config ? config : {};
  config = _.defaults(config, {});

  m.login = function(params) {
    return $http.post('/token', params)
      .success(function(res) {
        try {
          var user = JSON.parse(res.body);
          return p.resolve(user);
        }
        catch (ex) {
          return p.reject({message: 'Failed to login.', html: res.body});
        }
      })
      .error(function(err) {
        return p.reject(err);
      });
  };

  m.logout = function() {
    return p.resolve();
  };

  m.reauthenticate = function(params) {
    return m.login(params);
  };

  return m;
};<|endoftext|>