<commit_before>const colors = {
	'all' : '#259b24',
	'jpop' : '#ffc107',
	'vocaloid' : '#e91e63',
	'nightcore': '#5677fc'
};

var genreContents = { };
var loading = '';

$(function() {
	resetTooltip();
	var hash = getHash('all');
	loading = $('#song-list').html();
	selectAndSetContents(hash);
});

$('.nav li').click(function() {
	$('#song-list').html(loading);
	selectAndSetContents($(this).attr('genre'));
});

function selectAndSetContents(genre) {
	getContents(genre);
	$('.nav li').removeClass('active');
	$('.nav li[genre=' +  genre + ']').addClass('active');
}

function animateNavbar(genre) {
	$('#the-navbar').animate({
		'background-color': colors[genre],
	});
}

function getContents(genre) {
	if(genre in genreContents) {
		$('#song-list').html(genreContents[genre]);
		animateNavbar(genre);
	} else $.get('./api/v1/list.php', {
		'genre': genre,
		'format': 'html'
	}, function(resp) {
		var contents = resp.message;
		if(resp.status != 200)
			contents = "Status Code " + resp.status + ": " + contents;

		animateNavbar(genre);
		contents = contents.replace(/song-play-button/g, 'song-play-button glyphicon glyphicon-play-circle').replace(/song-download-button/g, 'song-download-button glyphicon glyphicon-download');
		$('#song-list').html(contents);
		genreContents[genre] = contents;
	});
}

function setGenre(genre, html) {
	resetTooltip();
}

function resetTooltip() {
	$('[data-toggle="tooltip"]').tooltip({'placement': 'top'});
}

function getHash(fallback) {
	var hash = window.location.hash.substring(1);
	return hash.length == 0 ? fallback : hash;
}

String.prototype.startsWith = function(str) {
	return this.indexOf(str) == 0;
}<commit_msg>Proper tooltip stuff.<commit_after>const colors = {
	'all' : '#259b24',
	'jpop' : '#ffc107',
	'vocaloid' : '#e91e63',
	'nightcore': '#5677fc'
};

var genreContents = { };
var loading = '';

$(function() {
	resetTooltip();
	var hash = getHash('all');
	loading = $('#song-list').html();
	selectAndSetContents(hash);
});

$('.nav li').click(function() {
	$('#song-list').html(loading);
	selectAndSetContents($(this).attr('genre'));
});

function selectAndSetContents(genre) {
	getContents(genre);
	$('.nav li').removeClass('active');
	$('.nav li[genre=' +  genre + ']').addClass('active');
}

function animateNavbar(genre) {
	$('#the-navbar').animate({
		'background-color': colors[genre],
	});
	$('html, body').animate({  scrollTop: 0 }, 500);
}

function getContents(genre) {
	if(genre in genreContents) {
		$('#song-list').html(genreContents[genre]);
		animateNavbar(genre);
	} else $.get('./api/v1/list.php', {
		'genre': genre,
		'format': 'html'
	}, function(resp) {
		var contents = resp.message;
		if(resp.status != 200)
			contents = "Status Code " + resp.status + ": " + contents;

		animateNavbar(genre);
		contents = contents.replace(/song-play-button/g, 'song-play-button glyphicon glyphicon-play-circle').replace(/song-download-button/g, 'song-download-button glyphicon glyphicon-download');
		$('#song-list').html(contents);
		genreContents[genre] = contents;
		resetTooltip();
	});
}

function resetTooltip() {
	$('[data-toggle="tooltip"]').tooltip({'placement': 'top'});
}

function getHash(fallback) {
	var hash = window.location.hash.substring(1);
	return hash.length == 0 ? fallback : hash;
}

String.prototype.startsWith = function(str) {
	return this.indexOf(str) == 0;
}<|endoftext|>


<commit_before>const colors = {
	'all' : '#259b24',
	'jpop' : '#ffc107',
	'vocaloid' : '#e91e63',
	'nightcore': '#5677fc'
};

var genreContents = { };
var loading = '';
var currentPlaying;

var hamburgerCss = { };

$(function() {
	resetTooltip();
	var hash = getHash('all');
	loading = $('#song-list').html();
	selectAndSetContents(hash);
});

$('.nav li').click(function() {
	$('#song-list').html(loading);
	selectAndSetContents($(this).attr('genre'));
});

$(document).on('click', '.song-play-button', function() {
	var dl = $(this).parent('div').find('a').attr('href');
	var parent = $(this).closest('.song-box');
	var title = parent.find('.song-title').text();
	var player = $('#player');

	var artist = parent.find('.song-artist').text();
	var albumArtist = parent.find('.song-artist').attr('data-original-title');
	var displayArtist = artist;
	if(artist != albumArtist)
		displayArtist = artist + " / " + albumArtist;

	var audio = '' + title + '
<audio controls="controls" autoplay="autoplay"><source src="' + dl + '" type="audio/mpeg"></audio>';

	if(currentPlaying != undefined)
		currentPlaying.animate({
			'background-color': '#fff',
		});

	parent.animate({
		'background-color': '#dff',
	});
	currentPlaying = parent;

	player.html(audio);
	if(player.css('display') == 'none')
		player.show(600);
	resetTooltip();
});

$(".navbar-toggle").click(function() {
	if($("#icon-bar0").css("width") == "13px") {
		$("#icon-bar0").animate({
			"textIndent": "0",
			"width": "22px",
			"margin-top": "0px",
			"margin-left": "0px",
			"margin-bottom": "-0px"
		}, {
			duration: 400,
			step: applyRotation
		});

		$("#icon-bar2").animate({
			"textIndent": "0",
			"width": "22px",
			"margin-left": "0px",
			"margin-top": "4px"
		}, {
			duration: 400,
			step: applyRotation
		});
	} else {
		$("#icon-bar0").animate({
			"textIndent": "135",
			"width": "13px",
			"margin-top": "2px",
			"margin-left": "-2px",
			"margin-bottom": "-2px"
		}, {
			duration: 400,
			step: applyRotation
		});

		$("#icon-bar2").animate({
			"textIndent": "45",
			"width": "13px",
			"margin-left": "-2px",
			"margin-top": "2px"
		}, {
			duration: 400,
			step: applyRotation
		});
	}
});

function applyRotation(now, tween) {
	if(tween.prop == "textIndent")
		$(this).css({ "transform": "rotate(" + now + "deg)" });
}

$('#btsync-key').click(function() {
	$('#btsync-hide-button').show(600);
	$('#btsync-hidden-key').show(600);
	$('#btsync-hidden-qr').hide(600);
});

$('#btsync-installer').click(function() {
	window.open('https://link.getsync.com/#f=JPV%20Media%20Folder&sz=35E8&s=P3MGCJYFIYDLHH5OTZ2IHUJK5HRXUHKS&i=CVSZIPOSYQ5MKBMPEZ5DKKRV3MVSG35VR&p=CDXRVCURLM4XKYRC4SJH4BFM7JJEMVEX', '_blank');
});

$('#btsync-qr').click(function() {
	$('#btsync-hide-button').show(600);
	$('#btsync-hidden-qr').show(600);
	$('#btsync-hidden-key').hide(600);
});

$('#btsync-hide-button').click(function() {
	$('#btsync-hide-button').hide(600);
	$('#btsync-hidden-key').hide(600);
	$('#btsync-hidden-qr').hide(600);
});

function selectAndSetContents(genre) {
	getContents(genre);
	$('.synced-bgcolor').animate({
		'background-color': colors[genre],
	});
	$('.synced-color').animate({
		'color': colors[genre],
	});

	$('html, body').animate({  scrollTop: 0 }, 500);
	$('.nav li').removeClass('active');
	$('.nav li[genre=' +  genre + ']').addClass('active');
	document.title = $('.nav li[genre=' +  genre + ']').attr('title') + ' | JPV Music Library';

	if(genre == 'all')
		$('#content-info').show(600);
	else $('#content-info').hide(600);
}

function getContents(genre) {
	if(genre in genreContents) {
		$('#song-list').html(genreContents[genre]);
		resetTooltip();
	} else $.get('./api/v1/list.php', {
		'genre': genre,
		'format': 'html'
	}, function(resp) {
		var contents = resp.message;
		$('#song-list').html(contents);
		genreContents[genre] = contents;
		resetTooltip();
	});
}

function resetTooltip() {
	$('[data-toggle="tooltip"]').tooltip({'placement': 'top'});
}

function getHash(fallback) {
	var hash = window.location.hash.substring(1);
	return hash.length == 0 ? fallback : hash;
}

String.prototype.startsWith = function(str) {
	return this.indexOf(str) == 0;
}<commit_msg>Less flashy arrow animation.<commit_after>const colors = {
	'all' : '#259b24',
	'jpop' : '#ffc107',
	'vocaloid' : '#e91e63',
	'nightcore': '#5677fc'
};

var genreContents = { };
var loading = '';
var currentPlaying;

var hamburgerCss = { };

$(function() {
	resetTooltip();
	var hash = getHash('all');
	loading = $('#song-list').html();
	selectAndSetContents(hash);
});

$('.nav li').click(function() {
	$('#song-list').html(loading);
	selectAndSetContents($(this).attr('genre'));
});

$(document).on('click', '.song-play-button', function() {
	var dl = $(this).parent('div').find('a').attr('href');
	var parent = $(this).closest('.song-box');
	var title = parent.find('.song-title').text();
	var player = $('#player');

	var artist = parent.find('.song-artist').text();
	var albumArtist = parent.find('.song-artist').attr('data-original-title');
	var displayArtist = artist;
	if(artist != albumArtist)
		displayArtist = artist + " / " + albumArtist;

	var audio = '' + title + '
<audio controls="controls" autoplay="autoplay"><source src="' + dl + '" type="audio/mpeg"></audio>';

	if(currentPlaying != undefined)
		currentPlaying.animate({
			'background-color': '#fff',
		});

	parent.animate({
		'background-color': '#dff',
	});
	currentPlaying = parent;

	player.html(audio);
	if(player.css('display') == 'none')
		player.show(600);
	resetTooltip();
});

$(".navbar-toggle").click(function() {
	if($("#icon-bar0").css("width") == "12px") {
		$("#icon-bar0").animate({
			"textIndent": "0",
			"width": "22px",
			"margin-top": "0px",
			"margin-left": "0px",
			"margin-bottom": "-0px"
		}, {
			duration: 300,
			step: applyRotation
		});

		$("#icon-bar1").animate({
			"width": "22px",
		}, {
			duration: 300,
			step: applyRotation
		});

		$("#icon-bar2").animate({
			"textIndent": "0",
			"width": "22px",
			"margin-left": "0px",
			"margin-top": "4px"
		}, {
			duration: 300,
			step: applyRotation
		});
	} else {
		$("#icon-bar0").animate({
			"textIndent": "-45",
			"width": "12px",
			"margin-top": "2px",
			"margin-left": "-2px",
			"margin-bottom": "-2px"
		}, {
			duration: 300,
			step: applyRotation
		});

		$("#icon-bar1").animate({
			"width": "18px",
		}, {
			duration: 300,
			step: applyRotation
		});

		$("#icon-bar2").animate({
			"textIndent": "45",
			"width": "12px",
			"margin-left": "-2px",
			"margin-top": "2px"
		}, {
			duration: 300,
			step: applyRotation
		});
	}
});

function applyRotation(now, tween) {
	if(tween.prop == "textIndent")
		$(this).css({ "transform": "rotate(" + now + "deg)" });
}

$('#btsync-key').click(function() {
	$('#btsync-hide-button').show(600);
	$('#btsync-hidden-key').show(600);
	$('#btsync-hidden-qr').hide(600);
});

$('#btsync-installer').click(function() {
	window.open('https://link.getsync.com/#f=JPV%20Media%20Folder&sz=35E8&s=P3MGCJYFIYDLHH5OTZ2IHUJK5HRXUHKS&i=CVSZIPOSYQ5MKBMPEZ5DKKRV3MVSG35VR&p=CDXRVCURLM4XKYRC4SJH4BFM7JJEMVEX', '_blank');
});

$('#btsync-qr').click(function() {
	$('#btsync-hide-button').show(600);
	$('#btsync-hidden-qr').show(600);
	$('#btsync-hidden-key').hide(600);
});

$('#btsync-hide-button').click(function() {
	$('#btsync-hide-button').hide(600);
	$('#btsync-hidden-key').hide(600);
	$('#btsync-hidden-qr').hide(600);
});

function selectAndSetContents(genre) {
	getContents(genre);
	$('.synced-bgcolor').animate({
		'background-color': colors[genre],
	});
	$('.synced-color').animate({
		'color': colors[genre],
	});

	$('html, body').animate({  scrollTop: 0 }, 500);
	$('.nav li').removeClass('active');
	$('.nav li[genre=' +  genre + ']').addClass('active');
	document.title = $('.nav li[genre=' +  genre + ']').attr('title') + ' | JPV Music Library';

	if(genre == 'all')
		$('#content-info').show(600);
	else $('#content-info').hide(600);
}

function getContents(genre) {
	if(genre in genreContents) {
		$('#song-list').html(genreContents[genre]);
		resetTooltip();
	} else $.get('./api/v1/list.php', {
		'genre': genre,
		'format': 'html'
	}, function(resp) {
		var contents = resp.message;
		$('#song-list').html(contents);
		genreContents[genre] = contents;
		resetTooltip();
	});
}

function resetTooltip() {
	$('[data-toggle="tooltip"]').tooltip({'placement': 'top'});
}

function getHash(fallback) {
	var hash = window.location.hash.substring(1);
	return hash.length == 0 ? fallback : hash;
}

String.prototype.startsWith = function(str) {
	return this.indexOf(str) == 0;
}<|endoftext|>


<commit_before>
// XXX Hack to prevent hextorstr function used by JWS send a string instead of
// a Word Array. On this way, no string decoding needs to take place and Crypto
// takes care of everything.
// Note that it should not affect the other algorithms as hextorstr is exclusively
// used on Hmac family (that invokes CryptoJS library).
window.hextorstr = function (c) {
  return window.CryptoJS.enc.Hex.parse(c);
};

//this is used to parse base64
function url_base64_decode(str) {
  var output = str.replace('-', '+').replace('_', '/');
  switch (output.length % 4) {
    case 0:
      break;
    case 2:
      output += '==';
      break;
    case 3:
      output += '=';
      break;
    default:
      throw 'Illegal base64url string!';
  }
  return window.atob(output); //polifyll https://github.com/davidchambers/Base64.js
}

window.decode = function (base64json) {
  var json = null, error = null;
  try {
    json = url_base64_decode(base64json);
    json = JSON.stringify(JSON.parse(json), undefined, 2);
  } catch (e) {
    error = e;
  }
  return {result: json, error: error};
};

window.sign = function (header, payload, secret, isSecretBase64Encoded) {
  var value = '', error = null, headerAsJSON, payloadAsJSON;

  try {
    headerAsJSON = JSON.stringify(JSON.parse(header));
  } catch (e) {
    error = {result: null, error: {cause: e, who: ['header']}};
  }
  try {
    payloadAsJSON = JSON.stringify(JSON.parse(payload));
  } catch (e) {
    if (error) {
      error.error.who.push('payload');
    } else {
      error = {result: null, error: {cause: e, who: ['payload']}};
    }
  }

  if (error) {
    return error;
  }

  if (isSecretBase64Encoded) {
    try {
      secret = window.b64utob64(secret);
      secret = window.CryptoJS.enc.Base64.parse(secret).toString();
    } catch (e) {
      return {result: '', error: e};
    }
  } else {
    secret = window.CryptoJS.enc.Latin1.parse(secret).toString();
  }

  try {
    value = KJUR.jws.JWS.sign(null, headerAsJSON, payloadAsJSON, secret);
  } catch (e) {
    error = e;
  }

  return {result: value, error: error};
};

window.isValidBase64String = function (s) {
  try {
    s = window.b64utob64(s);
    window.CryptoJS.enc.Base64.parse(s).toString();
    return true;
  } catch (e) {
    return false;
  }
};

window.verify = function (value, secret, isSecretBase64Encoded) {
  var result = '', error = null;

  if (isSecretBase64Encoded) {
    try {
      secret = window.b64utob64(secret);
      secret = window.CryptoJS.enc.Base64.parse(secret).toString();
    } catch (e) {
      return {result: '', error: e};
    }
  } else {
    secret = window.CryptoJS.enc.Latin1.parse(secret).toString();
  }

  try {
    result = KJUR.jws.JWS.verify(value, secret);
  } catch (e) {
    error = e;
  }

  return {result: result, error: error};
};
<commit_msg>Fix multiple occurences of `-` or `_` in tokens<commit_after>
// XXX Hack to prevent hextorstr function used by JWS send a string instead of
// a Word Array. On this way, no string decoding needs to take place and Crypto
// takes care of everything.
// Note that it should not affect the other algorithms as hextorstr is exclusively
// used on Hmac family (that invokes CryptoJS library).
window.hextorstr = function (c) {
  return window.CryptoJS.enc.Hex.parse(c);
};

//this is used to parse base64
function url_base64_decode(str) {
  var output = str.replace(/-/g, '+').replace(/_/g, '/');
  switch (output.length % 4) {
    case 0:
      break;
    case 2:
      output += '==';
      break;
    case 3:
      output += '=';
      break;
    default:
      throw 'Illegal base64url string!';
  }
  return window.atob(output); //polifyll https://github.com/davidchambers/Base64.js
}

window.decode = function (base64json) {
  var json = null, error = null;
  try {
    json = url_base64_decode(base64json);
    json = JSON.stringify(JSON.parse(json), undefined, 2);
  } catch (e) {
    error = e;
  }
  return {result: json, error: error};
};

window.sign = function (header, payload, secret, isSecretBase64Encoded) {
  var value = '', error = null, headerAsJSON, payloadAsJSON;

  try {
    headerAsJSON = JSON.stringify(JSON.parse(header));
  } catch (e) {
    error = {result: null, error: {cause: e, who: ['header']}};
  }
  try {
    payloadAsJSON = JSON.stringify(JSON.parse(payload));
  } catch (e) {
    if (error) {
      error.error.who.push('payload');
    } else {
      error = {result: null, error: {cause: e, who: ['payload']}};
    }
  }

  if (error) {
    return error;
  }

  if (isSecretBase64Encoded) {
    try {
      secret = window.b64utob64(secret);
      secret = window.CryptoJS.enc.Base64.parse(secret).toString();
    } catch (e) {
      return {result: '', error: e};
    }
  } else {
    secret = window.CryptoJS.enc.Latin1.parse(secret).toString();
  }

  try {
    value = KJUR.jws.JWS.sign(null, headerAsJSON, payloadAsJSON, secret);
  } catch (e) {
    error = e;
  }

  return {result: value, error: error};
};

window.isValidBase64String = function (s) {
  try {
    s = window.b64utob64(s);
    window.CryptoJS.enc.Base64.parse(s).toString();
    return true;
  } catch (e) {
    return false;
  }
};

window.verify = function (value, secret, isSecretBase64Encoded) {
  var result = '', error = null;

  if (isSecretBase64Encoded) {
    try {
      secret = window.b64utob64(secret);
      secret = window.CryptoJS.enc.Base64.parse(secret).toString();
    } catch (e) {
      return {result: '', error: e};
    }
  } else {
    secret = window.CryptoJS.enc.Latin1.parse(secret).toString();
  }

  try {
    result = KJUR.jws.JWS.verify(value, secret);
  } catch (e) {
    error = e;
  }

  return {result: result, error: error};
};
<|endoftext|>


<commit_before> document.addEventListener("deviceready", onDeviceReady, false);
    var db = window.openDatabase("gastos", "1.0", "local database", 200000); //will create database Dummy_DB or open it

    //function will be called when device ready
    function onDeviceReady(){
        db.transaction(populateDB, errorCB, successCB);
    }

    //create table and insert some record
    function populateDB(tx) {
        tx.executeSql('Create Table IF NOT EXISTS categorias_ingreso(id_categoria_ingreso integer primary key, nombre_categoria_ingreso UNIQUE text)');
        tx.executeSql('Create Table IF NOT EXISTS categorias_egreso(id_categoria_egreso integer primary key, nombre_categoria_egreso UNIQUE text)');
        tx.executeSql('Create Table IF NOT EXISTS saldos_ingreso(id_saldo_ingreso integer primary key, fecha_ingreso TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, monto_ingresado real, id_categoria_ingreso integer)');
        tx.executeSql('Create Table IF NOT EXISTS saldos_egreso(id_saldo_egreso integer primary key, fecha_egreso TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, monto_egresado real, id_categoria_egreso integer)');
        tx.executeSql('Create Table IF NOT EXISTS cta(id_cuenta_in integer primary key, nombre text, saldo real)');
    }

    /*//function will be called when an error occurred
    function errorCB(err) {
        console.log("Error processing SQL: "+err.code);
    }

    //function will be called when process succeed
    function successCB() {
        console.log("success!");
        db.transaction(queryDB,errorCB);
    }

    function queryDB(tx){
        tx.executeSql('SELECT id_categoria_ingreso,nombre_categoria_ingreso FROM categorias_ingreso',[],querySuccess,errorCB);
    }

    function querySuccess(tx,result){
         $.each(result.rows,function(index){
           var row = result.rows.item(index);
          $('#main_table').append('
'+row['nombre_categoria_ingreso']+'
');
         });
    }*/

  function checarCuenta(){

		db.transaction(function(tx){
		tx.executeSql('SELECT COUNT(id_cuenta_in) AS cantidad FROM cta',function(tx,res){
			var chequeo = res.rows.item(0).cantidad

			if(chequeo==0){

    		window.location=("../views/four-first.html");
    	}
    	else{

    		window.location=("../index.html");
    	}
	});
	});
	}

function insertarNuevoSaldo(id) {
  var dba = window.openDatabase("gastos", "1.0", "local database", 200000);
  dba.transaction(function(tx) {
    tx.executeSql('INSERT INTO cta(id_cuenta_in,saldo) VALUES (?,?)',[], successCB, errorCB);
  });
}

/*document.addEventListener("deviceready", onDeviceReady, false);
var db;
var saldo_m = document.getElementById('saldo_m');
var saldo_aca = document.getElementById('saldo_aca');
var patrimonio = document.getElementById('patrimonio');
function onDeviceReady(){
db = window.sqlitePlugin.openDatabase({name:"tp1.db"});
console.log(db);
db.transaction(function (tx) {
  tx.executeSql('Create Table IF NOT EXISTS categorias_ingreso(id_categoria_ingreso integer primary key, nombre_categoria_ingreso text)');
  tx.executeSql('Create Table IF NOT EXISTS categorias_egreso(id_categoria_egreso integer primary key, nombre_categoria_egreso text)');
  tx.executeSql('Create Table IF NOT EXISTS saldos_ingreso(id_saldo_ingreso integer primary key, fecha_ingreso TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, monto_ingresado real, id_categoria_ingreso integer)');
  tx.executeSql('Create Table IF NOT EXISTS saldos_egreso(id_saldo_egreso integer primary key, fecha_egreso TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, monto_egresado real, id_categoria_egreso integer)');
  tx.executeSql('Create Table IF NOT EXISTS cta(id_cuenta_in integer primary key, nombre text, saldo real)');
},
function (error) {
  alert("Error en crear la tabla")
});

}
/*
db.transaction(function(tx) {
  tx.executeSql("INSERT INTO test_table(saldo_m,saldo_aca, patrimonio) VALUES (?,?,?)",[1000,2000,3000],function (tx,res) {
  },
function (error) {
  alert("Error al insertar un dato")
},
function (succes) {
  alert("inserId: "+ res.insertId + "-- probably 1")
});
});
*/
/*db.transaction(function (tx) {
  tx.executeSql("select * from test_table;", [], function (tx,res) {
  saldo_m.innerHTML = res.rows.item(0).saldo_m;
  saldo_aca.innerHTML = res.rows.item(0).saldo_aca;
  patrimonio.innerHTML =  res.rows.item(0).patrimonio;
  alert(res);
},function (error) {
  alert("Error al realizar la petcicion")
});
});*/
<commit_msg>Update ken.js<commit_after> document.addEventListener("deviceready", onDeviceReady, false);
    var db = window.openDatabase("gastos", "1.0", "local database", 200000); //will create database Dummy_DB or open it

    //function will be called when device ready
    function onDeviceReady(){
        db.transaction(populateDB, errorCB, successCB);
    }

    //create table and insert some record
    function populateDB(tx) {
        tx.executeSql('Create Table IF NOT EXISTS categorias_ingreso(id_categoria_ingreso integer primary key, nombre_categoria_ingreso text UNIQUE)');
        tx.executeSql('Create Table IF NOT EXISTS categorias_egreso(id_categoria_egreso integer primary key, nombre_categoria_egreso text UNIQUE)');
        tx.executeSql('Create Table IF NOT EXISTS saldos_ingreso(id_saldo_ingreso integer primary key, fecha_ingreso TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, monto_ingresado real, id_categoria_ingreso integer)');
        tx.executeSql('Create Table IF NOT EXISTS saldos_egreso(id_saldo_egreso integer primary key, fecha_egreso TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, monto_egresado real, id_categoria_egreso integer)');
        tx.executeSql('Create Table IF NOT EXISTS cta(id_cuenta_in integer primary key, nombre text, saldo real)');
    }

    /*//function will be called when an error occurred
    function errorCB(err) {
        console.log("Error processing SQL: "+err.code);
    }

    //function will be called when process succeed
    function successCB() {
        console.log("success!");
        db.transaction(queryDB,errorCB);
    }

    function queryDB(tx){
        tx.executeSql('SELECT id_categoria_ingreso,nombre_categoria_ingreso FROM categorias_ingreso',[],querySuccess,errorCB);
    }

    function querySuccess(tx,result){
         $.each(result.rows,function(index){
           var row = result.rows.item(index);
          $('#main_table').append('
'+row['nombre_categoria_ingreso']+'
');
         });
    }*/

  function checarCuenta(){

		db.transaction(function(tx){
		tx.executeSql('SELECT COUNT(id_cuenta_in) AS cantidad FROM cta',function(tx,res){
			var chequeo = res.rows.item(0).cantidad

			if(chequeo==0){

    		window.location=("../views/four-first.html");
    	}
    	else{

    		window.location=("../index.html");
    	}
	});
	});
	}

function insertarNuevoSaldo(id) {
  var dba = window.openDatabase("gastos", "1.0", "local database", 200000);
  dba.transaction(function(tx) {
    tx.executeSql('INSERT INTO cta(id_cuenta_in,saldo) VALUES (?,?)',[], successCB, errorCB);
  });
}

/*document.addEventListener("deviceready", onDeviceReady, false);
var db;
var saldo_m = document.getElementById('saldo_m');
var saldo_aca = document.getElementById('saldo_aca');
var patrimonio = document.getElementById('patrimonio');
function onDeviceReady(){
db = window.sqlitePlugin.openDatabase({name:"tp1.db"});
console.log(db);
db.transaction(function (tx) {
  tx.executeSql('Create Table IF NOT EXISTS categorias_ingreso(id_categoria_ingreso integer primary key, nombre_categoria_ingreso text)');
  tx.executeSql('Create Table IF NOT EXISTS categorias_egreso(id_categoria_egreso integer primary key, nombre_categoria_egreso text)');
  tx.executeSql('Create Table IF NOT EXISTS saldos_ingreso(id_saldo_ingreso integer primary key, fecha_ingreso TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, monto_ingresado real, id_categoria_ingreso integer)');
  tx.executeSql('Create Table IF NOT EXISTS saldos_egreso(id_saldo_egreso integer primary key, fecha_egreso TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, monto_egresado real, id_categoria_egreso integer)');
  tx.executeSql('Create Table IF NOT EXISTS cta(id_cuenta_in integer primary key, nombre text, saldo real)');
},
function (error) {
  alert("Error en crear la tabla")
});

}
/*
db.transaction(function(tx) {
  tx.executeSql("INSERT INTO test_table(saldo_m,saldo_aca, patrimonio) VALUES (?,?,?)",[1000,2000,3000],function (tx,res) {
  },
function (error) {
  alert("Error al insertar un dato")
},
function (succes) {
  alert("inserId: "+ res.insertId + "-- probably 1")
});
});
*/
/*db.transaction(function (tx) {
  tx.executeSql("select * from test_table;", [], function (tx,res) {
  saldo_m.innerHTML = res.rows.item(0).saldo_m;
  saldo_aca.innerHTML = res.rows.item(0).saldo_aca;
  patrimonio.innerHTML =  res.rows.item(0).patrimonio;
  alert(res);
},function (error) {
  alert("Error al realizar la petcicion")
});
});*/
<|endoftext|>


<commit_before>// kkk.js
var isMap = false;

$(function(){

	$( "#day" ).click(function() {
		setDay();
	});

	$( "#day-today" ).click(function() {
		setToday();
	});

	$( "#day-tomorrow" ).click(function() {
		setTomorrow();
	});

	$( "#time" ).click(function() {
		var temp = ($(this).text().substr(0,2)*1 +1)%24;
		$("#time").text($( "#time-"+temp ).text());
	});

	for(var i = 0; i < 24; i++){
		var temp = i;
		$( "#time-"+temp ).click(function() {
			$( "#time" ).text($(this).text());
	});
	}

	$( "#btn-findmap" ).click(function() {
		setButtons();
		initReserveView();
	});

	$( "#btn-back" ).click(function() {
		setButtons();
		initReserveView();
	});

	$( "#btn-lastRackHistory" ).click(function() {
		initReserveView();
		// this function is in googlemap.js
		if(window.localStorage.getItem('lastRackHistory') > -1){
			showRackState(window.localStorage.getItem('lastRackHistory'));
		}
	});

	$( "#btn-nearestRack" ).click(function() {
		initReserveView();
	});

	$( "#btn-reserve" ).click(function() {
		if (currentRid == -1) {
			console.log("rid error");
			return false;
		}

		$.post('/bicycle/reserve',
		{
			'rid' : ''+currentRid
		},
		function(response) {
			if (response.status === 0) {
				// Success!
				window.localStorage.setItem('lastRackHistory', currentRid);
				//location.href = '/reservation';
				showRackState(currentRid);
		}, 'json')
		.fail(function(jqxhr) {
				// Fail.
				alert(jqxhr.responseJSON.data);
		});

		return false;
	});

	if(window.localStorage.getItem('lastRackHistory') == "" ||
		window.localStorage.getItem('lastRackHistory') == null ){
		$( "#btn-lastRackHistory").addClass("disabled");
	} else {
		$( "#btn-lastRackHistory").removeClass("disabled");
	}

});

var dayByday = true;
var time = 0;

function setButtons(){
	if(isMap){

		$("#btn-back").css("visibility","hidden");
		$("#map-canvas").css("visibility","hidden");

		$(".span6 .btn-large").css("display", "inline");
	} else {

		$("#btn-back").css("visibility","visible");
		$("#map-canvas").css("visibility","visible");
		// this function is in googlemap.js
		resetDrop();
		$(".span6 .btn-large").css("display", "none");

	}

	isMap = !isMap;

}

function setDay(){
	if(dayByday){
		$( "#day" ).text("Tomorrow");
	}else{
		$( "#day" ).text("Today");
	}

	dayByday = !dayByday;
}

function setToday(){
	$( "#day" ).text("Today");
	dayByday = true;
}

function setTomorrow(){
	$( "#day" ).text("Tomorrow");
	dayByday = false;
}

function initReserveView(){
	$( "#btn-reserve").addClass("disabled");
	$( "#bar-free").width("0%");
	$( "#bar-rest").width("0%");
	$("#locationInfo").text("");
	currentRid = -1;
}

function clickResereBtn(){

}

<commit_msg>Reservation Button<commit_after>// kkk.js
var isMap = false;

$(function(){

	$( "#day" ).click(function() {
		setDay();
	});

	$( "#day-today" ).click(function() {
		setToday();
	});

	$( "#day-tomorrow" ).click(function() {
		setTomorrow();
	});

	$( "#time" ).click(function() {
		var temp = ($(this).text().substr(0,2)*1 +1)%24;
		$("#time").text($( "#time-"+temp ).text());
	});

	for(var i = 0; i < 24; i++){
		var temp = i;
		$( "#time-"+temp ).click(function() {
			$( "#time" ).text($(this).text());
	});
	}

	$( "#btn-findmap" ).click(function() {
		setButtons();
		initReserveView();
	});

	$( "#btn-back" ).click(function() {
		setButtons();
		initReserveView();
	});

	$( "#btn-lastRackHistory" ).click(function() {
		initReserveView();
		// this function is in googlemap.js
		if(window.localStorage.getItem('lastRackHistory') > -1){
			showRackState(window.localStorage.getItem('lastRackHistory'));
		}
	});

	$( "#btn-nearestRack" ).click(function() {
		initReserveView();
	});

	$( "#btn-reserve" ).click(function() {
		if (currentRid == -1) {
			console.log("rid error");
			return false;
		}

		$.post('/bicycle/reserve',
		{
			'rid' : ''+currentRid
		},
		function(response) {
			// Success!
			window.localStorage.setItem('lastRackHistory', currentRid);
			//location.href = '/reservation';
			showRackState(currentRid);
		}, 'json')
		.fail(function(jqxhr) {
				// Fail.
				alert(jqxhr.responseJSON.data);
		});

		return false;
	});

	if(window.localStorage.getItem('lastRackHistory') == "" ||
		window.localStorage.getItem('lastRackHistory') == null ){
		$( "#btn-lastRackHistory").addClass("disabled");
	} else {
		$( "#btn-lastRackHistory").removeClass("disabled");
	}

});

var dayByday = true;
var time = 0;

function setButtons(){
	if(isMap){

		$("#btn-back").css("visibility","hidden");
		$("#map-canvas").css("visibility","hidden");

		$(".span6 .btn-large").css("display", "inline");
	} else {

		$("#btn-back").css("visibility","visible");
		$("#map-canvas").css("visibility","visible");
		// this function is in googlemap.js
		resetDrop();
		$(".span6 .btn-large").css("display", "none");

	}

	isMap = !isMap;

}

function setDay(){
	if(dayByday){
		$( "#day" ).text("Tomorrow");
	}else{
		$( "#day" ).text("Today");
	}

	dayByday = !dayByday;
}

function setToday(){
	$( "#day" ).text("Today");
	dayByday = true;
}

function setTomorrow(){
	$( "#day" ).text("Tomorrow");
	dayByday = false;
}

function initReserveView(){
	$( "#btn-reserve").addClass("disabled");
	$( "#bar-free").width("0%");
	$( "#bar-rest").width("0%");
	$("#locationInfo").text("");
	currentRid = -1;
}

function clickResereBtn(){

}

<|endoftext|>


<commit_before>var placeSearch, autocomplete,
    map, searchBox, destination = "Sydney",
    country = "Australia";

function updateSearchBox() {
    searchBox.set('places', [autocomplete.getPlace()]);
}

function showSearchMap() {
    console.log("Inside showSearchMap");

    var map = new google.maps.Map(document.getElementById('map'), {
        center: {
            lat: -33.8688,
            lng: 151.2195
        },
        zoom: 15,
        mapTypeId: 'roadmap',

     });

    var input = document.getElementById('pac-input');

    searchBox = new google.maps.places.SearchBox(input);
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    // Bias the SearchBox results towards current map's viewport.
    map.addListener('bounds_changed', function() {
        searchBox.setBounds(map.getBounds());
    });

    var markers = [];
    // Listen for the event fired when the user selects a prediction and retrieve
    // more details for that place.
    searchBox.addListener('places_changed', function() {
        console.log("search box places changed !!");
        console.log(arguments);
        var places = searchBox.getPlaces();

        if (places.length == 0) {
            return;
        }

        // Clear out the old markers.
        markers.forEach(function(marker) {
            marker.setMap(null);
        });
        markers = [];

        // For each place, get the icon, name and location.
        var bounds = new google.maps.LatLngBounds();
        places.forEach(function(place) {
            if (!place.geometry) {
                console.log("Returned place contains no geometry");
                return;
            }
            var icon = {
                url: place.icon,
                size: new google.maps.Size(71, 71),
                origin: new google.maps.Point(0, 0),
                anchor: new google.maps.Point(17, 34),
                scaledSize: new google.maps.Size(25, 25)
            };

            // Create a marker for each place.
            var marker = new google.maps.Marker({
                map: map,
                icon: icon,
                title: place.name,
                position: place.geometry.location,
                animation: google.maps.Animation.BOUNCE

            });
            google.maps.event.addListener(marker, 'click', function() {
                map.setZoom(9);
                map.setCenter(marker.getPosition());
            });
            markers.push(marker);

            if (place.geometry.viewport) {
                // Only geocodes have viewport.
                bounds.union(place.geometry.viewport);
            } else {
                bounds.extend(place.geometry.location);
            }

            $('html, body').stop().animate({
                scrollTop: ($("#mapArea").offset().top - 50)
            }, 1250, 'easeInOutExpo');

            destination = place.name;
            weatherFunc();
            getImagesFunc();
            console.log("Current Destination:" + destination);
            console.log(place);
            getCountryName(place);
            fillInfo();

        });
        map.fitBounds(bounds);

    });
}

function getCountryName(place) {
    for (var i = 0; i < place.address_components.length; i++) {
        var addressType = place.address_components[i].types[0];
        if (addressType == 'country') {
            country = place.address_components[i]['long_name'];
        }
    }
    console.log("Current country" + country);
}

function initAutocomplete() {
    console.log("Initializing auto complete and search boxes");
    // Create the autocomplete object, restricting the search to geographical
    // location types.
    showSearchMap();

    autocomplete = new google.maps.places.Autocomplete(
        /** @type {!HTMLInputElement} */
        (document.getElementById('autocomplete')), {
            types: ['geocode']
        });

    // When the user selects an address from the dropdown, populate the address
    // fields in the form.
    autocomplete.addListener('place_changed', updateSearchBox);

}

$("form").submit(function(e) {
    e.preventDefault();
});
<commit_msg>styled map<commit_after>var placeSearch, autocomplete,
    map, searchBox, destination = "Sydney",
    country = "Australia",
    styledMapType;

function updateSearchBox() {
    searchBox.set('places', [autocomplete.getPlace()]);
}

function showSearchMap() {
    console.log("Inside showSearchMap");

    var map = new google.maps.Map(document.getElementById('map'), {
        center: {
            lat: -33.8688,
            lng: 151.2195
        },
        zoom: 15,
        mapTypeControlOptions: {
            mapTypeIds: ['roadmap', 'satellite', 'hybrid', 'terrain',
                'styled_map'
            ]
        }

    });
    map.mapTypes.set('styled_map', styledMapType);
    map.setMapTypeId('styled_map');

    var input = document.getElementById('pac-input');

    searchBox = new google.maps.places.SearchBox(input);
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    // Bias the SearchBox results towards current map's viewport.
    map.addListener('bounds_changed', function() {
        searchBox.setBounds(map.getBounds());
    });

    var markers = [];
    // Listen for the event fired when the user selects a prediction and retrieve
    // more details for that place.
    searchBox.addListener('places_changed', function() {
        console.log("search box places changed !!");
        console.log(arguments);
        var places = searchBox.getPlaces();

        if (places.length == 0) {
            return;
        }

        // Clear out the old markers.
        // markers.forEach(function(marker) {
        //     marker.setMap(null);
        // });
        markers = [];

        // For each place, get the icon, name and location.
        var bounds = new google.maps.LatLngBounds();
        places.forEach(function(place) {
            if (!place.geometry) {
                console.log("Returned place contains no geometry");
                return;
            }
            var image = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';

            var icon = {
                url: place.icon,
                size: new google.maps.Size(71, 71),
                origin: new google.maps.Point(0, 0),
                anchor: new google.maps.Point(17, 34),
                scaledSize: new google.maps.Size(25, 25)
            };

            // Create a marker for each place.
            // var marker = new google.maps.Marker({
            //     map: map,
            //     icon: image,
            //     title: place.name,
            //     position: place.geometry.location,
            //     animation: google.maps.Animation.BOUNCE
            //
            // });
            // google.maps.event.addListener(marker, 'click', function() {
            //     map.setZoom(9);
            //     map.setCenter(marker.getPosition());
            // });
            // markers.push(marker);

            map.mapTypes.set('styled_map', styledMapType);
            map.setMapTypeId('styled_map');

            if (place.geometry.viewport) {
                // Only geocodes have viewport.
                bounds.union(place.geometry.viewport);
            } else {
                bounds.extend(place.geometry.location);
            }

            $('html, body').stop().animate({
                scrollTop: ($("#mapArea").offset().top - 50)
            }, 1250, 'easeInOutExpo');

            destination = place.name;
            weatherFunc();
            getImagesFunc();
            console.log("Current Destination:" + destination);
            console.log(place);
            getCountryName(place);
            fillInfo();

        });
        map.fitBounds(bounds);

    });
}

function getCountryName(place) {
    for (var i = 0; i < place.address_components.length; i++) {
        var addressType = place.address_components[i].types[0];
        if (addressType == 'country') {
            country = place.address_components[i]['long_name'];
        }
    }
    console.log("Current country" + country);
}

function initAutocomplete() {
    console.log("Initializing auto complete and search boxes");
    styledMapType = new google.maps.StyledMapType(
        style, {
            name: 'Styled Map'
        });
    // Create the autocomplete object, restricting the search to geographical
    // location types.
    showSearchMap();

    autocomplete = new google.maps.places.Autocomplete(
        /** @type {!HTMLInputElement} */
        (document.getElementById('autocomplete')), {
            types: ['geocode']
        });

    // When the user selects an address from the dropdown, populate the address
    // fields in the form.
    autocomplete.addListener('place_changed', updateSearchBox);

}

$("form").submit(function(e) {
    e.preventDefault();
});

var style = [{
        "elementType": "geometry",
        "stylers": [{
            "color": "#212121"
        }]
    },
    {
        "elementType": "labels.icon",
        "stylers": [{
            "visibility": "off"
        }]
    },
    {
        "elementType": "labels.text.fill",
        "stylers": [{
            "color": "#757575"
        }]
    },
    {
        "elementType": "labels.text.stroke",
        "stylers": [{
            "color": "#212121"
        }]
    },
    {
        "featureType": "administrative",
        "elementType": "geometry",
        "stylers": [{
            "color": "#757575"
        }]
    },
    {
        "featureType": "administrative.country",
        "elementType": "labels.text.fill",
        "stylers": [{
            "color": "#9e9e9e"
        }]
    },
    {
        "featureType": "administrative.land_parcel",
        "stylers": [{
            "visibility": "off"
        }]
    },
    {
        "featureType": "administrative.locality",
        "elementType": "labels.text.fill",
        "stylers": [{
            "color": "#bdbdbd"
        }]
    },
    {
        "featureType": "landscape.natural.landcover",
        "stylers": [{
                "color": "#804040"
            },
            {
                "visibility": "simplified"
            }
        ]
    },
    {
        "featureType": "poi",
        "elementType": "labels.text.fill",
        "stylers": [{
            "color": "#757575"
        }]
    },
    {
        "featureType": "poi.attraction",
        "stylers": [{
                "color": "#ffff00"
            },
            {
                "visibility": "simplified"
            },
            {
                "weight": 6.5
            }
        ]
    },
    {
        "featureType": "poi.attraction",
        "elementType": "geometry.fill",
        "stylers": [{
            "visibility": "off"
        }]
    },
    {
        "featureType": "poi.park",
        "elementType": "geometry",
        "stylers": [{
            "color": "#181818"
        }]
    },
    {
        "featureType": "poi.park",
        "elementType": "labels.text.fill",
        "stylers": [{
            "color": "#616161"
        }]
    },
    {
        "featureType": "poi.park",
        "elementType": "labels.text.stroke",
        "stylers": [{
            "color": "#1b1b1b"
        }]
    },
    {
        "featureType": "poi.place_of_worship",
        "stylers": [{
                "color": "#ffff00"
            },
            {
                "visibility": "simplified"
            }
        ]
    },
    {
        "featureType": "poi.place_of_worship",
        "elementType": "geometry",
        "stylers": [{
            "visibility": "simplified"
        }]
    },
    {
        "featureType": "poi.place_of_worship",
        "elementType": "geometry.stroke",
        "stylers": [{
            "visibility": "simplified"
        }]
    },
    {
        "featureType": "poi.place_of_worship",
        "elementType": "labels.icon",
        "stylers": [{
            "visibility": "off"
        }]
    },
    {
        "featureType": "road",
        "elementType": "geometry.fill",
        "stylers": [{
            "color": "#2c2c2c"
        }]
    },
    {
        "featureType": "road",
        "elementType": "labels.text.fill",
        "stylers": [{
            "color": "#8a8a8a"
        }]
    },
    {
        "featureType": "road.arterial",
        "elementType": "geometry",
        "stylers": [{
            "color": "#373737"
        }]
    },
    {
        "featureType": "road.highway",
        "elementType": "geometry",
        "stylers": [{
            "color": "#3c3c3c"
        }]
    },
    {
        "featureType": "road.highway.controlled_access",
        "elementType": "geometry",
        "stylers": [{
            "color": "#4e4e4e"
        }]
    },
    {
        "featureType": "road.local",
        "elementType": "labels.text.fill",
        "stylers": [{
            "color": "#616161"
        }]
    },
    {
        "featureType": "transit",
        "elementType": "labels.text.fill",
        "stylers": [{
            "color": "#757575"
        }]
    },
    {
        "featureType": "water",
        "elementType": "geometry",
        "stylers": [{
            "color": "#000000"
        }]
    },
    {
        "featureType": "water",
        "elementType": "labels.text.fill",
        "stylers": [{
            "color": "#3d3d3d"
        }]
    }
];
<|endoftext|>


<commit_before>// TODO split osm-pbf-leaflet into separate projects
//require('osm-pbf-leaflet');
require('../node_modules/osm-pbf-leaflet/lib/OSMReader.js');
require('../node_modules/osm-pbf-leaflet/lib/leaflet-osm.js');
require('leaflet-tilelayer-vector');
require('../lib/Permalink.js');
require('../lib/Leaflet.zoomslider/src/L.Control.Zoomslider.js');
require('./L.Control.Zoomslider-patch.js');
require('../lib/Leaflet.zoomdisplay/leaflet.zoomdisplay.js');
require('./Control.Progress');
//require('./Control.ZoomInfo.js');
require('./PbfWorker.js');
require('./Path._updatePathViewport.js');

var popup = require('./popup.js');
var miniMap = require('./minimap.js');

var map;
var baseLayer;
var emptyBaseLayer;
var vectorTileLayer;
var tileDebugLayer;
var layerControl;
var visibility = 'visible';
var baseLayerActive = false;
var landuse = true;

/**
 * Changes the visibility for all features (supporting hover only)
 *
 * @param {string} 'visible' | 'hidden'
 */
var updateVisibility = function(aVisibility) {
    visibility = aVisibility;
    if (visibility === 'hidden') {
        activateBaseLayer();
    } else {
        restoreBaseLayer();
    }

    if (L.Path.CANVAS) {
        map._pathRoot.style.visibility = aVisibility;
    } else {
        // does not work as expected in Chrome (v26):
        // when svg root is hidden, setting visible on child has no effect
        //map._pathRoot.setAttribute('visibility', visibility);
        var children = map._pathRoot.childNodes;
        for (var i = 0; i < children.length; i++) {
            setPathVisibility(children[i], aVisibility);
        }
        map._pathRoot.setAttribute('pointer-events', 'painted');
    }
};

var activateBaseLayer = function() {
    baseLayerActive = map.hasLayer(baseLayer);
    if (!baseLayerActive) {
        map.addLayer(baseLayer);
        map.removeLayer(emptyBaseLayer);
    }
};

var restoreBaseLayer = function() {
    if (!baseLayerActive) {
        map.removeLayer(baseLayer);
        map.addLayer(emptyBaseLayer);
    }
};

var setPathVisibility = function(pathEle, aVisibility) {
    if (pathEle) {
        pathEle.setAttribute('visibility', aVisibility);
    }
};

var showLanduse = function(aLanduse) {
    landuse = aLanduse;
    vectorTileLayer.redraw();
};

function init() {

    // enlarge vector clip bounds, restricted by tile bounds,
    // see Path._updatePathViewport.js
    L.Path.CLIP_PADDING = 1;

    map = L.map('map', {
        minZoom: 5,
        maxZoom: 19,
        // disable keyboard, L.Map.Keyboard._onMouseDown slow (?)
        keyboard: false,
        // disable force/kinetic dragging, not recognizable with many vectors, sometimes too fast
        inertia: false,
        // ignored by MiniMap > reset setView in minimap.js
        //reset: true,
        //animate: false
    });
    map.setView([47.7223, 9.3854], 14);
    map.addControl(new L.Control.Permalink({text: 'Permalink'}));
    //map.addControl(new L.Control.ZoomInfo());

    emptyBaseLayer = L.layerGroup().addTo(map);
    baseLayer = new L.OSM.Mapnik({
        attribution: 'map © OpenStreetMap contributors'
    });

    var colors = {
        // Leaflet colors (http://leafletjs.com/examples/geojson.html)
        polygon: '#b0de5c',
        line: '#0033ff',
        point: '#ff7800',
        hover: 'red'
    };

    var pointStyle = {
        radius: 4,
        fillColor: colors.point,
        color: "#000",
        weight: 1,
        opacity: 1,
        fillOpacity: 0.8
    };
    var lineStyle = {
        weight: 4,
        opacity: 0.7,
        color: colors.line
    };
    var polygonStyle = {
        weight: 2,
        color: "#999",
        opacity: 1,
        fillColor: colors.polygon,
        fillOpacity: 0.5
    };
    var styles = {
        node: pointStyle,
        way: lineStyle,
        area: polygonStyle
    };

    var getHoverStyle = function(layer) {
        return {
            weight: layer.options.weight + 1,
            color: colors.hover,
            fillColor: colors.hover
        };
    };
    var bindHover = function(feature, layer) {
        layer.on('mouseover', function(evt) {
            if (!this.defaultOptions) {
                this.defaultOptions = this.options;
            }
            this.setStyle(getHoverStyle(this));
            setPathVisibility(this._path, 'visible');

            // lazy label binding for better performance
            // (registering less events + creating less objects on tile load)
            var popupContent = popup.getFeatureInfoHtml(this.feature);
            if (!this._label) {
                this.bindLabel(popupContent);
                this._showLabel(evt);
            }
        }, layer);
        layer.on('mouseout', function(evt) {
            // TODO resetStyle for L.OSM.DataLayer? (has styles instead of style)
            //layer.resetStyle(evt.target);
            L.Util.extend(this.options, this.defaultOptions);
            this.setStyle(this.options);
            setPathVisibility(this._path, 'inherit');
        }, layer);
    };

    var bindPopup = function(feature, layer) {
        layer.on('click', function(evt) {
            // lazy popup binding for better performance
            // (registering less events + creating less objects on tile load)
            var popupContent = popup.getFeatureInfoHtml(this.feature);
            this.bindPopup(popupContent, {offset:new L.Point(0,0)});
            this._openPopup(evt);
        }, layer);
    };

    function allKeys(tags, start) {
        for (key in tags) {
            if (!(start === key.substr(0, start.length))) {
                return false;
            }
        }
        return true;
    }

    // true keeps feature, false discards
    var filter = function(feature) {
        var tags = feature.tags,
            noTags = Object.keys(tags).length === 0;
        return (map.getZoom() >= 17
            || !(noTags || tags.building || allKeys(tags, 'building') || allKeys(tags, 'roof:')
                || allKeys(tags, 'addr:') || tags.natural === 'tree' || tags.highway === 'street_lamp'))
            && (map.getZoom() >= 15 || !(feature.type === 'node') || tags.place)
            && (landuse || !(feature.area && (tags.landuse || tags.natural || tags.leisure)));
    };

    var vectorOptions = {
        filter: filter,
        styles: styles,
        onEachFeature: function(feature, layer) {
            bindHover(feature, layer);
            bindPopup(feature, layer);
            layer.on('add', function(evt) {
                setPathVisibility(evt.target._container, visibility);
            });
        }
    };

    var tileOptions = {
        // remove tiles outside viewport
        unloadInvisibleTiles: true,
        // no tile loading while panning, too slow with large vector tiles
        updateWhenIdle: true,
        // unique feature key function, for filtering duplicate features contained in multiple tiles
        unique: function(feature) {
            return feature.type.substr(0,1) + feature.id;
        },
        // factory function for creating the actual vector layer, default is L.geoJson
        // PBF parsing done in worker, use default layer here to avoid dependency in main bundle
        //layerFactory: L.osmPbf
        layerFactory: function(data, options) {
            return new L.OSM.DataLayer(data, options);
        },
        // web worker
        workerFactory: L.pbfWorker,
        //workerFactory: L.noWorker,
        // fixed zoom level 13 for Mapsplit tiles (resize all other levels)
        serverZooms: [13],
        minZoom: 13,
        maxZoom: 19,
        attribution: 'data © OpenStreetMap contributors, '
            + 'licensed under ODbL'
    };

    vectorTileLayer = new L.TileLayer.Vector.Unclipped("tiles/{x}_{y}.pbf", tileOptions, vectorOptions);
    /*
    vectorTileLayer.on('loading', function() {
        console.time('load');
        timer.reset();
    });
    vectorTileLayer.on('load', function() {
        console.timeEnd('load');
        timer.report();
        //var tilesKeys = Object.keys(vectorTileLayer._tiles);
        //console.log('_tiles (' + tilesKeys.length + '): ' + tilesKeys);
    });
    map.on('moveend', function() {
        console.log('----- moveend -----');
    });
    */

    // hack for Path_updatePathViewport.js
    map._vectorTileLayer = vectorTileLayer;

    map.addControl(new L.Control.Progress(vectorTileLayer, {div: 'progress-container'}));
    map.addLayer(vectorTileLayer);

    var progressLayer = new L.TileLayer.Progress(vectorTileLayer).addTo(map);

    layerControl = L.control.layers({
        'no base layer': emptyBaseLayer,
        'OSM Mapnik': baseLayer
    }, {
        'Vector Tiles': vectorTileLayer,
        'Loading Tiles': progressLayer
    }).addTo(map);

    // MiniMap (overview map)
    miniMap.init(map);

    /*
    // debug layer, from:
    // http://blog.mathieu-leplatre.info/leaflet-tiles-in-lambert-93-projection-2154.html
    tileDebugLayer = L.tileLayer.canvas();
    tileDebugLayer.drawTile = function(canvas, tilePoint, zoom) {
        var ctx = canvas.getContext('2d');
        ctx.strokeStyle = ctx.fillStyle = "red";
        ctx.rect(0,0, 256,256);
        ctx.stroke();
        ctx.fillText('' + tilePoint.x + '_' + tilePoint.y,5,10);
    };
    map.addLayer(tileDebugLayer);
    */
}

init();

exports.updateVisibility = updateVisibility;
exports.showLanduse = showLanduse;
exports.map = map;
exports.activateBaseLayer = activateBaseLayer;
exports.restoreBaseLayer = restoreBaseLayer;
<commit_msg>building:demolished >= 17<commit_after>// TODO split osm-pbf-leaflet into separate projects
//require('osm-pbf-leaflet');
require('../node_modules/osm-pbf-leaflet/lib/OSMReader.js');
require('../node_modules/osm-pbf-leaflet/lib/leaflet-osm.js');
require('leaflet-tilelayer-vector');
require('../lib/Permalink.js');
require('../lib/Leaflet.zoomslider/src/L.Control.Zoomslider.js');
require('./L.Control.Zoomslider-patch.js');
require('../lib/Leaflet.zoomdisplay/leaflet.zoomdisplay.js');
require('./Control.Progress');
//require('./Control.ZoomInfo.js');
require('./PbfWorker.js');
require('./Path._updatePathViewport.js');

var popup = require('./popup.js');
var miniMap = require('./minimap.js');

var map;
var baseLayer;
var emptyBaseLayer;
var vectorTileLayer;
var tileDebugLayer;
var layerControl;
var visibility = 'visible';
var baseLayerActive = false;
var landuse = true;

/**
 * Changes the visibility for all features (supporting hover only)
 *
 * @param {string} 'visible' | 'hidden'
 */
var updateVisibility = function(aVisibility) {
    visibility = aVisibility;
    if (visibility === 'hidden') {
        activateBaseLayer();
    } else {
        restoreBaseLayer();
    }

    if (L.Path.CANVAS) {
        map._pathRoot.style.visibility = aVisibility;
    } else {
        // does not work as expected in Chrome (v26):
        // when svg root is hidden, setting visible on child has no effect
        //map._pathRoot.setAttribute('visibility', visibility);
        var children = map._pathRoot.childNodes;
        for (var i = 0; i < children.length; i++) {
            setPathVisibility(children[i], aVisibility);
        }
        map._pathRoot.setAttribute('pointer-events', 'painted');
    }
};

var activateBaseLayer = function() {
    baseLayerActive = map.hasLayer(baseLayer);
    if (!baseLayerActive) {
        map.addLayer(baseLayer);
        map.removeLayer(emptyBaseLayer);
    }
};

var restoreBaseLayer = function() {
    if (!baseLayerActive) {
        map.removeLayer(baseLayer);
        map.addLayer(emptyBaseLayer);
    }
};

var setPathVisibility = function(pathEle, aVisibility) {
    if (pathEle) {
        pathEle.setAttribute('visibility', aVisibility);
    }
};

var showLanduse = function(aLanduse) {
    landuse = aLanduse;
    vectorTileLayer.redraw();
};

function init() {

    // enlarge vector clip bounds, restricted by tile bounds,
    // see Path._updatePathViewport.js
    L.Path.CLIP_PADDING = 1;

    map = L.map('map', {
        minZoom: 5,
        maxZoom: 19,
        // disable keyboard, L.Map.Keyboard._onMouseDown slow (?)
        keyboard: false,
        // disable force/kinetic dragging, not recognizable with many vectors, sometimes too fast
        inertia: false,
        // ignored by MiniMap > reset setView in minimap.js
        //reset: true,
        //animate: false
    });
    map.setView([47.7223, 9.3854], 14);
    map.addControl(new L.Control.Permalink({text: 'Permalink'}));
    //map.addControl(new L.Control.ZoomInfo());

    emptyBaseLayer = L.layerGroup().addTo(map);
    baseLayer = new L.OSM.Mapnik({
        attribution: 'map © OpenStreetMap contributors'
    });

    var colors = {
        // Leaflet colors (http://leafletjs.com/examples/geojson.html)
        polygon: '#b0de5c',
        line: '#0033ff',
        point: '#ff7800',
        hover: 'red'
    };

    var pointStyle = {
        radius: 4,
        fillColor: colors.point,
        color: "#000",
        weight: 1,
        opacity: 1,
        fillOpacity: 0.8
    };
    var lineStyle = {
        weight: 4,
        opacity: 0.7,
        color: colors.line
    };
    var polygonStyle = {
        weight: 2,
        color: "#999",
        opacity: 1,
        fillColor: colors.polygon,
        fillOpacity: 0.5
    };
    var styles = {
        node: pointStyle,
        way: lineStyle,
        area: polygonStyle
    };

    var getHoverStyle = function(layer) {
        return {
            weight: layer.options.weight + 1,
            color: colors.hover,
            fillColor: colors.hover
        };
    };
    var bindHover = function(feature, layer) {
        layer.on('mouseover', function(evt) {
            if (!this.defaultOptions) {
                this.defaultOptions = this.options;
            }
            this.setStyle(getHoverStyle(this));
            setPathVisibility(this._path, 'visible');

            // lazy label binding for better performance
            // (registering less events + creating less objects on tile load)
            var popupContent = popup.getFeatureInfoHtml(this.feature);
            if (!this._label) {
                this.bindLabel(popupContent);
                this._showLabel(evt);
            }
        }, layer);
        layer.on('mouseout', function(evt) {
            // TODO resetStyle for L.OSM.DataLayer? (has styles instead of style)
            //layer.resetStyle(evt.target);
            L.Util.extend(this.options, this.defaultOptions);
            this.setStyle(this.options);
            setPathVisibility(this._path, 'inherit');
        }, layer);
    };

    var bindPopup = function(feature, layer) {
        layer.on('click', function(evt) {
            // lazy popup binding for better performance
            // (registering less events + creating less objects on tile load)
            var popupContent = popup.getFeatureInfoHtml(this.feature);
            this.bindPopup(popupContent, {offset:new L.Point(0,0)});
            this._openPopup(evt);
        }, layer);
    };

    function allKeys(tags, start) {
        for (key in tags) {
            if (!(start === key.substr(0, start.length))) {
                return false;
            }
        }
        return true;
    }

    // true keeps feature, false discards
    var filter = function(feature) {
        var tags = feature.tags,
            noTags = Object.keys(tags).length === 0;
        return (map.getZoom() >= 17
            || !(noTags || tags.building || allKeys(tags, 'building') || allKeys(tags, 'roof:')
                || allKeys(tags, 'addr:') || tags.natural === 'tree' || tags.highway === 'street_lamp'
                || tags.barrier === 'fence' || tags['building:demolished'] === 'yes'))
            && (map.getZoom() >= 15 || !(feature.type === 'node') || tags.place)
            && (landuse || !(feature.area && (tags.landuse || tags.natural || tags.leisure)));
    };

    var vectorOptions = {
        filter: filter,
        styles: styles,
        onEachFeature: function(feature, layer) {
            bindHover(feature, layer);
            bindPopup(feature, layer);
            layer.on('add', function(evt) {
                setPathVisibility(evt.target._container, visibility);
            });
        }
    };

    var tileOptions = {
        // remove tiles outside viewport
        unloadInvisibleTiles: true,
        // no tile loading while panning, too slow with large vector tiles
        updateWhenIdle: true,
        // unique feature key function, for filtering duplicate features contained in multiple tiles
        unique: function(feature) {
            return feature.type.substr(0,1) + feature.id;
        },
        // factory function for creating the actual vector layer, default is L.geoJson
        // PBF parsing done in worker, use default layer here to avoid dependency in main bundle
        //layerFactory: L.osmPbf
        layerFactory: function(data, options) {
            return new L.OSM.DataLayer(data, options);
        },
        // web worker
        workerFactory: L.pbfWorker,
        //workerFactory: L.noWorker,
        // fixed zoom level 13 for Mapsplit tiles (resize all other levels)
        serverZooms: [13],
        minZoom: 13,
        maxZoom: 19,
        attribution: 'data © OpenStreetMap contributors, '
            + 'licensed under ODbL'
    };

    vectorTileLayer = new L.TileLayer.Vector.Unclipped("tiles/{x}_{y}.pbf", tileOptions, vectorOptions);
    /*
    vectorTileLayer.on('loading', function() {
        console.time('load');
        timer.reset();
    });
    vectorTileLayer.on('load', function() {
        console.timeEnd('load');
        timer.report();
        //var tilesKeys = Object.keys(vectorTileLayer._tiles);
        //console.log('_tiles (' + tilesKeys.length + '): ' + tilesKeys);
    });
    map.on('moveend', function() {
        console.log('----- moveend -----');
    });
    */

    // hack for Path_updatePathViewport.js
    map._vectorTileLayer = vectorTileLayer;

    map.addControl(new L.Control.Progress(vectorTileLayer, {div: 'progress-container'}));
    map.addLayer(vectorTileLayer);

    var progressLayer = new L.TileLayer.Progress(vectorTileLayer).addTo(map);

    layerControl = L.control.layers({
        'no base layer': emptyBaseLayer,
        'OSM Mapnik': baseLayer
    }, {
        'Vector Tiles': vectorTileLayer,
        'Loading Tiles': progressLayer
    }).addTo(map);

    // MiniMap (overview map)
    miniMap.init(map);

    /*
    // debug layer, from:
    // http://blog.mathieu-leplatre.info/leaflet-tiles-in-lambert-93-projection-2154.html
    tileDebugLayer = L.tileLayer.canvas();
    tileDebugLayer.drawTile = function(canvas, tilePoint, zoom) {
        var ctx = canvas.getContext('2d');
        ctx.strokeStyle = ctx.fillStyle = "red";
        ctx.rect(0,0, 256,256);
        ctx.stroke();
        ctx.fillText('' + tilePoint.x + '_' + tilePoint.y,5,10);
    };
    map.addLayer(tileDebugLayer);
    */
}

init();

exports.updateVisibility = updateVisibility;
exports.showLanduse = showLanduse;
exports.map = map;
exports.activateBaseLayer = activateBaseLayer;
exports.restoreBaseLayer = restoreBaseLayer;
<|endoftext|>


<commit_before>var data;
var marker;
var markers = new Array();
var contentStrings = new Array();
var lat1;
var lon1;

// TODO for tomorrow - refactor the file thoroughly!!!
$(document).bind( "mobileinit", function(event) {
    $.extend($.mobile.zoom, {locked:false,enabled:true});
});

$('#backToCube').click(function(){
  window.location.href = ".";
});

$(window).resize(function(){
  windowWidth = $(window).width();
  $('#helpCard1').css('margin-left',(windowWidth/2 - 125).toString()+"px");
  $('#goBackCard').css('margin-left',(windowWidth/2 - 125).toString()+"px");

  windowHeight = $(window).height();
  $('#backToCube').css('margin-top',(windowHeight/2 - 35).toString()+"px");
});

$(document).ready(function(){

  cookieArray = [];
  initialCookieArray = document.cookie.split('; ').sort();
  for (var x in initialCookieArray){
    if (initialCookieArray[x].indexOf("sports") != -1 ||
        initialCookieArray[x].indexOf("days") != -1 ||
        initialCookieArray[x].indexOf("price") != -1 ||
        initialCookieArray[x].indexOf("isComingFromMap") !=-1 ||
        initialCookieArray[x].indexOf("tutorialModeOn") != -1)
    {
      cookieArray.push(initialCookieArray[x])
    }
  }
  cookieArray.sort();

  tutorialMode = cookieArray[4].split('=')[1];
  isComingFromMap = cookieArray[1].split('=')[1];

  console.log(cookieArray)

  var windowHeight = $(window).height();
  $('#backToCube').css('margin-top',(windowHeight/2 - 35).toString()+"px");
  // creating the map and the info window
  var myLatlng = new google.maps.LatLng(55.950, -3.190);  //Edinburgh center

  var mapOptions = {
    zoom: 12,
    center: myLatlng,
    minZoom: 10,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById('map-canvas'),
                mapOptions);

  var infoWindowOptions = {
    maxWidth: 300
  };
  var infowindow = new google.maps.InfoWindow(infoWindowOptions);

  if( tutorialMode == 'true' ){

    windowWidth = $(window).width();
    $('#helpCard1').fadeIn(1000);
    $('#helpCard1').css('margin-left',(windowWidth/2 - 125).toString()+"px");

    var myLatlng = new google.maps.LatLng("55.942665", "-3.218126");
    var marker = new google.maps.Marker({
      position: myLatlng,
      map: map
    });

    contentStrings =
      "
" +
        "Venue name goes here" +
      "
venueemail@example.com" +
      "
0131 XXXX XXXX" +
      "
" +
        cookieArray[0].split('=')[1] + "" +
      "
";

    google.maps.event.addListener(marker, 'click',function() {
      infowindow.setContent(contentStrings);
      infowindow.open(map,marker);
    });

    google.maps.event.addListener(infowindow,'closeclick',function(){
      $('#helpCard1').fadeOut(1000);
      $('#goBackCard').fadeIn(1000);
      $('#goBackCard').css('margin-left',(windowWidth/2 - 125).toString()+"px");
    });

    $('.helpCardClose').click(function(){
      $(this).parent().fadeOut(1000);
    });
  }
  else {

    // constructing the query to be sent to the server
    var sportsArray = cookieArray[3].split('=')[1].split(",");
    var daysArray = cookieArray[0].split('=')[1].split(",");
    var priceArray = cookieArray[2].split('=')[1].split(",");
    priceArray[1] = priceArray[1].replace('Below ','').replace('£','');
    if (sportsArray == ""){
      sports=null;
    }
    else {
      var sports = JSON.stringify(sportsArray);
      sports = sports.replace(/"/g, '\\"');
    }

    if(daysArray == ""){
      days = null;
    }
    else{
      var days = JSON.stringify(daysArray);
      days = days.replace(/"/g, '\\"');
    }

    var price = JSON.stringify(priceArray);
    price = price.replace(/"/g, '\\"');

    console.log(sports + "|" + days + "|" + price)

    // making the request to the server
    request = new XMLHttpRequest();
    request.open("GET","query.php?sports=" +
            sports + "&days=" + days + "&price=" + price, true);
    request.send (null);

    request.onreadystatechange = function()
    {
      if (request.readyState==4 && request.status==200)
      {
        data = JSON.parse(request.responseText);
        console.log(data.length)
        console.log(data);

        var i = 0;

        // creating the markers and populating the contentStrings array which has
        // the info window data for each marker
        // populating the markers array
        for(var obj in data)
        {
          var myLatlng = new google.maps.LatLng(data[i].latitude,
                              data[i].longtitude);
          var marker = new google.maps.Marker({
            id : i,
            position: myLatlng,
            map: map,
            title: 'Marker ' + i
          });

          var email;

          if(data[i].email){
             email = data[i].email
          }
          else{
             email = "No email provided."
          }

          contentStrings[i] = "
" + data[i].name + "" +
            "
" + email + "" +
            "
" + data[i].phone + "" +
            "
" + data[i].sports + "
";

          console.log(email);
          markers[i] = marker;

          // event listener for each marker
          google.maps.event.addListener(marker, 'click',
            function() {
              var id = this.id;
              var marker = markers[id];
              infowindow.setContent(contentStrings[id]);
              infowindow.open(map,marker);
            });
          i++;
        }

      }
    }
  }

});
<commit_msg>js: Null emails are no longer links<commit_after>var data;
var marker;
var markers = new Array();
var contentStrings = new Array();
var lat1;
var lon1;

// TODO for tomorrow - refactor the file thoroughly!!!
$(document).bind( "mobileinit", function(event) {
    $.extend($.mobile.zoom, {locked:false,enabled:true});
});

$('#backToCube').click(function(){
  window.location.href = ".";
});

$(window).resize(function(){
  windowWidth = $(window).width();
  $('#helpCard1').css('margin-left',(windowWidth/2 - 125).toString()+"px");
  $('#goBackCard').css('margin-left',(windowWidth/2 - 125).toString()+"px");

  windowHeight = $(window).height();
  $('#backToCube').css('margin-top',(windowHeight/2 - 35).toString()+"px");
});

$(document).ready(function(){

  cookieArray = [];
  initialCookieArray = document.cookie.split('; ').sort();
  for (var x in initialCookieArray){
    if (initialCookieArray[x].indexOf("sports") != -1 ||
        initialCookieArray[x].indexOf("days") != -1 ||
        initialCookieArray[x].indexOf("price") != -1 ||
        initialCookieArray[x].indexOf("isComingFromMap") !=-1 ||
        initialCookieArray[x].indexOf("tutorialModeOn") != -1)
    {
      cookieArray.push(initialCookieArray[x])
    }
  }
  cookieArray.sort();

  tutorialMode = cookieArray[4].split('=')[1];
  isComingFromMap = cookieArray[1].split('=')[1];

  console.log(cookieArray)

  var windowHeight = $(window).height();
  $('#backToCube').css('margin-top',(windowHeight/2 - 35).toString()+"px");
  // creating the map and the info window
  var myLatlng = new google.maps.LatLng(55.950, -3.190);  //Edinburgh center

  var mapOptions = {
    zoom: 12,
    center: myLatlng,
    minZoom: 10,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById('map-canvas'),
                mapOptions);

  var infoWindowOptions = {
    maxWidth: 300
  };
  var infowindow = new google.maps.InfoWindow(infoWindowOptions);

  if( tutorialMode == 'true' ){

    windowWidth = $(window).width();
    $('#helpCard1').fadeIn(1000);
    $('#helpCard1').css('margin-left',(windowWidth/2 - 125).toString()+"px");

    var myLatlng = new google.maps.LatLng("55.942665", "-3.218126");
    var marker = new google.maps.Marker({
      position: myLatlng,
      map: map
    });

    contentStrings =
      "
" +
        "Venue name goes here" +
      "
venueemail@example.com" +
      "
0131 XXXX XXXX" +
      "
" +
        cookieArray[0].split('=')[1] + "" +
      "
";

    google.maps.event.addListener(marker, 'click',function() {
      infowindow.setContent(contentStrings);
      infowindow.open(map,marker);
    });

    google.maps.event.addListener(infowindow,'closeclick',function(){
      $('#helpCard1').fadeOut(1000);
      $('#goBackCard').fadeIn(1000);
      $('#goBackCard').css('margin-left',(windowWidth/2 - 125).toString()+"px");
    });

    $('.helpCardClose').click(function(){
      $(this).parent().fadeOut(1000);
    });
  }
  else {

    // constructing the query to be sent to the server
    var sportsArray = cookieArray[3].split('=')[1].split(",");
    var daysArray = cookieArray[0].split('=')[1].split(",");
    var priceArray = cookieArray[2].split('=')[1].split(",");
    priceArray[1] = priceArray[1].replace('Below ','').replace('£','');
    if (sportsArray == ""){
      sports=null;
    }
    else {
      var sports = JSON.stringify(sportsArray);
      sports = sports.replace(/"/g, '\\"');
    }

    if(daysArray == ""){
      days = null;
    }
    else{
      var days = JSON.stringify(daysArray);
      days = days.replace(/"/g, '\\"');
    }

    var price = JSON.stringify(priceArray);
    price = price.replace(/"/g, '\\"');

    console.log(sports + "|" + days + "|" + price)

    // making the request to the server
    request = new XMLHttpRequest();
    request.open("GET","query.php?sports=" +
            sports + "&days=" + days + "&price=" + price, true);
    request.send (null);

    request.onreadystatechange = function()
    {
      if (request.readyState==4 && request.status==200)
      {
        data = JSON.parse(request.responseText);
        console.log(data.length)
        console.log(data);

        var i = 0;

        // creating the markers and populating the contentStrings array which has
        // the info window data for each marker
        // populating the markers array
        for(var obj in data)
        {
          var myLatlng = new google.maps.LatLng(data[i].latitude,
                              data[i].longtitude);
          var marker = new google.maps.Marker({
            id : i,
            position: myLatlng,
            map: map,
            title: 'Marker ' + i
          });

          var email;

          if(data[i].email){
             email = "" + data[i].email + ""
          }
          else{
             email = "No email provided."
          }

          contentStrings[i] = "
" + data[i].name + "" +
            "
" + email +
            "
" + data[i].phone + "" +
            "
" + data[i].sports + "
";

          console.log(email);
          markers[i] = marker;

          // event listener for each marker
          google.maps.event.addListener(marker, 'click',
            function() {
              var id = this.id;
              var marker = markers[id];
              infowindow.setContent(contentStrings[id]);
              infowindow.open(map,marker);
            });
          i++;
        }

      }
    }
  }

});
<|endoftext|>


<commit_before>pwi_form = function() {
var $viewerSelected = 'fancybox',
settings = {
          username: 'brianc@palaver.net',
          popupPlugin: $viewerSelected,
          showPhotoDownload: true,
          showPhotoCaption: true,
          showPhotoFilename: true,
          thumbSize: 1024,
	  photoSize: 1600
          };
$(".cem-shell-main-content").pwi(settings);
};
<commit_msg>Clean up small formatting glitch<commit_after>pwi_form = function() {
var $viewerSelected = 'fancybox',
settings = {
          username: 'brianc@palaver.net',
          popupPlugin: $viewerSelected,
          showPhotoDownload: true,
          showPhotoCaption: true,
          showPhotoFilename: true,
          thumbSize: 1024,
          photoSize: 1600
          };
$(".cem-shell-main-content").pwi(settings);
};
<|endoftext|>


<commit_before>(function (window, undefined) {
    "use strict";
    // test for REM unit support
    var cssremunit =  function() {
        var div = document.createElement( 'div' );
            div.style.cssText = 'font-size: 1rem;';

        return (/rem/).test(div.style.fontSize);
    },

    // filter returned link nodes for stylesheets
    isStyleSheet = function () {
        var styles = document.getElementsByTagName('link'),
            filteredStyles = [];

        for ( var i = 0; i < styles.length; i++) {
            if ( styles[i].rel.toLowerCase() === 'stylesheet' && styles[i].getAttribute('data-norem') === null ) {
                filteredStyles.push( styles[i] );
            }
        }

        return filteredStyles;
    },

   processSheets = function () {
        var links = [];
        sheets = isStyleSheet(); // search for link tags and confirm it's a stylesheet
        sheets.og = sheets.length; // store the original length of sheets as a property
        for( var i = 0; i < sheets.length; i++ ){
            links[i] = sheets[i].href;
            xhr( links[i], matchCSS, i );
        }
    },

    matchCSS = function ( response, i ) { // collect all of the rules from the xhr response texts and match them to a pattern
        var clean = removeComments( removeMediaQueries(response.responseText) ),
            pattern = /[\w\d\s\-\/\\\[\]:,.'"*()<>+~%#^$_=|@]+\{[\w\d\s\-\/\\%#:;,.'"*()]+\d*\.?\d+rem[\w\d\s\-\/\\%#:;,.'"*()]*\}/g, //find selectors that use rem in one or more of their rules
            current = clean.match(pattern),
            remPattern =/\d*\.?\d+rem/g,
            remCurrent = clean.match(remPattern);

        if( current !== null && current.length !== 0 ){
            found = found.concat( current ); // save all of the blocks of rules with rem in a property
            foundProps = foundProps.concat( remCurrent ); // save all of the properties with rem
        }
        if( i === sheets.og-1 ){
            buildCSS();
        }
    },

    buildCSS = function () { // first build each individual rule from elements in the found array and then add it to the string of rules.
        var pattern = /[\w\d\s\-\/\\%#:,.'"*()]+\d*\.?\d+rem[\w\d\s\-\/\\%#:,.'"*()]*[;}]/g; // find properties with rem values in them
        for( var i = 0; i < found.length; i++ ){
            rules = rules + found[i].substr(0,found[i].indexOf("{")+1); // save the selector portion of each rule with a rem value
            var current = found[i].match( pattern );
            for( var j = 0; j<current.length; j++ ){ // build a new set of with only the selector and properties that have rem in the value
                rules = rules + current[j];
                if( j === current.length-1 && rules[rules.length-1] !== "}" ){
                    rules = rules + "\n}";
                }
            }
        }

        parseCSS();
    },

    parseCSS = function () { // replace each set of parentheses with evaluated content
	var remSize;
        for( var i = 0; i < foundProps.length; i++ ){
            remSize = parseFloat(foundProps[i].substr(0,foundProps[i].length-3));
            css[i] = Math.round( remSize * fontSize ) + 'px';
        }

        loadCSS();
    },

    loadCSS = function () { // replace and load the new rules
        for( var i = 0; i < css.length; i++ ){ // only run this loop as many times as css has entries
            if( css[i] ){
                rules = rules.replace( foundProps[i],css[i] ); // replace old rules with our processed rules
            }
        }
        var remcss = document.createElement( 'style' );
        remcss.setAttribute( 'type', 'text/css' );
        remcss.id = 'remReplace';
        document.getElementsByTagName( 'head' )[0].appendChild( remcss );   // create the new element
        if( remcss.styleSheet ) {
            remcss.styleSheet.cssText = rules; // IE8 will not support innerHTML on read-only elements, such as STYLE
        } else {
            remcss.appendChild( document.createTextNode( rules ) );
        }
    },

    xhr = function ( url, callback, i ) { // create new XMLHttpRequest object and run it
        try {
            var xhr = getXMLHttpRequest();
            xhr.open( 'GET', url, true );
            xhr.send();
            var ie = (function () { //function checking IE version
            var undef,
                v = 3,
                div = document.createElement('div'),
                all = div.getElementsByTagName('i');
                while (
                    div.innerHTML = '',
                    all[0]
                );
            return v > 4 ? v : undef;
            }());

            if ( ie >= 7 ){ //If IE is greater than 6
                // This targets modern browsers and modern versions of IE,
                // which don't need the "new" keyword.
                xhr.onreadystatechange = function () {
                    if ( xhr.readyState === 4 ){
                        callback(xhr, i);
                    } // else { callback function on AJAX error }
                };
            } else {
                // This block targets old versions of IE, which require "new".
                xhr.onreadystatechange = new function() { //IE6 and IE7 need the "new function()" syntax to work properly
                    if ( xhr.readyState === 4 ){
                        callback(xhr, i);
                    } // else { callback function on AJAX error }
                };
            }
         } catch (e){
            if ( window.XDomainRequest ) {
                var xdr = new XDomainRequest();
                xdr.open('get', url);
                xdr.onload = function() {
                    callback(xdr, i);
                };
                xdr.onerror = function() {
                    return false; // xdr load fail
                };
                xdr.send();
            }
         }
    },

    removeComments = function ( css ) {
        var start = css.search(/\/\*/),
            end = css.search(/\*\//);
        if ( (start > -1) && (end > start) ) {
            css = css.substring(0, start) + css.substring(end + 2);
            return removeComments(css);
        }
        else {
            return css;
        }
    },

	// Test for Media Query support
    mediaQuery = function() {
        if (window.matchMedia || window.msMatchMedia) { return true; }
        return false;
    },

    // Remove queries.
    removeMediaQueries = function(css) {
        if (!mediaQuery()) {
            // If the browser doesn't support media queries, we find all @media declarations in the CSS and remove them.
            // Note: Since @rules can't be nested in the CSS spec, we're safe to just check for the closest following "}}" to the "@media".
            css = css.replace(/@media[\s\S]*?\}\s*\}/, "");
        }

        return css;
    },

    getXMLHttpRequest = function () { // we're gonna check if our browser will let us use AJAX
        if (window.XMLHttpRequest) {
            return new XMLHttpRequest();
        } else { // if XMLHttpRequest doesn't work
            try {
                return new ActiveXObject("MSXML2.XMLHTTP"); // then we'll instead use AJAX through ActiveX for IE6/IE7
            } catch (e1) {
                try {
                    return new ActiveXObject("Microsoft.XMLHTTP"); // other microsoft
                } catch (e2) {
                    // No XHR at all...
                }
            }
        }
    };

    if( !cssremunit() ){ // this checks if the rem value is supported
        var rules = '', // initialize the rules variable in this scope so it can be used later
            sheets = [], // initialize the array holding the sheets for use later
            found = [], // initialize the array holding the found rules for use later
            foundProps = [], // initialize the array holding the found properties for use later
            css = [], // initialize the array holding the parsed rules for use later
            body = document.getElementsByTagName('body')[0],
            fontSize = '';
        if (body.currentStyle) {
            if ( body.currentStyle.fontSize.indexOf("px") >= 0 ) {
                fontSize = body.currentStyle.fontSize.replace('px', '');
            } else if ( body.currentStyle.fontSize.indexOf("em") >= 0 ) {
                fontSize = body.currentStyle.fontSize.replace('em', '');
            } else if ( body.currentStyle.fontSize.indexOf("pt") >= 0 ) {
                fontSize = body.currentStyle.fontSize.replace('pt', '');
            } else {
                fontSize = (body.currentStyle.fontSize.replace('%', '') / 100) * 16; // IE8 returns the percentage while other browsers return the computed value
            }
        } else if (window.getComputedStyle) {
            fontSize = document.defaultView.getComputedStyle(body, null).getPropertyValue('font-size').replace('px', ''); // find font-size in body element
        }
        processSheets();
    } // else { do nothing, you are awesome and have REM support }

})(window);
<commit_msg>Rectify when buildCSS is called<commit_after>(function (window, undefined) {
    "use strict";
    // test for REM unit support
    var cssremunit =  function() {
        var div = document.createElement( 'div' );
            div.style.cssText = 'font-size: 1rem;';

        return (/rem/).test(div.style.fontSize);
    },

    // filter returned link nodes for stylesheets
    isStyleSheet = function () {
        var styles = document.getElementsByTagName('link'),
            filteredStyles = [];

        for ( var i = 0; i < styles.length; i++) {
            if ( styles[i].rel.toLowerCase() === 'stylesheet' && styles[i].getAttribute('data-norem') === null ) {
                filteredStyles.push( styles[i] );
            }
        }

        return filteredStyles;
    },

   processSheets = function () {
        var links = [];
        sheets = isStyleSheet(); // search for link tags and confirm it's a stylesheet
        sheets.og = sheets.length; // store the original length of sheets as a property
        sheets.loaded = 0; // keep track of how have been loaded from the xhr request
        for( var i = 0; i < sheets.length; i++ ){
            links[i] = sheets[i].href;
            xhr( links[i], matchCSS, i );
        }
    },

    matchCSS = function ( response, i ) { // collect all of the rules from the xhr response texts and match them to a pattern
        var clean = removeComments( removeMediaQueries(response.responseText) ),
            pattern = /[\w\d\s\-\/\\\[\]:,.'"*()<>+~%#^$_=|@]+\{[\w\d\s\-\/\\%#:;,.'"*()]+\d*\.?\d+rem[\w\d\s\-\/\\%#:;,.'"*()]*\}/g, //find selectors that use rem in one or more of their rules
            current = clean.match(pattern),
            remPattern =/\d*\.?\d+rem/g,
            remCurrent = clean.match(remPattern);

        if( current !== null && current.length !== 0 ){
            found = found.concat( current ); // save all of the blocks of rules with rem in a property
            foundProps = foundProps.concat( remCurrent ); // save all of the properties with rem
        }
        if( ++sheets.loaded === sheets.og ){
            buildCSS();
        }
    },

    buildCSS = function () { // first build each individual rule from elements in the found array and then add it to the string of rules.
        var pattern = /[\w\d\s\-\/\\%#:,.'"*()]+\d*\.?\d+rem[\w\d\s\-\/\\%#:,.'"*()]*[;}]/g; // find properties with rem values in them
        for( var i = 0; i < found.length; i++ ){
            rules = rules + found[i].substr(0,found[i].indexOf("{")+1); // save the selector portion of each rule with a rem value
            var current = found[i].match( pattern );
            for( var j = 0; j<current.length; j++ ){ // build a new set of with only the selector and properties that have rem in the value
                rules = rules + current[j];
                if( j === current.length-1 && rules[rules.length-1] !== "}" ){
                    rules = rules + "\n}";
                }
            }
        }

        parseCSS();
    },

    parseCSS = function () { // replace each set of parentheses with evaluated content
	var remSize;
        for( var i = 0; i < foundProps.length; i++ ){
            remSize = parseFloat(foundProps[i].substr(0,foundProps[i].length-3));
            css[i] = Math.round( remSize * fontSize ) + 'px';
        }

        loadCSS();
    },

    loadCSS = function () { // replace and load the new rules
        for( var i = 0; i < css.length; i++ ){ // only run this loop as many times as css has entries
            if( css[i] ){
                rules = rules.replace( foundProps[i],css[i] ); // replace old rules with our processed rules
            }
        }
        var remcss = document.createElement( 'style' );
        remcss.setAttribute( 'type', 'text/css' );
        remcss.id = 'remReplace';
        document.getElementsByTagName( 'head' )[0].appendChild( remcss );   // create the new element
        if( remcss.styleSheet ) {
            remcss.styleSheet.cssText = rules; // IE8 will not support innerHTML on read-only elements, such as STYLE
        } else {
            remcss.appendChild( document.createTextNode( rules ) );
        }
    },

    xhr = function ( url, callback, i ) { // create new XMLHttpRequest object and run it
        try {
            var xhr = getXMLHttpRequest();
            xhr.open( 'GET', url, true );
            xhr.send();
            var ie = (function () { //function checking IE version
            var undef,
                v = 3,
                div = document.createElement('div'),
                all = div.getElementsByTagName('i');
                while (
                    div.innerHTML = '',
                    all[0]
                );
            return v > 4 ? v : undef;
            }());

            if ( ie >= 7 ){ //If IE is greater than 6
                // This targets modern browsers and modern versions of IE,
                // which don't need the "new" keyword.
                xhr.onreadystatechange = function () {
                    if ( xhr.readyState === 4 ){
                        callback(xhr, i);
                    } // else { callback function on AJAX error }
                };
            } else {
                // This block targets old versions of IE, which require "new".
                xhr.onreadystatechange = new function() { //IE6 and IE7 need the "new function()" syntax to work properly
                    if ( xhr.readyState === 4 ){
                        callback(xhr, i);
                    } // else { callback function on AJAX error }
                };
            }
         } catch (e){
            if ( window.XDomainRequest ) {
                var xdr = new XDomainRequest();
                xdr.open('get', url);
                xdr.onload = function() {
                    callback(xdr, i);
                };
                xdr.onerror = function() {
                    return false; // xdr load fail
                };
                xdr.send();
            }
         }
    },

    removeComments = function ( css ) {
        var start = css.search(/\/\*/),
            end = css.search(/\*\//);
        if ( (start > -1) && (end > start) ) {
            css = css.substring(0, start) + css.substring(end + 2);
            return removeComments(css);
        }
        else {
            return css;
        }
    },

	// Test for Media Query support
    mediaQuery = function() {
        if (window.matchMedia || window.msMatchMedia) { return true; }
        return false;
    },

    // Remove queries.
    removeMediaQueries = function(css) {
        if (!mediaQuery()) {
            // If the browser doesn't support media queries, we find all @media declarations in the CSS and remove them.
            // Note: Since @rules can't be nested in the CSS spec, we're safe to just check for the closest following "}}" to the "@media".
            css = css.replace(/@media[\s\S]*?\}\s*\}/, "");
        }

        return css;
    },

    getXMLHttpRequest = function () { // we're gonna check if our browser will let us use AJAX
        if (window.XMLHttpRequest) {
            return new XMLHttpRequest();
        } else { // if XMLHttpRequest doesn't work
            try {
                return new ActiveXObject("MSXML2.XMLHTTP"); // then we'll instead use AJAX through ActiveX for IE6/IE7
            } catch (e1) {
                try {
                    return new ActiveXObject("Microsoft.XMLHTTP"); // other microsoft
                } catch (e2) {
                    // No XHR at all...
                }
            }
        }
    };

    if( !cssremunit() ){ // this checks if the rem value is supported
        var rules = '', // initialize the rules variable in this scope so it can be used later
            sheets = [], // initialize the array holding the sheets for use later
            found = [], // initialize the array holding the found rules for use later
            foundProps = [], // initialize the array holding the found properties for use later
            css = [], // initialize the array holding the parsed rules for use later
            body = document.getElementsByTagName('body')[0],
            fontSize = '';
        if (body.currentStyle) {
            if ( body.currentStyle.fontSize.indexOf("px") >= 0 ) {
                fontSize = body.currentStyle.fontSize.replace('px', '');
            } else if ( body.currentStyle.fontSize.indexOf("em") >= 0 ) {
                fontSize = body.currentStyle.fontSize.replace('em', '');
            } else if ( body.currentStyle.fontSize.indexOf("pt") >= 0 ) {
                fontSize = body.currentStyle.fontSize.replace('pt', '');
            } else {
                fontSize = (body.currentStyle.fontSize.replace('%', '') / 100) * 16; // IE8 returns the percentage while other browsers return the computed value
            }
        } else if (window.getComputedStyle) {
            fontSize = document.defaultView.getComputedStyle(body, null).getPropertyValue('font-size').replace('px', ''); // find font-size in body element
        }
        processSheets();
    } // else { do nothing, you are awesome and have REM support }

})(window);
<|endoftext|>