<commit_before>define([
        'config',
        'backbone',
        'mustache',
        'jquery',
        'text!views/FindAChurch/Search.html'
        ],
        function(config, Backbone, Mustache, $, template){

    return Backbone.View.extend({
        initialize: function(){
            _.bindAll(this, 'location_keyup', 'geocode', 'set_distance_unit_preference',
                'is_distance_unit_preference_set', 'get_distance_units', 'location_keyup')
            window.app.geocoder = new google.maps.Geocoder();
        },
        render: function(){
            this.$el.html(Mustache.render(template))

            // Attach search event handler to search button and text box
            $('.search').on('click', this.geocode)
            $('.location').on('keyup', this.location_keyup)
            $('.radius').on('change', this.geocode)
            $('.units').on('change', this.set_distance_unit_preference)

            // TODO: Improve User Interface:
            // TODO: - Try to be able to guess which unit of distance (Mi or KM) they prefer based on
            //  some input from the user.
            // TODO:   * Event Handler: On page load

            //If the distance unit preference is set,
			// set the distance units in the form based on what is in the preference.
			if ( this.is_distance_unit_preference_set() ){
				this.$('.units').val(localStorage['distance_units']);
			}
            // TODO:     * Else, on page load, before the person searches,
			else {
				// Guess what units they want based on one of the following:
                //            * First try the users' browser's geolocation information. If
                //                  the user is in one of the countries that use miles, select "miles" in the form
                //                  and save it to the preference.

                var thiz=this

                if (navigator.geolocation){
                    // Center the map on the viewer's country by default
                    navigator.geolocation.getCurrentPosition(function(position){
                        window.app.geocoder = new google.maps.Geocoder();
                        window.app.geocoder.geocode( { 'address': position.coords.latitude + "," + position.coords.longitude}, function(results, status) {
                        //	Underscore.js _.filter() method) for results[0].address_components[x].types.short_name == 'US'
                            if (status == google.maps.GeocoderStatus.OK){
                                // Set the user's location's country's distance units in the form
                                thiz.$('.units').val(thiz.get_distance_units(results))
                            }
                        })
                    })
                }else{
                    console.log("Geolocation is not supported by this browser.");
                    // TODO:   * Next, try the browser country or language setting.
//                     var userLang = navigator.language || navigator.browserLanguage || navigator.systemLanguage || navigator.userLanguage;
//                     console.log(userLang)
//                     // Determine if userLang contains a 2-character country code after a hyphen
//                     //  (e.g., userLang could equal 'en-US')
//                     var country_code = userLang.split('-')[1]
//                     var language_code = userLang.split('-')[0]
//                     if (country_code !== '' && typeof country_code !== 'undefined'){
// 						this.record_distance_units(country_code)
//                     }else{
//                         // Use the language code.  This might help:  http://download.geonames.org/export/dump/countryInfo.txt
//                         // These are the languages of the countries that use miles
//                         var languages = ['en', 'mm', 'bur', 'mya']
//                         // If the country's language is NOT in this set, then the country uses kilometers.
//                         if (languages.indexOf(language_code) === -1){
//                             localStorage('distance_units', 'km')
//                         }else{
//                             // If the country does use this language, then we don't know if it uses miles or kilometers.
//                         }
//                     }
//                     // TODO:   * Get their preference from their IP address
                    // TODO:        Load http://freegeoip.net/json/ via JQuery.get()
				    $.get("http://freegeoip.net/json",function(data,status){
						var country_code = data.country_code
						thiz.record_distance_units(country_code)

					});

                    // Create the map
                    this.create_map({coords:this.default_map_center})
                }

			}
        },
        record_distance_units:function(country_code){
			// Test if this country code uses miles or kilometers.
			// TODO: Maybe these codes should be put into one data structure with the array used
			//  below (["United Kingdom", "Liberia", "Myanmar", "United States"]) so we don't
			//  complicate future maintenance of the application.
			var country_codes = ['GB', 'LR', 'MM', 'US']
			// If country_code is in the list, then
			if (country_codes.indexOf(country_code) !== -1){
				// Record preference accordingly
				localStorage('distance_units', 'miles')
			}else{
				localStorage('distance_units', 'km')
			}

		},

		is_distance_unit_preference_set:function(){
			// Get preference here
			localStorage['distance_units']
			if (typeof localStorage['distance_units'] === 'undefined'){
				return false;
			}else{
				return true
			}
		},
		set_distance_unit_preference:function(event){
			//  Set preference here
			localStorage['distance_units'] = this.$('.units').val();
			if (event.target === this.$(".units")) {
				loclalStorage['distance_units_manual'] = 'manual'
				//if a person selects the the distance, it becomes their preference
			}

		},
        location_keyup:function(event){
            if (event.which == 13){
                this.geocode(event)
            }
        },
		get_distance_units:function(results){
            var country_names_objects = _.filter(results[0].address_components, function(item){
            	//See if it contains countries that use miles (GB, LR, MM, US)
                return ["United Kingdom", "Liberia", "Myanmar", "United States"].indexOf(item.long_name) !== -1
			});
            country_names = _.chain(country_names_objects)
                .pluck('long_name')
                .filter(function(item){ return typeof item !== 'undefined'; })
                .value()
            if (country_names.length >0){
                output = 'miles'
            }else{
                output = 'km'
            }
            return output;
		},
        geocode: function (event){
            event.preventDefault()
            // If user submitted an address, put that address into this.model
            // Use location user entered

            // Convert radius*units to meters
            var radius = $('.radius').val();
            var units = $('.units').val();
            var distance;
            if (units == 'miles'){
                distance = radius * 1609.344;
            } else if (units == 'km') {
                distance = radius * 1000;
            }

			this.set_distance_unit_preference()

            // Geocode location
        	var thiz=this
            var location = $('.location').val()
            if (location == ''){
                location = thiz.model.get('location')
            }
            window.app.geocoder.geocode( { 'address': location}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    // Put the above variables into this.model in one action so there's only one change event
                    thiz.model.set({
                        location:location,
                        radius:radius,
                        distance:distance,
                        units:units,
                        results:results
                    })
					if (!thiz.is_distance_unit_preference_set() && localStorage['distance_units_manual'] !== 'manual'){
    				    // Try figuring the user's distance_unit preference based on the country in which they are searching.
    					// Set the preference to contain 'miles' or 'km'
						var distance_units = thiz.get_distance_units(results)
						localStorage['distance_units'] = distance_units
                        // Set form to display the distance units of the country in which the user searched
                        thiz.$('.units').val(distance_units)
					}
                } else {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            });
		}
    });
});
//TODO:  Figure out why after the above work to save the distance units preference, after typing an address in the location search box, there is an error in the JavaScript cntrols and the map does not center on that location.<commit_msg>Pass event and call correct event handler to get units select box change event handler to work<commit_after>define([
        'config',
        'backbone',
        'mustache',
        'jquery',
        'text!views/FindAChurch/Search.html'
        ],
        function(config, Backbone, Mustache, $, template){

    return Backbone.View.extend({
        initialize: function(){
            _.bindAll(this, 'location_keyup', 'geocode', 'set_distance_unit_preference',
                'is_distance_unit_preference_set', 'get_distance_units', 'location_keyup')
            window.app.geocoder = new google.maps.Geocoder();
        },
        render: function(){
            this.$el.html(Mustache.render(template))

            // Attach search event handler to search button and text box
            $('.search').on('click', this.geocode)
            $('.location').on('keyup', this.location_keyup)
            $('.radius').on('change', this.geocode)
            $('.units').on('change', this.geocode)

            // TODO: Improve User Interface:
            // TODO: - Try to be able to guess which unit of distance (Mi or KM) they prefer based on
            //  some input from the user.
            // TODO:   * Event Handler: On page load

            //If the distance unit preference is set,
			// set the distance units in the form based on what is in the preference.
			if ( this.is_distance_unit_preference_set() ){
				this.$('.units').val(localStorage['distance_units']);
			}
            // TODO:     * Else, on page load, before the person searches,
			else {
				// Guess what units they want based on one of the following:
                //            * First try the users' browser's geolocation information. If
                //                  the user is in one of the countries that use miles, select "miles" in the form
                //                  and save it to the preference.

                var thiz=this

                if (navigator.geolocation){
                    // Center the map on the viewer's country by default
                    navigator.geolocation.getCurrentPosition(function(position){
                        window.app.geocoder = new google.maps.Geocoder();
                        window.app.geocoder.geocode( { 'address': position.coords.latitude + "," + position.coords.longitude}, function(results, status) {
                        //	Underscore.js _.filter() method) for results[0].address_components[x].types.short_name == 'US'
                            if (status == google.maps.GeocoderStatus.OK){
                                // Set the user's location's country's distance units in the form
                                thiz.$('.units').val(thiz.get_distance_units(results))
                            }
                        })
                    })
                }else{
                    console.log("Geolocation is not supported by this browser.");
                    // TODO:   * Next, try the browser country or language setting.
//                     var userLang = navigator.language || navigator.browserLanguage || navigator.systemLanguage || navigator.userLanguage;
//                     console.log(userLang)
//                     // Determine if userLang contains a 2-character country code after a hyphen
//                     //  (e.g., userLang could equal 'en-US')
//                     var country_code = userLang.split('-')[1]
//                     var language_code = userLang.split('-')[0]
//                     if (country_code !== '' && typeof country_code !== 'undefined'){
// 						this.record_distance_units(country_code)
//                     }else{
//                         // Use the language code.  This might help:  http://download.geonames.org/export/dump/countryInfo.txt
//                         // These are the languages of the countries that use miles
//                         var languages = ['en', 'mm', 'bur', 'mya']
//                         // If the country's language is NOT in this set, then the country uses kilometers.
//                         if (languages.indexOf(language_code) === -1){
//                             localStorage('distance_units', 'km')
//                         }else{
//                             // If the country does use this language, then we don't know if it uses miles or kilometers.
//                         }
//                     }
//                     // TODO:   * Get their preference from their IP address
                    // TODO:        Load http://freegeoip.net/json/ via JQuery.get()
				    $.get("http://freegeoip.net/json",function(data,status){
						var country_code = data.country_code
						thiz.record_distance_units(country_code)

					});

                    // Create the map
                    this.create_map({coords:this.default_map_center})
                }

			}
        },
        record_distance_units:function(country_code){
			// Test if this country code uses miles or kilometers.
			// TODO: Maybe these codes should be put into one data structure with the array used
			//  below (["United Kingdom", "Liberia", "Myanmar", "United States"]) so we don't
			//  complicate future maintenance of the application.
			var country_codes = ['GB', 'LR', 'MM', 'US']
			// If country_code is in the list, then
			if (country_codes.indexOf(country_code) !== -1){
				// Record preference accordingly
				localStorage('distance_units', 'miles')
			}else{
				localStorage('distance_units', 'km')
			}

		},

		is_distance_unit_preference_set:function(){
			// Get preference here
			localStorage['distance_units']
			if (typeof localStorage['distance_units'] === 'undefined'){
				return false;
			}else{
				return true
			}
		},
		set_distance_unit_preference:function(event){
			//  Set preference here
			localStorage['distance_units'] = this.$('.units').val();
			if (event.target === this.$(".units")) {
				loclalStorage['distance_units_manual'] = 'manual'
				//if a person selects the the distance, it becomes their preference
			}

		},
        location_keyup:function(event){
            if (event.which == 13){
                this.geocode(event)
            }
        },
		get_distance_units:function(results){
            var country_names_objects = _.filter(results[0].address_components, function(item){
            	//See if it contains countries that use miles (GB, LR, MM, US)
                return ["United Kingdom", "Liberia", "Myanmar", "United States"].indexOf(item.long_name) !== -1
			});
            country_names = _.chain(country_names_objects)
                .pluck('long_name')
                .filter(function(item){ return typeof item !== 'undefined'; })
                .value()
            if (country_names.length >0){
                output = 'miles'
            }else{
                output = 'km'
            }
            return output;
		},
        geocode: function (event){
            event.preventDefault()
            // If user submitted an address, put that address into this.model
            // Use location user entered

            // Convert radius*units to meters
            var radius = $('.radius').val();
            var units = $('.units').val();
            var distance;
            if (units == 'miles'){
                distance = radius * 1609.344;
            } else if (units == 'km') {
                distance = radius * 1000;
            }

			this.set_distance_unit_preference(event)

            // Geocode location
        	var thiz=this
            var location = $('.location').val()
            if (location == ''){
                location = thiz.model.get('location')
            }
            window.app.geocoder.geocode( { 'address': location}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    // Put the above variables into this.model in one action so there's only one change event
                    thiz.model.set({
                        location:location,
                        radius:radius,
                        distance:distance,
                        units:units,
                        results:results
                    })
					if (!thiz.is_distance_unit_preference_set() && localStorage['distance_units_manual'] !== 'manual'){
    				    // Try figuring the user's distance_unit preference based on the country in which they are searching.
    					// Set the preference to contain 'miles' or 'km'
						var distance_units = thiz.get_distance_units(results)
						localStorage['distance_units'] = distance_units
                        // Set form to display the distance units of the country in which the user searched
                        thiz.$('.units').val(distance_units)
					}
                } else {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            });
		}
    });
});
//TODO:  Figure out why after the above work to save the distance units preference, after typing an address in the location search box, there is an error in the JavaScript cntrols and the map does not center on that location.<|endoftext|>


<commit_before>/**
 * UI Control Dropdown Class
 * @class UI.Control.Dropdown
 * @extends {UI.Control}
 * @type {Class}
 */
define(function(require, exports, module) {

  var api = require('utils/api');
  var Field = require('UI/Control/Field');
  var ButtonControl = require('UI/Control/Button');
  var ButtonMenu = require('UI/Control/ButtonMenu');

  var _log = __debug('ui-control-dropdown').defineLevel();

  var Dropdown = new Class({

    Extends: Field,

    name: 'dropdown',

    options: {
      name: 'dropdown',
      type: 'text', // push, file
      menuFx: {
        duration: 150,
        link: 'chain',
        transition: Fx.Transitions.Quart.easeOut
      },
      binding: {
        _list: ['input', 'button'],
        input: {
          'input.mousedown': '_onMouseDown',
          'input.keydown': '_onKeyDown',
          'input.keyup': '_onKeyUp'
        },
        button: {
          'button.press': '_onButtonPress'
        }
      }
    },

    /**
     * [_initElement description]
     * @return {void} [description]
     */
    _initElement: function() {
      this.parent();

      this.control = {};

      this.element.addClass('type-dropdown');

      //this.input.set('readonly', 'readonly');

      var opts = this.options;

      if (!this.readonly) {
        this._initMenu(opts);
        this._initButton();
        this._initEvents();
      }
    },

    /**
     * _onKeyDown
     * @return {void}
     */
    _onKeyDown: function(e) {
      _log.debug('KeyDown');

      if (e.key !== 'tab') {
        e.stop();
        return;
      }

      if (this.readonly) {
        e.stop();
        return;
      }
    },

    /**
     * [_onKeyDown description]
     * @param  {event} e
     * @return {void}
     */
    _onKeyUp: function(e) {
      _log.debug('_onKeyUp', e);

    },

    /**
     * [_initIcon description]
     * @return {void} [description]
     */
    _initButton: function() {
      _log.debug('_initButton');

      this.button = new ButtonControl({
        'clss': 'right',
        type: 'icon',
        name: 'movedown',
        icon: 'mdi-hardware-keyboard-arrow-down',
      }).inject(this.element, 'top');
    },

    /**
     * [_onButtonClick description]
     * @return {void} [description]
     */
    _onButtonPress: function(e) {
      _log.debug('_onButtonClick', e);

      if (this.isFocused) {
        this._showMenu();
      } else {
        this.input.focus();
      }
    },

    /**
     * [_onMouseDown description]
     * @return {void} [description]
     */
    _onMouseDown: function(e) {
      this.parent(e);

      this._onButtonPress(e);
    },

    /**
     * [_initToolbarComp description]
     * @param {Object} opts
     * @return {Object}
     */
    _initMenu: function(opts) {
      _log.debug('_initMenu', opts);
      var self = this;
      //var list = opts.list;
      var timer = null;

      opts.list = opts.list || [];

      this.container = this.element.getParent();

      var value = self.input.get('value');

      var menu = this.menu = new Element('ul', {
        class: 'ui-menu',
      }).inject(this.element, 'bottom').addEvents({
        mouseleave: function() {
          clearTimeout(timer);
          timer = setTimeout(function() {
            menu.setStyle('display', 'none');
          }, 500);
        },
        mouseenter: function() {
          clearTimeout(timer);
        },
        click: function() {
          menu.setStyle('display', 'none');
        }
      });

      for (var i = 0; i < opts.list.length; i++) {
        var name = opts.list[i];
        var def = opts.list[name];
        this._initItem(name, def, this.menu, value);
      }

      this.menuFx = new Fx.Morph(this.menu, opts.menuFx);

      //_log.debug('menu coord', menu.getCoordinates());
      //menu.setStyle('display', 'none');

      return menu;
    },

    /**
     * [_initEvents description]
     * @return {void}
     */
    _initEvents: function() {
      var self = this;

      if (this.readonly) {
        return;
      }

      this.addEvents({
        select: function(name) {
          _log.debug('select');
          self.input.set('value', name);
          self.fireEvent('change', name);
        }
      });

    },

    /**
     * [_onFocus description]
     * @return {void}
     */
    _onFocus: function(e) {
      _log.debug('_onFocus');

      this._showMenu(e);

      this.parent(e);
    },

    /**
     * [_onFocus description]
     * @return {void}
     */
    _onBlur: function(e) {
      _log.debug('_onBlur');
      this.parent(e);
      this._hideMenu(e);
    },

    /**
     * [_showMenu description]
     * @return {void}
     */
    _showMenu: function() {

      if (this.readonly) {
        return;
      }

      var menu = this.menu;

      menu.setStyles({
        height: 0,
        left: 16,
        paddingTop: 0,
        paddingBottom: 0,
        display: 'block',
        opacity: 0
      });

      var coord = this.input.getCoordinates(this.element);

      var top = coord.height + coord.top;
      menu.setStyle('top', top);

      var width = coord.width;

      //_log.debug('widh', menu.scrollWidth, coord.width);

      if (menu.scrollWidth > coord.width) {
        width = menu.scrollWidth;
      }

      menu.setStyle('width', width);

      this.menuFx.start({
        height: this.menu.scrollHeight + 22,
        paddingTop: 10,
        paddingBottom: 10,
        opacity: 1
      });

      this.fireEvent('showMenu', menu);
    },

    /**
     * [_showMenu description]
     * @return {void}
     */
    _hideMenu: function() {

      if (this.input.get('readonly')) {
        return;
      }

      this.menuFx.start({
        height: 0,
        paddingTop: 0,
        paddingBottom: 0,
        opacity: 0
      });

      var self = this;
      (function() {
        self.menu.setStyle('display', 'none');
      }).delay(this.options.menuFx.duration);

      this.fireEvent('hide');
    },

    /**
     * [_initMenuPosition description]
     * @return {Object}
     */
    _initMenuPosition: function() {
      //_log.debug('_initMenuPosition');
      //var container = this.container.getParent().getCoordinates();
      var coord = this.element.getCoordinates(this.container);

      return coord;
    },

    /**
     * [_initItem description]
     * @param  {string} name
     * @param  {Object} def
     * @param  {DOMElement} element
     * @return {void}
     */
    _initItem: function(name, def, element, value) {
      var self = this;
      var clss = ButtonControl;
      var opts;
      var comps = name.split(/\./);

      if (comps.length > 1) {
        clss = 'UI.' + comps[0].capitalize();
        name = comps[1];
      }

      if (name === 'separator') {
        clss = Separator;
      }

      if (def && def.clss) {
        clss = def.clss;
      }

      if (def && def.opts) {
        opts = def.opts;
        _log.debug('--', name, def.opts);
        opts.text = Locale.get('control.' + name, name) || name;
        //opts.icon = mnml.icon.font[name];
        opts.tag = 'span';
      } else {
        opts = {
          name: name,
          //icon: mnml.icon.font[name]
        };
      }

      //_log.debug(this.options.value, name);

      if (this.value === name) {
        opts.klss = 'is-selected';
      }

      if (!name) {
        return;
      }

      var Clss = api.strToClss(clss);

      if (clss === ButtonControl || clss === ButtonMenu) {
        opts.text = Locale.get('control.' + name, name) || name;
      }

      this.options.control = this.options.control || {};

      this.control[name] = new Clss(opts).inject(element);

      if (clss === ButtonControl) {
        this.control[name].addEvents({
          press: function() {
            var name = this.options.name;
            //_log.debug('press', name, this.isEnable());
            if (this.isEnable()) {
              self.value = name;
              //self.fireEvent('control::'+name, this);
              self.fireEvent('select', name);
            }
            self.menu.hide();
          }
        });
      }
    },

    /**
     * [_onElementMouseDown description]
     * @param  {event} e
     * @return {void}
     */
    _onClick: function(e) {
      //_log.debug('_onElementClick');
      var opts = this.options;

      e.stopPropagation();

      if (!this.menu) {
        this._initMenu(opts);
      }

      this.menuShow(e);
    }

  });

  module.exports = Dropdown;

});
<commit_msg>clean control when field is read only<commit_after>/**
 * UI Control Dropdown Class
 * @class UI.Control.Dropdown
 * @extends {UI.Control}
 * @type {Class}
 */
define(function(require, exports, module) {

  var api = require('utils/api');
  var Field = require('UI/Control/Field');
  var ButtonControl = require('UI/Control/Button');
  var ButtonMenu = require('UI/Control/ButtonMenu');

  var _log = __debug('ui-control-dropdown').defineLevel();

  var Dropdown = new Class({

    Extends: Field,

    name: 'dropdown',

    options: {
      name: 'dropdown',
      type: 'text', // push, file
      menuFx: {
        duration: 150,
        link: 'chain',
        transition: Fx.Transitions.Quart.easeOut
      },
      binding: {
        _list: ['input', 'button'],
        input: {
          'input.mousedown': '_onMouseDown',
          'input.keydown': '_onKeyDown',
          'input.keyup': '_onKeyUp'
        },
        button: {
          'button.press': '_onButtonPress'
        }
      }
    },

    /**
     * [_initElement description]
     * @return {void} [description]
     */
    _initElement: function() {
      this.parent();

      this.control = {};

      this.element.addClass('type-dropdown');

      //this.input.set('readonly', 'readonly');

      var opts = this.options;

      if (this.readonly) {
        this.options.binding._list = [];
      } else {
        this._initMenu(opts);
        this._initButton();
        this._initEvents();
      }
    },

    /**
     * _onKeyDown
     * @return {void}
     */
    _onKeyDown: function(e) {
      _log.debug('KeyDown');

      if (e.key !== 'tab') {
        e.stop();
        return;
      }

      if (this.readonly) {
        e.stop();
        return;
      }
    },

    /**
     * [_onKeyDown description]
     * @param  {event} e
     * @return {void}
     */
    _onKeyUp: function(e) {
      _log.debug('_onKeyUp', e);

    },

    /**
     * [_initIcon description]
     * @return {void} [description]
     */
    _initButton: function() {
      _log.debug('_initButton');

      this.button = new ButtonControl({
        'clss': 'right',
        type: 'icon',
        name: 'movedown',
        icon: 'mdi-hardware-keyboard-arrow-down',
      }).inject(this.element, 'top');
    },

    /**
     * [_onButtonClick description]
     * @return {void} [description]
     */
    _onButtonPress: function(e) {
      _log.debug('_onButtonClick', e);

      if (this.isFocused) {
        this._showMenu();
      } else {
        this.input.focus();
      }
    },

    /**
     * [_onMouseDown description]
     * @return {void} [description]
     */
    _onMouseDown: function(e) {
      this.parent(e);

      this._onButtonPress(e);
    },

    /**
     * [_initToolbarComp description]
     * @param {Object} opts
     * @return {Object}
     */
    _initMenu: function(opts) {
      _log.debug('_initMenu', opts);
      var self = this;
      //var list = opts.list;
      var timer = null;

      opts.list = opts.list || [];

      this.container = this.element.getParent();

      var value = self.input.get('value');

      var menu = this.menu = new Element('ul', {
        class: 'ui-menu',
      }).inject(this.element, 'bottom').addEvents({
        mouseleave: function() {
          clearTimeout(timer);
          timer = setTimeout(function() {
            menu.setStyle('display', 'none');
          }, 500);
        },
        mouseenter: function() {
          clearTimeout(timer);
        },
        click: function() {
          menu.setStyle('display', 'none');
        }
      });

      for (var i = 0; i < opts.list.length; i++) {
        var name = opts.list[i];
        var def = opts.list[name];
        this._initItem(name, def, this.menu, value);
      }

      this.menuFx = new Fx.Morph(this.menu, opts.menuFx);

      //_log.debug('menu coord', menu.getCoordinates());
      //menu.setStyle('display', 'none');

      return menu;
    },

    /**
     * [_initEvents description]
     * @return {void}
     */
    _initEvents: function() {
      var self = this;

      if (this.readonly) {
        return;
      }

      this.addEvents({
        select: function(name) {
          _log.debug('select');
          self.input.set('value', name);
          self.fireEvent('change', name);
        }
      });

    },

    /**
     * [_onFocus description]
     * @return {void}
     */
    _onFocus: function(e) {
      _log.debug('_onFocus');

      this._showMenu(e);

      this.parent(e);
    },

    /**
     * [_onFocus description]
     * @return {void}
     */
    _onBlur: function(e) {
      _log.debug('_onBlur');
      this.parent(e);
      this._hideMenu(e);
    },

    /**
     * [_showMenu description]
     * @return {void}
     */
    _showMenu: function() {

      if (this.readonly) {
        return;
      }

      var menu = this.menu;

      menu.setStyles({
        height: 0,
        left: 16,
        paddingTop: 0,
        paddingBottom: 0,
        display: 'block',
        opacity: 0
      });

      var coord = this.input.getCoordinates(this.element);

      var top = coord.height + coord.top;
      menu.setStyle('top', top);

      var width = coord.width;

      //_log.debug('widh', menu.scrollWidth, coord.width);

      if (menu.scrollWidth > coord.width) {
        width = menu.scrollWidth;
      }

      menu.setStyle('width', width);

      this.menuFx.start({
        height: this.menu.scrollHeight + 22,
        paddingTop: 10,
        paddingBottom: 10,
        opacity: 1
      });

      this.fireEvent('showMenu', menu);
    },

    /**
     * [_showMenu description]
     * @return {void}
     */
    _hideMenu: function() {

      if (this.input.get('readonly')) {
        return;
      }

      this.menuFx.start({
        height: 0,
        paddingTop: 0,
        paddingBottom: 0,
        opacity: 0
      });

      var self = this;
      (function() {
        self.menu.setStyle('display', 'none');
      }).delay(this.options.menuFx.duration);

      this.fireEvent('hide');
    },

    /**
     * [_initMenuPosition description]
     * @return {Object}
     */
    _initMenuPosition: function() {
      //_log.debug('_initMenuPosition');
      //var container = this.container.getParent().getCoordinates();
      var coord = this.element.getCoordinates(this.container);

      return coord;
    },

    /**
     * [_initItem description]
     * @param  {string} name
     * @param  {Object} def
     * @param  {DOMElement} element
     * @return {void}
     */
    _initItem: function(name, def, element, value) {
      var self = this;
      var clss = ButtonControl;
      var opts;
      var comps = name.split(/\./);

      if (comps.length > 1) {
        clss = 'UI.' + comps[0].capitalize();
        name = comps[1];
      }

      if (name === 'separator') {
        clss = Separator;
      }

      if (def && def.clss) {
        clss = def.clss;
      }

      if (def && def.opts) {
        opts = def.opts;
        _log.debug('--', name, def.opts);
        opts.text = Locale.get('control.' + name, name) || name;
        //opts.icon = mnml.icon.font[name];
        opts.tag = 'span';
      } else {
        opts = {
          name: name,
          //icon: mnml.icon.font[name]
        };
      }

      //_log.debug(this.options.value, name);

      if (this.value === name) {
        opts.klss = 'is-selected';
      }

      if (!name) {
        return;
      }

      var Clss = api.strToClss(clss);

      if (clss === ButtonControl || clss === ButtonMenu) {
        opts.text = Locale.get('control.' + name, name) || name;
      }

      this.options.control = this.options.control || {};

      this.control[name] = new Clss(opts).inject(element);

      if (clss === ButtonControl) {
        this.control[name].addEvents({
          press: function() {
            var name = this.options.name;
            //_log.debug('press', name, this.isEnable());
            if (this.isEnable()) {
              self.value = name;
              //self.fireEvent('control::'+name, this);
              self.fireEvent('select', name);
            }
            self.menu.hide();
          }
        });
      }
    },

    /**
     * [_onElementMouseDown description]
     * @param  {event} e
     * @return {void}
     */
    _onClick: function(e) {
      //_log.debug('_onElementClick');
      var opts = this.options;

      e.stopPropagation();

      if (!this.menu) {
        this._initMenu(opts);
      }

      this.menuShow(e);
    }

  });

  module.exports = Dropdown;

});
<|endoftext|>


<commit_before>/**
 * @author: Dennis Hernández
 * @webSite: http://djhvscf.github.io/Blog
 * @version: v1.2.0
 *
 * @update zhixin wen <wenzhixin2010@gmail.com>
 */

(function ($) {
    'use strict';

    var cookieIds = {
        sortOrder: 'bs.table.sortOrder',
        sortName: 'bs.table.sortName',
        pageNumber: 'bs.table.pageNumber',
        pageList: 'bs.table.pageList',
        columns: 'bs.table.columns',
        searchText: 'bs.table.searchText',
        filterControl: 'bs.table.filterControl'
    };

    var getCurrentHeader = function (that) {
        var header = that.$header;
        if (that.options.height) {
            header = that.$tableHeader;
        }

        return header;
    };

    var getCurrentSearchControls = function (that) {
        var searchControls = 'select, input';
        if (that.options.height) {
            searchControls = 'table select, table input';
        }

        return searchControls;
    };

    var cookieEnabled = function () {
        return !!(navigator.cookieEnabled);
    };

    var inArrayCookiesEnabled = function (cookieName, cookiesEnabled) {
        var index = -1;

        for (var i = 0; i < cookiesEnabled.length; i++) {
            if (cookieName.toLowerCase() === cookiesEnabled[i].toLowerCase()) {
                index = i;
                break;
            }
        }

        return index;
    };

    var setCookie = function (that, cookieName, cookieValue) {
        if ((!that.options.cookie) || (!cookieEnabled()) || (that.options.cookieIdTable === '')) {
            return;
        }

        if (inArrayCookiesEnabled(cookieName, that.options.cookiesEnabled) === -1) {
            return;
        }

        cookieName = that.options.cookieIdTable + '.' + cookieName;
        if (!cookieName || /^(?:expires|max\-age|path|domain|secure)$/i.test(cookieName)) {
            return false;
        }

        document.cookie = encodeURIComponent(cookieName) + '=' + encodeURIComponent(cookieValue) + calculateExpiration(that.options.cookieExpire) + (that.options.cookieDomain ? '; domain=' + that.options.cookieDomain : '') + (that.options.cookiePath ? '; path=' + that.options.cookiePath : '') + (that.cookieSecure ? '; secure' : '');
        return true;
    };

    var getCookie = function (that, tableName, cookieName) {
        if (!cookieName) {
            return null;
        }

        if (inArrayCookiesEnabled(cookieName, that.options.cookiesEnabled) === -1) {
            return null;
        }

        cookieName = tableName + '.' + cookieName;

        return decodeURIComponent(document.cookie.replace(new RegExp('(?:(?:^|.*;)\\s*' + encodeURIComponent(cookieName).replace(/[\-\.\+\*]/g, '\\$&') + '\\s*\\=\\s*([^;]*).*$)|^.*$'), '$1')) || null;
    };

    var hasCookie = function (cookieName) {
        if (!cookieName) {
            return false;
        }
        return (new RegExp('(?:^|;\\s*)' + encodeURIComponent(cookieName).replace(/[\-\.\+\*]/g, '\\$&') + '\\s*\\=')).test(document.cookie);
    };

    var deleteCookie = function (tableName, cookieName, sPath, sDomain) {
        cookieName = tableName + '.' + cookieName;
        if (!hasCookie(cookieName)) {
            return false;
        }
        document.cookie = encodeURIComponent(cookieName) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT' + (sDomain ? '; domain=' + sDomain : '') + (sPath ? '; path=' + sPath : '');
        return true;
    };

    var calculateExpiration = function(cookieExpire) {
        var time = cookieExpire.replace(/[0-9]*/, ''); //s,mi,h,d,m,y
        cookieExpire = cookieExpire.replace(/[A-Za-z]/, ''); //number

        switch (time.toLowerCase()) {
            case 's':
                cookieExpire = +cookieExpire;
                break;
            case 'mi':
                cookieExpire = cookieExpire * 60;
                break;
            case 'h':
                cookieExpire = cookieExpire * 60 * 60;
                break;
            case 'd':
                cookieExpire = cookieExpire * 24 * 60 * 60;
                break;
            case 'm':
                cookieExpire = cookieExpire * 30 * 24 * 60 * 60;
                break;
            case 'y':
                cookieExpire = cookieExpire * 365 * 30 * 24 * 60 * 60;
                break;
            default:
                cookieExpire = undefined;
                break;
        }

        return cookieExpire === undefined ? '' : '; max-age=' + cookieExpire;
    };

    $.extend($.fn.bootstrapTable.defaults, {
        cookie: false,
        cookieExpire: '2h',
        cookiePath: null,
        cookieDomain: null,
        cookieSecure: null,
        cookieIdTable: '',
        cookiesEnabled: ['bs.table.sortOrder', 'bs.table.sortName', 'bs.table.pageNumber', 'bs.table.pageList', 'bs.table.columns', 'bs.table.searchText', 'bs.table.filterControl'],
        //internal variable
        filterControls: [],
        filterControlValuesLoaded: false
    });

    $.fn.bootstrapTable.methods.push('deleteCookie');

    var BootstrapTable = $.fn.bootstrapTable.Constructor,
        _init = BootstrapTable.prototype.init,
        _initTable = BootstrapTable.prototype.initTable,
        _onSort = BootstrapTable.prototype.onSort,
        _onPageNumber = BootstrapTable.prototype.onPageNumber,
        _onPageListChange = BootstrapTable.prototype.onPageListChange,
        _onPageFirst = BootstrapTable.prototype.onPageFirst,
        _onPagePre = BootstrapTable.prototype.onPagePre,
        _onPageNext = BootstrapTable.prototype.onPageNext,
        _onPageLast = BootstrapTable.prototype.onPageLast,
        _toggleColumn = BootstrapTable.prototype.toggleColumn,
        _selectPage = BootstrapTable.prototype.selectPage,
        _onSearch = BootstrapTable.prototype.onSearch;

    BootstrapTable.prototype.init = function () {
        var timeoutId = 0;
        this.options.filterControls = [];
        this.options.filterControlValuesLoaded = false;

        this.options.cookiesEnabled = typeof this.options.cookiesEnabled === 'string' ?
            this.options.cookiesEnabled.replace('[', '').replace(']', '').replace(/ /g, '').toLowerCase().split(',') : this.options.cookiesEnabled;

        if (this.options.filterControl) {
            var that = this;
            this.$el.on('column-search.bs.table', function (e, field, text) {
                var isNewField = true;

                for (var i = 0; i < that.options.filterControls.length; i++) {
                    if (that.options.filterControls[i].field === field) {
                        that.options.filterControls[i].text = text;
                        isNewField = false;
                        break;
                    }
                }
                if (isNewField) {
                    that.options.filterControls.push({
                        field: field,
                        text: text
                    });
                }

                setCookie(that, cookieIds.filterControl, JSON.stringify(that.options.filterControls));
            }).on('post-body.bs.table', function () {
                setTimeout(function () {
                    if (!that.options.filterControlValuesLoaded) {
                        that.options.filterControlValuesLoaded = true;
                        var filterControl = JSON.parse(getCookie(that, that.options.cookieIdTable, cookieIds.filterControl));
                        if (filterControl) {
                            var field = null,
                                result = [],
                                header = getCurrentHeader(that),
                                searchControls = getCurrentSearchControls(that);

                            header.find(searchControls).each(function (index, ele) {
                                field = $(this).closest('[data-field]').data('field');
                                result = $.grep(filterControl, function (valueObj) {
                                    return valueObj.field === field;
                                });

                                if (result.length > 0) {
                                    $(this).val(result[0].text);
                                    that.onColumnSearch({currentTarget: $(this)});
                                }
                            });
                        }
                    }
                }, 250);
            });
        }
        _init.apply(this, Array.prototype.slice.apply(arguments));
    };

    BootstrapTable.prototype.initTable = function () {
        _initTable.apply(this, Array.prototype.slice.apply(arguments));
        this.initCookie();
    };

    BootstrapTable.prototype.initCookie = function () {
        if (!this.options.cookie) {
            return;
        }

        if ((this.options.cookieIdTable === '') || (this.options.cookieExpire === '') || (!cookieEnabled())) {
            throw new Error("Configuration error. Please review the cookieIdTable, cookieExpire properties, if those properties are ok, then this browser does not support the cookies");
            return;
        }

        var sortOrderCookie = getCookie(this, this.options.cookieIdTable, cookieIds.sortOrder),
            sortOrderNameCookie = getCookie(this, this.options.cookieIdTable, cookieIds.sortName),
            pageNumberCookie = getCookie(this, this.options.cookieIdTable, cookieIds.pageNumber),
            pageListCookie = getCookie(this, this.options.cookieIdTable, cookieIds.pageList),
            columnsCookie = JSON.parse(getCookie(this, this.options.cookieIdTable, cookieIds.columns)),
            searchTextCookie = getCookie(this, this.options.cookieIdTable, cookieIds.searchText);

        //sortOrder
        this.options.sortOrder = sortOrderCookie ? sortOrderCookie : this.options.sortOrder;
        //sortName
        this.options.sortName = sortOrderNameCookie ? sortOrderNameCookie : this.options.sortName;
        //pageNumber
        this.options.pageNumber = pageNumberCookie ? +pageNumberCookie : this.options.pageNumber;
        //pageSize
        this.options.pageSize = pageListCookie ? pageListCookie === this.options.formatAllRows() ? pageListCookie : +pageListCookie : this.options.pageSize;
        //searchText
        this.options.searchText = searchTextCookie ? searchTextCookie : '';

        if (columnsCookie) {
            $.each(this.columns, function (i, column) {
                column.visible = $.inArray(column.field, columnsCookie) !== -1;
            });
        }
    };

    BootstrapTable.prototype.onSort = function () {
        _onSort.apply(this, Array.prototype.slice.apply(arguments));
        setCookie(this, cookieIds.sortOrder, this.options.sortOrder);
        setCookie(this, cookieIds.sortName, this.options.sortName);
    };

    BootstrapTable.prototype.onPageNumber = function () {
        _onPageNumber.apply(this, Array.prototype.slice.apply(arguments));
        setCookie(this, cookieIds.pageNumber, this.options.pageNumber);
    };

    BootstrapTable.prototype.onPageListChange = function () {
        _onPageListChange.apply(this, Array.prototype.slice.apply(arguments));
        setCookie(this, cookieIds.pageList, this.options.pageSize);
    };

    BootstrapTable.prototype.onPageFirst = function () {
        _onPageFirst.apply(this, Array.prototype.slice.apply(arguments));
        setCookie(this, cookieIds.pageNumber, this.options.pageNumber);
    };

    BootstrapTable.prototype.onPagePre = function () {
        _onPagePre.apply(this, Array.prototype.slice.apply(arguments));
        setCookie(this, cookieIds.pageNumber, this.options.pageNumber);
    };

    BootstrapTable.prototype.onPageNext = function () {
        _onPageNext.apply(this, Array.prototype.slice.apply(arguments));
        setCookie(this, cookieIds.pageNumber, this.options.pageNumber);
    };

    BootstrapTable.prototype.onPageLast = function () {
        _onPageLast.apply(this, Array.prototype.slice.apply(arguments));
        setCookie(this, cookieIds.pageNumber, this.options.pageNumber);
    };

    BootstrapTable.prototype.toggleColumn = function () {
        _toggleColumn.apply(this, Array.prototype.slice.apply(arguments));

        var visibleColumns = [];

        $.each(this.columns, function (i, column) {
            if (column.visible) {
                visibleColumns.push(column.field);
            }
        });

        setCookie(this, cookieIds.columns, JSON.stringify(visibleColumns));
    };

    BootstrapTable.prototype.selectPage = function (page) {
        _selectPage.apply(this, Array.prototype.slice.apply(arguments));
        setCookie(this, cookieIds.pageNumber, page);
    };

    BootstrapTable.prototype.onSearch = function () {
        _onSearch.apply(this, Array.prototype.slice.apply(arguments));
        setCookie(this, cookieIds.searchText, this.searchText);
    };

    BootstrapTable.prototype.deleteCookie = function (cookieName) {
        if ((cookieName === '') || (!cookieEnabled())) {
            return;
        }

        deleteCookie(this.options.cookieIdTable, cookieIds[cookieName], this.options.cookiePath, this.options.cookieDomain);
    };
})(jQuery);
<commit_msg>fix searchtext cookie set by column filters'<commit_after>/**
 * @author: Dennis Hernández
 * @webSite: http://djhvscf.github.io/Blog
 * @version: v1.2.0
 *
 * @update zhixin wen <wenzhixin2010@gmail.com>
 */

(function ($) {
    'use strict';

    var cookieIds = {
        sortOrder: 'bs.table.sortOrder',
        sortName: 'bs.table.sortName',
        pageNumber: 'bs.table.pageNumber',
        pageList: 'bs.table.pageList',
        columns: 'bs.table.columns',
        searchText: 'bs.table.searchText',
        filterControl: 'bs.table.filterControl'
    };

    var getCurrentHeader = function (that) {
        var header = that.$header;
        if (that.options.height) {
            header = that.$tableHeader;
        }

        return header;
    };

    var getCurrentSearchControls = function (that) {
        var searchControls = 'select, input';
        if (that.options.height) {
            searchControls = 'table select, table input';
        }

        return searchControls;
    };

    var cookieEnabled = function () {
        return !!(navigator.cookieEnabled);
    };

    var inArrayCookiesEnabled = function (cookieName, cookiesEnabled) {
        var index = -1;

        for (var i = 0; i < cookiesEnabled.length; i++) {
            if (cookieName.toLowerCase() === cookiesEnabled[i].toLowerCase()) {
                index = i;
                break;
            }
        }

        return index;
    };

    var setCookie = function (that, cookieName, cookieValue) {
        if ((!that.options.cookie) || (!cookieEnabled()) || (that.options.cookieIdTable === '')) {
            return;
        }

        if (inArrayCookiesEnabled(cookieName, that.options.cookiesEnabled) === -1) {
            return;
        }

        cookieName = that.options.cookieIdTable + '.' + cookieName;
        if (!cookieName || /^(?:expires|max\-age|path|domain|secure)$/i.test(cookieName)) {
            return false;
        }

        document.cookie = encodeURIComponent(cookieName) + '=' + encodeURIComponent(cookieValue) + calculateExpiration(that.options.cookieExpire) + (that.options.cookieDomain ? '; domain=' + that.options.cookieDomain : '') + (that.options.cookiePath ? '; path=' + that.options.cookiePath : '') + (that.cookieSecure ? '; secure' : '');
        return true;
    };

    var getCookie = function (that, tableName, cookieName) {
        if (!cookieName) {
            return null;
        }

        if (inArrayCookiesEnabled(cookieName, that.options.cookiesEnabled) === -1) {
            return null;
        }

        cookieName = tableName + '.' + cookieName;

        return decodeURIComponent(document.cookie.replace(new RegExp('(?:(?:^|.*;)\\s*' + encodeURIComponent(cookieName).replace(/[\-\.\+\*]/g, '\\$&') + '\\s*\\=\\s*([^;]*).*$)|^.*$'), '$1')) || null;
    };

    var hasCookie = function (cookieName) {
        if (!cookieName) {
            return false;
        }
        return (new RegExp('(?:^|;\\s*)' + encodeURIComponent(cookieName).replace(/[\-\.\+\*]/g, '\\$&') + '\\s*\\=')).test(document.cookie);
    };

    var deleteCookie = function (tableName, cookieName, sPath, sDomain) {
        cookieName = tableName + '.' + cookieName;
        if (!hasCookie(cookieName)) {
            return false;
        }
        document.cookie = encodeURIComponent(cookieName) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT' + (sDomain ? '; domain=' + sDomain : '') + (sPath ? '; path=' + sPath : '');
        return true;
    };

    var calculateExpiration = function(cookieExpire) {
        var time = cookieExpire.replace(/[0-9]*/, ''); //s,mi,h,d,m,y
        cookieExpire = cookieExpire.replace(/[A-Za-z]/, ''); //number

        switch (time.toLowerCase()) {
            case 's':
                cookieExpire = +cookieExpire;
                break;
            case 'mi':
                cookieExpire = cookieExpire * 60;
                break;
            case 'h':
                cookieExpire = cookieExpire * 60 * 60;
                break;
            case 'd':
                cookieExpire = cookieExpire * 24 * 60 * 60;
                break;
            case 'm':
                cookieExpire = cookieExpire * 30 * 24 * 60 * 60;
                break;
            case 'y':
                cookieExpire = cookieExpire * 365 * 30 * 24 * 60 * 60;
                break;
            default:
                cookieExpire = undefined;
                break;
        }

        return cookieExpire === undefined ? '' : '; max-age=' + cookieExpire;
    };

    $.extend($.fn.bootstrapTable.defaults, {
        cookie: false,
        cookieExpire: '2h',
        cookiePath: null,
        cookieDomain: null,
        cookieSecure: null,
        cookieIdTable: '',
        cookiesEnabled: ['bs.table.sortOrder', 'bs.table.sortName', 'bs.table.pageNumber', 'bs.table.pageList', 'bs.table.columns', 'bs.table.searchText', 'bs.table.filterControl'],
        //internal variable
        filterControls: [],
        filterControlValuesLoaded: false
    });

    $.fn.bootstrapTable.methods.push('deleteCookie');

    var BootstrapTable = $.fn.bootstrapTable.Constructor,
        _init = BootstrapTable.prototype.init,
        _initTable = BootstrapTable.prototype.initTable,
        _onSort = BootstrapTable.prototype.onSort,
        _onPageNumber = BootstrapTable.prototype.onPageNumber,
        _onPageListChange = BootstrapTable.prototype.onPageListChange,
        _onPageFirst = BootstrapTable.prototype.onPageFirst,
        _onPagePre = BootstrapTable.prototype.onPagePre,
        _onPageNext = BootstrapTable.prototype.onPageNext,
        _onPageLast = BootstrapTable.prototype.onPageLast,
        _toggleColumn = BootstrapTable.prototype.toggleColumn,
        _selectPage = BootstrapTable.prototype.selectPage,
        _onSearch = BootstrapTable.prototype.onSearch;

    BootstrapTable.prototype.init = function () {
        var timeoutId = 0;
        this.options.filterControls = [];
        this.options.filterControlValuesLoaded = false;

        this.options.cookiesEnabled = typeof this.options.cookiesEnabled === 'string' ?
            this.options.cookiesEnabled.replace('[', '').replace(']', '').replace(/ /g, '').toLowerCase().split(',') : this.options.cookiesEnabled;

        if (this.options.filterControl) {
            var that = this;
            this.$el.on('column-search.bs.table', function (e, field, text) {
                var isNewField = true;

                for (var i = 0; i < that.options.filterControls.length; i++) {
                    if (that.options.filterControls[i].field === field) {
                        that.options.filterControls[i].text = text;
                        isNewField = false;
                        break;
                    }
                }
                if (isNewField) {
                    that.options.filterControls.push({
                        field: field,
                        text: text
                    });
                }

                setCookie(that, cookieIds.filterControl, JSON.stringify(that.options.filterControls));
            }).on('post-body.bs.table', function () {
                setTimeout(function () {
                    if (!that.options.filterControlValuesLoaded) {
                        that.options.filterControlValuesLoaded = true;
                        var filterControl = JSON.parse(getCookie(that, that.options.cookieIdTable, cookieIds.filterControl));
                        if (filterControl) {
                            var field = null,
                                result = [],
                                header = getCurrentHeader(that),
                                searchControls = getCurrentSearchControls(that);

                            header.find(searchControls).each(function (index, ele) {
                                field = $(this).closest('[data-field]').data('field');
                                result = $.grep(filterControl, function (valueObj) {
                                    return valueObj.field === field;
                                });

                                if (result.length > 0) {
                                    $(this).val(result[0].text);
                                    that.onColumnSearch({currentTarget: $(this)});
                                }
                            });
                        }
                    }
                }, 250);
            });
        }
        _init.apply(this, Array.prototype.slice.apply(arguments));
    };

    BootstrapTable.prototype.initTable = function () {
        _initTable.apply(this, Array.prototype.slice.apply(arguments));
        this.initCookie();
    };

    BootstrapTable.prototype.initCookie = function () {
        if (!this.options.cookie) {
            return;
        }

        if ((this.options.cookieIdTable === '') || (this.options.cookieExpire === '') || (!cookieEnabled())) {
            throw new Error("Configuration error. Please review the cookieIdTable, cookieExpire properties, if those properties are ok, then this browser does not support the cookies");
            return;
        }

        var sortOrderCookie = getCookie(this, this.options.cookieIdTable, cookieIds.sortOrder),
            sortOrderNameCookie = getCookie(this, this.options.cookieIdTable, cookieIds.sortName),
            pageNumberCookie = getCookie(this, this.options.cookieIdTable, cookieIds.pageNumber),
            pageListCookie = getCookie(this, this.options.cookieIdTable, cookieIds.pageList),
            columnsCookie = JSON.parse(getCookie(this, this.options.cookieIdTable, cookieIds.columns)),
            searchTextCookie = getCookie(this, this.options.cookieIdTable, cookieIds.searchText);

        //sortOrder
        this.options.sortOrder = sortOrderCookie ? sortOrderCookie : this.options.sortOrder;
        //sortName
        this.options.sortName = sortOrderNameCookie ? sortOrderNameCookie : this.options.sortName;
        //pageNumber
        this.options.pageNumber = pageNumberCookie ? +pageNumberCookie : this.options.pageNumber;
        //pageSize
        this.options.pageSize = pageListCookie ? pageListCookie === this.options.formatAllRows() ? pageListCookie : +pageListCookie : this.options.pageSize;
        //searchText
        this.options.searchText = searchTextCookie ? searchTextCookie : '';

        if (columnsCookie) {
            $.each(this.columns, function (i, column) {
                column.visible = $.inArray(column.field, columnsCookie) !== -1;
            });
        }
    };

    BootstrapTable.prototype.onSort = function () {
        _onSort.apply(this, Array.prototype.slice.apply(arguments));
        setCookie(this, cookieIds.sortOrder, this.options.sortOrder);
        setCookie(this, cookieIds.sortName, this.options.sortName);
    };

    BootstrapTable.prototype.onPageNumber = function () {
        _onPageNumber.apply(this, Array.prototype.slice.apply(arguments));
        setCookie(this, cookieIds.pageNumber, this.options.pageNumber);
    };

    BootstrapTable.prototype.onPageListChange = function () {
        _onPageListChange.apply(this, Array.prototype.slice.apply(arguments));
        setCookie(this, cookieIds.pageList, this.options.pageSize);
    };

    BootstrapTable.prototype.onPageFirst = function () {
        _onPageFirst.apply(this, Array.prototype.slice.apply(arguments));
        setCookie(this, cookieIds.pageNumber, this.options.pageNumber);
    };

    BootstrapTable.prototype.onPagePre = function () {
        _onPagePre.apply(this, Array.prototype.slice.apply(arguments));
        setCookie(this, cookieIds.pageNumber, this.options.pageNumber);
    };

    BootstrapTable.prototype.onPageNext = function () {
        _onPageNext.apply(this, Array.prototype.slice.apply(arguments));
        setCookie(this, cookieIds.pageNumber, this.options.pageNumber);
    };

    BootstrapTable.prototype.onPageLast = function () {
        _onPageLast.apply(this, Array.prototype.slice.apply(arguments));
        setCookie(this, cookieIds.pageNumber, this.options.pageNumber);
    };

    BootstrapTable.prototype.toggleColumn = function () {
        _toggleColumn.apply(this, Array.prototype.slice.apply(arguments));

        var visibleColumns = [];

        $.each(this.columns, function (i, column) {
            if (column.visible) {
                visibleColumns.push(column.field);
            }
        });

        setCookie(this, cookieIds.columns, JSON.stringify(visibleColumns));
    };

    BootstrapTable.prototype.selectPage = function (page) {
        _selectPage.apply(this, Array.prototype.slice.apply(arguments));
        setCookie(this, cookieIds.pageNumber, page);
    };

    BootstrapTable.prototype.onSearch = function () {
        var target = Array.prototype.slice.apply(arguments);
        _onSearch.apply(this, target);

        if ($(target[0].currentTarget).parent().hasClass('search')) {
          setCookie(this, cookieIds.searchText, this.searchText);
        }
    };

    BootstrapTable.prototype.deleteCookie = function (cookieName) {
        if ((cookieName === '') || (!cookieEnabled())) {
            return;
        }

        deleteCookie(this.options.cookieIdTable, cookieIds[cookieName], this.options.cookiePath, this.options.cookieDomain);
    };
})(jQuery);
<|endoftext|>


<commit_before>'use strict'

export default class LodashWrapper {
  constructor (_) {
    this.steps = []
    const self = this
    let step = 1
    // this.lodash = _.runInContext().mixin(
    //   _(_) // let the Inception begins :-)
    //   .functions()
    //   .keyBy()
    //   .mapValues(function (funcName) {
    //     return function (...args) {
    //       const result = _[funcName](...args)
    //
    //       self.steps.push({
    //         step: step++,
    //         funcName,
    //         args: JSON.stringify(args, null, 2),
    //         result: JSON.stringify(result, null, 2)
    //       })
    //
    //       return result
    //     }
    //   })
    //   .value()
    // )

    this.lodash = _.runInContext()

    // Proxy prototype methods
    _(this.lodash.prototype)
      .omit(['constructor', 'toJSON', 'value'])
      .forEach((body, name) => {
        const originalFunction = this.lodash.prototype[name]
        this.lodash.prototype[name] = function (...args) {
          const result = originalFunction.call(this, ...args)

          self.steps.push({
            step: step++,
            funcName: name,
            args: JSON.stringify(args, null, 2),
            result: JSON.stringify(result, null, 2)
          })

          return result
        }
      })
  }

  get stats () {
    return this.steps
  }

  resetStats () {
    this.steps = []
  }
}
<commit_msg>Rewrite inception logic<commit_after>'use strict'

export default class LodashWrapper {
  constructor (_) {
    this.steps = []
    let step = 1

    const record = (name, args, result) => {
      if (name === 'chain' || typeof (name) === 'undefined') {
        return
      }

      this.steps.push({
        step: step++,
        funcName: name,
        args: JSON.stringify(args, null, 2),
        result: JSON.stringify(result, null, 2)
      })
    }

    const availableFunctions = _.keys(_)

    const handler = {
      get: (original, propertyName) => {
        if (!availableFunctions.includes(propertyName)) {
          return original[propertyName]
        }

        // console.info(`Getting ${propertyName}`)
        original[propertyName].dexterLabFuncName = propertyName
        return new Proxy(original[propertyName], handler)
      },

      apply: (original, thisArg, args) => {
        // console.info(`Calling ${original.dexterLabFuncName}`)
        const result = original.apply(thisArg, args)

        if (result.__wrapped__) {
          record(original.dexterLabFuncName, args, result.value())
          return new Proxy(result, handler)
        }

        record(original.dexterLabFuncName, args, result)
        return result
      }
    }

     // let the Inception begins :-)
    this.lodash = new Proxy(_.runInContext(), handler)
  }

  get stats () {
    return this.steps
  }

  resetStats () {
    this.steps = []
  }
}
<|endoftext|>


<commit_before>// Copyright 2015, EMC, Inc.
/* jshint node:true */

'use strict';

describe('Http.Api.Files', function () {
    it('needs specs');
});
<commit_msg>add unit test for file router<commit_after>// Copyright 2015, EMC, Inc.
/* jshint node:true */

'use strict';

var stream = require('stream');

describe('Http.Api.Files', function() {
    var fileService,
        mockRdStream;

    before('start HTTP server', function() {
        this.timeout(5000);
        return helper.startServer().then(function() {
            fileService = helper.injector.get('fileService');
        });
    });

    after('stop HTTP server', function() {
        return helper.stopServer();
    });

    describe('GET /files/:uuid', function() {
        before('create mock file stream', function() {
            mockRdStream = new stream.Readable();
            mockRdStream._read = function() {
                this.push('this is mock file 1234');
                this.push(null);
            };
        });

        beforeEach('set up mocks', function() {
            sinon.stub(fileService, 'get');
        });

        afterEach('tear down mocks', function() {
            fileService.get.restore();
        });

        it('should return file by uuid', function() {
            fileService.get.withArgs('1234')
                .returns(Promise.resolve(mockRdStream));

            return helper.request()
                .get('/api/1.1/files/1234')
                .expect(200)
                .expect('this is mock file 1234')
                .expect(function() {
                    expect(fileService.get).to.have.been.calledOnce;
                });
        });

        it('should return File not found', function() {
            fileService.get.withArgs('5678')
                .returns(Promise.reject({ name: '404' }));

            return helper.request()
                .get('/api/1.1/files/5678')
                .expect('Content-Type', /^application\/json/)
                .expect(404)
                .expect({ error: 'File not found.' })
                .expect(function() {
                    expect(fileService.get).to.have.been.calledOnce;
                });
        });

        it('should return Failed to serve file request', function() {
            fileService.get.withArgs('abcd')
                .returns(Promise.reject({}));

            return helper.request()
                .get('/api/1.1/files/abcd')
                .expect('Content-Type', /^application\/json/)
                .expect(500)
                .expect({ error: 'Failed to serve file request.' })
                .expect(function() {
                    expect(fileService.get).to.have.been.calledOnce;
                });
        });
    });

    describe('GET /files/:filename/latest', function() {
        before('create mock file stream', function() {
            mockRdStream = new stream.Readable();
            mockRdStream._read = function() {
                this.push('this is mock file, filename:mockfile1');
                this.push(null);
            };
        });

        beforeEach('set up mocks', function() {
            sinon.stub(fileService, 'get');
            sinon.stub(fileService, 'verify');
        });

        afterEach('tear down mocks', function() {
            fileService.get.restore();
            fileService.verify.restore();
        });

        it('should return latest file by filename', function() {
            fileService.verify.withArgs('mockfile1')
                .returns(Promise.resolve(
                    [
                        { uuid: 'abcd' },
                        { uuid: '5678' },
                        { uuid: '1234' }
                    ]
                ));

            fileService.get.withArgs('1234')
                .returns(Promise.resolve(mockRdStream));

            return helper.request()
                .get('/api/1.1/files/mockfile1/latest')
                .expect(200)
                .expect('this is mock file, filename:mockfile1')
                .expect(function() {
                    expect(fileService.verify).to.have.been.calledOnce;
                    expect(fileService.get).to.have.been.calledOnce;
                });
        });

        it('should return File not found', function() {
            fileService.verify.withArgs('mockfile2')
                .returns(Promise.reject({ name: '404' }));

            return helper.request()
                .get('/api/1.1/files/mockfile2/latest')
                .expect('Content-Type', /^application\/json/)
                .expect(404)
                .expect({ error: 'File not found.' })
                .expect(function() {
                    expect(fileService.verify).to.have.been.calledOnce;
                    expect(fileService.get).to.not.have.been.called;
                });
        });

        it('should return File not found 2', function() {
            fileService.verify.withArgs('mockfile3')
                .returns(Promise.resolve([{ uuid: '1234' }]));

            fileService.get.returns(Promise.reject({ name: '404' }));

            return helper.request()
                .get('/api/1.1/files/mockfile3/latest')
                .expect('Content-Type', /^application\/json/)
                .expect(404)
                .expect({ error: 'File not found.' })
                .expect(function() {
                    expect(fileService.verify).to.have.been.calledOnce;
                    expect(fileService.get).to.have.been.calledOnce;
                });
        });

        it('should return Failed to serve file request', function() {
            fileService.verify.withArgs('mockfile4')
                .returns(Promise.resolve([{ uuid: '1234' }]));

            fileService.get.returns(Promise.reject({}));

            return helper.request()
                .get('/api/1.1/files/mockfile4/latest')
                .expect('Content-Type', /^application\/json/)
                .expect(500)
                .expect({ error: 'Failed to serve file request.' })
                .expect(function() {
                    expect(fileService.get).to.have.been.calledOnce;
                    expect(fileService.get).to.have.been.calledOnce;
                });
        });
    });

    describe('DELETE /files/:uuid', function() {
        beforeEach('set up mocks', function() {
            sinon.stub(fileService, 'delete');
        });

        afterEach('tear down mocks', function() {
            fileService.delete.restore();
        });

        it('should delete file by uuid', function() {
            fileService.delete.withArgs('1234')
                .returns(Promise.resolve());

            return helper.request()
                .delete('/api/1.1/files/1234')
                .expect(204)
                .expect(function() {
                    expect(fileService.delete).to.have.been.calledOnce;
                });
        });

        it('should return File not found', function() {
            fileService.delete.withArgs('5678')
                .returns(Promise.reject({ name: '404' }));

            return helper.request()
                .delete('/api/1.1/files/5678')
                .expect('Content-Type', /^application\/json/)
                .expect(404)
                .expect({ error: 'File not found.' })
                .expect(function() {
                    expect(fileService.delete).to.have.been.calledOnce;
                });
        });

        it('should return Error deleting file from the database', function() {
            fileService.delete.withArgs('abcd')
                .returns(Promise.reject({}));

            return helper.request()
                .delete('/api/1.1/files/abcd')
                .expect('Content-Type', /^application\/json/)
                .expect(500)
                .expect({ error: 'Error deleting file from the database.' })
                .expect(function() {
                    expect(fileService.delete).to.have.been.calledOnce;
                });
        });
    });

    describe('GET /files/metadata/:filename', function() {
        beforeEach('set up mocks', function() {
            sinon.stub(fileService, 'verify');
        });

        afterEach('tear down mocks', function() {
            fileService.verify.restore();
        });

        it('should return metadata by filename', function() {
            fileService.verify.withArgs('mockfile1')
                .returns(Promise.resolve([{ uuid: '123456' }]));

            return helper.request()
                .get('/api/1.1/files/metadata/mockfile1')
                .expect(200)
                .expect([{ uuid: '123456'}])
                .expect(function() {
                    expect(fileService.verify).to.have.been.calledOnce;
                });
        });

        it('should return File not found', function() {
            fileService.verify.withArgs('mockfile2')
                .returns(Promise.reject({ name: '404' }));

            return helper.request()
                .get('/api/1.1/files/metadata/mockfile2')
                .expect('Content-Type', /^application\/json/)
                .expect(404)
                .expect({ error: 'File not found.' })
                .expect(function() {
                    expect(fileService.verify).to.have.been.calledOnce;
                });
        });

        it('should return Error retrieving metadata', function() {
            fileService.verify.withArgs('mockfile3')
                .returns(Promise.reject({}));

            return helper.request()
                .get('/api/1.1/files/metadata/mockfile3')
                .expect('Content-Type', /^application\/json/)
                .expect(500)
                .expect({ error: 'Error retrieving metadata.' })
                .expect(function() {
                    expect(fileService.verify).to.have.been.calledOnce;
                });
        });
    });

    describe('GET /files/md5/:filename/latest', function() {
        beforeEach('set up mocks', function() {
            sinon.stub(fileService, 'verify');
        });

        afterEach('tear down mocks', function() {
            fileService.verify.restore();
        });

        it('should return md5 by filename', function() {
            fileService.verify.withArgs('mockfile1')
                .returns(Promise.resolve([{ md5: 'xxxx-yyyy' }]));

            return helper.request()
                .get('/api/1.1/files/md5/mockfile1/latest')
                .expect(200)
                .expect('"xxxx-yyyy"')
                .expect(function() {
                    expect(fileService.verify).to.have.been.calledOnce;
                });
        });

        it('should return File not found', function() {
            fileService.verify.withArgs('mockfile2')
                .returns(Promise.reject({ name: '404' }));

            return helper.request()
                .get('/api/1.1/files/md5/mockfile2/latest/')
                .expect('Content-Type', /^application\/json/)
                .expect(404)
                .expect({ error: 'File not found.' })
                .expect(function() {
                    expect(fileService.verify).to.have.been.calledOnce;
                });
        });

        it('should return Error retrieving metadata', function() {
            fileService.verify.withArgs('mockfile3')
                .returns(Promise.reject({}));

            return helper.request()
                .get('/api/1.1/files/md5/mockfile3/latest')
                .expect('Content-Type', /^application\/json/)
                .expect(500)
                .expect({ error: 'Error retrieving metadata.' })
                .expect(function() {
                    expect(fileService.verify).to.have.been.calledOnce;
                });
        });
    });

    describe('GET /files/list/all', function() {
        beforeEach('set up mocks', function() {
            sinon.stub(fileService, 'list');
        });

        afterEach('tear down mocks', function() {
            fileService.list.restore();
        });

        it('should return file list by query', function() {
            fileService.list.withArgs({ name: 'file1'})
                .returns(Promise.resolve([{ name: 'file1', data: 'test data' }]));

            return helper.request()
                .get('/api/1.1/files/list/all')
                .send({ name: 'file1'})
                .expect(200)
                .expect([{ name: 'file1', data: 'test data'}])
                .expect(function() {
                    expect(fileService.list).to.have.been.calledOnce;
                });
        });

        it('should return Error retrieving file list', function() {
            fileService.list.returns(Promise.reject({}));

            return helper.request()
                .get('/api/1.1/files/list/all')
                .expect('Content-Type', /^application\/json/)
                .expect(500)
                .expect({ error: 'Error retrieving file list.' })
                .expect(function() {
                    expect(fileService.list).to.have.been.calledOnce;
                });
        });
    });
});
<|endoftext|>


<commit_before>import angular from "angular";

import squareImageModule from "../square-image.js";
import postContentModule from "../post-content.js";

import { connect2Redux } from "../../won-utils.js";
import { attach, getIn } from "../../utils.js";
import { actionCreators } from "../../actions/actions.js";
import { classOnComponentRoot } from "../../cstm-ng-utils.js";

const serviceDependencies = ["$ngRedux", "$scope", "$element"];

function genComponentConf() {
  let template = `

        <won-square-image
            class="clickable"
            uri="::self.postUri"
            ng-if="!self.postLoading"
            ng-click="self.router__stateGoCurrent({postUri: self.postUri})">
        </won-square-image>

                <won-post-content post-uri="self.postUri">

    `;

  class Controller {
    constructor(/* arguments = dependency injections */) {
      attach(this, serviceDependencies, arguments);
      window.pcm4dbg = this;

      const selectFromState = state => {
        const post = this.postUri && state.getIn(["needs", this.postUri]);

        return {
          post,
          postLoading:
            !post ||
            getIn(state, ["process", "needs", post.get("uri"), "loading"]),
        };
      };

      connect2Redux(selectFromState, actionCreators, ["self.postUri"], this);
      classOnComponentRoot("won-is-loading", () => this.postLoading, this);
    }
  }
  Controller.$inject = serviceDependencies;

  return {
    restrict: "E",
    controller: Controller,
    controllerAs: "self",
    bindToController: true, //scope-bindings -> ctrl
    scope: {
      postUri: "=",
    },
    template: template,
  };
}

export default angular
  .module("won.owner.components.postContentMessage", [
    squareImageModule,
    postContentModule,
  ])
  .directive("wonPostContentMessage", genComponentConf).name;
<commit_msg>Adds connectionUri to post-content-message as preliminary work to add the hints in that component instead of within the chat<commit_after>import angular from "angular";

import squareImageModule from "../square-image.js";
import postContentModule from "../post-content.js";

import { connect2Redux } from "../../won-utils.js";
import { attach, getIn } from "../../utils.js";
import { actionCreators } from "../../actions/actions.js";
import { classOnComponentRoot } from "../../cstm-ng-utils.js";

const serviceDependencies = ["$ngRedux", "$scope", "$element"];

function genComponentConf() {
  let template = `

        <won-square-image
            class="clickable"
            uri="::self.postUri"
            ng-if="!self.postLoading"
            ng-click="self.router__stateGoCurrent({postUri: self.postUri})">
        </won-square-image>

                <won-post-content post-uri="self.postUri">

    `;

  class Controller {
    constructor(/* arguments = dependency injections */) {
      attach(this, serviceDependencies, arguments);
      window.pcm4dbg = this;

      const selectFromState = state => {
        const post = this.postUri && state.getIn(["needs", this.postUri]);

        return {
          post,
          postLoading:
            !post ||
            getIn(state, ["process", "needs", post.get("uri"), "loading"]),
        };
      };

      connect2Redux(
        selectFromState,
        actionCreators,
        ["self.postUri", "self.connectionUri"],
        this
      );
      classOnComponentRoot("won-is-loading", () => this.postLoading, this);
    }
  }
  Controller.$inject = serviceDependencies;

  return {
    restrict: "E",
    controller: Controller,
    controllerAs: "self",
    bindToController: true, //scope-bindings -> ctrl
    scope: {
      postUri: "=",
      connectionUri: "=",
    },
    template: template,
  };
}

export default angular
  .module("won.owner.components.postContentMessage", [
    squareImageModule,
    postContentModule,
  ])
  .directive("wonPostContentMessage", genComponentConf).name;
<|endoftext|>


<commit_before>// package version used in the ix-lib parameter
export const VERSION = 'v3.1.3';
// regex pattern used to determine if a domain is valid
export const DOMAIN_REGEX = /^(?:[a-z\d\-_]{1,62}\.){0,125}(?:[a-z\d](?:\-(?=\-*[a-z\d])|[a-z]|\d){0,62}\.)[a-z\d]{1,63}$/i;
// minimum generated srcset width
export const MIN_SRCSET_WIDTH = 100;
// maximum generated srcset width
export const MAX_SRCSET_WIDTH = 8192;
// default tolerable percent difference between srcset pair widths
export const DEFAULT_SRCSET_WIDTH_TOLERANCE = 0.08;

// default quality parameter values mapped by each dpr srcset entry
export const DPR_QUALITIES = {
  1: 75,
  2: 50,
  3: 35,
  4: 23,
  5: 20,
};

export const DEFAULT_OPTIONS = {
  domain: null,
  useHTTPS: true,
  includeLibraryParam: true,
  urlPrefix: 'https://',
  secureURLToken: null,
};
<commit_msg>fix: remove "v" prefix from VERSION constant<commit_after>// package version used in the ix-lib parameter
export const VERSION = '3.1.3';
// regex pattern used to determine if a domain is valid
export const DOMAIN_REGEX = /^(?:[a-z\d\-_]{1,62}\.){0,125}(?:[a-z\d](?:\-(?=\-*[a-z\d])|[a-z]|\d){0,62}\.)[a-z\d]{1,63}$/i;
// minimum generated srcset width
export const MIN_SRCSET_WIDTH = 100;
// maximum generated srcset width
export const MAX_SRCSET_WIDTH = 8192;
// default tolerable percent difference between srcset pair widths
export const DEFAULT_SRCSET_WIDTH_TOLERANCE = 0.08;

// default quality parameter values mapped by each dpr srcset entry
export const DPR_QUALITIES = {
  1: 75,
  2: 50,
  3: 35,
  4: 23,
  5: 20,
};

export const DEFAULT_OPTIONS = {
  domain: null,
  useHTTPS: true,
  includeLibraryParam: true,
  urlPrefix: 'https://',
  secureURLToken: null,
};
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var _ = require('underscore');
var userService = require('services/user.service');

// routes
router.post('/googleClassAttendance', googleClassAttendance);

module.exports = router;

var daysArray = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
var dates = [];
var firstTrainingColumn = 0;
var lastTraingingColumn = 0;
var studentsAttendance = [];

function googleClassAttendance(req, res) {
    var stuff = req.body;
    getSheetData(stuff[0]);
    console.log("studentAttendance", studentsAttendance);
    res.sendStatus(200);
}

function getSheetData(result){
        dates = [];
        firstTrainingColumn = _.findIndex(result[0], findDay);
        lastTraingingColumn = _.findLastIndex(result[0], findDay);
        constructDates(result);
        console.log("dates", dates);
        getAllUsers(null, null, result);
}

function findDay(day) {
    return _.find(daysArray, function (dayName) {
        if (day == dayName) {
            return true;
        }
    });
}

function constructDates(result){
    _.each(result[0], function(dateName, index){
        var date = {};
        if(index >= firstTrainingColumn && index <= lastTraingingColumn){
            date.dayName = dateName;
            dates.push(date);
        }
    });

    //date number
    _.each(result[1], function(dateName, index){
        if(index >= firstTrainingColumn && index <= lastTraingingColumn){
            dates[index - firstTrainingColumn].dateNumber = dateName;
        }
    });

    _.each(result[2], function(dateName, index){
        if(index >= firstTrainingColumn && index <= lastTraingingColumn){
            dates[index - firstTrainingColumn].date = dateName;
        }
    });
}

function getAllUsers(req, res, data) {
    userService.getAll()
        .then(function (users) {
            if (users) {
                populateUsersAttendance(users, data)
            }
        });
}

function populateUsersAttendance(users, data){
    console.log("users", users);
    populateStudentAttendance(data);
    _.each(users, function(user){
        var studentAttendance = _.find(studentsAttendance, function(student){
            if(student.name.trim() == (user.firstName + " " + user.lastName)){
                return true;
            }
        });

        console.log("86, student Att", studentAttendance);

        if(studentAttendance != null){
            //user.attendance = [];
            _.each(studentAttendance.attendance, function(attended){
                if(attended.didAttend == 1){
                    var attend = _.find(user.attendance, function(userAttened){
                        if(userAttened == attended.date.trim()){
                            return true;
                        }
                    });
                    if(attend == null){
                        if(user.attendance == undefined){
                            user.attendance = [];
                        }
                        user.attendance.push(attended.date);
                    }
                }
            });

            userService.update(user._id, user);
        }
    });

}

function populateStudentAttendance(result){
    _.each(result, function(row){
        var student = {};
        student.attendance = [];
        _.each(row, function(column, index){
            console.log("studentname", column);
            if(index == 1){
                student.name = column;
            }

            if(index >= firstTrainingColumn && index <= lastTraingingColumn){
                var attended = {};
                attended.date = vm.dates[index - firstTrainingColumn].date;
                attended.didAttend = column;
                student.attendance.push(attended);
            }

        });

        if(student.name != null && student.name != "" && student.name != "Name"){
            studentsAttendance.push(student);
        }
    });
}

<commit_msg>stuff<commit_after>var express = require('express');
var router = express.Router();
var _ = require('underscore');
var userService = require('services/user.service');

// routes
router.post('/googleClassAttendance', googleClassAttendance);

module.exports = router;

var daysArray = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
var dates = [];
var firstTrainingColumn = 0;
var lastTraingingColumn = 0;
var studentsAttendance = [];

function googleClassAttendance(req, res) {
    var stuff = req.body;
    getSheetData(stuff[0]);
    console.log("studentAttendance", studentsAttendance);
    res.sendStatus(200);
}

function getSheetData(result){
        dates = [];
        firstTrainingColumn = _.findIndex(result[0], findDay);
        lastTraingingColumn = _.findLastIndex(result[0], findDay);
        constructDates(result);
        getAllUsers(null, null, result);
}

function findDay(day) {
    return _.find(daysArray, function (dayName) {
        if (day == dayName) {
            return true;
        }
    });
}

function constructDates(result){
    _.each(result[0], function(dateName, index){
        var date = {};
        if(index >= firstTrainingColumn && index <= lastTraingingColumn){
            date.dayName = dateName;
            dates.push(date);
        }
    });

    //date number
    _.each(result[1], function(dateName, index){
        if(index >= firstTrainingColumn && index <= lastTraingingColumn){
            dates[index - firstTrainingColumn].dateNumber = dateName;
        }
    });

    _.each(result[2], function(dateName, index){
        if(index >= firstTrainingColumn && index <= lastTraingingColumn){
            dates[index - firstTrainingColumn].date = dateName;
        }
    });
}

function getAllUsers(req, res, data) {
    userService.getAll()
        .then(function (users) {
            if (users) {
                populateUsersAttendance(users, data)
            }
        });
}

function populateUsersAttendance(users, data){
    populateStudentAttendance(data);
    _.each(users, function(user){
        var studentAttendance = _.find(studentsAttendance, function(student){
            if(student.name.trim() == (user.firstName + " " + user.lastName)){
                return true;
            }
        });

        console.log("86, student Att", studentAttendance);

        if(studentAttendance != null){
            _.each(studentAttendance.attendance, function(attended){
                if(attended.didAttend == 1){
                    var attend = _.find(user.attendance, function(userAttened){
                        if(userAttened == attended.date.trim()){
                            return true;
                        }
                    });
                    if(attend == null){
                        if(user.attendance == undefined){
                            user.attendance = [];
                        }
                        user.attendance.push(attended.date);
                    }
                }
            });

            userService.update(user._id, user);
        }
    });

}

function populateStudentAttendance(result){
    _.each(result, function(row){
        console.log(row);
        var student = {};
        student.attendance = [];
        _.each(row, function(column, index){
            if(index == 1){
                student.name = column;
            }

            if(index >= firstTrainingColumn && index <= lastTraingingColumn){
                var attended = {};
                attended.date = dates[index - firstTrainingColumn].date;
                attended.didAttend = column;
                student.attendance.push(attended);
            }

        });

        if(student.name != null && student.name != "" && student.name != "Name"){
            studentsAttendance.push(student);
        }
    });
}

<|endoftext|>