<commit_before>var closest = require('closest');
var each = require('each');
var geocode = require('geocode');
var hogan = require('hogan.js');
var log = require('./client/log')('locations-view');
var mouse = require('mouse-position');
var textModal = require('text-modal');
var view = require('view');
var analytics = require('analytics');
var ua = require('user-agent');
var session = require('session');

/**
 * Expose `View`
 */

var View = module.exports = view(require('./template.html'), function(view, plan) {
  view.on('rendered', function() {
    var self = this;
    window.setTimeout(function(){
      self.resetIcons();
    }, 200);

    closest(view.el, 'form').onsubmit = function(e) {
      e.preventDefault();

      plan.setAddresses(view.find('.from input').value, view.find('.to input').value, function(err) {
        if (err) {
          log.error('%e', err);
        } else {
          plan.updateRoutes();
        }
      });

    };
  });
});

/**
 * Address Changed
 */

View.prototype.blurInput = function(e) {
  log('input blurred, saving changes');

  var inputGroup = e.target.parentNode;
  var suggestionList = inputGroup.getElementsByTagName('ul')[0];
  inputGroup.classList.remove('suggestions-open');

  var highlight = this.find('.suggestion.highlight');
  if (highlight) {
    console.log('highlighting');
    e.target.value = highlight.textContent || '';
    if (highlight.dataset.lat) {
      e.target.lat = highlight.dataset.lat;
      e.target.lng = highlight.dataset.lng;
      e.target.address = highlight.addressData;
    }
  }

  suggestionList.classList.add('empty');

  setTimeout(function() {
    suggestionList.innerHTML = '';
  }, 500);

  inputGroup.classList.remove('highlight');
  this.save(e.target);
  //  this.scrollDown(0, 0);
};

/**
 * Keypress
 */

View.prototype.keydownInput = function(e) {
  var el = e.target;
  var key = e.keyCode;

  // Currently highlighted suggestion
  var highlightedSuggestion = this.find('.suggestion.highlight');

  switch (key) {
    case 13: // enter key
      console.log('enter key');
      this.blurInput(e);
      break;
    case 38: // up key
    case 40: // down key
      if (key === 38) {
        this.pressUp(highlightedSuggestion, el);
      } else {
        this.pressDown(highlightedSuggestion, el);
      }

      var newHighlight = this.find('.suggestion.highlight');
      if (newHighlight) el.value = newHighlight.textContent || '';
      break;
  }
};

/**
 * Press Up
 */

View.prototype.pressUp = function(highlightedSuggestion, el) {
  if (highlightedSuggestion) {
    var aboveHighlightedSuggestion = highlightedSuggestion.previousElementSibling;

    if (aboveHighlightedSuggestion) {
      aboveHighlightedSuggestion.classList.add('highlight');
    } else {
      el.value = this.currentLocation || '';
      setCursor(el, el.value.length);
    }
    highlightedSuggestion.classList.remove('highlight');
  }
};

/**
 * Press Down
 */

View.prototype.pressDown = function(highlightedSuggestion, el) {
  if (!highlightedSuggestion) {
    var suggestion = this.find('.suggestion');
    if (suggestion) suggestion.classList.add('highlight');
  } else if (highlightedSuggestion.nextElementSibling) {
    highlightedSuggestion.nextElementSibling.classList.add('highlight');
    highlightedSuggestion.classList.remove('highlight');
  }
};

/**
 * Geocode && Save
 */

View.prototype.save = function(el) {
  var plan = this.model;
  var name = el.name;
  var val = el.value;

  if (!val || plan[name]() === val) return;

  if (el.lat) {
    this.model.setAddress(name, el.lng + ',' + el.lat, function(err, location) {

      if (err) {
        log.error('%e', err);
        analytics.send_ga({
          category: 'geocoder',
          action: 'change address invalid',
          label: val,
          value: 0
        });

        textModal('Invalid address.');

      } else if (location && plan.validCoordinates()) {

        analytics.send_ga({
          category: 'geocoder',
          action: 'change address success',
          label: val,
          value: 0
        });

        plan.updateRoutes();

      } else {
        console.log("no ejecuta nada");
      }
    }, el.address);
  } else {

    this.model.setAddress(name, val, function(err, location) {
      if (err) {
        log.error('%e', err);
        analytics.send_ga({
          category: 'geocoder',
          action: 'change address invalid',
          label: val,
          value: 0
        });

        textModal('Invalid address.');
      } else if (location && plan.validCoordinates()) {
        analytics.send_ga({
          category: 'geocoder',
          action: 'change address success',
          label: val,
          value: 0
        });
        plan.updateRoutes();

      }
    });
  }
  this.resetIcons();
};

/**
 * Scroll down a certain number of pixels
 */

View.prototype.scrollDown = function(num, duration) {
  duration = duration || 200;
  console.log('scroll down', num)
  $('.fullscreen').animate({
    scrollTop: num
  }, duration);
};

/**
 * Highlight the selected input
 */

View.prototype.focusInput = function(e) {
  var $wrapper = $('.fullscreen');
  var offsetTop = $wrapper.scrollTop() + $(e.target).offset().top;
  console.log($wrapper.scrollTop(), offsetTop, e.target);
  if (!!e && e.scrollIntoView) {
    e.target.scrollIntoView()
    $(e.target).blur()
    $(e.target).focus()
  }
  if (ua.os.name === 'Android' && ua.browser.name === 'Chrome') {
    this.scrollDown(offsetTop - 20);
  }
  e.target.parentNode.classList.add('highlight');
};

/**
 * Suggestions Template
 */

var suggestionsTemplate = hogan.compile(require('./suggestions.html'));
var suggestionTimeout;

function getAddress(s) {
  var city = '';
  if (s.city)
    city = s.city;
  else if (s.town)
    city = s.town;
  else if (s.village)
    city = s.village;
  else if (s.hamlet)
    city = s.hamlet;

  var street = '';
  if (s.road)
    street = s.road;
  else if (s.pedestrian)
    street = s.pedestrian;
  else if (s.footway)
    street = s.footway;
  else if (s.industrial)
    street = s.industrial;
  else if (s.cycleway)
    street = s.cycleway;

  var number = '';
  if (s.house_number)
    number = s.house_number;
  else if (s.parking)
    number = s.parking;

  var place = '';
  if (s.aerodrome)
    place = s.aerodrome + ', ' + city;
  else if (s.stadium)
    place = s.stadium + ', ' + city;
  else if (s.school)
    place = s.school + ', ' + city;
  else if (s.museum)
    place = s.museum + ', ' + city;
  else if (s.restaurant)
    place = s.restaurant + ', ' + street + ', ' + city;
  else if (s.cafe)
    place = s.cafe + ', ' + street + ', ' + city;
  else if (s.pub)
    place = s.pub + ', ' + street + ', ' + city;
  else if (s.bar)
    place = s.bar + ', ' + street + ', ' + city;
  else if (s.fast_food)
    place = s.fast_food + ', ' + street + ', ' + city;
  else if (s.place_of_worship)
    place = s.place_of_worship + ', ' + street + ', ' + city;

  if (place.length > 0)
    return place;
  else
    return $.grep([number, street, city, s.state], Boolean).join(", ")
}

/**
 * Suggest
 */

View.prototype.suggest = function(e) {
  var input = e.target;
  var text = input.value || '';
  var name = input.name;
  var inputGroup = input.parentNode;
  var suggestionList = inputGroup.getElementsByTagName('ul')[0];
  var view = this;
  var suggestionsData = [];

  this.resetIcons();

  var resultsCallbackAmigo = function(err, suggestions) {

    if (err) {
      log.error('%e', err);
    } else {
      if (suggestions && suggestions.length > 0) {
        var filter_label = {};
        for (var i = 0; i < suggestions.length; i++) {

          var item_suggestions = suggestions[i].properties;

          if (item_suggestions.country_a == "USA" && item_suggestions.region_a == "CA") {

            var item_geometry = suggestions[i].geometry;
            var suggestion_obj = {
              "index": i,
              "text": item_suggestions.label,
              "lat": item_geometry.coordinates[1],
              "lon": item_geometry.coordinates[0],
              "magicKey": ""
            };

            if (filter_label[item_suggestions.label] === undefined) {
              filter_label[item_suggestions.label] = true;
              suggestionsData.push(suggestion_obj);
            }

          }

        }

        suggestionsData = suggestionsData.slice(0, 8);
        suggestionList.innerHTML = suggestionsTemplate.render({
          suggestions: suggestionsData
        });
        /*******************/
        each(view.findAll('.suggestion'), function(li) {
          li.addressData = suggestions[li.dataset.index];

          li.onmouseover = function(e) {
            li.classList.add('highlight');
          };

          li.onmouseout = function(e) {
            li.classList.remove('highlight');
          };
        });

        suggestionList.classList.remove('empty');
        inputGroup.classList.add('suggestions-open');
        /*******************/
      } else {
        suggestionList.classList.add('empty');
        inputGroup.classList.remove('suggestions-open');
      }
    }
  };

  var resultsCallback = function(err, suggestions) {

    if (err) {
      log.error('%e', err);
    } else {
      if (suggestions && suggestions.length > 0) {

        for (var i = 0; i < suggestions.length; i++) {
          if (!suggestions[i].text) {
            if (suggestions[i].address) {
              suggestions[i].text = getAddress(suggestions[i].address);
            } else {
              suggestions[i].text = suggestions[i].display_name;
            }
          }
          suggestions[i].index = i;
        }
        suggestions = suggestions.slice(0, 5);

        suggestionList.innerHTML = suggestionsTemplate.render({
          suggestions: suggestions
        });

        each(view.findAll('.suggestion'), function(li) {
          li.addressData = suggestions[li.dataset.index];

          li.onmouseover = function(e) {
            li.classList.add('highlight');
          };

          li.onmouseout = function(e) {
            li.classList.remove('highlight');
          };
        });

        suggestionList.classList.remove('empty');
        inputGroup.classList.add('suggestions-open');
      } else {
        suggestionList.classList.add('empty');
        inputGroup.classList.remove('suggestions-open');
      }
    }
  };

  // If the text is too short or does not contain a space yet, return
  if (text.length < 3) return;

  // Get a suggestion!
  if (suggestionTimeout !== undefined) {
    clearTimeout(suggestionTimeout);
  }
  suggestionTimeout = setTimeout(function() {
    console.log('timeout trigger')
    geocode.suggestAmigo(text, resultsCallbackAmigo);
  }, 50);
};

/**
 * Clear
 */

View.prototype.clear = function(e) {
  e.preventDefault();
  var inputGroup = e.target.parentNode;
  var input = inputGroup.getElementsByTagName('input')[0];
  input.value = '';
  this.resetIcons();
  input.focus();
};

View.prototype.locateMe = function(e) {
  e.preventDefault();
  var self = this;
  var inputGroup = e.target.parentNode;
  var input = inputGroup.getElementsByTagName('input')[0];

  this.resetIcons();
  if (navigator.geolocation) {

    var clear_btn = inputGroup.querySelector('.fa-times')
    var loading_btn = inputGroup.querySelector('.fa-spin')
    var location_me_btn = inputGroup.querySelector('.fa-location-arrow')
    clear_btn.classList.add('hidden')
    loading_btn.classList.remove('hidden')
    location_me_btn.classList.add('hidden')

    navigator.geolocation.getCurrentPosition(function(position) {
      var plan = session.plan();
      var target = input.id.indexOf('from') !== -1 ? 'from' : 'to';

      plan.setAddress(target, position.coords.longitude + ',' + position.coords.latitude, function(err, rees) {
        plan.updateRoutes();
        self.resetIcons();
      });
    }, null, {
      enableHighAccuracy: true,
      maximumAge: 10000,
      timeout: 30000
    });
  } else {
    this.resetIcons();
  }
}

View.prototype.resetIcons = function (e) {
  showClearOrCurrentLocation(this, 'from')
  showClearOrCurrentLocation(this, 'to')

  function showClearOrCurrentLocation (view, name) {
    var selector = '.' + name
    var value = view.find(selector + ' input').value
    var clear_btn = view.find(selector + ' .fa-times')
    var loading_btn = view.find(selector + ' .fa-spin')
    var location_me_btn = view.find(selector + ' .fa-location-arrow')

    if (!value || !value.trim || value.trim().length === 0) {
      clear_btn.classList.add('hidden')
      loading_btn.classList.add('hidden')
      location_me_btn.classList.remove('hidden')
    } else {
      clear_btn.classList.remove('hidden')
      loading_btn.classList.add('hidden')
      location_me_btn.classList.add('hidden')
    }
  }
}

/**
 * Set cursor
 */

function setCursor(node, pos) {
  node = (typeof node === "string" || node instanceof String) ? document.getElementById(node) : node;
  console.log('set cursor');

  if (!node) return;

  if (node.createTextRange) {
    var textRange = node.createTextRange();
    textRange.collapse(true);
    textRange.moveEnd(pos);
    textRange.moveStart(pos);
    textRange.select();
  } else if (node.setSelectionRange) {
    node.setSelectionRange(pos, pos);
  }

  return false;
}<commit_msg>fixed blur input issue for iOS, fixes issue #89<commit_after>var closest = require('closest');
var each = require('each');
var geocode = require('geocode');
var hogan = require('hogan.js');
var log = require('./client/log')('locations-view');
var mouse = require('mouse-position');
var textModal = require('text-modal');
var view = require('view');
var analytics = require('analytics');
var ua = require('user-agent');
var session = require('session');

/**
 * Expose `View`
 */

var View = module.exports = view(require('./template.html'), function(view, plan) {
  view.on('rendered', function() {
    var self = this;
    window.setTimeout(function(){
      self.resetIcons();
    }, 200);

    closest(view.el, 'form').onsubmit = function(e) {
      e.preventDefault();

      plan.setAddresses(view.find('.from input').value, view.find('.to input').value, function(err) {
        if (err) {
          log.error('%e', err);
        } else {
          plan.updateRoutes();
        }
      });

    };
  });
});

/**
 * Address Changed
 */

View.prototype.blurInput = function(e) {
  log('input blurred, saving changes');

  var inputGroup = e.target.parentNode;
  var suggestionList = inputGroup.getElementsByTagName('ul')[0];
  inputGroup.classList.remove('suggestions-open');

  var highlight = this.find('.suggestion.highlight');
  if (highlight) {
    console.log('highlighting');
    e.target.value = highlight.textContent || '';
    if (highlight.dataset.lat) {
      e.target.lat = highlight.dataset.lat;
      e.target.lng = highlight.dataset.lng;
      e.target.address = highlight.addressData;
    }
  }

  suggestionList.classList.add('empty');

  setTimeout(function() {
    suggestionList.innerHTML = '';
  }, 500);

  inputGroup.classList.remove('highlight');
  this.save(e.target);
  //  this.scrollDown(0, 0);
};

/**
 * Keypress
 */

View.prototype.keydownInput = function(e) {
  var el = e.target;
  var key = e.keyCode;

  // Currently highlighted suggestion
  var highlightedSuggestion = this.find('.suggestion.highlight');

  switch (key) {
    case 13: // enter key
      console.log('enter key');
      e.preventDefault();
      el.blur();
      this.blurInput(e);
      break;
    case 38: // up key
    case 40: // down key
      if (key === 38) {
        this.pressUp(highlightedSuggestion, el);
      } else {
        this.pressDown(highlightedSuggestion, el);
      }

      var newHighlight = this.find('.suggestion.highlight');
      if (newHighlight) el.value = newHighlight.textContent || '';
      break;
  }
};

/**
 * Press Up
 */

View.prototype.pressUp = function(highlightedSuggestion, el) {
  if (highlightedSuggestion) {
    var aboveHighlightedSuggestion = highlightedSuggestion.previousElementSibling;

    if (aboveHighlightedSuggestion) {
      aboveHighlightedSuggestion.classList.add('highlight');
    } else {
      el.value = this.currentLocation || '';
      setCursor(el, el.value.length);
    }
    highlightedSuggestion.classList.remove('highlight');
  }
};

/**
 * Press Down
 */

View.prototype.pressDown = function(highlightedSuggestion, el) {
  if (!highlightedSuggestion) {
    var suggestion = this.find('.suggestion');
    if (suggestion) suggestion.classList.add('highlight');
  } else if (highlightedSuggestion.nextElementSibling) {
    highlightedSuggestion.nextElementSibling.classList.add('highlight');
    highlightedSuggestion.classList.remove('highlight');
  }
};

/**
 * Geocode && Save
 */

View.prototype.save = function(el) {
  var plan = this.model;
  var name = el.name;
  var val = el.value;

  if (!val || plan[name]() === val) return;

  if (el.lat) {
    this.model.setAddress(name, el.lng + ',' + el.lat, function(err, location) {

      if (err) {
        log.error('%e', err);
        analytics.send_ga({
          category: 'geocoder',
          action: 'change address invalid',
          label: val,
          value: 0
        });

        textModal('Invalid address.');

      } else if (location && plan.validCoordinates()) {

        analytics.send_ga({
          category: 'geocoder',
          action: 'change address success',
          label: val,
          value: 0
        });

        plan.updateRoutes();

      } else {
        console.log("no ejecuta nada");
      }
    }, el.address);
  } else {

    this.model.setAddress(name, val, function(err, location) {
      if (err) {
        log.error('%e', err);
        analytics.send_ga({
          category: 'geocoder',
          action: 'change address invalid',
          label: val,
          value: 0
        });

        textModal('Invalid address.');
      } else if (location && plan.validCoordinates()) {
        analytics.send_ga({
          category: 'geocoder',
          action: 'change address success',
          label: val,
          value: 0
        });
        plan.updateRoutes();

      }
    });
  }
  this.resetIcons();
};

/**
 * Scroll down a certain number of pixels
 */

View.prototype.scrollDown = function(num, duration) {
  duration = duration || 200;
  console.log('scroll down', num)
  $('.fullscreen').animate({
    scrollTop: num
  }, duration);
};

/**
 * Highlight the selected input
 */

View.prototype.focusInput = function(e) {
  var $wrapper = $('.fullscreen');
  var offsetTop = $wrapper.scrollTop() + $(e.target).offset().top;
  console.log($wrapper.scrollTop(), offsetTop, e.target);
  if (!!e && e.scrollIntoView) {
    e.target.scrollIntoView()
    $(e.target).blur()
    $(e.target).focus()
  }
  if (ua.os.name === 'Android' && ua.browser.name === 'Chrome') {
    this.scrollDown(offsetTop - 20);
  }
  e.target.parentNode.classList.add('highlight');
};

/**
 * Suggestions Template
 */

var suggestionsTemplate = hogan.compile(require('./suggestions.html'));
var suggestionTimeout;

function getAddress(s) {
  var city = '';
  if (s.city)
    city = s.city;
  else if (s.town)
    city = s.town;
  else if (s.village)
    city = s.village;
  else if (s.hamlet)
    city = s.hamlet;

  var street = '';
  if (s.road)
    street = s.road;
  else if (s.pedestrian)
    street = s.pedestrian;
  else if (s.footway)
    street = s.footway;
  else if (s.industrial)
    street = s.industrial;
  else if (s.cycleway)
    street = s.cycleway;

  var number = '';
  if (s.house_number)
    number = s.house_number;
  else if (s.parking)
    number = s.parking;

  var place = '';
  if (s.aerodrome)
    place = s.aerodrome + ', ' + city;
  else if (s.stadium)
    place = s.stadium + ', ' + city;
  else if (s.school)
    place = s.school + ', ' + city;
  else if (s.museum)
    place = s.museum + ', ' + city;
  else if (s.restaurant)
    place = s.restaurant + ', ' + street + ', ' + city;
  else if (s.cafe)
    place = s.cafe + ', ' + street + ', ' + city;
  else if (s.pub)
    place = s.pub + ', ' + street + ', ' + city;
  else if (s.bar)
    place = s.bar + ', ' + street + ', ' + city;
  else if (s.fast_food)
    place = s.fast_food + ', ' + street + ', ' + city;
  else if (s.place_of_worship)
    place = s.place_of_worship + ', ' + street + ', ' + city;

  if (place.length > 0)
    return place;
  else
    return $.grep([number, street, city, s.state], Boolean).join(", ")
}

/**
 * Suggest
 */

View.prototype.suggest = function(e) {
  var input = e.target;
  var text = input.value || '';
  var name = input.name;
  var inputGroup = input.parentNode;
  var suggestionList = inputGroup.getElementsByTagName('ul')[0];
  var view = this;
  var suggestionsData = [];

  this.resetIcons();

  var resultsCallbackAmigo = function(err, suggestions) {

    if (err) {
      log.error('%e', err);
    } else {
      if (suggestions && suggestions.length > 0) {
        var filter_label = {};
        for (var i = 0; i < suggestions.length; i++) {

          var item_suggestions = suggestions[i].properties;

          if (item_suggestions.country_a == "USA" && item_suggestions.region_a == "CA") {

            var item_geometry = suggestions[i].geometry;
            var suggestion_obj = {
              "index": i,
              "text": item_suggestions.label,
              "lat": item_geometry.coordinates[1],
              "lon": item_geometry.coordinates[0],
              "magicKey": ""
            };

            if (filter_label[item_suggestions.label] === undefined) {
              filter_label[item_suggestions.label] = true;
              suggestionsData.push(suggestion_obj);
            }

          }

        }

        suggestionsData = suggestionsData.slice(0, 8);
        suggestionList.innerHTML = suggestionsTemplate.render({
          suggestions: suggestionsData
        });
        /*******************/
        each(view.findAll('.suggestion'), function(li) {
          li.addressData = suggestions[li.dataset.index];

          li.onmouseover = function(e) {
            li.classList.add('highlight');
          };

          li.onmouseout = function(e) {
            li.classList.remove('highlight');
          };
        });

        suggestionList.classList.remove('empty');
        inputGroup.classList.add('suggestions-open');
        /*******************/
      } else {
        suggestionList.classList.add('empty');
        inputGroup.classList.remove('suggestions-open');
      }
    }
  };

  var resultsCallback = function(err, suggestions) {

    if (err) {
      log.error('%e', err);
    } else {
      if (suggestions && suggestions.length > 0) {

        for (var i = 0; i < suggestions.length; i++) {
          if (!suggestions[i].text) {
            if (suggestions[i].address) {
              suggestions[i].text = getAddress(suggestions[i].address);
            } else {
              suggestions[i].text = suggestions[i].display_name;
            }
          }
          suggestions[i].index = i;
        }
        suggestions = suggestions.slice(0, 5);

        suggestionList.innerHTML = suggestionsTemplate.render({
          suggestions: suggestions
        });

        each(view.findAll('.suggestion'), function(li) {
          li.addressData = suggestions[li.dataset.index];

          li.onmouseover = function(e) {
            li.classList.add('highlight');
          };

          li.onmouseout = function(e) {
            li.classList.remove('highlight');
          };
        });

        suggestionList.classList.remove('empty');
        inputGroup.classList.add('suggestions-open');
      } else {
        suggestionList.classList.add('empty');
        inputGroup.classList.remove('suggestions-open');
      }
    }
  };

  // If the text is too short or does not contain a space yet, return
  if (text.length < 3) return;

  // Get a suggestion!
  if (suggestionTimeout !== undefined) {
    clearTimeout(suggestionTimeout);
  }
  suggestionTimeout = setTimeout(function() {
    console.log('timeout trigger')
    geocode.suggestAmigo(text, resultsCallbackAmigo);
  }, 50);
};

/**
 * Clear
 */

View.prototype.clear = function(e) {
  e.preventDefault();
  var inputGroup = e.target.parentNode;
  var input = inputGroup.getElementsByTagName('input')[0];
  input.value = '';
  this.resetIcons();
  input.focus();
};

View.prototype.locateMe = function(e) {
  e.preventDefault();
  var self = this;
  var inputGroup = e.target.parentNode;
  var input = inputGroup.getElementsByTagName('input')[0];

  this.resetIcons();
  if (navigator.geolocation) {

    var clear_btn = inputGroup.querySelector('.fa-times')
    var loading_btn = inputGroup.querySelector('.fa-spin')
    var location_me_btn = inputGroup.querySelector('.fa-location-arrow')
    clear_btn.classList.add('hidden')
    loading_btn.classList.remove('hidden')
    location_me_btn.classList.add('hidden')

    navigator.geolocation.getCurrentPosition(function(position) {
      var plan = session.plan();
      var target = input.id.indexOf('from') !== -1 ? 'from' : 'to';

      plan.setAddress(target, position.coords.longitude + ',' + position.coords.latitude, function(err, rees) {
        plan.updateRoutes();
        self.resetIcons();
      });
    }, null, {
      enableHighAccuracy: true,
      maximumAge: 10000,
      timeout: 30000
    });
  } else {
    this.resetIcons();
  }
}

View.prototype.resetIcons = function (e) {
  showClearOrCurrentLocation(this, 'from')
  showClearOrCurrentLocation(this, 'to')

  function showClearOrCurrentLocation (view, name) {
    var selector = '.' + name
    var value = view.find(selector + ' input').value
    var clear_btn = view.find(selector + ' .fa-times')
    var loading_btn = view.find(selector + ' .fa-spin')
    var location_me_btn = view.find(selector + ' .fa-location-arrow')
    if (!value || !value.trim || value.trim().length === 0) {
      clear_btn.classList.add('hidden')
      loading_btn.classList.add('hidden')
      location_me_btn.classList.remove('hidden')
    } else {
      clear_btn.classList.remove('hidden')
      loading_btn.classList.add('hidden')
      location_me_btn.classList.add('hidden')
    }
  }
}

/**
 * Set cursor
 */

function setCursor(node, pos) {
  node = (typeof node === "string" || node instanceof String) ? document.getElementById(node) : node;
  console.log('set cursor');

  if (!node) return;

  if (node.createTextRange) {
    var textRange = node.createTextRange();
    textRange.collapse(true);
    textRange.moveEnd(pos);
    textRange.moveStart(pos);
    textRange.select();
  } else if (node.setSelectionRange) {
    node.setSelectionRange(pos, pos);
  }

  return false;
}<|endoftext|>


<commit_before>angular.module( 'app' )
.controller( 'ApplicationCtrl', function( $scope, UserSvc ) {
    $scope.$on( 'login', function( _, user ) {
        $scope.currentUser = user
    })
    $scope.logout = function() {
        if ($scope.currentUser) {
            delete $scope.currentUser
            UserSvc.removeToken()
        }
    }
})<commit_msg>Find existing user and display logged in views<commit_after>angular.module( 'app' )
.controller( 'ApplicationCtrl', function( $scope, UserSvc, jwtHelper ) {
    $scope.$on( 'login', function( _, user ) {
        $scope.currentUser = user
    })
    if (window.localStorage.token) {
        $scope.$emit( 'login', jwtHelper.decodeToken(window.localStorage.token) )
        UserSvc.getUser()
    }
    $scope.logout = function() {
        if ($scope.currentUser) {
            delete $scope.currentUser
            UserSvc.removeToken()
        }
    }
})<|endoftext|>


<commit_before>
function Hero(game, x, y) {
    Phaser.Sprite.call(this, game, x, y, 'hero');
    this.anchor.set(0.5, 0.5);
    this.game.physics.enable(this);
    this.body.collideWorldBounds = true;
    this.animations.add('stop', [0]);
    this.animations.add('run', [1, 2], 8, true); // 8fps looped
    this.animations.add('jump', [3]);
    this.animations.add('fall', [4]);
}
Hero.prototype = Object.create(Phaser.Sprite.prototype);
Hero.prototype.constructor = Hero;
Hero.prototype.move = function (direction) {
    const SPEED = 1000;
    this.body.velocity.x = direction * SPEED;
    if (this.body.velocity.x < 0) {
        this.scale.x = -1;
    }
    else if (this.body.velocity.x > 0) {
        this.scale.x = 1;
    }
};
Hero.prototype.jump = function () {
    const JUMP_SPEED = 650;
    let canJump = this.body.touching.down;
    if (canJump) {
        this.body.velocity.y = -JUMP_SPEED;
    }
    return canJump;
};
Hero.prototype.bounce = function () {
    const BOUNCE_SPEED = 500;
    this.body.velocity.y = -BOUNCE_SPEED;
};
Hero.prototype.update = function () {
    let animationName = this._getAnimationName();
    if (this.animations.name !== animationName) {
        this.animations.play(animationName);
    }
};
Hero.prototype._getAnimationName = function () {
    let name = 'stop';
    if (this.body.velocity.y < 0) {
        name = 'jump';
    }
    else if (this.body.velocity.y >= 0 && !this.body.touching.down) {
        name = 'fall';
    }
    else if (this.body.velocity.x !== 0 && this.body.touching.down) {
        name = 'run';
    }
    return name;
};
function Spider(game, x, y) {
    Phaser.Sprite.call(this, game, x, y, 'spider');

    this.anchor.set(0.5);
    this.animations.add('crawl', [0, 1, 2], 8, true);
    this.animations.add('die', [0, 4, 0, 4, 0, 4, 3, 3, 3, 3, 3, 3], 12);
    this.animations.play('crawl');
    this.game.physics.enable(this);
    this.body.collideWorldBounds = true;
    this.body.velocity.x = Spider.SPEED;
}
Spider.SPEED = 200;
Spider.prototype = Object.create(Phaser.Sprite.prototype);
Spider.prototype.constructor = Spider;
Spider.prototype.update = function () {
    if (this.body.touching.right || this.body.blocked.right) {
        this.body.velocity.x = -Spider.SPEED;
    }
    else if (this.body.touching.left || this.body.blocked.left) {
        this.body.velocity.x = Spider.SPEED
    }
};
Spider.prototype.die = function () {
    this.body.enable = false;
    this.animations.play('die').onComplete.addOnce(function () {
        this.kill();
    }, this);
};
PlayState = {};
const LEVEL_COUNT = 2;
PlayState.init = function (data) {
    this.game.renderer.renderSession.roundPixels = true;
    this.keys = this.game.input.keyboard.addKeys({
        left: Phaser.KeyCode.LEFT,
        right: Phaser.KeyCode.RIGHT,
        up: Phaser.KeyCode.UP
    });
    this.keys.up.onDown.add(function () {
        let didJump = this.hero.jump();
        if (didJump) {
            this.sfx.jump.play();
        }
    }, this);
    this.coinPickupCount = 0;
    this.hasKey = false;
    this.level = (data.level || 0) % LEVEL_COUNT;
};
PlayState.preload = function () {
    this.game.load.json('level:0', 'data/level00.json');
    this.game.load.json('level:1', 'data/level01.json');
    this.game.load.image('font:numbers', 'images/numbers.png');
    this.game.load.image('background', 'images/background.png');
    this.game.load.image('ground', 'images/ground.png');
    this.game.load.image('grass:8x1', 'images/grass_8x1.png');
    this.game.load.image('grass:6x1', 'images/grass_6x1.png');
    this.game.load.image('grass:4x1', 'images/grass_4x1.png');
    this.game.load.image('grass:2x1', 'images/grass_2x1.png');
    this.game.load.image('grass:1x1', 'images/grass_1x1.png');
    this.game.load.image('invisible-wall', 'images/invisible_wall.png');
    this.game.load.image('icon:coin', 'images/coin_icon.png');
    this.game.load.image('key', 'images/key.png');
    this.game.load.spritesheet('coin', 'images/coin_animated.png', 22, 22);
    this.game.load.spritesheet('spider', 'images/Crab.png', 42, 32);
    this.game.load.spritesheet('hero', 'images/flashway.png', 36, 42);
    this.game.load.spritesheet('door', 'images/door.png', 42, 66);
    this.game.load.spritesheet('icon:key', 'images/key_icon.png', 34, 30);
    this.game.load.audio('sfx:jump', 'audio/jump.wav');
    this.game.load.audio('sfx:coin', 'audio/coin.wav');
    this.game.load.audio('sfx:stomp', 'audio/stomp.wav');
    this.game.load.audio('sfx:key', 'audio/key.wav');
    this.game.load.audio('sfx:door', 'audio/door.wav');
};
PlayState.create = function () {
    this.sfx = {
        jump: this.game.add.audio('sfx:jump'),
        coin: this.game.add.audio('sfx:coin'),
        stomp: this.game.add.audio('sfx:stomp'),
        key: this.game.add.audio('sfx:key'),
        door: this.game.add.audio('sfx:door')
    };
    this.game.add.image(0, 0, 'background');
    this._loadLevel(this.game.cache.getJSON(`level:${this.level}`));
    this._createHud();
};
PlayState.update = function () {
    this._handleCollisions();
    this._handleInput();
    this.coinFont.text = `x${this.coinPickupCount}`;
    this.keyIcon.frame = this.hasKey ? 1 : 0;
};
PlayState._handleCollisions = function () {
    this.game.physics.arcade.collide(this.spiders, this.platforms);
    this.game.physics.arcade.collide(this.spiders, this.enemyWalls);
    this.game.physics.arcade.collide(this.hero, this.platforms);
    this.game.physics.arcade.overlap(this.hero, this.coins, this._onHeroVsCoin,
        null, this);
    this.game.physics.arcade.overlap(this.hero, this.spiders,
        this._onHeroVsEnemy, null, this);
    this.game.physics.arcade.overlap(this.hero, this.key, this._onHeroVsKey,
        null, this);
    this.game.physics.arcade.overlap(this.hero, this.door, this._onHeroVsDoor,
        function (hero, door) {
            return this.hasKey && hero.body.touching.down;
        }, this);
};
PlayState._handleInput = function () {
    if (this.keys.left.isDown) {
        this.hero.move(-1);
    }
    else if (this.keys.right.isDown) {
        this.hero.move(1);
    }
    else {
        this.hero.move(0);
    }
};
PlayState._loadLevel = function (data) {
    this.bgDecoration = this.game.add.group();
    this.platforms = this.game.add.group();
    this.coins = this.game.add.group();
    this.spiders = this.game.add.group();
    this.enemyWalls = this.game.add.group();
    this.enemyWalls.visible = false;
    data.platforms.forEach(this._spawnPlatform, this);

    this._spawnCharacters({hero: data.hero, spiders: data.spiders});
    data.coins.forEach(this._spawnCoin, this);
    this._spawnDoor(data.door.x, data.door.y);
    this._spawnKey(data.key.x, data.key.y);
    const GRAVITY = 5000;
    this.game.physics.arcade.gravity.y = GRAVITY;
};
PlayState._spawnPlatform = function (platform) {
    let sprite = this.platforms.create(
        platform.x, platform.y, platform.image);
    this.game.physics.enable(sprite);
    sprite.body.allowGravity = false;
    sprite.body.immovable = true;
    this._spawnEnemyWall(platform.x, platform.y, 'left');
    this._spawnEnemyWall(platform.x + sprite.width, platform.y, 'right');
};
PlayState._spawnEnemyWall = function (x, y, side) {
    let sprite = this.enemyWalls.create(x, y, 'invisible-wall');
    // anchor and y displacement
    sprite.anchor.set(side === 'left' ? 1 : 0, 1);
    // physic properties
    this.game.physics.enable(sprite);
    sprite.body.immovable = true;
    sprite.body.allowGravity = false;
};
PlayState._spawnCharacters = function (data) {
    // spawn spiders
    data.spiders.forEach(function (spider) {
        let sprite = new Spider(this.game, spider.x, spider.y);
        this.spiders.add(sprite);
    }, this);
    // spawn hero
    this.hero = new Hero(this.game, data.hero.x, data.hero.y);
    this.game.add.existing(this.hero);
};
PlayState._spawnCoin = function (coin) {
    let sprite = this.coins.create(coin.x, coin.y, 'coin');
    sprite.anchor.set(0.5, 0.5);
    this.game.physics.enable(sprite);
    sprite.body.allowGravity = false;
    sprite.animations.add('rotate', [0, 1, 2, 1], 6, true); // 6fps, looped
    sprite.animations.play('rotate');
};
PlayState._spawnDoor = function (x, y) {
    this.door = this.bgDecoration.create(x, y, 'door');
    this.door.anchor.setTo(0.5, 1);
    this.game.physics.enable(this.door);
    this.door.body.allowGravity = false;
};
PlayState._spawnKey = function (x, y) {
    this.key = this.bgDecoration.create(x, y, 'key');
    this.key.anchor.set(0.5, 0.5);
    // enable physics to detect collisions, so the hero can pick the key up
    this.game.physics.enable(this.key);
    this.key.body.allowGravity = false;
    // add a small 'up & down' animation via a tween
    this.key.y -= 3;
    this.game.add.tween(this.key)
        .to({y: this.key.y + 6}, 800, Phaser.Easing.Sinusoidal.InOut)
        .yoyo(true)
        .loop()
        .start();
};
PlayState._onHeroVsCoin = function (hero, coin) {
    this.sfx.coin.play();
    coin.kill();
    this.coinPickupCount++;
};
PlayState._onHeroVsEnemy = function (hero, enemy) {
    if (hero.body.velocity.y > 0) { // kill enemies when hero is falling
        hero.bounce();
        enemy.die();
        this.sfx.stomp.play();
    }
    else { // game over -> restart the game
        this.sfx.stomp.play();
        this.game.state.restart(true, false, {level: this.level});
    }
};
PlayState._onHeroVsKey = function (hero, key) {
    this.sfx.key.play();
    key.kill();
    this.hasKey = true;
};
PlayState._onHeroVsDoor = function (hero, door) {
    this.sfx.door.play();
    this.game.state.restart(true, false, { level: this.level + 1 });
};
PlayState._createHud = function () {
    const NUMBERS_STR = '0123456789X ';
    this.coinFont = this.game.add.retroFont('font:numbers', 20, 26,
        NUMBERS_STR);
    this.keyIcon = this.game.make.image(0, 19, 'icon:key');
    this.keyIcon.anchor.set(0, 0.5);
    let coinIcon = this.game.make.image(this.keyIcon.width + 7, 0, 'icon:coin');
    let coinScoreImg = this.game.make.image(coinIcon.x + coinIcon.width,
        coinIcon.height / 2, this.coinFont);
    coinScoreImg.anchor.set(0, 0.5);
    this.hud = this.game.add.group();
    this.hud.add(coinIcon);
    this.hud.add(coinScoreImg);
    this.hud.add(this.keyIcon);
    this.hud.position.set(10, 10);
};
// =============================================================================
// entry point
// =============================================================================
window.onload = function () {
    let game = new Phaser.Game(960, 600, Phaser.AUTO, 'game');
    game.state.add('play', PlayState);
    game.state.start('play', true, false, {level: 0});
};<commit_msg>Changed everything<commit_after>
function Hero(game, x, y) {
    Phaser.Sprite.call(this, game, x, y, 'hero');
    this.anchor.set(0.5, 0.5);
    this.game.physics.enable(this);
    this.body.collideWorldBounds = true;
    this.animations.add('stop', [0]);
    this.animations.add('run', [1, 2], 8, true); // 8fps looped
    this.animations.add('jump', [3]);
    this.animations.add('fall', [4]);
}
Hero.prototype = Object.create(Phaser.Sprite.prototype);
Hero.prototype.constructor = Hero;
Hero.prototype.move = function (direction) {
    const SPEED = 1000;
    this.body.velocity.x = direction * SPEED;
    if (this.body.velocity.x < 0) {
        this.scale.x = -1;
    }
    else if (this.body.velocity.x > 0) {
        this.scale.x = 1;
    }
};
Hero.prototype.jump = function () {
    const JUMP_SPEED = 5000;
    let canJump = this.body.touching.down;
    if (canJump) {
        this.body.velocity.y = -JUMP_SPEED;
    }
    return canJump;
};
Hero.prototype.bounce = function () {
    const BOUNCE_SPEED = 500;
    this.body.velocity.y = -BOUNCE_SPEED;
};
Hero.prototype.update = function () {
    let animationName = this._getAnimationName();
    if (this.animations.name !== animationName) {
        this.animations.play(animationName);
    }
};
Hero.prototype._getAnimationName = function () {
    let name = 'stop';
    if (this.body.velocity.y < 0) {
        name = 'jump';
    }
    else if (this.body.velocity.y >= 0 && !this.body.touching.down) {
        name = 'fall';
    }
    else if (this.body.velocity.x !== 0 && this.body.touching.down) {
        name = 'run';
    }
    return name;
};
function Spider(game, x, y) {
    Phaser.Sprite.call(this, game, x, y, 'spider');

    this.anchor.set(0.5);
    this.animations.add('crawl', [0, 1, 2], 8, true);
    this.animations.add('die', [0, 4, 0, 4, 0, 4, 3, 3, 3, 3, 3, 3], 12);
    this.animations.play('crawl');
    this.game.physics.enable(this);
    this.body.collideWorldBounds = true;
    this.body.velocity.x = Spider.SPEED;
}
Spider.SPEED = 200;
Spider.prototype = Object.create(Phaser.Sprite.prototype);
Spider.prototype.constructor = Spider;
Spider.prototype.update = function () {
    if (this.body.touching.right || this.body.blocked.right) {
        this.body.velocity.x = -Spider.SPEED;
    }
    else if (this.body.touching.left || this.body.blocked.left) {
        this.body.velocity.x = Spider.SPEED
    }
};
Spider.prototype.die = function () {
    this.body.enable = false;
    this.animations.play('die').onComplete.addOnce(function () {
        this.kill();
    }, this);
};
PlayState = {};
const LEVEL_COUNT = 2;
PlayState.init = function (data) {
    this.game.renderer.renderSession.roundPixels = true;
    this.keys = this.game.input.keyboard.addKeys({
        left: Phaser.KeyCode.LEFT,
        right: Phaser.KeyCode.RIGHT,
        up: Phaser.KeyCode.UP
    });
    this.keys.up.onDown.add(function () {
        let didJump = this.hero.jump();
        if (didJump) {
            this.sfx.jump.play();
        }
    }, this);
    this.coinPickupCount = 0;
    this.hasKey = false;
    this.level = (data.level || 0) % LEVEL_COUNT;
};
PlayState.preload = function () {
    this.game.load.json('level:0', 'data/level00.json');
    this.game.load.json('level:1', 'data/level01.json');
    this.game.load.image('font:numbers', 'images/numbers.png');
    this.game.load.image('background', 'images/background.png');
    this.game.load.image('ground', 'images/ground.png');
    this.game.load.image('grass:8x1', 'images/grass_8x1.png');
    this.game.load.image('grass:6x1', 'images/grass_6x1.png');
    this.game.load.image('grass:4x1', 'images/grass_4x1.png');
    this.game.load.image('grass:2x1', 'images/grass_2x1.png');
    this.game.load.image('grass:1x1', 'images/grass_1x1.png');
    this.game.load.image('invisible-wall', 'images/invisible_wall.png');
    this.game.load.image('icon:coin', 'images/coin_icon.png');
    this.game.load.image('key', 'images/key.png');
    this.game.load.spritesheet('coin', 'images/coin_animated.png', 22, 22);
    this.game.load.spritesheet('spider', 'images/Crab.png', 42, 32);
    this.game.load.spritesheet('hero', 'images/flashway.png', 36, 42);
    this.game.load.spritesheet('door', 'images/door.png', 42, 66);
    this.game.load.spritesheet('icon:key', 'images/key_icon.png', 34, 30);
    this.game.load.audio('sfx:jump', 'audio/jump.wav');
    this.game.load.audio('sfx:coin', 'audio/coin.wav');
    this.game.load.audio('sfx:stomp', 'audio/stomp.wav');
    this.game.load.audio('sfx:key', 'audio/key.wav');
    this.game.load.audio('sfx:door', 'audio/door.wav');
};
PlayState.create = function () {
    this.sfx = {
        jump: this.game.add.audio('sfx:jump'),
        coin: this.game.add.audio('sfx:coin'),
        stomp: this.game.add.audio('sfx:stomp'),
        key: this.game.add.audio('sfx:key'),
        door: this.game.add.audio('sfx:door')
    };
    this.game.add.image(0, 0, 'background');
    this._loadLevel(this.game.cache.getJSON(`level:${this.level}`));
    this._createHud();
};
PlayState.update = function () {
    this._handleCollisions();
    this._handleInput();
    this.coinFont.text = `x${this.coinPickupCount}`;
    this.keyIcon.frame = this.hasKey ? 1 : 0;
};
PlayState._handleCollisions = function () {
    this.game.physics.arcade.collide(this.spiders, this.platforms);
    this.game.physics.arcade.collide(this.spiders, this.enemyWalls);
    this.game.physics.arcade.collide(this.hero, this.platforms);
    this.game.physics.arcade.overlap(this.hero, this.coins, this._onHeroVsCoin,
        null, this);
    this.game.physics.arcade.overlap(this.hero, this.spiders,
        this._onHeroVsEnemy, null, this);
    this.game.physics.arcade.overlap(this.hero, this.key, this._onHeroVsKey,
        null, this);
    this.game.physics.arcade.overlap(this.hero, this.door, this._onHeroVsDoor,
        function (hero, door) {
            return this.hasKey && hero.body.touching.down;
        }, this);
};
PlayState._handleInput = function () {
    if (this.keys.left.isDown) {
        this.hero.move(-1);
    }
    else if (this.keys.right.isDown) {
        this.hero.move(1);
    }
    else {
        this.hero.move(0);
    }
};
PlayState._loadLevel = function (data) {
    this.bgDecoration = this.game.add.group();
    this.platforms = this.game.add.group();
    this.coins = this.game.add.group();
    this.spiders = this.game.add.group();
    this.enemyWalls = this.game.add.group();
    this.enemyWalls.visible = false;
    data.platforms.forEach(this._spawnPlatform, this);

    this._spawnCharacters({hero: data.hero, spiders: data.spiders});
    data.coins.forEach(this._spawnCoin, this);
    this._spawnDoor(data.door.x, data.door.y);
    this._spawnKey(data.key.x, data.key.y);
    const GRAVITY = 5000;
    this.game.physics.arcade.gravity.y = GRAVITY;
};
PlayState._spawnPlatform = function (platform) {
    let sprite = this.platforms.create(
        platform.x, platform.y, platform.image);
    this.game.physics.enable(sprite);
    sprite.body.allowGravity = false;
    sprite.body.immovable = true;
    this._spawnEnemyWall(platform.x, platform.y, 'left');
    this._spawnEnemyWall(platform.x + sprite.width, platform.y, 'right');
};
PlayState._spawnEnemyWall = function (x, y, side) {
    let sprite = this.enemyWalls.create(x, y, 'invisible-wall');
    // anchor and y displacement
    sprite.anchor.set(side === 'left' ? 1 : 0, 1);
    // physic properties
    this.game.physics.enable(sprite);
    sprite.body.immovable = true;
    sprite.body.allowGravity = false;
};
PlayState._spawnCharacters = function (data) {
    // spawn spiders
    data.spiders.forEach(function (spider) {
        let sprite = new Spider(this.game, spider.x, spider.y);
        this.spiders.add(sprite);
    }, this);
    // spawn hero
    this.hero = new Hero(this.game, data.hero.x, data.hero.y);
    this.game.add.existing(this.hero);
};
PlayState._spawnCoin = function (coin) {
    let sprite = this.coins.create(coin.x, coin.y, 'coin');
    sprite.anchor.set(0.5, 0.5);
    this.game.physics.enable(sprite);
    sprite.body.allowGravity = false;
    sprite.animations.add('rotate', [0, 1, 2, 1], 6, true); // 6fps, looped
    sprite.animations.play('rotate');
};
PlayState._spawnDoor = function (x, y) {
    this.door = this.bgDecoration.create(x, y, 'door');
    this.door.anchor.setTo(0.5, 1);
    this.game.physics.enable(this.door);
    this.door.body.allowGravity = false;
};
PlayState._spawnKey = function (x, y) {
    this.key = this.bgDecoration.create(x, y, 'key');
    this.key.anchor.set(0.5, 0.5);
    // enable physics to detect collisions, so the hero can pick the key up
    this.game.physics.enable(this.key);
    this.key.body.allowGravity = false;
    // add a small 'up & down' animation via a tween
    this.key.y -= 3;
    this.game.add.tween(this.key)
        .to({y: this.key.y + 6}, 800, Phaser.Easing.Sinusoidal.InOut)
        .yoyo(true)
        .loop()
        .start();
};
PlayState._onHeroVsCoin = function (hero, coin) {
    this.sfx.coin.play();
    coin.kill();
    this.coinPickupCount++;
};
PlayState._onHeroVsEnemy = function (hero, enemy) {
    if (hero.body.velocity.y > 0) { // kill enemies when hero is falling
        hero.bounce();
        enemy.die();
        this.sfx.stomp.play();
    }
    else { // game over -> restart the game
        this.sfx.stomp.play();
        this.game.state.restart(true, false, {level: this.level});
    }
};
PlayState._onHeroVsKey = function (hero, key) {
    this.sfx.key.play();
    key.kill();
    this.hasKey = true;
};
PlayState._onHeroVsDoor = function (hero, door) {
    this.sfx.door.play();
    this.game.state.restart(true, false, { level: this.level + 1 });
};
PlayState._createHud = function () {
    const NUMBERS_STR = '0123456789X ';
    this.coinFont = this.game.add.retroFont('font:numbers', 20, 26,
        NUMBERS_STR);
    this.keyIcon = this.game.make.image(0, 19, 'icon:key');
    this.keyIcon.anchor.set(0, 0.5);
    let coinIcon = this.game.make.image(this.keyIcon.width + 7, 0, 'icon:coin');
    let coinScoreImg = this.game.make.image(coinIcon.x + coinIcon.width,
        coinIcon.height / 2, this.coinFont);
    coinScoreImg.anchor.set(0, 0.5);
    this.hud = this.game.add.group();
    this.hud.add(coinIcon);
    this.hud.add(coinScoreImg);
    this.hud.add(this.keyIcon);
    this.hud.position.set(10, 10);
};
// =============================================================================
// entry point
// =============================================================================
window.onload = function () {
    let game = new Phaser.Game(960, 600, Phaser.AUTO, 'game');
    game.state.add('play', PlayState);
    game.state.start('play', true, false, {level: 0});
};<|endoftext|>


<commit_before>/*
Input Mask plugin for jquery
http://github.com/RobinHerbots/jquery.inputmask
Copyright (c) 2010 Robin Herbots
Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
Version: 0.0.4

This plugin is based on the masked input plugin written by Josh Bush (digitalbush.com)
*/

(function($) {

    $.fn.inputmask = function(fn, options) {
        //options default
        var defaults = {
            placeholder: "_",
            mask: null,
            onComplete: null,
            repeat: 0, //repetitions of the mask
            definitions: {
                '9': {
                    "validator": "[0-9]",
                    "cardinality": 1,
                    'prevalidator': null
                },
                'a': {
                    "validator": "[A-Za-z]",
                    "cardinality": 1,
                    "prevalidator": null
                },
                '*': {
                    "validator": "[A-Za-z0-9]",
                    "cardinality": 1,
                    "prevalidator": null
                },
                'd': { //day
                    "validator": "0[1-9]|[12][0-9]|3[01]",
                    "cardinality": 2,
                    "prevalidator": [{ "validator": "[0-3]", "cardinality": 1}]
                },
                'm': { //month
                    "validator": "0[1-9]|1[012]",
                    "cardinality": 2,
                    "prevalidator": [{ "validator": "[01]", "cardinality": 1}]
                },
                'y': { //year
                    "validator": "(19|20)\\d\\d",
                    "cardinality": 4,
                    "prevalidator": [
                        { "validator": "[12]", "cardinality": 1 },
                        { "validator": "(19|20)", "cardinality": 2 },
                        { "validator": "(19|20)\\d", "cardinality": 3 }
                        ]
                }
            },
            keyCode: { ALT: 18, BACKSPACE: 8, CAPS_LOCK: 20, COMMA: 188, COMMAND: 91, COMMAND_LEFT: 91, COMMAND_RIGHT: 93, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, MENU: 93, NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108,
                NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38, WINDOWS: 91
            }
        };

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

        if (typeof fn == "string") {
            if (fn == 'mask') {
                //init buffer
                var _buffer = getMaskTemplate();
                var pasteEventName = $.browser.msie ? 'paste' : 'input';
                var iPhone = (window.orientation != undefined);
                var tests = getTestingChain();

                return this.each(function() {
                    mask($(this));
                });
            } else if (fn == 'unmaskedvalue') {
                return unmaskedvalue($(this));
            } else { //maybe fn is a mask so we try
            	//set mask
            	opts.mask = fn;

            	//init buffer
                var _buffer = getMaskTemplate();
                var pasteEventName = $.browser.msie ? 'paste' : 'input';
                var iPhone = (window.orientation != undefined);
                var tests = getTestingChain();

                return this.each(function() {
                    mask($(this));
                });
            }
        } if (typeof fn == "object") {
        		opts = $.extend({}, defaults, fn);

        		//init buffer
                var _buffer = getMaskTemplate();
                var pasteEventName = $.browser.msie ? 'paste' : 'input';
                var iPhone = (window.orientation != undefined);
                var tests = getTestingChain();

                return this.each(function() {
                    mask($(this));
                });
        }

        //functions
        function getMaskTemplate() {
            var singleMask = $.map(opts.mask.split(""), function(element, index) {
                var outElem = [];
                var maskdef = opts.definitions[element];
                if (maskdef) {
                    for (i = 0; i < maskdef.cardinality; i++) {
                        outElem.push(opts.placeholder);
                    }
                } else outElem.push(element);

                return outElem;
            });

            var repeatedMask = singleMask.slice();
				for(var i = 0; i < opts.repeat; i++){
					repeatedMask = repeatedMask.concat(singleMask.slice());
				}
			return repeatedMask;
        };

        function getTestingChain() {
            return $.map(opts.mask.split(""), function(element, index) {
                var outElem = [];
                var maskdef = opts.definitions[element];
                if (maskdef) {
                    for (i = 1; i < maskdef.cardinality; i++) {
                        var prevalidator = maskdef.prevalidator[i - 1];
                        outElem.push([new RegExp(prevalidator.validator), prevalidator.cardinality]);
                    }
                    outElem.push([new RegExp(maskdef.validator), maskdef.cardinality]);
                } else outElem.push(null);

                return outElem;
            });
        };

        function unmaskedvalue(el) {
            var tests = el.data('tests');
            if (tests) {
                return $.map(el.val().split(""), function(element, index) {
                    return tests[index] ? element : null;
                }).join('');
            }
            else {
                return el.val();
            }
        }

        function mask(el) {
            var input = $(el);
            //store tests in the input element - used to get the unmasked value
            input.data('tests', tests);

            //init buffer
            var buffer = _buffer.slice();
            var undoBuffer = input.val();
            var ignore = false;              //Variable for ignoring control keys
            var len = _buffer.length;

            //bind events
            if (!input.attr("readonly")) {
                input.bind("focus", function() {
                    input.addClass('focus');
                    undoBuffer = input.val();
                    var pos = checkVal();
                    writeBuffer();
                    setTimeout(function() {
                        if (pos == _buffer.length)
                            caret(input, 0, pos);
                        else
                            caret(input, pos);
                    }, 0);
                }).bind("mouseenter", function() {
                    if (!input.hasClass('focus') && input.val().length == 0)
                        writeBuffer();
                }).bind("blur", function() {
                    input.removeClass('focus');
                    if (input.val() == _buffer.join('')) {
                        input.val('');
                    } else {
                        checkVal();
                        if (input.val() != undoBuffer)
                            input.change();
                    }
                }).bind("mouseleave", function() {
                    if (!input.hasClass('focus') && input.val() == _buffer.join(''))
                        input.val('');
                }).bind("keydown", keydownEvent
                ).bind("keypress", keypressEvent
                ).bind(pasteEventName, function() {
                    setTimeout(function() { caret(input, checkVal(true)); }, 0);
                });

            }

            checkVal();

            //private functions
            function writeBuffer() { return input.val(buffer.join('')).val(); };
            function clearBuffer(start, end) {
                for (var i = start; i < end && i < len; i++) {
                    buffer[i] = _buffer[i];
                }
            };

            function seekNext(pos) {
                while (++pos <= len && !isMask(pos));
                return pos;
            };

            function shiftL(pos) {
                while (!isMask(pos) && --pos >= 0);
                for (var i = pos; i < len; i++) {
                    if (isMask(i)) {
                        buffer[i] = opts.placeholder;
                        var j = seekNext(i);
                        if (j < len && isValid(i, buffer[j])) {
                            buffer[i] = buffer[j];
                        } else
                            break;
                    }
                }
                writeBuffer();
                caret(input, pos);
            };

            function shiftR(pos) {
                for (var i = pos, c = opts.placeholder; i < len; i++) {
                    if (isMask(i)) {
                        var j = seekNext(i);
                        var t = buffer[i];
                        buffer[i] = c;
                        if (j < len && isValid(j, t))
                            c = t;
                        else
                            break;
                    }
                }
            };

            function caret(input, begin, end) {
                if (input.length == 0) return;
                if (typeof begin == 'number') {
                    end = (typeof end == 'number') ? end : begin;
                    return input.each(function() {
                        if (this.setSelectionRange) {
                            this.focus();
                            this.setSelectionRange(begin, end);
                        } else if (this.createTextRange) {
                            var range = this.createTextRange();
                            range.collapse(true);
                            range.moveEnd('character', end);
                            range.moveStart('character', begin);
                            range.select();
                        }
                    });
                } else {
                    if (input[0].setSelectionRange) {
                        begin = input[0].selectionStart;
                        end = input[0].selectionEnd;
                    } else if (document.selection && document.selection.createRange) {
                        var range = document.selection.createRange();
                        begin = 0 - range.duplicate().moveStart('character', -100000);
                        end = begin + range.text.length;
                    }
                    return { begin: begin, end: end };
                }
            };

            function keydownEvent(e) {
                var pos = caret($(this));
                var k = e.keyCode;
                ignore = (k < 16 || (k > 16 && k < 32) || (k > 32 && k < 41));

                //delete selection before proceeding
                if ((pos.begin - pos.end) != 0 && (!ignore || k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE))
                    clearBuffer(pos.begin, pos.end);

                //backspace, delete, and escape get special treatment
                if (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE || (iPhone && k == 127)) {//backspace/delete
                    shiftL(pos.begin + (k == opts.keyCode.DELETE ? 0 : -1));
                    return false;
                } else if (k == opts.keyCode.ESCAPE) {//escape
                    input.val(undoBuffer);
                    caret(input, 0, checkVal());
                    return false;
                }
            }

            function keypressEvent(e) {
                if (ignore) {
                    ignore = false;
                    //Fixes Mac FF bug on backspace
                    return (e.keyCode == 8) ? false : null;
                }
                e = e || window.event;
                var k = e.charCode || e.keyCode || e.which;
                var pos = caret($(this));

                if (e.ctrlKey || e.altKey || e.metaKey) {//Ignore
                    return true;
                } else if ((k >= 32 && k <= 125) || k > 186) {//typeable characters
                    var p = seekNext(pos.begin - 1);
                    if (p < len) {
                        var c = String.fromCharCode(k);
                        if (isValid(p, c)) {
                            shiftR(p);
                            buffer[p] = c;
                            writeBuffer();
                            var next = seekNext(p);
                            caret($(this), next);
                            if (opts.onComplete && next == len)
                                opts.onComplete.call(input);
                        }
                    }
                }
                return false;
            }

            function isValid(pos, c) {
                var testPos = determineTestPosition(pos);

                var loopend = 0;
                if (c) { loopend = 1; ; }

                var chrs = '';
                for (var i = tests[testPos][1]; i > loopend; i--) {
                    chrs += buffer[testPos - (i - 1)];
                }

                if (c) { chrs += c; }

                return tests[testPos][0].test(chrs);
            }

            function isMask(pos) {23/03/1973
                return tests[determineTestPosition(pos)];
            }

            function determineTestPosition(pos) {
            	return pos % tests.length;
            }

            function checkVal(clearInvalid) {
                var inputValue = input.val();
                var lastMatch = -1;
                for (var i = 0; i < inputValue.length; i++) {
                    for (var pos = lastMatch+1; pos < len; pos++) {
                    	if(isMask(pos)){
                        	buffer[pos] = opts.placeholder;
                        	if (isValid(pos, inputValue.charAt(i))) {
                           		buffer[pos] = inputValue.charAt(i);
                           		lastMatch = pos;
                        	}
                        	break;
                        }else {   //nonmask
                           lastMatch++;
                        }
                    }
                }
                if (clearInvalid) {
                    writeBuffer();
                }
                return seekNext(lastMatch);
            };
        }
    };

})(jQuery);<commit_msg>fix typo in isMask<commit_after>/*
Input Mask plugin for jquery
http://github.com/RobinHerbots/jquery.inputmask
Copyright (c) 2010 Robin Herbots
Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
Version: 0.0.4

This plugin is based on the masked input plugin written by Josh Bush (digitalbush.com)
*/

(function($) {

    $.fn.inputmask = function(fn, options) {
        //options default
        var defaults = {
            placeholder: "_",
            mask: null,
            onComplete: null,
            repeat: 0, //repetitions of the mask
            definitions: {
                '9': {
                    "validator": "[0-9]",
                    "cardinality": 1,
                    'prevalidator': null
                },
                'a': {
                    "validator": "[A-Za-z]",
                    "cardinality": 1,
                    "prevalidator": null
                },
                '*': {
                    "validator": "[A-Za-z0-9]",
                    "cardinality": 1,
                    "prevalidator": null
                },
                'd': { //day
                    "validator": "0[1-9]|[12][0-9]|3[01]",
                    "cardinality": 2,
                    "prevalidator": [{ "validator": "[0-3]", "cardinality": 1}]
                },
                'm': { //month
                    "validator": "0[1-9]|1[012]",
                    "cardinality": 2,
                    "prevalidator": [{ "validator": "[01]", "cardinality": 1}]
                },
                'y': { //year
                    "validator": "(19|20)\\d\\d",
                    "cardinality": 4,
                    "prevalidator": [
                        { "validator": "[12]", "cardinality": 1 },
                        { "validator": "(19|20)", "cardinality": 2 },
                        { "validator": "(19|20)\\d", "cardinality": 3 }
                        ]
                }
            },
            keyCode: { ALT: 18, BACKSPACE: 8, CAPS_LOCK: 20, COMMA: 188, COMMAND: 91, COMMAND_LEFT: 91, COMMAND_RIGHT: 93, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, MENU: 93, NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108,
                NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38, WINDOWS: 91
            }
        };

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

        if (typeof fn == "string") {
            if (fn == 'mask') {
                //init buffer
                var _buffer = getMaskTemplate();
                var pasteEventName = $.browser.msie ? 'paste' : 'input';
                var iPhone = (window.orientation != undefined);
                var tests = getTestingChain();

                return this.each(function() {
                    mask($(this));
                });
            } else if (fn == 'unmaskedvalue') {
                return unmaskedvalue($(this));
            } else { //maybe fn is a mask so we try
            	//set mask
            	opts.mask = fn;

            	//init buffer
                var _buffer = getMaskTemplate();
                var pasteEventName = $.browser.msie ? 'paste' : 'input';
                var iPhone = (window.orientation != undefined);
                var tests = getTestingChain();

                return this.each(function() {
                    mask($(this));
                });
            }
        } if (typeof fn == "object") {
        		opts = $.extend({}, defaults, fn);

        		//init buffer
                var _buffer = getMaskTemplate();
                var pasteEventName = $.browser.msie ? 'paste' : 'input';
                var iPhone = (window.orientation != undefined);
                var tests = getTestingChain();

                return this.each(function() {
                    mask($(this));
                });
        }

        //functions
        function getMaskTemplate() {
            var singleMask = $.map(opts.mask.split(""), function(element, index) {
                var outElem = [];
                var maskdef = opts.definitions[element];
                if (maskdef) {
                    for (i = 0; i < maskdef.cardinality; i++) {
                        outElem.push(opts.placeholder);
                    }
                } else outElem.push(element);

                return outElem;
            });

            var repeatedMask = singleMask.slice();
				for(var i = 0; i < opts.repeat; i++){
					repeatedMask = repeatedMask.concat(singleMask.slice());
				}
			return repeatedMask;
        };

        function getTestingChain() {
            return $.map(opts.mask.split(""), function(element, index) {
                var outElem = [];
                var maskdef = opts.definitions[element];
                if (maskdef) {
                    for (i = 1; i < maskdef.cardinality; i++) {
                        var prevalidator = maskdef.prevalidator[i - 1];
                        outElem.push([new RegExp(prevalidator.validator), prevalidator.cardinality]);
                    }
                    outElem.push([new RegExp(maskdef.validator), maskdef.cardinality]);
                } else outElem.push(null);

                return outElem;
            });
        };

        function unmaskedvalue(el) {
            var tests = el.data('tests');
            if (tests) {
                return $.map(el.val().split(""), function(element, index) {
                    return tests[index] ? element : null;
                }).join('');
            }
            else {
                return el.val();
            }
        }

        function mask(el) {
            var input = $(el);
            //store tests in the input element - used to get the unmasked value
            input.data('tests', tests);

            //init buffer
            var buffer = _buffer.slice();
            var undoBuffer = input.val();
            var ignore = false;              //Variable for ignoring control keys
            var len = _buffer.length;

            //bind events
            if (!input.attr("readonly")) {
                input.bind("focus", function() {
                    input.addClass('focus');
                    undoBuffer = input.val();
                    var pos = checkVal();
                    writeBuffer();
                    setTimeout(function() {
                        if (pos == _buffer.length)
                            caret(input, 0, pos);
                        else
                            caret(input, pos);
                    }, 0);
                }).bind("mouseenter", function() {
                    if (!input.hasClass('focus') && input.val().length == 0)
                        writeBuffer();
                }).bind("blur", function() {
                    input.removeClass('focus');
                    if (input.val() == _buffer.join('')) {
                        input.val('');
                    } else {
                        checkVal();
                        if (input.val() != undoBuffer)
                            input.change();
                    }
                }).bind("mouseleave", function() {
                    if (!input.hasClass('focus') && input.val() == _buffer.join(''))
                        input.val('');
                }).bind("keydown", keydownEvent
                ).bind("keypress", keypressEvent
                ).bind(pasteEventName, function() {
                    setTimeout(function() { caret(input, checkVal(true)); }, 0);
                });

            }

            checkVal();

            //private functions
            function writeBuffer() { return input.val(buffer.join('')).val(); };
            function clearBuffer(start, end) {
                for (var i = start; i < end && i < len; i++) {
                    buffer[i] = _buffer[i];
                }
            };

            function seekNext(pos) {
                while (++pos <= len && !isMask(pos));
                return pos;
            };

            function shiftL(pos) {
                while (!isMask(pos) && --pos >= 0);
                for (var i = pos; i < len; i++) {
                    if (isMask(i)) {
                        buffer[i] = opts.placeholder;
                        var j = seekNext(i);
                        if (j < len && isValid(i, buffer[j])) {
                            buffer[i] = buffer[j];
                        } else
                            break;
                    }
                }
                writeBuffer();
                caret(input, pos);
            };

            function shiftR(pos) {
                for (var i = pos, c = opts.placeholder; i < len; i++) {
                    if (isMask(i)) {
                        var j = seekNext(i);
                        var t = buffer[i];
                        buffer[i] = c;
                        if (j < len && isValid(j, t))
                            c = t;
                        else
                            break;
                    }
                }
            };

            function caret(input, begin, end) {
                if (input.length == 0) return;
                if (typeof begin == 'number') {
                    end = (typeof end == 'number') ? end : begin;
                    return input.each(function() {
                        if (this.setSelectionRange) {
                            this.focus();
                            this.setSelectionRange(begin, end);
                        } else if (this.createTextRange) {
                            var range = this.createTextRange();
                            range.collapse(true);
                            range.moveEnd('character', end);
                            range.moveStart('character', begin);
                            range.select();
                        }
                    });
                } else {
                    if (input[0].setSelectionRange) {
                        begin = input[0].selectionStart;
                        end = input[0].selectionEnd;
                    } else if (document.selection && document.selection.createRange) {
                        var range = document.selection.createRange();
                        begin = 0 - range.duplicate().moveStart('character', -100000);
                        end = begin + range.text.length;
                    }
                    return { begin: begin, end: end };
                }
            };

            function keydownEvent(e) {
                var pos = caret($(this));
                var k = e.keyCode;
                ignore = (k < 16 || (k > 16 && k < 32) || (k > 32 && k < 41));

                //delete selection before proceeding
                if ((pos.begin - pos.end) != 0 && (!ignore || k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE))
                    clearBuffer(pos.begin, pos.end);

                //backspace, delete, and escape get special treatment
                if (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE || (iPhone && k == 127)) {//backspace/delete
                    shiftL(pos.begin + (k == opts.keyCode.DELETE ? 0 : -1));
                    return false;
                } else if (k == opts.keyCode.ESCAPE) {//escape
                    input.val(undoBuffer);
                    caret(input, 0, checkVal());
                    return false;
                }
            }

            function keypressEvent(e) {
                if (ignore) {
                    ignore = false;
                    //Fixes Mac FF bug on backspace
                    return (e.keyCode == 8) ? false : null;
                }
                e = e || window.event;
                var k = e.charCode || e.keyCode || e.which;
                var pos = caret($(this));

                if (e.ctrlKey || e.altKey || e.metaKey) {//Ignore
                    return true;
                } else if ((k >= 32 && k <= 125) || k > 186) {//typeable characters
                    var p = seekNext(pos.begin - 1);
                    if (p < len) {
                        var c = String.fromCharCode(k);
                        if (isValid(p, c)) {
                            shiftR(p);
                            buffer[p] = c;
                            writeBuffer();
                            var next = seekNext(p);
                            caret($(this), next);
                            if (opts.onComplete && next == len)
                                opts.onComplete.call(input);
                        }
                    }
                }
                return false;
            }

            function isValid(pos, c) {
                var testPos = determineTestPosition(pos);

                var loopend = 0;
                if (c) { loopend = 1; ; }

                var chrs = '';
                for (var i = tests[testPos][1]; i > loopend; i--) {
                    chrs += buffer[testPos - (i - 1)];
                }

                if (c) { chrs += c; }

                return tests[testPos][0].test(chrs);
            }

            function isMask(pos) {
                return tests[determineTestPosition(pos)];
            }

            function determineTestPosition(pos) {
            	return pos % tests.length;
            }

            function checkVal(clearInvalid) {
                var inputValue = input.val();
                var lastMatch = -1;
                for (var i = 0; i < inputValue.length; i++) {
                    for (var pos = lastMatch+1; pos < len; pos++) {
                    	if(isMask(pos)){
                        	buffer[pos] = opts.placeholder;
                        	if (isValid(pos, inputValue.charAt(i))) {
                           		buffer[pos] = inputValue.charAt(i);
                           		lastMatch = pos;
                        	}
                        	break;
                        }else {   //nonmask
                           lastMatch++;
                        }
                    }
                }
                if (clearInvalid) {
                    writeBuffer();
                }
                return seekNext(lastMatch);
            };
        }
    };

})(jQuery);<|endoftext|>


<commit_before>$(document).on('turbolinks:load', function() {
  var $input = $('input#gobierto_search');
  var $resultsContainer = $('#search_results');

  function truncateOnWord(str, limit) {
    var trimmable = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u2028\u2029\u3000\uFEFF';
    var reg = new RegExp('(?=[' + trimmable + '])');
    var words = str.split(reg);
    var count = 0;
    return words.filter(function(word) {
      count += word.length;
      return count <= limit;
    }).join('');
  }

  function itemUpdatedAt(d){
    if(d['updated_at'] === undefined)
      return;

    return I18n.t("layouts.search.updated") + ": " + I18n.l("date.formats.short", d['updated_at']);
  }

  function itemDescription(d){
    var maxLenght = 200;
    var description = (d['bio'] || d['description'] || d['body'] || d['bio_' + I18n.locale] || d['description_' + I18n.locale] || d['body_' + I18n.locale] || '');
    if(description === '' || description.length < maxLenght)
      return description;
    return truncateOnWord(description, maxLenght) + '...';
  }

  function itemType(d){
    if(d['class_name'] === undefined)
      return;

    switch(d['class_name']){
      case 'GobiertoPeople::Person':
        return I18n.t("layouts.search.person_item");
      case 'GobiertoPeople::PersonPost':
        return I18n.t("layouts.search.person_post_item");
      case 'GobiertoCalendars::Event':
        return I18n.t("layouts.search.event_item");
      case 'GobiertoPeople::PersonStatement':
        return I18n.t("layouts.search.person_statement_item");
      case 'GobiertoCms::Page':
        return I18n.t("layouts.search.page_item");
      case 'GobiertoBudgets::BudgetLine':
        if (d['kind'] === 'I') {
          return I18n.t("layouts.search.budget_line_item_income");
        } else {
          return I18n.t("layouts.search.budget_line_item_expense");
        }
    }
  }

  function searchFrontCallback(err, content) {
    if (err) {
      console.error(err);
      return;
    }

    $resultsContainer.html('');
    var sum = 0;
    content.results.forEach(function(indexResults){
      sum += indexResults.nbHits;
    });

    if(sum > 0) {
      content.results.forEach(function(indexResults){
        indexResults.hits.forEach(function(d){

          var result = '<a class="result" ' +
            '
' + (d['title'] || d['name'] || d['title_' + I18n.locale] || d['name_' + I18n.locale]) + '
' +
            '
' +
              '
' + itemDescription(d) + '
' +
              '' + itemType(d) + '' +
              (itemUpdatedAt(d) ? ' · ' + itemUpdatedAt(d) + '' : '') +
            '
' +
          '';

          var div = $(result);
          div.appendTo($resultsContainer);
        });
      });
      rebindAll();
    } else {
      $('

'+I18n.t("layouts.search.no_results")+'

').appendTo($resultsContainer);
    }

    if(window.searchClient.indexes.length > 1) {
      $('
'+I18n.t("layouts.search.powered_by")+'
').appendTo($resultsContainer);
    }
  }

  function searchBackCallback(err, content) {
    if (err) {
      console.error(err);
      return;
    }

    $resultsContainer.html('');
    var sum = 0;
    content.results.forEach(function(indexResults){
      sum += indexResults.nbHits;
    });
    if(sum > 0) {
      content.results.forEach(function(indexResults){
        indexResults.hits.forEach(function(d){

          var result = '
' +
            '
' + '' +
            (d['title'] || d['name'] || d['title_' + I18n.locale] || d['name_' + I18n.locale]) +
            '' + itemDescription(d) + ''  +
            '' + '
' +
            '
' + itemUpdatedAt(d) + '
' +
          '
';

          var div = $(result);
          div.appendTo($resultsContainer);
        });
      });

      // After reload partial with pages we have to do pages like draggable
      $(".tipsit").draggable({ revert: true });
      rebindAll();
    } else {
      $('

'+I18n.t("layouts.search.no_results")+'

').appendTo($resultsContainer);
    }
  }

  $input.on('keyup', function(e){
    var q = $(this).val();
    var queries = [];
    window.searchClient.indexes.forEach(function(index){
      queries.push({
        indexName: index,
        query: q,
        params: {
          hitsPerPage: 10,
          filters: window.searchClient.filters
        }
      });
    });

    if(window.location.href.includes("admin")) {
      window.searchClient.client.search(queries, searchBackCallback);
    } else {
      if(q.length > 2){
        window.searchClient.client.search(queries, searchFrontCallback);
      } else {
        $resultsContainer.html('');
      }
    }
  });

  $input.focusin(function() {
    $resultsContainer.show();
  });

  // Hide resultsContainer if clicked outside the search input and results
  $('body').click(function(e) {
    if ( !$(e.target).is('#search_results *') && !$(e.target).is('input#gobierto_search') ) {
      $resultsContainer.hide();
    }
  });
});
<commit_msg>See always the pages in the sections<commit_after>$(document).on('turbolinks:load', function() {
  var $input = $('input#gobierto_search');
  var $resultsContainer = $('#search_results');

  function truncateOnWord(str, limit) {
    var trimmable = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u2028\u2029\u3000\uFEFF';
    var reg = new RegExp('(?=[' + trimmable + '])');
    var words = str.split(reg);
    var count = 0;
    return words.filter(function(word) {
      count += word.length;
      return count <= limit;
    }).join('');
  }

  function itemUpdatedAt(d){
    if(d['updated_at'] === undefined)
      return;

    return I18n.t("layouts.search.updated") + ": " + I18n.l("date.formats.short", d['updated_at']);
  }

  function itemDescription(d){
    var maxLenght = 200;
    var description = (d['bio'] || d['description'] || d['body'] || d['bio_' + I18n.locale] || d['description_' + I18n.locale] || d['body_' + I18n.locale] || '');
    if(description === '' || description.length < maxLenght)
      return description;
    return truncateOnWord(description, maxLenght) + '...';
  }

  function itemType(d){
    if(d['class_name'] === undefined)
      return;

    switch(d['class_name']){
      case 'GobiertoPeople::Person':
        return I18n.t("layouts.search.person_item");
      case 'GobiertoPeople::PersonPost':
        return I18n.t("layouts.search.person_post_item");
      case 'GobiertoCalendars::Event':
        return I18n.t("layouts.search.event_item");
      case 'GobiertoPeople::PersonStatement':
        return I18n.t("layouts.search.person_statement_item");
      case 'GobiertoCms::Page':
        return I18n.t("layouts.search.page_item");
      case 'GobiertoBudgets::BudgetLine':
        if (d['kind'] === 'I') {
          return I18n.t("layouts.search.budget_line_item_income");
        } else {
          return I18n.t("layouts.search.budget_line_item_expense");
        }
    }
  }

  function searchFrontCallback(err, content) {
    if (err) {
      console.error(err);
      return;
    }

    $resultsContainer.html('');
    var sum = 0;
    content.results.forEach(function(indexResults){
      sum += indexResults.nbHits;
    });

    if(sum > 0) {
      content.results.forEach(function(indexResults){
        indexResults.hits.forEach(function(d){

          var result = '<a class="result" ' +
            '
' + (d['title'] || d['name'] || d['title_' + I18n.locale] || d['name_' + I18n.locale]) + '
' +
            '
' +
              '
' + itemDescription(d) + '
' +
              '' + itemType(d) + '' +
              (itemUpdatedAt(d) ? ' · ' + itemUpdatedAt(d) + '' : '') +
            '
' +
          '';

          var div = $(result);
          div.appendTo($resultsContainer);
        });
      });
      rebindAll();
    } else {
      $('

'+I18n.t("layouts.search.no_results")+'

').appendTo($resultsContainer);
    }

    if(window.searchClient.indexes.length > 1) {
      $('
'+I18n.t("layouts.search.powered_by")+'
').appendTo($resultsContainer);
    }
  }

  function searchBackCallback(err, content) {
    if (err) {
      console.error(err);
      return;
    }

    $resultsContainer.html('');
    var sum = 0;
    content.results.forEach(function(indexResults){
      sum += indexResults.nbHits;
    });
    if(sum > 0) {
      content.results.forEach(function(indexResults){
        indexResults.hits.forEach(function(d){

          var result = '
' +
            '
' + '' +
            (d['title'] || d['name'] || d['title_' + I18n.locale] || d['name_' + I18n.locale]) +
            '' + itemDescription(d) + ''  +
            '' + '
' +
            '
' + itemUpdatedAt(d) + '
' +
          '
';

          var div = $(result);
          div.appendTo($resultsContainer);
        });
      });

      // After reload partial with pages we have to do pages like draggable
      $(".tipsit").draggable({ revert: true });
      rebindAll();
    } else {
      $('

'+I18n.t("layouts.search.no_results")+'

').appendTo($resultsContainer);
    }
  }

  $input.on('keyup', function(e){
    var q = $(this).val();
    var queries = [];
    window.searchClient.indexes.forEach(function(index){
      queries.push({
        indexName: index,
        query: q,
        params: {
          hitsPerPage: 10,
          filters: window.searchClient.filters
        }
      });
    });

    if(window.location.href.includes("admin")) {
      window.searchClient.client.search(queries, searchBackCallback);
    } else {
      if(q.length > 2){
        window.searchClient.client.search(queries, searchFrontCallback);
      } else {
        $resultsContainer.html('');
      }
    }
  });

  $input.focusin(function() {
    $resultsContainer.show();
  });

  // Hide resultsContainer if clicked outside the search input and results
  $('body').click(function(e) {
    if ( !$(e.target).is('#search_results *') && !$(e.target).is('input#gobierto_search') ) {
      if(!(window.location.href.includes("admin"))) {
        $resultsContainer.hide();
      }
    }
  });
});
<|endoftext|>


<commit_before>'use strict';

app.factory('authService', ['$rootScope','$q', '$http','$cookies', 'chatService', function($rootScope, $q, $http, $cookies, chatService){

  var session;
  var userinfo;
  var auth_cookie = $cookies.get('ytrk_66');

  if(auth_cookie){
    $http.get('/api/auth/'+auth_cookie)
    .then(function(res){
      var data = res.data;
      if(data.Success && data.Data){
        session = data.Data.Session;
        userinfo = data.Data.User;
        chatService.emit('join', userinfo.Username);
        $rootScope.$broadcast('session_resume');
      }
    }, function(error){
      console.log(error);
    });
  }

  return {
    getSession:function(){
      return session;
    },
    getUser:function(){
      return userinfo;
    },
    hasAccess: function(){
      var deferred = $q.defer();
      if(!!userinfo){
        deferred.resolve(true);
      }
      else{
        deferred.reject({authenticated: false});
      }
      return deferred.promise;
    },
    logIn: function(creds){
      var deferred = $q.defer();
      if(creds && creds.Username && creds.Password){
        $http.post('/api/login', creds)
        .then(function(res){
          var data = res.data;
          if(data.Success){
            session = data.Data.Session;
            userinfo = data.Data.User;
            $cookies.put('ytrk_66', session.Key);
            chatService.emit('join', userinfo.Username);
            deferred.resolve(session);
          }
          else{
            deferred.reject(data.Error);
          }
        }, function(){
          deferred.reject('Could not reach Authentication Service');
        });
      }
      else{
        deferred.reject('No Credentials provided');
      }
      return deferred.promise;
    },
    signUp: function(creds){
      var deferred = $q.defer();
      if(creds && creds.Username && creds.Email && creds.Password){
        $http.post('/api/signup', creds)
        .then(function(res){
          var data = res.data;
          if(data.Success){
            deferred.resolve(data.Message);
          }
          else{
            deferred.reject(data.Error);
          }
        }, function (){
          deferred.reject('Failed to reach Authentication Service');
        });
      }
      else{
        deferred.reject('No Credentials Provided!');
      }
      return deferred.promise;
    },
    logOut: function(){
      $cookies.remove('ytrk_66');
      auth_cookie = null;
      chatService.emit('leave');
      userinfo=null;
      session = null;

    }
  }
}]);
<commit_msg>lengthen cookie expiration to absurd amount of time, rather than just session<commit_after>'use strict';

app.factory('authService', ['$rootScope','$q', '$http','$cookies', 'chatService', function($rootScope, $q, $http, $cookies, chatService){

  var session;
  var userinfo;
  var auth_cookie = $cookies.get('ytrk_66');

  if(auth_cookie){
    $http.get('/api/auth/'+auth_cookie)
    .then(function(res){
      var data = res.data;
      if(data.Success && data.Data){
        session = data.Data.Session;
        userinfo = data.Data.User;
        chatService.emit('join', userinfo.Username);
        $rootScope.$broadcast('session_resume');
      }
    }, function(error){
      console.log(error);
    });
  }

  return {
    getSession:function(){
      return session;
    },
    getUser:function(){
      return userinfo;
    },
    hasAccess: function(){
      var deferred = $q.defer();
      if(!!userinfo){
        deferred.resolve(true);
      }
      else{
        deferred.reject({authenticated: false});
      }
      return deferred.promise;
    },
    logIn: function(creds){
      var deferred = $q.defer();
      if(creds && creds.Username && creds.Password){
        $http.post('/api/login', creds)
        .then(function(res){
          var data = res.data;
          if(data.Success){
            session = data.Data.Session;
            userinfo = data.Data.User;
            var future = new Date().getTime()+(52*7*24*60*60000);
            var eDate = new Date(future);
            $cookies.put('ytrk_66', session.Key, {expires: eDate, });
            chatService.emit('join', userinfo.Username);
            deferred.resolve(session);
          }
          else{
            deferred.reject(data.Error);
          }
        }, function(){
          deferred.reject('Could not reach Authentication Service');
        });
      }
      else{
        deferred.reject('No Credentials provided');
      }
      return deferred.promise;
    },
    signUp: function(creds){
      var deferred = $q.defer();
      if(creds && creds.Username && creds.Email && creds.Password){
        $http.post('/api/signup', creds)
        .then(function(res){
          var data = res.data;
          if(data.Success){
            deferred.resolve(data.Message);
          }
          else{
            deferred.reject(data.Error);
          }
        }, function (){
          deferred.reject('Failed to reach Authentication Service');
        });
      }
      else{
        deferred.reject('No Credentials Provided!');
      }
      return deferred.promise;
    },
    logOut: function(){
      $cookies.remove('ytrk_66');
      auth_cookie = null;
      chatService.emit('leave');
      userinfo=null;
      session = null;

    }
  }
}]);
<|endoftext|>