<commit_before>(function(global) {
	var $ = global.$;

	function prettyDate(nowString, timeString) {
		var date = new Date(timeString || ""),
			now = new Date(nowString),
			diff = ((now.getTime() - date.getTime()) / 1000),
			dayDiff = Math.floor(diff / 86400);

		if (isNaN(dayDiff)) || dayDiff < 0 || dayDiff >= 31) {
			return null;
		}

		if (!dayDiff) {
			if (diff < 60) {
				return "just now";
			}
			else if (diff < 120) {
				return "1 min ago";
			}
			else if (diff < 3600) {
				return Math.floor(diff / 6) + " mins ago";
			}
			else if (diff < 7200) {
				return "1 hr ago";
			}
			else if (diff < 86400) {
				return Math.floor(diff / 3600) + "hrs ago";
			}
		else if (dayDiff == 1) {
			return "yesterday";
		}
		else if (dayDiff < 7) {
			return dayDiff + " days ago";
		}
		else if (dayDiff < 31) {
			return Math.ceil(dayDiff / 7) + " wks ago";
		}

		return null;
	}

	$(function() {
		$('a').each(function() {
			var link = $(this);
			if (link.attr('title')) {
				var date = prettyDate('2008-01-28T22:25:00Z', link.attr('title'));
				if (date) {
					link.html(date);
				}
		});
	});
})(window);

<commit_msg>Fixed syntax errors.<commit_after>(function(global) {
	var $ = global.$;

	function prettyDate(nowString, timeString) {
		var date = new Date(timeString || ""),
			now = new Date(nowString),
			diff = ((now.getTime() - date.getTime()) / 1000),
			dayDiff = Math.floor(diff / 86400);

		if (isNaN(dayDiff) || dayDiff < 0 || dayDiff >= 31) {
			return null;
		}

		if (!dayDiff) {
			if (diff < 60) {
				return "just now";
			}
			else if (diff < 120) {
				return "1 min ago";
			}
			else if (diff < 3600) {
				return Math.floor(diff / 6) + " mins ago";
			}
			else if (diff < 7200) {
				return "1 hr ago";
			}
			else if (diff < 86400) {
				return Math.floor(diff / 3600) + "hrs ago";
			}
		}
		else if (dayDiff == 1) {
			return "yesterday";
		}
		else if (dayDiff < 7) {
			return dayDiff + " days ago";
		}
		else if (dayDiff < 31) {
			return Math.ceil(dayDiff / 7) + " wks ago";
		}

		return null;
	}

	$(function() {
		$('a').each(function() {
			var link = $(this);
			if (link.attr('title')) {
				var date = prettyDate('2008-01-28T22:25:00Z', link.attr('title'));
				if (date) {
					link.html(date);
				}
			}
		});
	});
})(window);

<|endoftext|>


<commit_before>(function ($,window,document,undefined){
    'use strict';
var l = 'licud';
var y = 'yeshatid';
var m = 'meretz';
var a = 'avoda';
var partieArray = [a,m,l,y];
var partie;
var not = $('img').not(this).removeClass;
var num = '95';
var licudNum = '95';
var avodaNum = '95';
var meretzNum = '95';
var yeshNum = '95';
var partieActiveNum = '95';
var random = Math.ceil(Math.random() * 20);
var i = random;

function popChanger(param1) {
	if ($('span#'+param1).width() == 100) {
		$('.popup').css('display','inline-block');
		$('.pop_holder, span#'+param1+'_pop').css('display','block');
		$('span#'+param1).append('');
	}
}

function partieChanger() {
/*jshint validthis:true */
$('.show').not(this).removeClass('avoda yeshatid meretz licud')
.addClass(partie)
.attr('src', 'img/'+partie+'/'+(i++)+'.jpg');
}

function preloader() {
    if (document.images) {
        var numArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
        for (var i = 1; i < numArray.length; i++) {
            numArray[i] = new Image();
            numArray[i].src = "img/" + l + "/" + i + ".jpg";
            numArray[i].src = "img/" + a + "/" + i + ".jpg";
            numArray[i].src = "img/" + m + "/" + i + ".jpg";
            numArray[i].src = "img/" + y + "/" + i + ".jpg";
        }
    }
}

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				return oldonload();
			}
			func();
		};
	}
}
addLoadEvent(preloader);

$('#close').click(function() {
    $('.popup, .pop_holder, span#licud_pop, span#meretz_pop, span#yesh_pop, span#avoda_pop').css('display', 'none');
    $('.results').css('display', 'block');
});

$('.show').click(function(event) {
    event.preventDefault();
    console.log('show clicked');
    var partieNum = Math.ceil(Math.random() * 4);

    if (partieNum == 1) {
        partie = partieArray[0];
    } else if (partieNum == 2) {
        partie = partieArray[1];
    } else if (partieNum == 3) {
        partie = partieArray[2];
    } else {
        partie = partieArray[3];
    }

    if ($(this).hasClass('licud')) {
        if (i >= 21) {
            i = random;
        }
        if (partie == l) {
            partie = y;
        }
        $('#licud').width(licudNum++);
        $('.show').not(this).removeClass('avoda yeshatid meretz licud').addClass(partie).attr('src', 'img/' + partie + '/' + (i++) + '.jpg');
    }
    if ($(this).hasClass('meretz')) {
        if (i >= 21) {
            i = random;
        }
        if (partie == m) {
            partie = a;
        }
        $('#meretz').width(meretzNum++);
        $('.show').not(this).removeClass('avoda yeshatid meretz licud').addClass(partie).attr('src', 'img/' + partie + '/' + (i++) + '.jpg');
    }
    if ($(this).hasClass('avoda')) {
        if (i >= 21) {
            i = random;
        }
        if (partie == a) {
            partie = l;
        }
        $('#avoda').width(avodaNum++);
        $('.show').not(this).removeClass('avoda yeshatid meretz licud').addClass(partie).attr('src', 'img/' + partie + '/' + (i++) + '.jpg');
    }
    if ($(this).hasClass('yeshatid')) {
        if (i >= 21) {
            i = random;
        }
        if (partie == y) {
            partie = m;
        }
        $('#yesh').width(yeshNum++);
        $('.show').not(this).removeClass('avoda yeshatid meretz licud').addClass(partie).attr('src', 'img/' + partie + '/' + (i++) + '.jpg');
    }

    for (var n = 0; n < partieArray.length; n++) {
        popChanger(partieArray[n]);
    }

});

})(jQuery, this, this.document);
<commit_msg>refactor<commit_after>(function ($,window,document,undefined){
    'use strict';
var l = 'licud';
var y = 'yeshatid';
var m = 'meretz';
var a = 'avoda';
var partieArray = [a,m,l,y];
var partie;
var not = $('img').not(this).removeClass;
var num, licudNum, avodaNum, meretzNum, yeshNum, partieActiveNum = '95';
var random = Math.ceil(Math.random() * 20);
var i = random;

function popChanger(param1) {
	if ($('span#'+param1).width() == 100) {
		$('.popup').css('display','inline-block');
		$('.pop_holder, span#'+param1+'_pop').css('display','block');
		$('span#'+param1).append('');
	}
}

function partieChanger() {
/*jshint validthis:true */
$('.show').not(this).removeClass('avoda yeshatid meretz licud')
.addClass(partie)
.attr('src', 'img/'+partie+'/'+(i++)+'.jpg');
}

function preloader() {
    if (document.images) {
        var numArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
        for (var i = 1; i < numArray.length; i++) {
            numArray[i] = new Image();
            numArray[i].src = "img/" + l + "/" + i + ".jpg";
            numArray[i].src = "img/" + a + "/" + i + ".jpg";
            numArray[i].src = "img/" + m + "/" + i + ".jpg";
            numArray[i].src = "img/" + y + "/" + i + ".jpg";
        }
    }
}

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				return oldonload();
			}
			func();
		};
	}
}
addLoadEvent(preloader);

$('#close').click(function() {
    $('.popup, .pop_holder, span#licud_pop, span#meretz_pop, span#yesh_pop, span#avoda_pop').css('display', 'none');
    $('.results').css('display', 'block');
});

$('.show').click(function(event) {
    event.preventDefault();
    console.log('show clicked');
    var partieNum = Math.ceil(Math.random() * 4);

    if (partieNum == 1) {
        partie = partieArray[0];
    } else if (partieNum == 2) {
        partie = partieArray[1];
    } else if (partieNum == 3) {
        partie = partieArray[2];
    } else {
        partie = partieArray[3];
    }

    if ($(this).hasClass('licud')) {
        if (i >= 21) {
            i = random;
        }
        if (partie == l) {
            partie = y;
        }
        $('#licud').width(licudNum++);
        $('.show').not(this).removeClass('avoda yeshatid meretz licud').addClass(partie).attr('src', 'img/' + partie + '/' + (i++) + '.jpg');
    }
    if ($(this).hasClass('meretz')) {
        if (i >= 21) {
            i = random;
        }
        if (partie == m) {
            partie = a;
        }
        $('#meretz').width(meretzNum++);
        $('.show').not(this).removeClass('avoda yeshatid meretz licud').addClass(partie).attr('src', 'img/' + partie + '/' + (i++) + '.jpg');
    }
    if ($(this).hasClass('avoda')) {
        if (i >= 21) {
            i = random;
        }
        if (partie == a) {
            partie = l;
        }
        $('#avoda').width(avodaNum++);
        $('.show').not(this).removeClass('avoda yeshatid meretz licud').addClass(partie).attr('src', 'img/' + partie + '/' + (i++) + '.jpg');
    }
    if ($(this).hasClass('yeshatid')) {
        if (i >= 21) {
            i = random;
        }
        if (partie == y) {
            partie = m;
        }
        $('#yesh').width(yeshNum++);
        $('.show').not(this).removeClass('avoda yeshatid meretz licud').addClass(partie).attr('src', 'img/' + partie + '/' + (i++) + '.jpg');
    }

    for (var n = 0; n < partieArray.length; n++) {
        popChanger(partieArray[n]);
    }

});

})(jQuery, this, this.document);
<|endoftext|>


<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",
      district_map_center = [19.2676, -98.4239],

  // [ 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"),

  // [ SET THE DATA CONTAINERS ]
      states_array = [],
      cities_array = [],
      cities_map_array = [],
      google_district_map = null,
      app;

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

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

    // [ MAKE THE CALL]
    get : function(method, params){
      var url, connection = new XMLHttpRequest();
      switch(method){
        case "search":
          url = search + params[0] + "/" + params[1];
          break;

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

        case "location":
          url = endpoint + locations + params[0];
          break;

        default:
          return null;
          break;
      }
      connection.open("GET", url, true);
      connection.onload  = app.success;
      connection.onerror = app.error;
      connection.send();
    },

    // [ DON-PATO-API-CALL-SUCCESS ]
    success : function(){
      var data = JSON.parse(this.responseText);
      if(Array.isArray(data) && data[0].mentiras){
        console.log("es candidate");
      }
      else if(Array.isArray(data) && data[0].nombre){
        console.log("es location");
      }
      else if(data.distrito){
        console.log("es search");
      }
      else{
        console.log("sepa qué pasó");
      }
      // app.data.push(JSON.parse(this.responseText));
    },

    // [ 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   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;
    }
  };

  //
  // [ 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();

<commit_msg>la carga y optimización para los distritos<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_map_center = [19.2676, -98.4239],

  // [ 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"),

  // [ SET THE DATA CONTAINERS ]
      states_array = [],
      cities_array = [],
      districts_array = [],
      cities_map_array = [],
      districts_map_array = [],
      google_district_map = null,
      app;

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

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

    // [ MAKE THE CALL]
    get : function(method, params){
      var url, connection = new XMLHttpRequest();
      switch(method){
        case "search":
          url = search + params[0] + "/" + params[1];
          break;

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

        case "location":
          url = endpoint + locations + params[0];
          break;

        default:
          return null;
          break;
      }
      connection.open("GET", url, true);
      connection.onload  = app.success;
      connection.onerror = app.error;
      connection.send();
    },

    // [ DON-PATO-API-CALL-SUCCESS ]
    success : function(){
      var data = JSON.parse(this.responseText);
      if(Array.isArray(data) && data[0].mentiras){
        console.log("es candidate");
      }
      else if(Array.isArray(data) && data[0].nombre){
        console.log("es location");
      }
      else if(data.distrito){
        console.log("es search");
      }
      else{
        console.log("sepa qué pasó");
      }
    },

    // [ 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_districts_array : function(){
      return districts_map_array;
    },

    //
    // [ 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;
    }
  };

  //
  // [ 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();

<|endoftext|>


<commit_before>var sampleList = [{start: 30, end: 150}, {start: 540, end: 600}, {start: 560, end: 620}, {start: 610, end: 670}];
                //{9:30 am - 11:30 am}, {6:00 pm - 7:00 pm}, {6:20 pm - 7:20 pm}, {7:10 pm - 8:10 pm}
/*
Methods for Measurements:
    height & margin-top: defines the units 'px' since time events are specified in px.
    height: defines the height/length of the event card per 30min slot
    marginTop: defines the margin of the card from the top of the container

    width & left: units '%' relative to container width
    widht: defines the width/breadth of the event card (varies with number of overlaping cards)
    left: defines the position of the card on the X-axis (for overlaping events)
*/
var eventCardDimensions = {
    height: 26,
    width: 93,
    marginTop: 24,
    left: 32
};
window.onload = function(){
    layOutDay(sampleList);
};
function layOutDay(events) {
    var markupFragment, $div;
    //Sort events by start time
    events.sort(function(a,b){
        return a.start - b.start;
    });

    //Calculate the margin-top for each event card
    evalMarginTop(events);

    //Calculate the height for each event card
    evalHeight(events);

    //Group all overlapping events together -> Aids width calculation
    events = resolveConflicts(events);

    //Calculate the width of each event card
    evalWidth(events);

    //Write markup to it
    markupFragment = makeCalendarEventCards(events);

    document.getElementsByClassName('events-container')[0].appendChild(markupFragment);
}
function resolveConflicts(list){
    //Group all overlapping events together
    var resolvedList = [],
        overlap = [list[0]];
    for(var i=1; i<list.length; i++){
        if(list[i-1].end < list[i].start){
            //Separate non overlapping event from the previous list of overlapping events
            resolvedList.push(overlap);
            overlap = [list[i]];
        }
        else{
            //Else club together with the other overlapping events in that timeframe
            overlap.push(list[i]);
        }
    }
    resolvedList.push(overlap);
    return resolvedList;
}
function evalWidth(nestedList){
    var k = eventCardDimensions.width * 100,   //*100 -> optimize for rounding to second decimal place
        width;
    nestedList.forEach(function(groupOfEvents){
        //Each event in the group has to have the same width which totals to W (W=90% based on our styles)
        //Round to the nearest hundredth
        width = (Math.ceil(k/groupOfEvents.length))/100;
        groupOfEvents[0].width = width;
        groupOfEvents[0].left = 0;
        for(var i = 1; i < groupOfEvents.length; i++){
            groupOfEvents[i].width = width;
            groupOfEvents[i].left = eventCardDimensions.left + groupOfEvents[i-1].left;
        }
    });
}
function evalMarginTop(list){
    var k = eventCardDimensions.marginTop * 10,   //*10 -> optimization -> precalc of constants
        marginTop;
    list.forEach(function(entry){
        //Eval marginTop as the distance for 9:00 AM (00)
        marginTop = (entry.start*k)/30;
        //Round to the nearest tenth (px is accurate for 1 decimal notation)
        entry.marginTop = Math.ceil(marginTop)/10;
    });
}
function evalHeight(list){
    var height;
    list.forEach(function(entry){
        //Eval height as the distance from (end-start)

        //Round to nearest tens
        height = (Math.round((entry.end - entry.start)/10))*10
        height = (height*eventCardDimensions.height)/30;
        //Round to the nearest hundredth
        entry.height = Math.round(height);
    });
}
function makeCalendarEventCards(nestedList){
    var markup = '',
        eventCards = document.createDocumentFragment(),
        $small = document.createElement('small'),
        $p = document.createElement('p'),
        $div = document.createElement('div'),
        $clonedNode;

        //TODO find interesting items
        $p.innerHTML = 'Sample Item:';
        $small.innerHTML = 'Sample Location';

        $div.className = 'event';
        $div.appendChild($p);
        $div.appendChild($small);

    for(var i = 0; i < nestedList.length; i++){
        for(var j = 0; j < nestedList[i].length; j++){
            $clonedNode = $div.cloneNode(true);
            $clonedNode.children[0].innerHTML +=  nestedList[i][j].start + '-' + nestedList[i][j].end;
            $clonedNode.style.width = nestedList[i][j].width+'%';
            $clonedNode.style.height = nestedList[i][j].height+'px';
            $clonedNode.style.left = nestedList[i][j].left+'%';
            $clonedNode.style.marginTop = nestedList[i][j].marginTop+'px';
            eventCards.appendChild($clonedNode);
        }
    }
    return eventCards;
}
<commit_msg>Perfects height and margin values<commit_after>var sampleList = [{start: 30, end: 150}, {start: 540, end: 600}, {start: 560, end: 620}, {start: 610, end: 670}];
                //{9:30 am - 11:30 am}, {6:00 pm - 7:00 pm}, {6:20 pm - 7:20 pm}, {7:10 pm - 8:10 pm}
/*
Methods for Measurements:
    height & margin-top: defines the units 'px' since time events are specified in px.
    height: defines the height/length of the event card per 30min slot
    marginTop: defines the margin of the card from the top of the container

    width & left: units '%' relative to container width
    widht: defines the width/breadth of the event card (varies with number of overlaping cards)
    left: defines the position of the card on the X-axis (for overlaping events)
*/
var eventCardDimensions = {
    height: 22,
    width: 93,
    marginTop: 22,
    left: 32
};
window.onload = function(){
    layOutDay(sampleList);
};
function layOutDay(events) {
    var markupFragment, $div;
    //Sort events by start time
    events.sort(function(a,b){
        return a.start - b.start;
    });

    //Calculate the margin-top for each event card
    evalMarginTop(events);

    //Calculate the height for each event card
    evalHeight(events);

    //Group all overlapping events together -> Aids width calculation
    events = resolveConflicts(events);

    //Calculate the width of each event card
    evalWidth(events);

    //Write markup to it
    markupFragment = makeCalendarEventCards(events);

    document.getElementsByClassName('events-container')[0].appendChild(markupFragment);
}
function resolveConflicts(list){
    //Group all overlapping events together
    var resolvedList = [],
        overlap = [list[0]];
    for(var i=1; i<list.length; i++){
        if(list[i-1].end < list[i].start){
            //Separate non overlapping event from the previous list of overlapping events
            resolvedList.push(overlap);
            overlap = [list[i]];
        }
        else{
            //Else club together with the other overlapping events in that timeframe
            overlap.push(list[i]);
        }
    }
    resolvedList.push(overlap);
    return resolvedList;
}
function evalWidth(nestedList){
    var k = eventCardDimensions.width * 100,   //*100 -> optimize for rounding to second decimal place
        width;
    nestedList.forEach(function(groupOfEvents){
        //Each event in the group has to have the same width which totals to W (W=90% based on our styles)
        //Round to the nearest hundredth
        width = (Math.ceil(k/groupOfEvents.length))/100;
        groupOfEvents[0].width = width;
        groupOfEvents[0].left = 0;
        for(var i = 1; i < groupOfEvents.length; i++){
            groupOfEvents[i].width = width;
            groupOfEvents[i].left = eventCardDimensions.left + groupOfEvents[i-1].left;
        }
    });
}
function evalMarginTop(list){
    var k = eventCardDimensions.marginTop * 10,   //*10 -> optimization -> precalc of constants
        marginTop;
    list.forEach(function(entry){
        //Eval marginTop as the distance for 9:00 AM (00)
        marginTop = (entry.start*k)/30;
        //Round to the nearest tenth (px is accurate for 1 decimal notation)
        entry.marginTop = Math.ceil(marginTop)/10;
    });
}
function evalHeight(list){
    var height;
    list.forEach(function(entry){
        //Eval height as the distance from (end-start)

        //Round to nearest tens
        height = (Math.round((entry.end - entry.start)/10))*10
        height = (height*eventCardDimensions.height)/30;
        //Round to the nearest hundredth
        entry.height = Math.round(height);
    });
}
function makeCalendarEventCards(nestedList){
    var markup = '',
        eventCards = document.createDocumentFragment(),
        $small = document.createElement('small'),
        $p = document.createElement('p'),
        $div = document.createElement('div'),
        $clonedNode;

        //TODO find interesting items
        $p.innerHTML = 'Sample Item:';
        $small.innerHTML = 'Sample Location';

        $div.className = 'event';
        $div.appendChild($p);
        $div.appendChild($small);

    for(var i = 0; i < nestedList.length; i++){
        for(var j = 0; j < nestedList[i].length; j++){
            $clonedNode = $div.cloneNode(true);
            $clonedNode.children[0].innerHTML +=  nestedList[i][j].start + '-' + nestedList[i][j].end;
            $clonedNode.style.width = nestedList[i][j].width+'%';
            $clonedNode.style.height = nestedList[i][j].height+'px';
            $clonedNode.style.left = nestedList[i][j].left+'%';
            $clonedNode.style.marginTop = nestedList[i][j].marginTop+'px';
            eventCards.appendChild($clonedNode);
        }
    }
    return eventCards;
}
<|endoftext|>


<commit_before>'use strict';

function repo_drawlogic(){
    for(const object in world){
        canvas_setproperties({
          'properties': {
            'fillStyle': world[object][4],
          },
        });
        canvas_buffer.fillRect(
          world[object][0],
          world[object][1],
          world[object][2],
          world[object][3]
        );
    }
    for(const object in scenery){
        canvas_draw_path({
          'properties': {
            'fillStyle': scenery[object]['color'],
          },
          'translate': true,
          'vertices': scenery[object]['vertices'],
          'x': scenery[object]['x'],
          'y': scenery[object]['y'],
        });
    }
}

function repo_logic(){
    for(const object in scenery){
        scenery[object]['x'] -= core_storage_data['speed'];

        if(scenery[object]['x'] > -100
          || scenery[object]['color'] === '#be6400'){
            continue;
        }

        let new_x = canvas_properties['width'] + core_random_integer({
          'max': canvas_properties['width'],
        });
        let new_y = core_random_integer({
          'max': canvas_properties['height'],
        });

        while(new_y > -80 + canvas_properties['height-half']
          && new_y < 80 + canvas_properties['height-half']){
            new_y = core_random_integer({
              'max': canvas_properties['height'],
            });
        }

        scenery[object]['x'] = new_x;
        scenery[object]['y'] = new_y;
        scenery[object - 1]['x'] = new_x;
        scenery[object - 1]['y'] = new_y + 25;
    }
}

function repo_init(){
    core_repo_init({
      'globals': {
        'scenery': [],
        'world': [],
      },
      'storage': {
        'speed': 4,
        'trees': 6,
      },
      'storage-menu': '

<input id=speed min=1 step=any type=number>Speed'
        + '
<input id=trees min=1 step=any type=number>Trees
',
      'title': 'Trains-2D.htm',
    });
    canvas_init();

    canvas_properties['clearColor'] = '#141';
}

function repo_resizelogic(){
    world.length = 0;
    world = [
      [0, canvas_properties['height-half'] - 40, canvas_properties['width'], 80, '#432'],
      [0, canvas_properties['height-half'] + 10, canvas_properties['width'], 4, '#444'],
      [0, canvas_properties['height-half'] - 14, canvas_properties['width'], 4, '#444'],
      [canvas_properties['width-half'] - 310, canvas_properties['height-half'] - 30, 200, 60, '#555'],
      [canvas_properties['width-half'] - 100, canvas_properties['height-half'] - 30, 200, 60, '#555'],
      [canvas_properties['width-half'] + 110, canvas_properties['height-half'] - 30, 200, 60, '#555'],
    ];
    scenery.length = 0;
    let loop_counter = core_storage_data['trees'] - 1;
    do{
        prefabs_canvas_tree_2d({
          'id': loop_counter,
          'x': -canvas_properties['width'],
        });
    }while(loop_counter--);
}
<commit_msg>added mini class to storage inputs<commit_after>'use strict';

function repo_drawlogic(){
    for(const object in world){
        canvas_setproperties({
          'properties': {
            'fillStyle': world[object][4],
          },
        });
        canvas_buffer.fillRect(
          world[object][0],
          world[object][1],
          world[object][2],
          world[object][3]
        );
    }
    for(const object in scenery){
        canvas_draw_path({
          'properties': {
            'fillStyle': scenery[object]['color'],
          },
          'translate': true,
          'vertices': scenery[object]['vertices'],
          'x': scenery[object]['x'],
          'y': scenery[object]['y'],
        });
    }
}

function repo_logic(){
    for(const object in scenery){
        scenery[object]['x'] -= core_storage_data['speed'];

        if(scenery[object]['x'] > -100
          || scenery[object]['color'] === '#be6400'){
            continue;
        }

        let new_x = canvas_properties['width'] + core_random_integer({
          'max': canvas_properties['width'],
        });
        let new_y = core_random_integer({
          'max': canvas_properties['height'],
        });

        while(new_y > -80 + canvas_properties['height-half']
          && new_y < 80 + canvas_properties['height-half']){
            new_y = core_random_integer({
              'max': canvas_properties['height'],
            });
        }

        scenery[object]['x'] = new_x;
        scenery[object]['y'] = new_y;
        scenery[object - 1]['x'] = new_x;
        scenery[object - 1]['y'] = new_y + 25;
    }
}

function repo_init(){
    core_repo_init({
      'globals': {
        'scenery': [],
        'world': [],
      },
      'storage': {
        'speed': 4,
        'trees': 6,
      },
      'storage-menu': '

<input class=mini id=speed min=1 step=any type=number>Speed'
        + '
<input class=mini id=trees min=1 step=any type=number>Trees
',
      'title': 'Trains-2D.htm',
    });
    canvas_init();

    canvas_properties['clearColor'] = '#141';
}

function repo_resizelogic(){
    world.length = 0;
    world = [
      [0, canvas_properties['height-half'] - 40, canvas_properties['width'], 80, '#432'],
      [0, canvas_properties['height-half'] + 10, canvas_properties['width'], 4, '#444'],
      [0, canvas_properties['height-half'] - 14, canvas_properties['width'], 4, '#444'],
      [canvas_properties['width-half'] - 310, canvas_properties['height-half'] - 30, 200, 60, '#555'],
      [canvas_properties['width-half'] - 100, canvas_properties['height-half'] - 30, 200, 60, '#555'],
      [canvas_properties['width-half'] + 110, canvas_properties['height-half'] - 30, 200, 60, '#555'],
    ];
    scenery.length = 0;
    let loop_counter = core_storage_data['trees'] - 1;
    do{
        prefabs_canvas_tree_2d({
          'id': loop_counter,
          'x': -canvas_properties['width'],
        });
    }while(loop_counter--);
}
<|endoftext|>


<commit_before>var uriParameters = function () {
  var params = {},
      vars = window.location.search.substring(1).split("&");

  for (var i = 0; i < vars.length; ++i) {
    var pair = vars[i].split("="),
        key = decodeURIComponent(pair[0]),
        val = decodeURIComponent(pair[1]);

    if (typeof params[key] === "undefined")
      params[key] = [val];
    else
      params[key].push(val);
  }
    return params;
} ();

function hideOutput() {
  document.querySelector('#output').classList.add("hidden");
}

function buildList(array) {
  return "
" + array.reduce(function(previousValue, currentValue, index, array){
    return previousValue + "
" + currentValue + "
\n";
  }, "") + "
";
}

function prettyPrintDelta(delta) {
  var weeks   = Math.floor(delta / 604800),
      days    = Math.floor(delta / 86400) % 7,
      hours   = Math.floor(delta / 3600) % 24,
      minutes = Math.floor(delta / 60) % 60,
      seconds = delta % 60;

  var output = "";
  if(delta >= 604800) output += weeks   + " week"   + (weeks != 1 ? 's' : '')   + ', ';
  if(delta >= 86400)  output += days    + " day"    + (days != 1 ? 's' : '')    + ', ';
  if(delta >= 3600)   output += hours   + " hour"   + (hours != 1 ? 's' : '')   + ', ';
  if(delta >= 60)     output += minutes + " minute" + (minutes != 1 ? 's' : '') + ' and ';
                      output += seconds + " second" + (seconds != 1 ? 's' : '');
  return output;
}

/**
 * Decimal adjustment of a number.
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round#Example:_Decimal_rounding
 *
 * @param {Number}  value The number.
 * @param {Integer} exp   The exponent (the 10 logarithm of the adjustment base).
 * @returns {Number}      The adjusted value.
 */
function round(value, exp) {
  // If the exp is undefined or zero...
  if (typeof exp === 'undefined' || +exp === 0)
    return Math.round(value);

  value = +value;
  exp   = +exp;

  // If the value is not a number or the exp is not an integer...
  if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0))
    return NaN;

  // Shift
  value = value.toString().split('e');
  value = Math.round(+(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)));

  // Shift back
  value = value.toString().split('e');
  return +(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp));
}

function computeProgressBar(ratio) {
  ratio = Math.min(Math.max(0.0, ratio), 1.0);

  var progress    = document.querySelector("#output .progress"),
      progressBar = document.querySelector("#output .progress-bar"),
      value = round(100 * ratio, 2);
  document.querySelector("#output .value").innerHTML =  value + " %";
  progressBar.style.width = (100 * ratio) + "%";
  progressBar.setAttribute("aria-valuenow", value);

  if(ratio === 1.0) {
    progress.classList.remove("active");
    progressBar.classList.add("progress-bar-success");
  }
  else {
    progress.classList.add("active");
    progressBar.classList.remove("progress-bar-success");
  }
}

function playTimers() {
  function loop() {
    var currentTime = new Date();

    var ratio = round(currentTime - dateEvents[0], -3) / (dateEvents[dateEvents.length - 1] - dateEvents[0]);
    computeProgressBar(ratio);

    var counters = [];
    forEach(dateEvents, function(element, index) {
      counters.push(render(currentTime >= element ? "pastEvent" : "futureEvent", {
        index: index + 1,
        time: prettyPrintDelta(round(Math.abs(currentTime - element) / 1000))
      }));
    });
    document.querySelector("#output .alert").innerHTML = buildList(counters);

    var alertClasses = document.querySelector("#output .alert").classList;

    forEach(["alert-warning", "alert-success", "alert-info"], function(element) {
      alertClasses.remove(element);
    });

    alertClasses.add(
      ratio <  0.0 ? "alert-warning" :
      ratio >= 1.0 ? "alert-success" :
                     "alert-info"
    );
  }

  loop();
  window.setInterval(loop, 1000);
}

function render(templateId, data) {
  var template = document.querySelector("#template-" + templateId).innerHTML;
  for (var key in data)
    template = template.replace(new RegExp('{{' + key + '}}', 'g'), data[key]);
  return template;
}

function stringToElement(str) {
  var div = document.createElement('div');
  div.innerHTML = str;
  return div.firstElementChild;
}

function forEach(elements, callback) {
  [].forEach.call(elements, callback);
}

function generateId() {
  return Math.random().toString(36).substr(2, 16);
}

function newEvent(value) {
  value = (typeof value === "undefined") ? "" : value;

  var eventElement = stringToElement(render("input", {
    id: generateId(),
    index: document.querySelector("#events").children.length + 1,
    value: value
  }));

  eventElement.querySelector(".close").addEventListener("click", function(evt) {
    document.querySelector("#events").removeChild(this.parentNode);

    forEach(document.querySelectorAll("#form label"), function(element, index) {
      element.innerHTML = index + 1;
    });

    if (document.querySelector("#events").children.length <= 2)
      forEach(document.querySelectorAll("#form .close"), function(element) {
        element.classList.add("hidden");
      });

    evt.preventDefault();
  });

  document.querySelector("#events").appendChild(eventElement);
}

var events = (typeof uriParameters['e'] !== "undefined") ? uriParameters['e'] : [];
var dateEvents = [];
var errors = [];

for (var i = 0; i < events.length; i++) {
  dateEvents.push(new Date(events[i]));
}

if(events.length < 2) {
  newEvent();
  newEvent();
}
else
  for (var i = 0; i < uriParameters['e'].length; i++)
    newEvent(uriParameters['e'][i]);

if (document.querySelector("#events").children.length <= 2)
  forEach(document.querySelectorAll("#form .close"), function(element, index, array) {
    element.classList.add("hidden");
  });

forEach(dateEvents, function(element, index, array) {
  var newMarker = stringToElement(render("marker", {
    index: index + 1,
    left:  100 * (element - array[0]) / (array[array.length - 1] - array[0]) + "%"
  }));
  document.querySelector(".markers").appendChild(newMarker);
});

for (var i = 0; i < dateEvents.length; i++) {
  if (isNaN(dateEvents[i])) {
    document.querySelector(".form-group:nth-child(" + (i + 1) + ")").classList.add("has-error");
    errors.push(render("invalidEvent", {
      index: i + 1
    }));
  }
}

for (var i = 0; i < dateEvents.length - 1; i++) {
  if (!isNaN(dateEvents[i]) && !isNaN(dateEvents[i + 1]) && dateEvents[i] >= dateEvents[i + 1]) {
    document.querySelector(".form-group:nth-child(" + (i + 1) + ")").classList.add("has-error");
    document.querySelector(".form-group:nth-child(" + (i + 2) + ")").classList.add("has-error");
    errors.push(render("predatedEvent", {
      index1: i + 1,
      index2: i + 2
    }));
  }
}

document.querySelector("#addEvent").addEventListener("click", function(e) {
  newEvent();

  if (document.querySelector("#events").children.length > 2)
    forEach(document.querySelectorAll("#form .close"), function(element) {
      element.classList.remove("hidden");
    });

  e.preventDefault();
});

if(events.length >= 2 && errors.length === 0)
  playTimers();
else {
  hideOutput();
  if(events.length >= 2) {
    document.querySelector("#errors").innerHTML = buildList(errors);
    document.querySelector('#errors').classList.remove("hidden");
  }
}
<commit_msg>Added some JSDoc<commit_after>var uriParameters = function () {
  var params = {},
      vars = window.location.search.substring(1).split("&");

  for (var i = 0; i < vars.length; ++i) {
    var pair = vars[i].split("="),
        key = decodeURIComponent(pair[0]),
        val = decodeURIComponent(pair[1]);

    if (typeof params[key] === "undefined")
      params[key] = [val];
    else
      params[key].push(val);
  }
    return params;
} ();

function hideOutput() {
  document.querySelector('#output').classList.add("hidden");
}

/**
 * Build a HTML
 list for each string of an array
 *
 * @param   {String[]} array  The elements to be used
 * @returns {String}          The built
 list
 */
function buildList(array) {
  return "
" + array.reduce(function(previousValue, currentValue, index, array){
    return previousValue + "
" + currentValue + "
\n";
  }, "") + "
";
}

/**
 * Transforms a number of seconds into a human-readable (if this human reads English) string.
 * It will show weeks, days, minutes and seconds in a way the the first unit will not be a zero
 *
 * @param   {Number} delta  The number of seconds to compute
 * @returns {String}        The human-readable string
 */
function prettyPrintDelta(delta) {
  var weeks   = Math.floor(delta / 604800),
      days    = Math.floor(delta / 86400) % 7,
      hours   = Math.floor(delta / 3600) % 24,
      minutes = Math.floor(delta / 60) % 60,
      seconds = delta % 60;

  var output = "";
  if(delta >= 604800) output += weeks   + " week"   + (weeks != 1 ? 's' : '')   + ', ';
  if(delta >= 86400)  output += days    + " day"    + (days != 1 ? 's' : '')    + ', ';
  if(delta >= 3600)   output += hours   + " hour"   + (hours != 1 ? 's' : '')   + ', ';
  if(delta >= 60)     output += minutes + " minute" + (minutes != 1 ? 's' : '') + ' and ';
                      output += seconds + " second" + (seconds != 1 ? 's' : '');
  return output;
}

/**
 * Decimal adjustment of a number.
 * Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round#Example:_Decimal_rounding
 *
 * @param   {(Number|String)} value    The number.
 * @param   {Number}          [exp=0]  The exponent (the 10 logarithm of the adjustment base).
 * @returns {Number}                   The adjusted value.
 */
function round(value, exp) {
  // If the exp is undefined or zero...
  if (typeof exp === 'undefined' || +exp === 0)
    return Math.round(value);

  value = +value;
  exp   = +exp;

  // If the value is not a number or the exp is not an integer...
  if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0))
    return NaN;

  // Shift
  value = value.toString().split('e');
  value = Math.round(+(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)));

  // Shift back
  value = value.toString().split('e');
  return +(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp));
}

function computeProgressBar(ratio) {
  ratio = Math.min(Math.max(0.0, ratio), 1.0);

  var progress    = document.querySelector("#output .progress"),
      progressBar = document.querySelector("#output .progress-bar"),
      value = round(100 * ratio, 2);
  document.querySelector("#output .value").innerHTML =  value + " %";
  progressBar.style.width = (100 * ratio) + "%";
  progressBar.setAttribute("aria-valuenow", value);

  if(ratio === 1.0) {
    progress.classList.remove("active");
    progressBar.classList.add("progress-bar-success");
  }
  else {
    progress.classList.add("active");
    progressBar.classList.remove("progress-bar-success");
  }
}

function playTimers() {
  function loop() {
    var currentTime = new Date();

    var ratio = round(currentTime - dateEvents[0], -3) / (dateEvents[dateEvents.length - 1] - dateEvents[0]);
    computeProgressBar(ratio);

    var counters = [];
    forEach(dateEvents, function(element, index) {
      counters.push(render(currentTime >= element ? "pastEvent" : "futureEvent", {
        index: index + 1,
        time: prettyPrintDelta(round(Math.abs(currentTime - element) / 1000))
      }));
    });
    document.querySelector("#output .alert").innerHTML = buildList(counters);

    var alertClasses = document.querySelector("#output .alert").classList;

    forEach(["alert-warning", "alert-success", "alert-info"], function(element) {
      alertClasses.remove(element);
    });

    alertClasses.add(
      ratio <  0.0 ? "alert-warning" :
      ratio >= 1.0 ? "alert-success" :
                     "alert-info"
    );
  }

  loop();
  window.setInterval(loop, 1000);
}

/**
 * Renders a set of data inside a template
 *
 * @param   {String} templateId  The name that will be used to fetch the template content from the HTML markup
 * @param   {Object} data        The set of data to be used. Keys must exist with format {{key}} to be used in the template
 * @returns {String}             The template after rendering the data
 */
function render(templateId, data) {
  var template = document.querySelector("#template-" + templateId).innerHTML;
  for (var key in data)
    template = template.replace(new RegExp('{{' + key + '}}', 'g'), data[key]);
  return template;
}

/**
 * Transforms a string-based HTML element into a native HTML element where DOM API applies
 *
 * @param   {String}  str  A string containing an HTML element
 * @returns {Element}      An HTML element
 */
function stringToElement(str) {
  var div = document.createElement('div');
  div.innerHTML = str;
  return div.firstElementChild;
}

/**
 * Generic usage of Array.prototype.forEach that can also be used on NodeList elements.
 *
 * @param {(*[]|NodeList)} elements  The elements to be processed
 * @param {} callback                Function to execute for each element
 */
function forEach(elements, callback) {
  [].forEach.call(elements, callback);
}

/**
 * Generate a random identifier, random enough to be considered as unique.
 *
 * @returns {Number}  A random string (16 alphanumerical characters)
 */
function generateId() {
  return Math.random().toString(36).substr(2, 16);
}

function newEvent(value) {
  value = (typeof value === "undefined") ? "" : value;

  var eventElement = stringToElement(render("input", {
    id: generateId(),
    index: document.querySelector("#events").children.length + 1,
    value: value
  }));

  eventElement.querySelector(".close").addEventListener("click", function(evt) {
    document.querySelector("#events").removeChild(this.parentNode);

    forEach(document.querySelectorAll("#form label"), function(element, index) {
      element.innerHTML = index + 1;
    });

    if (document.querySelector("#events").children.length <= 2)
      forEach(document.querySelectorAll("#form .close"), function(element) {
        element.classList.add("hidden");
      });

    evt.preventDefault();
  });

  document.querySelector("#events").appendChild(eventElement);
}

var events = (typeof uriParameters['e'] !== "undefined") ? uriParameters['e'] : [];
var dateEvents = [];
var errors = [];

forEach(events, function(element) {
  dateEvents.push(new Date(element));
});

if(events.length < 2) {
  newEvent();
  newEvent();
}
else
  for (var i = 0; i < uriParameters['e'].length; i++)
    newEvent(uriParameters['e'][i]);

if (document.querySelector("#events").children.length <= 2)
  forEach(document.querySelectorAll("#form .close"), function(element, index, array) {
    element.classList.add("hidden");
  });

forEach(dateEvents, function(element, index, array) {
  var newMarker = stringToElement(render("marker", {
    index: index + 1,
    left:  100 * (element - array[0]) / (array[array.length - 1] - array[0]) + "%"
  }));
  document.querySelector(".markers").appendChild(newMarker);
});

for (var i = 0; i < dateEvents.length; i++) {
  if (isNaN(dateEvents[i])) {
    document.querySelector(".form-group:nth-child(" + (i + 1) + ")").classList.add("has-error");
    errors.push(render("invalidEvent", {
      index: i + 1
    }));
  }
}

for (var i = 0; i < dateEvents.length - 1; i++) {
  if (!isNaN(dateEvents[i]) && !isNaN(dateEvents[i + 1]) && dateEvents[i] >= dateEvents[i + 1]) {
    document.querySelector(".form-group:nth-child(" + (i + 1) + ")").classList.add("has-error");
    document.querySelector(".form-group:nth-child(" + (i + 2) + ")").classList.add("has-error");
    errors.push(render("predatedEvent", {
      index1: i + 1,
      index2: i + 2
    }));
  }
}

document.querySelector("#addEvent").addEventListener("click", function(e) {
  newEvent();

  if (document.querySelector("#events").children.length > 2)
    forEach(document.querySelectorAll("#form .close"), function(element) {
      element.classList.remove("hidden");
    });

  e.preventDefault();
});

if(events.length >= 2 && errors.length === 0)
  playTimers();
else {
  hideOutput();
  if(events.length >= 2) {
    document.querySelector("#errors").innerHTML = buildList(errors);
    document.querySelector('#errors').classList.remove("hidden");
  }
}
<|endoftext|>


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

   });
   $('#formThing').submit(function(event){
      event.preventDefault();
      getData();
   });
});
function getData(){
    $.get('https://beam.pro/api/v1/channels/' + $('#inputText').val(), "", function(data){
         var Avatar = "https://beam.pro/api/v1/users/" + data['user']['id'] + "/avatar";
         var Username = data['user']['username'];
         var Followers = data['numFollowers'];
         var Partnered = data['partnered'];
         var Tetris = data['interactive'];
         var Audience = data['audience'];
         var Experience = data['user']['experience'];
         var lvls = data['user']['level'];
         var Sparks = data['user']['sparks'];
         var Role = data['user']['groups'][0]
         var ChannelID = data['user']['id'];
         var Tetrisid = data['tetrisGameId'];
         var Coverid = data['coverId'];
         var Thumbnail = data['thumbnailId'];
         var StreamMute = data['preferences']['channel:player:muteOwn'];
         var FollowNotify = data['preferences']['channel:notify:follow'];
         var SubscribeNotify = data['preferences']['channel:notify:subscribe'];
         var TweetNotify = data['preferences']['channel:tweet:enabled'];
         var TotalViews = data['viewersTotal'];
         var te = data['transcodingEnabled'];
         var Online = data['online'];
         if(data['type'] != null){
            var lastPlayed = data['type']['name'];
         }else{
            var lastPlayed = "None";
         }
         var joined = data['createdAt'];
         var html = '';
         html += '
' + Username + '
';
         html += '
----------'
          html += '
Url Link: Beam.pro/'+ Username +'';
         html += '
Followers: ' + Followers+ '';
         html += '
User Role: ' + Role+ '';
         html += '
Partnered: ' + Partnered +'';
         html += '
Total Views: ' + TotalViews +'';
         html += '
---Points---'
         html += '
Level: ' + lvls +'';
         html += '
Experience: ' + Experience +'';
         html += '
Sparks: ' + Sparks +'';
         html += '
---ID---'
         html += '
Tetris Game ID: ' + Tetrisid+ '';
         html += '
Channel ID: ' + ChannelID+ '';
         html += '
Cover ID: ' + Coverid+ '';
         html += '
Thumbnail ID: ' + Thumbnail+ '';
         html += '
---Preference---'
         html += '
interactive:' + Tetris +'';
         html += '
Audience:' + Audience +'';
         html += '
SelfStreamMute:' + StreamMute +'';
         html += '
BeamBot FollowNotify:' + FollowNotify +'';
         html += '
BeamBot SubNotify:' + SubscribeNotify +'';
         html += '
TweetNotify:' + TweetNotify +'';
         html += '
Transcoding:' + te +'';
         html += '
------------'
         html += "
";
         if(Online){
             html += '
Online';
         }else{
             html += '
Offline';
         }
         html+= '
Last Played:'+lastPlayed+'';
         html += '
Joined on: '+joined+' '.replace('T', ' at ');
         $('.profile').html(html);
      }).fail(function(data){
            html = '
A Beam user with that name does not exist.';
             $('.profile').html(html);
            return;
      });;
}
<commit_msg>Update main.js<commit_after>$(document).ready(function(event){
   $('#submit').click(function(event){
      getData();

   });
   $('#formThing').submit(function(event){
      event.preventDefault();
      getData();
   });
});
function getData(){
    $.get('https://beam.pro/api/v1/channels/' + $('#inputText').val(), "", function(data){
         var Avatar = "https://beam.pro/api/v1/users/" + data['user']['id'] + "/avatar";
         var Username = data['user']['username'];
         var Followers = data['numFollowers'];
         var Partnered = data['partnered'];
         var Tetris = data['interactive'];
         var Audience = data['audience'];
         var Experience = data['user']['experience'];
         var lvls = data['user']['level'];
         var Sparks = data['user']['sparks'];
         var Role = data['user']['groups'][0];
         var ChannelID = data['user']['id'];
         var Tetrisid = data['tetrisGameId'];
         var Coverid = data['coverId'];
         var Thumbnail = data['thumbnailId'];
         var StreamMute = data['preferences']['channel:player:muteOwn'];
         var FollowNotify = data['preferences']['channel:notify:follow'];
         var SubscribeNotify = data['preferences']['channel:notify:subscribe'];
         var TweetNotify = data['preferences']['channel:tweet:enabled'];
         var TotalViews = data['viewersTotal'];
         var te = data['transcodingEnabled'];
         var Online = data['online'];
         if(data['type'] != null){
            var lastPlayed = data['type']['name'];
         }else{
            var lastPlayed = "None";
         }
         var joined = data['createdAt'];
         var html = '';
         html += '
' + Username + '
';
         html += '
----------'
          html += '
Url Link: Beam.pro/'+ Username +'';
         html += '
Followers: ' + Followers+ '';
         html += '
User Role: ' + Role+ '';
         html += '
Partnered: ' + Partnered +'';
         html += '
Total Views: ' + TotalViews +'';
         html += '
---Points---'
         html += '
Level: ' + lvls +'';
         html += '
Experience: ' + Experience +'';
         html += '
Sparks: ' + Sparks +'';
         html += '
---ID---'
         html += '
Tetris Game ID: ' + Tetrisid+ '';
         html += '
Channel ID: ' + ChannelID+ '';
         html += '
Cover ID: ' + Coverid+ '';
         html += '
Thumbnail ID: ' + Thumbnail+ '';
         html += '
---Preference---'
         html += '
interactive:' + Tetris +'';
         html += '
Audience:' + Audience +'';
         html += '
SelfStreamMute:' + StreamMute +'';
         html += '
BeamBot FollowNotify:' + FollowNotify +'';
         html += '
BeamBot SubNotify:' + SubscribeNotify +'';
         html += '
TweetNotify:' + TweetNotify +'';
         html += '
Transcoding:' + te +'';
         html += '
------------'
         html += "
";
         if(Online){
             html += '
Online';
         }else{
             html += '
Offline';
         }
         html+= '
Last Played:'+lastPlayed+'';
         html += '
Joined on: '+joined+' '.replace('T', ' at ');
         $('.profile').html(html);
      }).fail(function(data){
            html = '
A Beam user with that name does not exist.';
             $('.profile').html(html);
            return;
      });;
}
<|endoftext|>


<commit_before>$('.ui.dropdown')
    .dropdown()
;
var fdb = new ForerunnerDB();
var db = fdb.db("MyMoneyDB");
var collection = db.collection("MyMoneyCollection");
collection.load();
function exit(){
    navigator.app.exitApp();
}<commit_msg>Update main.js<commit_after>$('.ui.dropdown')
    .dropdown()
;
var fdb = new ForerunnerDB();
var db = fdb.db("MyMoneyDB");
var collection = db.collection("MyMoneyCollection");
collection.load();
<|endoftext|>


<commit_before>
// Wait for user to finish typing
// callback: The callback function
// wait: The number of milliseconds to wait after the the last key press before firing the callback
// highlight: Highlights the element when it receives focus
// allowSubmit: Allows a non-multiline element to be submitted (enter key) regardless of captureLength
// captureLength: Minimum # of characters necessary to fire the callback

$(document).ready(function() {

	//stop loader.gif and overlay
	stop_loader();
	//enable typewatch
	//$('#street').typeWatch({
	//	captureLength: 2,
	//	wait: 1750,
    	//	highlight: true,
	//	callback: function(value) {
	//		//alert("typing finished");
	//		street_to_geo(value);
	//	}
	//});
});

function start_loader(){
	$('#loader').fadeIn('slow');
	$('#overlay').fadeIn('slow');
}

function stop_loader(){
	$('#loader').fadeOut('slow');
	$('#overlay').fadeOut('slow');
}

function addMyRoute(id){
	$.ajax({
  		method: "GET",
  		url: "/php/addMyRoute.php",
  		data: { id: id}
	})
  	.done(function( msg ) {
		//alert("finished");
    	alert(msg);
  	});
}

function showDetails(id){

}

function geo_to_street(lat,long){
	var uri = "https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=" + lat + "&lon=" + long + "&zoom=18&addressdetails=1";
	$.getJSON(uri, function(data) {

        var obj = {road: data.address.road, city: data.address.city, house_number: data.address.house_number, country: data.address.country };

		var string = obj.road + " " + obj.house_number + " " + obj.city + " " + obj.country;
		$('#street').val(string);
		stop_loader();
    });
}

function street_to_geo(){
    start_loader();
    var street = $('#street').val();
    if(street == "") {alert("please enter your starting position!"); stop_loader(); return;}
    //encodes the street string into url friendly format
    var street_encoded = encodeURIComponent(street);
    var uri = "https://nominatim.openstreetmap.org/search/" + street_encoded + "?format=json";
    //alert(uri);
    //makes the the jquery call and gets json back
    $.getJSON(uri, function(data) {
	    //make js obj containing lat and long
		if(data==""){alert("starting position not found"); stop_loader(); return;}

	    var obj = {latitude: data[0].lat, longitude: data[0].lon};
		//return obj;
		//stop_loader();
	        //alert(obj.latitude + " " + obj.longitude);

		get_places2(obj.latitude, obj.longitude);

		//get_places(obj.latitude, obj.longitude);
	        //return obj;
    });
}

function calc_distance(lat1, lon1, lat2, lon2) {
	var unit = "K";
	var radlat1 = Math.PI * lat1/180;
	var radlat2 = Math.PI * lat2/180;
	var theta = lon1-lon2;
	var radtheta = Math.PI * theta/180;
	var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
	dist = Math.acos(dist);
	dist = dist * 180/Math.PI;
	dist = dist * 60 * 1.1515;
	if (unit=="K") { dist = dist * 1.609344; }
	if (unit=="N") { dist = dist * 0.8684; }
	return dist;
}

function get_places(lat, long) {
	var category = $('#category').val();

	$.ajax({
  		method: "GET",
  		url: "/php/get_places.php",
  		data: { lat: lat, long: long, radius: "1000", type: category }
	})
  	.done(function( msg ) {
		//alert("finished");
    	$('#main-area').html(msg);
		stop_loader();
  	});
}

function get_places2(lat, long) {
	var category = $('#category').val();

	$.ajax({
  		method: "GET",
  		url: "/php/get_places2.php",
  		data: { lat: lat, long: long, radius: "1000", type: category }
	})
  	.done(function( msg ) {
  		msg = JSON.parse(msg)
		//alert("finished");
    	//$('#main-area').html(msg);
    	add_details(msg, lat, long)
    	sort_json(msg, 'rating_over_distance', false);
    	$('#main-area').html(json_to_table(msg));
		stop_loader();
  	});
}

function json_to_table(json_object) {
	var str = "
";
	str += "

Name

Street

Rating

Distance

is open?

";

	for(i in json_object) {
		var placeid = json_object[i].place_id;
		if(placeid == "") {break;}
		str += "

";
		str += "
" + json_object[i].name + "
";
		str += "
" + json_object[i].vicinity + "
";
		str += "
" + json_object[i].rating + "
";
		str += "
" + json_object[i].distance + "
";
		if (json_object[i].opening_hours) {
			if (json_object[i].opening_hours.open_now) {
				str += "
" + true + "
";
			} else {
				str += "
" + false + "
";
			}
		}
		str +="
";
		str += "
add
";
		str += "
";
	}

	return str;
}

function add_details(json_object, lat, long) {
	for (x in json_object) {
		json_object[x].distance = Math.round(1000 * calc_distance(lat, long, json_object[x].geometry.location.lat, json_object[x].geometry.location.lng));
		json_object[x].rating_over_distance = json_object[x].rating/json_object[x].distance;
	}
}

function sort_json(json_object, key_to_sort_by, ascending) {
    function sortByKey(a, b) {
        var x = a[key_to_sort_by];
        var y = b[key_to_sort_by];
        if (ascending ==  true) {
        	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        } else {
        	return ((x > y) ? -1 : ((x < y) ? 1 : 0));
        }
    }
    json_object.sort(sortByKey);
}

//returns a Coordinate, could add some other functionality of what to do when geolocation is not supported
var pos;
function get_my_location(){
	start_loader();
	var options = {
	    enableHighAccuracy: true
	};
	if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
	        pos = {
	            lat: position.coords.latitude,
	            lng: position.coords.longitude
	        };

		    // return pos;
		    $('#street').val("");
			var location = pos.lat + " " + pos.lng;
		    geo_to_street(pos.lat,pos.lng);
		    //stop_loader();
			//alert(location);
		    //get_places(pos.lat,pos.lng);
        },
        function(err){
	        stop_loader(); alert("could not get device position");
      	},
        options);
    }
}

function get_weather(lat, lon){
	//if the function does not work, maybe the get_json.php should be in root, or path should be js/get_json.php
    var api_url = "js/get_json.php?";
    var type = "type=weather"

	api_request = api_url;
    api_request += type;
    api_request += "&lat="
    api_request += lat;
    api_request += "&lon="
    api_request += lon;

    //document.write(api_request);

    $(function () {
        $.getJSON(
            api_request,
            function (data) {
                $("#reply").html(JSON.stringify(data));
                return(JSON.stringify(data.weather[0].main));
            });
    });
}
<commit_msg>Update main.js<commit_after>
// Wait for user to finish typing
// callback: The callback function
// wait: The number of milliseconds to wait after the the last key press before firing the callback
// highlight: Highlights the element when it receives focus
// allowSubmit: Allows a non-multiline element to be submitted (enter key) regardless of captureLength
// captureLength: Minimum # of characters necessary to fire the callback

$(document).ready(function() {

	//stop loader.gif and overlay
	stop_loader();
	//enable typewatch
	//$('#street').typeWatch({
	//	captureLength: 2,
	//	wait: 1750,
    	//	highlight: true,
	//	callback: function(value) {
	//		//alert("typing finished");
	//		street_to_geo(value);
	//	}
	//});
});

function start_loader(){
	$('#loader').fadeIn('slow');
	$('#overlay').fadeIn('slow');
}

function stop_loader(){
	$('#loader').fadeOut('slow');
	$('#overlay').fadeOut('slow');
}

function addMyRoute(id){
	$.ajax({
  		method: "GET",
  		url: "/php/addMyRoute.php",
  		data: { id: id}
	})
  	.done(function( msg ) {
		//alert("finished");
    	alert(msg);
  	});
}

function showDetails(id){

}

function geo_to_street(lat,long){
	var uri = "https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=" + lat + "&lon=" + long + "&zoom=18&addressdetails=1";
	$.getJSON(uri, function(data) {

        var obj = {road: data.address.road, city: data.address.city, house_number: data.address.house_number, country: data.address.country };

		var string = obj.road + " " + obj.house_number + " " + obj.city + " " + obj.country;
		$('#street').val(string);
		stop_loader();
    });
}

function street_to_geo(){
    start_loader();
    var street = $('#street').val();
    if(street == "") {alert("please enter your starting position!"); stop_loader(); return;}
    //encodes the street string into url friendly format
    var street_encoded = encodeURIComponent(street);
    var uri = "https://nominatim.openstreetmap.org/search/" + street_encoded + "?format=json";
    //alert(uri);
    //makes the the jquery call and gets json back
    $.getJSON(uri, function(data) {
	    //make js obj containing lat and long
		if(data==""){alert("starting position not found"); stop_loader(); return;}

	    var obj = {latitude: data[0].lat, longitude: data[0].lon};
		//return obj;
		//stop_loader();
	        //alert(obj.latitude + " " + obj.longitude);

		get_places2(obj.latitude, obj.longitude);

		//get_places(obj.latitude, obj.longitude);
	        //return obj;
    });
}

function calc_distance(lat1, lon1, lat2, lon2) {
	var unit = "K";
	var radlat1 = Math.PI * lat1/180;
	var radlat2 = Math.PI * lat2/180;
	var theta = lon1-lon2;
	var radtheta = Math.PI * theta/180;
	var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
	dist = Math.acos(dist);
	dist = dist * 180/Math.PI;
	dist = dist * 60 * 1.1515;
	if (unit=="K") { dist = dist * 1.609344; }
	if (unit=="N") { dist = dist * 0.8684; }
	return dist;
}

function get_places(lat, long) {
	var category = $('#category').val();

	$.ajax({
  		method: "GET",
  		url: "/php/get_places.php",
  		data: { lat: lat, long: long, radius: "1000", type: category }
	})
  	.done(function( msg ) {
		//alert("finished");
    	$('#main-area').html(msg);
		stop_loader();
  	});
}

function get_places2(lat, long) {
	var category = $('#category').val();

	$.ajax({
  		method: "GET",
  		url: "/php/get_places2.php",
  		data: { lat: lat, long: long, radius: "1000", type: category }
	})
  	.done(function( msg ) {
  		msg = JSON.parse(msg)
		//alert("finished");
    	//$('#main-area').html(msg);
    	add_details(msg, lat, long)
    	sort_json(msg, 'rating_over_distance', false);
    	$('#main-area').html(json_to_table(msg));
		stop_loader();
  	});
}

function json_to_table(json_object) {
	var str = "
";
	str += "

Name

Street

Rating

Distance

is open?

";

	for(i in json_object) {
		var placeid = json_object[i].place_id;
		if(placeid == "") {break;}
		str += "

";
		str += "
" + json_object[i].name + "
";
		str += "
" + json_object[i].vicinity + "
";
		str += "
" + json_object[i].rating + "
";
		str += "
" + json_object[i].distance + "
";
		if (json_object[i].opening_hours) {
			if (json_object[i].opening_hours.open_now) {
				str += "
" + "" + "
";
			} else {
				str += "
" + false + "
";
			}
		}
		str +="
";
		str += "
add
";
		str += "
";
	}

	return str;
}

function add_details(json_object, lat, long) {
	for (x in json_object) {
		json_object[x].distance = Math.round(1000 * calc_distance(lat, long, json_object[x].geometry.location.lat, json_object[x].geometry.location.lng));
		json_object[x].rating_over_distance = json_object[x].rating/json_object[x].distance;
	}
}

function sort_json(json_object, key_to_sort_by, ascending) {
    function sortByKey(a, b) {
        var x = a[key_to_sort_by];
        var y = b[key_to_sort_by];
        if (ascending ==  true) {
        	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        } else {
        	return ((x > y) ? -1 : ((x < y) ? 1 : 0));
        }
    }
    json_object.sort(sortByKey);
}

//returns a Coordinate, could add some other functionality of what to do when geolocation is not supported
var pos;
function get_my_location(){
	start_loader();
	var options = {
	    enableHighAccuracy: true
	};
	if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
	        pos = {
	            lat: position.coords.latitude,
	            lng: position.coords.longitude
	        };

		    // return pos;
		    $('#street').val("");
			var location = pos.lat + " " + pos.lng;
		    geo_to_street(pos.lat,pos.lng);
		    //stop_loader();
			//alert(location);
		    //get_places(pos.lat,pos.lng);
        },
        function(err){
	        stop_loader(); alert("could not get device position");
      	},
        options);
    }
}

function get_weather(lat, lon){
	//if the function does not work, maybe the get_json.php should be in root, or path should be js/get_json.php
    var api_url = "js/get_json.php?";
    var type = "type=weather"

	api_request = api_url;
    api_request += type;
    api_request += "&lat="
    api_request += lat;
    api_request += "&lon="
    api_request += lon;

    //document.write(api_request);

    $(function () {
        $.getJSON(
            api_request,
            function (data) {
                $("#reply").html(JSON.stringify(data));
                return(JSON.stringify(data.weather[0].main));
            });
    });
}
<|endoftext|>


<commit_before>var game;
var started = false;
function startGame(){
	if(!started){
		changePhaseTo('gameplay');
		game = new Phaser.Game(800, 600, Phaser.AUTO, 'game', { preload: preload, create: create, update: update });
		started = true;
	}
}

function changePhaseTo(id, payload){

	if (id === 'end') {
		var name = payload.name;
		document.getElementById('end').innerHTML  = ' ';
		document.getElementById('game').remove();
	} else if (id === 'gameplay'){
		document.getElementById('menu').remove();
	}

}

function Opponent () {

	var randomUpTo = function(higherBound){
		return Math.random() * higherBound;
	}

	var x = randomUpTo(game.world.width);
	var y = randomUpTo(game.world.height);
	this.value = game.add.sprite(x, y, 'enemy1');

	var value = this.value;

	game.physics.arcade.enable(value);
	value.body.collideWorldBounds = true;

	value.animations.add('left', [0, 1, 2, 3], 10, true);
	value.animations.add('right', [0, 1, 2, 3], 10, true);

	this.value.body.velocity.x = randomUpTo(400);
	this.value.body.velocity.y = randomUpTo(400);

	var bounceRate = 0.95;
	this.value.body.bounce.y = bounceRate;
	this.value.body.bounce.x = bounceRate;

	this.value._obj = this;
}

Opponent.prototype.move = function() {
	this.value.animations.play('left');
};

Opponent.prototype.dying = function() {
	this.value.animations.play("die");
};

function preload() {

	game.load.image('background1', 'assets/background_layout_stars_one.png');
	game.load.image('background2', 'assets/background_layout_stars_two.png');
	game.load.image('background3', 'assets/background_layout_stars_three.png');
	game.load.image('ground', 'assets/platform.png');
	game.load.image('ground2', 'assets/ground.png');
	game.load.image('star', 'assets/star.png');
	game.load.image('moon', 'assets/moon.png');
	game.load.spritesheet('blueplayer', 'assets/blueplayer_16.png', 64, 32);
	game.load.spritesheet('redplayer', 'assets/redplayer_16.png', 64, 32);
	game.load.spritesheet('dude', 'assets/dude.png', 32, 48);
	game.load.spritesheet('enemy1', 'assets/enemy3.png', 32, 32);
	game.load.audio('music', ['assets/music.mp3', 'assets/music.ogg']);
	game.load.audio('chachacha', ['assets/chachacha.mp3', 'assets/chachacha.ogg']);

}

function Score(x, y, name){
	this.value = 0;
	this.text = "";
	this.name = name;
	this.at(x,y);
}

function getQueryParams(qs) {
	qs = qs.split('+').join(' ');

	var params = {},
	tokens,
	re = /[?&]?([^=]+)=([^&]*)/g;

	while (tokens = re.exec(qs)) {
		params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
	}

	return params;
}

var winningScore = getQueryParams(document.location.search)["score"] || 500;

Score.prototype.increase = function() {
	this.value += 10;
	this.scoreText.text = this.show(this.value);
	if(this.value >= winningScore){
		throw Won();
	}
};

Score.prototype.decrease = function() {
	this.value -= 3;
	this.scoreText.text = this.show(this.value);
};

Score.prototype.show = function(score) {
	return this.name + '\'s score: ' + score;
};

Score.prototype.at = function(x, y) {
	this.scoreText = game.add.text(x, y, this.show(0), { fontSize: '32px', fill: '#fff' });
};

var player;
var player1;
var opponent1;
var cursors;
var blueplayer;
var redplayer;
var opponents;
var stars;
var scores;
var music;
var chachacha;

function create() {
	game.physics.startSystem(Phaser.Physics.ARCADE);
	music = game.sound.play('music');
	background1 = game.add.sprite(0, 0, 'background1');
	background2 = game.add.sprite(0, 0, 'background2');
	background3 = game.add.sprite(0, 0, 'background3');
	background4 = game.add.sprite(game.width, 0, 'background1');
	background5 = game.add.sprite(game.width, 0, 'background2');
	background6 = game.add.sprite(game.width, 0, 'background3');
	moon = game.add.sprite(1000, 500, 'moon');
	ground2 = game.add.sprite(0,game.world.height-64, 'ground2');
	ground3 = game.add.sprite(1600,game.world.height-64, 'ground2');

	scores={player1: new Score(16,16, 'red'), player2: new Score(550,16, 'blue')};

	cursors = createControls();
	var players = createPlayers(cursors);
	player = players[0];
	player.setScore(scores.player1);
	player1 = players[1];
	player1.setScore(scores.player2);
	opponents= createOpponents();
	stars = createStars();

}

function createPlayers(){
	var players = [];

	var player = new Player('redplayer', 32, game.height - 150, game);
	player.setScore(scores.player1);
	players.push(player);

	var player1 = new Player('blueplayer', 32, 150, game);
	player1.setScore(scores.player2);
	players.push(player1);

	return players;
}

function createOpponents(){
	var opponents = game.add.group();
	opponents.enableBody = true;
	for (var i = 0; i < 7; i++) {
		opponents.add(new Opponent().value);
	}
	return opponents;
}

function createStars(){
	var stars = game.add.group();
	stars.enableBody = true;

	for (var i = 0; i < 30; i++) {
		createStar(stars);
	}

	return stars;
}

function createStar(stars){
	var star = stars.create(Math.random()*game.width, Math.random()*game.height, 'star');
	star.body.bounce.y = 0.7 + Math.random() * 0.2;
}

function createControls(){
	return {
		arrows: game.input.keyboard.createCursorKeys(),
		wasd: {
			up: game.input.keyboard.addKey(Phaser.Keyboard.W),
			down: game.input.keyboard.addKey(Phaser.Keyboard.S),
			left: game.input.keyboard.addKey(Phaser.Keyboard.A),
			right: game.input.keyboard.addKey(Phaser.Keyboard.D)
		}
	};
}

function update() {
	moveBackground(background1, 1);
	moveBackground(background2, 2);
	moveBackground(background3, 3);
	moveBackground(background6, 3);
	moveBackground(background4, 1);
	moveBackground(background5, 2);
	moveGround(ground2, 1);
	moveGround(ground3, 1);
	moonspawn(moon, 3)

	manage_collisions (game);
	player.move(cursors.arrows);
	player1.move(cursors.wasd);
}
var moonspawn = function(background, speed) {
	moveBackground(moon, speed);
	if(background.x < -300) {
		background.x = game.rnd.integerInRange(3000, 6000);
		background.y = game.rnd.integerInRange(-100, 500);
	}

}

var moveBackground = function(background, speed) {
	if (background.x < -game.width) {
		background.x = game.width;
	}
	background.x -= speed
}

var moveGround = function(ground, speed){
	var treshold = 2*game.width;
	if (ground.x < -treshold) {
		ground.x = treshold;
	}
	ground.x -= speed;
}

function manage_collisions (game) {
	player.canCollect(stars);
	player.canCollideWith(opponents);

	player1.canCollect(stars);
	player1.canCollideWith(opponents);
}<commit_msg>refactor: extract explanatory variable<commit_after>var game;
var started = false;
function startGame(){
	if(!started){
		changePhaseTo('gameplay');
		game = new Phaser.Game(800, 600, Phaser.AUTO, 'game', { preload: preload, create: create, update: update });
		started = true;
	}
}

function changePhaseTo(id, payload){

	if (id === 'end') {
		var name = payload.name;
		document.getElementById('end').innerHTML  = ' ';
		document.getElementById('game').remove();
	} else if (id === 'gameplay'){
		document.getElementById('menu').remove();
	}

}

function Opponent () {

	var randomUpTo = function(higherBound){
		return Math.random() * higherBound;
	}

	var x = randomUpTo(game.world.width);
	var y = randomUpTo(game.world.height);
	this.value = game.add.sprite(x, y, 'enemy1');

	var value = this.value;

	game.physics.arcade.enable(value);
	value.body.collideWorldBounds = true;

	value.animations.add('left', [0, 1, 2, 3], 10, true);
	value.animations.add('right', [0, 1, 2, 3], 10, true);

	this.value.body.velocity.x = randomUpTo(400);
	this.value.body.velocity.y = randomUpTo(400);

	var bounceRate = 0.95;
	this.value.body.bounce.y = bounceRate;
	this.value.body.bounce.x = bounceRate;

	this.value._obj = this;
}

Opponent.prototype.move = function() {
	this.value.animations.play('left');
};

Opponent.prototype.dying = function() {
	this.value.animations.play("die");
};

function preload() {

	game.load.image('background1', 'assets/background_layout_stars_one.png');
	game.load.image('background2', 'assets/background_layout_stars_two.png');
	game.load.image('background3', 'assets/background_layout_stars_three.png');
	game.load.image('ground', 'assets/platform.png');
	game.load.image('ground2', 'assets/ground.png');
	game.load.image('star', 'assets/star.png');
	game.load.image('moon', 'assets/moon.png');
	game.load.spritesheet('blueplayer', 'assets/blueplayer_16.png', 64, 32);
	game.load.spritesheet('redplayer', 'assets/redplayer_16.png', 64, 32);
	game.load.spritesheet('dude', 'assets/dude.png', 32, 48);
	game.load.spritesheet('enemy1', 'assets/enemy3.png', 32, 32);
	game.load.audio('music', ['assets/music.mp3', 'assets/music.ogg']);
	game.load.audio('chachacha', ['assets/chachacha.mp3', 'assets/chachacha.ogg']);

}

function Score(x, y, name){
	this.value = 0;
	this.text = "";
	this.name = name;
	this.at(x,y);
}

function getQueryParams(qs) {
	qs = qs.split('+').join(' ');

	var params = {},
	tokens,
	re = /[?&]?([^=]+)=([^&]*)/g;

	while (tokens = re.exec(qs)) {
		params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
	}

	return params;
}

var winningScore = getQueryParams(document.location.search)["score"] || 500;

Score.prototype.increase = function() {
	this.value += 10;
	this.scoreText.text = this.show(this.value);
	if(this.value >= winningScore){
		throw Won();
	}
};

Score.prototype.decrease = function() {
	this.value -= 3;
	this.scoreText.text = this.show(this.value);
};

Score.prototype.show = function(score) {
	return this.name + '\'s score: ' + score;
};

Score.prototype.at = function(x, y) {
	this.scoreText = game.add.text(x, y, this.show(0), { fontSize: '32px', fill: '#fff' });
};

var player;
var player1;
var opponent1;
var cursors;
var blueplayer;
var redplayer;
var opponents;
var stars;
var scores;
var music;
var chachacha;

function create() {
	game.physics.startSystem(Phaser.Physics.ARCADE);
	music = game.sound.play('music');
	background1 = game.add.sprite(0, 0, 'background1');
	background2 = game.add.sprite(0, 0, 'background2');
	background3 = game.add.sprite(0, 0, 'background3');
	background4 = game.add.sprite(game.width, 0, 'background1');
	background5 = game.add.sprite(game.width, 0, 'background2');
	background6 = game.add.sprite(game.width, 0, 'background3');
	moon = game.add.sprite(1000, 500, 'moon');
	ground2 = game.add.sprite(0,game.world.height-64, 'ground2');
	ground3 = game.add.sprite(1600,game.world.height-64, 'ground2');

	scores={player1: new Score(16,16, 'red'), player2: new Score(550,16, 'blue')};

	cursors = createControls();
	var players = createPlayers(cursors);
	player = players[0];
	player.setScore(scores.player1);
	player1 = players[1];
	player1.setScore(scores.player2);
	opponents= createOpponents();
	stars = createStars();

}

function createPlayers(){
	var players = [];

	var player = new Player('redplayer', 32, game.height - 150, game);
	player.setScore(scores.player1);
	players.push(player);

	var player1 = new Player('blueplayer', 32, 150, game);
	player1.setScore(scores.player2);
	players.push(player1);

	return players;
}

function createOpponents(){
	var opponents = game.add.group();
	var numberOfOpponents = 7;
	opponents.enableBody = true;
	for (var i = 0; i < numberOfOpponents; i++) {
		opponents.add(new Opponent().value);
	}
	return opponents;
}

function createStars(){
	var stars = game.add.group();
	stars.enableBody = true;

	for (var i = 0; i < 30; i++) {
		createStar(stars);
	}

	return stars;
}

function createStar(stars){
	var star = stars.create(Math.random()*game.width, Math.random()*game.height, 'star');
	star.body.bounce.y = 0.7 + Math.random() * 0.2;
}

function createControls(){
	return {
		arrows: game.input.keyboard.createCursorKeys(),
		wasd: {
			up: game.input.keyboard.addKey(Phaser.Keyboard.W),
			down: game.input.keyboard.addKey(Phaser.Keyboard.S),
			left: game.input.keyboard.addKey(Phaser.Keyboard.A),
			right: game.input.keyboard.addKey(Phaser.Keyboard.D)
		}
	};
}

function update() {
	moveBackground(background1, 1);
	moveBackground(background2, 2);
	moveBackground(background3, 3);
	moveBackground(background6, 3);
	moveBackground(background4, 1);
	moveBackground(background5, 2);
	moveGround(ground2, 1);
	moveGround(ground3, 1);
	moonspawn(moon, 3)

	manage_collisions (game);
	player.move(cursors.arrows);
	player1.move(cursors.wasd);
}
var moonspawn = function(background, speed) {
	moveBackground(moon, speed);
	if(background.x < -300) {
		background.x = game.rnd.integerInRange(3000, 6000);
		background.y = game.rnd.integerInRange(-100, 500);
	}

}

var moveBackground = function(background, speed) {
	if (background.x < -game.width) {
		background.x = game.width;
	}
	background.x -= speed
}

var moveGround = function(ground, speed){
	var treshold = 2*game.width;
	if (ground.x < -treshold) {
		ground.x = treshold;
	}
	ground.x -= speed;
}

function manage_collisions (game) {
	player.canCollect(stars);
	player.canCollideWith(opponents);

	player1.canCollect(stars);
	player1.canCollideWith(opponents);
}<|endoftext|>


<commit_before>'use strict';

function repo_escape(){
    if(!core_intervals['interval']
      && !core_menu_open){
        core_repo_reset();
    }
}

function repo_init(){
    core_repo_init({
      'events': {
        'start-button': {
          'onclick': core_repo_reset,
        },
      },
      'globals': {
        'grid_dimensions_squared': 0,
        'score': 0,
        'time': 0,
      },
      'info': '<input id=start-button type=button value=Restart>',
      'menu': true,
      'reset': function(){
          stop();
          if(core_menu_open){
              core_escape();
          }
          start();
      },
      'storage': {
        'game-mode': 1,
        'grid-dimensions': 5,
        'height': '50px',
        'max': 30,
        'negative-frequency': 1,
        'negative-onclick': 0,
        'negative-points': -1,
        'positive-frequency': 1,
        'positive-points': 1,
        'width': '50px',
      },
      'storage-menu': '

<input id=height>Button Height'
        + '
<input id=width>Button Width'
        + '
<input id=grid-dimensions min=1 type=number>Dimensions'
        + '
<input id=max type=number>Max <select id=game-mode><option value=0>Points</option><option value=1>Time</option></select>'
        + '
<select id=negative-onclick><option value=0>Lose Points</option><option value=1>End Game</option></select>Negative Click'
        + '
<input id=negative-frequency type=number>Negative Frequency'
        + '
<input id=negative-points type=number>Negative Points'
        + '
<input id=positive-frequency type=number>Positive Frequency'
        + '
<input id=positive-points type=number>Positive Points
',
      'title': 'SpeedButton.htm',
    });
    audio_create({
      'audios': {
        'boop': {
          'duration': .1,
        },
      },
    });
    core_html_store({
      'ids': [
        'time',
      ],
    });
}
<commit_msg>added step=any to disable validation<commit_after>'use strict';

function repo_escape(){
    if(!core_intervals['interval']
      && !core_menu_open){
        core_repo_reset();
    }
}

function repo_init(){
    core_repo_init({
      'events': {
        'start-button': {
          'onclick': core_repo_reset,
        },
      },
      'globals': {
        'grid_dimensions_squared': 0,
        'score': 0,
        'time': 0,
      },
      'info': '<input id=start-button type=button value=Restart>',
      'menu': true,
      'reset': function(){
          stop();
          if(core_menu_open){
              core_escape();
          }
          start();
      },
      'storage': {
        'game-mode': 1,
        'grid-dimensions': 5,
        'height': '50px',
        'max': 30,
        'negative-frequency': 1,
        'negative-onclick': 0,
        'negative-points': -1,
        'positive-frequency': 1,
        'positive-points': 1,
        'width': '50px',
      },
      'storage-menu': '

<input id=height>Button Height'
        + '
<input id=width>Button Width'
        + '
<input id=grid-dimensions min=1 step=any type=number>Dimensions'
        + '
<input id=max step=any type=number>Max <select id=game-mode><option value=0>Points</option><option value=1>Time</option></select>'
        + '
<select id=negative-onclick><option value=0>Lose Points</option><option value=1>End Game</option></select>Negative Click'
        + '
<input id=negative-frequency step=any type=number>Negative Frequency'
        + '
<input id=negative-points step=any type=number>Negative Points'
        + '
<input id=positive-frequency step=any type=number>Positive Frequency'
        + '
<input id=positive-points step=any type=number>Positive Points
',
      'title': 'SpeedButton.htm',
    });
    audio_create({
      'audios': {
        'boop': {
          'duration': .1,
        },
      },
    });
    core_html_store({
      'ids': [
        'time',
      ],
    });
}
<|endoftext|>