<commit_before>/**
 * Gumi v0.1
 * Usage: http://b1lly.github.io/gumi
 * GitHub: http://github.com/b1lly/gumi
 */

;(function($, window, document, undefined) {
  var defaults = {
    buttonClass: 'btn-default',
    buttonSelectedClass: 'btn-selected',
    optionDisabledClass: 'option-disabled',
    dropdownClass: 'dropdown-default',
    onChange: function() {},
    onOpen: function() {}
  };

  /**
   * @constructor
   */
  var Gumi = function(elem, options) {
    this.elem = elem;
    this.$elem = $(elem);
    this.$elem.addClass('gumi-wrap');

    // Reference to the button that shows the current selected option
    // and also handles the click event to show the dropdown
    this.$button = $('');

    // Contains a reference to the dropdown list of options
    this.$dropdown = this.$elem.find('ul').hide();

    // Native form select element that gumi links too
    this.$select = $('<select />');

    this.selectedIndex = 0;
    this.selectedLabel = undefined;
    this.selectedValue = undefined;

    this.options = $.extend({}, defaults, options);

    this._load = true;
    this._defaults = defaults;
    this._initialSelected = undefined;

    this._init();
  };

  /**
   * Build out our Gumi prototype and methods
   */
  Gumi.prototype = {
    constructor: Gumi,

    /**
     * Initialize the Gumi selectbox
     */
    _init: function() {
      this._createSelect();
      this._createDropdown();
      this._bindDropdown();
      this._bindSelectOption();
    },

    /**
     * Takes a serialized string of params and converts it to a map of data
     * based on the data attribute 'params' on the button node
     * e.g. { 'key' : 'val' }
     */
    _deserializeParams: function() {
      var params = this.$button.data('params'),
          data = {};

      if (!params) {
        return;
      }

      if (typeof params === 'string') {
        params = params.split(' ');

        var currentParam;
        for (var i = 0, len = params.length; i < len; i ++) {
          currentParam = params[i].split('=');
          data[currentParam[0]] = currentParam[1];
        }

        this._addDataToSelect(data);
      }
    },

    /**
     * Adds HTML5 Data attributes/values to the select
     * @param {object} data Map of data key to data value e.g. { 'height': 300 }
     */
    _addDataToSelect: function(data) {
      for (var key in data) {
        this.$select.data(key, data[key]);
      }
    },

    /**
     * Creates a hidden "<select>" based on
     * the list items from the ul jQuery selector
     */
    _createSelect: function() {
      var that = this,
          selectedIndex = 0;

      // Handle using a button that exists
      var $button = this.$elem.find('button');
      if ($button.length) {
        this.$button = $button;
      }

      // Copy some attributes over to our select
      this.$select
        .addClass(this.options.dropdownClass)
        .addClass(that.$button.data('class'))
        .attr('name', that.$button.data('name'))
        .prop('required', that.$button.data('required'))
        .hide();

      // Add 'data' params to the select as HTML data-attributes
      this._deserializeParams();

      // Add the list options to our select options
      this.$elem.find('li').each(function(index) {
        var $self = $(this),
            val = $self.data('value');

        var value = val === undefined || (val.length === 0 && val !== '') ?
            $self.html() : val,
            label = $self.data('label') || $self.html() || value;

        // Figure out which one should be selected by default
        if ($self.data('selected') === true) {
          selectedIndex = index;
        }

        // Handle custom styling for disabled class
        if ($self.data('disabled') === true) {
          $self.addClass(that.options.optionDisabledClass);
        }

        // Only show options that are selectable
        if ($self.data('selectable') === false) {
          $self.hide();
        }

        $('<option />')
          .val(value)
          .append(label)
          .addClass($self.attr('class'))
          .appendTo(that.$select);
      });

      // Set the default option
      this.setSelectedOption(selectedIndex);

      // Attach our native select to the DOM
      this.$elem.append(this.$select);

      this.initialSelected = selectedIndex;
      this._load = false;
    },

    /**
     * Creates the clickable button to show
     * the dropdown, and attaches "optional"
     * custom classes to both the button and the dropdown
     */
    _createDropdown: function() {
      this.$button
        .addClass('gumi-btn')
        .addClass(this.options.buttonClass);

      // Insert the button before the dropdown
      this.$elem.prepend(this.$button);

      // Styling should hide the dropdown by default
      this.$dropdown
        .addClass('gumi-dropdown')
        .addClass(this.options.dropdownClass);
    },

    /**
     * Handle the interaction for showing and hiding the dropdown options
     */
    _bindDropdown: function() {
      var that = this;

      this.$button.on('click.Gumi', function(e) {
        e.preventDefault();
        e.stopPropagation();

        // We want to reset all other dropdowns on the page
        // to avoid having multiple dropdowns open at a time
        that._resetDropdowns(that.$elem);

        // Handles clicking the button toggling
        that.$button.toggleClass(that.options.buttonSelectedClass);
        that.$dropdown.toggle();

        if (that.$dropdown.is(':visible')) {
          that.options.onOpen.call(that.$elem);
        }
      });

      $(document).off('click.Gumi');
      $(document).on('click.Gumi', function(e) {
        if ($(e.target).closest('.gumi-dropdown').length === 0) {
          that._resetDropdowns();
        }
      });
    },

    /**
     * When a user selects an option, we need to update our native
     * <select> in addition to our instance data
     */
    _bindSelectOption: function() {
      var that = this;

      that.$dropdown.on('click.Gumi', 'li', function(e) {
        var $self = $(this);
        e.stopPropagation();

        if (!$self.data('disabled')) {
          that.setSelectedOption($(this).index());
          that.closeDropdown();
        }
      });
    },

    /**
     * Resets all dropdowns on the page to default state, excluding callee
     * @param {jQueryObject} $elem Optional element to exclude from reset
     */
    _resetDropdowns: function($elem) {
      $('.gumi-wrap').not($elem).each(function() {
        $(this).data('gumi').closeDropdown();
      });
    },

    /**
     * Set the selected option based on it's value
     * @param {string|number|boolean} value The value of the option to look for in our list
     */
    setSelected: function(value) {
      var $option = this.setSelectedOption(this.$select.find('option[value="' + value + '"]'));

      if ($option.length) {
        setSelectedOption($option.index());
      }
    },

    /**
     * Sets the selected state to the native select box
     * based on the index. Also updates the instance and the label on the button
     * @param {number} opt_index Index of the select option to select (defaults 0)
     */
    setSelectedOption: function(opt_index) {
      opt_index = opt_index || 0;

      var $option = this.$select.find('option').eq(opt_index);

      this.selectedIndex = opt_index;
      this.selectedLabel = this.$dropdown.eq(opt_index).data('label') || $option.text();
      this.selectedValue = $option.val();

      $option
        .prop('selected', true)
        .trigger('change');

      if (this._load === false ||
          (this._load === true && !this.$button.data('default-value'))) {
        this.$button.html('' + this.selectedLabel + ' ');

        // Trigger our custom callback
        this.options.onChange.call(this.$select);
      }
    },

    /**
     * Public interface to bind a custom change event handler
     * @param {string} evt The event type to listen to
     * @param {function} fn The function callback for the event
     */
    onEvent: function(evt, fn) {
      if (typeof fn === 'function') {
        if (this.options[evt]) {
          this.options[evt] = fn;
        }
      }
    },

    /**
     * Hides the dropdown and removes the selected state of the button
     */
    closeDropdown: function() {
      this.$button.removeClass(this.options.buttonSelectedClass);
      this.$dropdown.hide();
    },

    /**
     * Resets the dropdown to it's original state during initialization
     */
    reset: function() {
      this.setSelectedOption(this._initialSelected);
    }
  };

  /**
   * Simple jQuery API for Gumi
   */
  $.fn.gumi = function(options) {
    return this.each(function() {
      var gumi = $.data(this, 'gumi');

      if (!gumi) {
        $.data(this, 'gumi', new Gumi(this, options));
      } else {
        return {
          setSelected: gumi.setSelected,
          setSelectedOption: gumi.setSelectedOption,
          onEvent: gumi.onEvent,
          closeDropdown: gumi.closeDropdown,
          reset: gumi.reset
        }
      }
    });
  };

})(jQuery, window, document);

<commit_msg>fix value error<commit_after>/**
 * Gumi v0.1
 * Usage: http://b1lly.github.io/gumi
 * GitHub: http://github.com/b1lly/gumi
 */

;(function($, window, document, undefined) {
  var defaults = {
    buttonClass: 'btn-default',
    buttonSelectedClass: 'btn-selected',
    optionDisabledClass: 'option-disabled',
    dropdownClass: 'dropdown-default',
    onChange: function() {},
    onOpen: function() {}
  };

  /**
   * @constructor
   */
  var Gumi = function(elem, options) {
    this.elem = elem;
    this.$elem = $(elem);
    this.$elem.addClass('gumi-wrap');

    // Reference to the button that shows the current selected option
    // and also handles the click event to show the dropdown
    this.$button = $('');

    // Contains a reference to the dropdown list of options
    this.$dropdown = this.$elem.find('ul').hide();

    // Native form select element that gumi links too
    this.$select = $('<select />');

    this.selectedIndex = 0;
    this.selectedLabel = undefined;
    this.selectedValue = undefined;

    this.options = $.extend({}, defaults, options);

    this._load = true;
    this._defaults = defaults;
    this._initialSelected = undefined;

    this._init();
  };

  /**
   * Build out our Gumi prototype and methods
   */
  Gumi.prototype = {
    constructor: Gumi,

    /**
     * Initialize the Gumi selectbox
     */
    _init: function() {
      this._createSelect();
      this._createDropdown();
      this._bindDropdown();
      this._bindSelectOption();
    },

    /**
     * Takes a serialized string of params and converts it to a map of data
     * based on the data attribute 'params' on the button node
     * e.g. { 'key' : 'val' }
     */
    _deserializeParams: function() {
      var params = this.$button.data('params'),
          data = {};

      if (!params) {
        return;
      }

      if (typeof params === 'string') {
        params = params.split(' ');

        var currentParam;
        for (var i = 0, len = params.length; i < len; i ++) {
          currentParam = params[i].split('=');
          data[currentParam[0]] = currentParam[1];
        }

        this._addDataToSelect(data);
      }
    },

    /**
     * Adds HTML5 Data attributes/values to the select
     * @param {object} data Map of data key to data value e.g. { 'height': 300 }
     */
    _addDataToSelect: function(data) {
      for (var key in data) {
        this.$select.data(key, data[key]);
      }
    },

    /**
     * Creates a hidden "<select>" based on
     * the list items from the ul jQuery selector
     */
    _createSelect: function() {
      var that = this,
          selectedIndex = 0;

      // Handle using a button that exists
      var $button = this.$elem.find('button');
      if ($button.length) {
        this.$button = $button;
      }

      // Copy some attributes over to our select
      this.$select
        .addClass(this.options.dropdownClass)
        .addClass(that.$button.data('class'))
        .attr('name', that.$button.data('name'))
        .prop('required', that.$button.data('required'))
        .hide();

      // Add 'data' params to the select as HTML data-attributes
      this._deserializeParams();

      // Add the list options to our select options
      this.$elem.find('li').each(function(index) {
        var $self = $(this),
            val = $self.data('value');

        var value = val === undefined && val !== '' ? $self.html() : val,
            label = $self.data('label') || $self.html() || value;

        // Figure out which one should be selected by default
        if ($self.data('selected') === true) {
          selectedIndex = index;
        }

        // Handle custom styling for disabled class
        if ($self.data('disabled') === true) {
          $self.addClass(that.options.optionDisabledClass);
        }

        // Only show options that are selectable
        if ($self.data('selectable') === false) {
          $self.hide();
        }

        $('<option />')
          .val(value)
          .append(label)
          .addClass($self.attr('class'))
          .appendTo(that.$select);
      });

      // Set the default option
      this.setSelectedOption(selectedIndex);

      // Attach our native select to the DOM
      this.$elem.append(this.$select);

      this.initialSelected = selectedIndex;
      this._load = false;
    },

    /**
     * Creates the clickable button to show
     * the dropdown, and attaches "optional"
     * custom classes to both the button and the dropdown
     */
    _createDropdown: function() {
      this.$button
        .addClass('gumi-btn')
        .addClass(this.options.buttonClass);

      // Insert the button before the dropdown
      this.$elem.prepend(this.$button);

      // Styling should hide the dropdown by default
      this.$dropdown
        .addClass('gumi-dropdown')
        .addClass(this.options.dropdownClass);
    },

    /**
     * Handle the interaction for showing and hiding the dropdown options
     */
    _bindDropdown: function() {
      var that = this;

      this.$button.on('click.Gumi', function(e) {
        e.preventDefault();
        e.stopPropagation();

        // We want to reset all other dropdowns on the page
        // to avoid having multiple dropdowns open at a time
        that._resetDropdowns(that.$elem);

        // Handles clicking the button toggling
        that.$button.toggleClass(that.options.buttonSelectedClass);
        that.$dropdown.toggle();

        if (that.$dropdown.is(':visible')) {
          that.options.onOpen.call(that.$elem);
        }
      });

      $(document).off('click.Gumi');
      $(document).on('click.Gumi', function(e) {
        if ($(e.target).closest('.gumi-dropdown').length === 0) {
          that._resetDropdowns();
        }
      });
    },

    /**
     * When a user selects an option, we need to update our native
     * <select> in addition to our instance data
     */
    _bindSelectOption: function() {
      var that = this;

      that.$dropdown.on('click.Gumi', 'li', function(e) {
        var $self = $(this);
        e.stopPropagation();

        if (!$self.data('disabled')) {
          that.setSelectedOption($(this).index());
          that.closeDropdown();
        }
      });
    },

    /**
     * Resets all dropdowns on the page to default state, excluding callee
     * @param {jQueryObject} $elem Optional element to exclude from reset
     */
    _resetDropdowns: function($elem) {
      $('.gumi-wrap').not($elem).each(function() {
        $(this).data('gumi').closeDropdown();
      });
    },

    /**
     * Set the selected option based on it's value
     * @param {string|number|boolean} value The value of the option to look for in our list
     */
    setSelected: function(value) {
      var $option = this.setSelectedOption(this.$select.find('option[value="' + value + '"]'));

      if ($option.length) {
        setSelectedOption($option.index());
      }
    },

    /**
     * Sets the selected state to the native select box
     * based on the index. Also updates the instance and the label on the button
     * @param {number} opt_index Index of the select option to select (defaults 0)
     */
    setSelectedOption: function(opt_index) {
      opt_index = opt_index || 0;

      var $option = this.$select.find('option').eq(opt_index);

      this.selectedIndex = opt_index;
      this.selectedLabel = this.$dropdown.eq(opt_index).data('label') || $option.text();
      this.selectedValue = $option.val();

      $option
        .prop('selected', true)
        .trigger('change');

      if (this._load === false ||
          (this._load === true && !this.$button.data('default-value'))) {
        this.$button.html('' + this.selectedLabel + ' ');

        // Trigger our custom callback
        this.options.onChange.call(this.$select);
      }
    },

    /**
     * Public interface to bind a custom change event handler
     * @param {string} evt The event type to listen to
     * @param {function} fn The function callback for the event
     */
    onEvent: function(evt, fn) {
      if (typeof fn === 'function') {
        if (this.options[evt]) {
          this.options[evt] = fn;
        }
      }
    },

    /**
     * Hides the dropdown and removes the selected state of the button
     */
    closeDropdown: function() {
      this.$button.removeClass(this.options.buttonSelectedClass);
      this.$dropdown.hide();
    },

    /**
     * Resets the dropdown to it's original state during initialization
     */
    reset: function() {
      this.setSelectedOption(this._initialSelected);
    }
  };

  /**
   * Simple jQuery API for Gumi
   */
  $.fn.gumi = function(options) {
    return this.each(function() {
      var gumi = $.data(this, 'gumi');

      if (!gumi) {
        $.data(this, 'gumi', new Gumi(this, options));
      } else {
        return {
          setSelected: gumi.setSelected,
          setSelectedOption: gumi.setSelectedOption,
          onEvent: gumi.onEvent,
          closeDropdown: gumi.closeDropdown,
          reset: gumi.reset
        }
      }
    });
  };

})(jQuery, window, document);

<|endoftext|>


<commit_before>/*jslint unparam: true, browser: true, indent: 2 */

;(function ($, window, document, undefined) {
  'use strict';

  Foundation.libs.topbar = {
    name : 'topbar',

    version : '4.2.3',

    settings : {
      index : 0,
      stickyClass : 'sticky',
      custom_back_text: true,
      back_text: 'Back',
      is_hover: true,
      scrolltop : true, // jump to top when sticky nav menu toggle is clicked
      init : false
    },

    init : function (section, method, options) {
      Foundation.inherit(this, 'data_options');
      var self = this;

      if (typeof method === 'object') {
        $.extend(true, this.settings, method);
      } else if (typeof options !== 'undefined') {
        $.extend(true, this.settings, options);
      }

      if (typeof method !== 'string') {

        $('.top-bar, [data-topbar]').each(function () {
          $.extend(true, self.settings, self.data_options($(this)));
          self.settings.$w = $(window);
          self.settings.$topbar = $(this);
          self.settings.$section = self.settings.$topbar.find('section');
          self.settings.$titlebar = self.settings.$topbar.children('ul').first();
          self.settings.$topbar.data('index', 0);

          var breakpoint = $("
").insertAfter(self.settings.$topbar);
          self.settings.breakPoint = breakpoint.width();
          breakpoint.remove();

          self.assemble();

          if (self.settings.$topbar.parent().hasClass('fixed')) {
            $('body').css('padding-top', self.outerHeight(self.settings.$topbar));
          }
        });

        if (!self.settings.init) {
          this.events();
        }

        return this.settings.init;
      } else {
        // fire method
        return this[method].call(this, options);
      }
    },

    events : function () {
      var self = this;
      var offst = this.outerHeight($('.top-bar, [data-topbar]'));
      $(this.scope)
        .off('.fndtn.topbar')
        .on('click.fndtn.topbar', '.top-bar .toggle-topbar, [data-topbar] .toggle-topbar', function (e) {
          var topbar = $(this).closest('.top-bar, [data-topbar]'),
              section = topbar.find('section, .section'),
              titlebar = topbar.children('ul').first();

          e.preventDefault();

          if (self.breakpoint()) {
            if (!self.rtl) {
              section.css({left: '0%'});
              section.find('>.name').css({left: '100%'});
            } else {
              section.css({right: '0%'});
              section.find('>.name').css({right: '100%'});
            }

            section.find('li.moved').removeClass('moved');
            topbar.data('index', 0);

            topbar
              .toggleClass('expanded')
              .css('height', '');
          }

          if (!topbar.hasClass('expanded')) {
            if (topbar.hasClass('fixed')) {
              topbar.parent().addClass('fixed');
              topbar.removeClass('fixed');
              $('body').css('padding-top',offst);
            }
          } else if (topbar.parent().hasClass('fixed')) {
            topbar.parent().removeClass('fixed');
            topbar.addClass('fixed');
            $('body').css('padding-top','0');

            if (self.settings.scrolltop) {
              window.scrollTo(0,0);
            }
          }
        })

        .on('mouseenter mouseleave', '.top-bar li', function (e) {
          if (!self.settings.is_hover) return;

          if (/enter|over/i.test(e.type)) {
            $(this).addClass('hover');
          } else {
            $(this).removeClass('hover');
          }
        })

        .on('click.fndtn.topbar', '.top-bar li.has-dropdown', function (e) {
          if (self.breakpoint()) return;

          var li = $(this),
              target = $(e.target),
              topbar = li.closest('[data-topbar], .top-bar'),
              is_hover = topbar.data('topbar');

          if (self.settings.is_hover && !Modernizr.touch) return;

          e.stopImmediatePropagation();

          if (target[0].nodeName === 'A' && target.parent().hasClass('has-dropdown')) {
            e.preventDefault();
          }

          if (li.hasClass('hover')) {
            li
              .removeClass('hover')
              .find('li')
              .removeClass('hover');
          } else {
            li.addClass('hover');
          }
        })

        .on('click.fndtn.topbar', '.top-bar .has-dropdown>a, [data-topbar] .has-dropdown>a', function (e) {
          if (self.breakpoint()) {
            e.preventDefault();

            var $this = $(this),
                topbar = $this.closest('.top-bar, [data-topbar]'),
                section = topbar.find('section, .section'),
                titlebar = topbar.children('ul').first(),
                dropdownHeight = $this.next('.dropdown').outerHeight(),
                $selectedLi = $this.closest('li');

            topbar.data('index', topbar.data('index') + 1);
            $selectedLi.addClass('moved');

            if (!self.rtl) {
              section.css({left: -(100 * topbar.data('index')) + '%'});
              section.find('>.name').css({left: 100 * topbar.data('index') + '%'});
            } else {
              section.css({right: -(100 * topbar.data('index')) + '%'});
              section.find('>.name').css({right: 100 * topbar.data('index') + '%'});
            }

            topbar.css('height', self.outerHeight($this.siblings('ul'), true) + self.outerHeight(titlebar, true));
          }
        });

      $(window).on('resize.fndtn.topbar', function () {
        if (!self.breakpoint()) {
          $('.top-bar, [data-topbar]')
            .css('height', '')
            .removeClass('expanded')
            .find('li')
            .removeClass('hover');
        }
      }.bind(this));

      $('body').on('click.fndtn.topbar', function (e) {
        var parent = $(e.target).closest('[data-topbar], .top-bar');

        if (parent.length > 0) {
          return;
        }

        $('.top-bar li, [data-topbar] li').removeClass('hover');
      });

      // Go up a level on Click
      $(this.scope).on('click.fndtn', '.top-bar .has-dropdown .back, [data-topbar] .has-dropdown .back', function (e) {
        e.preventDefault();

        var $this = $(this),
            topbar = $this.closest('.top-bar, [data-topbar]'),
            titlebar = topbar.children('ul').first(),
            section = topbar.find('section, .section'),
            $movedLi = $this.closest('li.moved'),
            $previousLevelUl = $movedLi.parent();

        topbar.data('index', topbar.data('index') - 1);

        if (!self.rtl) {
          section.css({left: -(100 * topbar.data('index')) + '%'});
          section.find('>.name').css({left: 100 * topbar.data('index') + '%'});
        } else {
          section.css({right: -(100 * topbar.data('index')) + '%'});
          section.find('>.name').css({right: 100 * topbar.data('index') + '%'});
        }

        if (topbar.data('index') === 0) {
          topbar.css('height', '');
        } else {
          topbar.css('height', self.outerHeight($previousLevelUl, true) + self.outerHeight(titlebar, true));
        }

        setTimeout(function () {
          $movedLi.removeClass('moved');
        }, 300);
      });
    },

    breakpoint : function () {
      return $(document).width() <= this.settings.breakPoint || $('html').hasClass('lt-ie9');
    },

    assemble : function () {
      var self = this;
      // Pull element out of the DOM for manipulation
      this.settings.$section.detach();

      this.settings.$section.find('.has-dropdown>a').each(function () {
        var $link = $(this),
            $dropdown = $link.siblings('.dropdown'),
            url = $link.attr('href');

        if (url && url.length > 1) {
          var $titleLi = $('

' + $link.text() +'
');
        } else {
          var $titleLi = $('

');
        }

        // Copy link to subnav
        if (self.settings.custom_back_text == true) {
          $titleLi.find('h5>a').html('« ' + self.settings.back_text);
        } else {
          $titleLi.find('h5>a').html('« ' + $link.html());
        }
        $dropdown.prepend($titleLi);
      });

      // Put element back in the DOM
      this.settings.$section.appendTo(this.settings.$topbar);

      // check for sticky
      this.sticky();
    },

    height : function (ul) {
      var total = 0,
          self = this;

      ul.find('> li').each(function () { total += self.outerHeight($(this), true); });

      return total;
    },

    sticky : function () {
      var klass = '.' + this.settings.stickyClass;
      if ($(klass).length > 0) {
        var distance = $(klass).length ? $(klass).offset().top: 0,
            $window = $(window);
            var offst = this.outerHeight($('.top-bar'));
        //Whe resize elements of the page on windows resize. Must recalculate distance
		$(window).resize(function() {
            clearTimeout(t_top);
			t_top = setTimeout (function() {
				distance = $(klass).offset().top;
			},105);
		});
          $window.scroll(function() {
            if ($window.scrollTop() > (distance)) {
              $(klass).addClass("fixed");
              $('body').css('padding-top',offst);
            }

            else if ($window.scrollTop() <= distance) {
              $(klass).removeClass("fixed");
              $('body').css('padding-top','0');
            }
        });
      }
    },

    off : function () {
      $(this.scope).off('.fndtn.topbar');
      $(window).off('.fndtn.topbar');
    },

    reflow : function () {}
  };
}(Foundation.zj, this, this.document));
<commit_msg>Declares t_top variable before it's used on window resize.<commit_after>/*jslint unparam: true, browser: true, indent: 2 */

;(function ($, window, document, undefined) {
  'use strict';

  Foundation.libs.topbar = {
    name : 'topbar',

    version : '4.2.3',

    settings : {
      index : 0,
      stickyClass : 'sticky',
      custom_back_text: true,
      back_text: 'Back',
      is_hover: true,
      scrolltop : true, // jump to top when sticky nav menu toggle is clicked
      init : false
    },

    init : function (section, method, options) {
      Foundation.inherit(this, 'data_options');
      var self = this;

      if (typeof method === 'object') {
        $.extend(true, this.settings, method);
      } else if (typeof options !== 'undefined') {
        $.extend(true, this.settings, options);
      }

      if (typeof method !== 'string') {

        $('.top-bar, [data-topbar]').each(function () {
          $.extend(true, self.settings, self.data_options($(this)));
          self.settings.$w = $(window);
          self.settings.$topbar = $(this);
          self.settings.$section = self.settings.$topbar.find('section');
          self.settings.$titlebar = self.settings.$topbar.children('ul').first();
          self.settings.$topbar.data('index', 0);

          var breakpoint = $("
").insertAfter(self.settings.$topbar);
          self.settings.breakPoint = breakpoint.width();
          breakpoint.remove();

          self.assemble();

          if (self.settings.$topbar.parent().hasClass('fixed')) {
            $('body').css('padding-top', self.outerHeight(self.settings.$topbar));
          }
        });

        if (!self.settings.init) {
          this.events();
        }

        return this.settings.init;
      } else {
        // fire method
        return this[method].call(this, options);
      }
    },

    events : function () {
      var self = this;
      var offst = this.outerHeight($('.top-bar, [data-topbar]'));
      $(this.scope)
        .off('.fndtn.topbar')
        .on('click.fndtn.topbar', '.top-bar .toggle-topbar, [data-topbar] .toggle-topbar', function (e) {
          var topbar = $(this).closest('.top-bar, [data-topbar]'),
              section = topbar.find('section, .section'),
              titlebar = topbar.children('ul').first();

          e.preventDefault();

          if (self.breakpoint()) {
            if (!self.rtl) {
              section.css({left: '0%'});
              section.find('>.name').css({left: '100%'});
            } else {
              section.css({right: '0%'});
              section.find('>.name').css({right: '100%'});
            }

            section.find('li.moved').removeClass('moved');
            topbar.data('index', 0);

            topbar
              .toggleClass('expanded')
              .css('height', '');
          }

          if (!topbar.hasClass('expanded')) {
            if (topbar.hasClass('fixed')) {
              topbar.parent().addClass('fixed');
              topbar.removeClass('fixed');
              $('body').css('padding-top',offst);
            }
          } else if (topbar.parent().hasClass('fixed')) {
            topbar.parent().removeClass('fixed');
            topbar.addClass('fixed');
            $('body').css('padding-top','0');

            if (self.settings.scrolltop) {
              window.scrollTo(0,0);
            }
          }
        })

        .on('mouseenter mouseleave', '.top-bar li', function (e) {
          if (!self.settings.is_hover) return;

          if (/enter|over/i.test(e.type)) {
            $(this).addClass('hover');
          } else {
            $(this).removeClass('hover');
          }
        })

        .on('click.fndtn.topbar', '.top-bar li.has-dropdown', function (e) {
          if (self.breakpoint()) return;

          var li = $(this),
              target = $(e.target),
              topbar = li.closest('[data-topbar], .top-bar'),
              is_hover = topbar.data('topbar');

          if (self.settings.is_hover && !Modernizr.touch) return;

          e.stopImmediatePropagation();

          if (target[0].nodeName === 'A' && target.parent().hasClass('has-dropdown')) {
            e.preventDefault();
          }

          if (li.hasClass('hover')) {
            li
              .removeClass('hover')
              .find('li')
              .removeClass('hover');
          } else {
            li.addClass('hover');
          }
        })

        .on('click.fndtn.topbar', '.top-bar .has-dropdown>a, [data-topbar] .has-dropdown>a', function (e) {
          if (self.breakpoint()) {
            e.preventDefault();

            var $this = $(this),
                topbar = $this.closest('.top-bar, [data-topbar]'),
                section = topbar.find('section, .section'),
                titlebar = topbar.children('ul').first(),
                dropdownHeight = $this.next('.dropdown').outerHeight(),
                $selectedLi = $this.closest('li');

            topbar.data('index', topbar.data('index') + 1);
            $selectedLi.addClass('moved');

            if (!self.rtl) {
              section.css({left: -(100 * topbar.data('index')) + '%'});
              section.find('>.name').css({left: 100 * topbar.data('index') + '%'});
            } else {
              section.css({right: -(100 * topbar.data('index')) + '%'});
              section.find('>.name').css({right: 100 * topbar.data('index') + '%'});
            }

            topbar.css('height', self.outerHeight($this.siblings('ul'), true) + self.outerHeight(titlebar, true));
          }
        });

      $(window).on('resize.fndtn.topbar', function () {
        if (!self.breakpoint()) {
          $('.top-bar, [data-topbar]')
            .css('height', '')
            .removeClass('expanded')
            .find('li')
            .removeClass('hover');
        }
      }.bind(this));

      $('body').on('click.fndtn.topbar', function (e) {
        var parent = $(e.target).closest('[data-topbar], .top-bar');

        if (parent.length > 0) {
          return;
        }

        $('.top-bar li, [data-topbar] li').removeClass('hover');
      });

      // Go up a level on Click
      $(this.scope).on('click.fndtn', '.top-bar .has-dropdown .back, [data-topbar] .has-dropdown .back', function (e) {
        e.preventDefault();

        var $this = $(this),
            topbar = $this.closest('.top-bar, [data-topbar]'),
            titlebar = topbar.children('ul').first(),
            section = topbar.find('section, .section'),
            $movedLi = $this.closest('li.moved'),
            $previousLevelUl = $movedLi.parent();

        topbar.data('index', topbar.data('index') - 1);

        if (!self.rtl) {
          section.css({left: -(100 * topbar.data('index')) + '%'});
          section.find('>.name').css({left: 100 * topbar.data('index') + '%'});
        } else {
          section.css({right: -(100 * topbar.data('index')) + '%'});
          section.find('>.name').css({right: 100 * topbar.data('index') + '%'});
        }

        if (topbar.data('index') === 0) {
          topbar.css('height', '');
        } else {
          topbar.css('height', self.outerHeight($previousLevelUl, true) + self.outerHeight(titlebar, true));
        }

        setTimeout(function () {
          $movedLi.removeClass('moved');
        }, 300);
      });
    },

    breakpoint : function () {
      return $(document).width() <= this.settings.breakPoint || $('html').hasClass('lt-ie9');
    },

    assemble : function () {
      var self = this;
      // Pull element out of the DOM for manipulation
      this.settings.$section.detach();

      this.settings.$section.find('.has-dropdown>a').each(function () {
        var $link = $(this),
            $dropdown = $link.siblings('.dropdown'),
            url = $link.attr('href');

        if (url && url.length > 1) {
          var $titleLi = $('

' + $link.text() +'
');
        } else {
          var $titleLi = $('

');
        }

        // Copy link to subnav
        if (self.settings.custom_back_text == true) {
          $titleLi.find('h5>a').html('« ' + self.settings.back_text);
        } else {
          $titleLi.find('h5>a').html('« ' + $link.html());
        }
        $dropdown.prepend($titleLi);
      });

      // Put element back in the DOM
      this.settings.$section.appendTo(this.settings.$topbar);

      // check for sticky
      this.sticky();
    },

    height : function (ul) {
      var total = 0,
          self = this;

      ul.find('> li').each(function () { total += self.outerHeight($(this), true); });

      return total;
    },

    sticky : function () {
      var klass = '.' + this.settings.stickyClass;
      if ($(klass).length > 0) {
        var distance = $(klass).length ? $(klass).offset().top: 0,
            $window = $(window),
            offst = this.outerHeight($('.top-bar')),
            t_top;
        //Whe resize elements of the page on windows resize. Must recalculate distance
		$(window).resize(function() {
            clearTimeout(t_top);
			t_top = setTimeout (function() {
				distance = $(klass).offset().top;
			},105);
		});
          $window.scroll(function() {
            if ($window.scrollTop() > (distance)) {
              $(klass).addClass("fixed");
              $('body').css('padding-top',offst);
            }

            else if ($window.scrollTop() <= distance) {
              $(klass).removeClass("fixed");
              $('body').css('padding-top','0');
            }
        });
      }
    },

    off : function () {
      $(this.scope).off('.fndtn.topbar');
      $(window).off('.fndtn.topbar');
    },

    reflow : function () {}
  };
}(Foundation.zj, this, this.document));
<|endoftext|>


<commit_before>    var txmap = {};
    txmap.map = {};
    txmap.latLng = new qq.maps.LatLng('22.5428234337', '114.0595370000');
    txmap.init = function() {
//        try{
//            wx.getLocation({
//                type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
//                success: function (res) {
//                    txmap.latLong = {
//                                        latitude: res.latitude,// 纬度，浮点数，范围为90 ~ -90
//                                        longitude: res.longitude// 经度，浮点数，范围为180 ~ -180。
//                                    }
//                    txmap.speed = res.speed; // 速度，以米/每秒计
//                    txmap.accuracy = res.accuracy; // 位置精度
//
//    /*--start---创建街景--start---*/
//    //                pano = new qq.maps.Panorama(document.getElementById('container'), {
//    //                      pano: '10011501120802180635300',    //场景ID
//    //                      pov:{   //视角
//    //                              heading:1,  //偏航角
//    //                              pitch:0     //俯仰角
//    //                          },
//    //                      zoom:1      //缩放
//    //                  })
//    //                pano_service = new qq.maps.PanoramaService();
//    //                var point = {lat: latitude, lng: longitude};
//    //                var radius;
//    //                pano_service.getPano(point, radius, function (result){
//    //                    pano.setPano(result.svid);
//    //                });
//    /*---end----创建街景---end----*/
//                }
//            });
//        }catch(e){
//            throw 'open in wechat';
//        }

        //var sw = new qq.maps.LatLng(txmap.latLong.latitude-0.03949, txmap.latLong.latitude-0.03949); //西南角坐标
        //var ne = new qq.maps.LatLng(txmap.latLong.latitude+0.03949, txmap.latLong.latitude+0.03949); //东北角坐标
        //var latlngBounds = new qq.maps.LatLngBounds(ne, sw); //矩形的地理坐标范围

        //div容器
        var container = document.getElementById("container");

        //初始化地图
        this.map = new qq.maps.Map(container, {
            // 地图的中心地理坐标。
            center: txmap.latLng,
            zoom: 13
        });

        qq.maps.event.addListener(this.map, 'click', function(e){
            //txmap.map.panTo(new qq.maps.LatLng(e.latLng.lat, e.latLng.lng));
        });

        qq.maps.event.addListener(this.map, 'dbclick', function(e){
            if(txmap.map.getZoom()===18){
                $('.weui_actionsheet_cell').data(e);
                var mask = $('#mask');
                var weuiActionsheet = $('#weui_actionsheet');
                weuiActionsheet.addClass('weui_actionsheet_toggle');
                mask.show().addClass('weui_fade_toggle').one('click', function () {
                    hideActionSheet(weuiActionsheet, mask);
                });
                $('#actionsheet_cancel').one('click', function () {
                    hideActionSheet(weuiActionsheet, mask);
                });
                weuiActionsheet.unbind('transitionend').unbind('webkitTransitionEnd');

                function hideActionSheet(weuiActionsheet, mask) {
                    weuiActionsheet.removeClass('weui_actionsheet_toggle');
                    mask.removeClass('weui_fade_toggle');
                    weuiActionsheet.on('transitionend', function () {
                        mask.hide();
                    }).on('webkitTransitionEnd', function () {
                        mask.hide();
                    })
                }
            }
        });

        qq.maps.event.addListener(this.map, 'rightclick', function(e){
            $('.weui_actionsheet_cell').data(e);

            var mask = $('#mask');
            var weuiActionsheet = $('#weui_actionsheet');
            weuiActionsheet.addClass('weui_actionsheet_toggle');
            mask.show().addClass('weui_fade_toggle').one('click', function () {
                hideActionSheet(weuiActionsheet, mask);
            });
            $('#actionsheet_cancel').one('click', function () {
                hideActionSheet(weuiActionsheet, mask);
            });
            weuiActionsheet.unbind('transitionend').unbind('webkitTransitionEnd');

            function hideActionSheet(weuiActionsheet, mask) {
                weuiActionsheet.removeClass('weui_actionsheet_toggle');
                mask.removeClass('weui_fade_toggle');
                weuiActionsheet.on('transitionend', function () {
                    mask.hide();
                }).on('webkitTransitionEnd', function () {
                    mask.hide();
                })
            }
        });

        //根据指定的范围调整地图视野。
        //map.fitBounds(latlngBounds);
        qq.maps.event.addListener(this.map, 'bounds_changed', function () {
            //console.log("地图的可视范围为：" + map.getBounds());
        });

        qq.maps.event.addListener(this.map, 'center_changed', function () {
            //console.log("地图中心为：" + map.getCenter());
        });

        //当地图缩放级别更改时会触发此事件。
        qq.maps.event.addListener(this.map, 'zoom_changed', function () {
            //console.log("地图缩放级别为：" + map.getZoom());
        });

        qq.maps.event.addListener(this.map, 'maptypeid_changed', function () {
            //console.log("地图类型ID为：" + map.getMapTypeId());
        });

        $('body').on('click', '.weui_actionsheet_cell:eq(0)', function(e){
            /*--start---创建街景--start---*/
            var latLng = $(this).data().latLng;
            pano_service = new qq.maps.PanoramaService();
            var point = {lat: latLng.lat, lng: latLng.lng};
            var radius;
            pano_service.getPano(point, radius, function (result){
                pano = new qq.maps.Panorama(document.getElementById('container'), {
                    //pano: '10011501120802180635300',    //场景ID
                    pov:{   //视角
                            heading:1,  //偏航角
                            pitch:0     //俯仰角
                        },
                    zoom:1      //缩放
                })
                pano.setPano(result.svid);
            });

            $('#mask').click();
            /*---end----创建街景---end----*/
        });

        $('body').on('click', '.weui_actionsheet_cell:eq(1)', function(e){
            $('#loadingToast').find('.weui_toast_content').html('敬请期待').end().show();
        });

        $('body').on('click', '.weui_actionsheet_cell:eq(2)', function(e){
            $('#loadingToast').find('.weui_toast_content').html('敬请期待').end().show();
        });

        $('body').on('click', '.weui_actionsheet_cell:eq(3)', function(e){
            $('#loadingToast').find('.weui_toast_content').html('敬请期待').end().show();
        });

//        var times = 0;
//        var oInterval = setInterval(function () {
//
//            //panBy()将地图中心移动一段指定的距离（以像素为单位）。
//            map.panBy(-100, 100);
//
//            //zoomBy()将地图缩放到指定的缩放比例（每次所增加的数值）。
//            map.zoomBy(5);
//            times++;
//            if (times >= 1) {
//                clearInterval(oInterval)
//            }
//        }, 3 * 1000);
//
//
//        setTimeout(function () {
//
//            //panTo()将地图中心移动到指定的经纬度坐标。
//            map.panTo(new qq.maps.LatLng(39.9, 116.4));
//
//            //zoomTo()将地图缩放到指定的级别。
//            map.zoomTo(15);
//
//        }, 8 * 1000);
//
//
//        setTimeout(function () {
//            //setCenter()设置地图中心点坐标。
//            map.setCenter(new qq.maps.LatLng(30, 117));
//
//            //setZoom()设置地图缩放级别。
//            map.setZoom(6);
//
//            //setMapTypeId()设置地图类型。
//            map.setMapTypeId(qq.maps.MapTypeId.HYBRID);
//
//        }, 15 * 1000);
//
//
//        setTimeout(function () {
//
//            //设置地图参数。
//            map.setOptions({
//                keyboardShortcuts: false,
//                scrollwheel: false
//            });
//
//        }, 30 * 1000);
    };

    txmap.init();

    if(openInWechat){
        wx.ready(function(res){
            wx.getLocation({
                type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                success: function (res) {
                    txmap.latLng = new qq.maps.LatLng(res.latitude, res.longitude);
                    txmap.speed = res.speed; // 速度，以米/每秒计
                    txmap.accuracy = res.accuracy; // 位置精度

                    txmap.map.setCenter(txmap.latLng);
                    var marker = new qq.maps.Marker({//设置marker标记
                        map: txmap.map,
                        position: txmap.latLng
                    });

                    //设置Marker的可见性，为true时可见,false时不可见，默认属性为true
                    marker.setVisible(true);
                    //设置Marker的动画属性为从落下
                    marker.setAnimation(qq.maps.MarkerAnimation.DOWN);
                    //设置Marker是否可以被拖拽，为true时可拖拽，false时不可拖拽，默认属性为false
                    marker.setDraggable(true);
                }
            });
        });
    }else{
        if($('#client_ip').val().indexOf('127.')>-1 && $('#client_ip').val().indexOf('10.')>-1){
            //获取  城市位置信息查询 接口
            citylocation = new qq.maps.CityService({
                //设置地图
                map : txmap.map,

                complete : function(results){
                    txmap.latLng = results.detail.latLng;
                    txmap.map.setCenter(txmap.latLng);
                    var marker = new qq.maps.Marker({//设置marker标记
                        map: txmap.map,
                        position: txmap.latLng
                    });
                    //设置Marker的可见性，为true时可见,false时不可见，默认属性为true
                    marker.setVisible(true);
                    //设置Marker的动画属性为从落下
                    marker.setAnimation(qq.maps.MarkerAnimation.DOWN);
                    //设置Marker是否可以被拖拽，为true时可拖拽，false时不可拖拽，默认属性为false
                    marker.setDraggable(true);
                }
            });

            citylocation.searchCityByIP($('#client_ip').val());
        }else{

            txmap.map.setCenter(txmap.latLng);
            var marker = new qq.maps.Marker({//设置marker标记
                map: txmap.map,
                position: txmap.latLng
            });

            //设置Marker的可见性，为true时可见,false时不可见，默认属性为true
            marker.setVisible(true);
            //设置Marker的动画属性为从落下
            marker.setAnimation(qq.maps.MarkerAnimation.DOWN);
            //设置Marker是否可以被拖拽，为true时可拖拽，false时不可拖拽，默认属性为false
            marker.setDraggable(true);
        }

    }<commit_msg>add map<commit_after>    var txmap = {};
    txmap.map = {};
    txmap.latLng = new qq.maps.LatLng('22.5428234337', '114.0595370000');
    txmap.init = function() {
//        try{
//            wx.getLocation({
//                type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
//                success: function (res) {
//                    txmap.latLong = {
//                                        latitude: res.latitude,// 纬度，浮点数，范围为90 ~ -90
//                                        longitude: res.longitude// 经度，浮点数，范围为180 ~ -180。
//                                    }
//                    txmap.speed = res.speed; // 速度，以米/每秒计
//                    txmap.accuracy = res.accuracy; // 位置精度
//
//    /*--start---创建街景--start---*/
//    //                pano = new qq.maps.Panorama(document.getElementById('container'), {
//    //                      pano: '10011501120802180635300',    //场景ID
//    //                      pov:{   //视角
//    //                              heading:1,  //偏航角
//    //                              pitch:0     //俯仰角
//    //                          },
//    //                      zoom:1      //缩放
//    //                  })
//    //                pano_service = new qq.maps.PanoramaService();
//    //                var point = {lat: latitude, lng: longitude};
//    //                var radius;
//    //                pano_service.getPano(point, radius, function (result){
//    //                    pano.setPano(result.svid);
//    //                });
//    /*---end----创建街景---end----*/
//                }
//            });
//        }catch(e){
//            throw 'open in wechat';
//        }

        //var sw = new qq.maps.LatLng(txmap.latLong.latitude-0.03949, txmap.latLong.latitude-0.03949); //西南角坐标
        //var ne = new qq.maps.LatLng(txmap.latLong.latitude+0.03949, txmap.latLong.latitude+0.03949); //东北角坐标
        //var latlngBounds = new qq.maps.LatLngBounds(ne, sw); //矩形的地理坐标范围

        //div容器
        var container = document.getElementById("container");

        //初始化地图
        this.map = new qq.maps.Map(container, {
            // 地图的中心地理坐标。
            center: txmap.latLng,
            zoom: 13
        });

        qq.maps.event.addListener(this.map, 'click', function(e){
            //txmap.map.panTo(new qq.maps.LatLng(e.latLng.lat, e.latLng.lng));
        });

        qq.maps.event.addListener(this.map, 'dbclick', function(e){
            if(txmap.map.getZoom()===18){
                $('.weui_actionsheet_cell').data(e);
                var mask = $('#mask');
                var weuiActionsheet = $('#weui_actionsheet');
                weuiActionsheet.addClass('weui_actionsheet_toggle');
                mask.show().addClass('weui_fade_toggle').one('click', function () {
                    hideActionSheet(weuiActionsheet, mask);
                });
                $('#actionsheet_cancel').one('click', function () {
                    hideActionSheet(weuiActionsheet, mask);
                });
                weuiActionsheet.unbind('transitionend').unbind('webkitTransitionEnd');

                function hideActionSheet(weuiActionsheet, mask) {
                    weuiActionsheet.removeClass('weui_actionsheet_toggle');
                    mask.removeClass('weui_fade_toggle');
                    weuiActionsheet.on('transitionend', function () {
                        mask.hide();
                    }).on('webkitTransitionEnd', function () {
                        mask.hide();
                    })
                }
            }
        });

        qq.maps.event.addListener(this.map, 'rightclick', function(e){
            $('.weui_actionsheet_cell').data(e);

            var mask = $('#mask');
            var weuiActionsheet = $('#weui_actionsheet');
            weuiActionsheet.addClass('weui_actionsheet_toggle');
            mask.show().addClass('weui_fade_toggle').one('click', function () {
                hideActionSheet(weuiActionsheet, mask);
            });
            $('#actionsheet_cancel').one('click', function () {
                hideActionSheet(weuiActionsheet, mask);
            });
            weuiActionsheet.unbind('transitionend').unbind('webkitTransitionEnd');

            function hideActionSheet(weuiActionsheet, mask) {
                weuiActionsheet.removeClass('weui_actionsheet_toggle');
                mask.removeClass('weui_fade_toggle');
                weuiActionsheet.on('transitionend', function () {
                    mask.hide();
                }).on('webkitTransitionEnd', function () {
                    mask.hide();
                })
            }
        });

        //根据指定的范围调整地图视野。
        //map.fitBounds(latlngBounds);
        qq.maps.event.addListener(this.map, 'bounds_changed', function () {
            //console.log("地图的可视范围为：" + map.getBounds());
        });

        qq.maps.event.addListener(this.map, 'center_changed', function () {
            //console.log("地图中心为：" + map.getCenter());
        });

        //当地图缩放级别更改时会触发此事件。
        qq.maps.event.addListener(this.map, 'zoom_changed', function () {
            //console.log("地图缩放级别为：" + map.getZoom());
        });

        qq.maps.event.addListener(this.map, 'maptypeid_changed', function () {
            //console.log("地图类型ID为：" + map.getMapTypeId());
        });

        $('body').on('click', '.weui_actionsheet_cell:eq(0)', function(e){
            /*--start---创建街景--start---*/
            var latLng = $(this).data().latLng;
            pano_service = new qq.maps.PanoramaService();
            var point = {lat: latLng.lat, lng: latLng.lng};
            var radius;
            pano_service.getPano(point, radius, function (result){
                pano = new qq.maps.Panorama(document.getElementById('container'), {
                    //pano: '10011501120802180635300',    //场景ID
                    pov:{   //视角
                            heading:1,  //偏航角
                            pitch:0     //俯仰角
                        },
                    zoom:1      //缩放
                })
                pano.setPano(result.svid);
            });

            $('#mask').click();
            /*---end----创建街景---end----*/
        });

        $('body').on('click', '.weui_actionsheet_cell:eq(1)', function(e){
            $('#loadingToast').find('.weui_toast_content').html('敬请期待').end().show();
            setTimeout(function(){
                $('#loadingToast').hdie();
            }, 2000);
        });

        $('body').on('click', '.weui_actionsheet_cell:eq(2)', function(e){
            $('#loadingToast').find('.weui_toast_content').html('敬请期待').end().show();
            setTimeout(function(){
                $('#loadingToast').hdie();
            }, 2000);
        });

        $('body').on('click', '.weui_actionsheet_cell:eq(3)', function(e){
            $('#loadingToast').find('.weui_toast_content').html('敬请期待').end().show();
            setTimeout(function(){
                $('#loadingToast').hdie();
            }, 2000);
        });

//        var times = 0;
//        var oInterval = setInterval(function () {
//
//            //panBy()将地图中心移动一段指定的距离（以像素为单位）。
//            map.panBy(-100, 100);
//
//            //zoomBy()将地图缩放到指定的缩放比例（每次所增加的数值）。
//            map.zoomBy(5);
//            times++;
//            if (times >= 1) {
//                clearInterval(oInterval)
//            }
//        }, 3 * 1000);
//
//
//        setTimeout(function () {
//
//            //panTo()将地图中心移动到指定的经纬度坐标。
//            map.panTo(new qq.maps.LatLng(39.9, 116.4));
//
//            //zoomTo()将地图缩放到指定的级别。
//            map.zoomTo(15);
//
//        }, 8 * 1000);
//
//
//        setTimeout(function () {
//            //setCenter()设置地图中心点坐标。
//            map.setCenter(new qq.maps.LatLng(30, 117));
//
//            //setZoom()设置地图缩放级别。
//            map.setZoom(6);
//
//            //setMapTypeId()设置地图类型。
//            map.setMapTypeId(qq.maps.MapTypeId.HYBRID);
//
//        }, 15 * 1000);
//
//
//        setTimeout(function () {
//
//            //设置地图参数。
//            map.setOptions({
//                keyboardShortcuts: false,
//                scrollwheel: false
//            });
//
//        }, 30 * 1000);
    };

    txmap.init();

    if(openInWechat){
        wx.ready(function(res){
            wx.getLocation({
                type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                success: function (res) {
                    txmap.latLng = new qq.maps.LatLng(res.latitude, res.longitude);
                    txmap.speed = res.speed; // 速度，以米/每秒计
                    txmap.accuracy = res.accuracy; // 位置精度

                    txmap.map.setCenter(txmap.latLng);
                    var marker = new qq.maps.Marker({//设置marker标记
                        map: txmap.map,
                        position: txmap.latLng
                    });

                    //设置Marker的可见性，为true时可见,false时不可见，默认属性为true
                    marker.setVisible(true);
                    //设置Marker的动画属性为从落下
                    marker.setAnimation(qq.maps.MarkerAnimation.DOWN);
                    //设置Marker是否可以被拖拽，为true时可拖拽，false时不可拖拽，默认属性为false
                    marker.setDraggable(true);
                }
            });
        });
    }else{
        if($('#client_ip').val().indexOf('127.')>-1 && $('#client_ip').val().indexOf('10.')>-1){
            //获取  城市位置信息查询 接口
            citylocation = new qq.maps.CityService({
                //设置地图
                map : txmap.map,

                complete : function(results){
                    txmap.latLng = results.detail.latLng;
                    txmap.map.setCenter(txmap.latLng);
                    var marker = new qq.maps.Marker({//设置marker标记
                        map: txmap.map,
                        position: txmap.latLng
                    });
                    //设置Marker的可见性，为true时可见,false时不可见，默认属性为true
                    marker.setVisible(true);
                    //设置Marker的动画属性为从落下
                    marker.setAnimation(qq.maps.MarkerAnimation.DOWN);
                    //设置Marker是否可以被拖拽，为true时可拖拽，false时不可拖拽，默认属性为false
                    marker.setDraggable(true);
                }
            });

            citylocation.searchCityByIP($('#client_ip').val());
        }else{

            txmap.map.setCenter(txmap.latLng);
            var marker = new qq.maps.Marker({//设置marker标记
                map: txmap.map,
                position: txmap.latLng
            });

            //设置Marker的可见性，为true时可见,false时不可见，默认属性为true
            marker.setVisible(true);
            //设置Marker的动画属性为从落下
            marker.setAnimation(qq.maps.MarkerAnimation.DOWN);
            //设置Marker是否可以被拖拽，为true时可拖拽，false时不可拖拽，默认属性为false
            marker.setDraggable(true);
        }

    }<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// The onClicked callback function.
function onClickHandler(info, tab) {
  // http://stackoverflow.com/questions/8262266/xmlhttprequest-multipart-related-post-with-xml-and-image-as-payload
  function gen_multipart(metadata, image, mimetype) {
    image = new Uint8Array(image); // Wrap in view to get data

    var before = [
      "Media multipart posting\n",
      '--END_OF_PART', "\n",
      metadata,
      '--END_OF_PART', "\n",
      'Content-Type:', mimetype, "\n\n"].join('');
    var after = '\n--END_OF_PART--';
    var size = before.length + image.byteLength + after.length;
    var uint8array = new Uint8Array(size);
    var i = 0;

    // Append the string.
    for (; i<before.length; i++) {
        uint8array[i] = before.charCodeAt(i) & 0xff;
    }

    // Append the binary data.
    for (var j=0; j<image.byteLength; i++, j++) {
        uint8array[i] = image[j];
    }

    // Append the remaining string
    for (var j=0; j<after.length; i++, j++) {
        uint8array[i] = after.charCodeAt(j) & 0xff;
    }
    return uint8array.buffer; // <-- This is an ArrayBuffer object!
  }

  function makeUploadMatadata(info, tab) {
    summary = "PageUrl:" + info.pageUrl + "\n" +
          "SrcUrl:" + info.srcUrl + "\n" +
          "title:" + tab.title;
    result =
      "Content-type: application/atom+xml\n\n" +
      "<entry xmlns='http://www.w3.org/2005/Atom'>\n" +
      "<title>"+ info.srcUrl +"</title>\n" +
      "" + summary + "\n" +
      "<category scheme=\"http://schemas.google.com/g/2005#kind\"" +
      " term=\"http://schemas.google.com/photos/2007#photo\"\n/>" +
      "</entry>\n"
    return result;
  };

  //http://stackoverflow.com/questions/8262266/xmlhttprequest-multipart-related-post-with-xml-and-image-as-payload
  function upload_to_album(arrayBuffer, filetype, albumid, metadata) {
    var request = gen_multipart(metadata, arrayBuffer, filetype);
    var url = 'http://picasaweb.google.com/data/feed/api/user/default/albumid/' + albumid;
    chrome.identity.getAuthToken({'interactive': true}, function (token) {
      uploadAlbum(url, request, token, true);
    });
  }

  function uploadAlbum(url, sendData, token, retry) {
    var method = 'POST';
    var xhr = new XMLHttpRequest();
    xhr.open(method, url, true);
    xhr.setRequestHeader("Content-Type",  'multipart/related; boundary="END_OF_PART"');
    xhr.setRequestHeader("MIME-version", "1.0");
    xhr.setRequestHeader("GData-Version", '3.0');
    //xhr.setRequestHeader("Content-Length", request.length);
    // Add OAuth Token
    xhr.setRequestHeader("Authorization", "Bearer " + token);
    xhr.onreadystatechange = function(data) {
        if (xhr.readyState == 4) {
          if (xhr.status == 401 && retry) {
            // 認証失敗
            chrome.identity.removeCachedAuthToken(
              {"token": token},
              function() {
                chrome.identity.getAuthToken({'interactive': true}, function (token) {
                  uploadAlbum(url, sendData, token, false);
                })
              });
          } else if (xhr.status != 201) {
            // なんかエラー
            alert(xhr.status + "\n" + xhr.responseText);
          }
        }
    };
    xhr.send(sendData);
  }

  function getImageToUpload(info, tab, albumid) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", info.srcUrl, true);
    xhr.responseType = "blob";

    xhr.onload = function(e) {
      if (this.status == 200) {
        var blob = this.response;
        var reader = new FileReader();
        reader.addEventListener("loadend", function(){
            upload_to_album(this.result, blob.type, albumid, makeUploadMatadata(info,tab));
        });
        reader.readAsArrayBuffer(blob);
      }
    };
    xhr.send();
  }

  function getAlbumId(info) {
    var menuId = info.menuItemId;
    if (menuId.substr(0,3) === "gp_") {
      return menuId.substr(3);
    } else {
      throw new Error("Not Google Photos Menus?");
    }
  }
  getImageToUpload(info, tab, getAlbumId(info));
};

chrome.contextMenus.onClicked.addListener(onClickHandler);

chrome.runtime.onInstalled.addListener(function() {
  var contexts = ["image"];
  var title = "Google Photosにアップロードするやつ";
  var parentId = "gp_parent"
  chrome.contextMenus.create({
    "title": title,
    "contexts":contexts,
    "id": parentId
  });
  chrome.contextMenus.create({
    "title": "default",
    "id": "gp_default",
    "contexts": contexts,
    "parentId": parentId
  });
});
<commit_msg>summary文字列をちょっと見易く<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// The onClicked callback function.
function onClickHandler(info, tab) {
  // http://stackoverflow.com/questions/8262266/xmlhttprequest-multipart-related-post-with-xml-and-image-as-payload
  function gen_multipart(metadata, image, mimetype) {
    image = new Uint8Array(image); // Wrap in view to get data

    var before = [
      "Media multipart posting\n",
      '--END_OF_PART', "\n",
      metadata,
      '--END_OF_PART', "\n",
      'Content-Type:', mimetype, "\n\n"].join('');
    var after = '\n--END_OF_PART--';
    var size = before.length + image.byteLength + after.length;
    var uint8array = new Uint8Array(size);
    var i = 0;

    // Append the string.
    for (; i<before.length; i++) {
        uint8array[i] = before.charCodeAt(i) & 0xff;
    }

    // Append the binary data.
    for (var j=0; j<image.byteLength; i++, j++) {
        uint8array[i] = image[j];
    }

    // Append the remaining string
    for (var j=0; j<after.length; i++, j++) {
        uint8array[i] = after.charCodeAt(j) & 0xff;
    }
    return uint8array.buffer; // <-- This is an ArrayBuffer object!
  }

  function makeUploadMatadata(info, tab) {
    summary = "PageUrl : " + info.pageUrl + "\n" +
          "SrcUrl : " + info.srcUrl + "\n" +
          "title : " + tab.title;
    result =
      "Content-type: application/atom+xml\n\n" +
      "<entry xmlns='http://www.w3.org/2005/Atom'>\n" +
      "<title>"+ info.srcUrl +"</title>\n" +
      "" + summary + "\n" +
      "<category scheme=\"http://schemas.google.com/g/2005#kind\"" +
      " term=\"http://schemas.google.com/photos/2007#photo\"\n/>" +
      "</entry>\n"
    return result;
  };

  //http://stackoverflow.com/questions/8262266/xmlhttprequest-multipart-related-post-with-xml-and-image-as-payload
  function upload_to_album(arrayBuffer, filetype, albumid, metadata) {
    var request = gen_multipart(metadata, arrayBuffer, filetype);
    var url = 'http://picasaweb.google.com/data/feed/api/user/default/albumid/' + albumid;
    chrome.identity.getAuthToken({'interactive': true}, function (token) {
      uploadAlbum(url, request, token, true);
    });
  }

  function uploadAlbum(url, sendData, token, retry) {
    var method = 'POST';
    var xhr = new XMLHttpRequest();
    xhr.open(method, url, true);
    xhr.setRequestHeader("Content-Type",  'multipart/related; boundary="END_OF_PART"');
    xhr.setRequestHeader("MIME-version", "1.0");
    xhr.setRequestHeader("GData-Version", '3.0');
    //xhr.setRequestHeader("Content-Length", request.length);
    // Add OAuth Token
    xhr.setRequestHeader("Authorization", "Bearer " + token);
    xhr.onreadystatechange = function(data) {
        if (xhr.readyState == 4) {
          if (xhr.status == 401 && retry) {
            // 認証失敗
            chrome.identity.removeCachedAuthToken(
              {"token": token},
              function() {
                chrome.identity.getAuthToken({'interactive': true}, function (token) {
                  uploadAlbum(url, sendData, token, false);
                })
              });
          } else if (xhr.status != 201) {
            // なんかエラー
            alert(xhr.status + "\n" + xhr.responseText);
          }
        }
    };
    xhr.send(sendData);
  }

  function getImageToUpload(info, tab, albumid) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", info.srcUrl, true);
    xhr.responseType = "blob";

    xhr.onload = function(e) {
      if (this.status == 200) {
        var blob = this.response;
        var reader = new FileReader();
        reader.addEventListener("loadend", function(){
            upload_to_album(this.result, blob.type, albumid, makeUploadMatadata(info,tab));
        });
        reader.readAsArrayBuffer(blob);
      }
    };
    xhr.send();
  }

  function getAlbumId(info) {
    var menuId = info.menuItemId;
    if (menuId.substr(0,3) === "gp_") {
      return menuId.substr(3);
    } else {
      throw new Error("Not Google Photos Menus?");
    }
  }
  getImageToUpload(info, tab, getAlbumId(info));
};

chrome.contextMenus.onClicked.addListener(onClickHandler);

chrome.runtime.onInstalled.addListener(function() {
  var contexts = ["image"];
  var title = "Google Photosにアップロードするやつ";
  var parentId = "gp_parent"
  chrome.contextMenus.create({
    "title": title,
    "contexts":contexts,
    "id": parentId
  });
  chrome.contextMenus.create({
    "title": "default",
    "id": "gp_default",
    "contexts": contexts,
    "parentId": parentId
  });
});
<|endoftext|>


<commit_before>var path = require('path');
var env = process.env.NODE_ENV || 'development';
var headers = { 'Content-Type': 'application/json' };

server = Bones.Server.extend({});

var options = {
    type: '.js',
    wrapper: Bones.utils.wrapClientFile,
    sort: Bones.utils.sortByLoadOrder
};

// TODO: This should be moved to the initialize method!
server.prototype.assets = {
    vendor: new mirror([
        require.resolve(path.join(__dirname, '../assets/jquery')),
        require.resolve('underscore'),
        require.resolve('backbone')
    ], { type: '.js' }),
    core: new mirror([
        require.resolve(path.join(__dirname, '../shared/utils')),
        require.resolve(path.join(__dirname, '../client/utils')),
        require.resolve(path.join(__dirname, '../shared/backbone')),
        require.resolve(path.join(__dirname, '../client/backbone'))
    ], { type: '.js' }),
    models: new mirror([], options),
    views: new mirror([], options),
    routers: new mirror([], options),
    templates: new mirror([], options)
};

if (env === 'development') {
    server.prototype.assets.core.unshift(require.resolve(path.join(__dirname, '../assets/debug')));
}

// TODO: This should be moved to the initialize method!
server.prototype.assets.all = new mirror([
    server.prototype.assets.vendor,
    server.prototype.assets.core,
    server.prototype.assets.routers,
    server.prototype.assets.models,
    server.prototype.assets.views,
    server.prototype.assets.templates
], { type: '.js' });

// Stores models, views served by this server.
// TODO: This should be moved to the initialize method!
server.prototype.models = {};
server.prototype.views = {};

// Stores instances of routers registered with this server.
// TODO: This should be moved to the initialize method!
server.prototype.routers = {};

server.prototype.initialize = function(app) {
    this.registerComponents(app);
    this.initializeAssets(app);
    this.initializeModels(app);
};

server.prototype.registerComponents = function(app) {
    var components = ['routers', 'models', 'views', 'templates'];
    components.forEach(function(kind) {
        for (var name in app[kind]) {
            app[kind][name].register(this);
        }
    }, this);
};

server.prototype.initializeAssets = function(app) {
    this.get('/assets/bones/vendor.js', this.assets.vendor.handler);
    this.get('/assets/bones/core.js', this.assets.core.handler);
    this.get('/assets/bones/routers.js', this.assets.routers.handler);
    this.get('/assets/bones/models.js', this.assets.models.handler);
    this.get('/assets/bones/views.js', this.assets.views.handler);
    this.get('/assets/bones/templates.js', this.assets.templates.handler);

    this.get('/assets/bones/all.js', this.assets.all.handler);
};

server.prototype.initializeModels = function(app) {
    this.models = app.models;
    _.bindAll(this, 'loadModel', 'getModel', 'saveModel', 'delModel', 'loadCollection');
    this.get('/api/:model/:id', [this.loadModel, this.getModel]);
    this.post('/api/:model', [this.loadModel, this.saveModel]);
    this.put('/api/:model/:id', [this.loadModel, this.saveModel]);
    this.del('/api/:model/:id', [this.loadModel, this.delModel]);
    this.get('/api/:collection', this.loadCollection.bind(this));
};

server.prototype.loadCollection = function(req, res, next) {
    var name = Bones.utils.pluralize(req.params.collection);
    if (name in this.models) {
        // Pass any querystring paramaters to the collection.
        req.collection = new this.models[name]([], req.query);
        req.collection.fetch({
            success: function(collection, resp) {
                res.send(resp, headers);
            },
            error: function(collection, err) {
                var error = err instanceof Object ? err.message : err;
                next(new Error.HTTP(error, err && err.status || 500));
            }
        });
    } else {
        next();
    }
};

server.prototype.loadModel = function(req, res, next) {
    var name = req.params.model;
    if (name in this.models) {
        // Pass any querystring paramaters to the model.
        req.model = new this.models[name]({ id: req.params.id }, req.query);
    }
    next();
};

server.prototype.getModel = function(req, res, next) {
    if (!req.model) return next();
    req.model.fetch({
        success: function(model, resp) {
            res.send(resp, headers);
        },
        error: function(model, err) {
            var error = err instanceof Object ? err.message : err;
            next(new Error.HTTP(error, err && err.status || 404));
        }
    });
};

server.prototype.saveModel = function(req, res, next) {
    if (!req.model) return next();
    req.model.save(req.body, {
        success: function(model, resp) {
            res.send(resp, headers);
        },
        error: function(model, err) {
            var error = err instanceof Object ? err.message : err;
            next(new Error.HTTP(error, err && err.status || 409));
        }
    });
};

server.prototype.delModel = function(req, res, next) {
    if (!req.model) return next();
    if (req.body && !req.model.set(req.body, {
        error: function(model, err) { next(err); }
    })) return;
    req.model.destroy({
        success: function(model, resp) {
            res.send(resp, headers);
        },
        error: function(model, err) {
            var error = err instanceof Object ? err.message : err;
            next(new Error.HTTP(error, err && err.status || 409));
        }
    });
};
<commit_msg>`id` in param wins over `id` in request body.<commit_after>var path = require('path');
var env = process.env.NODE_ENV || 'development';
var headers = { 'Content-Type': 'application/json' };

server = Bones.Server.extend({});

var options = {
    type: '.js',
    wrapper: Bones.utils.wrapClientFile,
    sort: Bones.utils.sortByLoadOrder
};

// TODO: This should be moved to the initialize method!
server.prototype.assets = {
    vendor: new mirror([
        require.resolve(path.join(__dirname, '../assets/jquery')),
        require.resolve('underscore'),
        require.resolve('backbone')
    ], { type: '.js' }),
    core: new mirror([
        require.resolve(path.join(__dirname, '../shared/utils')),
        require.resolve(path.join(__dirname, '../client/utils')),
        require.resolve(path.join(__dirname, '../shared/backbone')),
        require.resolve(path.join(__dirname, '../client/backbone'))
    ], { type: '.js' }),
    models: new mirror([], options),
    views: new mirror([], options),
    routers: new mirror([], options),
    templates: new mirror([], options)
};

if (env === 'development') {
    server.prototype.assets.core.unshift(require.resolve(path.join(__dirname, '../assets/debug')));
}

// TODO: This should be moved to the initialize method!
server.prototype.assets.all = new mirror([
    server.prototype.assets.vendor,
    server.prototype.assets.core,
    server.prototype.assets.routers,
    server.prototype.assets.models,
    server.prototype.assets.views,
    server.prototype.assets.templates
], { type: '.js' });

// Stores models, views served by this server.
// TODO: This should be moved to the initialize method!
server.prototype.models = {};
server.prototype.views = {};

// Stores instances of routers registered with this server.
// TODO: This should be moved to the initialize method!
server.prototype.routers = {};

server.prototype.initialize = function(app) {
    this.registerComponents(app);
    this.initializeAssets(app);
    this.initializeModels(app);
};

server.prototype.registerComponents = function(app) {
    var components = ['routers', 'models', 'views', 'templates'];
    components.forEach(function(kind) {
        for (var name in app[kind]) {
            app[kind][name].register(this);
        }
    }, this);
};

server.prototype.initializeAssets = function(app) {
    this.get('/assets/bones/vendor.js', this.assets.vendor.handler);
    this.get('/assets/bones/core.js', this.assets.core.handler);
    this.get('/assets/bones/routers.js', this.assets.routers.handler);
    this.get('/assets/bones/models.js', this.assets.models.handler);
    this.get('/assets/bones/views.js', this.assets.views.handler);
    this.get('/assets/bones/templates.js', this.assets.templates.handler);

    this.get('/assets/bones/all.js', this.assets.all.handler);
};

server.prototype.initializeModels = function(app) {
    this.models = app.models;
    _.bindAll(this, 'loadModel', 'getModel', 'saveModel', 'delModel', 'loadCollection');
    this.get('/api/:model/:id', [this.loadModel, this.getModel]);
    this.post('/api/:model', [this.loadModel, this.saveModel]);
    this.put('/api/:model/:id', [this.loadModel, this.saveModel]);
    this.del('/api/:model/:id', [this.loadModel, this.delModel]);
    this.get('/api/:collection', this.loadCollection.bind(this));
};

server.prototype.loadCollection = function(req, res, next) {
    var name = Bones.utils.pluralize(req.params.collection);
    if (name in this.models) {
        // Pass any querystring paramaters to the collection.
        req.collection = new this.models[name]([], req.query);
        req.collection.fetch({
            success: function(collection, resp) {
                res.send(resp, headers);
            },
            error: function(collection, err) {
                var error = err instanceof Object ? err.message : err;
                next(new Error.HTTP(error, err && err.status || 500));
            }
        });
    } else {
        next();
    }
};

server.prototype.loadModel = function(req, res, next) {
    var name = req.params.model;
    if (name in this.models) {
        // `id` in param wins over `id` in request body.
        if (req.body && 'id' in req.body && req.params.id)
            req.body.id = req.params.id;
        // Pass any querystring paramaters to the model.
        req.model = new this.models[name]({ id: req.params.id }, req.query);
    }
    next();
};

server.prototype.getModel = function(req, res, next) {
    if (!req.model) return next();
    req.model.fetch({
        success: function(model, resp) {
            res.send(resp, headers);
        },
        error: function(model, err) {
            var error = err instanceof Object ? err.message : err;
            next(new Error.HTTP(error, err && err.status || 404));
        }
    });
};

server.prototype.saveModel = function(req, res, next) {
    if (!req.model) return next();
    req.model.save(req.body, {
        success: function(model, resp) {
            res.send(resp, headers);
        },
        error: function(model, err) {
            var error = err instanceof Object ? err.message : err;
            next(new Error.HTTP(error, err && err.status || 409));
        }
    });
};

server.prototype.delModel = function(req, res, next) {
    if (!req.model) return next();
    if (req.body && !req.model.set(req.body, {
        error: function(model, err) { next(err); }
    })) return;
    req.model.destroy({
        success: function(model, resp) {
            res.send(resp, headers);
        },
        error: function(model, err) {
            var error = err instanceof Object ? err.message : err;
            next(new Error.HTTP(error, err && err.status || 409));
        }
    });
};
<|endoftext|>


<commit_before>"use strict";

const Promise = require('bluebird');
const engine = require('../numerics');

function gpsSource(id,latitude0,longitude0,altitude0)
{
  this.id = id;
  this.stime = null;
  this.time0 = null;
  this.refTime = null;
  this.samples = [];
  this.latitude0 = latitude0;
  this.longitude0 = longitude0;
  this.altitude0 = altitude0;
  this.initializing = false;
  this.initialized = false;
}

gpsSource.prototype.addCoordinate = Promise.coroutine(function*(millis,lat,long,alt)
{
  let sample = { millis:millis, lat:lat, long:long, alt:alt };

  try
  {
    if(!this.initialized)
    {
      if(!this.initializing)
      {
        this.initializing = true;

        let initialObservation = new Float64Array([lat,long,alt]);
        let initialVariance = new Float64Array([0.01,0.01,0.01]);

        this.state = yield engine.kalmanInitialGuess(initialObservation,initialVariance);
        this.model = yield engine.kalmanNewModel(this.id,0.0001,0.005,0.5);
        this.samples = [sample];
        this.initialized = true;
        this.stime = millis;

        let now = new Date();

        this.time0 = millis;
        this.refTime = now.valueOf();
      }
    }
    else
    {
      let stime = this.stime;

      this.samples.push(sample);
      this.stime = millis;

      let predictedState = yield engine.kalmanPredict(this.id,this.model,this.state);
      let observations = new Float64Array([sample.lat,sample.long,sample.alt]);

      this.state = yield engine.kalmanUpdate(this.id,this.model,predictedState,observations,(millis - stime)/1000);
    }
  }
  catch(e)
  {
    console.log("kalman failed:",e);
  }
});

gpsSource.prototype.defaultGPS = function(callback)
{
  let res =  { lat:this.latitude0, long:this.longitude0, alt:this.altitude0, latVar:0, longVar:0, altVar:0 };

  callback(null,res);
}

const defaultGPS = Promise.promisify(function(src,callback)
{
   src.defaultGPS(callback);
});

gpsSource.prototype.predict = Promise.coroutine(function*()
{
  var res;

  if(this.model != null)
  {
    let predictedState = yield engine.kalmanPredict(this.id,this.model,this.state);
    let coordArray = yield engine.kalmanStateMean(predictedState);
    let varianceArray = yield engine.kalmanStateVariance(predictedState);

    res =
    {
      lat:coordArray[0],
      long:coordArray[1],
      alt:coordArray[2],
      vt:coordArray[3],
      vg:coordArray[4],
      va:coordArray[5],
      latVar:varianceArray[0],
      longVar:varianceArray[1],
      altVar:varianceArray[2]
    };
  }
  else res = yield defaultGPS(this);
  return res;
});

gpsSource.prototype.prune = function()
{
  let now = new Date();
  let newSamples = [];
  let checkTime = now.valueOf() + (this.time0 - this.refTime) - 5000;

  for(let i = 0;i < this.samples.length;i++)
  {
    if(checkTime < this.samples[i].millis) newSamples.push(this.samples[i]);
  }
  this.samples = newSamples;
}

module.exports =
{
  newSource: function(id,latitude0,longitude0,altitude0)
  {
    let source = new gpsSource(id,latitude0,longitude0,altitude0);

     setInterval(function() { source.prune(); },500);
     return source;
  }
}
<commit_msg>changed pruning, expected variance<commit_after>"use strict";

const Promise = require('bluebird');
const engine = require('../numerics');

function gpsSource(id,latitude0,longitude0,altitude0)
{
  this.id = id;
  this.stime = null;
  this.ptime = null;
  this.samples = [];
  this.latitude0 = latitude0;
  this.longitude0 = longitude0;
  this.altitude0 = altitude0;
  this.initializing = false;
  this.initialized = false;
}

gpsSource.prototype.addCoordinate = Promise.coroutine(function*(millis,lat,long,alt)
{
  let sample = { millis:millis, lat:lat, long:long, alt:alt };

  try
  {
    if(!this.initialized)
    {
      if(!this.initializing)
      {
        this.initializing = true;

        let initialObservation = new Float64Array([lat,long,alt]);
        let initialVariance = new Float64Array([0.01,0.01,0.01]);

        this.state = yield engine.kalmanInitialGuess(initialObservation,initialVariance);
        this.model = yield engine.kalmanNewModel(this.id,0.0001,4.368271880716285e-7,0.5);
        this.samples = [sample];
        this.initialized = true;
        this.stime = millis;
      }
    }
    else
    {
      let stime = this.stime;

      this.samples.push(sample);
      this.stime = millis;

      let predictedState = yield engine.kalmanPredict(this.id,this.model,this.state);
      let observations = new Float64Array([sample.lat,sample.long,sample.alt]);

      this.state = yield engine.kalmanUpdate(this.id,this.model,predictedState,observations,(millis - stime)/1000);
    }
  }
  catch(e)
  {
    console.log("kalman failed:",e);
  }
});

gpsSource.prototype.defaultGPS = function(callback)
{
  let res =  { lat:this.latitude0, long:this.longitude0, alt:this.altitude0, latVar:0, longVar:0, altVar:0 };

  callback(null,res);
}

const defaultGPS = Promise.promisify(function(src,callback)
{
   src.defaultGPS(callback);
});

gpsSource.prototype.predict = Promise.coroutine(function*()
{
  var res;

  if(this.model != null)
  {
    let predictedState = yield engine.kalmanPredict(this.id,this.model,this.state);
    let coordArray = yield engine.kalmanStateMean(predictedState);
    let varianceArray = yield engine.kalmanStateVariance(predictedState);

    res =
    {
      lat:coordArray[0],
      long:coordArray[1],
      alt:coordArray[2],
      vt:coordArray[3],
      vg:coordArray[4],
      va:coordArray[5],
      latVar:varianceArray[0],
      longVar:varianceArray[1],
      altVar:varianceArray[2]
    };
  }
  else res = yield defaultGPS(this);
  return res;
});

gpsSource.prototype.prune = function()
{
  let now = new Date();
  let newSamples = [];
  let maxTime;

  for(let i = 0;i < this.samples.length;i++)
    if(maxTime == null || maxTime < this.samples[i].millis) maxTime = this.samples[i].millis;
  if(maxTime != null)
  {
    if(this.ptime == null || this.ptime < maxTime - 5000) this.ptime = maxTime - 5000;
    else this.ptime += 500;
  }
  else this.ptime = null;

  console.log("ptime = ",this.ptime);

  for(let i = 0;i < this.samples.length;i++)
  {
    if(this.ptime != null && this.ptime < this.samples[i].millis) newSamples.push(this.samples[i]);
  }
  this.samples = newSamples;
}

module.exports =
{
  newSource: function(id,latitude0,longitude0,altitude0)
  {
    let source = new gpsSource(id,latitude0,longitude0,altitude0);

     setInterval(function() { source.prune(); },500);
     return source;
  }
}
<|endoftext|>


<commit_before>(function($) {
    var JFMFS = function(element, options) {
        var elem = $(element);
        var obj = this;
        var settings = $.extend({
            param: 'defaultValue'
        }, options || {});

        // ----------+----------+----------+----------+----------+----------+----------+
        // Initialization of container
        // ----------+----------+----------+----------+----------+----------+----------+
        elem.html(
            "
" +
            "
" +
            "        Find Friends: <input type='text' id='jfmfs-friend-filter-text'/>" +
            "        All" +
            "        Selected (0)" +
            "
" +
            "

" +
            "
"
        );

        FB.api('/me/friends', function(response) {
            $.each(response.data, function(i, friend) {
                $("#jfmfs-friend-container").append("

" + friend.name + "

");
                init();
            });
        });

        // ----------+----------+----------+----------+----------+----------+----------+
        // Public functions
        // ----------+----------+----------+----------+----------+----------+----------+

        this.getSelectedIds = function() {
            var ids = [];
            $.each(elem.find(".jfmfs-friend.selected"), function(i, friend) {
                ids.push($(friend).attr("id"));
            });
            return ids;
        };

        // ----------+----------+----------+----------+----------+----------+----------+
        // Private functions
        // ----------+----------+----------+----------+----------+----------+----------+

        var init = function() {
            // handle when a friend is clicked for selection
            elem.find(".jfmfs-friend").live('click', function() {
                // toggleClass all of a sudden stopped working???
                if( $(this).hasClass("selected") )  $(this).removeClass("selected");
                if( !$(this).hasClass("selected") )  $(this).addClass("selected");
                $("#jfmfs-selected-count").html($(".jfmfs-friend.selected").size());
                $(this).removeClass("hover");
            });

            // filter by selected, hide all non-selected
            elem.find("#jfmfs-filter-selected").live('click', function() {
                $(".jfmfs-friend").not(".selected").addClass("hide-non-selected");
                $(".filter-link").removeClass("selected");
                $(this).addClass("selected");
            });

            // remove filter, show all
            elem.find("#jfmfs-filter-all").live('click', function() {
                $(".jfmfs-friend").removeClass("hide-non-selected");
                $(".filter-link").removeClass("selected");
                $(this).addClass("selected");
            });

            // hover effect on friends
            elem.find(".jfmfs-friend:not(.selected)").live(
                'hover', function (ev) {
                    if (ev.type == 'mouseover') {
                        $(this).addClass("hover");
                    }
                    if (ev.type == 'mouseout') {
                        $(this).removeClass("hover");
                    }
                });

            // filter as you type
            elem.find("#jfmfs-friend-filter-text")
                .keyup( function() {
                    var filter = $(this).val();
                    if(filter == '') {
                        $(".jfmfs-friend").removeClass("hide-filtered");
                    }
                    else {
                        $("#jfmfs-friend-selector").find(".friend-name:not(:Contains(" + filter +"))").parent().addClass("hide-filtered");
                        $("#jfmfs-friend-selector").find(".friend-name:Contains(" + filter +")").parent().removeClass("hide-filtered");
                    }
                })
                .focus( function() {
                    if($.trim($(this).val()) == 'Start typing a name')
                        $(this).val('');
                    })
                .blur(function() {
                    if($.trim($(this).val()) == '')
                        $(this).val('Start typing a name');
                    });

            // hover states on the buttons
            elem.find(".jfmfs-button").hover(
                function(){ $(this).addClass("jfmfs-button-hover");} ,
                function(){ $(this).removeClass("jfmfs-button-hover");}
            );

        };

    };

    $.fn.jfmfs = function(options) {
        return this.each(function() {
            var element = $(this);

            // Return early if this element already has a plugin instance
            if (element.data('jfmfs')) return;

            // pass options to plugin constructor
            var jfmfs = new JFMFS(this, options);

            // Store plugin object in this element's data
            element.data('jfmfs', jfmfs);

        });
    };

    // todo, make this more ambiguous
    jQuery.expr[':'].Contains = function(a, i, m) {
      return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
    };

})(jQuery);<commit_msg>debugging issue with sample site<commit_after>(function($) {
    var JFMFS = function(element, options) {
        var elem = $(element);
        var obj = this;
        var settings = $.extend({
            param: 'defaultValue'
        }, options || {});

        // ----------+----------+----------+----------+----------+----------+----------+
        // Initialization of container
        // ----------+----------+----------+----------+----------+----------+----------+
        elem.html(
            "
" +
            "
" +
            "        Find Friends: <input type='text' id='jfmfs-friend-filter-text'/>" +
            "        All" +
            "        Selected (0)" +
            "
" +
            "

" +
            "
"
        );

        FB.api('/me/friends', function(response) {
            $.each(response.data, function(i, friend) {
                $("#jfmfs-friend-container").append("

" + friend.name + "

");
                init();
            });
        });

        // ----------+----------+----------+----------+----------+----------+----------+
        // Public functions
        // ----------+----------+----------+----------+----------+----------+----------+

        this.getSelectedIds = function() {
            var ids = [];
            $.each(elem.find(".jfmfs-friend.selected"), function(i, friend) {
                ids.push($(friend).attr("id"));
            });
            return ids;
        };

        // ----------+----------+----------+----------+----------+----------+----------+
        // Private functions
        // ----------+----------+----------+----------+----------+----------+----------+

        var init = function() {
            // handle when a friend is clicked for selection
            elem.find(".jfmfs-friend").live('click', function() {
                // toggleClass all of a sudden stopped working???
                if( $(this).hasClass("selected") )  $(this).removeClass("selected");
                else if( !$(this).hasClass("selected") )  $(this).addClass("selected");
                $("#jfmfs-selected-count").html($(".jfmfs-friend.selected").size());
                $(this).removeClass("hover");
            });

            // filter by selected, hide all non-selected
            elem.find("#jfmfs-filter-selected").live('click', function() {
                $(".jfmfs-friend").not(".selected").addClass("hide-non-selected");
                $(".filter-link").removeClass("selected");
                $(this).addClass("selected");
            });

            // remove filter, show all
            elem.find("#jfmfs-filter-all").live('click', function() {
                $(".jfmfs-friend").removeClass("hide-non-selected");
                $(".filter-link").removeClass("selected");
                $(this).addClass("selected");
            });

            // hover effect on friends
            elem.find(".jfmfs-friend:not(.selected)").live(
                'hover', function (ev) {
                    if (ev.type == 'mouseover') {
                        $(this).addClass("hover");
                    }
                    if (ev.type == 'mouseout') {
                        $(this).removeClass("hover");
                    }
                });

            // filter as you type
            elem.find("#jfmfs-friend-filter-text")
                .keyup( function() {
                    var filter = $(this).val();
                    if(filter == '') {
                        $(".jfmfs-friend").removeClass("hide-filtered");
                    }
                    else {
                        $("#jfmfs-friend-selector").find(".friend-name:not(:Contains(" + filter +"))").parent().addClass("hide-filtered");
                        $("#jfmfs-friend-selector").find(".friend-name:Contains(" + filter +")").parent().removeClass("hide-filtered");
                    }
                })
                .focus( function() {
                    if($.trim($(this).val()) == 'Start typing a name')
                        $(this).val('');
                    })
                .blur(function() {
                    if($.trim($(this).val()) == '')
                        $(this).val('Start typing a name');
                    });

            // hover states on the buttons
            elem.find(".jfmfs-button").hover(
                function(){ $(this).addClass("jfmfs-button-hover");} ,
                function(){ $(this).removeClass("jfmfs-button-hover");}
            );

        };

    };

    $.fn.jfmfs = function(options) {
        return this.each(function() {
            var element = $(this);

            // Return early if this element already has a plugin instance
            if (element.data('jfmfs')) return;

            // pass options to plugin constructor
            var jfmfs = new JFMFS(this, options);

            // Store plugin object in this element's data
            element.data('jfmfs', jfmfs);

        });
    };

    // todo, make this more ambiguous
    jQuery.expr[':'].Contains = function(a, i, m) {
      return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
    };

})(jQuery);<|endoftext|>