<commit_before>// API DE DON PATO - ELECCIONES 2015
// @package  : don_pato
// @location : /js
// @file     : main.js
// @author  : Gobierno fácil <howdy@gobiernofacil.com>
// @url     : http://gobiernofacil.com

var APP = function(){
  //
  // S E T   T H E   C O N F I G   V A R I A B L E S
  // --------------------------------------------------------------------------------
  //

  // [ SET DEFAULT VALUES ]
  var endpoint   = "http://elecciones.rob.mx/",
      search     = "http://representantes.pati.to/busqueda/geo/diputados/",
      candidates = "candidatoas/",
      locations  = "casillas/",
      states_csv    = "/js/data/estados_min.csv",
      cities_csv    = "/js/data/municipios.csv",
      districts_csv = "/js/data/distritos.csv",
      district_key_regex  = /df-(\d+)-(\d)/,
      location_regex      = /(\d+)-([a-z\d]+)/i,
      district_map_center = [19.2676, -98.4239], // san merlín!

  // [ CACHE THE UI ELEMENTS ]
      state_selector      = document.querySelector("#district-selector-container select[name='state']"),
      city_selector       = document.querySelector("#district-selector-container select[name='city']"),
      district_map        = document.querySelector("#district-map-container .map"),
      locations_map       = document.querySelector("#district-city-container .map"),
      candidate_container = document.querySelector("#district-candidates-container ul"),
      location_container  = document.querySelector("#locations-map-container"),

  // [ SET THE DATA CONTAINERS ]
      states_array        = [],
      cities_array        = [],
      districts_array     = [],
      cities_map_array    = [],
      districts_map_array = [],
      google_district_map  = null,
      google_location_map  = null,
      google_geocoder      = new google.maps.Geocoder(),
      district_key         = null,
      current_location     = null,
      current_location_key = null,
      current_polygon      = null,
      current_state        = null,
      current_city         = null,
      current_district     = null,
      app;

  //
  // D E F I N E   T H E   A P P
  // --------------------------------------------------------------------------------
  //
  app = {

    //
    // [ G E O L O C A L I Z E   T H E   S T U F F ]
    // ---------------------------------------------
    //
    get_geolocation : function(){
      navigator.geolocation.getCurrentPosition(this.success_geolocation);
    },

    success_geolocation : function(loc){
      app.get("search", [loc.coords.latitude, loc.coords.longitude]);
    },

    error_geolocation : function(){
      console.log("meh murió la geolocalización");
    },

    //
    // [ C A L L   T H E   "Don Pato"   A P I ]
    // ----------------------------------------
    //

    // [ MAKE THE CALL]
    get : function(method, params){
      var url, success_function;
      switch(method){
        case "search":
          url = search + params[0] + "/" + params[1];
          success_function = this.search_success;
          break;

        case "candidate":
          url = endpoint + candidates + params[0] + ".json";
          success_function = this.candidate_success;
          break;

        case "location":
          url = endpoint + locations + params[0];
          success_function = this.location_success;
          break;

        default:
          return null;
          break;
      }
      success_function = success_function.bind(this, params);
      d3.json(url, success_function);
    },

    // [ DON-PATO-API-CALL-SUCCESS (SEARCH) ]
    search_success : function(params, error, data){
      district_map_center  = params;
      district_key         = data.distrito;
      current_location     = data.seccion.id;
      current_polygon      = data.seccion.coords.coordinates[0];
      current_state        = district_key_regex.exec(district_key)[1];
      current_district     = district_key_regex.exec(district_key)[2];
      current_location_key = location_regex.exec(current_location)[2];

      state_selector.value = current_state;
      this.set_cities(current_state);

      if(! google_district_map){
        this.initialize_district_map();
      }
      else{
        google_district_map.setCenter({lat: district_map_center[0], lng: district_map_center[1]});
      }

      this.get("candidate", [district_key]);
      this.get("location", [current_location]);
    },

    // [ DON-PATO-API-CALL-SUCCESS (CANDIDATE) ]
    candidate_success : function(params, error, data){
      console.log(error, data, params);
      this.set_candidate(data);
    },

    // [ DON-PATO-API-CALL-SUCCESS (LOCATION) ]
    location_success : function(params, error, data){
      console.log(error, data, params);
      this.set_location_data(data);
    },

    // [ FUCK! ]
    error : function(conn){
      console.log("error", this, conn.responseText);
    },

    //
    // [ T H E   L O C A T I O N   S E L E C T O R ]
    // ---------------------------------------------
    //

    // [ FILL THE STATE SELECTOR ]
    set_states : function(states){
      states.unshift({clave_entidad : 0, nombre:"selecciona un estado", url : ""});
      states.forEach(function(value, index, array){
        var option = document.createElement('option');
        var text   = document.createTextNode(value.nombre);
        option.appendChild(text);
        option.setAttribute("value", value.clave_entidad);
        state_selector.appendChild(option);
      });
    },

    // [ LOAD THE STATE LIST ]
    get_states : function(){
      var that = this;
      d3.csv(states_csv, null, function(error, rows){
        states_array = rows;
        that.set_states(rows);
      });
    },

    // [ FILL THE CITY SELECTOR ]
    set_cities : function(e){
      var state_id = typeof e === "object" ? e.currentTarget.value : e;
      var cities = app.get_cities_by_state(state_id);
      cities.unshift({clave_entidad : 0, clave_municipio:0, nombre : "selecciona un municipio"});
      city_selector.innerHTML = "";
      cities.forEach(function(value, index, array){
        var option = document.createElement('option');
        var text   = document.createTextNode(value.nombre);
        option.appendChild(text);
        option.setAttribute("value", value.clave_municipio);
        city_selector.appendChild(option);
      });
    },

    // [ LOAD THE CITY LIST ]
    get_cities : function(){
      var that = this;
      d3.csv(cities_csv, null, function(error, rows){
        cities_array = rows;
        that.map_cities(rows);
      });
    },

    // [ MAP THE CITY ]
    map_cities : function(cities){
      var map  = [],
      counter  = 0,
      pointer  = 1,
      displace = 0;
      cities.forEach(function(value, index, array){
        if(pointer == value.clave_entidad){
          counter++;
        }
        else{
          map.push([displace, counter]);
          counter  = 1;
          displace = index;
          pointer  = value.clave_entidad;
        }

        if(array.length == index + 1){
          map.push([displace, counter]);
        }
      });

      cities_array     = cities;
      cities_map_array = map;
      app.set_cities("0");
    },

    // [ GET CITIES BY STATE ]
    get_cities_by_state : function(state_id){
      if(! +state_id) return [];

      var x  = cities_map_array[+state_id - 1],
      cities = cities_array.slice(x[0], x[0] + x[1]);
      return cities;
    },

    //
    // [ T H E   D I S T R I C T   D A T A ]
    // ---------------------------------------------
    //

    // [ LOAD THE DISTRICT LIST ]
    get_districts : function(){
      var that = this;
      d3.csv(districts_csv, null, function(error, rows){
        districts_array = rows;
        that.map_districts(rows);
      });
    },

    // [ MAP THE CITY ]
    map_districts : function(districts){
      var map          = [],
      state            = [],
      district         = [],
      state_pointer    = 0,
      district_pointer = 0;

      districts.forEach(function(value, index, array){
        // [A] STATES
        if(!state_pointer || state_pointer != value.clave_entidad){
          if(state_pointer) map.push(state);
          if(!state_pointer) district.push(value);
          state = [];
          state_pointer    = value.clave_entidad;
          district_pointer = value.distrito;
        }
        // [B]
        else{
          // [B.A] DISTRICTS
          if(district_pointer != value.distrito){
            state.push(district);
            district = [];
            district_pointer = value.distrito;
            district.push(value);
          }
          // [B.B]
          else{
            district.push(value);
          } // [B.B]

          if(array.length === index+1 || array[index+1].clave_entidad != state_pointer){
            state.push(district);
            district = [];
            district_pointer = value.distrito;
            district.push(value);
          }
        } // [B]
        if(array.length === index+1) map.push(state);
      }); // forEach

      districts_map_array = map;

      return map;
    },

    get_cities_by_district : function(state, district){
      var cities_array = districts_map_array[+state - 1][+district - 1],
          current_city = null,
          city_list    = [],
          loc          = parseInt(current_location_key);

      for(var i = 0; i < cities_array.length; i++){
        if(loc >= +cities_array[i].inicia && loc <= +cities_array[i].termina){
          current_city = cities_array[i].clave_municipio;
        }
        if(city_list.indexOf(cities_array[i].clave_municipio) == -1){
          city_list.push(cities_array[i].clave_municipio);
        }
      }
      return [
        current_city,
        city_list,
        loc,
        city_selector.querySelector("option[value='" + (current_city - 1) + "']")
      ];
    },

    //
    // [ T H E   G O O G L E   D I S T R I C T   M A P ]
    // -------------------------------------------------
    //

    // [ INITIALIZE THE DISTRICT MAP ]
    initialize_district_map : function(e){
      var mapOptions = {
        center : {
          lat : district_map_center[0],
          lng : district_map_center[1]
        },
        zoom : 10
      };
      google_district_map = new google.maps.Map(district_map, mapOptions);
    },

    // [ SET THE MAP CENTER ]
    set_district_map_center : function(e){
      var city_id  = typeof e === "object" ? e.currentTarget.value : e,
          state_id = state_selector.value,
          cities   = app.get_cities_by_state(state_id),
          city, i;

      if(! cities.length || ! +city_id) return;

      for(i = 0; i < cities.length; i++){
        if(cities[i].clave_municipio == city_id){
          city = cities[i];
          break;
        }
      }
      district_map_center = [+city.lat, +city.lng];
    },

    // [ GET THE DISTRICT MAP CENTER ]
    get_district_map_center : function(){
      return district_map_center;
    },

    //
    // [ T H E   G O O G L E   L O C A T I O N S   M A P ]
    // ---------------------------------------------------
    //

    initialize_locations_map : function(){
      var mapOptions = {
        center : {
          lat : 0,
          lng : 0
        },
        zoom : 12
      };
      google_location_map = new google.maps.Map(locations_map, mapOptions);
    },

    get_geolocation_from_google : function(location){
      google_geocoder.geocode({address : location}, function(results, status){
        console.log(results, status);
      });
    },

    //
    // [ T H E   G O O D   G U Y S ]
    // ---------------------------------------------------
    //
    set_location_data : function(locations){
      var container = document.createElement("div"),
          address, c, html, loc;

      locations.forEach(function(val, index, array){
        c    = container.cloneNode(),
        html = "";
        loc = val.nombre + ", " + val.direccion.calle + " " + val.direccion.numero;
        html +="
" + loc + "
";
        val.funcionarios.forEach(function(v,i,a){
          html += "
" + v.nombre + " " + v.apellidos + " (" + v.cargo + ")
";
        });
        c.innerHTML = html;
        location_container.appendChild(c);

        cities_array = app.get_cities_by_district(current_state, current_district);
        address = loc + ", " + cities_array[3].innerHTML + ", "
                  + states_array[+current_state].nombre + ", México";
        app.get_geolocation_from_google(address);
      });
    },

    //
    // [ T H E   C A N D I D A T E S   F U N C T I O N S ]
    // ---------------------------------------------------
    //
    set_candidate : function(candidates){
      candidate_container.innerHTML = "";
      var create = document.createElement.bind(document),
          txt    = document.createTextNode.bind(document);

      candidates.forEach(function(val, index, array){
        // [0]. crea el contenedor
        var li = create("li");
        // [1]. agrega la imagen
        var img     = create("img"),
            img_el  = create("p");
            img.src = val.foto;
            img_el.appendChild(img);
            li.appendChild(img_el);
        // [2]. agrega el nombre
        var name     = create("p"),
            name_src = txt(val.nombre);
            name.appendChild(name_src);
            li.appendChild(name);
        // [3]. agrega la casa de campaña
        var house = create("p"),
            house_src = txt(val.casa_campana ? val.casa_campana : "indigente/no sabe/no contestó");
            house.appendChild(house_src);
            li.appendChild(house);
        // [4]. agrega el partido
        var parties = create("p");
            parties_src = val.partidos.join(",");
            parties.innerHTML = parties_src;
            li.appendChild(parties);
            /*
            age,
            age_text,
            curruculum_work,
            curruculum_work_text,
            curricullum_template,
            curriculum_template_text,
            name,
            name_text,
            parties,
            sex,
            social_a,
            social_b,
            social_c,
            social_d,
            alternate,
            phone;
            */
        candidate_container.appendChild(li);
      });
    }
  };

  //
  // [ R I G   T H E   U I ]
  // -----------------------
  //
  state_selector.onchange = app.set_cities;
  city_selector.onchange  = app.set_district_map_center;

  //
  // [ R E T U R N   T H E   A P P ]
  // -------------------------------
  //
  return app;
};

// inicia el API
app = new APP();

app.get_states();
app.get_cities();
app.get_districts();

<commit_msg>debug<commit_after>// API DE DON PATO - ELECCIONES 2015
// @package  : don_pato
// @location : /js
// @file     : main.js
// @author  : Gobierno fácil <howdy@gobiernofacil.com>
// @url     : http://gobiernofacil.com

var APP = function(){
  //
  // S E T   T H E   C O N F I G   V A R I A B L E S
  // --------------------------------------------------------------------------------
  //

  // [ SET DEFAULT VALUES ]
  var endpoint   = "http://elecciones.rob.mx/",
      search     = "http://representantes.pati.to/busqueda/geo/diputados/",
      candidates = "candidatoas/",
      locations  = "casillas/",
      states_csv    = "/js/data/estados_min.csv",
      cities_csv    = "/js/data/municipios.csv",
      districts_csv = "/js/data/distritos.csv",
      district_key_regex  = /df-(\d+)-(\d)/,
      location_regex      = /(\d+)-([a-z\d]+)/i,
      district_map_center = [19.2676, -98.4239], // san merlín!

  // [ CACHE THE UI ELEMENTS ]
      state_selector      = document.querySelector("#district-selector-container select[name='state']"),
      city_selector       = document.querySelector("#district-selector-container select[name='city']"),
      district_map        = document.querySelector("#district-map-container .map"),
      locations_map       = document.querySelector("#district-city-container .map"),
      candidate_container = document.querySelector("#district-candidates-container ul"),
      location_container  = document.querySelector("#locations-map-container"),

  // [ SET THE DATA CONTAINERS ]
      states_array        = [],
      cities_array        = [],
      districts_array     = [],
      cities_map_array    = [],
      districts_map_array = [],
      google_district_map  = null,
      google_location_map  = null,
      google_geocoder      = new google.maps.Geocoder(),
      district_key         = null,
      current_location     = null,
      current_location_key = null,
      current_polygon      = null,
      current_state        = null,
      current_city         = null,
      current_district     = null,
      app;

  //
  // D E F I N E   T H E   A P P
  // --------------------------------------------------------------------------------
  //
  app = {

    //
    // [ G E O L O C A L I Z E   T H E   S T U F F ]
    // ---------------------------------------------
    //
    get_geolocation : function(){
      navigator.geolocation.getCurrentPosition(this.success_geolocation);
    },

    success_geolocation : function(loc){
      app.get("search", [loc.coords.latitude, loc.coords.longitude]);
    },

    error_geolocation : function(){
      console.log("meh murió la geolocalización");
    },

    //
    // [ C A L L   T H E   "Don Pato"   A P I ]
    // ----------------------------------------
    //

    // [ MAKE THE CALL]
    get : function(method, params){
      var url, success_function;
      switch(method){
        case "search":
          url = search + params[0] + "/" + params[1];
          success_function = this.search_success;
          break;

        case "candidate":
          url = endpoint + candidates + params[0] + ".json";
          success_function = this.candidate_success;
          break;

        case "location":
          url = endpoint + locations + params[0];
          success_function = this.location_success;
          break;

        default:
          return null;
          break;
      }
      success_function = success_function.bind(this, params);
      d3.json(url, success_function);
    },

    // [ DON-PATO-API-CALL-SUCCESS (SEARCH) ]
    search_success : function(params, error, data){
      district_map_center  = params;
      district_key         = data.distrito;
      current_location     = data.seccion.id;
      current_polygon      = data.seccion.coords.coordinates[0];
      current_state        = district_key_regex.exec(district_key)[1];
      current_district     = district_key_regex.exec(district_key)[2];
      current_location_key = location_regex.exec(current_location)[2];

      state_selector.value = current_state;
      this.set_cities(current_state);

      if(! google_district_map){
        this.initialize_district_map();
      }
      else{
        google_district_map.setCenter({lat: district_map_center[0], lng: district_map_center[1]});
      }

      this.get("candidate", [district_key]);
      this.get("location", [current_location]);
    },

    // [ DON-PATO-API-CALL-SUCCESS (CANDIDATE) ]
    candidate_success : function(params, error, data){
      console.log(error, data, params);
      this.set_candidate(data);
    },

    // [ DON-PATO-API-CALL-SUCCESS (LOCATION) ]
    location_success : function(params, error, data){
      console.log(error, data, params);
      this.set_location_data(data);
    },

    // [ FUCK! ]
    error : function(conn){
      console.log("error", this, conn.responseText);
    },

    //
    // [ T H E   L O C A T I O N   S E L E C T O R ]
    // ---------------------------------------------
    //

    // [ FILL THE STATE SELECTOR ]
    set_states : function(states){
      states.unshift({clave_entidad : 0, nombre:"selecciona un estado", url : ""});
      states.forEach(function(value, index, array){
        var option = document.createElement('option');
        var text   = document.createTextNode(value.nombre);
        option.appendChild(text);
        option.setAttribute("value", value.clave_entidad);
        state_selector.appendChild(option);
      });
    },

    // [ LOAD THE STATE LIST ]
    get_states : function(){
      var that = this;
      d3.csv(states_csv, null, function(error, rows){
        states_array = rows;
        that.set_states(rows);
      });
    },

    // [ FILL THE CITY SELECTOR ]
    set_cities : function(e){
      var state_id = typeof e === "object" ? e.currentTarget.value : e;
      var cities = app.get_cities_by_state(state_id);
      cities.unshift({clave_entidad : 0, clave_municipio:0, nombre : "selecciona un municipio"});
      city_selector.innerHTML = "";
      cities.forEach(function(value, index, array){
        var option = document.createElement('option');
        var text   = document.createTextNode(value.nombre);
        option.appendChild(text);
        option.setAttribute("value", value.clave_municipio);
        city_selector.appendChild(option);
      });
    },

    // [ LOAD THE CITY LIST ]
    get_cities : function(){
      var that = this;
      d3.csv(cities_csv, null, function(error, rows){
        cities_array = rows;
        that.map_cities(rows);
      });
    },

    // [ MAP THE CITY ]
    map_cities : function(cities){
      var map  = [],
      counter  = 0,
      pointer  = 1,
      displace = 0;
      cities.forEach(function(value, index, array){
        if(pointer == value.clave_entidad){
          counter++;
        }
        else{
          map.push([displace, counter]);
          counter  = 1;
          displace = index;
          pointer  = value.clave_entidad;
        }

        if(array.length == index + 1){
          map.push([displace, counter]);
        }
      });

      cities_array     = cities;
      cities_map_array = map;
      app.set_cities("0");
    },

    // [ GET CITIES BY STATE ]
    get_cities_by_state : function(state_id){
      if(! +state_id) return [];

      var x  = cities_map_array[+state_id - 1],
      cities = cities_array.slice(x[0], x[0] + x[1]);
      return cities;
    },

    //
    // [ T H E   D I S T R I C T   D A T A ]
    // ---------------------------------------------
    //

    // [ LOAD THE DISTRICT LIST ]
    get_districts : function(){
      var that = this;
      d3.csv(districts_csv, null, function(error, rows){
        districts_array = rows;
        that.map_districts(rows);
      });
    },

    // [ MAP THE CITY ]
    map_districts : function(districts){
      var map          = [],
      state            = [],
      district         = [],
      state_pointer    = 0,
      district_pointer = 0;

      districts.forEach(function(value, index, array){
        // [A] STATES
        if(!state_pointer || state_pointer != value.clave_entidad){
          if(state_pointer) map.push(state);
          if(!state_pointer) district.push(value);
          state = [];
          state_pointer    = value.clave_entidad;
          district_pointer = value.distrito;
        }
        // [B]
        else{
          // [B.A] DISTRICTS
          if(district_pointer != value.distrito){
            state.push(district);
            district = [];
            district_pointer = value.distrito;
            district.push(value);
          }
          // [B.B]
          else{
            district.push(value);
          } // [B.B]

          if(array.length === index+1 || array[index+1].clave_entidad != state_pointer){
            state.push(district);
            district = [];
            district_pointer = value.distrito;
            district.push(value);
          }
        } // [B]
        if(array.length === index+1) map.push(state);
      }); // forEach

      districts_map_array = map;

      return map;
    },

    get_cities_by_district : function(state, district){
      var cities_array = districts_map_array[+state - 1][+district - 1],
          current_city = null,
          city_list    = [],
          loc          = parseInt(current_location_key);

      for(var i = 0; i < cities_array.length; i++){
        if(loc >= +cities_array[i].inicia && loc <= +cities_array[i].termina){
          current_city = cities_array[i].clave_municipio;
        }
        if(city_list.indexOf(cities_array[i].clave_municipio) == -1){
          city_list.push(cities_array[i].clave_municipio);
        }
      }
      return [
        current_city,
        city_list,
        loc,
        city_selector.querySelector("option[value='" + (current_city - 1) + "']")
      ];
    },

    //
    // [ T H E   G O O G L E   D I S T R I C T   M A P ]
    // -------------------------------------------------
    //

    // [ INITIALIZE THE DISTRICT MAP ]
    initialize_district_map : function(e){
      var mapOptions = {
        center : {
          lat : district_map_center[0],
          lng : district_map_center[1]
        },
        zoom : 10
      };
      google_district_map = new google.maps.Map(district_map, mapOptions);
    },

    // [ SET THE MAP CENTER ]
    set_district_map_center : function(e){
      var city_id  = typeof e === "object" ? e.currentTarget.value : e,
          state_id = state_selector.value,
          cities   = app.get_cities_by_state(state_id),
          city, i;

      if(! cities.length || ! +city_id) return;

      for(i = 0; i < cities.length; i++){
        if(cities[i].clave_municipio == city_id){
          city = cities[i];
          break;
        }
      }
      district_map_center = [+city.lat, +city.lng];
    },

    // [ GET THE DISTRICT MAP CENTER ]
    get_district_map_center : function(){
      return district_map_center;
    },

    //
    // [ T H E   G O O G L E   L O C A T I O N S   M A P ]
    // ---------------------------------------------------
    //

    initialize_locations_map : function(){
      var mapOptions = {
        center : {
          lat : 0,
          lng : 0
        },
        zoom : 12
      };
      google_location_map = new google.maps.Map(locations_map, mapOptions);
    },

    get_geolocation_from_google : function(location){
      google_geocoder.geocode({address : location}, function(results, status){
        console.log(results, status);
      });
    },

    //
    // [ T H E   G O O D   G U Y S ]
    // ---------------------------------------------------
    //
    set_location_data : function(locations){
      var container = document.createElement("div"),
          address, c, html, loc;

      locations.forEach(function(val, index, array){
        c    = container.cloneNode(),
        html = "";
        loc = val.nombre + ", " + val.direccion.calle + " " + val.direccion.numero;
        html +="
" + loc + "
";
        val.funcionarios.forEach(function(v,i,a){
          html += "
" + v.nombre + " " + v.apellidos + " (" + v.cargo + ")
";
        });
        c.innerHTML = html;
        location_container.appendChild(c);

        cities_array = app.get_cities_by_district(current_state, current_district);
        console.log("iras estos datos:", current_state, current_district, cities_array);
        address = loc + ", " + cities_array[3].innerHTML + ", "
                  + states_array[+current_state].nombre + ", México";
        app.get_geolocation_from_google(address);
      });
    },

    //
    // [ T H E   C A N D I D A T E S   F U N C T I O N S ]
    // ---------------------------------------------------
    //
    set_candidate : function(candidates){
      candidate_container.innerHTML = "";
      var create = document.createElement.bind(document),
          txt    = document.createTextNode.bind(document);

      candidates.forEach(function(val, index, array){
        // [0]. crea el contenedor
        var li = create("li");
        // [1]. agrega la imagen
        var img     = create("img"),
            img_el  = create("p");
            img.src = val.foto;
            img_el.appendChild(img);
            li.appendChild(img_el);
        // [2]. agrega el nombre
        var name     = create("p"),
            name_src = txt(val.nombre);
            name.appendChild(name_src);
            li.appendChild(name);
        // [3]. agrega la casa de campaña
        var house = create("p"),
            house_src = txt(val.casa_campana ? val.casa_campana : "indigente/no sabe/no contestó");
            house.appendChild(house_src);
            li.appendChild(house);
        // [4]. agrega el partido
        var parties = create("p");
            parties_src = val.partidos.join(",");
            parties.innerHTML = parties_src;
            li.appendChild(parties);
            /*
            age,
            age_text,
            curruculum_work,
            curruculum_work_text,
            curricullum_template,
            curriculum_template_text,
            name,
            name_text,
            parties,
            sex,
            social_a,
            social_b,
            social_c,
            social_d,
            alternate,
            phone;
            */
        candidate_container.appendChild(li);
      });
    }
  };

  //
  // [ R I G   T H E   U I ]
  // -----------------------
  //
  state_selector.onchange = app.set_cities;
  city_selector.onchange  = app.set_district_map_center;

  //
  // [ R E T U R N   T H E   A P P ]
  // -------------------------------
  //
  return app;
};

// inicia el API
app = new APP();

app.get_states();
app.get_cities();
app.get_districts();

<|endoftext|>


<commit_before>/*eslint-disable no-console */
import _ from "underscore";
import App from "./App";
import { defaultsWith } from "./defaultAppArgs";

class TestApp {
    constructor() {
        this.actions = {};
        this.container = {};
    }
    run(delegateHooks = {}) {
        // Make TestApp be the delegate.
        var appArgs = defaultsWith(_.extend(this, delegateHooks));
        App.run(...appArgs);
    }
    registerAction(name, actionCmd) {
        this.actions[name] = actionCmd;
    }
    createBootstrapper() { // Make TestApp also the bootstrapper.
        return this;
    }
    bootstrap(onComplete) {
        var providers = this.delegate.provide(this.container);
        var actions = this.delegate.createActions(this.actions);
        onComplete(actions, providers);
    }
    handleRunError(error) {
        console.error(error);
    }
}

export default new TestApp();
<commit_msg>TestApp is now an instance of ProvidedAppDelegate.<commit_after>/*eslint-disable no-console */
import _ from "underscore";
import App from "./App";
import ProvidedAppDelegate from "./ProvidedAppDelegate";
import { defaultsWithDelegate } from "./defaultAppArgs";

class TestApp extends ProvidedAppDelegate {
    constructor() {
        super();
        this.actions = {};
        this.container = {};
    }
    run(delegateHooks = {}) {
        _.extend(this, delegateHooks);
        var appArgs = defaultsWithDelegate(this);
        App.run(...appArgs);
    }
    registerAction(name, actionCmd) {
        this.actions[name] = actionCmd;
    }
    createBootstrapper() { // Make TestApp also the bootstrapper.
        return this;
    }
    bootstrap(onComplete) {
        var providers = this.delegate.provide(this.container);
        var actions = this.delegate.createActions(this.actions);
        onComplete(actions, providers);
    }
    handleRunError(error) {
        console.error(error);
    }
}

export default new TestApp();
<|endoftext|>


<commit_before>$(document).ready(function(event){
   $('#submit').click(function(event){
      getData();

   });
   $('#formThing').submit(function(event){
      event.preventDefault();
      getData();
   });
});
function getData(){
    $.get('http://player.me/api/v1/users/' + $('#inputText').val() + "?username=true" , function(outer){
         var data = outer.results
         var avatar = "https://player.me/api/v1/users/" + data['id'] + "/avatars";
         var username = data['id']['username'];
         var followers = data['followers_count'];
         var joined = data['created_at'];
         var html = '';
         html += '
' + username + '
';
         html += '
Followers: ' + followers;

         html += '
Joined on: ' + joined.replace('T', ' at ');
         $('.profile').html(html);
      });
}
<commit_msg>Thanks to @kayteh fixed it now! @TheBaconSpace Go ahead!<commit_after>$(document).ready(function(event){
   $('#submit').click(function(event){
      getData();

   });
   $('#formThing').submit(function(event){
      event.preventDefault();
      getData();
   });
});
function getData(){
      $.ajax({
    url: 'http://player.me/api/v1/users/' + $('#inputText').val() + "?username=true",

    // The name of the callback parameter, as specified by the YQL service
    jsonp: "callback",

    // Tell jQuery we're expecting JSONP
    dataType: "jsonp",

    // Work with the response
    success: function( response ) {
        var data = response.results
         var avatar = data['avatar']['original'];
         var username = data['username'];
         var followers = data['followers_count'];
         var joined = data['created_at'];
         var html = '';
         html += '
' + username + '
';
         html += '
Followers: ' + followers;

         html += '
Joined on: ' + joined.replace('T', ' at ');
         $('.profile').html(html);
    }
    });
}
<|endoftext|>


<commit_before>/*

Copyright (c) 2015 Hexagon <robinnilsson@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

/* ToDo:

	* Vikta titel efter hur mycket plats sökorden tar i titeln
	* Missingspacesnurra

*/

var	Index = require('./Index.js'),
	processors = require('./processors.js'),
	rankers = require('./rankers.js');

// Helper function for measuring execution time
var time = (function () {
	var times = {};

	return function (id) {
		var diff;

		if (!times[id]) {
			times[id] = process.hrtime();
			return;
		}

		diff = process.hrtime(times[id]);
		times[id] = null;

		return (diff[0] * 1e9 + diff[1]) / 1E6;
	};
}());

// Helper function for option defaults
function defaults (defaults, source) {
	var obj = {},
		key;

	if (!source) {
		return defaults;
	}

	for (key in defaults) {
		obj[key] = (source[key] !== undefined) ? source[key] : defaults[key];
	}

	return obj;
}

function processWord (word, opts) {
	var result,
		i;

	// Check if the word is too short
	if (!word || word.length < opts.minWordLen) {
		return;
	}

	// Check if the word is too long
	if (word.length > opts.maxWordLen) {
		word = word.substring(0, opts.maxWordLen);
	}

	// Always convert everything to lowercase if not case sensitive
	if (!opts.caseSensitive) {
		word = word.toLowerCase();
	}

	// Prepare object
	result = { original: word, processed: undefined };

	// Apply all wordProcessors
	for (i = 0; i < opts.wordProcessors.length; i++) {
		if (!word) {
			break;
		}

		word = opts.wordProcessors[i](word);
	}

	// Check if the preprocessor disabled this word
	if (!word) {
		return;
	}

	// Save processed word
	result.processed = word;

	return result;
};

function Thinker (opts) {
	var self = this;

	// Optional `new` keyword
	if (!(self instanceof Thinker)) {
		return new Thinker;
	}

	// Index backend
	self.index = new Index();

	// Can be set afterwards
	self.enableSuggestions = false;
	self.ranker = function() {};

	// All these options must be set before indexing and
	// cannot change afterwards (the object will also be frozen).
	self.options = defaults({
		characters: /[^a-zA-Z0-9']/g,
		caseSensitive: false,
		minWildcardWordLen: 4,
		maxWildcardWordLen: 32,
		minWordLen: 2,
		maxWordLen: 32,
		wordProcessors: [],
		fieldProcessors: []
	}, opts && opts.options);
};

Thinker.prototype.feed = function (texts, opts) {
	var self = this,
		currentDocument,
		currentField,
		currentWord,
		i,j,k;

	//
	opts = self.options = defaults(self.options, opts);

	//
	Object.freeze(self.options);

	//
	function addWord (word, docid, fieldIdx) {
		var wIndex,
			i, j;

		// Add processed
		wIndex = self.index.populate(word, docid, fieldIdx);

		// Add partials
		for (i = opts.minWildcardWordLen; i < word.original.length && i < opts.maxWildcardWordLen; i++) {
			for (j = 0; j < (word.original.length - i) + 1; j++) {
				// Do not input partial if equals processed
				//if( word.original.substr(j,i) !== word.processed ) {
					self.index.populatePartial(word.original.substr(j, i), wIndex);
				//}
			}
		}
	}

	/* Stage 1, query index for each individual word */
	while (currentDocument = texts.pop()) {

		// split text into separate words, removing empty results
		// Loop through all textfields (index > 0)
		for (j = 1 ; j < currentDocument.length; j++) {

			// Extract current field
			currentField = currentDocument[j];

			// Apply all fieldProcessors
			for (i = 0; i < opts.fieldProcessors.length; i++) {
				if (currentField) {
					currentField = opts.fieldProcessors[i](currentField);
				}
			}

			// Split field into separate words
			currentField = currentField.split(opts.characters);

			// Extract unique words
			for (k = 0; k < currentField.length; k++) {
				if ((currentWord = processWord(currentField[k], opts))) {
					addWord(currentWord, currentDocument[0], j);
				}
			}
		}
	}
};

Thinker.prototype.addFieldProcessor = function (fn) {
	return (this.options.fieldProcessors.push(fn), this);
};

Thinker.prototype.addWordProcessor = function (fn) {
	return (this.options.wordProcessors.push(fn), this);
};

Thinker.prototype.find = function (string, exact) {
	time('findTime');

	var self = this,

		// Extract valid parts of the expression
		words = string.split(self.options.characters),
		word,

		// Find matching texts
		resultSet = { expressions: [] },

		queryResult,
		suggestion,
		i;

	exact = !!exact;

	for (i = 0; i < words.length; i++) {
		// Normalize and validate word
		if (!(word = words[i]) || !(word = processWord(words[i], self.options))) {
			continue;
		}

		//
		queryResult = self.index.query(word, exact);

		//
		if (!queryResult.direct && self.enableSuggestions) {
			suggestion = self.index.findClosestWord(word.original);
		}

		//
		resultSet.expressions.push({
			interpretation: exact ? word.original : word.processed,
			original: word.original,
			suggestion: suggestion,
			exactMode: exact,
			hits: queryResult
		});
	}

	// Rank resultSet
	time('rankTime')
	resultSet = self.ranker(resultSet);

	return {
		results: resultSet,
		findTime: time('findTime'),
		rankTime: time('rankTime')
	};
};

Thinker.processors = processors;
Thinker.rankers = rankers;

module.exports = Thinker;<commit_msg>Update Thinker.js<commit_after>/*

Copyright (c) 2015 Hexagon <robinnilsson@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

/* ToDo:

	* Vikta titel efter hur mycket plats sökorden tar i titeln
	* Missingspacesnurra

*/

var	Index = require('./index.js'),
	processors = require('./processors.js'),
	rankers = require('./rankers.js');

// Helper function for measuring execution time
var time = (function () {
	var times = {};

	return function (id) {
		var diff;

		if (!times[id]) {
			times[id] = process.hrtime();
			return;
		}

		diff = process.hrtime(times[id]);
		times[id] = null;

		return (diff[0] * 1e9 + diff[1]) / 1E6;
	};
}());

// Helper function for option defaults
function defaults (defaults, source) {
	var obj = {},
		key;

	if (!source) {
		return defaults;
	}

	for (key in defaults) {
		obj[key] = (source[key] !== undefined) ? source[key] : defaults[key];
	}

	return obj;
}

function processWord (word, opts) {
	var result,
		i;

	// Check if the word is too short
	if (!word || word.length < opts.minWordLen) {
		return;
	}

	// Check if the word is too long
	if (word.length > opts.maxWordLen) {
		word = word.substring(0, opts.maxWordLen);
	}

	// Always convert everything to lowercase if not case sensitive
	if (!opts.caseSensitive) {
		word = word.toLowerCase();
	}

	// Prepare object
	result = { original: word, processed: undefined };

	// Apply all wordProcessors
	for (i = 0; i < opts.wordProcessors.length; i++) {
		if (!word) {
			break;
		}

		word = opts.wordProcessors[i](word);
	}

	// Check if the preprocessor disabled this word
	if (!word) {
		return;
	}

	// Save processed word
	result.processed = word;

	return result;
};

function Thinker (opts) {
	var self = this;

	// Optional `new` keyword
	if (!(self instanceof Thinker)) {
		return new Thinker;
	}

	// Index backend
	self.index = new Index();

	// Can be set afterwards
	self.enableSuggestions = false;
	self.ranker = function() {};

	// All these options must be set before indexing and
	// cannot change afterwards (the object will also be frozen).
	self.options = defaults({
		characters: /[^a-zA-Z0-9']/g,
		caseSensitive: false,
		minWildcardWordLen: 4,
		maxWildcardWordLen: 32,
		minWordLen: 2,
		maxWordLen: 32,
		wordProcessors: [],
		fieldProcessors: []
	}, opts && opts.options);
};

Thinker.prototype.feed = function (texts, opts) {
	var self = this,
		currentDocument,
		currentField,
		currentWord,
		i,j,k;

	//
	opts = self.options = defaults(self.options, opts);

	//
	Object.freeze(self.options);

	//
	function addWord (word, docid, fieldIdx) {
		var wIndex,
			i, j;

		// Add processed
		wIndex = self.index.populate(word, docid, fieldIdx);

		// Add partials
		for (i = opts.minWildcardWordLen; i < word.original.length && i < opts.maxWildcardWordLen; i++) {
			for (j = 0; j < (word.original.length - i) + 1; j++) {
				// Do not input partial if equals processed
				//if( word.original.substr(j,i) !== word.processed ) {
					self.index.populatePartial(word.original.substr(j, i), wIndex);
				//}
			}
		}
	}

	/* Stage 1, query index for each individual word */
	while (currentDocument = texts.pop()) {

		// split text into separate words, removing empty results
		// Loop through all textfields (index > 0)
		for (j = 1 ; j < currentDocument.length; j++) {

			// Extract current field
			currentField = currentDocument[j];

			// Apply all fieldProcessors
			for (i = 0; i < opts.fieldProcessors.length; i++) {
				if (currentField) {
					currentField = opts.fieldProcessors[i](currentField);
				}
			}

			// Split field into separate words
			currentField = currentField.split(opts.characters);

			// Extract unique words
			for (k = 0; k < currentField.length; k++) {
				if ((currentWord = processWord(currentField[k], opts))) {
					addWord(currentWord, currentDocument[0], j);
				}
			}
		}
	}
};

Thinker.prototype.addFieldProcessor = function (fn) {
	return (this.options.fieldProcessors.push(fn), this);
};

Thinker.prototype.addWordProcessor = function (fn) {
	return (this.options.wordProcessors.push(fn), this);
};

Thinker.prototype.find = function (string, exact) {
	time('findTime');

	var self = this,

		// Extract valid parts of the expression
		words = string.split(self.options.characters),
		word,

		// Find matching texts
		resultSet = { expressions: [] },

		queryResult,
		suggestion,
		i;

	exact = !!exact;

	for (i = 0; i < words.length; i++) {
		// Normalize and validate word
		if (!(word = words[i]) || !(word = processWord(words[i], self.options))) {
			continue;
		}

		//
		queryResult = self.index.query(word, exact);

		//
		if (!queryResult.direct && self.enableSuggestions) {
			suggestion = self.index.findClosestWord(word.original);
		}

		//
		resultSet.expressions.push({
			interpretation: exact ? word.original : word.processed,
			original: word.original,
			suggestion: suggestion,
			exactMode: exact,
			hits: queryResult
		});
	}

	// Rank resultSet
	time('rankTime')
	resultSet = self.ranker(resultSet);

	return {
		results: resultSet,
		findTime: time('findTime'),
		rankTime: time('rankTime')
	};
};

Thinker.processors = processors;
Thinker.rankers = rankers;

module.exports = Thinker;
<|endoftext|>


<commit_before>$(function(){
	var getSolved = function(username, callback){
		var apiUrl = "http://judge.u-aizu.ac.jp/onlinejudge/webservice/user?id=";
		$.ajax({
			url: apiUrl + username,
			type: 'get',
			dataType: 'xml',
			success: function(xml, status){
				var username_ = $(xml).find("user > id").text();
				var solved_ = $(xml).find("user > status > solved").text();
				callback(username_, solved_, status);
			}
		});
	}

	var users = ["raimei10130", "kagamiz", "orisano", "li_saku", "marin72_com"];
	var users_ = [];
	var solved_ = [];
	var count = 0;
	var userTemplate = _.template("
<%= name %>	<%= solved %>
");
	_.each(users, function(user){ getSolved(user, function(username, solved){
		$("table#watch-table").append(userTemplate({name: username, solved: solved}));
		count++;
		users_.push({name: username, solved: solved});
	});});

	var waitComplete = function(span, callback){
		if (count == users.length){
			callback();
		}
		else {
			setTimeout(function(){
				waitComplete(span, callback);
			}, span);
		}
	};

	waitComplete(1000, function(){
		var ctx = document.getElementById("solved-graph").getContext("2d");
		users_.sort(function(a, b){
				return a.solved - b.solved;
		});
		new Chart(ctx).Bar({
			labels: _.map(users_, function(usr){ return (usr.name) }),
			datasets : [{ data : _.map(users_, function(usr){ return (usr.solved)}) }]
		});
	});
});<commit_msg>sorting table<commit_after>$(function(){
	var getSolved = function(username, callback){
		var apiUrl = "http://judge.u-aizu.ac.jp/onlinejudge/webservice/user?id=";
		$.ajax({
			url: apiUrl + username,
			type: 'get',
			dataType: 'xml',
			success: function(xml, status){
				var username_ = $(xml).find("user > id").text();
				var solved_ = $(xml).find("user > status > solved").text();
				callback(username_, solved_, status);
			}
		});
	}

	var users = ["raimei10130", "kagamiz", "orisano", "li_saku", "marin72_com"];
	var users_ = [];
	var solved_ = [];
	var count = 0;
	var userTemplate = _.template("
<%= name %>	<%= solved %>
");
	_.each(users, function(user){ getSolved(user, function(username, solved){
		count++;
		users_.push({name: username, solved: solved});
	});});

	var waitComplete = function(span, callback){
		if (count == users.length){
			callback();
		}
		else {
			setTimeout(function(){
				waitComplete(span, callback);
			}, span);
		}
	};

	waitComplete(100, function(){
		var ctx = document.getElementById("solved-graph").getContext("2d");
		users_.sort(function(a, b){
				return a.solved - b.solved;
		});
		_.each(users_, function(item){ $("table#watch-table").append(userTemplate(item)); });
		new Chart(ctx).Bar({
			labels: _.map(users_, function(usr){ return (usr.name) }),
			datasets : [{ data : _.map(users_, function(usr){ return (usr.solved)}) }]
		});
	});
});<|endoftext|>


<commit_before>const
  minimatch = require('minimatch'),
  path = require('path'),
  globWatcher = require('glob-watcher'),
  sgUtil = require('./util');

class Watcher {

  constructor({conf, browserSync, CollectorStore: {getSections, getFiles, updateTimestamp}}) {

    this.getSections = getSections;
    this.getFiles = getFiles;
    this.updateTimestamp = updateTimestamp;
    this.browserSync = browserSync;

    this.globOptions = conf.get('globOptions');
    this.htmlExt = conf.get('htmlExt');
    this.templateExt = conf.get('templateExt');
    this.dataExt = conf.get('dataExt');
    this.emitDelay = conf.get('emitDelay', 100);
    this.logLevel = conf.get('logLevel', 0);
    this.emitTimeout = null;
    this.emitQue = {};

    this.watch = this.watch.bind(this);
    this.start = this.start.bind(this);
    this.onAddFiles = this.onAddFiles.bind(this);
    this.onUnlinkFiles = this.onUnlinkFiles.bind(this);
    this.emitDelayed = this.emitDelayed.bind(this);
    this.resetEmitQue = this.resetEmitQue.bind(this);
    this.addToEmitQue = this.addToEmitQue.bind(this);
  }

  watch(section) {
    const {watchPattern} = section;

    return globWatcher(watchPattern, {ignoreInitial: true})
      .on('change', (filename) => this.onChangeFiles(path.resolve(filename), section))
      .on('add', (filename) => this.onAddFiles(path.resolve(filename), section))
      .on('unlink', (filename) => this.onUnlinkFiles(path.resolve(filename), section));
  }

  start() {
    this.getSections().forEach(this.watch);
  }

  onAddFiles(filename, section) {

    if (minimatch(filename, `**/*.${this.templateExt}`)) {
      if (this.logLevel > 1) {
        sgUtil.log(`Watcher: file has been added (${filename})`);
      }
      const affectedUrls = this.updateTimestamp(filename);
      this.removeCaches(filename, section);
      section.setFile({filename, section});
      this.emitDelayed(filename, affectedUrls, 'onadd');
    }

    if (minimatch(filename, `**/*.${this.dataExt}`)) {
      this.onChangeFiles(filename, section);
    }
  }

  onChangeFiles(filename, section) {

    if (this.logLevel > 1) {
      sgUtil.log(`Watcher: file has been updated (${filename})`);
    }

    filename = sgUtil.replaceFileExtension(filename, this.templateExt);

    const affectedUrls = this.updateTimestamp(filename);

    section.updateFile(filename);
    this.removeCaches(filename, section);
    this.emitDelayed(filename, affectedUrls, 'onchange');
  }

  onUnlinkFiles(filename, section) {

    if (minimatch(filename, `**/*.${this.templateExt}`)) {
      if (this.logLevel > 1) {
        sgUtil.log(`Watcher: file has been unlinked (${filename})`);
      }

      const affectedUrls = this.updateTimestamp(filename);

      section.unsetFile(filename);
      this.removeCaches(filename, section);
      this.emitDelayed(filename, affectedUrls, 'onunlink');
    }

    if (minimatch(filename, `**/*.${this.dataExt}`)) {
      this.onChangeFiles(filename, section);
    }
  }

  addToEmitQue({filename, extension}) {
    if (this.emitQue[extension] === undefined) {
      this.emitQue[extension] = [];
    }
    this.emitQue[extension].push(filename);
  }

  resetEmitQue() {
    this.emitQue = {};
  }

  emitDelayed(filename, affectedUrls, origin) {
    const
      {htmlExt, templateExt, dataExt, emitQue, emitDelay, addToEmitQue, resetEmitQue, browserSync} = this,
      extension = sgUtil.getFileExtension(filename);

    if ([htmlExt, templateExt, dataExt].indexOf(extension) !== -1) {

      addToEmitQue({filename, extension});
      clearTimeout(this.emitTimeout);

      const extensions = Object.keys(emitQue);

      this.emitTimeout = setTimeout(() => {

        browserSync.sockets.emit('atomatic:reload', affectedUrls);
        browserSync.emitter.emit('atomatic:change', affectedUrls)
        if (!origin !== 'onchange' || !extensions.indexOf(dataExt)) {
          browserSync.sockets.emit('atomatic:fetchSection');
        }
        resetEmitQue();
        sgUtil.log(`[atomatic] Emit reload based on file changes`, 'bs');
      }, emitDelay);
    }
  }

  removeCaches(filename, section) {

    section._timestamp = 0;
    const dirname = path.dirname(filename);

    Object.keys(this.globOptions.cache)
      .filter(key => key.indexOf(dirname) !== -1)
      .map(key => delete this.globOptions.cache[key]);
  }
}

module.exports = Watcher;<commit_msg>move emit event log to log before the emit itself<commit_after>const
  minimatch = require('minimatch'),
  path = require('path'),
  globWatcher = require('glob-watcher'),
  sgUtil = require('./util');

class Watcher {

  constructor({conf, browserSync, CollectorStore: {getSections, getFiles, updateTimestamp}}) {

    this.getSections = getSections;
    this.getFiles = getFiles;
    this.updateTimestamp = updateTimestamp;
    this.browserSync = browserSync;

    this.globOptions = conf.get('globOptions');
    this.htmlExt = conf.get('htmlExt');
    this.templateExt = conf.get('templateExt');
    this.dataExt = conf.get('dataExt');
    this.emitDelay = conf.get('emitDelay', 100);
    this.logLevel = conf.get('logLevel', 0);
    this.emitTimeout = null;
    this.emitQue = {};

    this.watch = this.watch.bind(this);
    this.start = this.start.bind(this);
    this.onAddFiles = this.onAddFiles.bind(this);
    this.onUnlinkFiles = this.onUnlinkFiles.bind(this);
    this.emitDelayed = this.emitDelayed.bind(this);
    this.resetEmitQue = this.resetEmitQue.bind(this);
    this.addToEmitQue = this.addToEmitQue.bind(this);
  }

  watch(section) {
    const {watchPattern} = section;

    return globWatcher(watchPattern, {ignoreInitial: true})
      .on('change', (filename) => this.onChangeFiles(path.resolve(filename), section))
      .on('add', (filename) => this.onAddFiles(path.resolve(filename), section))
      .on('unlink', (filename) => this.onUnlinkFiles(path.resolve(filename), section));
  }

  start() {
    this.getSections().forEach(this.watch);
  }

  onAddFiles(filename, section) {

    if (minimatch(filename, `**/*.${this.templateExt}`)) {
      if (this.logLevel > 1) {
        sgUtil.log(`Watcher: file has been added (${filename})`);
      }
      const affectedUrls = this.updateTimestamp(filename);
      this.removeCaches(filename, section);
      section.setFile({filename, section});
      this.emitDelayed(filename, affectedUrls, 'onadd');
    }

    if (minimatch(filename, `**/*.${this.dataExt}`)) {
      this.onChangeFiles(filename, section);
    }
  }

  onChangeFiles(filename, section) {

    if (this.logLevel > 1) {
      sgUtil.log(`Watcher: file has been updated (${filename})`);
    }

    filename = sgUtil.replaceFileExtension(filename, this.templateExt);

    const affectedUrls = this.updateTimestamp(filename);

    section.updateFile(filename);
    this.removeCaches(filename, section);
    this.emitDelayed(filename, affectedUrls, 'onchange');
  }

  onUnlinkFiles(filename, section) {

    if (minimatch(filename, `**/*.${this.templateExt}`)) {
      if (this.logLevel > 1) {
        sgUtil.log(`Watcher: file has been unlinked (${filename})`);
      }

      const affectedUrls = this.updateTimestamp(filename);

      section.unsetFile(filename);
      this.removeCaches(filename, section);
      this.emitDelayed(filename, affectedUrls, 'onunlink');
    }

    if (minimatch(filename, `**/*.${this.dataExt}`)) {
      this.onChangeFiles(filename, section);
    }
  }

  addToEmitQue({filename, extension}) {
    if (this.emitQue[extension] === undefined) {
      this.emitQue[extension] = [];
    }
    this.emitQue[extension].push(filename);
  }

  resetEmitQue() {
    this.emitQue = {};
  }

  emitDelayed(filename, affectedUrls, origin) {
    const
      {htmlExt, templateExt, dataExt, emitQue, emitDelay, addToEmitQue, resetEmitQue, browserSync} = this,
      extension = sgUtil.getFileExtension(filename);

    if ([htmlExt, templateExt, dataExt].indexOf(extension) !== -1) {

      addToEmitQue({filename, extension});
      clearTimeout(this.emitTimeout);

      const extensions = Object.keys(emitQue);

      this.emitTimeout = setTimeout(() => {
        sgUtil.log(`[atomatic] Emit reload based on file changes`, 'bs');
        browserSync.sockets.emit('atomatic:reload', affectedUrls);
        browserSync.emitter.emit('atomatic:change', affectedUrls)
        if (!origin !== 'onchange' || !extensions.indexOf(dataExt)) {
          browserSync.sockets.emit('atomatic:fetchSection');
        }
        resetEmitQue();
      }, emitDelay);
    }
  }

  removeCaches(filename, section) {

    section._timestamp = 0;
    const dirname = path.dirname(filename);

    Object.keys(this.globOptions.cache)
      .filter(key => key.indexOf(dirname) !== -1)
      .map(key => delete this.globOptions.cache[key]);
  }
}

module.exports = Watcher;<|endoftext|>


<commit_before>$(document).ready(function() {

    // Declare global variables
    var machineModelDesc = $('.machine-model-description'), machineImage = $('#machine-image'), nextMachineImage = $('#machine-image').next('#machine-title'), btnAdd = $('#btnAdd'), s4Machine = $('label[for="s4"]');
    s4MachineName = s4Machine.find('.machineName').html(), s4MachineType = s4Machine.find('.machineType').html(), s4MachinePrice = s4Machine.find('.amount').html()

    s5Machine = $('label[for="s5"]');
    s5MachineName = s5Machine.find('.machineName').html(), s5MachineType = s5Machine.find('.machineType').html(), s5MachinePrice = s5Machine.find('.amount').html()

    s6Machine = $('label[for="s6"]');
    s6MachineName = s6Machine.find('.machineName').html(), s6MachineType = s6Machine.find('.machineType').html(), s6MachinePrice = s6Machine.find('.amount').html()

    s7Machine = $('label[for="s7"]');
    s7MachineName = s7Machine.find('.machineName').html(), s7MachineType = s7Machine.find('.machineType').html(), s7MachinePrice = s7Machine.find('.amount').html();

    //  $('.field-name-machine-model input').each(function(index) {
    //      var machineID = $(this).attr('id');
    //  });

    // Create instances of the machine object and assign
    // properties
    //  machineS4 = {
    //      machineName : $('input '),
    //      machineType : "Weigh/Fill System",
    //      machinePrice : 6150
    //  };

    // Hide fallback content and delete button
    $('.large-discharge-funnel,.field-name-dimensions li,#btnDel,#step-2,#step-3,#step-4,#step-5,#hidden-accessories-page,.spout-shape-images > *').hide();
    // Remove fallback form elements
    $('.default-spout,.default-discharge-funnel,#btnQuote').remove();
    // .bottom class puts a negative z-index on the hidden
    // accessories page so that it loads underneath the rest of
    // the content. This removes that class on load.
    $('.bottom').removeClass('bottom');
    // Hide all but the first machine model description
    machineModelDesc.not('.machine-model-description:first').hide();
    // Remove .hidden class from JS ready content
    $('.small-discharge-funnel,.large-discharge-funnel,#btnAdd,#btnDel,#btnFront,#btnSide,.cloneSpout,.step-submit,#sidebar,#btnPrint,#btnEmail,#btnClose,#btnContinue,.order-summary,#hidden-accessories-page,#machine-title,#order-summary').removeClass('hidden');
    // Check the default discharge funnel field
    $('#small-standard-discharge-funnel').prop('checked', true).addClass('active');

    // Add a waypoint to the sidebar
    var mi_container = $('#sidebar');
    // Remove the no-sidebar class for fallback
    $('#main-content').removeClass('no-sidebar');
    // Set the .sticky class when waypoint is reached
    mi_container.waypoint(function(direction) {
        $('#machine-image-container').toggleClass('sticky', direction === 'down');
    });

    function radioSelect() {
        var radioInputFields = $('input[name=machine-model],input[name=weight-hopper],input[name=discharge-funnel],input.spout-type');

        radioInputFields.click(function(e) {
            var fieldID = $(this), inputVal = fieldID.closest('ul.field-type-radio').find('.active').val(), objectVal = fieldID.val();

            if (inputVal === objectVal) {
                e.preventDefault();
                //add this to prevent default click behaviour
            } else {
                var fieldValue = fieldID.val(), spoutContainer = fieldID.closest('fieldset'), grandTotalContainer = $('#cost-container .amount'), grandTotal = parseInt(grandTotalContainer.text(), 10), price = parseInt(fieldID.next('label').find(".amount").text(), 10), siblingAmounts = 0;
                radioName = fieldID.attr("name");

                $("input[name='" + radioName + "'].active").not(fieldID).each(function() {
                    siblingAmounts += parseInt($(this).next("label").find(".amount").text(), 10);
                });
                fieldID.toggleClass("active");
                $("input[name='" + radioName + "']").not(fieldID).removeClass("active");
                if (fieldID.hasClass("active")) {
                    grandTotal -= siblingAmounts;
                    grandTotal += price;
                } else {
                    grandTotal -= price;
                }
                grandTotalContainer.html(grandTotal);

                switch (fieldValue) {
                    case 'S-4':
                        machineModelDesc.hide();
                        s4Machine.find('.machine-model-description').show();
                        machineImage.removeClass('s4 s5 s6 s7').addClass('s4');
                        nextMachineImage.html(s4MachineName + " " + s4MachineType);
                        break;
                    case 'S-5':
                        machineModelDesc.hide();
                        s5Machine.find('.machine-model-description').show();
                        machineImage.removeClass('s4 s5 s6 s7').addClass('s5');
                        nextMachineImage.html(s5MachineName + " " + s5MachineType);
                        break;
                    case 'S-6':
                        machineModelDesc.hide();
                        s6Machine.find('.machine-model-description').show();
                        machineImage.removeClass('s4 s5 s6 s7').addClass('s6');
                        nextMachineImage.html(s6MachineName + " " + s6MachineType);
                        break;
                    case 'S-7':
                        machineModelDesc.hide();
                        s7Machine.find('.machine-model-description').show();
                        machineImage.removeClass('s4 s5 s6 s7').addClass('s7');
                        nextMachineImage.html(s7MachineName + " " + s7MachineType);
                        break;
                    case 'small-weight-hopper':
                        $('.small-discharge-funnel').show().find('#small-standard-discharge-funnel').prop('checked', true);
                        $('.large-discharge-funnel').hide().find('input').prop('checked', false);
                        machineImage.removeClass('smwh lrgwh std-fnl steep-fnl').addClass('smwh std-fnl');
                        break;
                    case 'large-weight-hopper':
                        $('.large-discharge-funnel').show().find('#large-standard-discharge-funnel').prop('checked', false);
                        $('.small-discharge-funnel').hide().find('input').prop('checked', false);
                        machineImage.removeClass('smwh lrgwh std-fnl steep-fnl').addClass('lrgwh std-fnl');
                        break;
                    case 'small-steep-funnel':
                    case 'large-steep-funnel':
                    case 'small-standard-discharge-funnel':
                    case 'large-standard-discharge-funnel':
                        machineImage.toggleClass('std-fnl steep-fnl');
                        break;
                    case 'flag-bag':
                        machineImage.find('.spout').removeClass('hidden');
                        spoutContainer.find('.field-name-dimensions li').hide();
                        spoutContainer.find('.spout-shape-images > *').hide()
                        spoutContainer.find('.spout-width-inches').show();
                        spoutContainer.find('.spout-shape-images > .flat-bag-spout-shape').show();
                        spoutContainer.find('.description p').html("Enter the width of the bag opening (W).");
                        break;
                    case '4-sided-bag':
                        machineImage.find('.spout').removeClass('hidden');
                        spoutContainer.find('.field-name-dimensions li').hide();
                        spoutContainer.find('.spout-shape-images > *').hide()
                        spoutContainer.find('.spout-width-inches,.spout-height-inches').show();
                        spoutContainer.find('.spout-shape-images > .four-sided-bag-spout-shape').show();
                        spoutContainer.find('.description p').html("Looking down at the top of your bag, enter the dimensions (D1) and (D2) of the bag opening.");
                        break;
                    case 'can-jar':
                        machineImage.find('.spout').removeClass('hidden');
                        spoutContainer.find('.field-name-dimensions li').hide();
                        spoutContainer.find('.spout-shape-images > *').hide()
                        spoutContainer.find('.spout-diameter-inches').show();
                        spoutContainer.find('.spout-shape-images > .can-or-jar-spout-shape').show();
                        spoutContainer.find('.description p').html("Enter the inside diameter of the bottle or can opening (D).");
                        break;
                }
            }
        });

    }

    radioSelect();

    $('#btnFront,#btnSide').click(function() {
        btnDirection = $(this).val();
        if (btnDirection === 'Front') {
            machineImage.addClass('front').removeClass('side');
        } else {
            machineImage.addClass('side').removeClass('front');
        }
    });

    $('.step-submit').click(function() {
        var stepContainer = $(this).closest('.step-container'), nextContainerID = stepContainer.next().attr('id'), prevContainerID = stepContainer.prev().attr('id');
        $('#pag-navigation a').removeClass('active');

        if ($(this).is('.next')) {
            stepContainer.hide().next().show();
            $('#pag-navigation a[href*=' + nextContainerID + ']').addClass('active');
        } else {
            stepContainer.hide().prev().show();
            $('#pag-navigation a[href*=' + prevContainerID + ']').addClass('active');
        }
    });

    $('#pag-navigation a').click(function() {
        var stepValue = $(this).attr('href');
        $('#pag-navigation a').removeClass('active');
        $(this).addClass('active');
        $('.step-container').hide();
        $(stepValue).show();
    });

    $('#hidden-accessories-page-btn').click(function() {
        $('#hidden-accessories-page').show();
    });
    $('#btnClose,#btnContinue').click(function() {
        $(this).closest('.step-container').hide();
    });

    btnAdd.click(function() {
        var num = $('.cloneSpout').length, newNum = new Number(num + 1),
        // the numeric ID of the new input field
        // being
        // added
        newSpoutID = 'spout-' + newNum, newSpoutTypeID = 'spout-' + newNum + "-type", newSpoutDimensionsID = 'spout-' + newNum + "-dimensions",
        // create the new element via clone(),
        // and
        // manipulate it's ID using newNum value
        newElem = $('#spout-' + num).clone().attr('id', newSpoutID),
        // manipulate the name/id values of the
        // elements
        // inside the new element
        radioFieldID = 1;

        newElem.children('legend').html('Spout ' + newNum).next().attr('id', newSpoutTypeID).find('input').attr({
            "id" : function(arr) {
                return newSpoutTypeID + "-" + arr
            },
            'name' : newSpoutTypeID
        }).prop('checked', false).next().attr('for', function(arr) {
            return newSpoutTypeID + "-" + arr
        });
        newElem.find('.description p').html("Please enter the spout type spout that you require by clicking on the image above.");
        newElem.find('.spout-shape-images > *').hide()
        newElem.children('.field-name-dimensions').attr('id', newSpoutDimensionsID).find('li').hide().find('.spout-width-inches input').attr('id', newSpoutID + "-width-inches").closest('.field-name-dimensions').find('.spout-height-inches input').attr('id', newSpoutID + "-height-inches").closest('.field-name-dimensions').find('.spout-diameter-inches input').attr('id', newSpoutID + "-diameter-inches");

        // insert the new element after the last
        // "duplicatable" input field
        $('#spout-' + num).after(newElem);

        // enable the "remove" button
        $('#btnDel').show().prop('disabled', false);

        // business rule: you can only add 5
        // names
        if (newNum == 3)
            btnAdd.hide();

        radioSelect();
    });

    $('#btnDel').click(function() {
        var num = $('.cloneSpout').length;
        // how many "duplicatable" input fields we currently
        // have
        $('#spout-' + num).remove();
        // remove the last element

        // enable the "add" button
        if (num == 3)
            btnAdd.show();

        // if only one element remains, disable the "remove"
        // button
        if (num - 1 == 1)
            $('#btnDel').hide().attr('disabled', 'disabled');
    });

});
<commit_msg>Added a $ to variables representing a jquery object. Tidied machine attribute variable declarations which falsely included semicolons without a var at the beginning.<commit_after>$(document).ready(function() {

    // Declare global variables
    var $machineModelDesc = $('.machine-model-description'), $machineImage = $('#machine-image'), $nextMachineImage = $('#machine-image').next('#machine-title'), $btnAdd = $('#$btnAdd'),
    // S-4 Machine attributes
    $s4Machine = $('label[for="s4"]'), s4MachineName = $s4Machine.find('.machineName').text(), s4MachineType = $s4Machine.find('.machineType').text(), s4MachinePrice = $s4Machine.find('.amount').text()
    // S-5Machine attributes
    $s5Machine = $('label[for="s5"]'), s5MachineName = $s5Machine.find('.machineName').text(), s5MachineType = $s5Machine.find('.machineType').text(), s5MachinePrice = $s5Machine.find('.amount').text()
    // S-6 Machine attributes
    $s6Machine = $('label[for="s6"]'), s6MachineName = $s6Machine.find('.machineName').text(), s6MachineType = $s6Machine.find('.machineType').text(), s6MachinePrice = $s6Machine.find('.amount').text()
    // S-7 Machine attributes
    s7Machine = $('label[for="s7"]'), s7MachineName = s7Machine.find('.machineName').text(), s7MachineType = s7Machine.find('.machineType').text(), s7MachinePrice = s7Machine.find('.amount').text();

    //  $('.field-name-machine-model input').each(function(index) {
    //      var machineID = $(this).attr('id');
    //  });

    // Create instances of the machine object and assign
    // properties
    //  machineS4 = {
    //      machineName : $('input '),
    //      machineType : "Weigh/Fill System",
    //      machinePrice : 6150
    //  };

    // Hide fallback content and delete button
    $('.large-discharge-funnel,.field-name-dimensions li,#btnDel,#step-2,#step-3,#step-4,#step-5,#hidden-accessories-page,.spout-shape-images > *').hide();
    // Remove fallback form elements
    $('.default-spout,.default-discharge-funnel,#btnQuote').remove();
    // .bottom class puts a negative z-index on the hidden
    // accessories page so that it loads underneath the rest of
    // the content. This removes that class on load.
    $('.bottom').removeClass('bottom');
    // Hide all but the first machine model description
    $machineModelDesc.not('.machine-model-description:first').hide();
    // Remove .hidden class from JS ready content
    $('.small-discharge-funnel,.large-discharge-funnel,#$btnAdd,#btnDel,#btnFront,#btnSide,.cloneSpout,.step-submit,#sidebar,#btnPrint,#btnEmail,#btnClose,#btnContinue,.order-summary,#hidden-accessories-page,#machine-title,#order-summary').removeClass('hidden');
    // Check the default discharge funnel field
    $('#small-standard-discharge-funnel').prop('checked', true).addClass('active');

    // Add a waypoint to the sidebar
    var $mi_container = $('#sidebar');
    // Remove the no-sidebar class for fallback
    $('#main-content').removeClass('no-sidebar');
    // Set the .sticky class when waypoint is reached
    $mi_container.waypoint(function(direction) {
        $('#machine-image-container').toggleClass('sticky', direction === 'down');
    });

    function radioSelect() {
        var $radioInputFields = $('input[name=machine-model],input[name=weight-hopper],input[name=discharge-funnel],input.spout-type');

        $radioInputFields.click(function(e) {
            var $fieldID = $(this), inputVal = $fieldID.closest('ul.field-type-radio').find('.active').val(), objectVal = $fieldID.val();

            if (inputVal === objectVal) {
                e.preventDefault();
                //add this to prevent default click behaviour
            } else {
                var fieldValue = $fieldID.val(), $spoutContainer = $fieldID.closest('fieldset'), $grandTotalContainer = $('#cost-container .amount'), grandTotal = parseInt($grandTotalContainer.text(), 10), price = parseInt($fieldID.next('label').find(".amount").text(), 10), siblingAmounts = 0;
                radioName = $fieldID.attr("name");

                $("input[name='" + radioName + "'].active").not($fieldID).each(function() {
                    siblingAmounts += parseInt($(this).next("label").find(".amount").text(), 10);
                });
                $fieldID.toggleClass("active");
                $("input[name='" + radioName + "']").not($fieldID).removeClass("active");
                if ($fieldID.hasClass("active")) {
                    grandTotal -= siblingAmounts;
                    grandTotal += price;
                } else {
                    grandTotal -= price;
                }
                $grandTotalContainer.html(grandTotal);

                switch (fieldValue) {
                    case 'S-4':
                        $machineModelDesc.hide();
                        $s4Machine.find('.machine-model-description').show();
                        $machineImage.removeClass('s4 s5 s6 s7').addClass('s4');
                        $nextMachineImage.html(s4MachineName + " " + s4MachineType);
                        break;
                    case 'S-5':
                        $machineModelDesc.hide();
                        $s5Machine.find('.machine-model-description').show();
                        $machineImage.removeClass('s4 s5 s6 s7').addClass('s5');
                        $nextMachineImage.html(s5MachineName + " " + s5MachineType);
                        break;
                    case 'S-6':
                        $machineModelDesc.hide();
                        $s6Machine.find('.machine-model-description').show();
                        $machineImage.removeClass('s4 s5 s6 s7').addClass('s6');
                        $nextMachineImage.html(s6MachineName + " " + s6MachineType);
                        break;
                    case 'S-7':
                        $machineModelDesc.hide();
                        s7Machine.find('.machine-model-description').show();
                        $machineImage.removeClass('s4 s5 s6 s7').addClass('s7');
                        $nextMachineImage.html(s7MachineName + " " + s7MachineType);
                        break;
                    case 'small-weight-hopper':
                        $('.small-discharge-funnel').show().find('#small-standard-discharge-funnel').prop('checked', true);
                        $('.large-discharge-funnel').hide().find('input').prop('checked', false);
                        $machineImage.removeClass('smwh lrgwh std-fnl steep-fnl').addClass('smwh std-fnl');
                        break;
                    case 'large-weight-hopper':
                        $('.large-discharge-funnel').show().find('#large-standard-discharge-funnel').prop('checked', false);
                        $('.small-discharge-funnel').hide().find('input').prop('checked', false);
                        $machineImage.removeClass('smwh lrgwh std-fnl steep-fnl').addClass('lrgwh std-fnl');
                        break;
                    case 'small-steep-funnel':
                    case 'large-steep-funnel':
                    case 'small-standard-discharge-funnel':
                    case 'large-standard-discharge-funnel':
                        $machineImage.toggleClass('std-fnl steep-fnl');
                        break;
                    case 'flag-bag':
                        $machineImage.find('.spout').removeClass('hidden');
                        $spoutContainer.find('.field-name-dimensions li').hide();
                        $spoutContainer.find('.spout-shape-images > *').hide()
                        $spoutContainer.find('.spout-width-inches').show();
                        $spoutContainer.find('.spout-shape-images > .flat-bag-spout-shape').show();
                        $spoutContainer.find('.description p').html("Enter the width of the bag opening (W).");
                        break;
                    case '4-sided-bag':
                        $machineImage.find('.spout').removeClass('hidden');
                        $spoutContainer.find('.field-name-dimensions li').hide();
                        $spoutContainer.find('.spout-shape-images > *').hide()
                        $spoutContainer.find('.spout-width-inches,.spout-height-inches').show();
                        $spoutContainer.find('.spout-shape-images > .four-sided-bag-spout-shape').show();
                        $spoutContainer.find('.description p').html("Looking down at the top of your bag, enter the dimensions (D1) and (D2) of the bag opening.");
                        break;
                    case 'can-jar':
                        $machineImage.find('.spout').removeClass('hidden');
                        $spoutContainer.find('.field-name-dimensions li').hide();
                        $spoutContainer.find('.spout-shape-images > *').hide()
                        $spoutContainer.find('.spout-diameter-inches').show();
                        $spoutContainer.find('.spout-shape-images > .can-or-jar-spout-shape').show();
                        $spoutContainer.find('.description p').html("Enter the inside diameter of the bottle or can opening (D).");
                        break;
                }
            }
        });

    }

    radioSelect();

    $('#btnFront,#btnSide').click(function() {
        btnDirection = $(this).val();
        if (btnDirection === 'Front') {
            $machineImage.addClass('front').removeClass('side');
        } else {
            $machineImage.addClass('side').removeClass('front');
        }
    });

    $('.step-submit').click(function() {
        var $stepContainer = $(this).closest('.step-container'), nextStepContainerID = $stepContainer.next().attr('id'), prevStepContainerID = $stepContainer.prev().attr('id');
        $('#pag-navigation a').removeClass('active');

        if ($(this).is('.next')) {
            $stepContainer.hide().next().show();
            $('#pag-navigation a[href*=' + nextStepContainerID + ']').addClass('active');
        } else {
            $stepContainer.hide().prev().show();
            $('#pag-navigation a[href*=' + prevStepContainerID + ']').addClass('active');
        }
    });

    $('#pag-navigation a').click(function() {
        var stepValue = $(this).attr('href');
        $('#pag-navigation a').removeClass('active');
        $(this).addClass('active');
        $('.step-container').hide();
        $(stepValue).show();
    });

    $('#hidden-accessories-page-btn').click(function() {
        $('#hidden-accessories-page').show();
    });
    $('#btnClose,#btnContinue').click(function() {
        $(this).closest('.step-container').hide();
    });

    $btnAdd.click(function() {
        var num = $('.cloneSpout').length, newNum = new Number(num + 1),
        // the numeric ID of the new input field
        // being
        // added
        newSpoutID = 'spout-' + newNum, newSpoutTypeID = 'spout-' + newNum + "-type", newSpoutDimensionsID = 'spout-' + newNum + "-dimensions",
        // create the new element via clone(),
        // and
        // manipulate it's ID using newNum value
        newElem = $('#spout-' + num).clone().attr('id', newSpoutID),
        // manipulate the name/id values of the
        // elements
        // inside the new element
        radioFieldID = 1;

        newElem.children('legend').html('Spout ' + newNum).next().attr('id', newSpoutTypeID).find('input').attr({
            "id" : function(arr) {
                return newSpoutTypeID + "-" + arr
            },
            'name' : newSpoutTypeID
        }).prop('checked', false).next().attr('for', function(arr) {
            return newSpoutTypeID + "-" + arr
        });
        newElem.find('.description p').html("Please enter the spout type spout that you require by clicking on the image above.");
        newElem.find('.spout-shape-images > *').hide()
        newElem.children('.field-name-dimensions').attr('id', newSpoutDimensionsID).find('li').hide().find('.spout-width-inches input').attr('id', newSpoutID + "-width-inches").closest('.field-name-dimensions').find('.spout-height-inches input').attr('id', newSpoutID + "-height-inches").closest('.field-name-dimensions').find('.spout-diameter-inches input').attr('id', newSpoutID + "-diameter-inches");

        // insert the new element after the last
        // "duplicatable" input field
        $('#spout-' + num).after(newElem);

        // enable the "remove" button
        $('#btnDel').show().prop('disabled', false);

        // business rule: you can only add 5
        // names
        if (newNum == 3)
            $btnAdd.hide();

        radioSelect();
    });

    $('#btnDel').click(function() {
        var num = $('.cloneSpout').length;
        // how many "duplicatable" input fields we currently
        // have
        $('#spout-' + num).remove();
        // remove the last element

        // enable the "add" button
        if (num == 3)
            $btnAdd.show();

        // if only one element remains, disable the "remove"
        // button
        if (num - 1 == 1)
            $('#btnDel').hide().attr('disabled', 'disabled');
    });

});
<|endoftext|>


<commit_before>var App;

window.dhtmlHistory.create({
	toJSON: function(o) {
		return JSON.stringify(o);
	}
	, fromJSON: function(s) {
		return JSON.parse(s);
	}
});

(function(App){
	"use strict";
	var Main = function(){
		this.getConfig(function(r, t){
			var modules = Object.keys(r.modules)
			t.buildMenu(modules);

			t.start(r);
		});
	}

	/**
	 * Gets the main site configuration
	 * @return {json} Configuration
	 */
	Main.prototype.getConfig = function(callback) {
		var t = this;
		new Vi({url:'config.json', response: 'object'}).server(function(r){
			if(typeof callback === 'function'){
				callback(r, t);
			}
		});
	};

	Main.prototype.start = function(r) {
		var lang = this.browserLanguage();
		var modules = {};

		for(var k in r.modules){
			if(r.modules.hasOwnProperty(k)){
				modules[k] = {nombre: k, url:r.url};
			}
		}

		var j = {name: 'ExpMan', modules:modules, div:'#container', _div: '#container', currentLang: lang};
		this.a = new AppSystem(j);

		App = this.a;
		window.App = App;
		this.a._data = r;
		var t = this;

		this.initializeWallets(this, function(t){
			t.searchWallets(t, function(t){
				t.get_chosenWallet(t, function(t, chosen){
					dhtmlHistory.initialize();
					dhtmlHistory.addListener(t.handleHistory);

					var chosen_wallet = chosen;
					for(var i = 0, len = App.wallets.length; i < len; i++){
						var wallet = App.wallets[i];
						if(chosen !== null && chosen.idWallet === wallet.idWallet){
							chosen_wallet = wallet;
						}
					}

					t.openWallet(chosen_wallet, function(){
						t.a.init(function(){
							var initialModule = dhtmlHistory.getCurrentLocation();
							if(initialModule == '/' || initialModule == ''){
								t.loadCategory(t.chooseDefaultModule());
							}else{
								var c = initialModule.substr(1);
								t.loadCategory(c);
							}
						});
					});
				});
			});
		});
	};

	Main.prototype.chooseDefaultModule = function() {
		var module = 'wallets';
		if( typeof this.a._chosen === 'object' ) {
			module = 'activities';
		}

		return module;
	};

	Main.prototype.handleHistory = function(newLocation, historyData) {
		var category = newLocation.substr(1);
		_App._cat = category;
		if(typeof _App.a.current === 'object'){
			_App.loadCategory(category);
		}
	};

	Main.prototype.buildMenu = function(modules) {
		this.menu = document.getElementById('main-menu');
		for(var i = 0, len = modules.length; i < len; i++){
			var m = modules[i];
			var li = document.createElement('li');
			li.id = 'm-'+m;

			var a = document.createElement('a');
			a.setAttribute('data-ltag', m);
			a.setAttribute('data-module', m);

			li.appendChild(a);
			this.menu.appendChild(li);

			a._t = this;
			a.addEventListener('click', function(){
				var category = this.getAttribute('data-module');
				this._t.loadCategory(category);
			});
		}
	};

	Main.prototype.cleanMenuCategory = function() {
		var lis = document.querySelectorAll('#main-menu>li');
		for(var i = 0, len = lis.length; i < len; i++){
			var li = lis[i];
			li.className = '';
		}
	};

	Main.prototype.activeMenuCategory = function(category) {
		var el = document.getElementById('m-'+category);
		this.cleanMenuCategory();
		el.className = 'active';
	};

	Main.prototype.loadCategory = function(category) {
		dhtmlHistory.add('/'+category, {message: "Module " +category});
		this.activeMenuCategory(category);

		this.a.div = this.a._div;
		this.a.getModule(category);
		this.a.current.start();
	};

	Main.prototype.browserLanguage = function() {
		var lang = navigator.language || navigator.userLanguage;
		lang = lang.match(/([a-z]+)/gi);
		if(lang !== null){
			lang = lang[0];
		}

		var l = '';
		switch(lang){
			case 'es':
				l = lang;
			break;
			default:
			case 'en':
				l = lang;
			break;
		}

		return l;
	};

	//Initialize Wallets
	Main.prototype.initializeWallets = function(obj, callback){
		callback = (typeof callback !== 'function') ? function(){} : callback;

		var mainStructure = App._data.mainStructure;
		mainStructure.name = 'bank';
		var bank = DB(mainStructure);
		bank.initialize(function(){
			App.bank = bank;
			callback(obj);
		});
	}

	//Search for existing wallets
	Main.prototype.searchWallets = function(obj, callback){
		callback = (typeof callback !== 'function') ? function(){} : callback;

		this.a.bank.search('wallets', 'by_name', '', 'all', function(wallets){
			App.wallets = wallets;
			App._wallets = [];

			callback(obj);
		});
	}

	Main.prototype.openWallet = function(wallet, callback) {
		if(wallet === null){
			callback();

			return;
		}

		if(this.a._wallet !== undefined){
			delete this.a._wallet;
		}

		var d = datetoUTC();
		var arr = {idWallet: wallet.idWallet};
		arr.date = d.date;
		arr.time = d.time;

		arr = [arr];

		App._chosen = wallet;

		var request = window.indexedDB.open(wallet.name);
		var t = this;

		request.onsuccess = function(event) {
			var wallet_db = request.result;

			var mainStructure = App._data.walletStructure;
			mainStructure.name = wallet_db.name;
			var wallet = DB(mainStructure);
			App._wallet = wallet;
			App._wallet.initialize(function(){
				App.bank.populate('chosen_wallet', arr, callback);
			});
		};
	};

	Main.prototype.get_chosenWallet = function(obj, callback) {
		callback = (typeof callback === 'function') ? callback : function(){};

		this.a.bank.lastID('chosen_wallet', 'by_chosen', function(d){
			callback(obj, d);
		});
	};

	window._App = new Main();
})(App);

//Code thanks to Jake Trent
//http://rockycode.com/blog/addremove-classes-raw-javascript/

function hasClass(ele,cls) {
  return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

function addClass(ele,cls) {
  if (!hasClass(ele,cls)) ele.className += " "+cls;
}

function removeClass(ele,cls) {
  if (hasClass(ele,cls)) {
      var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
      ele.className=ele.className.replace(reg,' ');
  }
}

function datetoUTC(date){
	date = (typeof date === 'object' && date.hasOwnProperty('getFullYear') === true) ? date : new Date();
	var r = {};

	//Date and time
	var utc = date.toISOString();
	r.date = utc.match(/([0-9]{4}[-][0-9]{2}[-][0-9]{2})/gi)[0];
	r.time = utc.match(/[0-9]{2}[:][0-9]{2}[:][0-9]{2}[.]?[0-9]{0,3}/gi)[0];

	return r;
}<commit_msg>Fixed default category<commit_after>var App;

window.dhtmlHistory.create({
	toJSON: function(o) {
		return JSON.stringify(o);
	}
	, fromJSON: function(s) {
		return JSON.parse(s);
	}
});

(function(App){
	"use strict";
	var Main = function(){
		this.getConfig(function(r, t){
			var modules = Object.keys(r.modules)
			t.buildMenu(modules);

			t.start(r);
		});
	}

	/**
	 * Gets the main site configuration
	 * @return {json} Configuration
	 */
	Main.prototype.getConfig = function(callback) {
		var t = this;
		new Vi({url:'config.json', response: 'object'}).server(function(r){
			if(typeof callback === 'function'){
				callback(r, t);
			}
		});
	};

	Main.prototype.start = function(r) {
		var lang = this.browserLanguage();
		var modules = {};

		for(var k in r.modules){
			if(r.modules.hasOwnProperty(k)){
				modules[k] = {nombre: k, url:r.url};
			}
		}

		var j = {name: 'ExpMan', modules:modules, div:'#container', _div: '#container', currentLang: lang};
		this.a = new AppSystem(j);

		App = this.a;
		window.App = App;
		this.a._data = r;
		var t = this;

		this.initializeWallets(this, function(t){
			t.searchWallets(t, function(t){
				t.get_chosenWallet(t, function(t, chosen){
					dhtmlHistory.initialize();
					dhtmlHistory.addListener(t.handleHistory);

					var chosen_wallet = chosen;
					for(var i = 0, len = App.wallets.length; i < len; i++){
						var wallet = App.wallets[i];
						if(chosen !== null && chosen.idWallet === wallet.idWallet){
							chosen_wallet = wallet;
						}
					}

					t.openWallet(chosen_wallet, function(){
						t.a.init(function(){
							var initialModule = dhtmlHistory.getCurrentLocation();
							if(initialModule == '/' || initialModule == ''){
								t.loadCategory(t.chooseDefaultModule());
							}else{
								var c = initialModule.substr(1);
								t.loadCategory(t.chooseDefaultModule(c));
							}
						});
					});
				});
			});
		});
	};

	Main.prototype.chooseDefaultModule = function(module) {
		var def = (typeof module === 'undefined')  ? true : false;
		module = (typeof module === 'undefined') ? 'wallets' : module;
		if( typeof this.a._chosen === 'object' && def === true) {
			module = 'activities';
		} else if(typeof this.a._chosen !== 'object'){
			module = 'wallets';
		}

		return module;
	};

	Main.prototype.handleHistory = function(newLocation, historyData) {
		var category = newLocation.substr(1);
		_App._cat = category;
		if(typeof _App.a.current === 'object'){
			_App.loadCategory(category);
		}
	};

	Main.prototype.buildMenu = function(modules) {
		this.menu = document.getElementById('main-menu');
		for(var i = 0, len = modules.length; i < len; i++){
			var m = modules[i];
			var li = document.createElement('li');
			li.id = 'm-'+m;

			var a = document.createElement('a');
			a.setAttribute('data-ltag', m);
			a.setAttribute('data-module', m);

			li.appendChild(a);
			this.menu.appendChild(li);

			a._t = this;
			a.addEventListener('click', function(){
				var category = this.getAttribute('data-module');
				this._t.loadCategory(category);
			});
		}
	};

	Main.prototype.cleanMenuCategory = function() {
		var lis = document.querySelectorAll('#main-menu>li');
		for(var i = 0, len = lis.length; i < len; i++){
			var li = lis[i];
			li.className = '';
		}
	};

	Main.prototype.activeMenuCategory = function(category) {
		var el = document.getElementById('m-'+category);
		this.cleanMenuCategory();
		el.className = 'active';
	};

	Main.prototype.loadCategory = function(category) {
		dhtmlHistory.add('/'+category, {message: "Module " +category});
		this.activeMenuCategory(category);

		this.a.div = this.a._div;
		this.a.getModule(category);
		this.a.current.start();
	};

	Main.prototype.browserLanguage = function() {
		var lang = navigator.language || navigator.userLanguage;
		lang = lang.match(/([a-z]+)/gi);
		if(lang !== null){
			lang = lang[0];
		}

		var l = '';
		switch(lang){
			case 'es':
				l = lang;
			break;
			default:
			case 'en':
				l = lang;
			break;
		}

		return l;
	};

	//Initialize Wallets
	Main.prototype.initializeWallets = function(obj, callback){
		callback = (typeof callback !== 'function') ? function(){} : callback;

		var mainStructure = App._data.mainStructure;
		mainStructure.name = 'bank';
		var bank = DB(mainStructure);
		bank.initialize(function(){
			App.bank = bank;
			callback(obj);
		});
	}

	//Search for existing wallets
	Main.prototype.searchWallets = function(obj, callback){
		callback = (typeof callback !== 'function') ? function(){} : callback;

		this.a.bank.search('wallets', 'by_name', '', 'all', function(wallets){
			App.wallets = wallets;
			App._wallets = [];

			callback(obj);
		});
	}

	Main.prototype.openWallet = function(wallet, callback) {
		if(wallet === null){
			callback();

			return;
		}

		if(this.a._wallet !== undefined){
			delete this.a._wallet;
		}

		var d = datetoUTC();
		var arr = {idWallet: wallet.idWallet};
		arr.date = d.date;
		arr.time = d.time;

		arr = [arr];

		App._chosen = wallet;

		var request = window.indexedDB.open(wallet.name);
		var t = this;

		request.onsuccess = function(event) {
			var wallet_db = request.result;

			var mainStructure = App._data.walletStructure;
			mainStructure.name = wallet_db.name;
			var wallet = DB(mainStructure);
			App._wallet = wallet;
			App._wallet.initialize(function(){
				App.bank.populate('chosen_wallet', arr, callback);
			});
		};
	};

	Main.prototype.get_chosenWallet = function(obj, callback) {
		callback = (typeof callback === 'function') ? callback : function(){};

		this.a.bank.lastID('chosen_wallet', 'by_chosen', function(d){
			callback(obj, d);
		});
	};

	window._App = new Main();
})(App);

//Code thanks to Jake Trent
//http://rockycode.com/blog/addremove-classes-raw-javascript/

function hasClass(ele,cls) {
  return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

function addClass(ele,cls) {
  if (!hasClass(ele,cls)) ele.className += " "+cls;
}

function removeClass(ele,cls) {
  if (hasClass(ele,cls)) {
      var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
      ele.className=ele.className.replace(reg,' ');
  }
}

function datetoUTC(date){
	date = (typeof date === 'object' && date.hasOwnProperty('getFullYear') === true) ? date : new Date();
	var r = {};

	//Date and time
	var utc = date.toISOString();
	r.date = utc.match(/([0-9]{4}[-][0-9]{2}[-][0-9]{2})/gi)[0];
	r.time = utc.match(/[0-9]{2}[:][0-9]{2}[:][0-9]{2}[.]?[0-9]{0,3}/gi)[0];
	r.datetime = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),  date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());

	return r;
}<|endoftext|>


<commit_before>$(function() {

    // Start tooltip
    $('[data-toggle=tooltip]').tooltip();

});<commit_msg>Remove tooltip<commit_after>$(function() {

    //

});<|endoftext|>


<commit_before>// Add inverted rows to timeline
$(document).ready(function(){
  $(".timeline li:odd").addClass("timeline-inverted")
  var formURL = $("#contactForm").attr("action").value()
  formURL += "melvitax"
  formURL += "@"
  formURL += "me"
  formUEL += ".com"
  $("#contactForm").attr("action", formURL)
});

// Netlify CMS
if (window.netlifyIdentity) {
  window.netlifyIdentity.on("init", user => {
    if (!user) {
      window.netlifyIdentity.on("login", () => {
        document.location.href = "/admin/";
      });
    }
  });
}<commit_msg>corrected misspelling<commit_after>// Add inverted rows to timeline
$(document).ready(function(){
  $(".timeline li:odd").addClass("timeline-inverted")
  var formURL = $("#contactForm").attr("action")
  formURL += "melvitax"
  formURL += "@"
  formURL += "me"
  formURL += ".com"
  $("#contactForm").attr("action", formURL)
});

// Netlify CMS
if (window.netlifyIdentity) {
  window.netlifyIdentity.on("init", user => {
    if (!user) {
      window.netlifyIdentity.on("login", () => {
        document.location.href = "/admin/";
      });
    }
  });
}<|endoftext|>


<commit_before>var path = require('path');
var childProcess = require('child_process');

function gulp(task, callback) {
  return childProcess.exec([
    'node_modules/.bin/gulp',
    '--gulpfile', path.resolve(__dirname, 'fixtures', 'gulpfile.js'),
    task
  ].join(' '), callback);
}

describe('gulp-jasmine-browser', function() {
  it('works', function(done) {
    gulp('dummy', function(error, stdout) {
      expect(stdout).toContain('2 specs, 1 failure');
      done();
    });
  });
});
<commit_msg>Ensure that gulp does not return errors in integration test<commit_after>var path = require('path');
var childProcess = require('child_process');

function gulp(task, callback) {
  return childProcess.exec([
    'node_modules/.bin/gulp',
    '--gulpfile', path.resolve(__dirname, 'fixtures', 'gulpfile.js'),
    task
  ].join(' '), callback);
}

describe('gulp-jasmine-browser', function() {
  it('works', function(done) {
    gulp('dummy', function(error, stdout) {
      expect(error).toBe(null);
      expect(stdout).toContain('2 specs, 1 failure');
      done();
    });
  });
});
<|endoftext|>