<commit_before>/*
 * rwdjs
 * JavaScript library for managing JavaScript used in responsive web designs
 *
 * http://rwdjs.joe.gl
 * MIT License
 * Requires jQuery
 */

var rwdjs = rwdjs || (function ($) {
    var rules = [],
        prevWidth,
        parent,
        console = {
            log:   function () { },
            warn:  function () { },
            error: function () { },
            info:  function () { }
        },
        utils = {
            remToPx: function (remVal) {
                /// rem is a useful unit for responsive designs, but rwdjs requires values in pixels.
                ///     This function converts rem values to px.
                /// <param name="remVal" type="Number">The value in rem which you want to convert to px.</param>
                /// <returns type="Number">The rem value in pixels.</returns>
                return parseFloat(getComputedStyle(document.documentElement).fontSize) * remVal;
            }
        };

    if(window.console) {
        log = function (obj) {
            window.console.log(obj);
        };
        warn = function (obj) {
            window.console.warn(obj);
        };
        error = function (obj) {
            window.console.error(obj);
        };
        info = function (obj) {
            window.console.info(obj);
        };
    }

    if(!$) {
        this.console.error("rwdjs: jQuery is not loaded.");
    }

    parent = $(window);

    function runRule(rule, forceRun) {
        var width = parent.width(),
            prevIn = prevWidth >= rule.minWidth && prevWidth <= rule.maxWidth,
            nowIn = width >= rule.minWidth && width <= rule.maxWidth,
            movedIn = nowIn && !prevIn,
            movedOut = prevIn && !nowIn;

        if(movedIn || movedOut || (forceRun && nowIn)) {
            rule.func(nowIn);
        }
    }

    function run() {
        /// Force the rules to be re-evaluated. This function is run initially and on the window resize event, but it's here just in case you should wish to access it.

        var width = parent.width();
        //just in case only the height changed
        if (width !== prevWidth) {

            //check to see if we've gone over a breakpoint
            $.each(rules, function (i, rule) {
                runRule(rule);
            });

            prevWidth = width;
        }
    }

    function init() {
        //prevWidth = parent.width();

        $(parent).resize(function () {
            run();
        });
        run();
    }

    function addRule(minWidth, maxWidth, on, off) {
        /// <signature>
        /// Add a rule with a single function (which is passed a boolean argument indicating on/off state.
        /// <param name="minWidth" type="Number">The width must be at least this size for the rule to apply. Use 'null' or '0' if there is no minimum.</param>
        /// <param name="maxWidth" type="Number">The width must be this size or less for the rule to apply. Use 'null' or 'Infinity' if there is no maximum.</param>
        /// <param name="on" type="Function">The function which is run whenever the rule is triggered on or off. A boolean argument passed to this function indicates the on/off state.</param>
        /// </signature>
        /// <signature>
        /// Add a rule with one function when the rule is triggered on and a second when the rule is triggered off.
        /// <param name="minWidth" type="Number">The width must be at least this size for the rule to apply. Use 'null' or '0' if there is no minimum.</param>
        /// <param name="maxWidth" type="Number">The width must be this size or less for the rule to apply. Use 'null' or 'Infinity' if there is no maximum.</param>
        /// <param name="on" type="Function">The function which is run whenever the rule is triggered on.</param>
        /// <param name="off" type="Function">The function which is run whenever the rule is triggered off.</param>
        /// </signature>

        //initialise if its the first time
        if (!prevWidth) {
            init();
        }

        //Make our maths work in case of nulls
        if (!maxWidth) {
            maxWidth = Infinity;
        }
        if (!minWidth) {
            minWidth = 0;
        }

        var func = on;
        if (off) {
            func = function (runOn) {
                if (runOn) {
                    on();
                } else {
                    off();
                }
            }
        }

        var rule = { minWidth: minWidth, maxWidth: maxWidth, func: func };

        //add to our list of rules
        rules.push(rule);

        runRule(rule, true);
    }

    //publically accessible variables
    return {
        addRule: addRule,
        run: run,
        utils: utils
    };
}(window.jQuery));<commit_msg>Use innerWidth<commit_after>/*
 * rwdjs
 * JavaScript library for managing JavaScript used in responsive web designs
 *
 * http://rwdjs.joe.gl
 * MIT License
 * Requires jQuery
 */

var rwdjs = rwdjs || (function ($) {
    var rules = [],
        prevWidth,
        parent,
        console = {
            log:   function () { },
            warn:  function () { },
            error: function () { },
            info:  function () { }
        },
        utils = {
            remToPx: function (remVal) {
                /// rem is a useful unit for responsive designs, but rwdjs requires values in pixels.
                ///     This function converts rem values to px.
                /// <param name="remVal" type="Number">The value in rem which you want to convert to px.</param>
                /// <returns type="Number">The rem value in pixels.</returns>
                return parseFloat(getComputedStyle(document.documentElement).fontSize) * remVal;
            }
        };

    if(window.console) {
        log = function (obj) {
            window.console.log(obj);
        };
        warn = function (obj) {
            window.console.warn(obj);
        };
        error = function (obj) {
            window.console.error(obj);
        };
        info = function (obj) {
            window.console.info(obj);
        };
    }

    if(!$) {
        this.console.error("rwdjs: jQuery is not loaded.");
    }

    parent = $(window);

    function runRule(rule, forceRun) {
        var width = parent.innerWidth(),
            prevIn = prevWidth >= rule.minWidth && prevWidth <= rule.maxWidth,
            nowIn = width >= rule.minWidth && width <= rule.maxWidth,
            movedIn = nowIn && !prevIn,
            movedOut = prevIn && !nowIn;

        if(movedIn || movedOut || (forceRun && nowIn)) {
            rule.func(nowIn);
        }
    }

    function run() {
        /// Force the rules to be re-evaluated. This function is run initially and on the window resize event, but it's here just in case you should wish to access it.

        var width = parent.innerWidth();
        //just in case only the height changed
        if (width !== prevWidth) {

            //check to see if we've gone over a breakpoint
            $.each(rules, function (i, rule) {
                runRule(rule);
            });

            prevWidth = width;
        }
    }

    function init() {
        $(parent).resize(function () {
            run();
        });
        run();
    }

    function addRule(minWidth, maxWidth, on, off) {
        /// <signature>
        /// Add a rule with a single function (which is passed a boolean argument indicating on/off state.
        /// <param name="minWidth" type="Number">The width must be at least this size for the rule to apply. Use 'null' or '0' if there is no minimum.</param>
        /// <param name="maxWidth" type="Number">The width must be this size or less for the rule to apply. Use 'null' or 'Infinity' if there is no maximum.</param>
        /// <param name="on" type="Function">The function which is run whenever the rule is triggered on or off. A boolean argument passed to this function indicates the on/off state.</param>
        /// </signature>
        /// <signature>
        /// Add a rule with one function when the rule is triggered on and a second when the rule is triggered off.
        /// <param name="minWidth" type="Number">The width must be at least this size for the rule to apply. Use 'null' or '0' if there is no minimum.</param>
        /// <param name="maxWidth" type="Number">The width must be this size or less for the rule to apply. Use 'null' or 'Infinity' if there is no maximum.</param>
        /// <param name="on" type="Function">The function which is run whenever the rule is triggered on.</param>
        /// <param name="off" type="Function">The function which is run whenever the rule is triggered off.</param>
        /// </signature>

        //initialise if its the first time
        if (!prevWidth) {
            init();
        }

        //Make our maths work in case of nulls
        if (!maxWidth) {
            maxWidth = Infinity;
        }
        if (!minWidth) {
            minWidth = 0;
        }

        var func = on;
        if (off) {
            func = function (runOn) {
                if (runOn) {
                    on();
                } else {
                    off();
                }
            }
        }

        var rule = { minWidth: minWidth, maxWidth: maxWidth, func: func };

        //add to our list of rules
        rules.push(rule);

        runRule(rule, true);
    }

    //publically accessible variables
    return {
        addRule: addRule,
        run: run,
        utils: utils
    };
}(window.jQuery));<|endoftext|>


<commit_before>var spawn = require("cross-spawn");
var fs = require("fs");
var kebabCase = require("lodash.kebabcase");
var path = require("path");
var util = require("util");

module.exports.check = function(request) {
  // Only look for the dependency directory
  // @TODO Support namespaced NPM modules (e.g. @cycle/dom)
  var dep = request.split("/").shift().toLowerCase();

  // Ignore relative modules, which aren't installed by NPM
  if (!dep.match(/^[a-z\-0-9]+$/)) {
    return;
  }

  try {
    var pkgPath = require.resolve(path.join(process.cwd(), "package.json"));
    var pkg = require(pkgPath);

    // Remove cached copy for future checks
    delete require.cache[pkgPath];
  } catch(e) {
    console.error(e);
    throw e;
  }

  var hasDep = pkg.dependencies && pkg.dependencies[dep];
  var hasDevDep = pkg.devDependencies && pkg.devDependencies[dep];

  // Bail early if we've already installed this dependency
  if (hasDep || hasDevDep) {
    return;
  }

  return dep;
}

module.exports.install = function install(dep, options) {
  var args = ["install"].concat([dep]).filter(Boolean);

  if (options) {
    for (option in options) {
      var arg = util.format("--%s", kebabCase(option));
      var value = options[option];

      if (value === false) {
        continue;
      }

      if (value === true) {
        args.push(arg);
      } else {
        args.push(util.format("%s='%s'", arg, value));
      }
    }
  }

  console.info("Installing missing dependency `%s`...", dep);

  var output = spawn.sync("npm", args, { stdio: "inherit" });

  return output;
};
<commit_msg>Ignore global modules (e.g. "path")<commit_after>var spawn = require("cross-spawn");
var fs = require("fs");
var kebabCase = require("lodash.kebabcase");
var path = require("path");
var util = require("util");

var EXTERNAL = /^[a-z\-0-9]+$/;

module.exports.check = function(request) {
  // Only look for the dependency directory
  // @TODO Support namespaced NPM modules (e.g. @cycle/dom)
  var dep = request.split("/").shift().toLowerCase();

  // Ignore relative modules, which aren't installed by NPM
  if (!dep.match(EXTERNAL)) {
    return;
  }

  try {
    var pkgPath = require.resolve(path.join(process.cwd(), "package.json"));
    var pkg = require(pkgPath);

    // Remove cached copy for future checks
    delete require.cache[pkgPath];
  } catch(e) {
    console.error(e);
    throw e;
  }

  var hasDep = pkg.dependencies && pkg.dependencies[dep];
  var hasDevDep = pkg.devDependencies && pkg.devDependencies[dep];

  // Bail early if we've already installed this dependency
  if (hasDep || hasDevDep) {
    return;
  }

  try {
    var resolved = require.resolve(dep);

    if (resolved.match(EXTERNAL)) {
      return;
    }
  } catch(e) {
    // Module is not resolveable
  }

  return dep;
}

module.exports.install = function install(dep, options) {
  var args = ["install"].concat([dep]).filter(Boolean);

  if (options) {
    for (option in options) {
      var arg = util.format("--%s", kebabCase(option));
      var value = options[option];

      if (value === false) {
        continue;
      }

      if (value === true) {
        args.push(arg);
      } else {
        args.push(util.format("%s='%s'", arg, value));
      }
    }
  }

  console.info("Installing missing dependency `%s`...", dep);

  var output = spawn.sync("npm", args, { stdio: "inherit" });

  return output;
};
<|endoftext|>


<commit_before>const crel = require("crel")
const {EditorView} = require("prosemirror-view")

const {renderGrouped} = require("./menu")

const prefix = "ProseMirror-menubar"

// ::- A wrapper around
// [`EditorView`](http://prosemirror.net/ref.html#view.EditorView)
// that adds a menubar above the editor.
//
// Supports the following additional props:
//
// - **`floatingMenu`**`: ?bool` determines whether the menu floats,
//   i.e. whether it sticks to the top of the viewport when the editor
//   is partially scrolled out of view.
//
// - **`menuContent`**`: [[MenuElement]]` provides the content of the
//   menu, as a nested array to be passed to `renderGrouped`.
class MenuBarEditorView {
  constructor(place, props) {
    // :: dom.Node The wrapping DOM element around the editor and the
    // menu. Will get the CSS class `ProseMirror-menubar-wrapper`.
    this.wrapper = crel("div", {class: prefix + "-wrapper"})
    if (place && place.appendChild) place.appendChild(this.wrapper)
    else if (place) place(this.wrapper)
    if (!props.dispatchTransaction)
      props.dispatchTransaction = tr => this.updateState(this.editor.state.apply(tr))
    // :: EditorView The wrapped editor view. _Don't_ directly call
    // `update` or `updateState` on this, always go through the
    // wrapping view.
    this.editor = new EditorView(this.wrapper, props)

    this.menu = crel("div", {class: prefix})
    this.menu.className = prefix
    this.spacer = null

    this.wrapper.insertBefore(this.menu, this.wrapper.firstChild)

    this.maxHeight = 0
    this.widthForMaxHeight = 0
    this.floating = false

    // :: EditorProps The current props of this view.
    this.props = props
    this.updateMenu()

    if (this.editor.someProp("floatingMenu")) {
      this.updateFloat()
      this.scrollFunc = () => {
        let root = this.editor.root
        if (!(root.body || root).contains(this.wrapper))
          window.removeEventListener("scroll", this.scrollFunc)
        else
          this.updateFloat()
      }
      window.addEventListener("scroll", this.scrollFunc)
    }
  }

  // :: (EditorProps) Update the view's props.
  update(props) {
    this.props = props
    this.editor.update(props)
    this.updateMenu()
  }

  // :: (EditorState) Update only the state of the editor.
  updateState(state) {
    this.editor.updateState(state)
    this.updateMenu()
  }

  updateMenu() {
    this.menu.textContent = ""
    this.menu.appendChild(renderGrouped(this.editor, this.editor.someProp("menuContent")))

    if (this.floating) {
      this.updateScrollCursor()
    } else {
      if (this.menu.offsetWidth != this.widthForMaxHeight) {
        this.widthForMaxHeight = this.menu.offsetWidth
        this.maxHeight = 0
      }
      if (this.menu.offsetHeight > this.maxHeight) {
        this.maxHeight = this.menu.offsetHeight
        this.menu.style.minHeight = this.maxHeight + "px"
      }
    }
  }

  updateScrollCursor() {
    let selection = this.editor.root.getSelection()
    if (!selection.focusNode) return
    let rects = selection.getRangeAt(0).getClientRects()
    let selRect = rects[selectionIsInverted(selection) ? 0 : rects.length - 1]
    if (!selRect) return
    let menuRect = this.menu.getBoundingClientRect()
    if (selRect.top < menuRect.bottom && selRect.bottom > menuRect.top) {
      let scrollable = findWrappingScrollable(this.wrapper)
      if (scrollable) scrollable.scrollTop -= (menuRect.bottom - selRect.top)
    }
  }

  updateFloat() {
    let parent = this.wrapper, editorRect = parent.getBoundingClientRect()
    if (this.floating) {
      if (editorRect.top >= 0 || editorRect.bottom < this.menu.offsetHeight + 10) {
        this.floating = false
        this.menu.style.position = this.menu.style.left = this.menu.style.width = ""
        this.menu.style.display = ""
        this.spacer.parentNode.removeChild(this.spacer)
        this.spacer = null
      } else {
        let border = (parent.offsetWidth - parent.clientWidth) / 2
        this.menu.style.left = (editorRect.left + border) + "px"
        this.menu.style.display = (editorRect.top > window.innerHeight ? "none" : "")
      }
    } else {
      if (editorRect.top < 0 && editorRect.bottom >= this.menu.offsetHeight + 10) {
        this.floating = true
        let menuRect = this.menu.getBoundingClientRect()
        this.menu.style.left = menuRect.left + "px"
        this.menu.style.width = menuRect.width + "px"
        this.menu.style.position = "fixed"
        this.spacer = crel("div", {class: prefix + "-spacer", style: `height: ${menuRect.height}px`})
        parent.insertBefore(this.spacer, this.menu)
      }
    }
  }

  // :: ()
  // Destroy the editor instance.
  destroy() {
    this.editor.destroy()
  }
}
exports.MenuBarEditorView = MenuBarEditorView

// Not precise, but close enough
function selectionIsInverted(selection) {
  if (selection.anchorNode == selection.focusNode) return selection.anchorOffset > selection.focusOffset
  return selection.anchorNode.compareDocumentPosition(selection.focusNode) == Node.DOCUMENT_POSITION_FOLLOWING
}

function findWrappingScrollable(node) {
  for (let cur = node.parentNode; cur; cur = cur.parentNode)
    if (cur.scrollHeight > cur.clientHeight) return cur
}
<commit_msg>Support mounting a given DOM node as wrapper<commit_after>const crel = require("crel")
const {EditorView} = require("prosemirror-view")

const {renderGrouped} = require("./menu")

const prefix = "ProseMirror-menubar"

// ::- A wrapper around
// [`EditorView`](http://prosemirror.net/ref.html#view.EditorView)
// that adds a menubar above the editor.
//
// Supports the following additional props:
//
// - **`floatingMenu`**`: ?bool` determines whether the menu floats,
//   i.e. whether it sticks to the top of the viewport when the editor
//   is partially scrolled out of view.
//
// - **`menuContent`**`: [[MenuElement]]` provides the content of the
//   menu, as a nested array to be passed to `renderGrouped`.
class MenuBarEditorView {
  constructor(place, props) {
    // :: dom.Node The wrapping DOM element around the editor and the
    // menu. Will get the CSS class `ProseMirror-menubar-wrapper`.
    this.wrapper = crel(place && place.mount || "div", {class: prefix + "-wrapper"})
    if (place) {
      if (place.appendChild) place.appendChild(this.wrapper)
      else if (place.apply) place(this.wrapper)
    }
    if (!props.dispatchTransaction)
      props.dispatchTransaction = tr => this.updateState(this.editor.state.apply(tr))
    // :: EditorView The wrapped editor view. _Don't_ directly call
    // `update` or `updateState` on this, always go through the
    // wrapping view.
    this.editor = new EditorView(this.wrapper, props)

    this.menu = crel("div", {class: prefix})
    this.menu.className = prefix
    this.spacer = null

    this.wrapper.insertBefore(this.menu, this.wrapper.firstChild)

    this.maxHeight = 0
    this.widthForMaxHeight = 0
    this.floating = false

    // :: EditorProps The current props of this view.
    this.props = props
    this.updateMenu()

    if (this.editor.someProp("floatingMenu")) {
      this.updateFloat()
      this.scrollFunc = () => {
        let root = this.editor.root
        if (!(root.body || root).contains(this.wrapper))
          window.removeEventListener("scroll", this.scrollFunc)
        else
          this.updateFloat()
      }
      window.addEventListener("scroll", this.scrollFunc)
    }
  }

  // :: (EditorProps) Update the view's props.
  update(props) {
    this.props = props
    this.editor.update(props)
    this.updateMenu()
  }

  // :: (EditorState) Update only the state of the editor.
  updateState(state) {
    this.editor.updateState(state)
    this.updateMenu()
  }

  updateMenu() {
    this.menu.textContent = ""
    this.menu.appendChild(renderGrouped(this.editor, this.editor.someProp("menuContent")))

    if (this.floating) {
      this.updateScrollCursor()
    } else {
      if (this.menu.offsetWidth != this.widthForMaxHeight) {
        this.widthForMaxHeight = this.menu.offsetWidth
        this.maxHeight = 0
      }
      if (this.menu.offsetHeight > this.maxHeight) {
        this.maxHeight = this.menu.offsetHeight
        this.menu.style.minHeight = this.maxHeight + "px"
      }
    }
  }

  updateScrollCursor() {
    let selection = this.editor.root.getSelection()
    if (!selection.focusNode) return
    let rects = selection.getRangeAt(0).getClientRects()
    let selRect = rects[selectionIsInverted(selection) ? 0 : rects.length - 1]
    if (!selRect) return
    let menuRect = this.menu.getBoundingClientRect()
    if (selRect.top < menuRect.bottom && selRect.bottom > menuRect.top) {
      let scrollable = findWrappingScrollable(this.wrapper)
      if (scrollable) scrollable.scrollTop -= (menuRect.bottom - selRect.top)
    }
  }

  updateFloat() {
    let parent = this.wrapper, editorRect = parent.getBoundingClientRect()
    if (this.floating) {
      if (editorRect.top >= 0 || editorRect.bottom < this.menu.offsetHeight + 10) {
        this.floating = false
        this.menu.style.position = this.menu.style.left = this.menu.style.width = ""
        this.menu.style.display = ""
        this.spacer.parentNode.removeChild(this.spacer)
        this.spacer = null
      } else {
        let border = (parent.offsetWidth - parent.clientWidth) / 2
        this.menu.style.left = (editorRect.left + border) + "px"
        this.menu.style.display = (editorRect.top > window.innerHeight ? "none" : "")
      }
    } else {
      if (editorRect.top < 0 && editorRect.bottom >= this.menu.offsetHeight + 10) {
        this.floating = true
        let menuRect = this.menu.getBoundingClientRect()
        this.menu.style.left = menuRect.left + "px"
        this.menu.style.width = menuRect.width + "px"
        this.menu.style.position = "fixed"
        this.spacer = crel("div", {class: prefix + "-spacer", style: `height: ${menuRect.height}px`})
        parent.insertBefore(this.spacer, this.menu)
      }
    }
  }

  // :: ()
  // Destroy the editor instance.
  destroy() {
    this.editor.destroy()
  }
}
exports.MenuBarEditorView = MenuBarEditorView

// Not precise, but close enough
function selectionIsInverted(selection) {
  if (selection.anchorNode == selection.focusNode) return selection.anchorOffset > selection.focusOffset
  return selection.anchorNode.compareDocumentPosition(selection.focusNode) == Node.DOCUMENT_POSITION_FOLLOWING
}

function findWrappingScrollable(node) {
  for (let cur = node.parentNode; cur; cur = cur.parentNode)
    if (cur.scrollHeight > cur.clientHeight) return cur
}
<|endoftext|>


<commit_before>'use strict';

//make '.jsx' extensions files requirable by node
require('node-jsx').install();

//require node modules
var express = require('express'),
    http = require('http'),
    path = require('path'),
    renderer = require('react-engine');

var app = express();

//set up react-engine
var engine = renderer.server.create();
app.engine('jsx', engine);
app.set('views', __dirname + '/public/views');
app.set('view engine', 'jsx');

app.set('view',renderer.expressView);

//public assets
app.use(express.static(__dirname + '/public'));

app.set('port', process.env.PORT || 3000);

app.use(require('body-parser')());

//router
(require('./router')(app));

http.createServer(app).listen(app.get('port'),function(){

  var host = 'localhost';

  var port = app.get('port');

  console.log('Express started in: ' + app.get('env') +
  ' mode on http://%s:%s; press Ctrl-c to terminate', host, port);
});
<commit_msg>use body-parser separate<commit_after>'use strict';

//make '.jsx' extensions files requirable by node
require('node-jsx').install();

//require node modules
var express = require('express'),
    http = require('http'),
    path = require('path'),
    renderer = require('react-engine');

var app = express();

//set up react-engine
var engine = renderer.server.create();
app.engine('jsx', engine);
app.set('views', __dirname + '/public/views');
app.set('view engine', 'jsx');

app.set('view',renderer.expressView);

//public assets
app.use(express.static(__dirname + '/public'));

app.set('port', process.env.PORT || 3000);

app.use(require('body-parser').urlencoded({
  extended:true
}));

//router
(require('./router')(app));

http.createServer(app).listen(app.get('port'),function(){

  var host = 'localhost';

  var port = app.get('port');

  console.log('Express started in: ' + app.get('env') +
  ' mode on http://%s:%s; press Ctrl-c to terminate', host, port);
});
<|endoftext|>


<commit_before>var FoodTruckLocator = function() {
  var _map = null,
      _trucks = null,
      _markers = null,
      _center = null,
      _geocoder = new google.maps.Geocoder();

  function refreshViewData() {
    updateDistanceFromCurrentLocation();
    updateMap();
    updateTruckLists();
  }

  function setCookie(name, value, days) {
    if (days) {
      var date = new Date();
      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
      var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
  }

  function findLocation() {
    var lat = getCookie("latitude"), lng = getCookie("longitude");
    if (lat && lng) {
      return new google.maps.LatLng(lat, lng);
    } else {
      return _center;
    }
  }

  function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') c = c.substring(1, c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
  }

  var Markers = function(map) {
    var markers = {}, lastLetter = 0;

    function buildIconURL(letter) {
      if (Modernizr.touch) {
        return "http://maps.google.com/mapfiles/marker.png";
      }
      var code = letter.charCodeAt(0)
      var color = "";
      if (code > 90) {
        code = code - 26;
        color = "_orange"
      }
      letter = String.fromCharCode(code);
      return "http://www.google.com/mapfiles/marker" + color + letter + ".png"
    }

    this.clear = function() {
      $.each(markers, function(key, marker) {
        marker.setMap(null);
      });
      markers = {};
    };

    this.add = function(stop, bounds) {
      if (markers[stop.location.name] == undefined) {
        stop.marker = new google.maps.Marker({
          map: map,
          icon: buildIconURL(String.fromCharCode(65 + lastLetter)),
          position: stop.position
        });
        markers[stop.location.name] = stop.marker;
        lastLetter++;
        bounds.extend(stop.position);
      } else {
        stop.marker = markers[stop.location.name];
      }
    }
  };

  var Clock = {
    now : function() {
      return new Date().getTime();
      //return 1366544517358;
    }
  };

  var Trucks = function(model) {
    this.stops = [];
    this.trucks = {};
    var self = this;
    for (var i=0; i < model["trucks"].length; i++) {
      this.trucks[model["trucks"][i]["id"]] = model["trucks"][i];
    }

    $.each(model["stops"], function(idx, item) {
      self.stops.push(buildStop(item));
    });

    function buildStop(stop) {
      return {
        stop : stop,
        truck : self.trucks[stop["truckId"]],
        location : model["locations"][stop["location"]-1],
        position : new google.maps.LatLng(model["locations"][stop["location"]-1].latitude,
            model["locations"][stop["location"]-1].longitude)
      }
    }

    this.all = function() {
      return this.stops;
    }

    this.nowOrLater = function() {
      var now = Clock.now();
      return $.grep(this.stops, function(item) {
        return item.stop["endMillis"] > now;
      });
    }

    this.updateDistanceFrom = function(location) {
      $.each(this.stops, function(idx, stop) {
        var distance = google.maps.geometry.spherical.computeDistanceBetween(location,
            stop.position , 3959);
        stop.distance = Math.round(distance * 100) / 100;
      });
    }

    this.openNow = function() {
      var now = Clock.now(), items = [];
      $.each(self.stops, function(idx, item) {
        if (item.stop["startMillis"] <= now && item.stop["endMillis"] > now) {
          items.push(item);
        }
      });
      return items;
    };

    this.openLater = function() {
      var now = Clock.now(), items = [];
      $.each(self.stops, function(idx, item) {
        if (item.stop["startMillis"] > now) {
          items.push(item);
        }
      });
      return items;
    }
  };

  function formatLocation(location) {
    if (/, Chicago, IL$/i.test(location)) {
      location = location.substring(0, location.length - 13);
    }
    return location;
  }

  function buildTruckList($truckList, stops) {
    $truckList.empty();
    var items = "
", lastIcon = null;
    $.each(stops, function(idx, stop){
      var distance = stop.distance ? (" (" + stop.distance + " miles away) ") : "";
      var iconColumn = "";
      if (lastIcon != stop.marker.icon) {
        iconColumn = "";
      } else {
        iconColumn = "";
      }
      lastIcon = stop.marker.icon;
      items +=   "
" +
          "

" + iconColumn + "	" +
          "	" +
          stop.truck.name + "
" +
          formatLocation(stop.location.name) + distance + "
" +
          stop.stop.startTime + " - " + stop.stop.endTime +
          "

" +
          "
";
    });
    $truckList.append(items + "
");
  }

  function updateTruckLists() {
    var location = findLocation();
    buildTruckList($("#nowTrucks"), sortByDistanceFromLocation(_trucks.openNow(), location));
    buildTruckList($("#laterTrucks"), sortByDistanceFromLocation(_trucks.openLater(), location));
  }

  function updateDistanceFromCurrentLocation() {
    _trucks.updateDistanceFrom(findLocation());
  }

  function sortByDistanceFromLocation(stops, location) {
    return stops.sort(function(a, b) {
      if (typeof a.distance == "undefined" || a.distance == null) {
        return 0;
      }
      return a.distance > b.distance ? 1 : ((a.distance == b.distance) ? 0 : -1);
    });
  }

  function updateMap() {
    _markers.clear();
    var bounds = new google.maps.LatLngBounds(),
        currentLocation = findLocation();

    bounds.extend(currentLocation);
    // TODO: we're sorting in two locations...probably shouldn't do that.
    $.each(sortByDistanceFromLocation(_trucks.openNow(), currentLocation), function(idx, stop) {
      _markers.add(stop, bounds);
//      bounds.extend(objectOnMap.position.latLng);
    });
    $.each(sortByDistanceFromLocation(_trucks.openLater(), currentLocation), function(idx, stop) {
      _markers.add(stop, bounds);
//      bounds.extend(objectOnMap.position.latLng);
    });
    _map.fitBounds(bounds);
  }

  function resize() {
    $("#map_canvas").height($(window).height() - $("#topBar").height());
    $("#sidebar").height($(window).height() - $("#topBar").height());
    $("#listContainer").height($(window).height() - $("#topBar").height());
  }

  function setupGlobalEventHandlers() {
    $("#mobileLink").click(function(e) {
      e.preventDefault();
      $("#mobileDialog").modal({ show: true, keyboard : true, backdrop: true});
    });
    $(window).resize(function() {
      resize();
    });
    $("#settingsLink").click(function(e) {
      e.preventDefault();
      var locationName = getCookie("locationName");
      if (Modernizr.geolocation) {
        $("#useGPS").prop("checked", "true" == getCookie("useGPS"));
      } else {
        $("#useGPSLabel").css("display:none");
        $("#useGPS").prop("checked", false);
      }
      $("#locationName").attr("value", locationName);
      $("#settingsDialog").modal({show: true, keyboard : true, backdrop: true});
    });
    $("#useGPS").click(function(e) {

    });
    $("#saveSettingsButton").click(function(e) {
      e.preventDefault();
      var existingGPS = getCookie("useGPS"),
          existingLocationName = getCookie("locationName"),
          locationName = $("#locationName").attr("value"),
          useGPS = ($("#useGPS").attr("checked") == "checked");

      if (useGPS) {
        navigator.geolocation.getCurrentPosition(function(position) {
          setCookie("latitude", position.coords.latitude)
          setCookie("longitude", position.coords.longitude);
          setCookie("useGPS", "true");
          refreshViewData();
          $("#settingsDialog").modal("hide");
        });
      } else {
        setCookie("useGPS", "false");
        if (existingLocationName != locationName || existingGPS) {
          _geocoder.geocode({ 'address': locationName }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
              setCookie("latitude", results[0].geometry.location.lat());
              setCookie("longitude", results[0].geometry.location.lng())
              setCookie("locationName", locationName);
              refreshViewData();
              $("#settingsDialog").modal("hide");
            } else {
              alert("Could not resolve that address");
            }
          });
        } else {
          $("#settingsDialog").modal("hide");
        }
      }
    });
  }

  return {
    setModel : function(model) {
      _trucks = new Trucks(model);
      refreshViewData();
    },
    reload : function() {
      // TODO: implement logic to reload model
    },
    run : function(mobile, center, time, modelPayload) {
      var self = this;
      _center = center;
      resize();
      _map = new google.maps.Map(document.getElementById("map_canvas"), {
        zoom: 13,
        center: center,
        maxZoom : 18,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      });
      _markers = new Markers(_map);
      setupGlobalEventHandlers();
      self.setModel(modelPayload);
    }
  };
}();
<commit_msg>Got icon bouncing working in nextgen code<commit_after>var FoodTruckLocator = function() {
  var _map = null,
      _trucks = null,
      _markers = null,
      _center = null,
      _geocoder = new google.maps.Geocoder();

  function refreshViewData() {
    updateDistanceFromCurrentLocation();
    updateMap();
    updateTruckLists();
  }

  function setCookie(name, value, days) {
    if (days) {
      var date = new Date();
      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
      var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
  }

  function findLocation() {
    var lat = getCookie("latitude"), lng = getCookie("longitude");
    if (lat && lng) {
      return new google.maps.LatLng(lat, lng);
    } else {
      return _center;
    }
  }

  function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') c = c.substring(1, c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
  }

  var Markers = function(map) {
    var markers = {}, lastLetter = 0, color = "";

    function buildIconURL(letter) {
      if (Modernizr.touch) {
        return "http://maps.google.com/mapfiles/marker.png";
      }
      var code = letter.charCodeAt(0)
      if (code > 90) {
        code = code - 26;
        color = "_orange"
      }
      letter = String.fromCharCode(code);
      return "http://www.google.com/mapfiles/marker" + color + letter + ".png"
    }

    this.clear = function() {
      color = "", lastLetter = 0;
      $.each(markers, function(key, marker) {
        marker.setMap(null);
      });
      markers = {};
    };

    this.add = function(stop, bounds) {
      if (markers[stop.location.name] == undefined) {
        var letterId = String.fromCharCode(65 + lastLetter);
        stop.marker = new google.maps.Marker({
          map: map,
          icon: buildIconURL(letterId),
          position: stop.position
        });
        stop.markerId = "marker" + color + letterId;
        markers[stop.location.name] = stop.marker;
        lastLetter++;
        bounds.extend(stop.position);
      } else {
        stop.marker = markers[stop.location.name];
      }
    };
  };

  var Clock = {
    now : function() {
      return new Date().getTime();
      //return 1366625176648;
    }
  };

  var Trucks = function(model) {
    this.stops = [];
    this.trucks = {};
    var self = this;
    for (var i=0; i < model["trucks"].length; i++) {
      this.trucks[model["trucks"][i]["id"]] = model["trucks"][i];
    }

    $.each(model["stops"], function(idx, item) {
      self.stops.push(buildStop(item));
    });

    function buildStop(stop) {
      return {
        stop : stop,
        truck : self.trucks[stop["truckId"]],
        location : model["locations"][stop["location"]-1],
        position : new google.maps.LatLng(model["locations"][stop["location"]-1].latitude,
            model["locations"][stop["location"]-1].longitude)
      }
    }

    this.all = function() {
      return this.stops;
    }

    this.nowOrLater = function() {
      var now = Clock.now();
      return $.grep(this.stops, function(item) {
        return item.stop["endMillis"] > now;
      });
    }

    this.updateDistanceFrom = function(location) {
      $.each(this.stops, function(idx, stop) {
        var distance = google.maps.geometry.spherical.computeDistanceBetween(location,
            stop.position , 3959);
        stop.distance = Math.round(distance * 100) / 100;
      });
    }

    this.openNow = function() {
      var now = Clock.now(), items = [];
      $.each(self.stops, function(idx, item) {
        if (item.stop["startMillis"] <= now && item.stop["endMillis"] > now) {
          items.push(item);
        }
      });
      return items;
    };

    this.openLater = function() {
      var now = Clock.now(), items = [];
      $.each(self.stops, function(idx, item) {
        if (item.stop["startMillis"] > now) {
          items.push(item);
        }
      });
      return items;
    }
  };

  function formatLocation(location) {
    if (/, Chicago, IL$/i.test(location)) {
      location = location.substring(0, location.length - 13);
    }
    return location;
  }

  function buildTruckList($truckList, stops) {
    $truckList.empty();
    var markerIds = [];
    var items = "
", lastIcon = null;
    $.each(stops, function(idx, stop){
      var distance = stop.distance ? (" (" + stop.distance + " miles away) ") : "";
      var iconColumn = "";
      if (lastIcon != stop.marker.icon) {
        iconColumn = "";
        markerIds.push({marker : stop.marker, id: stop.markerId});
      } else {
        iconColumn = "";
      }
      lastIcon = stop.marker.icon;
      items +=   "
" +
          "

" + iconColumn + "	" +
          "	" +
          stop.truck.name + "
" +
          formatLocation(stop.location.name) + distance + "
" +
          stop.stop.startTime + " - " + stop.stop.endTime +
          "

" +
          "
";
    });
    $truckList.append(items + "
");
    $.each(markerIds, function(idx, markerAndId) {
      if (markerAndId.marker.getAnimation() != null) {
        return;
      }
      $("#" + markerAndId.id).click(function() {
        markerAndId.marker.setAnimation(google.maps.Animation.BOUNCE);
        setTimeout(function() {
          markerAndId.marker.setAnimation(null);
        }, 3000);
      });

    });
  }

  function updateTruckLists() {
    var location = findLocation();
    buildTruckList($("#nowTrucks"), sortByDistanceFromLocation(_trucks.openNow(), location));
    buildTruckList($("#laterTrucks"), sortByDistanceFromLocation(_trucks.openLater(), location));
  }

  function updateDistanceFromCurrentLocation() {
    _trucks.updateDistanceFrom(findLocation());
  }

  function sortByDistanceFromLocation(stops, location) {
    return stops.sort(function(a, b) {
      if (typeof a.distance == "undefined" || a.distance == null) {
        return 0;
      }
      return a.distance > b.distance ? 1 : ((a.distance == b.distance) ? 0 : -1);
    });
  }

  function updateMap() {
    _markers.clear();
    var bounds = new google.maps.LatLngBounds(),
        currentLocation = findLocation();

    bounds.extend(currentLocation);
    // TODO: we're sorting in two locations...probably shouldn't do that.
    $.each(sortByDistanceFromLocation(_trucks.openNow(), currentLocation), function(idx, stop) {
      _markers.add(stop, bounds);
    });
    $.each(sortByDistanceFromLocation(_trucks.openLater(), currentLocation), function(idx, stop) {
      _markers.add(stop, bounds);
    });
    _map.fitBounds(bounds);
  }

  function resize() {
    $("#map_canvas").height($(window).height() - $("#topBar").height());
    $("#sidebar").height($(window).height() - $("#topBar").height());
    $("#listContainer").height($(window).height() - $("#topBar").height());
  }

  function setupGlobalEventHandlers() {
    $("#mobileLink").click(function(e) {
      e.preventDefault();
      $("#mobileDialog").modal({ show: true, keyboard : true, backdrop: true});
    });
    $(window).resize(function() {
      resize();
    });
    $("#settingsLink").click(function(e) {
      e.preventDefault();
      var locationName = getCookie("locationName");
      if (Modernizr.geolocation) {
        $("#useGPS").prop("checked", "true" == getCookie("useGPS"));
      } else {
        $("#useGPSLabel").css("display:none");
        $("#useGPS").prop("checked", false);
      }
      $("#locationName").attr("value", locationName);
      $("#settingsDialog").modal({show: true, keyboard : true, backdrop: true});
    });
    $("#useGPS").click(function(e) {

    });
    $("#saveSettingsButton").click(function(e) {
      e.preventDefault();
      var existingGPS = getCookie("useGPS"),
          existingLocationName = getCookie("locationName"),
          locationName = $("#locationName").attr("value"),
          useGPS = ($("#useGPS").attr("checked") == "checked");

      if (useGPS) {
        navigator.geolocation.getCurrentPosition(function(position) {
          setCookie("latitude", position.coords.latitude)
          setCookie("longitude", position.coords.longitude);
          setCookie("useGPS", "true");
          refreshViewData();
          $("#settingsDialog").modal("hide");
        });
      } else {
        setCookie("useGPS", "false");
        if (existingLocationName != locationName || existingGPS) {
          _geocoder.geocode({ 'address': locationName }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
              setCookie("latitude", results[0].geometry.location.lat());
              setCookie("longitude", results[0].geometry.location.lng())
              setCookie("locationName", locationName);
              refreshViewData();
              $("#settingsDialog").modal("hide");
            } else {
              alert("Could not resolve that address");
            }
          });
        } else {
          $("#settingsDialog").modal("hide");
        }
      }
    });
  }

  return {
    setModel : function(model) {
      _trucks = new Trucks(model);
      refreshViewData();
    },
    reload : function() {
      // TODO: implement logic to reload model
    },
    run : function(mobile, center, time, modelPayload) {
      var self = this;
      _center = center;
      resize();
      _map = new google.maps.Map(document.getElementById("map_canvas"), {
        zoom: 13,
        center: center,
        maxZoom : 18,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      });
      _markers = new Markers(_map);
      setupGlobalEventHandlers();
      self.setModel(modelPayload);
    }
  };
}();
<|endoftext|>


<commit_before>define([
    "ace",
    "src/languages"
], function(ace, languages) {
    var hr = codebox.require("hr/hr");
    var keyboard = codebox.require("utils/keyboard");

    // Import ace
    var aceRange =  ace.require("ace/range");
    var aceModes = ace.require("ace/ext/modelist");
    var aceLangs = ace.require("ace/ext/language_tools");
    var aceWhitespace = ace.require("ace/ext/whitespace");

    var Tab = codebox.tabs.Panel.extend({
        className: "component-editor",

        initialize: function() {
            var that = this;
            Tab.__super__.initialize.apply(this, arguments);

            // Create the ace editor
            this.$editor = $("<div>", {
                'class': "editor-content"
            });
            this.$editor.appendTo(this.$el);
            this.editor = ace.edit(this.$editor.get(0));
            this.editor.setTheme({
                'isDark': true,
                'cssClass': "ace-codebox",
                'cssText': ""
            });

            // Bind editor
            this.editor.session.on('change', function(e) {
                that.setTabState("modified", true);
            });

            // Allow commands shortcuts in the editor
            var $input = this.editor.textInput.getElement();
            var handleKeyEvent = function(e) {
                if (!e.altKey && !e.ctrlKey && !e.metaKey) return;
                keyboard.enableKeyEvent(e);
            };
            $input.addEventListener('keypress', handleKeyEvent, false);
            $input.addEventListener('keydown', handleKeyEvent, false);
            $input.addEventListener('keyup', handleKeyEvent, false);

            // Update editor layout
            this.listenTo(this.tab, "tab:layout", function() {
                this.editor.resize();
                this.editor.renderer.updateFull();
            });

            // Focus editor
            this.listenTo(this.tab, "tab:state", function(state) {
                if (state) this.focus();
            });

            // Clear editor when tab close
            this.listenTo(this.tab, "tab:close", function() {
                // Destroy the editor
                this.editor.destroy();

                // Destroy events and instance
                this.off();
                this.stopListening();
            });

            // File update
            this.listenTo(this.model, "change", this.updateFile);
            this.updateFile();

            // Read file
            this.read();
        },

        render: function() {
            this.editor.resize();
            this.editor.renderer.updateFull();

            return this.ready();
        },

        // Focus the editor
        focus: function() {
            this.editor.resize();
            this.editor.renderer.updateFull();
            this.editor.focus();
        },

        // Update file
        updateFile: function() {
            this.editor.getSession().setMode("ace/mode/"+languages.getModeByExtension(this.model.getExtension()));
        },

        // Set editor content
        setContent: function(content) {
            return this.editor.setValue(content);
        },

        // Get editor content
        getContent: function(content) {
            return this.editor.getValue();
        },

        // Read the file
        read: function() {
            var that = this;

            return this.model.read()
            .then(function(content) {
                return that.setContent(content);
            })
            .then(function() {
                that.setTabState("modified", false);
            });
        },

        // Write the file
        write: function() {
            var that = this;

            return this.model.write(this.getContent())
            .then(function() {
                that.setTabState("modified", false);
            });
        }
    });

    return Tab;
});<commit_msg>Reset selection when updating content<commit_after>define([
    "ace",
    "src/languages"
], function(ace, languages) {
    var hr = codebox.require("hr/hr");
    var keyboard = codebox.require("utils/keyboard");

    // Import ace
    var aceRange =  ace.require("ace/range");
    var aceModes = ace.require("ace/ext/modelist");
    var aceLangs = ace.require("ace/ext/language_tools");
    var aceWhitespace = ace.require("ace/ext/whitespace");

    var Tab = codebox.tabs.Panel.extend({
        className: "component-editor",

        initialize: function() {
            var that = this;
            Tab.__super__.initialize.apply(this, arguments);

            // Create the ace editor
            this.$editor = $("<div>", {
                'class': "editor-content"
            });
            this.$editor.appendTo(this.$el);
            this.editor = ace.edit(this.$editor.get(0));
            this.editor.setTheme({
                'isDark': true,
                'cssClass': "ace-codebox",
                'cssText': ""
            });

            // Bind editor
            this.editor.session.on('change', function(e) {
                that.setTabState("modified", true);
            });

            // Allow commands shortcuts in the editor
            var $input = this.editor.textInput.getElement();
            var handleKeyEvent = function(e) {
                if (!e.altKey && !e.ctrlKey && !e.metaKey) return;
                keyboard.enableKeyEvent(e);
            };
            $input.addEventListener('keypress', handleKeyEvent, false);
            $input.addEventListener('keydown', handleKeyEvent, false);
            $input.addEventListener('keyup', handleKeyEvent, false);

            // Update editor layout
            this.listenTo(this.tab, "tab:layout", function() {
                this.editor.resize();
                this.editor.renderer.updateFull();
            });

            // Focus editor
            this.listenTo(this.tab, "tab:state", function(state) {
                if (state) this.focus();
            });

            // Clear editor when tab close
            this.listenTo(this.tab, "tab:close", function() {
                // Destroy the editor
                this.editor.destroy();

                // Destroy events and instance
                this.off();
                this.stopListening();
            });

            // File update
            this.listenTo(this.model, "change", this.updateFile);
            this.updateFile();

            // Read file
            this.read();
        },

        render: function() {
            this.editor.resize();
            this.editor.renderer.updateFull();

            return this.ready();
        },

        // Focus the editor
        focus: function() {
            this.editor.resize();
            this.editor.renderer.updateFull();
            this.editor.focus();
        },

        // Update file
        updateFile: function() {
            this.editor.getSession().setMode("ace/mode/"+languages.getModeByExtension(this.model.getExtension()));
        },

        // Set editor content
        setContent: function(content) {
            return this.editor.setValue(content);
        },

        // Get editor content
        getContent: function(content) {
            return this.editor.getValue();
        },

        // Read the file
        read: function() {
            var that = this;

            return this.model.read()
            .then(function(content) {
                that.setContent(content);
                that.moveCursor(0, 0);
                that.setTabState("modified", false);
                that.focus();
            });
        },

        // Write the file
        write: function() {
            var that = this;

            return this.model.write(this.getContent())
            .then(function() {
                that.setTabState("modified", false);
            });
        },

        // Move cursor
        moveCursor: function(x, y) {
            this.editor.gotoLine(x, y);
        }
    });

    return Tab;
});<|endoftext|>


<commit_before>/*
 * hbSlider -- HighBridge Slider
 *
 */

(function($)
{
    /*************************
     *
     *  Helper functions
     *
     ************************/

    // Initialize slider
    function init(slider)
    {
        // Ensure a pane is set as current on load
        if($(slider).find('.slide-pane.current').length == 0)
            $(slider).find('.slide-pane').eq(0).addClass('current active');

        var offset = $(slider).find('.slide-pane').eq(0).outerWidth(true);

        // Determine visible panes
        for(var i = 1, l = slider.options.display; i < l; i++)
        {
            var pane = $(slider).find('.slide-pane').eq(i);

            TweenLite.set(pane[0], {x: offset+'px'});
            offset += pane.outerWidth(true);

            pane.addClass('active');
        }
    }

    function calculate_duration(slider, distance, duration)
    {
        return distance * duration / $(slider).width();
    }

    function animate(slide)
    {
        var slider = this;
        slider.animating = true;

        // Where are we now?
        var from = $(slider).find('.slide-pane.current');

        // Where are we moving to?
        var to = $(slider).find('.slide-pane').eq(slide.index);

        // Find the difference between the index of current pane and the index of where we're sliding to
        var difference;

        // If the index we're moving to is less than the current index and we're moving left
        if(to.index() < from.index() && slide.direction == 'left')
            difference = (to.index() + $(slider).find('.slide-pane').length) - from.index();

        // If the index we're moving to is greater than the current index and we're moving right
        else if(to.index() > from.index() && slide.direction == 'right')
            difference = (from.index() + $(slider).find('.slide-pane').length) - to.index();

        // Else...
        else
            difference = Math.abs(from.index() - to.index());

        var queue = {};
        var offset_to = (slide.direction == 'right') ? $(slider).width() : 0;

        if(slide.direction == 'right')
        {
            if(difference < slider.options.display)
            {
                for(var i = from.index() + slider.options.display, l = from.index(); i > l; i--)
                {
                    var index = i - 1;

                    if(index >= $(slider).find('.slide-pane').length)
                        index -= $(slider).find('.slide-pane').length;

                    var pane = $(slider).find('.slide-pane').eq(index);

                    queue[index] = {from: pane.position().left, to: offset_to, status: 'inactive'};
                    offset_to += pane.outerWidth(true);
                }
            }
            else
            {
                // Start at current index
                for(var i = from.index(), l = from.index() + slider.options.display; i < l; i++)
                {
                    var index = i;

                    if(index >= $(slider).find('.slide-pane').length)
                        index -= $(slider).find('.slide-pane').length;

                    var pane = $(slider).find('.slide-pane').eq(index);

                    queue[index] = {from: pane.position().left, to: offset_to, status: 'inactive'};
                    offset_to += pane.outerWidth(true);
                }
            }
        }
        else
        {
            if(difference < slider.options.display)
            {
                for(var i = from.index(), l = from.index() + slider.options.display; i < l; i++)
                {
                    var index = i;

                    if(index >= $(slider).find('.slide-pane').length)
                        index -= $(slider).find('.slide-pane').length;

                    var pane = $(slider).find('.slide-pane').eq(index);

                    offset_to -= pane.outerWidth(true);
                    queue[index] = {from: pane.position().left, to: offset_to, status: 'inactive'};
                }
            }
            else
            {
                for(var i = from.index() + slider.options.display, l = from.index(); i > l; i--)
                {
                    var index = i - 1;

                    if(index >= $(slider).find('.slide-pane').length)
                        index -= $(slider).find('.slide-pane').length;

                    var pane = $(slider).find('.slide-pane').eq(index);

                    offset_to -= pane.outerWidth(true);
                    queue[index] = {from: pane.position().left, to: offset_to, status: 'inactive'};
                }
            }
        }

        var offset_from = (slide.direction == 'right') ? 0 : $(slider).width();
        var offset_to = (slide.direction == 'right') ? $(slider).width() : 0;

        if(slide.direction == 'right')
        {
            for(var i = slide.index + slider.options.display, l = slide.index; i > l; i--)
            {
                var index = i - 1;

                if(index >= $(slider).find('.slide-pane').length)
                    index -= $(slider).find('.slide-pane').length;

                var pane = $(slider).find('.slide-pane').eq(index);

                if(!pane.hasClass('active'))
                {
                    pane.addClass('active');

                    offset_from -= pane.outerWidth(true);
                    offset_to -= pane.outerWidth(true);

                    queue[index] = {from: offset_from, to: offset_to, status: 'active'};
                }
                else
                {
                    offset_to -= pane.outerWidth(true);
                    queue[index] = {from: pane.position().left, to: offset_to, status: 'active'};
                }
            }
        }
        else
        {
            // Start at slide.index, until index + slider.options.display
            for(var i = slide.index, l = slide.index + slider.options.display; i < l; i++)
            {
                var index = i;

                if(index >= $(slider).find('.slide-pane').length)
                    index -= $(slider).find('.slide-pane').length;

                var pane = $(slider).find('.slide-pane').eq(index);

                if(!pane.hasClass('active'))
                {
                    pane.addClass('active');
                    queue[index] = {from: offset_from, to: offset_to, status: 'active'};

                    offset_from += pane.outerWidth(true);
                    offset_to += pane.outerWidth(true);
                }
                else
                {
                    queue[index] = {from: pane.position().left, to: offset_to, status: 'active'};
                    offset_to += pane.outerWidth(true);
                }
            }
        }

        for(var i = 0, keys = Object.keys(queue), l = keys.length; i < l; ++i)
        {
            var index = keys[i];
            var data = queue[keys[i]];
            var pane = $(slider).find('.slide-pane').eq(index);
            var duration = calculate_duration(slider, Math.abs(data.from - data.to), slider.options.duration);

            pane.addClass('animating');
            TweenLite.fromTo(pane[0], duration, {x: data.from}, {x: data.to, onComplete: animated, onCompleteParams: [slider, slide, data.status]});
        }
    }

    function animated(slider, slide, status)
    {
        var pane = $(this.target);

        $(slider).find('.slide-pane.current').removeClass('current');
        $(slider).find('.slide-pane').eq(slide.index).addClass('current');

        if(status == 'active')
            pane.addClass('active');
        else
            pane.removeClass('active');

        pane.removeClass('animating');

        if($(slider).find('.animating').length == 0)
        {
            slider.animating = false;
            if(typeof slider.options.slideEnd == "function") slider.options.slideEnd.call(slider);
        }
    }

    /*************************
     *
     *  Main slider code
     *
     ************************/

    var Slider = function(input)
    {
        var slider = this;

        // Define default slider.options
        slider.options = {display: 1, duration: 0.5};
        slider.options = $.extend(slider.options, input);

        init(slider);

        // When resize is triggered
        $(window).on('resize', function()
        {
            // First clear any previous styles set on the slider
            $(slider).removeAttr('style');

            // Loop through all panes and set the container height to their size
            $(slider).find('.slide-pane').each(function()
            {
                $(this).css('height', 'auto');
                var parent = $(slider);

                if($(this).outerHeight(true) > parent.height())
                {
                    parent.height($(this).outerHeight(true));
                }

                $(this).css('height', '100%');
            });
        });

        // Trigger resize now to try to position everything
        $(window).trigger('resize');

        // Trigger resize again once the window is fully loaded
        $(window).load(function()
        {
            $(window).trigger('resize');
        });

        // Convenience event for going to the next pane
        $(slider).on('slide-next', function()
        {
            var current = $(slider).find('.slide-pane.current');
            var index = current.index();

            var next = index + 1;

            if(next >= $(slider).find('.slide-pane').length)
                next = 0;

            $(slider).trigger('slide-to', next);
        });

        // Convenience event for going to the previous pane
        $(slider).on('slide-prev', function()
        {
            var current = $(slider).find('.slide-pane.current');
            var index = current.index();

            var prev = index - 1;

            if(prev < 0)
                prev = $(slider).find('.slide-pane').length - 1;

            $(slider).trigger('slide-to', prev);
        });

        // Allows sliding to any pane based on its index
        $(slider).on('slide-to', function(event, input)
        {
            var slide = {index: 0, direction: 'left'};

            // If our request is an object
            if(typeof input == "object") $.extend(slide, input);
            // Else if the request is simply a number
            if(input == parseInt(input))   slide.index = input;

            var from = $(slider).find('.slide-pane.current');
            var to = $(slider).find('.slide-pane').eq(slide.index);
            var last = $(slider).find('.slide-pane').length - 1;

            // Make sure we're actually going somewhere
            if(from.index() != to.index())
            {
                // If the pane we're moving to comes before the current, move right
                if(from.index() > to.index())
                    slide.direction = 'right';

                // If the pane we're moving to comes after the current, move left
                if(from.index() < to.index())
                    slide.direction = 'left';

                // If we're moving to the last pane from the first
                if(from.index() == 0 && to.index() == last)
                    slide.direction = 'right';

                // If we're moving to the first pane from the last
                if(from.index() == last && to.index() == 0)
                    slide.direction = 'left';

                if(!slider.animating)
                {
                    animate.call(slider, slide);
                    if(typeof slider.options != "undefined" && typeof slider.options.slideStart == "function") slider.options.slideStart.call(slider);
                }
            }
        });
    };

    /*************************
     *
     *  Bind to jQuery
     *
     ************************/

    $.fn.hbSlider = function(options)
    {
        for(var i = 0, l = this.length; i < l; i++)
        {
            Slider.call(this[i], options);
        }
    };
})(jQuery);
<commit_msg>Trigger slide to current on resize, fixes pane position<commit_after>/*
 * hbSlider -- HighBridge Slider
 *
 */

(function($)
{
    /*************************
     *
     *  Helper functions
     *
     ************************/

    // Initialize slider
    function init(slider)
    {
        // Ensure a pane is set as current on load
        if($(slider).find('.slide-pane.current').length == 0)
            $(slider).find('.slide-pane').eq(0).addClass('current active');

        var offset = $(slider).find('.slide-pane').eq(0).outerWidth(true);

        // Determine visible panes
        for(var i = 1, l = slider.options.display; i < l; i++)
        {
            var pane = $(slider).find('.slide-pane').eq(i);

            TweenLite.set(pane[0], {x: offset+'px'});
            offset += pane.outerWidth(true);

            pane.addClass('active');
        }
    }

    function calculate_duration(slider, distance, duration)
    {
        return distance * duration / $(slider).width();
    }

    function animate(slide)
    {
        var slider = this;
        slider.animating = true;

        // Where are we now?
        var from = $(slider).find('.slide-pane.current');

        // Where are we moving to?
        var to = $(slider).find('.slide-pane').eq(slide.index);

        // Find the difference between the index of current pane and the index of where we're sliding to
        var difference;

        // If the index we're moving to is less than the current index and we're moving left
        if(to.index() < from.index() && slide.direction == 'left')
            difference = (to.index() + $(slider).find('.slide-pane').length) - from.index();

        // If the index we're moving to is greater than the current index and we're moving right
        else if(to.index() > from.index() && slide.direction == 'right')
            difference = (from.index() + $(slider).find('.slide-pane').length) - to.index();

        // Else...
        else
            difference = Math.abs(from.index() - to.index());

        var queue = {};
        var offset_to = (slide.direction == 'right') ? $(slider).width() : 0;

        if(slide.direction == 'right')
        {
            if(difference < slider.options.display)
            {
                for(var i = from.index() + slider.options.display, l = from.index(); i > l; i--)
                {
                    var index = i - 1;

                    if(index >= $(slider).find('.slide-pane').length)
                        index -= $(slider).find('.slide-pane').length;

                    var pane = $(slider).find('.slide-pane').eq(index);

                    queue[index] = {from: pane.position().left, to: offset_to, status: 'inactive'};
                    offset_to += pane.outerWidth(true);
                }
            }
            else
            {
                // Start at current index
                for(var i = from.index(), l = from.index() + slider.options.display; i < l; i++)
                {
                    var index = i;

                    if(index >= $(slider).find('.slide-pane').length)
                        index -= $(slider).find('.slide-pane').length;

                    var pane = $(slider).find('.slide-pane').eq(index);

                    queue[index] = {from: pane.position().left, to: offset_to, status: 'inactive'};
                    offset_to += pane.outerWidth(true);
                }
            }
        }
        else
        {
            if(difference < slider.options.display)
            {
                for(var i = from.index(), l = from.index() + slider.options.display; i < l; i++)
                {
                    var index = i;

                    if(index >= $(slider).find('.slide-pane').length)
                        index -= $(slider).find('.slide-pane').length;

                    var pane = $(slider).find('.slide-pane').eq(index);

                    offset_to -= pane.outerWidth(true);
                    queue[index] = {from: pane.position().left, to: offset_to, status: 'inactive'};
                }
            }
            else
            {
                for(var i = from.index() + slider.options.display, l = from.index(); i > l; i--)
                {
                    var index = i - 1;

                    if(index >= $(slider).find('.slide-pane').length)
                        index -= $(slider).find('.slide-pane').length;

                    var pane = $(slider).find('.slide-pane').eq(index);

                    offset_to -= pane.outerWidth(true);
                    queue[index] = {from: pane.position().left, to: offset_to, status: 'inactive'};
                }
            }
        }

        var offset_from = (slide.direction == 'right') ? 0 : $(slider).width();
        var offset_to = (slide.direction == 'right') ? $(slider).width() : 0;

        if(slide.direction == 'right')
        {
            for(var i = slide.index + slider.options.display, l = slide.index; i > l; i--)
            {
                var index = i - 1;

                if(index >= $(slider).find('.slide-pane').length)
                    index -= $(slider).find('.slide-pane').length;

                var pane = $(slider).find('.slide-pane').eq(index);

                if(!pane.hasClass('active'))
                {
                    pane.addClass('active');

                    offset_from -= pane.outerWidth(true);
                    offset_to -= pane.outerWidth(true);

                    queue[index] = {from: offset_from, to: offset_to, status: 'active'};
                }
                else
                {
                    offset_to -= pane.outerWidth(true);
                    queue[index] = {from: pane.position().left, to: offset_to, status: 'active'};
                }
            }
        }
        else
        {
            // Start at slide.index, until index + slider.options.display
            for(var i = slide.index, l = slide.index + slider.options.display; i < l; i++)
            {
                var index = i;

                if(index >= $(slider).find('.slide-pane').length)
                    index -= $(slider).find('.slide-pane').length;

                var pane = $(slider).find('.slide-pane').eq(index);

                if(!pane.hasClass('active'))
                {
                    pane.addClass('active');
                    queue[index] = {from: offset_from, to: offset_to, status: 'active'};

                    offset_from += pane.outerWidth(true);
                    offset_to += pane.outerWidth(true);
                }
                else
                {
                    queue[index] = {from: pane.position().left, to: offset_to, status: 'active'};
                    offset_to += pane.outerWidth(true);
                }
            }
        }

        for(var i = 0, keys = Object.keys(queue), l = keys.length; i < l; ++i)
        {
            var index = keys[i];
            var data = queue[keys[i]];
            var pane = $(slider).find('.slide-pane').eq(index);
            var duration = calculate_duration(slider, Math.abs(data.from - data.to), slider.options.duration);

            pane.addClass('animating');
            TweenLite.fromTo(pane[0], duration, {x: data.from}, {x: data.to, onComplete: animated, onCompleteParams: [slider, slide, data.status]});
        }
    }

    function animated(slider, slide, status)
    {
        var pane = $(this.target);

        $(slider).find('.slide-pane.current').removeClass('current');
        $(slider).find('.slide-pane').eq(slide.index).addClass('current');

        if(status == 'active')
            pane.addClass('active');
        else
            pane.removeClass('active');

        pane.removeClass('animating');

        if($(slider).find('.animating').length == 0)
        {
            slider.animating = false;
            if(typeof slider.options.slideEnd == "function") slider.options.slideEnd.call(slider);
        }
    }

    /*************************
     *
     *  Main slider code
     *
     ************************/

    var Slider = function(input)
    {
        var slider = this;

        // Define default slider.options
        slider.options = {display: 1, duration: 0.5};
        slider.options = $.extend(slider.options, input);

        init(slider);

        // When resize is triggered
        $(window).on('resize', function()
        {
            // First clear any previous styles set on the slider
            $(slider).removeAttr('style');

            // Loop through all panes and set the container height to their size
            $(slider).find('.slide-pane').each(function()
            {
                $(this).css('height', 'auto');
                var parent = $(slider);

                if($(this).outerHeight(true) > parent.height())
                {
                    parent.height($(this).outerHeight(true));
                }

                $(this).css('height', '100%');
            });

            var current = $(slider).find('.slide-pane.current').index();

            // Trigger slide to current, fixing any potential difference in positioning after resizing
            $(slider).trigger('slide-to', current);
        });

        // Trigger resize now to try to position everything
        $(window).trigger('resize');

        // Trigger resize again once the window is fully loaded
        $(window).load(function()
        {
            $(window).trigger('resize');
        });

        // Convenience event for going to the next pane
        $(slider).on('slide-next', function()
        {
            var current = $(slider).find('.slide-pane.current');
            var index = current.index();

            var next = index + 1;

            if(next >= $(slider).find('.slide-pane').length)
                next = 0;

            $(slider).trigger('slide-to', next);
        });

        // Convenience event for going to the previous pane
        $(slider).on('slide-prev', function()
        {
            var current = $(slider).find('.slide-pane.current');
            var index = current.index();

            var prev = index - 1;

            if(prev < 0)
                prev = $(slider).find('.slide-pane').length - 1;

            $(slider).trigger('slide-to', prev);
        });

        // Allows sliding to any pane based on its index
        $(slider).on('slide-to', function(event, input)
        {
            var slide = {index: 0, direction: 'left'};

            // If our request is an object
            if(typeof input == "object") $.extend(slide, input);
            // Else if the request is simply a number
            if(input == parseInt(input))   slide.index = input;

            var from = $(slider).find('.slide-pane.current');
            var to = $(slider).find('.slide-pane').eq(slide.index);
            var last = $(slider).find('.slide-pane').length - 1;

            // If the pane we're moving to comes before the current, move right
            if(from.index() > to.index())
                slide.direction = 'right';

            // If the pane we're moving to comes after the current, move left
            if(from.index() < to.index())
                slide.direction = 'left';

            // If we're moving to the last pane from the first
            if(from.index() == 0 && to.index() == last)
                slide.direction = 'right';

            // If we're moving to the first pane from the last
            if(from.index() == last && to.index() == 0)
                slide.direction = 'left';

            if(!slider.animating)
            {
                animate.call(slider, slide);
                if(typeof slider.options != "undefined" && typeof slider.options.slideStart == "function") slider.options.slideStart.call(slider);
            }
        });
    };

    /*************************
     *
     *  Bind to jQuery
     *
     ************************/

    $.fn.hbSlider = function(options)
    {
        for(var i = 0, l = this.length; i < l; i++)
        {
            Slider.call(this[i], options);
        }
    };
})(jQuery);
<|endoftext|>