<commit_before>// Specifies a function to be executed when the DOM is fully loaded.
$(document).ready(function() {

	// Main function to run.
	var main = function(lat, lon, acc) {
		console.log('Latitude: ' + lat + ', Longitude: ' + lon + ', Accuracy: ' + acc);
		// Loads the JSON-encoded data from the server using a GET HTTP request.
		$.getJSON('data.php', function(data) {
			// Creates an object variable with all the data from the array, including
			// the geographic coordinates that specify the building.
			var ul = {
				name: 'Library',
				id: 'ul',
				status: data.Library.status,
				pcs: {
					available: data.Library.available,
					total: data.Library.total
				},
				coords: {
					lat: 50.792470,
					lon: -1.098845
				}
			};

			// Creates an object variable with all the data from the array, including
			// the geographic coordinates that specify the building.
			var pk = {
				name: 'Park',
				id: 'pk',
				status: data.Park.status,
				pcs: {
					available: data.Park.available,
					total: data.Park.total
				},
				coords: {
					lat: 50.797570,
					lon: -1.094108
				}
			};

			// Creates an object variable with all the data from the array, including
			// the geographic coordinates that specify the building.
			var po = {
				name: 'Portland',
				id: 'po',
				status: data.Portland.status,
				pcs: {
					available: data.Portland.available,
					total: data.Portland.total
				},
				coords: {
					lat: 50.798454,
					lon: -1.099490
				}
			};

			// Creates an object variable with all the data from the array, including
			// the geographic coordinates that specify the building.
			var ag = {
				name: 'Anglesea',
				id: 'ag',
				status: data.Anglesea.status,
				pcs: {
					available: data.Anglesea.available,
					total: data.Anglesea.total
				},
				coords: {
					lat: 50.797709,
					lon: -1.096582
				}
			};

			// Creates an array variable with all the data from all the objects.
			var buildings = [ul, pk, po, ag];

			// Loops through all the buildings in the array.
			for (var i = 0; i < buildings.length; i++) {
				// Creates a local variable for the current building.
				var building = buildings[i];

				// Gets the availability of the PCs available in the building.
				var availability = building.pcs.available + ' / ' + building.pcs.total + ' Available';

				if (building.status === 2) {
					// Gets the percentage of available PCS in the building.
					var percentage = (building.pcs.available / building.pcs.total) * 100
					// Tidies up the percentage and adds a percentage symbol.
					var percentagePretty = Math.floor(percentage) + '%';

					// Creates an HSL colour so as to keep the tone and just change the hue.
					var colour = 'hsl(' + percentage + ', 60%, 60%)';

					// Sets the width of the percentage bar to the percentage of available PCs.
					$('#' + building.id + ' .percent').css('width', percentagePretty);
					// Sets the colour of the percentage bar to the HSL colour.
					$('#' + building.id + ' .percent').css('background', colour);
				} else {
					// Resets the width of the percentage bar to the percentage of available PCs.
					$('#' + building.id + ' .percent').css('width', '0');

					// Changes the text in the availability paragraph for the building.
					$('#' + building.id + ' p').html('Closed');
				}

				// Changes the text in the availability paragraph for the building.
				$('#' + building.id + ' p').html(availability + '');

				// Checks that the latitude and longitude are not empty and the
				// accuracy is at a maximum of 32.
				if (lat != '' && lon != '' && acc <= 32) {
					// Runs the function to get the distance in kilometres.
					geo(building.id, building);
				}
			}

			// Checks that the latitude and longitude are not empty and that the
			// accuracy is at a maximum of 32.
			if (lat != '' && lon != '' && acc <= 32) {
				// Sets the first building in the array as the closest by default.
				var closest_building = buildings[0];

				// Loops through all the buildings.
				for (var j = 0; j < buildings.length; j++) {
					// Sets the current building in a variable.
					var building = buildings[j];

					// Checks if the building is open and if it's closer to
					// the user's location that the current closest building.
					if (building.status == 2 && building.distance < closest_building.distance) {
						// Sets the current building as the new closest building.
						closest_building = building;
					}
				}

				// Removes any existing inline elements in the heading of all buildings.
				$('h1 span').remove();

				// Checks if an inline element inside the heading of the building exists.
				if ($('#' + closest_building.id + ' h1 span').length !== 0) {
					// Changes the text in the inline element accordingly.
					$('#' + closest_building.id + ' h1 span').html('(Closest)');
				} else {
					// Creates an inline element with the according text.
					$('#' + closest_building.id + ' h1').append('(Closest)');
				}
			}
		});
	};

	// Runs the main function once geolocation variables are received.
	var start = function(lat, lon, acc) {
		// Runs the function for a first time with the geolocation variables.
		main(lat, lon, acc);

		// Runs the function again every 5 seconds.
		setInterval(function() {
			main(lat, lon, acc);
		}, 5000);
	};

	// Sets the PositionOptions to be used to get the user's current location.
	var options = {
		enableHighAccuracy: true,
		maximumAge: 0
	};

	// Callback function that takes a Position object as its sole input parameter.
	var success = function(pos) {
		// Clears the timeout of the fail timer.
		clearTimeout(fail_timeout);
		// Creates a variable that gets the coordinates from the input parameter.
		var current = pos.coords;

		// Passes the coordinates to the variables created earlier.
		lat = current.latitude;
		lon = current.longitude;
		acc = current.accuracy;

		// Runs the start function with the geolocation variables received.
		start(lat, lon, acc);
	};

	// Callback that takes a PositionError object as its sole input parameter.
	var error = function(err) {
		// Clears the timeout of the fail timer.
		clearTimeout(fail_timeout);
		// Prints out a warning if something goes wrong.
		console.warn('ERROR(' + err.code + '): ' + err.message);

		// Runs the start function with no geolocation.
		start('', '', '');
	};

	// Gets the distance in kilometres and returns it on the building availability.
	var geo = function(id, building) {
		building.distance = latlontokm(lat, lon, building.coords.lat, building.coords.lon);
		var dist = building.distance.toString().substr(0, building.distance.toString().indexOf('.'));
		var time = dist / 0.7;
		var hours = Math.floor(time / 3600);
		var minutes = Math.floor(time / 60);
		$('#' + id + ' p span').append(dist + 'm  • ETA: ' + minutes + 'm');
	};

	// Gets the difference in kilometres for the two destinations.
	var latlontokm = function(lat1, lon1, lat2, lon2) {
		var R = 6371;
		var dLat = deg2rad(lat2-lat1);
		var dLon = deg2rad(lon2-lon1);
		var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLon/2) * Math.sin(dLon/2);
		var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
		var d = R * c;
		return d * 1000;
	};

	// Converts degrees to radius.
	var deg2rad = function(deg) {
		return deg * (Math.PI/180);
	};

	// Runs the function without geolocation while we are awaiting confirmation
	// for using geolocation.
	var fail = function() {
		start('', '', '');
	};

	// Sets the default values for the latitude, longitude and accuracy variables.
	var lat = '';
	var lon = '';
	var acc = '';

	// Runs a timer while we are waiting for the user to allow geolocation.
	var fail_timeout = setTimeout(function() { fail(); }, 2000);

	// Checks if geolocation is available on this device.
	if (navigator.geolocation) {
		// Uses a geolocation method to get the current position of the device.
		navigator.geolocation.getCurrentPosition(success, error, options);
	} else {
		// Runs the function without geolocation.
		fail();
	}
});<commit_msg>Fixes #8. Uses strong/bold on distance instead of showing the closest building.<commit_after>// Specifies a function to be executed when the DOM is fully loaded.
$(document).ready(function() {

	// Main function to run.
	var main = function(lat, lon, acc) {
		console.log('Latitude: ' + lat + ', Longitude: ' + lon + ', Accuracy: ' + acc);
		// Loads the JSON-encoded data from the server using a GET HTTP request.
		$.getJSON('data.php', function(data) {
			// Creates an object variable with all the data from the array, including
			// the geographic coordinates that specify the building.
			var ul = {
				name: 'Library',
				id: 'ul',
				status: data.Library.status,
				pcs: {
					available: data.Library.available,
					total: data.Library.total
				},
				coords: {
					lat: 50.792470,
					lon: -1.098845
				}
			};

			// Creates an object variable with all the data from the array, including
			// the geographic coordinates that specify the building.
			var pk = {
				name: 'Park',
				id: 'pk',
				status: data.Park.status,
				pcs: {
					available: data.Park.available,
					total: data.Park.total
				},
				coords: {
					lat: 50.797570,
					lon: -1.094108
				}
			};

			// Creates an object variable with all the data from the array, including
			// the geographic coordinates that specify the building.
			var po = {
				name: 'Portland',
				id: 'po',
				status: data.Portland.status,
				pcs: {
					available: data.Portland.available,
					total: data.Portland.total
				},
				coords: {
					lat: 50.798454,
					lon: -1.099490
				}
			};

			// Creates an object variable with all the data from the array, including
			// the geographic coordinates that specify the building.
			var ag = {
				name: 'Anglesea',
				id: 'ag',
				status: data.Anglesea.status,
				pcs: {
					available: data.Anglesea.available,
					total: data.Anglesea.total
				},
				coords: {
					lat: 50.797709,
					lon: -1.096582
				}
			};

			// Creates an array variable with all the data from all the objects.
			var buildings = [ul, pk, po, ag];

			// Loops through all the buildings in the array.
			for (var i = 0; i < buildings.length; i++) {
				// Creates a local variable for the current building.
				var building = buildings[i];

				// Gets the availability of the PCs available in the building.
				var availability = building.pcs.available + ' / ' + building.pcs.total + ' Available';

				if (building.status === 2) {
					// Gets the percentage of available PCS in the building.
					var percentage = (building.pcs.available / building.pcs.total) * 100
					// Tidies up the percentage and adds a percentage symbol.
					var percentagePretty = Math.floor(percentage) + '%';

					// Creates an HSL colour so as to keep the tone and just change the hue.
					var colour = 'hsl(' + percentage + ', 60%, 60%)';

					// Sets the width of the percentage bar to the percentage of available PCs.
					$('#' + building.id + ' .percent').css('width', percentagePretty);
					// Sets the colour of the percentage bar to the HSL colour.
					$('#' + building.id + ' .percent').css('background', colour);
				} else {
					// Resets the width of the percentage bar to the percentage of available PCs.
					$('#' + building.id + ' .percent').css('width', '0');

					// Changes the text in the availability paragraph for the building.
					$('#' + building.id + ' p').html('Closed');
				}

				// Changes the text in the availability paragraph for the building.
				$('#' + building.id + ' p').html(availability + '');

				// Checks that the latitude and longitude are not empty and the
				// accuracy is at a maximum of 32.
				if (lat != '' && lon != '' && acc <= 32) {
					// Runs the function to get the distance in kilometres.
					geo(building.id, building);
				}
			}

			// Checks that the latitude and longitude are not empty and that the
			// accuracy is at a maximum of 32.
			if (lat != '' && lon != '' && acc <= 32) {
				// Sets the first building in the array as the closest by default.
				var closest_building = buildings[0];

				// Loops through all the buildings.
				for (var j = 0; j < buildings.length; j++) {
					// Sets the current building in a variable.
					var building = buildings[j];

					// Checks if the building is open and if it's closer to
					// the user's location that the current closest building.
					if (building.status == 2 && building.distance < closest_building.distance) {
						// Sets the current building as the new closest building.
						closest_building = building;
					}
				}

				// Removes any existing inline elements in the heading of all buildings.
				$('h1 span').remove();

				// Changes the text in the inline element accordingly.
				$('#' + closest_building.id + ' p span').html('' + $('#' + closest_building.id + ' p span').text() + '');
			}
		});
	};

	// Runs the main function once geolocation variables are received.
	var start = function(lat, lon, acc) {
		// Runs the function for a first time with the geolocation variables.
		main(lat, lon, acc);

		// Runs the function again every 5 seconds.
		setInterval(function() {
			main(lat, lon, acc);
		}, 5000);
	};

	// Sets the PositionOptions to be used to get the user's current location.
	var options = {
		enableHighAccuracy: true,
		maximumAge: 0
	};

	// Callback function that takes a Position object as its sole input parameter.
	var success = function(pos) {
		// Clears the timeout of the fail timer.
		clearTimeout(fail_timeout);
		// Creates a variable that gets the coordinates from the input parameter.
		var current = pos.coords;

		// Passes the coordinates to the variables created earlier.
		lat = current.latitude;
		lon = current.longitude;
		acc = current.accuracy;

		// Runs the start function with the geolocation variables received.
		start(lat, lon, acc);
	};

	// Callback that takes a PositionError object as its sole input parameter.
	var error = function(err) {
		// Clears the timeout of the fail timer.
		clearTimeout(fail_timeout);
		// Prints out a warning if something goes wrong.
		console.warn('ERROR(' + err.code + '): ' + err.message);

		// Runs the start function with no geolocation.
		start('', '', '');
	};

	// Gets the distance in kilometres and returns it on the building availability.
	var geo = function(id, building) {
		building.distance = latlontokm(lat, lon, building.coords.lat, building.coords.lon);
		var dist = building.distance.toString().substr(0, building.distance.toString().indexOf('.'));
		var time = dist / 0.7;
		var hours = Math.floor(time / 3600);
		var minutes = Math.floor(time / 60);
		$('#' + id + ' p span').append(dist + 'm  • ETA: ' + minutes + 'm');
	};

	// Gets the difference in kilometres for the two destinations.
	var latlontokm = function(lat1, lon1, lat2, lon2) {
		var R = 6371;
		var dLat = deg2rad(lat2-lat1);
		var dLon = deg2rad(lon2-lon1);
		var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLon/2) * Math.sin(dLon/2);
		var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
		var d = R * c;
		return d * 1000;
	};

	// Converts degrees to radius.
	var deg2rad = function(deg) {
		return deg * (Math.PI/180);
	};

	// Runs the function without geolocation while we are awaiting confirmation
	// for using geolocation.
	var fail = function() {
		start('', '', '');
	};

	// Sets the default values for the latitude, longitude and accuracy variables.
	var lat = '';
	var lon = '';
	var acc = '';

	// Runs a timer while we are waiting for the user to allow geolocation.
	var fail_timeout = setTimeout(function() { fail(); }, 2000);

	// Checks if geolocation is available on this device.
	if (navigator.geolocation) {
		// Uses a geolocation method to get the current position of the device.
		navigator.geolocation.getCurrentPosition(success, error, options);
	} else {
		// Runs the function without geolocation.
		fail();
	}
});<|endoftext|>


<commit_before>var map;
$(document).ready(function() {
 /* var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(40.4450813, -80.00877459999998),
	disableDefaultUI: true
  };
  map = new google.maps.Map(document.getElementById('map_canvas'),
      mapOptions);*/

 //parse url
 var pathname = window.location.pathname; //get current url
 var split = pathname.split("/"); //treat it like a string, break it up where the /'s are
 //console.log(split[2]);

 //case statement
 switch(split[2]) { //the second item in the array will be the type of page this will be
    case "candidates":
        $('#bycandidate').addClass('active'); //make the dropdown menu active on the correct item
		var candName = decodeURIComponent(split[3]); //grab the candidate name from the url
		console.log(toTitleCase(candName));
        break;
    case "counties":
      $('#bycounty').addClass('active');
	  var countyName = split[3];
		console.log("one more tiiiiiiiiiime");
		console.log("we're gonna celebrate");
	break;

	case "contributors":
       $('#bycontributor').addClass('active');
	   var contribNameRaw = split[3];

	   $.getJSON("/api/contributors/" + contribNameRaw, function(data){

	   		var need = "{need variable}";

		   	//intro row
				var container = $("#main");
				introRow = $("

").appendTo(container);
				introRow.addClass("row intro-row");

				var introLabel = $("CONTRIBUTOR");
				introLabel.appendTo(introRow);

				var jumbotron = $("

").appendTo(introRow);
				jumbotron.addClass("jumbotron");

				var contribName = data.results[0].contributor;

				var headerAmt = $("
" + contribName + "
");
				headerAmt.appendTo(jumbotron);

				var contribJob = data.results[0].occupation;
				var contribEmp = data.results[0].empName;

				//console.log(contribJob.length);

				var contribTitle = "";
				if((contribJob.length > 0) && (contribEmp.length > 0)){
					contribTitle = "" + contribJob + ", " + contribEmp + "";
				}else if ((contribJob.length > 0) && (contribEmp.length == 0)){
					contribTitle = "" + contribJob + "";
				}else if ((contribJob.length == 0) && (contribEmp.length > 0)){
					contribTitle = ", " + contribEmp + "";
				}else {
					contribTitle = "";
				};
				$(contribTitle).appendTo(headerAmt);

				var thinDivider = $("

");
				thinDivider.appendTo(jumbotron);

				// top totals row
				var topTotals = $("

").appendTo(container);

				var topTotalsLeft = $("

").appendTo(topTotals);

				// Location block
				var locationCity = data.results[0].city;
				var locationZip = data.results[0].zip;
				var topTotalsLeftLocationBlock = $("

LOCATION
" + locationCity + "

" + locationZip + "

" ).appendTo(topTotalsLeft);

				thinDivider.appendTo(topTotalsLeft);

				//Top contributed block
				var topTotalsContrib = $("

").appendTo(topTotalsLeft);
				var topTotalsContribCol12 = $("

").appendTo(topTotalsContrib);

				var contributionTotal = data.results[0].amount;
				var topTotalsContribLabel = $("TOP CONTRIBUTED
" + contributionTotal + "
").appendTo(topTotalsContribCol12);

				//Candidate breakdown table
				var topTotalsContribCandidate = $("

").appendTo(topTotalsContribCol12);
				var topTotalsContribCandidateCol12 = $("

").appendTo(topTotalsContribCandidate);
				var topTotalsContribCandidateTable = $("

").appendTo(topTotalsContribCandidateCol12);

				//Corbett_Wolf variables and logic
				var wolfContributionAmt = "";
				var wolfContributionNum = "";
				var results = data.results[0].beneficiaries;
				$.each(results, function(i, item){
					if(results[i].filerid == "20130153"){
						wolfContributionAmt = results[i].amount;
						wolfContributionNum = results[i].contributions;
					}else {
						wolfContributionAmt = "0";
						wolfContributionNum = "0";
					}
				});

				var corbettContributionAmt = "";
				var corbettContributionNum = "";
				var results = data.results[0].beneficiaries;
				$.each(results, function(i, item){
					if(results[i].filerid == "2009216"){
						corbettContributionAmt = results[i].amount;
						corbettContributionNum = results[i].contributions;
					}else {
						corbettContributionAmt = "0";
						corbettContributionNum = "0";
					}
				});

				var wolfBarWidth = "";
				var corbettBarWidth = "";
				if(wolfContributionAmt > corbettContributionAmt){
					wolfBarWidth = "100";
					corbettBarWidth = (corbettContributionAmt)/(wolfContributionAmt);
				}else if(corbettContributionAmt > wolfContributionAmt){
					corbettBarWidth = "100";
					wolfBarWidth = (wolfContributionAmt)/(corbettContributionAmt);
				} else{
					corbettBarWidth = "100";
					wolfBarWidth = "100";
				};

				//Corbett row --> need to make graphic length respect amt donated
				var topTotalsCorbettRow = $("
Corbett

" + corbettContributionAmt + " (" + corbettContributionNum + " donations)" + "
").appendTo(topTotalsContribCandidateTable);

				//Wolf row --> need to make graphic length respect amt donated
				var topTotalsWolfRow = $("
Wolf

" + wolfContributionAmt + " (" + wolfContributionNum + " donations)" + "
").appendTo(topTotalsContribCandidateTable);

				//Overtime
				var topTotalsOvertime = $("
").appendTo(topTotals);
				var topTotalsOvertimeGraph = $("
Contributions over time
").appendTo(topTotalsOvertime);

				thinDivider.appendTo(container);

			});

        break;
		case "contributions":
         $('#bycontributor').addClass('active');
		  var contributionID = split[3];

			$.getJSON("/api/contributions/" + contributionID, function(data){
				var contribName = data.results[0].contributor;
				var contributionAmt = "$" + data.results[0].contribution;

				var conDateRaw = data.results[0].date;
				var d = new Date(conDateRaw);
				var con_date = d.getDate(conDateRaw);
				var con_month = d.getMonth(conDateRaw);
				var con_year = d.getFullYear(conDateRaw);
				var contributionDate = con_month + "/" + con_date + "/" + con_year;

				var filerID = data.results[0].filerid;

				$.getJSON("/api/contributors/" + contribName, function(data){
					 var locationCity = data.results[0].city;
					 var locationZip = data.results[0].zip;
					 locationZip.substring(0,5);

					$.getJSON("/api/candidates/", function(data){

						var candidateName = "";
						var results = data.results;
						$.each(results, function(i, item){
							if(results[i].filerid == filerID){
								candidateName = results[i].name;
							}
						});

						//intro row
						var container = $("#main");
						introRow = $("

").appendTo(container);
						introRow.addClass("row intro-row");

						var introLabel = $("CONTRIBUTION");
						introLabel.appendTo(introRow);

						var jumbotron = $("

").appendTo(introRow);
						jumbotron.addClass("jumbotron");

						var headerAmt = $("
" + contributionAmt + "
");
						headerAmt.appendTo(jumbotron);

						var thinDivider = $("

");
						thinDivider.appendTo(jumbotron);

						//donation info row
						contributionRow = $("

").appendTo(container);
						contributionRow.addClass("row");

						var colmd5 = "col-md-5";
						var collg7 = "col-lg-7";
						var colmd7 = "col-md-7";
						var colsm7 = "col-sm-7";

						contributionColumn = $("

").appendTo(contributionRow);
						contributionColumn.addClass(colmd5);

						var h3 = "

";

						var contribItem = $(h3).appendTo(contributionColumn);
						contribItem.addClass("donor-item");
						var contribLabel = $("Donor: ").appendTo(contribItem);
						var contribLink = $("" + contribName + "").appendTo(contribItem);
						contribLink.attr("href", "/a/contributors/" + contribName);

						var candidateItem = $(h3).appendTo(contributionColumn);
						candidateItem.addClass("candidate-item");
						var candidateLabel = $("Candidate: ").appendTo(candidateItem);
						var candidateLink = $("" + candidateName + "").appendTo(candidateItem);
						candidateLink.attr("href", "/a/candidates/" + candidateName);

						var dateItem = $(h3).appendTo(contributionColumn);
						dateItem.addClass("date-item");
						var dateLabel = $("Date: ").appendTo(dateItem);
						var dateData = $("" + contributionDate + "").appendTo(dateItem);

						var locationItem = $(h3).appendTo(contributionColumn);
						locationItem.addClass("location-item");
						var locationLabel = $("Location: ").appendTo(locationItem);
						var locationData = $("" + locationCity + ", " + locationZip + "").appendTo(locationItem);

						mapColumn = $("

").appendTo(contributionRow);
						mapColumn.addClass(collg7 + " " + colmd7 + " " + colsm7);

						var countyMap = $("").appendTo(mapColumn);
						countyMap.addClass("sm_county_map");
						countyMap.attr("src", "/img/allegheny-map.png");
						countyMap.attr("alt", "Allegheny County locator map");

					});

				});

			});

		break;
    default:
        //default //code block
}

});

function toTitleCase(str)
{
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}<commit_msg>add laura's tabular data at bottom of contributors<commit_after>var map;
$(document).ready(function() {
 /* var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(40.4450813, -80.00877459999998),
	disableDefaultUI: true
  };
  map = new google.maps.Map(document.getElementById('map_canvas'),
      mapOptions);*/

 //parse url
 var pathname = window.location.pathname; //get current url
 var split = pathname.split("/"); //treat it like a string, break it up where the /'s are
 //console.log(split[2]);

 //case statement
 switch(split[2]) { //the second item in the array will be the type of page this will be
    case "candidates":
        $('#bycandidate').addClass('active'); //make the dropdown menu active on the correct item
		var candName = decodeURIComponent(split[3]); //grab the candidate name from the url
		console.log(toTitleCase(candName));
        break;
    case "counties":
      $('#bycounty').addClass('active');
	  var countyName = split[3];
		console.log("one more tiiiiiiiiiime");
		console.log("we're gonna celebrate");
	break;

	case "contributors":
       $('#bycontributor').addClass('active');
	   var contribNameRaw = split[3];

	   $.getJSON("/api/contributors/" + contribNameRaw, function(data){

	   		var need = "{need variable}";

		   	//intro row
				var container = $("#main");
				introRow = $("

").appendTo(container);
				introRow.addClass("row intro-row");

				var introLabel = $("CONTRIBUTOR");
				introLabel.appendTo(introRow);

				var jumbotron = $("

").appendTo(introRow);
				jumbotron.addClass("jumbotron");

				var contribName = data.results[0].contributor;

				var headerAmt = $("
" + contribName + "
");
				headerAmt.appendTo(jumbotron);

				var contribJob = data.results[0].occupation;
				var contribEmp = data.results[0].empName;

				//console.log(contribJob.length);

				var contribTitle = "";
				if((contribJob.length > 0) && (contribEmp.length > 0)){
					contribTitle = "" + contribJob + ", " + contribEmp + "";
				}else if ((contribJob.length > 0) && (contribEmp.length == 0)){
					contribTitle = "" + contribJob + "";
				}else if ((contribJob.length == 0) && (contribEmp.length > 0)){
					contribTitle = ", " + contribEmp + "";
				}else {
					contribTitle = "";
				};
				$(contribTitle).appendTo(headerAmt);

				var thinDivider = $("

");
				thinDivider.appendTo(jumbotron);

				// top totals row
				var topTotals = $("

").appendTo(container);

				var topTotalsLeft = $("

").appendTo(topTotals);

				// Location block
				var locationCity = data.results[0].city;
				var locationZip = data.results[0].zip;
				var topTotalsLeftLocationBlock = $("

LOCATION
" + locationCity + "

" + locationZip + "

" ).appendTo(topTotalsLeft);

				thinDivider.appendTo(topTotalsLeft);

				//Top contributed block
				var topTotalsContrib = $("

").appendTo(topTotalsLeft);
				var topTotalsContribCol12 = $("

").appendTo(topTotalsContrib);

				var contributionTotal = data.results[0].amount;
				var topTotalsContribLabel = $("TOP CONTRIBUTED
" + contributionTotal + "
").appendTo(topTotalsContribCol12);

				//Candidate breakdown table
				var topTotalsContribCandidate = $("

").appendTo(topTotalsContribCol12);
				var topTotalsContribCandidateCol12 = $("

").appendTo(topTotalsContribCandidate);
				var topTotalsContribCandidateTable = $("

").appendTo(topTotalsContribCandidateCol12);

				//Corbett_Wolf variables and logic
				var wolfContributionAmt = "";
				var wolfContributionNum = "";
				var results = data.results[0].beneficiaries;
				$.each(results, function(i, item){
					if(results[i].filerid == "20130153"){
						wolfContributionAmt = results[i].amount;
						wolfContributionNum = results[i].contributions;
					}else {
						wolfContributionAmt = "0";
						wolfContributionNum = "0";
					}
				});

				var corbettContributionAmt = "";
				var corbettContributionNum = "";
				var results = data.results[0].beneficiaries;
				$.each(results, function(i, item){
					if(results[i].filerid == "2009216"){
						corbettContributionAmt = results[i].amount;
						corbettContributionNum = results[i].contributions;
					}else {
						corbettContributionAmt = "0";
						corbettContributionNum = "0";
					}
				});

				var wolfBarWidth = "";
				var corbettBarWidth = "";
				if(wolfContributionAmt > corbettContributionAmt){
					wolfBarWidth = "100";
					corbettBarWidth = (corbettContributionAmt)/(wolfContributionAmt);
				}else if(corbettContributionAmt > wolfContributionAmt){
					corbettBarWidth = "100";
					wolfBarWidth = (wolfContributionAmt)/(corbettContributionAmt);
				} else{
					corbettBarWidth = "100";
					wolfBarWidth = "100";
				};

				//Corbett row --> need to make graphic length respect amt donated
				var topTotalsCorbettRow = $("
Corbett

" + corbettContributionAmt + " (" + corbettContributionNum + " donations)" + "
").appendTo(topTotalsContribCandidateTable);

				//Wolf row --> need to make graphic length respect amt donated
				var topTotalsWolfRow = $("
Wolf

" + wolfContributionAmt + " (" + wolfContributionNum + " donations)" + "
").appendTo(topTotalsContribCandidateTable);

				//Overtime
				var topTotalsOvertime = $("
").appendTo(topTotals);
				var topTotalsOvertimeGraph = $("
Contributions over time
").appendTo(topTotalsOvertime);

				thinDivider.appendTo(container);

				container.append(thinDivider);

				container.append('

Other donations by ' + contribName +'
<form class="form-inline pull-right"><input type="search" class="form-control" placeholder="Search"><button type="submit" class="btn btn-default">Submit</button></form>

Donor	 Occupation, Employer	Amount

 ');

				//get contributor data
				$.getJSON("/api/contributors/" + contribNameRaw, function(data){
					console.log(data.results[0].contributor);
					console.log(data.results.length);

					var line;
					for(var i =0; i < data.results.length; i++) {
						var emp;
						if (data.results[i].occupation == '') { //don't show comma if there's no occupation
							emp = data.results[i].empName;
						} else {
							emp = data.results[i].occupation + ", " + data.results[i].empName;
						}
						line = "
" + data.results[i].contributor + "	" +  emp  + "	$" + data.results[i].amount + "
";
						console.log(line);
						$('tbody').append(line);
					}

				});

			});

        break;
		case "contributions":
         $('#bycontributor').addClass('active');
		  var contributionID = split[3];

			$.getJSON("/api/contributions/" + contributionID, function(data){
				var contribName = data.results[0].contributor;
				var contributionAmt = "$" + data.results[0].contribution;

				var conDateRaw = data.results[0].date;
				var d = new Date(conDateRaw);
				var con_date = d.getDate(conDateRaw);
				var con_month = d.getMonth(conDateRaw);
				var con_year = d.getFullYear(conDateRaw);
				var contributionDate = con_month + "/" + con_date + "/" + con_year;

				var filerID = data.results[0].filerid;

				$.getJSON("/api/contributors/" + contribName, function(data){
					 var locationCity = data.results[0].city;
					 var locationZip = data.results[0].zip;
					 locationZip.substring(0,5);

					$.getJSON("/api/candidates/", function(data){

						var candidateName = "";
						var results = data.results;
						$.each(results, function(i, item){
							if(results[i].filerid == filerID){
								candidateName = results[i].name;
							}
						});

						//intro row
						var container = $("#main");
						introRow = $("

").appendTo(container);
						introRow.addClass("row intro-row");

						var introLabel = $("CONTRIBUTION");
						introLabel.appendTo(introRow);

						var jumbotron = $("

").appendTo(introRow);
						jumbotron.addClass("jumbotron");

						var headerAmt = $("
" + contributionAmt + "
");
						headerAmt.appendTo(jumbotron);

						var thinDivider = $("

");
						thinDivider.appendTo(jumbotron);

						//donation info row
						contributionRow = $("

").appendTo(container);
						contributionRow.addClass("row");

						var colmd5 = "col-md-5";
						var collg7 = "col-lg-7";
						var colmd7 = "col-md-7";
						var colsm7 = "col-sm-7";

						contributionColumn = $("

").appendTo(contributionRow);
						contributionColumn.addClass(colmd5);

						var h3 = "

";

						var contribItem = $(h3).appendTo(contributionColumn);
						contribItem.addClass("donor-item");
						var contribLabel = $("Donor: ").appendTo(contribItem);
						var contribLink = $("" + contribName + "").appendTo(contribItem);
						contribLink.attr("href", "/a/contributors/" + contribName);

						var candidateItem = $(h3).appendTo(contributionColumn);
						candidateItem.addClass("candidate-item");
						var candidateLabel = $("Candidate: ").appendTo(candidateItem);
						var candidateLink = $("" + candidateName + "").appendTo(candidateItem);
						candidateLink.attr("href", "/a/candidates/" + candidateName);

						var dateItem = $(h3).appendTo(contributionColumn);
						dateItem.addClass("date-item");
						var dateLabel = $("Date: ").appendTo(dateItem);
						var dateData = $("" + contributionDate + "").appendTo(dateItem);

						var locationItem = $(h3).appendTo(contributionColumn);
						locationItem.addClass("location-item");
						var locationLabel = $("Location: ").appendTo(locationItem);
						var locationData = $("" + locationCity + ", " + locationZip + "").appendTo(locationItem);

						mapColumn = $("

").appendTo(contributionRow);
						mapColumn.addClass(collg7 + " " + colmd7 + " " + colsm7);

						var countyMap = $("").appendTo(mapColumn);
						countyMap.addClass("sm_county_map");
						countyMap.attr("src", "/img/allegheny-map.png");
						countyMap.attr("alt", "Allegheny County locator map");

					});

				});

			});

		break;
    default:
        //default //code block
}

});

function toTitleCase(str)
{
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}<|endoftext|>


<commit_before>			//http://www.javascriptlint.com/online_lint.php

			//Funcoes do Phonegap
			var isPhoneGapReady = false;
			var isConnected = false;
			var isHighSpeed = false;
			var tipo_conexao = "";
			var email_aplicativo;
			var latitude = "";
			var longitude = "";

			//$(document).ready(function(){
			document.addEventListener("deviceready", onDeviceReady, false);
			//});

			function onDeviceReady() {
				isPhoneGapReady = true;
				// detect for network access
				networkDetection();
				// attach events for online and offline detection
				document.addEventListener("online", onOnline, false);
				document.addEventListener("offline", onOffline, false);
			}

			function networkDetection() {
				if (isPhoneGapReady) {

					isConnected = false;
					var states = {};
					states[navigator.connection.UNKNOWN]  = 'Unknown connection';
					states[navigator.connection.ETHERNET] = 'Ethernet connection';
					states[navigator.connection.WIFI]     = 'WiFi connection';
					states[navigator.connection.CELL_2G]  = 'Cell 2G connection';
					states[navigator.connection.CELL_3G]  = 'Cell 3G connection';
					states[navigator.connection.CELL_4G]  = 'Cell 4G connection';
					states[navigator.connection.NONE]     = 'No network connection';
					var tipo_conexao = states[navigator.connection.type];

					if (tipo_conexao != 'No network connection') {
						isConnected = true;
					}

				}
			}

			function onOnline() {
				isConnected = true;
			}
			function onOffline() {
				isConnected = false;
			}

			function ValidarNavegacao(){
				if (isPhoneGapReady){
					if (isConnected) {
						//Continuar
					} else {
						navigator.notification.alert('No existe conexo com a Internet', alertDismissed, 'Jogo de Perguntas', 'OK');
						$.mobile.changePage("index.html");
					}
				} else {
					navigator.notification.alert('O aplicativo no est pronto!', alertDismissed, 'Jogo de Perguntas', 'OK');
					$.mobile.changePage("index.html");
				}
			}

			//Funcoes do aplicativo
			function valButton(btn) {
				var cnt = -1;
				for (var i=btn.length-1; i > -1; i--) {
					if (btn[i].checked) {cnt = i; i = -1;}
				}
				if (cnt > -1) return btn[cnt].value;
				else return null;
			}

			function shuffleArray(array) {
				for (var i = array.length - 1; i > 0; i--) {
					var j = Math.floor(Math.random() * (i + 1));
					var temp = array[i];
					array[i] = array[j];
					array[j] = temp;
				}
				return array;
			}

			function ListarOpcoes(Pergunta){
				var tmp_opcao_contador = 1;
				var tmp_opcao_codigo = [];
				var tmp_opcao_descricao = [];
				$.ajax({
				type: "GET",
				url: "http://www.dbins.com.br/ferramentas/interior/xml/opcao_resposta.xml",
				dataType: "xml",
				success: function(data) {

					$(data).find('opcao_resposta').each(function(){

						var tmp_pergunta  = $(this).find("opr_pergunta").text();
						if (tmp_pergunta  == Pergunta) {
							var codigo = $(this).find("opr_cod").text();
							var opcao_resposta = $(this).find("opr_descricao").text();
							tmp_opcao_codigo.push(codigo);
							tmp_opcao_descricao.push(opcao_resposta);
						}
					});

					for (i = 0; i < 5; i++) {
						$('#opcao' + tmp_opcao_contador + '_rotulo').html(tmp_opcao_descricao[i]);
						$('#opcao' + tmp_opcao_contador).val(tmp_opcao_codigo[i]);
						tmp_opcao_contador++;
					}
					}
				});
			}

			function ValidarResposta(Resposta, Matriz){
				var retorno = "ERRO";
				for (w = 0; w < Matriz.length; w++) {
					if (Math.abs(Resposta) == Math.abs(Matriz[w])) {
						retorno = "ACERTO";
					}
				}
				return retorno;
			}

			function DescricaoResposta(Resposta, Matriz){
				var retorno = "";
				for (w = 0; w < Matriz.length; w++) {
					var conteudo = Matriz[w];
					var tmp_matriz = conteudo.split('*');
					if (Math.abs(Resposta) == Math.abs(tmp_matriz[0])) {
						retorno = tmp_matriz[1];
					}
				}
				return retorno;
			}

			//var perguntas = ["Pergunta1", "Pergunta2", "Pergunta3", "Pergunta4","Pergunta5"];
			var quantidade_acertos = 0;
			var codigo_pergunta = 612;
			var contador = 1;
			var perguntas = [];
			var opcoes_corretas = [];
			var opcoes_corretas_FULL = [];
			var opcoes_descricoes = [];
			var opcoes_descricoes_FULL = [];
			var tmp_respostas = [];
			var tmp_acertos = [];

			$(document).on('pageshow', '#inicio', function(){
				alert('*');
				if (isPhoneGapReady){
					if (isConnected) {
						$('#aviso_offline').hide();
						$('#btn_iniciar').show();
					} else {
						$('#aviso_offline').show();
						$('#btn_iniciar').hide();
					}
				} else {
					$('#aviso_offline').show();
					$('#btn_iniciar').hide();
				}
			});

			$(document).on('pageshow', '#tela1', function(){
				alert('*');
				ValidarNavegacao();
				$.ajax({
				type: "GET",
				url: "http://www.dbins.com.br/ferramentas/interior/xml/perguntas.xml",
				dataType: "xml",
				success: function(data) {

					$(data).find('pergunta').each(function(){

						var codigo = $(this).find("per_cod").text();
						var pergunta = $(this).find("per_pergunta").text();

						var tmp_array = [codigo, pergunta];
						var tmp_conteudo = codigo + '*' + pergunta;
						perguntas.push(tmp_conteudo);
					});
					perguntas = shuffleArray(perguntas);
					var tmp_conteudo = perguntas[0];
					var tmp_matriz = tmp_conteudo.split('*');
					$('#pergunta').html(tmp_matriz[1]);
					codigo_pergunta = tmp_matriz[0];
					}
				});
				//Puxando as opcoes de respostas
				$.ajax({
				type: "GET",
				url: "http://www.dbins.com.br/ferramentas/interior/xml/opcao_resposta.xml",
				dataType: "xml",
				success: function(data) {

					$(data).find('opcao_resposta').each(function(){

						var codigo = $(this).find("opr_cod").text();
						var descricao = $(this).find("opr_descricao").text();
						var valida = $(this).find("opr_valida").text();
						var tmp_conteudo = codigo + '*' + descricao;
						if (Math.abs(valida)==1){
							opcoes_corretas.push(codigo);
						}
						opcoes_descricoes.push(tmp_conteudo);
					});
					opcoes_corretas_FULL = opcoes_corretas;
					opcoes_descricoes_FULL = opcoes_descricoes;
					opcoes_descricoes = shuffleArray(opcoes_descricoes);
					},
					error: function(xhr, status, error) {
						//alert(status);
						//alert(xhr.responseText);
					 }
				});

				//Carga inicial do sistema
				ListarOpcoes(codigo_pergunta);

				$('#btn_responder').click(function(){

					contador = $('#contador').val();
					var tmp_contador = Math.abs(contador) - 1;
					var tmp_resposta_atual = $('input:radio[name=opcao]:checked').val();

					if (tmp_resposta_atual != null){

						//Limpando todos os botoes
						$('input[name=opcao]').prop('checked', false);

						tmp_respostas.push(tmp_resposta_atual);
						//Validar se a resposta esta certa
						//tmp_acertos.push("ERRO");
						if (ValidarResposta(tmp_resposta_atual, opcoes_corretas_FULL)=="ACERTO"){
							quantidade_acertos++;
						}

						//Incrementando o contador e mostrando a proxima pergunta
						contador++;
						var tmp_conteudo = perguntas[tmp_contador];
						var tmp_matriz = tmp_conteudo.split('*');

						$('#pergunta').html(contador + ' -  ' + tmp_matriz[1]);
						//Atualizado as opcoes
						codigo_pergunta = tmp_matriz[0];
						ListarOpcoes(codigo_pergunta);
						$('#contador').val(contador);
						if (contador == 6) {
							$('#pergunta').html('');
							//Exibir o resultado na mesma pagina

							//,Montando o painel de respostas
							var tmp_tabela;
							tmp_tabela = '
';
							tmp_tabela += '

Voce acertou ' + quantidade_acertos + ' de 5
';
							tmp_tabela += '
';
							tmp_tabela += 'Pergunta	';
							tmp_tabela += 'Sua resposta	';
							tmp_tabela += 'Resultado	';
							tmp_tabela += '

';

							for (i = 0; i < 5; i++) {
								var tmp_conteudo1 = perguntas[i];
								var tmp_matriz1 = tmp_conteudo1.split('*');
								tmp_tabela += '
';
								tmp_tabela += '' + tmp_matriz1[1]  +'	';
								tmp_tabela += '' + DescricaoResposta(tmp_respostas[i], opcoes_descricoes_FULL) + '	';
								tmp_tabela += '' + ValidarResposta(tmp_respostas[i], opcoes_corretas_FULL) + '	';
								tmp_tabela += '
';
							}

							tmp_tabela += '

';
							$('#tabela_respostas').html(tmp_tabela);
							$("#painel_perguntas").hide();
							$("#painel_respostas").show();
						}
					} else {
						alert('Voc nao selecionou nenhuma opcao!');
					}
				});
			 });

			<commit_msg>2016-05-10<commit_after>			//http://www.javascriptlint.com/online_lint.php

			//Funcoes do Phonegap
			var isPhoneGapReady = false;
			var isConnected = false;
			var isHighSpeed = false;
			var tipo_conexao = "";
			var email_aplicativo;
			var latitude = "";
			var longitude = "";

			//$(document).ready(function(){
			document.addEventListener("deviceready", onDeviceReady, false);
			//});

			function onDeviceReady() {
				isPhoneGapReady = true;
				// detect for network access
				networkDetection();
				// attach events for online and offline detection
				document.addEventListener("online", onOnline, false);
				document.addEventListener("offline", onOffline, false);
			}

			function networkDetection() {
				if (isPhoneGapReady) {

					isConnected = false;
					var states = {};
					states[navigator.connection.UNKNOWN]  = 'Unknown connection';
					states[navigator.connection.ETHERNET] = 'Ethernet connection';
					states[navigator.connection.WIFI]     = 'WiFi connection';
					states[navigator.connection.CELL_2G]  = 'Cell 2G connection';
					states[navigator.connection.CELL_3G]  = 'Cell 3G connection';
					states[navigator.connection.CELL_4G]  = 'Cell 4G connection';
					states[navigator.connection.NONE]     = 'No network connection';
					var tipo_conexao = states[navigator.connection.type];

					if (tipo_conexao != 'No network connection') {
						isConnected = true;
					}

				}
			}

			function onOnline() {
				isConnected = true;
			}
			function onOffline() {
				isConnected = false;
			}

			function ValidarNavegacao(){
				if (isPhoneGapReady){
					if (isConnected) {
						//Continuar
					} else {
						navigator.notification.alert('No existe conexo com a Internet', alertDismissed, 'Jogo de Perguntas', 'OK');
						$.mobile.changePage("index.html");
					}
				} else {
					navigator.notification.alert('O aplicativo no est pronto!', alertDismissed, 'Jogo de Perguntas', 'OK');
					$.mobile.changePage("index.html");
				}
			}

			//Funcoes do aplicativo
			function valButton(btn) {
				var cnt = -1;
				for (var i=btn.length-1; i > -1; i--) {
					if (btn[i].checked) {cnt = i; i = -1;}
				}
				if (cnt > -1) return btn[cnt].value;
				else return null;
			}

			function shuffleArray(array) {
				for (var i = array.length - 1; i > 0; i--) {
					var j = Math.floor(Math.random() * (i + 1));
					var temp = array[i];
					array[i] = array[j];
					array[j] = temp;
				}
				return array;
			}

			function ListarOpcoes(Pergunta){
				var tmp_opcao_contador = 1;
				var tmp_opcao_codigo = [];
				var tmp_opcao_descricao = [];
				$.ajax({
				type: "GET",
				url: "http://www.dbins.com.br/ferramentas/interior/xml/opcao_resposta.xml",
				dataType: "xml",
				success: function(data) {

					$(data).find('opcao_resposta').each(function(){

						var tmp_pergunta  = $(this).find("opr_pergunta").text();
						if (tmp_pergunta  == Pergunta) {
							var codigo = $(this).find("opr_cod").text();
							var opcao_resposta = $(this).find("opr_descricao").text();
							tmp_opcao_codigo.push(codigo);
							tmp_opcao_descricao.push(opcao_resposta);
						}
					});

					for (i = 0; i < 5; i++) {
						$('#opcao' + tmp_opcao_contador + '_rotulo').html(tmp_opcao_descricao[i]);
						$('#opcao' + tmp_opcao_contador).val(tmp_opcao_codigo[i]);
						tmp_opcao_contador++;
					}
					}
				});
			}

			function ValidarResposta(Resposta, Matriz){
				var retorno = "ERRO";
				for (w = 0; w < Matriz.length; w++) {
					if (Math.abs(Resposta) == Math.abs(Matriz[w])) {
						retorno = "ACERTO";
					}
				}
				return retorno;
			}

			function DescricaoResposta(Resposta, Matriz){
				var retorno = "";
				for (w = 0; w < Matriz.length; w++) {
					var conteudo = Matriz[w];
					var tmp_matriz = conteudo.split('*');
					if (Math.abs(Resposta) == Math.abs(tmp_matriz[0])) {
						retorno = tmp_matriz[1];
					}
				}
				return retorno;
			}

			//var perguntas = ["Pergunta1", "Pergunta2", "Pergunta3", "Pergunta4","Pergunta5"];
			var quantidade_acertos = 0;
			var codigo_pergunta = 612;
			var contador = 1;
			var perguntas = [];
			var opcoes_corretas = [];
			var opcoes_corretas_FULL = [];
			var opcoes_descricoes = [];
			var opcoes_descricoes_FULL = [];
			var tmp_respostas = [];
			var tmp_acertos = [];

			$(document).on('pageshow', '#inicio', function(){
				if (isPhoneGapReady){
					if (isConnected) {
						$('#aviso_offline').hide();
						$('#btn_iniciar').show();
					} else {
						$('#aviso_offline').show();
						$('#btn_iniciar').hide();
					}
				} else {
					$('#aviso_offline').show();
					$('#btn_iniciar').hide();
				}
			});

			$(document).on('pageshow', '#tela1', function(){
				ValidarNavegacao();
				$.ajax({
				type: "GET",
				url: "http://www.dbins.com.br/ferramentas/interior/xml/perguntas.xml",
				dataType: "xml",
				success: function(data) {

					$(data).find('pergunta').each(function(){

						var codigo = $(this).find("per_cod").text();
						var pergunta = $(this).find("per_pergunta").text();

						var tmp_array = [codigo, pergunta];
						var tmp_conteudo = codigo + '*' + pergunta;
						perguntas.push(tmp_conteudo);
					});
					perguntas = shuffleArray(perguntas);
					var tmp_conteudo = perguntas[0];
					var tmp_matriz = tmp_conteudo.split('*');
					$('#pergunta').html(tmp_matriz[1]);
					codigo_pergunta = tmp_matriz[0];
					}
				});
				//Puxando as opcoes de respostas
				$.ajax({
				type: "GET",
				url: "http://www.dbins.com.br/ferramentas/interior/xml/opcao_resposta.xml",
				dataType: "xml",
				success: function(data) {

					$(data).find('opcao_resposta').each(function(){

						var codigo = $(this).find("opr_cod").text();
						var descricao = $(this).find("opr_descricao").text();
						var valida = $(this).find("opr_valida").text();
						var tmp_conteudo = codigo + '*' + descricao;
						if (Math.abs(valida)==1){
							opcoes_corretas.push(codigo);
						}
						opcoes_descricoes.push(tmp_conteudo);
					});
					opcoes_corretas_FULL = opcoes_corretas;
					opcoes_descricoes_FULL = opcoes_descricoes;
					opcoes_descricoes = shuffleArray(opcoes_descricoes);
					},
					error: function(xhr, status, error) {
						//alert(status);
						//alert(xhr.responseText);
					 }
				});

				//Carga inicial do sistema
				ListarOpcoes(codigo_pergunta);

				$('#btn_responder').click(function(){

					contador = $('#contador').val();
					var tmp_contador = Math.abs(contador) - 1;
					var tmp_resposta_atual = $('input:radio[name=opcao]:checked').val();

					if (tmp_resposta_atual != null){

						//Limpando todos os botoes
						$('input[name=opcao]').prop('checked', false);

						tmp_respostas.push(tmp_resposta_atual);
						//Validar se a resposta esta certa
						//tmp_acertos.push("ERRO");
						if (ValidarResposta(tmp_resposta_atual, opcoes_corretas_FULL)=="ACERTO"){
							quantidade_acertos++;
						}

						//Incrementando o contador e mostrando a proxima pergunta
						contador++;
						var tmp_conteudo = perguntas[tmp_contador];
						var tmp_matriz = tmp_conteudo.split('*');

						$('#pergunta').html(contador + ' -  ' + tmp_matriz[1]);
						//Atualizado as opcoes
						codigo_pergunta = tmp_matriz[0];
						ListarOpcoes(codigo_pergunta);
						$('#contador').val(contador);
						if (contador == 6) {
							$('#pergunta').html('');
							//Exibir o resultado na mesma pagina

							//,Montando o painel de respostas
							var tmp_tabela;
							tmp_tabela = '
';
							tmp_tabela += '

Voce acertou ' + quantidade_acertos + ' de 5
';
							tmp_tabela += '
';
							tmp_tabela += 'Pergunta	';
							tmp_tabela += 'Sua resposta	';
							tmp_tabela += 'Resultado	';
							tmp_tabela += '

';

							for (i = 0; i < 5; i++) {
								var tmp_conteudo1 = perguntas[i];
								var tmp_matriz1 = tmp_conteudo1.split('*');
								tmp_tabela += '
';
								tmp_tabela += '' + tmp_matriz1[1]  +'	';
								tmp_tabela += '' + DescricaoResposta(tmp_respostas[i], opcoes_descricoes_FULL) + '	';
								tmp_tabela += '' + ValidarResposta(tmp_respostas[i], opcoes_corretas_FULL) + '	';
								tmp_tabela += '
';
							}

							tmp_tabela += '

';
							$('#tabela_respostas').html(tmp_tabela);
							$("#painel_perguntas").hide();
							$("#painel_respostas").show();
						}
					} else {
						alert('Voc nao selecionou nenhuma opcao!');
					}
				});
			 });

			<|endoftext|>


<commit_before>var mssuit = (i) => {
    var y = i % 4; // swap D & C
    return y === 0 ? 1 : y === 1 ? 0 : y;
  },
  msrank = (i) => Math.floor(i / 4),
  suit = (s) => s >> 4 & 3,
  rank = (r) => r & 15,
  toStr = (rank, suit) => rank ? ' A23456789TJQK' [rank] + 'DCHS ' [suit] : '  ';

function shuffle(demo) {
  var seed = demo || Math.floor(Math.random() * 1000000000),
    gameno = seed,
    deck = [],
    i = 52,
    rand = function rand() {
      seed = (seed * 214013 + 2531011) % 2147483648;
      return seed >> 16;
    };
  for (var j = 0; j < 52; j++) {
    deck.push(j);
  }
  while (--i) {
    j = rand() % (i + 1);
    var tmp = deck[i];
    deck[i] = deck[j];
    deck[j] = tmp;
  }
  deck = deck.reverse();

  return {
    deck: deck,
    gameno: gameno
  };
}

function message(tableau, sep = '
') {
  var msg, flag, r, c, card;
  for (msg = "", flag = true, r = 0; flag;) {
    r > 0 && (flag = false);
    for (c = 0; c < 8; c++) {
      n = tableau[c][r],
      card = toStr(rank(n), suit(n)),
      card != "  " && (flag = true),
      msg += card + " ";
    }
    msg += sep, r++;
  }
  return msg;
}
<commit_msg>Update shuffle.js<commit_after>var mssuit = (i) => {
    var y = i % 4; // swap D & C
    return y === 0 ? 1 : y === 1 ? 0 : y;
  },
  msrank = (i) => Math.floor(i / 4),
  suit = (s) => s >> 4 & 3,
  rank = (r) => r & 15,
  toStr = (rank, suit) => rank ? ' A23456789TJQK' [rank] + 'DCHS ' [suit] : '  ';

function shuffle(demo) {
  var seed = demo || Math.floor(Math.random() * 1000000000),
    gameno = seed,
    deck = [],
    i = 52,
    rand = function rand() {
      seed = (seed * 214013 + 2531011) % 2147483648;
      return seed >> 16;
    };
  for (var j = 0; j < 52; j++) {
    deck.push(j);
  }
  while (--i) {
    j = rand() % (i + 1);
    var tmp = deck[i];
    deck[i] = deck[j];
    deck[j] = tmp;
  }
  deck = deck.reverse();

  return {
    deck: deck,
    gameno: gameno
  };
}

function message(tableau, sep = '
') {
  var msg, flag, r, c, card, n;
  for (msg = "", flag = true, r = 0; flag;) {
    r > 0 && (flag = false);
    for (c = 0; c < 8; c++) {
      n = tableau[c][r],
      card = toStr(rank(n), suit(n)),
      card != "  " && (flag = true),
      msg += card + " ";
    }
    msg += sep, r++;
  }
  return msg;
}
<|endoftext|>


<commit_before>/**
 * @module rollup
 * @license MIT
 * @version 2017/12/18
 */

'use strict';

const path = require('path');
const fs = require('fs-extra');
const terser = require('terser');
const rollup = require('rollup');
const pkg = require('./package.json');
const typescript = require('rollup-plugin-typescript2');

/**
 * @function build
 * @param {Object} inputOptions
 * @param {Object} outputOptions
 */
async function build(inputOptions, outputOptions) {
  await fs.remove('dist');

  const bundle = await rollup.rollup(inputOptions);

  await bundle.write(outputOptions);

  const file = outputOptions.file;

  console.log(`Build ${file} success!`);

  const min = file.replace(/\.js$/i, '.min.js');
  const map = `${file}.map`;

  const minify = terser.minify(
    { 'portal.js': (await fs.readFile(path.resolve(file))).toString() },
    { ecma: 5, ie8: true, mangle: { eval: true }, sourceMap: { url: path.basename(map) } }
  );

  await fs.outputFile(min, outputOptions.banner + minify.code);
  console.log(`Build ${min} success!`);

  await fs.outputFile(map, minify.map);
  console.log(`Build ${map} success!`);
}

const banner = `/**
 * @module ${pkg.name}
 * @author ${pkg.author.name}
 * @license ${pkg.license}
 * @version ${pkg.version}
 * @description ${pkg.description}
 * @see ${pkg.homepage}
 */
`;

const inputOptions = {
  context: 'window',
  input: 'src/portal.ts',
  plugins: [typescript()]
};

const outputOptions = {
  banner,
  indent: true,
  strict: true,
  legacy: true,
  format: 'umd',
  name: 'Portal',
  amd: { id: 'portal' },
  file: 'dist/portal.js'
};

build(inputOptions, outputOptions);
<commit_msg>:art: Update file<commit_after>/**
 * @module rollup
 * @license MIT
 * @version 2017/12/18
 */

'use strict';

const path = require('path');
const fs = require('fs-extra');
const terser = require('terser');
const rollup = require('rollup');
const pkg = require('./package.json');
const typescript = require('rollup-plugin-typescript2');

/**
 * @function build
 * @param {Object} inputOptions
 * @param {Object} outputOptions
 */
async function build(inputOptions, outputOptions) {
  await fs.remove('dist');

  const bundle = await rollup.rollup(inputOptions);

  await bundle.write(outputOptions);

  const file = outputOptions.file;

  console.log(`Build ${file} success!`);

  const min = file.replace(/\.js$/i, '.min.js');
  const map = `${file}.map`;

  const minify = terser.minify(
    { 'portal.js': (await fs.readFile(path.resolve(file))).toString() },
    { ie8: true, mangle: { eval: true }, sourceMap: { url: path.basename(map) } }
  );

  await fs.outputFile(min, outputOptions.banner + minify.code);
  console.log(`Build ${min} success!`);

  await fs.outputFile(map, minify.map);
  console.log(`Build ${map} success!`);
}

const banner = `/**
 * @module ${pkg.name}
 * @author ${pkg.author.name}
 * @license ${pkg.license}
 * @version ${pkg.version}
 * @description ${pkg.description}
 * @see ${pkg.homepage}
 */
`;

const inputOptions = {
  context: 'window',
  input: 'src/portal.ts',
  plugins: [typescript()]
};

const outputOptions = {
  banner,
  indent: true,
  strict: true,
  legacy: true,
  format: 'umd',
  name: 'Portal',
  amd: { id: 'portal' },
  file: 'dist/portal.js'
};

build(inputOptions, outputOptions);
<|endoftext|>


<commit_before>'use strict';

function eat_purple_creature(){
    core_audio_start({
      'id': 'boop',
    });

    document.getElementById('score').innerHTML = parseInt(
      document.getElementById('score').innerHTML,
      10
    ) + 1;

    // If there is no space available for more holes, stop.
    var holes_per_point = core_storage_data['holes-per-point'];
    if(document.getElementById('score').innerHTML >=
      Math.floor(398 / (parseInt(holes_per_point, 10) + 1)) + 1){
        stop();
        return;
    }

    // Pick a button with color_empty and make it the new purple creature.
    var id = -1;
    do{
        id = core_random_integer({
          'max': 400,
        });
    }while(document.getElementById(id).style.backgroundColor != color_empty);
    document.getElementById(id).style.backgroundColor = color_purple;

    var loop_counter = holes_per_point - 1;
    // If more than 0 holes should be created.
    if(loop_counter >= 0){
        // Add new holes.
        do{
            while(document.getElementById(id).style.backgroundColor != color_empty){
                id = core_random_integer({
                  'max': 400,
                });
            }
            document.getElementById(id).style.backgroundColor = color_obstacle;
        }while(loop_counter--);
    }
}

function move_player(){
    // Check if game is still running, based on game mode and if frames/score are over max.
    var frames = parseFloat(document.getElementById('frames').innerHTML);
    var end_game = core_storage_data['game-mode'] === 1
      ? frames <= 0
        && core_storage_data['max'] > 0
      : core_storage_data['max'] != 0
        && parseInt(document.getElementById('score').innerHTML, 10) >= core_storage_data['max'];

    // If game is not running, stop().
    if(end_game){
        stop();
        return;
    }

    // Add or subtract 1 from frames depending on game mode.
    document.getElementById('frames').innerHTML = (frames +
        ((core_storage_data['game-mode'] === 1
      && core_storage_data['max'] > 0) ? -1 : 1));

    var check_color = 0;
    var dx = 0;
    var dy = 0;

    // If player is moving up.
    if(player['movement_direction'] === 0){
        // If player is not at the top of the screen.
        if(player['y'] - 1 >= 0){
            // Fetch color of space directly above the player.
            check_color = document.getElementById((player['y'] - 1) * 20 + player['x']).style.backgroundColor;

            // If the space is not an obstacle continue, else collision.
            if(check_color !== color_obstacle){
                // If color of space is purple, eat the creature.
                if(check_color === color_purple){
                    eat_purple_creature();
                }

                // Decrease player Y position.
                player['y'] -= 1;
                dy += 1;

            // Collision!
            }else{
                end_game = true;
            }

        // If player is at the top of the screen and can wrap in the Y-direction.
        }else if(core_storage_data['wrap'] == 2
          || core_storage_data['wrap'] == 3){
            // Fetch color of space at the bottom of the screen.
            check_color = document.getElementById((player['y'] + 19) * 20 + player['x']).style.backgroundColor;

            // If the space is not an obstacle continue.
            if(check_color !== color_obstacle){
                // If color of space is purple, eat the creature.
                if(check_color === color_purple){
                    eat_purple_creature()
                }

                // Set player Y position to bottom of the screen.
                player['y'] = 19;
                dy -= 19;

            // Collision!
            }else{
                end_game = true;
            }

        // Collision!
        }else{
            end_game = true;
        }

    // If player is moving right.
    }else if(player['movement_direction'] === 1){
        // If player is not at the right edge of the screen.
        if(player['x'] + 1 <= 19){
            // Fetch color of space to the right of the player.
            check_color = document.getElementById(player['y'] * 20 + player['x'] + 1).style.backgroundColor;

            // If the space is not an obstacle continue.
            if(check_color !== color_obstacle){
                // If color of space is purple, eat the creature.
                if(check_color === color_purple){
                    eat_purple_creature();
                }

                // Increase player X position.
                player['x'] += 1;
                dx -= 1;

            // Collision!
            }else{
                end_game = true;
            }

        // If player is at the right edge of the screen and can wrap in the X-direction.
        }else if(core_storage_data['wrap'] == 1
          || core_storage_data['wrap'] == 2){
            // Fetch color of space at the left of the screen.
            check_color = document.getElementById(player['y'] * 20 + player['x'] - 19).style.backgroundColor;

            // If the space is not an obstacle continue.
            if(check_color !== color_obstacle){
                // If color of space is purple, eat the creature.
                if(check_color === color_purple){
                    eat_purple_creature();
                }

                // Set player X position to left side of the screen.
                player['x'] -= 19;
                dx += 19;

            // Collision!
            }else{
                end_game = true;
            }

        // Collision!
        }else{
            end_game = true;
        }

    // If player is moving down.
    }else if(player['movement_direction'] === 2){
        // If player is not at the bottom of the screen.
        if(player['y'] + 1 <= 19){
            // Fetch color of space directory below the player.
            check_color = document.getElementById((player['y'] + 1) * 20 + player['x']).style.backgroundColor;

            // If the space is not an obstacle continue.
            if(check_color !== color_obstacle){
                // If color of space is purple, eat the creature.
                if(check_color === color_purple){
                    eat_purple_creature();
                }

                // Increase player Y position.
                player['y'] += 1;
                dy -= 1;

            // Collision!
            }else{
                end_game = true;
            }

        // If player is at the bottom edge of the screen and can wrap in the U-direction.
        }else if(core_storage_data['wrap'] == 2
          || core_storage_data['wrap'] == 3){
            // Fetch color of space at the top of the screen.
            check_color = document.getElementById((player['y'] - 19) * 20 + player['x']).style.backgroundColor;

            // If the space is not an obstacle continue.
            if(check_color !== color_obstacle){
                // If color of space is purple, eat the creature.
                if(check_color === color_purple){
                    eat_purple_creature();
                }

                // Set player Y position to top of the screen.
                player['y'] = 0;
                dy += 19;

            // Collision!
            }else{
                end_game = true;
            }

        // Collision!
        }else{
            end_game = true;
        }

    // If player is moving left.
    }else if(player['movement_direction'] === 3){
        if(player['x'] - 1 >= 0){
            // Fetch color of space to the left of the player.
            check_color = document.getElementById(player['y'] * 20 + player['x'] - 1).style.backgroundColor;

            // If the space is not an obstacle continue.
            if(check_color !== color_obstacle){
                // If color of space is purple, eat the creature.
                if(check_color === color_purple){
                    eat_purple_creature();
                }

                // Decrease player x position.
                player['x'] -= 1;
                dx += 1;

            // Collision!
            }else{
                end_game = true;
            }

        // If player is at the left edge of the screen and can wrap in the X-direction.
        }else if(core_storage_data['wrap'] == 1
          || core_storage_data['wrap'] == 2){
            // Fetch color of space at the right side of the screen.
            check_color = document.getElementById(player['y'] * 20 + player['x'] + 19).style.backgroundColor;

            // If the space is not an obstacle continue.
            if(check_color !== color_obstacle){
                // If color of space is purple, eat the creature.
                if(check_color === color_purple){
                    eat_purple_creature();
                }

                // Set player x position to right side of the screen.
                player['x'] += 19;
                dx -= 19;

            // Collision!
            }else{
                end_game = true;
            }

        // Collision!
        }else{
            end_game = true;
        }
    }

    // If a collision with an obstacle or edge was detected.
    if(end_game){
        // If game ends oncollision...
        if(core_storage_data['oncollision'] == 1){
            stop();

        // ...else if score decreases.
        }else if(core_storage_data['oncollision'] === 2){
            document.getElementById('score').innerHTML =
              parseInt(
                document.getElementById('score').innerHTML,
                10
              ) - 1;
        }
    }

    // If player x or y position has changed.
    if(dx !== 0
      || dy !== 0){
        // Reset old player position to color_empty.
        document.getElementById((player['y'] + dy) * 20 + player['x'] + dx).style.backgroundColor = color_empty;
    }

    // Set color of new player position to player['color'].
    document.getElementById(player['y'] * 20 + player['x']).style.backgroundColor = player['color'];
}

function repo_escape(){
    stop();
}

function repo_init(){
    core_repo_init({
      'audios': {
        'boop': {
          'duration': .1,
        },
      },
      'keybinds': {
        65: {
          'todo': function(){
              if(player['movement_direction'] !== 1 || core_storage_data['turn-angle'] == 1){
                  player['movement_direction'] = 3;
              }
          },
        },
        68: {
          'todo': function(){
              if(player['movement_direction'] !== 3 || core_storage_data['turn-angle'] == 1){
                  player['movement_direction'] = 1;
              }
          },
        },
        72: {
          'todo': function(){
              stop();
              start();
          },
        },
        83: {
          'todo': function(){
              if(player['movement_direction'] !== 0 || core_storage_data['turn-angle'] == 1){
                  player['movement_direction'] = 2;
              }
          },
        },
        87: {
          'todo': function(){
              if(player['movement_direction'] !== 2 || core_storage_data['turn-angle'] == 1){
                  player['movement_direction'] = 0;
              }
          },
        },
      },
      'storage': {
        'game-mode': 0,
        'holes-at-start': 0,
        'holes-per-point': 1,
        'max': 0,
        'ms-per-move': 125,
        'oncollision': 1,
        'turn-angle': 0,
        'wrap': 0,
        'y-margin': 0,
      },
      'storage-menu': '

<input id=holes-at-start>Holes at Start
<input id=holes-per-point>Holes/Point
<input id=max>Max <select id=game-mode><option value=1>Frames</option><option value=0>Points</option></select>
<input id=ms-per-move>ms/Move
<select id=oncollision><option value=0>Nothing</option><option value=1>End Game</option><option value=2>Score-1</option></select>OnCollision
<select id=turn-angle><option value=0>90</option><option value=1><=180</option></select>° Turn Angle
<select id=wrap><option value=0>No</option><option value=1>X</option><option value=2>X&Y</option><option value=3>Y</option></select>Wrap
<input id=y-margin>Y Margin
',
      'title': 'Snakish.htm',
    });

    // Set margin-top of game-div based on y-margin.
    document.getElementById('game-div').style.marginTop = core_storage_data['y-margin'] + 'px';

    // Create buttons for game-div.
    var output = '';

    for(var loop_counter = 0; loop_counter < 400; loop_counter++){
        if(loop_counter % 20 === 0 && loop_counter !== 0){
            output += '
';
        }

        var color = color_empty;
        if(loop_counter == 21){
            color = player['color'];

        }else if(loop_counter == 378){
            color = color_purple;
        }

        output +=
          '<input class=gridbutton disabled id=' + loop_counter
          + ' style="background:' + color
          + '" type=button>';
    }
    document.getElementById('game-div').innerHTML = output;

    stop();

    document.getElementById('start-button').onclick = start;
}

function start(){
    core_storage_save();

    // Set margin-top of game-div based on y-margin.
    document.getElementById('game-div').style.marginTop = core_storage_data['y-margin'] + 'px';

    // Reset buttons to empty with player and purple creature in initial positions.
    var loop_counter = 399;
    do{
        document.getElementById(loop_counter).style.backgroundColor = color_empty;
    }while(loop_counter--);
    document.getElementById(21).style.backgroundColor = player['color'];
    document.getElementById(378).style.backgroundColor = color_purple;

    document.getElementById('start-button').value = 'End [ESC]';
    document.getElementById('start-button').onclick = stop;
    document.getElementById('score').innerHTML = '0';

    // Reset player
    player['movement_direction'] = 1; // 0==Up, 1==Right, 2==Down, 3==Left
    player['x'] = 1;
    player['y'] = 1;

    // Create initial holes, if any.
    if(core_storage_data['holes-at-start'] > 0){
        var id = -1;
        loop_counter = core_storage_data['holes-at-start'] - 1;
        do{
            do{
                id = core_random_integer({
                  'max': 400,
                });
            }while(document.getElementById(id).style.backgroundColor !== color_empty);
            document.getElementById(id).style.backgroundColor = color_obstacle;
        }while(loop_counter--);
    }

    // Setup display or not display of max frames or max points.
    if(core_storage_data['game-mode'] === 1){
        document.getElementById('frames').innerHTML = core_storage_data['max'];
        document.getElementById('frames-max').innerHTML = core_storage_data['max'];
        document.getElementById('score-max').innerHTML = '';
        document.getElementById('frames-max-span').style.display =
          document.getElementById('max').value > 0
            ? 'inline'
            : 'none';

    }else{
        document.getElementById('frames').innerHTML = 0;
        document.getElementById('frames-max-span').style.display = 'none';
        document.getElementById('score-max').innerHTML = core_storage_data['max'] > 0
          ? ' / ' + core_storage_data['max']
          : '';
    }

    // Validate milliseconds per player movement and create interval.
    interval = window.setInterval(
      move_player,
      core_storage_data['ms-per-move'] > 0
        ? core_storage_data['ms-per-move']
        : 125
    );
}

function stop(){
    window.clearInterval(interval);
    document.getElementById('start-button').value = 'Start [H]';
    document.getElementById('start-button').onclick = start;
}

var color_empty = 'rgb(42, 42, 42)';
var color_obstacle = 'rgb(0, 0, 0)';
var color_purple = 'rgb(102, 51, 102)';
var interval = 0;
var player = {
  'color': 'rgb(32, 102, 32)',
  'movement_direction': 1,// 0==Up, 1==Right, 2==Down, 3==Left
  'x': 1,
  'y': 1,
};
<commit_msg>removed y-margin, improved formatting<commit_after>'use strict';

function eat_purple_creature(){
    core_audio_start({
      'id': 'boop',
    });

    document.getElementById('score').innerHTML = parseInt(
      document.getElementById('score').innerHTML,
      10
    ) + 1;

    // If there is no space available for more holes, stop.
    var holes_per_point = core_storage_data['holes-per-point'];
    if(document.getElementById('score').innerHTML >=
      Math.floor(398 / (parseInt(holes_per_point, 10) + 1)) + 1){
        stop();
        return;
    }

    // Pick a button with color_empty and make it the new purple creature.
    var id = -1;
    do{
        id = core_random_integer({
          'max': 400,
        });
    }while(document.getElementById(id).style.backgroundColor != color_empty);
    document.getElementById(id).style.backgroundColor = color_purple;

    var loop_counter = holes_per_point - 1;
    // If more than 0 holes should be created.
    if(loop_counter >= 0){
        // Add new holes.
        do{
            while(document.getElementById(id).style.backgroundColor != color_empty){
                id = core_random_integer({
                  'max': 400,
                });
            }
            document.getElementById(id).style.backgroundColor = color_obstacle;
        }while(loop_counter--);
    }
}

function move_player(){
    // Check if game is still running, based on game mode and if frames/score are over max.
    var frames = parseFloat(document.getElementById('frames').innerHTML);
    var end_game = core_storage_data['game-mode'] === 1
      ? frames <= 0
        && core_storage_data['max'] > 0
      : core_storage_data['max'] != 0
        && parseInt(document.getElementById('score').innerHTML, 10) >= core_storage_data['max'];

    // If game is not running, stop().
    if(end_game){
        stop();
        return;
    }

    // Add or subtract 1 from frames depending on game mode.
    document.getElementById('frames').innerHTML = (frames +
        ((core_storage_data['game-mode'] === 1
      && core_storage_data['max'] > 0) ? -1 : 1));

    var check_color = 0;
    var dx = 0;
    var dy = 0;

    // If player is moving up.
    if(player['movement_direction'] === 0){
        // If player is not at the top of the screen.
        if(player['y'] - 1 >= 0){
            // Fetch color of space directly above the player.
            check_color = document.getElementById((player['y'] - 1) * 20 + player['x']).style.backgroundColor;

            // If the space is not an obstacle continue, else collision.
            if(check_color !== color_obstacle){
                // If color of space is purple, eat the creature.
                if(check_color === color_purple){
                    eat_purple_creature();
                }

                // Decrease player Y position.
                player['y'] -= 1;
                dy += 1;

            // Collision!
            }else{
                end_game = true;
            }

        // If player is at the top of the screen and can wrap in the Y-direction.
        }else if(core_storage_data['wrap'] == 2
          || core_storage_data['wrap'] == 3){
            // Fetch color of space at the bottom of the screen.
            check_color = document.getElementById((player['y'] + 19) * 20 + player['x']).style.backgroundColor;

            // If the space is not an obstacle continue.
            if(check_color !== color_obstacle){
                // If color of space is purple, eat the creature.
                if(check_color === color_purple){
                    eat_purple_creature()
                }

                // Set player Y position to bottom of the screen.
                player['y'] = 19;
                dy -= 19;

            // Collision!
            }else{
                end_game = true;
            }

        // Collision!
        }else{
            end_game = true;
        }

    // If player is moving right.
    }else if(player['movement_direction'] === 1){
        // If player is not at the right edge of the screen.
        if(player['x'] + 1 <= 19){
            // Fetch color of space to the right of the player.
            check_color = document.getElementById(player['y'] * 20 + player['x'] + 1).style.backgroundColor;

            // If the space is not an obstacle continue.
            if(check_color !== color_obstacle){
                // If color of space is purple, eat the creature.
                if(check_color === color_purple){
                    eat_purple_creature();
                }

                // Increase player X position.
                player['x'] += 1;
                dx -= 1;

            // Collision!
            }else{
                end_game = true;
            }

        // If player is at the right edge of the screen and can wrap in the X-direction.
        }else if(core_storage_data['wrap'] == 1
          || core_storage_data['wrap'] == 2){
            // Fetch color of space at the left of the screen.
            check_color = document.getElementById(player['y'] * 20 + player['x'] - 19).style.backgroundColor;

            // If the space is not an obstacle continue.
            if(check_color !== color_obstacle){
                // If color of space is purple, eat the creature.
                if(check_color === color_purple){
                    eat_purple_creature();
                }

                // Set player X position to left side of the screen.
                player['x'] -= 19;
                dx += 19;

            // Collision!
            }else{
                end_game = true;
            }

        // Collision!
        }else{
            end_game = true;
        }

    // If player is moving down.
    }else if(player['movement_direction'] === 2){
        // If player is not at the bottom of the screen.
        if(player['y'] + 1 <= 19){
            // Fetch color of space directory below the player.
            check_color = document.getElementById((player['y'] + 1) * 20 + player['x']).style.backgroundColor;

            // If the space is not an obstacle continue.
            if(check_color !== color_obstacle){
                // If color of space is purple, eat the creature.
                if(check_color === color_purple){
                    eat_purple_creature();
                }

                // Increase player Y position.
                player['y'] += 1;
                dy -= 1;

            // Collision!
            }else{
                end_game = true;
            }

        // If player is at the bottom edge of the screen and can wrap in the U-direction.
        }else if(core_storage_data['wrap'] == 2
          || core_storage_data['wrap'] == 3){
            // Fetch color of space at the top of the screen.
            check_color = document.getElementById((player['y'] - 19) * 20 + player['x']).style.backgroundColor;

            // If the space is not an obstacle continue.
            if(check_color !== color_obstacle){
                // If color of space is purple, eat the creature.
                if(check_color === color_purple){
                    eat_purple_creature();
                }

                // Set player Y position to top of the screen.
                player['y'] = 0;
                dy += 19;

            // Collision!
            }else{
                end_game = true;
            }

        // Collision!
        }else{
            end_game = true;
        }

    // If player is moving left.
    }else if(player['movement_direction'] === 3){
        if(player['x'] - 1 >= 0){
            // Fetch color of space to the left of the player.
            check_color = document.getElementById(player['y'] * 20 + player['x'] - 1).style.backgroundColor;

            // If the space is not an obstacle continue.
            if(check_color !== color_obstacle){
                // If color of space is purple, eat the creature.
                if(check_color === color_purple){
                    eat_purple_creature();
                }

                // Decrease player x position.
                player['x'] -= 1;
                dx += 1;

            // Collision!
            }else{
                end_game = true;
            }

        // If player is at the left edge of the screen and can wrap in the X-direction.
        }else if(core_storage_data['wrap'] == 1
          || core_storage_data['wrap'] == 2){
            // Fetch color of space at the right side of the screen.
            check_color = document.getElementById(player['y'] * 20 + player['x'] + 19).style.backgroundColor;

            // If the space is not an obstacle continue.
            if(check_color !== color_obstacle){
                // If color of space is purple, eat the creature.
                if(check_color === color_purple){
                    eat_purple_creature();
                }

                // Set player x position to right side of the screen.
                player['x'] += 19;
                dx -= 19;

            // Collision!
            }else{
                end_game = true;
            }

        // Collision!
        }else{
            end_game = true;
        }
    }

    // If a collision with an obstacle or edge was detected.
    if(end_game){
        // If game ends oncollision...
        if(core_storage_data['oncollision'] == 1){
            stop();

        // ...else if score decreases.
        }else if(core_storage_data['oncollision'] === 2){
            document.getElementById('score').innerHTML =
              parseInt(
                document.getElementById('score').innerHTML,
                10
              ) - 1;
        }
    }

    // If player x or y position has changed.
    if(dx !== 0
      || dy !== 0){
        // Reset old player position to color_empty.
        document.getElementById((player['y'] + dy) * 20 + player['x'] + dx).style.backgroundColor = color_empty;
    }

    // Set color of new player position to player['color'].
    document.getElementById(player['y'] * 20 + player['x']).style.backgroundColor = player['color'];
}

function repo_escape(){
    stop();
}

function repo_init(){
    core_repo_init({
      'audios': {
        'boop': {
          'duration': .1,
        },
      },
      'keybinds': {
        65: {
          'todo': function(){
              if(player['movement_direction'] !== 1 || core_storage_data['turn-angle'] == 1){
                  player['movement_direction'] = 3;
              }
          },
        },
        68: {
          'todo': function(){
              if(player['movement_direction'] !== 3 || core_storage_data['turn-angle'] == 1){
                  player['movement_direction'] = 1;
              }
          },
        },
        72: {
          'todo': function(){
              stop();
              start();
          },
        },
        83: {
          'todo': function(){
              if(player['movement_direction'] !== 0 || core_storage_data['turn-angle'] == 1){
                  player['movement_direction'] = 2;
              }
          },
        },
        87: {
          'todo': function(){
              if(player['movement_direction'] !== 2 || core_storage_data['turn-angle'] == 1){
                  player['movement_direction'] = 0;
              }
          },
        },
      },
      'storage': {
        'game-mode': 0,
        'holes-at-start': 0,
        'holes-per-point': 1,
        'max': 0,
        'ms-per-move': 125,
        'oncollision': 1,
        'turn-angle': 0,
        'wrap': 0,
      },
      'storage-menu': '

<input id=holes-at-start>Holes at Start
<input id=holes-per-point>Holes/Point
<input id=max>Max <select id=game-mode><option value=1>Frames</option><option value=0>Points</option></select>
<input id=ms-per-move>ms/Move
<select id=oncollision><option value=1>End Game</option><option value=0>Nothing</option><option value=2>Score-1</option></select>OnCollision
<select id=turn-angle><option value=0>90</option><option value=1><=180</option></select>° Turn Angle
<select id=wrap><option value=0>No</option><option value=1>X</option><option value=2>X&Y</option><option value=3>Y</option></select>Wrap
',
      'title': 'Snakish.htm',
    });

    // Create buttons for game-div.
    var output = '';

    for(var loop_counter = 0; loop_counter < 400; loop_counter++){
        if(loop_counter % 20 === 0 && loop_counter !== 0){
            output += '
';
        }

        var color = color_empty;
        if(loop_counter == 21){
            color = player['color'];

        }else if(loop_counter == 378){
            color = color_purple;
        }

        output +=
          '<input class=gridbutton disabled id=' + loop_counter
          + ' style="background:' + color
          + '" type=button>';
    }
    document.getElementById('game-div').innerHTML = output;

    stop();

    document.getElementById('start-button').onclick = start;
}

function start(){
    core_storage_save();

    // Reset buttons to empty with player and purple creature in initial positions.
    var loop_counter = 399;
    do{
        document.getElementById(loop_counter).style.backgroundColor = color_empty;
    }while(loop_counter--);
    document.getElementById(21).style.backgroundColor = player['color'];
    document.getElementById(378).style.backgroundColor = color_purple;

    document.getElementById('start-button').value = 'End [ESC]';
    document.getElementById('start-button').onclick = stop;
    document.getElementById('score').innerHTML = '0';

    // Reset player
    player['movement_direction'] = 1; // 0==Up, 1==Right, 2==Down, 3==Left
    player['x'] = 1;
    player['y'] = 1;

    // Create initial holes, if any.
    if(core_storage_data['holes-at-start'] > 0){
        var id = -1;
        loop_counter = core_storage_data['holes-at-start'] - 1;
        do{
            do{
                id = core_random_integer({
                  'max': 400,
                });
            }while(document.getElementById(id).style.backgroundColor !== color_empty);
            document.getElementById(id).style.backgroundColor = color_obstacle;
        }while(loop_counter--);
    }

    // Setup display or not display of max frames or max points.
    if(core_storage_data['game-mode'] === 1){
        document.getElementById('frames').innerHTML = core_storage_data['max'];
        document.getElementById('frames-max').innerHTML = core_storage_data['max'];
        document.getElementById('score-max').innerHTML = '';
        document.getElementById('frames-max-span').style.display =
          document.getElementById('max').value > 0
            ? 'inline'
            : 'none';

    }else{
        document.getElementById('frames').innerHTML = 0;
        document.getElementById('frames-max-span').style.display = 'none';
        document.getElementById('score-max').innerHTML = core_storage_data['max'] > 0
          ? ' / ' + core_storage_data['max']
          : '';
    }

    // Validate milliseconds per player movement and create interval.
    interval = window.setInterval(
      move_player,
      core_storage_data['ms-per-move'] > 0
        ? core_storage_data['ms-per-move']
        : 125
    );
}

function stop(){
    window.clearInterval(interval);
    document.getElementById('start-button').value = 'Start [H]';
    document.getElementById('start-button').onclick = start;
}

var color_empty = 'rgb(42, 42, 42)';
var color_obstacle = 'rgb(0, 0, 0)';
var color_purple = 'rgb(102, 51, 102)';
var interval = 0;
var player = {
  'color': 'rgb(32, 102, 32)',
  'movement_direction': 1,// 0==Up, 1==Right, 2==Down, 3==Left
  'x': 1,
  'y': 1,
};
<|endoftext|>


<commit_before>
module.exports = function(RED) {
    function Roster(config) {
        RED.nodes.createNode(this,config);
        function objarray(obj){
            keys = Object.keys(obj);
            res = [];
            for(var k = 0; k<keys.length; k++) {
                res.push(obj[keys[k]]);
            }
            return res;
        }
		this.indexProperty = config.indexProperty;
		this.timeout = config.timeout;
        var node = this;
        var roster  = {};
        this.on('input', function(msg) {
			var newEntry = true;
			var payload = JSON.parse(msg.payload);
			payload.rosterTimestamp = new Date();
			console.log("ROS: ", payload, roster)
			//Check for valid message
			if(!payload[node.indexProperty]) {
				node.error("Missing property " + node.indexProperty + " in incoming message", msg);
				return;
			}
			// Have we already registered this entry?
			if (roster[payload[node.indexProperty]]) {
				newEntry = false;
			}
            roster[payload[this.indexProperty]] = payload;

			// Only send roster if it has changed.
			if(newEntry == true) {
	            node.send({payload: JSON.stringify(objarray(roster)) });
			}
        });
		setInterval(function(){
			var entryDeleted = false;
			for(var propertyName in roster) {
				var entry = roster[propertyName];
				var outputRoster = [];
				var now = new Date();
				var idle = (now-entry.rosterTimestamp)/1000;
				if(entry.rosterTimestamp>0 && (idle > node.timeout)) {
					delete roster[propertyName];
					entryDeleted = true;
				}
				outputRoster.push[roster[propertyName]];
			}
			// Only send roster if it has changed.
			if(entryDeleted == true) {
	            node.send({payload: JSON.stringify(objarray(outputRoster)) });
			}
		}, 1000)
    }
    RED.nodes.registerType("roster",Roster);
}
<commit_msg>FIXES for deletion. Mark active/inactive rather than delete<commit_after>
module.exports = function(RED) {
    function Roster(config) {
        RED.nodes.createNode(this,config);
        function objarray(obj){
            keys = Object.keys(obj);
            res = [];
            for(var k = 0; k<keys.length; k++) {
                res.push(obj[keys[k]]);
            }
            return res;
        }
		this.indexProperty = config.indexProperty;
		this.timeout = config.timeout;
        var node = this;
        console.log("TJIS ", this)
        this.roster = {};

        this.on('input', function(msg) {
			var newEntry = true;
			var payload = JSON.parse(msg.payload);
			payload.rosterTimestamp = new Date();
            payload.rosterStatus = "active";
			//console.log("ROS: ", payload, roster)
			//Check for valid message
			if(!payload[node.indexProperty]) {
				node.error("Missing property " + node.indexProperty + " in incoming message", msg);
				return;
			}
			// Have we already registered this entry?
			if (this.roster[payload[node.indexProperty]]) {
				newEntry = false;
			}
            this.roster[payload[this.indexProperty]] = payload;

			// Only send roster if it has changed.
			if(newEntry == true) {
	            node.send({payload: JSON.stringify(objarray(this.roster)) });
			}
        });
        function checkEntries(){
        			var entryDeleted = false;
        			for(var propertyName in this.roster) {
        				var entry = this.roster[propertyName];
        				var now = new Date();
        				var idle = (now-entry.rosterTimestamp)/1000;
                        //node.log("SI: ", entry, idle, propertyName)
        				if(entry.rosterTimestamp>0 && (idle > node.timeout)) {
        					//delete this.roster[propertyName];
                            this.roster[propertyName].rosterStatus = "inactive";
                            console.log("DELETED ", propertyName)
        					entryDeleted = true;
        				}
        				//this.roster.push[this.roster[propertyName]];
        			}
        			// Only send roster if it has changed.
        			if(entryDeleted == true) {
        	            node.send({payload: JSON.stringify(objarray(this.roster)) });
        			}
        		}
		setInterval(checkEntries.bind(this), 1000)
    }
    RED.nodes.registerType("roster",Roster);
}
<|endoftext|>


<commit_before>var IMAGE_URLS = {
  CONDOM: "images/igmikc-map-icon-condom.png",
  EVENT: "images/igmikc-map-icon-event.png",
  TREATMENT: "images/igmikc-map-icon-treatment.png"
};
var DEFAULT_MAP_CENTER = {
  LAT: 39.0397266,
  LNG: -94.5785667
};
var POINT_TYPE = {
  CONDOM: 'condom',
  EVENT: 'event',
  TREATMENT: 'treatment'
};
var map;

function mobileAndTabletcheck() {
  var check = false;
  (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera);
  return check;
}
function showMap (center) {
  map = new google.maps.Map(document.getElementById('googleMap'), {
    center:center,
    zoom:11,
    scrollwheel:false,
    draggable:true,
    mapTypeId:google.maps.MapTypeId.ROADMAP
  });

  // Create a