<commit_before>"use strict";

var gSightings = null;
var gOmittedCommonNames = [];
var gCustomDayNames = [];
var gPhotos = [];
var gCompiledTemplates = {};
var gCountyByLocation = {};

function renderTemplate(inPrefix, inData) {
	var compiledTemplate = ebirdmybird[inPrefix];
	var newDiv = document.createElement("div");
	newDiv.innerHTML = compiledTemplate(inData);

	var results = document.getElementById(inPrefix + '-results');
	while (results.firstChild) {
	    results.removeChild(results.firstChild);
	}

    // hide loading section
	document.getElementById('loading').classList.remove('visible');
	document.getElementById('loading').classList.add('hidden');

	hideAllSections();

	// show rendered template
    results.appendChild(newDiv);
	showSection('section#' + inPrefix);
}

function showSection(inSelector) {
	var sections = document.querySelectorAll(inSelector);
	for (var index = 0; index < sections.length; index++) {
		sections[index].classList.remove('hidden');
		sections[index].classList.add('visible');
	}
}

function hideAllSections() {
	var sections = document.querySelectorAll('section.card');
	for (var index = 0; index < sections.length; index++) {
		sections[index].classList.remove('visible');
		sections[index].classList.add('hidden');
	}
}

function barGraphCountsForSightings(inData, inElement) {
	var labels = Object.keys(inData).map(function(k){return k;});
	var values = Object.keys(inData).map(function(k){return inData[k].length;});
	var values2 = Object.keys(inData).map(function(k){return new SightingList(inData[k]).getUniqueValues('Common Name').length;});
	var values3 = Object.keys(inData).map(function(k){return new SightingList(inData[k]).locations.length;});

	labels.unshift('x');
	values.unshift('sightings');
	values2.unshift('species');
	values3.unshift('locations');

	var chart = c3.generate({
		bindto: d3.select(inElement),
		axis: {
			y: {
				show: false
			}
		},
		data: {
			x: 'x',
			columns: [
				values,
				values2,
				values3,
				labels,
			],
			types: {
				sightings: 'line',
				species: 'line',
				locations: 'line'
			},
			onclick: function(d, element) {
				window.location.hash = '#year/' + d.x;
			}
		}
	});
}

function byMonthForSightings(inData, inElement) {
	var labels = ['x', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
	var values = inData.map(function(a){return a.length;});

	values.unshift('sightings');

	var chart = c3.generate({
		bindto: d3.select(inElement),
		size: {
			width: 400,
			height: 150
		},
		bar: {
			width: {
				ratio: 1.0
			}
		},
		axis: {
			x: {
				type: 'category'
			},
			y: {
				show: false
			}
		},
		legend: {
			show: false
		},
		data: {
			x: 'x',
			columns: [
				values,
				labels
			],
			types: {
				sightings: 'bar'
			}
		}
	});
}

function renderHome() {
	renderTemplate('home', {
		numSightings: gSightings.count(),
		sightingsByYear: gSightings.byYear(),
		sightingsByMonth: gSightings.byMonth(),
		yearChartID: 'byYear' + Date.now(),
		monthChartID: 'byMonth' + Date.now(),
		numChecklists: gSightings.checklists.length,
		earliest: gSightings.earliestDateObject,
		latest: gSightings.latestDateObject,
		owner: 'Bill Walker'
	});
}

function renderChrono() {
	var earliestByCommonName = gSightings.earliestByCommonName();
	var lifeSightingsChronological = Object.keys(earliestByCommonName).map(function(k){return earliestByCommonName[k]});
	lifeSightingsChronological.sort(function(a, b) { return a['DateObject'] - b['DateObject']; });

	renderTemplate('chrono', {
		firstSightings: lifeSightingsChronological
	});
}

function renderTrips() {
	renderTemplate('trips', {
		trips: gSightings.dateObjects,
		customDayNames: gCustomDayNames
	});
}

function renderTrip(inDate) {
	var tripSightings = gSightings.filter(function(s) { return s['Date'] == inDate; });
	var tripSightingList = new SightingList(tripSightings);

	renderTemplate('trip', {
		tripDate: tripSightings[0].DateObject,
		photos: gPhotos.filter(function(p){return p.tripDate == inDate;}),
		customName: gCustomDayNames[inDate],
		comments: tripSightingList.getUniqueValues('Checklist Comments'),
		taxons: tripSightingList.getUniqueValues("Common Name"),
		sightingList: tripSightingList
	});
}

function renderYear(inYear) {
	var yearSightings = gSightings.byYear()[inYear];
	yearSightings.sort(function(a, b) { return a['Taxonomic Order'] - b['Taxonomic Order']; });
	var yearSightingList = new SightingList(yearSightings);

	renderTemplate('year', {
		year: inYear,
		photos: gPhotos.filter(function(p){return p.date.substring(0,4) == inYear;}),
		yearSightings: yearSightings,
		yearSpecies: yearSightingList.getUniqueValues('Common Name')
	});
}

function renderLocations() {
	renderTemplate('locations', {
		locations: gSightings.locations
	});
}

function renderLocation(inLocationName) {
	var locationSightingsTaxonomic = gSightings.filter(function(s) { return s['Location'] == inLocationName; });
	locationSightingsTaxonomic.sort(function(a, b) { return a['Taxonomic Order'] - b['Taxonomic Order']; });

	var locationSightingList = new SightingList(locationSightingsTaxonomic);

	renderTemplate('location', {
		name: inLocationName,
		chartID: 'bymonth' + Date.now(),
		sightingsByMonth: locationSightingList.byMonth(),
		photos: gPhotos.filter(function(p) { return p.location == inLocationName }),
		county: locationSightingsTaxonomic[0]["County"],
		state: locationSightingsTaxonomic[0]["State/Province"],
		locationSightingsTaxonomic: locationSightingsTaxonomic,
		longitude: locationSightingsTaxonomic[0]["Longitude"],
		latitude: locationSightingsTaxonomic[0]["Latitude"],
		sightingList: locationSightingList,
		taxons: locationSightingList.getUniqueValues("Common Name"),
		customDayNames: gCustomDayNames
	});
}

function renderCounty(inCountyName) {
	var countySightingsTaxonomic = gSightings.filter(function(s) { return s['County'] == inCountyName; });
	countySightingsTaxonomic.sort(function(a, b) { return a['Taxonomic Order'] - b['Taxonomic Order']; });

	var countySightingList = new SightingList(countySightingsTaxonomic);

	renderTemplate('county', {
		name: inCountyName,
		chartID: 'bymonth' + Date.now(),
		sightingsByMonth: countySightingList.byMonth(),
		photos: gPhotos.filter(function(p) { return countySightingList.locations.indexOf(p.location) >= 0; }),
		state: countySightingsTaxonomic[0]["State/Province"],
		sightingList: countySightingList,
		countySightingsTaxonomic: countySightingsTaxonomic,
		taxons: countySightingList.getUniqueValues("Common Name"),
		customDayNames: gCustomDayNames
	});
}

function renderTaxons() {
	var earliestByCommonName = gSightings.earliestByCommonName();
	var lifeSightingsTaxonomic = Object.keys(earliestByCommonName).map(function(k){return earliestByCommonName[k]});
	lifeSightingsTaxonomic.sort(function(a, b) { return a['Taxonomic Order'] - b['Taxonomic Order']; });

	renderTemplate('taxons', {
		lifeSightings: lifeSightingsTaxonomic
	});
}

function renderTaxon(inCommonName) {
	var taxonSightings = gSightings.filter(function(s) { return s['Common Name'] == inCommonName; });
	taxonSightings.sort(function(a, b) { return a['DateObject'] - b['DateObject']; });

	var taxonSightingsList = new SightingList(taxonSightings);

	var scientificName = taxonSightings[0]["Scientific Name"];

	renderTemplate('taxon', {
		name: inCommonName,
		photos: gPhotos.filter(function(p){return p.scientificName == scientificName;}),
		scientificName: scientificName,
		sightingsByMonth: taxonSightingsList.byMonth(),
		sightings: taxonSightings,
		chartID: 'bymonth' + Date.now()
	});
}

function renderDebug() {
	var tmp = gSightings.filter(function(s) { return s["Location"] && s["Location"].indexOf('/') >= 0; })
	var brokenLocationSightingList = new SightingList(tmp);

	// TODO: find photos whose scientific name is missing from sightings

	renderTemplate('debug', {
		photosMissingTrip: gPhotos.filter(function(p) { return gSightings.dates.indexOf(p.tripDate) < 0; }),
		photosMissingLocation: gPhotos.filter(function(p) { return gSightings.locations.indexOf(p.location) < 0; }),
		photos: gPhotos,
		brokenLocations: brokenLocationSightingList.getUniqueValues("Location")
	});
}

var routingMap = {
	'#home' : renderHome,
	'#chrono' : renderChrono,
	'#trips' : renderTrips,
	'#trip' : renderTrip,
	'#year' : renderYear,
	'#locations' : renderLocations,
	'#location' : renderLocation,
	'#county' : renderCounty,
	'#taxons' : renderTaxons,
	'#taxon' : renderTaxon,
	'#debug' : renderDebug
}

function routeBasedOnHash() {
	// show loading section
	document.getElementById('loading').classList.add('visible');
	document.getElementById('loading').classList.remove('hidden');

	// On every hash change the render function is called with the new hash.
	// This is how the navigation of our app happens.
	var theHashParts = window.location.hash.split('/');
	console.log('changed', theHashParts[0], theHashParts[1]);

	if (! theHashParts[0]) {
		// TODO: should use push state
		theHashParts[0] = '#home';
	}

	if(routingMap[theHashParts[0]]) {
		routingMap[theHashParts[0]](decodeURI(theHashParts[1]));
	} else {
		console.log('not found', window.location.hash);
	}
}

function loadCustomDayNames() {
	var oReq = new XMLHttpRequest();
	oReq.addEventListener("load", function() {
	  gCustomDayNames = JSON.parse(this.responseText);
	  console.log('loaded custom day names', Object.keys(gCustomDayNames).length);
	});
	oReq.open("GET", "./data/day-names.json");
	oReq.send();
}

function loadOmittedCommonNames() {
	var oReq = new XMLHttpRequest();
	oReq.addEventListener("load", function() {
	  gOmittedCommonNames = JSON.parse(this.responseText);
	  console.log('loaded omitted common names', gOmittedCommonNames.length);
	});
	oReq.open("GET", "./data/omitted-common-names.json");
	oReq.send();
}

function loadPhotos() {
	var oReq = new XMLHttpRequest();
	oReq.addEventListener("load", function() {
		gPhotos = JSON.parse(this.responseText);
		console.log('loaded photos', gPhotos.length);

		for (var index = 0; index < gPhotos.length; index++) {
			var imageFilename = '';
			var photo = gPhotos[index];
			if (photo.abbreviation == 'NULL') {
				imageFilename = photo.date + '-' + photo.scientificName.replace(' ', '_').toLowerCase();
			} else {
				imageFilename = photo.date + '-' + photo.abbreviation;
			}

			if (photo.original_filename != 'NULL') {
				imageFilename = imageFilename + '-' + photo.original_filename;
			}

			gPhotos[index].photoURL = 'http://birdwalker.com/images/photo/' + imageFilename + '.jpg';
			gPhotos[index].thumbURL = 'http://birdwalker.com/images/thumb/' + imageFilename + '.jpg';
			var tmp = photo.date.split('-');
			gPhotos[index].tripDate = [tmp[1], tmp[2], tmp[0]].join('-');
		}
	});
	oReq.open("GET", "./data/photos.json");
	oReq.send();
}

// REDIRECT to HTTPS!
var host = "wfwalker.github.io";
if ((host == window.location.host) && (window.location.protocol != "https:")) {
	window.location.protocol = "https";
} else {
	document.addEventListener("DOMContentLoaded", function(event) {
		console.log('start DOMContentLoaded');

		Handlebars.registerHelper('nicedate', function(inDate) {
			return new Handlebars.SafeString (
				d3.time.format("%b %d, %Y")(inDate)
			);
		});

		Handlebars.registerHelper('ebirddate', function(inDate) {
			return new Handlebars.SafeString (
				d3.time.format("%m-%d-%Y")(inDate)
			);
		});

		Handlebars.registerHelper('nicenumber', function(inNumber) {
			return new Handlebars.SafeString (
				d3.format(",d")(inNumber)
			);
		});

		Handlebars.registerHelper('bargraph', function(inData, inElement) {
			// per @digitarald use timeout to reorder helper after Handlebars templating
			window.setTimeout(function () { barGraphCountsForSightings(inData, '#' + inElement); }, 1);
		});

		Handlebars.registerHelper('monthgraph', function(inData, inElement) {
			// per @digitarald use timeout to reorder helper after Handlebars templating
			window.setTimeout(function () { byMonthForSightings(inData, '#' + inElement); }, 1);
		});

		console.log('end DOMContentLoaded');
	});

	Papa.parse('./data/ebird.csv', {
		download: true,
		header: true,
		complete: function(results) {
			gSightings = new SightingList(results.data);
			routeBasedOnHash();
		},
	});

	window.onhashchange = routeBasedOnHash;

	loadCustomDayNames();
	loadOmittedCommonNames();
	loadPhotos();
}

<commit_msg>fix lint errors<commit_after>'use strict';

var gSightings = null;
var gOmittedCommonNames = [];
var gCustomDayNames = [];
var gPhotos = [];
var gCompiledTemplates = {};
var gCountyByLocation = {};

function renderTemplate(inPrefix, inData) {
	var compiledTemplate = ebirdmybird[inPrefix];
	var newDiv = document.createElement('div');
	newDiv.innerHTML = compiledTemplate(inData);

	var results = document.getElementById(inPrefix + '-results');
	while (results.firstChild) {
	    results.removeChild(results.firstChild);
	}

    // hide loading section
	document.getElementById('loading').classList.remove('visible');
	document.getElementById('loading').classList.add('hidden');

	hideAllSections();

	// show rendered template
    results.appendChild(newDiv);
	showSection('section#' + inPrefix);
}

function showSection(inSelector) {
	var sections = document.querySelectorAll(inSelector);
	for (var index = 0; index < sections.length; index++) {
		sections[index].classList.remove('hidden');
		sections[index].classList.add('visible');
	}
}

function hideAllSections() {
	var sections = document.querySelectorAll('section.card');
	for (var index = 0; index < sections.length; index++) {
		sections[index].classList.remove('visible');
		sections[index].classList.add('hidden');
	}
}

function barGraphCountsForSightings(inData, inElement) {
	var labels = Object.keys(inData).map(function(k){return k;});
	var values = Object.keys(inData).map(function(k){return inData[k].length;});
	var values2 = Object.keys(inData).map(function(k){return new SightingList(inData[k]).getUniqueValues('Common Name').length;});
	var values3 = Object.keys(inData).map(function(k){return new SightingList(inData[k]).locations.length;});

	labels.unshift('x');
	values.unshift('sightings');
	values2.unshift('species');
	values3.unshift('locations');

	var chart = c3.generate({
		bindto: d3.select(inElement),
		axis: {
			y: {
				show: false,
			},
		},
		data: {
			x: 'x',
			columns: [
				values,
				values2,
				values3,
				labels,
			],
			types: {
				sightings: 'line',
				species: 'line',
				locations: 'line',
			},
			onclick: function(d, element) {
				window.location.hash = '#year/' + d.x;
			},
		},
	});
}

function byMonthForSightings(inData, inElement) {
	var labels = ['x', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
	var values = inData.map(function(a){return a.length;});

	values.unshift('sightings');

	var chart = c3.generate({
		bindto: d3.select(inElement),
		size: {
			width: 400,
			height: 150,
		},
		bar: {
			width: {
				ratio: 1.0,
			},
		},
		axis: {
			x: {
				type: 'category',
			},
			y: {
				show: false,
			},
		},
		legend: {
			show: false,
		},
		data: {
			x: 'x',
			columns: [
				values,
				labels,
			],
			types: {
				sightings: 'bar',
			},
		},
	});
}

function renderHome() {
	renderTemplate('home', {
		numSightings: gSightings.count(),
		sightingsByYear: gSightings.byYear(),
		sightingsByMonth: gSightings.byMonth(),
		yearChartID: 'byYear' + Date.now(),
		monthChartID: 'byMonth' + Date.now(),
		numChecklists: gSightings.checklists.length,
		earliest: gSightings.earliestDateObject,
		latest: gSightings.latestDateObject,
		owner: 'Bill Walker',
	});
}

function renderChrono() {
	var earliestByCommonName = gSightings.earliestByCommonName();
	var lifeSightingsChronological = Object.keys(earliestByCommonName).map(function(k) { return earliestByCommonName[k]; });
	lifeSightingsChronological.sort(function(a, b) { return a['DateObject'] - b['DateObject']; });

	renderTemplate('chrono', {
		firstSightings: lifeSightingsChronological,
	});
}

function renderTrips() {
	renderTemplate('trips', {
		trips: gSightings.dateObjects,
		customDayNames: gCustomDayNames,
	});
}

function renderTrip(inDate) {
	var tripSightings = gSightings.filter(function(s) { return s['Date'] == inDate; });
	var tripSightingList = new SightingList(tripSightings);

	renderTemplate('trip', {
		tripDate: tripSightings[0].DateObject,
		photos: gPhotos.filter(function(p){return p.tripDate == inDate;}),
		customName: gCustomDayNames[inDate],
		comments: tripSightingList.getUniqueValues('Checklist Comments'),
		taxons: tripSightingList.getUniqueValues('Common Name'),
		sightingList: tripSightingList,
	});
}

function renderYear(inYear) {
	var yearSightings = gSightings.byYear()[inYear];
	yearSightings.sort(function(a, b) { return a['Taxonomic Order'] - b['Taxonomic Order']; });
	var yearSightingList = new SightingList(yearSightings);

	renderTemplate('year', {
		year: inYear,
		photos: gPhotos.filter(function(p){return p.date.substring(0,4) == inYear;}),
		yearSightings: yearSightings,
		yearSpecies: yearSightingList.getUniqueValues('Common Name'),
	});
}

function renderLocations() {
	renderTemplate('locations', {
		locations: gSightings.locations,
	});
}

function renderLocation(inLocationName) {
	var locationSightingsTaxonomic = gSightings.filter(function(s) { return s['Location'] == inLocationName; });
	locationSightingsTaxonomic.sort(function(a, b) { return a['Taxonomic Order'] - b['Taxonomic Order']; });

	var locationSightingList = new SightingList(locationSightingsTaxonomic);

	renderTemplate('location', {
		name: inLocationName,
		chartID: 'bymonth' + Date.now(),
		sightingsByMonth: locationSightingList.byMonth(),
		photos: gPhotos.filter(function(p) { return p.location == inLocationName; }),
		county: locationSightingsTaxonomic[0]['County'],
		state: locationSightingsTaxonomic[0]['State/Province'],
		locationSightingsTaxonomic: locationSightingsTaxonomic,
		longitude: locationSightingsTaxonomic[0]['Longitude'],
		latitude: locationSightingsTaxonomic[0]['Latitude'],
		sightingList: locationSightingList,
		taxons: locationSightingList.getUniqueValues('Common Name'),
		customDayNames: gCustomDayNames,
	});
}

function renderCounty(inCountyName) {
	var countySightingsTaxonomic = gSightings.filter(function(s) { return s['County'] == inCountyName; });
	countySightingsTaxonomic.sort(function(a, b) { return a['Taxonomic Order'] - b['Taxonomic Order']; });

	var countySightingList = new SightingList(countySightingsTaxonomic);

	renderTemplate('county', {
		name: inCountyName,
		chartID: 'bymonth' + Date.now(),
		sightingsByMonth: countySightingList.byMonth(),
		photos: gPhotos.filter(function(p) { return countySightingList.locations.indexOf(p.location) >= 0; }),
		state: countySightingsTaxonomic[0]['State/Province'],
		sightingList: countySightingList,
		countySightingsTaxonomic: countySightingsTaxonomic,
		taxons: countySightingList.getUniqueValues('Common Name'),
		customDayNames: gCustomDayNames,
	});
}

function renderTaxons() {
	var earliestByCommonName = gSightings.earliestByCommonName();
	var lifeSightingsTaxonomic = Object.keys(earliestByCommonName).map(function(k){ return earliestByCommonName[k]; });
	lifeSightingsTaxonomic.sort(function(a, b) { return a['Taxonomic Order'] - b['Taxonomic Order']; });

	renderTemplate('taxons', {
		lifeSightings: lifeSightingsTaxonomic,
	});
}

function renderTaxon(inCommonName) {
	var taxonSightings = gSightings.filter(function(s) { return s['Common Name'] == inCommonName; });
	taxonSightings.sort(function(a, b) { return a['DateObject'] - b['DateObject']; });

	var taxonSightingsList = new SightingList(taxonSightings);

	var scientificName = taxonSightings[0]['Scientific Name'];

	renderTemplate('taxon', {
		name: inCommonName,
		photos: gPhotos.filter(function(p){return p.scientificName == scientificName;}),
		scientificName: scientificName,
		sightingsByMonth: taxonSightingsList.byMonth(),
		sightings: taxonSightings,
		chartID: 'bymonth' + Date.now(),
	});
}

function renderDebug() {
	var tmp = gSightings.filter(function(s) { return s['Location'] && s['Location'].indexOf('/') >= 0; });
	var brokenLocationSightingList = new SightingList(tmp);

	// TODO: find photos whose scientific name is missing from sightings

	renderTemplate('debug', {
		photosMissingTrip: gPhotos.filter(function(p) { return gSightings.dates.indexOf(p.tripDate) < 0; }),
		photosMissingLocation: gPhotos.filter(function(p) { return gSightings.locations.indexOf(p.location) < 0; }),
		photos: gPhotos,
		brokenLocations: brokenLocationSightingList.getUniqueValues('Location'),
	});
}

var routingMap = {
	'#home' : renderHome,
	'#chrono' : renderChrono,
	'#trips' : renderTrips,
	'#trip' : renderTrip,
	'#year' : renderYear,
	'#locations' : renderLocations,
	'#location' : renderLocation,
	'#county' : renderCounty,
	'#taxons' : renderTaxons,
	'#taxon' : renderTaxon,
	'#debug' : renderDebug,
};

function routeBasedOnHash() {
	// show loading section
	document.getElementById('loading').classList.add('visible');
	document.getElementById('loading').classList.remove('hidden');

	// On every hash change the render function is called with the new hash.
	// This is how the navigation of our app happens.
	var theHashParts = window.location.hash.split('/');
	console.log('changed', theHashParts[0], theHashParts[1]);

	if (! theHashParts[0]) {
		// TODO: should use push state
		theHashParts[0] = '#home';
	}

	if(routingMap[theHashParts[0]]) {
		routingMap[theHashParts[0]](decodeURI(theHashParts[1]));
	} else {
		console.log('not found', window.location.hash);
	}
}

function loadCustomDayNames() {
	var oReq = new XMLHttpRequest();
	oReq.addEventListener('load', function() {
	  gCustomDayNames = JSON.parse(this.responseText);
	  console.log('loaded custom day names', Object.keys(gCustomDayNames).length);
	});
	oReq.open('GET', './data/day-names.json');
	oReq.send();
}

function loadOmittedCommonNames() {
	var oReq = new XMLHttpRequest();
	oReq.addEventListener('load', function() {
	  gOmittedCommonNames = JSON.parse(this.responseText);
	  console.log('loaded omitted common names', gOmittedCommonNames.length);
	});
	oReq.open('GET', './data/omitted-common-names.json');
	oReq.send();
}

function loadPhotos() {
	var oReq = new XMLHttpRequest();
	oReq.addEventListener('load', function() {
		gPhotos = JSON.parse(this.responseText);
		console.log('loaded photos', gPhotos.length);

		for (var index = 0; index < gPhotos.length; index++) {
			var imageFilename = '';
			var photo = gPhotos[index];
			if (photo.abbreviation == 'NULL') {
				imageFilename = photo.date + '-' + photo.scientificName.replace(' ', '_').toLowerCase();
			} else {
				imageFilename = photo.date + '-' + photo.abbreviation;
			}

			if (photo.original_filename != 'NULL') {
				imageFilename = imageFilename + '-' + photo.original_filename;
			}

			gPhotos[index].photoURL = 'http://birdwalker.com/images/photo/' + imageFilename + '.jpg';
			gPhotos[index].thumbURL = 'http://birdwalker.com/images/thumb/' + imageFilename + '.jpg';
			var tmp = photo.date.split('-');
			gPhotos[index].tripDate = [tmp[1], tmp[2], tmp[0]].join('-');
		}
	});
	oReq.open('GET', './data/photos.json');
	oReq.send();
}

// REDIRECT to HTTPS!
var host = 'wfwalker.github.io';
if ((host == window.location.host) && (window.location.protocol != 'https:')) {
	window.location.protocol = 'https';
} else {
	document.addEventListener('DOMContentLoaded', function(event) {
		console.log('start DOMContentLoaded');

		Handlebars.registerHelper('nicedate', function(inDate) {
			return new Handlebars.SafeString (
				d3.time.format('%b %d, %Y')(inDate)
			);
		});

		Handlebars.registerHelper('ebirddate', function(inDate) {
			return new Handlebars.SafeString (
				d3.time.format('%m-%d-%Y')(inDate)
			);
		});

		Handlebars.registerHelper('nicenumber', function(inNumber) {
			return new Handlebars.SafeString (
				d3.format(',d')(inNumber)
			);
		});

		Handlebars.registerHelper('bargraph', function(inData, inElement) {
			// per @digitarald use timeout to reorder helper after Handlebars templating
			window.setTimeout(function () { barGraphCountsForSightings(inData, '#' + inElement); }, 1);
		});

		Handlebars.registerHelper('monthgraph', function(inData, inElement) {
			// per @digitarald use timeout to reorder helper after Handlebars templating
			window.setTimeout(function () { byMonthForSightings(inData, '#' + inElement); }, 1);
		});

		console.log('end DOMContentLoaded');
	});

	Papa.parse('./data/ebird.csv', {
		download: true,
		header: true,
		complete: function(results) {
			gSightings = new SightingList(results.data);
			routeBasedOnHash();
		},
	});

	window.onhashchange = routeBasedOnHash;

	loadCustomDayNames();
	loadOmittedCommonNames();
	loadPhotos();
}

<|endoftext|>


<commit_before>/* ====================================
 *  app.js
 * ===================================== */

'use strict';

console.log('\'Allo \'Allo!');
<commit_msg>Create angular app code<commit_after>/* ====================================
 *  app.js
 * ===================================== */

'use strict';

angular.module('myUIRouterApp', [
  'ui.router',
  'home'
])
.provider('greeter', function() {
  var salutation = 'Hello';
  this.setSalutation = function(s) {
    salutation = s;
  };

  function Greeter() {
    this.greet = function(a) {
      return salutation + ' ' + a;
    };
  }

  this.$get = function() {
    return new Greeter();
  };
})
.config(function($urlRouterProvider, greeterProvider) {
  $urlRouterProvider
    .otherwise('/user/notifications');
  greeterProvider.setSalutation('Ahoy');
});
<|endoftext|>


<commit_before>if (!process.env.token) {
    console.log('Error: Specify token in environment');
    process.exit(1);
}

require('any-promise/register/q');

var Botkit = require('./lib/Botkit.js'),
    os = require('os'),
    controller = Botkit.slackbot({
        //debug: true
    }),
    bot = controller.spawn({
        token: process.env.token
    }).startRTM(),
    Q = require('q'),
    request = require('request-promise-any');

controller.setupWebserver(process.env.PORT, function(err, webserver) {
  controller.createWebhookEndpoints(controller.webserver, 'PsRh1Hn3lbVjQpYtf3UaLwKH');
});

var games = {},
    suitMappings = {'HEARTS': 'red', 'SPADES': 'green', 'CLUBS': 'yellow', 'DIAMONDS': 'blue'},
    valueMappings = {'JACK': 'Draw 2', 'QUEEN': 'Skip', 'KING': 'Reverse'};

//TODO: Allow for commands via @mentions as well

controller.hears('new', ['slash_command'/*, 'direct_mention', 'mention'*/], function(bot, message){
    //console.log(message);
    initializeGame(bot, message);
});

controller.hears('join', ['slash_command'/*, 'direct_mention', 'mention'*/], function(bot, message){
    console.log(message);
    joinGame(bot, message);
});

controller.hears('quit', ['slash_command'/*, 'direct_mention', 'mention'*/], function(bot, message){
    console.log(message);
    quitGame(bot, message);
});

controller.hears('order', ['slash_command'/*, 'direct_mention', 'mention'*/], function(bot, message){
    console.log(message);
    reportTurnOrder(bot, message, true);
});

controller.hears('setup', ['slash_command'/*, 'direct_mention', 'mention'*/], function(bot, message){
    //console.log(message);
    for (var i = 2; i <= 2; i++){
        var mockUser = 'Player' + i;

        joinGame(bot, message, mockUser);
    }
});

controller.hears('start', ['slash_command'], function(bot, message){
    //console.log(message);
    beginGame(bot, message);
});

function beginGame(bot, message){
    var user = message.user_name,
        game = getGame(bot, message);

    if (!game){
        return;
    }

    if (game.player1 !== user){
        bot.replyPrivate(message, 'Only player 1 (' + game.player1 + ') can start the game.');
        return;
    }

    if (Object.keys(game.players).length < 2){
        bot.replyPrivate(message, 'You need at least two players to begin playing.');
        return;
    }

    if (game.started){
        bot.replyPrivate(message, 'The game is already started.');
        reportTurnOrder(bot, message, true, true);
        return;
    }

    game.started = true;
    var drawRequests = [];

    bot.replyPublic(message, 'Game has started! Shuffling the deck and dealing the hands.');

    //Create the deck
    request({
                uri: 'http://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=2',
                json: true
            })
        .then(function(result){
                game.deckId = result.deck_id;
            })
        /*.then(function(){
                console.log('Deck request finished');
            })*/
        .then(function(){
                for (playerName in game.players){
                    console.log('beginning draw for ' + playerName);
                    var player = game.players[playerName];
                    var drawRequest = request({
                                uri: 'http://deckofcardsapi.com/api/deck/' + game.deckId + '/draw/?count=7',
                                json: true
                            })
                        .then(function(result){
                            console.log(result);

                            console.log(result.cards.length + ' cards returned, adding to ' + playerName + ' hand');

                            for (var j = 0; j < result.cards.length; j++){
                                player.cards.push(getUnoCard(result.cards[j]));
                            }
                        })
                        .then(function(){
                            console.log('Draw request finished');
                            console.log(player);
                        });

                    drawRequests.push(drawRequest);
                }
            })
        .then(function(){
                Q.allSettled(drawRequests).then(function(){
                    console.log('All draw requests should be finished by now.');
                    console.log(game);
                    announceTurn(bot, message);
                })
            });
}

function getUnoCard(standardCard){
    console.log('standardCard:');
    console.log(standardCard);

    var value = valueMappings[standardCard.value] || (standardCard.value - 1),
        color = suitMappings[standardCard.suit];

    if (value === 'ACE'){
        color = 'Wild';
        switch (standardCard.suit){
            case 'CLUBS':
            case 'SPADES':
                value = 'Wild';
                break;
            case 'HEARTS':
            case 'DIAMONDS':
                value = 'Draw 4';
                break;
        }
    }

    var res = {
        color: color,
        value: value
    };
    console.log('unoCard:');
    console.log(res);

    return res;
}

function getStandardCard(unoCard){

}

function announceTurn(bot, message){
    var game = getGame(bot, message);

    bot.replyPublicDelayed(message, 'It is ' + game.turnOrder[0] + '\'s turn.\nType \\uno cards, \\uno draw, \\uno skip or \\uno play.')
}

function quitGame(bot, message){
    var user = message.user_name,
        game = getGame(bot, message),
        channel = message.channel;

    if (!game.players[user]){
        bot.replyPrivate(message, 'You weren\'t playing to begin with.');
        return;
    }

    delete game.players[user];

    var player = game.turnOrder.indexOf(user);
    game.turnOrder.splice(player, 1);

    bot.replyPublic(message, user + ' has left the game.');

    if (Object.keys(game.players).length === 0){
        bot.replyPublicDelayed(message, 'No more players. Ending the game.');
        games[channel] = newGame();
        return;
    }

    if (game.player1 === user){
        game.player1 = Object.keys(game.players)[0];
        bot.replyPublicDelayed(message, game.player1 + ' is the new player 1.');
    }

    if (Object.keys(game.players).length === 1){
        game.started = false;
        bot.replyPublicDelayed(message, 'Only one player remaining. Waiting for more players.');
    }

    reportTurnOrder(bot, message);
}

function joinGame(bot, message, userName){
    var user = userName || message.user_name,
        channel = message.channel;

    var game = getGame(bot, message);

    if (!game){
        return;
    }

    if (game.players[user]){
        bot.replyPrivate(message, user + ', you\'ve already joined the game!');
        return;
    }

    game.players[user] = {
        hand: []
    };
    game.turnOrder.push(user);

    bot.replyPublic(message, user + ' has joined the game.');

    reportTurnOrder(bot, message);
}

function getGame(bot, message, suppressReport){
    var channel = message.channel;

    if (!games[channel] || !games[channel].initialized){
        if (!suppressReport)
        {
            bot.replyPrivate(message, 'There is no game yet.');
        }
        return undefined;
    }

    return games[channel];
}

function reportTurnOrder(bot, message, isPrivate, isDelayed){
    var game = getGame(bot, message);

    if (!game){
        return;
    }

    var currentOrder = '';

    for (var i = 1; i < game.turnOrder.length + 1; i++){
        if (i > 1){
            currentOrder = currentOrder + ', ';
        }

        currentOrder = currentOrder + '\n' + i + '. ' + game.turnOrder[i - 1];
    }

    if (isPrivate){
        if (isDelayed){
            bot.replyPrivateDelayed(message, 'Current playing order:\n' + currentOrder);
        } else{
            bot.replyPrivate(message, 'Current playing order:\n' + currentOrder);
        }
    }
    else{
        bot.replyPublicDelayed(message, 'Current playing order:\n' + currentOrder);
    }
}

function initializeGame(bot, message){
    var user = message.user_name,
        channel = message.channel;

    var game = getGame(bot, message, true);

    if (!game){
        game = newGame();

        games[channel] = game;
    }

    if (game.initialized){
        bot.replyPrivate(message, 'There is already an uno game in progress. Type !join to join the game.');
        return;
    }

    game = newGame();
    games[channel] = game;

    game.initialized = true;
    game.player1 = user;
    game.players[user] = {
        hand: []
    };
    game.turnOrder.push(user);

    bot.replyPublic(message, user + ' has started UNO. Type !join to join the game.');

    reportTurnOrder(bot, message);
};

function newGame(){
    return {
        initialized: false,
        started: false,
        players: [],
        deckId: '',
        turnOrder: []
    };
}

controller.hears(['uptime', 'identify yourself', 'who are you', 'what is your name'],
    'direct_message,direct_mention,mention', function(bot, message) {

        var hostname = os.hostname();
        var uptime = formatUptime(process.uptime());

        bot.reply(message,
            ':robot_face: I am a bot named <@' + bot.identity.name +
             '>. I have been running for ' + uptime + ' on ' + hostname + '.');

    });

function formatUptime(uptime) {
    var unit = 'second';
    if (uptime > 60) {
        uptime = uptime / 60;
        unit = 'minute';
    }
    if (uptime > 60) {
        uptime = uptime / 60;
        unit = 'hour';
    }
    if (uptime != 1) {
        unit = unit + 's';
    }

    uptime = uptime + ' ' + unit;
    return uptime;
}
<commit_msg>card parsing debug<commit_after>if (!process.env.token) {
    console.log('Error: Specify token in environment');
    process.exit(1);
}

require('any-promise/register/q');

var Botkit = require('./lib/Botkit.js'),
    os = require('os'),
    controller = Botkit.slackbot({
        //debug: true
    }),
    bot = controller.spawn({
        token: process.env.token
    }).startRTM(),
    Q = require('q'),
    request = require('request-promise-any');

controller.setupWebserver(process.env.PORT, function(err, webserver) {
  controller.createWebhookEndpoints(controller.webserver, 'PsRh1Hn3lbVjQpYtf3UaLwKH');
});

var games = {},
    suitMappings = {'HEARTS': 'red', 'SPADES': 'green', 'CLUBS': 'yellow', 'DIAMONDS': 'blue'},
    valueMappings = {'JACK': 'Draw 2', 'QUEEN': 'Skip', 'KING': 'Reverse'};

//TODO: Allow for commands via @mentions as well

controller.hears('new', ['slash_command'/*, 'direct_mention', 'mention'*/], function(bot, message){
    //console.log(message);
    initializeGame(bot, message);
});

controller.hears('join', ['slash_command'/*, 'direct_mention', 'mention'*/], function(bot, message){
    console.log(message);
    joinGame(bot, message);
});

controller.hears('quit', ['slash_command'/*, 'direct_mention', 'mention'*/], function(bot, message){
    console.log(message);
    quitGame(bot, message);
});

controller.hears('order', ['slash_command'/*, 'direct_mention', 'mention'*/], function(bot, message){
    console.log(message);
    reportTurnOrder(bot, message, true);
});

controller.hears('setup', ['slash_command'/*, 'direct_mention', 'mention'*/], function(bot, message){
    //console.log(message);
    for (var i = 2; i <= 2; i++){
        var mockUser = 'Player' + i;

        joinGame(bot, message, mockUser);
    }
});

controller.hears('start', ['slash_command'], function(bot, message){
    //console.log(message);
    beginGame(bot, message);
});

function beginGame(bot, message){
    var user = message.user_name,
        game = getGame(bot, message);

    if (!game){
        return;
    }

    if (game.player1 !== user){
        bot.replyPrivate(message, 'Only player 1 (' + game.player1 + ') can start the game.');
        return;
    }

    if (Object.keys(game.players).length < 2){
        bot.replyPrivate(message, 'You need at least two players to begin playing.');
        return;
    }

    if (game.started){
        bot.replyPrivate(message, 'The game is already started.');
        reportTurnOrder(bot, message, true, true);
        return;
    }

    game.started = true;
    var drawRequests = [];

    bot.replyPublic(message, 'Game has started! Shuffling the deck and dealing the hands.');

    //Create the deck
    request({
                uri: 'http://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=2',
                json: true
            })
        .then(function(result){
                game.deckId = result.deck_id;
            })
        /*.then(function(){
                console.log('Deck request finished');
            })*/
        .then(function(){
                for (playerName in game.players){
                    console.log('beginning draw for ' + playerName);
                    var player = game.players[playerName];
                    var drawRequest = request({
                                uri: 'http://deckofcardsapi.com/api/deck/' + game.deckId + '/draw/?count=7',
                                json: true
                            })
                        .then(function(result){
                            console.log(result);

                            console.log(result.cards.length + ' cards returned, adding to ' + playerName + ' hand');

                            for (var j = 0; j < result.cards.length; j++){
                                console.log(result.cards[j]);
                                var card = getUnoCard(result.cards[j])
                                player.cards.push();
                            }
                        })
                        .then(function(){
                            console.log('Draw request finished');
                            console.log(player);
                        });

                    drawRequests.push(drawRequest);
                }
            })
        .then(function(){
                Q.allSettled(drawRequests).then(function(){
                    console.log('All draw requests should be finished by now.');
                    console.log(game);
                    announceTurn(bot, message);
                })
            });
}

function getUnoCard(standardCard){
    console.log('standardCard:');
    console.log(standardCard);

    var value = valueMappings[standardCard.value] || (standardCard.value - 1),
        color = suitMappings[standardCard.suit];

    if (value === 'ACE'){
        color = 'Wild';
        switch (standardCard.suit){
            case 'CLUBS':
            case 'SPADES':
                value = 'Wild';
                break;
            case 'HEARTS':
            case 'DIAMONDS':
                value = 'Draw 4';
                break;
        }
    }

    var res = {
        color: color,
        value: value
    };
    console.log('unoCard:');
    console.log(res);

    return res;
}

function getStandardCard(unoCard){

}

function announceTurn(bot, message){
    var game = getGame(bot, message);

    bot.replyPublicDelayed(message, 'It is ' + game.turnOrder[0] + '\'s turn.\nType \\uno cards, \\uno draw, \\uno skip or \\uno play.')
}

function quitGame(bot, message){
    var user = message.user_name,
        game = getGame(bot, message),
        channel = message.channel;

    if (!game.players[user]){
        bot.replyPrivate(message, 'You weren\'t playing to begin with.');
        return;
    }

    delete game.players[user];

    var player = game.turnOrder.indexOf(user);
    game.turnOrder.splice(player, 1);

    bot.replyPublic(message, user + ' has left the game.');

    if (Object.keys(game.players).length === 0){
        bot.replyPublicDelayed(message, 'No more players. Ending the game.');
        games[channel] = newGame();
        return;
    }

    if (game.player1 === user){
        game.player1 = Object.keys(game.players)[0];
        bot.replyPublicDelayed(message, game.player1 + ' is the new player 1.');
    }

    if (Object.keys(game.players).length === 1){
        game.started = false;
        bot.replyPublicDelayed(message, 'Only one player remaining. Waiting for more players.');
    }

    reportTurnOrder(bot, message);
}

function joinGame(bot, message, userName){
    var user = userName || message.user_name,
        channel = message.channel;

    var game = getGame(bot, message);

    if (!game){
        return;
    }

    if (game.players[user]){
        bot.replyPrivate(message, user + ', you\'ve already joined the game!');
        return;
    }

    game.players[user] = {
        hand: []
    };
    game.turnOrder.push(user);

    bot.replyPublic(message, user + ' has joined the game.');

    reportTurnOrder(bot, message);
}

function getGame(bot, message, suppressReport){
    var channel = message.channel;

    if (!games[channel] || !games[channel].initialized){
        if (!suppressReport)
        {
            bot.replyPrivate(message, 'There is no game yet.');
        }
        return undefined;
    }

    return games[channel];
}

function reportTurnOrder(bot, message, isPrivate, isDelayed){
    var game = getGame(bot, message);

    if (!game){
        return;
    }

    var currentOrder = '';

    for (var i = 1; i < game.turnOrder.length + 1; i++){
        if (i > 1){
            currentOrder = currentOrder + ', ';
        }

        currentOrder = currentOrder + '\n' + i + '. ' + game.turnOrder[i - 1];
    }

    if (isPrivate){
        if (isDelayed){
            bot.replyPrivateDelayed(message, 'Current playing order:\n' + currentOrder);
        } else{
            bot.replyPrivate(message, 'Current playing order:\n' + currentOrder);
        }
    }
    else{
        bot.replyPublicDelayed(message, 'Current playing order:\n' + currentOrder);
    }
}

function initializeGame(bot, message){
    var user = message.user_name,
        channel = message.channel;

    var game = getGame(bot, message, true);

    if (!game){
        game = newGame();

        games[channel] = game;
    }

    if (game.initialized){
        bot.replyPrivate(message, 'There is already an uno game in progress. Type !join to join the game.');
        return;
    }

    game = newGame();
    games[channel] = game;

    game.initialized = true;
    game.player1 = user;
    game.players[user] = {
        hand: []
    };
    game.turnOrder.push(user);

    bot.replyPublic(message, user + ' has started UNO. Type !join to join the game.');

    reportTurnOrder(bot, message);
};

function newGame(){
    return {
        initialized: false,
        started: false,
        players: [],
        deckId: '',
        turnOrder: []
    };
}

controller.hears(['uptime', 'identify yourself', 'who are you', 'what is your name'],
    'direct_message,direct_mention,mention', function(bot, message) {

        var hostname = os.hostname();
        var uptime = formatUptime(process.uptime());

        bot.reply(message,
            ':robot_face: I am a bot named <@' + bot.identity.name +
             '>. I have been running for ' + uptime + ' on ' + hostname + '.');

    });

function formatUptime(uptime) {
    var unit = 'second';
    if (uptime > 60) {
        uptime = uptime / 60;
        unit = 'minute';
    }
    if (uptime > 60) {
        uptime = uptime / 60;
        unit = 'hour';
    }
    if (uptime != 1) {
        unit = unit + 's';
    }

    uptime = uptime + ' ' + unit;
    return uptime;
}
<|endoftext|>


<commit_before>/** @jsx React.DOM */

var React = window.React = require('react'),
    LinesList = require('./ui/lines_list'),
    mountNode = document.getElementById('app');

var SvgScribblerApp = React.createClass({
  getInitialState: function() {
    var colors = randomColor({count: 2});
    var minStrokeWidth = 0;
    var maxStrokeWidth = 20;
    return {
      minStrokeWidth: minStrokeWidth,
      maxStrokeWidth: maxStrokeWidth,
      lines: [{
        points: [],
        stroke: colors[0],
        fill: colors[1],
        strokeWidth: this.getRandomStrokeWidth(minStrokeWidth, maxStrokeWidth),
        id: 1
      }],
      isDrawing: false
    };
  },
  getRandomStrokeWidth: function(min, max) {
    if (typeof min === 'undefined') {
      min = this.state.minStrokeWidth;
    }
    if (typeof max === 'undefined') {
      max = this.state.maxStrokeWidth;
    }
    return Math.floor(Math.random() * (max - min + 1) + min);
  },
  adjustSvgSize: function() {
    var svgWrapper = $('.svg-container');
    var footer = $('.footer');
    var height = $(window).height();
    height = height - svgWrapper.offset().top - footer.height();
    svgWrapper.css('height', height);
  },
  componentDidMount: function() {
    var self = this;
    $('#stroke-color-picker').spectrum({
      color: this.state.lines[0].stroke,
      change: function(color) {
        var line = self.getCurrentLine();
        line.stroke = color.toRgbString();
        self.updateCurrentLine(line);
      }
    });
    $('#fill-color-picker').spectrum({
      color: this.state.lines[0].fill,
      change: function(color) {
        var line = self.getCurrentLine();
        line.fill = color.toRgbString();
        self.updateCurrentLine(line);
      }
    });
    this.adjustSvgSize();
    $('[data-toggle="tooltip"]').tooltip();
  },
  doesPointExist: function(line, coords) {
    for (var i=0; i<line.length; i++) {
      var point = line[i];
      if (point.left === coords.x && point.top === coords.y) {
        return true;
      }
    }
    return false;
  },
  getCurrentLine: function() {
    var line = this.state.lines.slice(this.state.lines.length - 1)[0];
    var newLine = {};
    var props = Object.keys(line);
    for (var i=0; i<props.length; i++) {
      var prop = props[i];
      var originalValue = line[prop];
      if (Array.isArray(originalValue)) {
        newLine[prop] = originalValue.slice(0, originalValue.length);
      } else {
        newLine[prop] = originalValue;
      }
    }
    return newLine;
  },
  updateCurrentLine: function(line) {
    var newLines = this.state.lines.slice(0, this.state.lines.length - 1);
    newLines.push(line);
    this.setState({lines: newLines});
  },
  addPoint: function(coords) {
    var line = this.getCurrentLine();
    if (!this.doesPointExist(line, coords)) {
      var newPoint = {left: coords.x, top: coords.y, width: 10, height: 10};
      line.points.push(newPoint);
      this.updateCurrentLine(line);
    }
  },
  getCanvasCoords: function(e) {
    var canvas = $(e.target);
    var offset = canvas.offset();
    var left = offset.left;
    var top = offset.top;
    var x = e.pageX - left;
    var y = e.pageY - top;
    return {x: x, y: y};
  },
  addNewLineIfNecessary: function() {
    var lastLine = this.getCurrentLine();
    if (lastLine.points.length > 0) {
      var newLine = {
        points: [],
        stroke: lastLine.stroke,
        fill: lastLine.fill,
        strokeWidth: lastLine.strokeWidth,
        id: this.state.lines.length + 1
      };
      this.setState({lines: this.state.lines.concat(newLine)});
    }
  },
  onMouseDown: function(e) {
    this.setState({isDrawing: true});
    var coords = this.getCanvasCoords(e);
    this.addPoint(coords);
  },
  onMouseMove: function(e) {
    if (!this.state.isDrawing) {
      return;
    }
    var coords = this.getCanvasCoords(e);
    this.addPoint(coords);
  },
  onMouseUp: function(e) {
    var coords = this.getCanvasCoords(e);
    this.addPoint(coords);
    this.setState({isDrawing: false});
    this.addNewLineIfNecessary();
  },
  onMouseLeave: function(e) {
    this.setState({isDrawing: false});
    this.addNewLineIfNecessary();
  },
  getPointsList: function(line) {
    var pairs = [];
    for (var i=0; i<line.points.length; i++) {
      var point = line.points[i];
      pairs.push(point.left + ',' + point.top);
    }
    return pairs.join(' ');
  },
  getPolylineStyle: function(line) {
    return {
      stroke: line.stroke,
      fill: line.fill,
      strokeWidth: line.strokeWidth
    };
  },
  getPolylineSource: function() {
    var polylines = [];
    for (var i=0; i<this.state.lines.length; i++) {
      var line = this.state.lines[i];
      if (line.points.length < 2) {
        continue;
      }
      var svgPoints = [];
      for (var j=0; j<line.points.length; j++) {
        var point = line.points[j];
        svgPoints.push(point.left + ',' + point.top);
      }
      svgPoints = svgPoints.join(' ');
      var svgStyle = 'stroke: ' + line.stroke + '; fill: ' + line.fill +
                     '; stroke-width: ' + line.strokeWidth;
      polylines.push('  <polyline points="' + svgPoints + '" style="' +
                     svgStyle + '" />');
    }
    return polylines.join("\n") + "\n";
  },
  downloadSvg: function(e) {
    var button = $(e.target);
    var svgEl = $('svg.svg-result');
    var svgSource = $(svgEl.wrap('
').parent().html());
    svgSource.find('*').removeAttr('data-reactid');
    svgSource = svgSource.html();
    svgSource = '<svg version="1.1" xmlns="http://www.w3.org/2000/svg">' +
                "\n" + svgSource + "\n</svg>";
    svgEl.unwrap('
');
    console.log(svgSource);
    var b64 = Base64.encode(svgSource);
    var fileName = 'svg-scribbler-' + moment().format('YYYY-MM-DD-hh-mm-ss-a') +
                   '.svg';
    var link = $('').attr('href-lang', 'image/svg+xml').
                        attr('href', "data:image/svg+xml;base64,\n" + b64).
                        attr('download', fileName).text(' ');
    $('body').append(link);
    link[0].click();
    link.remove();
    button.blur();
  },
  downloadButtonStyle: function() {
    var display;
    if (this.state.lines.length > 1) {
      display = 'inline-block';
    } else {
      var line = this.getCurrentLine();
      display = line.points.length > 0 ? 'inline-block' : 'none';
    }
    return {display: display};
  },
  setLineColor: function(type, color) {
    $('#' + type + '-color-picker').spectrum('set', color);
    var line = this.getCurrentLine();
    line[type] = color;
    this.updateCurrentLine(line);
  },
  randomizeStroke: function() {
    this.setLineColor('stroke', randomColor());
  },
  randomizeFill: function() {
    this.setLineColor('fill', randomColor());
  },
  clearStroke: function() {
    this.setLineColor('stroke', 'transparent');
  },
  clearFill: function() {
    this.setLineColor('fill', 'transparent');
  },
  setStrokeWidth: function(e) {
    var slider = $(e.target);
    var line = this.getCurrentLine();
    line.strokeWidth = slider.val();
    this.updateCurrentLine(line);
  },
  deleteLine: function(lineToDelete) {
    var index;
    for (var i=0; i<this.state.lines.length; i++) {
      var line = this.state.lines[i];
      if (line.id === lineToDelete.id) {
        index = i;
        break;
      }
    }
    if (typeof index !== 'undefined') {
      var newLines = this.state.lines.slice(0, index).
                          concat(this.state.lines.slice(index + 1));
      this.setState({lines: newLines});
    }
  },
  render: function() {
    var self = this;
    return (

          <button type="button" className="pull-right btn btn-info download-button" onClick={this.downloadSvg} style={this.downloadButtonStyle()}>

            Download SVG
          </button>

SVG Scribbler

                Draw

                View SVG Source

                        Border:
                        <input type="text" id="stroke-color-picker" className="color-picker" />
                        <button type="button" className="randomize-color btn btn-flat btn-sm" data-toggle="tooltip" title="Randomize" onClick={this.randomizeStroke}>

                        </button>
                        <button type="button" className="clear-color btn btn-flat btn-sm" data-toggle="tooltip" title="Clear" onClick={this.clearStroke}>

                        </button>

                        Fill:
                        <input type="text" id="fill-color-picker" className="color-picker" />
                        <button type="button" className="randomize-color btn btn-flat btn-sm" data-toggle="tooltip" title="Randomize" onClick={this.randomizeFill}>

                        </button>
                        <button type="button" className="clear-color btn btn-flat btn-sm" data-toggle="tooltip" title="Clear" onClick={this.clearFill}>

                        </button>

                        Border width:

                            {this.state.minStrokeWidth}

                          <input onInput={this.setStrokeWidth} type="range" id="stroke-width-slider" min={this.state.minStrokeWidth} defaultValue={this.getCurrentLine().strokeWidth} step="1" max={this.state.maxStrokeWidth} />

                            {this.state.maxStrokeWidth}

                    <svg className="svg-result" version="1.1" xmlns="http://www.w3.org/2000/svg">
                      {
                        this.state.lines.map(function(line) {
                          if (line.points.length > 1) {
                            return <polyline points={self.getPointsList(line)} style={self.getPolylineStyle(line)} />
                          }
                        })
                      }
                    </svg>
                    <canvas className="svg-canvas" onMouseDown={this.onMouseDown} onMouseMove={this.onMouseMove} onMouseUp={this.onMouseUp} onMouseLeave={this.onMouseLeave}></canvas>

                  <LinesList lines={this.state.lines} onDeleteLine={this.deleteLine} />

<svg version="1.1" xmlns="http://www.w3.org/2000/svg">

    {this.getPolylineSource()}
  </svg>

    );
  }
});

React.render(<SvgScribblerApp />, mountNode);
<commit_msg>Can randomize stroke width with button<commit_after>/** @jsx React.DOM */

var React = window.React = require('react'),
    LinesList = require('./ui/lines_list'),
    mountNode = document.getElementById('app');

var SvgScribblerApp = React.createClass({
  getInitialState: function() {
    var colors = randomColor({count: 2});
    var minStrokeWidth = 0;
    var maxStrokeWidth = 20;
    return {
      minStrokeWidth: minStrokeWidth,
      maxStrokeWidth: maxStrokeWidth,
      lines: [{
        points: [],
        stroke: colors[0],
        fill: colors[1],
        strokeWidth: this.getRandomStrokeWidth(minStrokeWidth, maxStrokeWidth),
        id: 1
      }],
      isDrawing: false
    };
  },
  getRandomStrokeWidth: function(min, max) {
    if (typeof min === 'undefined') {
      min = this.state.minStrokeWidth;
    }
    if (typeof max === 'undefined') {
      max = this.state.maxStrokeWidth;
    }
    return Math.floor(Math.random() * (max - min + 1) + min);
  },
  adjustSvgSize: function() {
    var svgWrapper = $('.svg-container');
    var footer = $('.footer');
    var height = $(window).height();
    height = height - svgWrapper.offset().top - footer.height();
    svgWrapper.css('height', height);
  },
  componentDidMount: function() {
    var self = this;
    $('#stroke-color-picker').spectrum({
      color: this.state.lines[0].stroke,
      change: function(color) {
        var line = self.getCurrentLine();
        line.stroke = color.toRgbString();
        self.updateCurrentLine(line);
      }
    });
    $('#fill-color-picker').spectrum({
      color: this.state.lines[0].fill,
      change: function(color) {
        var line = self.getCurrentLine();
        line.fill = color.toRgbString();
        self.updateCurrentLine(line);
      }
    });
    this.adjustSvgSize();
    $('[data-toggle="tooltip"]').tooltip();
  },
  doesPointExist: function(line, coords) {
    for (var i=0; i<line.length; i++) {
      var point = line[i];
      if (point.left === coords.x && point.top === coords.y) {
        return true;
      }
    }
    return false;
  },
  getCurrentLine: function() {
    var line = this.state.lines.slice(this.state.lines.length - 1)[0];
    var newLine = {};
    var props = Object.keys(line);
    for (var i=0; i<props.length; i++) {
      var prop = props[i];
      var originalValue = line[prop];
      if (Array.isArray(originalValue)) {
        newLine[prop] = originalValue.slice(0, originalValue.length);
      } else {
        newLine[prop] = originalValue;
      }
    }
    return newLine;
  },
  updateCurrentLine: function(line) {
    var newLines = this.state.lines.slice(0, this.state.lines.length - 1);
    newLines.push(line);
    this.setState({lines: newLines});
  },
  addPoint: function(coords) {
    var line = this.getCurrentLine();
    if (!this.doesPointExist(line, coords)) {
      var newPoint = {left: coords.x, top: coords.y, width: 10, height: 10};
      line.points.push(newPoint);
      this.updateCurrentLine(line);
    }
  },
  getCanvasCoords: function(e) {
    var canvas = $(e.target);
    var offset = canvas.offset();
    var left = offset.left;
    var top = offset.top;
    var x = e.pageX - left;
    var y = e.pageY - top;
    return {x: x, y: y};
  },
  addNewLineIfNecessary: function() {
    var lastLine = this.getCurrentLine();
    if (lastLine.points.length > 0) {
      var newLine = {
        points: [],
        stroke: lastLine.stroke,
        fill: lastLine.fill,
        strokeWidth: lastLine.strokeWidth,
        id: this.state.lines.length + 1
      };
      this.setState({lines: this.state.lines.concat(newLine)});
    }
  },
  onMouseDown: function(e) {
    this.setState({isDrawing: true});
    var coords = this.getCanvasCoords(e);
    this.addPoint(coords);
  },
  onMouseMove: function(e) {
    if (!this.state.isDrawing) {
      return;
    }
    var coords = this.getCanvasCoords(e);
    this.addPoint(coords);
  },
  onMouseUp: function(e) {
    var coords = this.getCanvasCoords(e);
    this.addPoint(coords);
    this.setState({isDrawing: false});
    this.addNewLineIfNecessary();
  },
  onMouseLeave: function(e) {
    this.setState({isDrawing: false});
    this.addNewLineIfNecessary();
  },
  getPointsList: function(line) {
    var pairs = [];
    for (var i=0; i<line.points.length; i++) {
      var point = line.points[i];
      pairs.push(point.left + ',' + point.top);
    }
    return pairs.join(' ');
  },
  getPolylineStyle: function(line) {
    return {
      stroke: line.stroke,
      fill: line.fill,
      strokeWidth: line.strokeWidth
    };
  },
  getPolylineSource: function() {
    var polylines = [];
    for (var i=0; i<this.state.lines.length; i++) {
      var line = this.state.lines[i];
      if (line.points.length < 2) {
        continue;
      }
      var svgPoints = [];
      for (var j=0; j<line.points.length; j++) {
        var point = line.points[j];
        svgPoints.push(point.left + ',' + point.top);
      }
      svgPoints = svgPoints.join(' ');
      var svgStyle = 'stroke: ' + line.stroke + '; fill: ' + line.fill +
                     '; stroke-width: ' + line.strokeWidth;
      polylines.push('  <polyline points="' + svgPoints + '" style="' +
                     svgStyle + '" />');
    }
    return polylines.join("\n") + "\n";
  },
  downloadSvg: function(e) {
    var button = $(e.target);
    var svgEl = $('svg.svg-result');
    var svgSource = $(svgEl.wrap('
').parent().html());
    svgSource.find('*').removeAttr('data-reactid');
    svgSource = svgSource.html();
    svgSource = '<svg version="1.1" xmlns="http://www.w3.org/2000/svg">' +
                "\n" + svgSource + "\n</svg>";
    svgEl.unwrap('
');
    console.log(svgSource);
    var b64 = Base64.encode(svgSource);
    var fileName = 'svg-scribbler-' + moment().format('YYYY-MM-DD-hh-mm-ss-a') +
                   '.svg';
    var link = $('').attr('href-lang', 'image/svg+xml').
                        attr('href', "data:image/svg+xml;base64,\n" + b64).
                        attr('download', fileName).text(' ');
    $('body').append(link);
    link[0].click();
    link.remove();
    button.blur();
  },
  downloadButtonStyle: function() {
    var display;
    if (this.state.lines.length > 1) {
      display = 'inline-block';
    } else {
      var line = this.getCurrentLine();
      display = line.points.length > 0 ? 'inline-block' : 'none';
    }
    return {display: display};
  },
  setLineColor: function(type, color) {
    $('#' + type + '-color-picker').spectrum('set', color);
    var line = this.getCurrentLine();
    line[type] = color;
    this.updateCurrentLine(line);
  },
  randomizeStroke: function() {
    this.setLineColor('stroke', randomColor());
  },
  randomizeFill: function() {
    this.setLineColor('fill', randomColor());
  },
  clearStroke: function() {
    this.setLineColor('stroke', 'transparent');
  },
  clearFill: function() {
    this.setLineColor('fill', 'transparent');
  },
  setStrokeWidth: function(e) {
    var slider = $(e.target);
    var line = this.getCurrentLine();
    line.strokeWidth = slider.val();
    this.updateCurrentLine(line);
  },
  randomizeStrokeWidth: function() {
    var line = this.getCurrentLine();
    var currentStrokeWidth = line.strokeWidth;
    while (currentStrokeWidth === line.strokeWidth) {
      line.strokeWidth = this.getRandomStrokeWidth();
    }
    this.updateCurrentLine(line);
  },
  deleteLine: function(lineToDelete) {
    var index;
    for (var i=0; i<this.state.lines.length; i++) {
      var line = this.state.lines[i];
      if (line.id === lineToDelete.id) {
        index = i;
        break;
      }
    }
    if (typeof index !== 'undefined') {
      var newLines = this.state.lines.slice(0, index).
                          concat(this.state.lines.slice(index + 1));
      this.setState({lines: newLines});
    }
  },
  render: function() {
    var self = this;
    return (

          <button type="button" className="pull-right btn btn-info download-button" onClick={this.downloadSvg} style={this.downloadButtonStyle()}>

            Download SVG
          </button>

SVG Scribbler

                Draw

                View SVG Source

                        Border:
                        <input type="text" id="stroke-color-picker" className="color-picker" />
                        <button type="button" className="randomize-color btn btn-flat btn-sm" data-toggle="tooltip" title="Randomize" onClick={this.randomizeStroke}>

                        </button>
                        <button type="button" className="clear-color btn btn-flat btn-sm" data-toggle="tooltip" title="Clear" onClick={this.clearStroke}>

                        </button>

                        Fill:
                        <input type="text" id="fill-color-picker" className="color-picker" />
                        <button type="button" className="randomize-color btn btn-flat btn-sm" data-toggle="tooltip" title="Randomize" onClick={this.randomizeFill}>

                        </button>
                        <button type="button" className="clear-color btn btn-flat btn-sm" data-toggle="tooltip" title="Clear" onClick={this.clearFill}>

                        </button>

                        Border width:

                            {this.state.minStrokeWidth}

                          <input onInput={this.setStrokeWidth} type="range" id="stroke-width-slider" min={this.state.minStrokeWidth} value={this.getCurrentLine().strokeWidth} step="1" max={this.state.maxStrokeWidth} />

                            {this.state.maxStrokeWidth}

                        <button type="button" className="randomize-stroke-width btn btn-flat btn-sm" data-toggle="tooltip" title="Randomize" onClick={this.randomizeStrokeWidth}>

                        </button>

                    <svg className="svg-result" version="1.1" xmlns="http://www.w3.org/2000/svg">
                      {
                        this.state.lines.map(function(line) {
                          if (line.points.length > 1) {
                            return <polyline points={self.getPointsList(line)} style={self.getPolylineStyle(line)} />
                          }
                        })
                      }
                    </svg>
                    <canvas className="svg-canvas" onMouseDown={this.onMouseDown} onMouseMove={this.onMouseMove} onMouseUp={this.onMouseUp} onMouseLeave={this.onMouseLeave}></canvas>

                  <LinesList lines={this.state.lines} onDeleteLine={this.deleteLine} />

<svg version="1.1" xmlns="http://www.w3.org/2000/svg">

    {this.getPolylineSource()}
  </svg>

    );
  }
});

React.render(<SvgScribblerApp />, mountNode);
<|endoftext|>


<commit_before>(function () {
'use strict';

/* Handle nodejs exceptions */
if (typeof process != 'undefined') {
  process.on('uncaughtException', function(err) {
    console.log('Caught exception: ' + err);
  });
}

var module = angular.module('fim.base', [
  'ngAnimate',
  'ngSanitize',
  'ngTouch',
  'ngTable',
  'ngRoute',
  'ngCookies',
  'ui.bootstrap',
  'ui.validate',
  'pascalprecht.translate',
  'infinite-scroll',
  'ngClipboard'
]);

module.run(function ($log, $rootScope, $translate, plugins, serverService) {
  $log.log('fim.base application started');
  if (isNodeJS) {
    var win = require('nw.gui').Window.get();
    win.on('close', function (event) {

      var self = this;
      plugins.get('alerts').confirm({
        title: 'Close Mofowallet',
        message: 'Are you sure you want to exit MofoWallet?'
      }).then(
        function (confirmed) {
          if (confirmed) {
            var count = 0;
            angular.forEach(['TYPE_NXT','TYPE_FIM'], function (id) {
              if (serverService.isRunning(id)) {
                serverService.addListener(id, 'exit', function () {
                  count--;
                  if (count == 0) {
                    self.close(true);
                  }
                });

                count++;
                serverService.stopServer(id);
              }
            });
            if (count == 0) {
              self.hide();
              self.close(true);
            }
            else {
              plugins.get('alerts').wait({
                title: "Please wait",
                message: "Shutting down"
              });
            }
          }
        }
      );
    });
  }
});

module.config(function($translateProvider, $httpProvider) {
  $translateProvider.useStaticFilesLoader({ prefix: './i18n/', suffix: '.json' });
  $translateProvider.preferredLanguage('en');
  $translateProvider.useLocalStorage();

  delete $httpProvider.defaults.headers.common['X-Requested-With'];
});

module.config(['ngClipProvider', function(ngClipProvider) {
  ngClipProvider.setPath("ZeroClipboard.swf");
}]);

})();<commit_msg>Angular translate requires sanitize strategy<commit_after>(function () {
'use strict';

/* Handle nodejs exceptions */
if (typeof process != 'undefined') {
  process.on('uncaughtException', function(err) {
    console.log('Caught exception: ' + err);
  });
}

var module = angular.module('fim.base', [
  'ngAnimate',
  'ngSanitize',
  'ngTouch',
  'ngTable',
  'ngRoute',
  'ngCookies',
  'ui.bootstrap',
  'ui.validate',
  'pascalprecht.translate',
  'infinite-scroll',
  'ngClipboard'
]);

module.run(function ($log, $rootScope, $translate, plugins, serverService) {
  $log.log('fim.base application started');
  if (isNodeJS) {
    var win = require('nw.gui').Window.get();
    win.on('close', function (event) {

      var self = this;
      plugins.get('alerts').confirm({
        title: 'Close Mofowallet',
        message: 'Are you sure you want to exit MofoWallet?'
      }).then(
        function (confirmed) {
          if (confirmed) {
            var count = 0;
            angular.forEach(['TYPE_NXT','TYPE_FIM'], function (id) {
              if (serverService.isRunning(id)) {
                serverService.addListener(id, 'exit', function () {
                  count--;
                  if (count == 0) {
                    self.close(true);
                  }
                });

                count++;
                serverService.stopServer(id);
              }
            });
            if (count == 0) {
              self.hide();
              self.close(true);
            }
            else {
              plugins.get('alerts').wait({
                title: "Please wait",
                message: "Shutting down"
              });
            }
          }
        }
      );
    });
  }
});

module.config(function($translateProvider, $httpProvider) {
  $translateProvider.useSanitizeValueStrategy(null);
  $translateProvider.useStaticFilesLoader({ prefix: './i18n/', suffix: '.json' });
  $translateProvider.preferredLanguage('en');
  $translateProvider.useLocalStorage();

  delete $httpProvider.defaults.headers.common['X-Requested-With'];
});

module.config(['ngClipProvider', function(ngClipProvider) {
  ngClipProvider.setPath("ZeroClipboard.swf");
}]);

})();<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');
var PARAMS = require('./stencil/params');

var DEST = PARAMS.buildDir;

var ENTRY = { 'main.js': [ 'babel-core/polyfill', './scripts/main.js'] };

var providePlugins = {};

if (PARAMS.jsFramework === 'basic' || PARAMS.jsFramework === 'backbone') {
    providePlugins.$ = 'jquery';
    providePlugins.jQuery = 'jquery';
    providePlugins._ = 'lodash';
}

if (PARAMS.jsFramework === 'basic') {
    providePlugins.ko = 'knockout';
    providePlugins.postal = 'postal';
}

if (PARAMS.jsFramework === 'backbone') {
    providePlugins.Backbone = 'backbone';
}

var aliases = {};

if (PARAMS.cssFramework === 'bootstrap') {
    aliases.bootstrap = path.resolve(__dirname, 'node_modules/bootstrap-styl/js');
}

var LOADERS = [{
    test: /scripts\/vendor\/.+\.js$/,
    loaders: ['imports?this=>window']
}, {
    test: /\.jsx?$/,
    exclude: /node_modules|scripts\/vendor/,
    loaders: [
        'babel?stage=0',
        'eslint'
        ]
}];

module.exports = {
    entry: ENTRY,

    output: {
        filename: 'main.js',
        path: DEST + '/javascript/',
        publicPath: '/javascript/'
    },

    stats: {
        colors: true,
        reasons: false
    },

    plugins: [
        new webpack.ProvidePlugin(providePlugins)
    ],

    resolve: {
        aliases: aliases,
        modulesDirectories: ['local_modules', 'node_modules'],
        extensions: ['', '.js', '.jsx']
    },

    eslint: {
        configFile: './scripts/.eslintrc'
    },

    module: {
        loaders: LOADERS
    }
};
<commit_msg>remove lodash from basic framework<commit_after>var path = require('path');
var webpack = require('webpack');
var PARAMS = require('./stencil/params');

var DEST = PARAMS.buildDir;

var ENTRY = { 'main.js': [ 'babel-core/polyfill', './scripts/main.js'] };

var providePlugins = {};

if (PARAMS.jsFramework === 'basic' || PARAMS.jsFramework === 'backbone') {
    providePlugins.$ = 'jquery';
    providePlugins.jQuery = 'jquery';
}

if (PARAMS.jsFramework === 'basic') {
    providePlugins.ko = 'knockout';
    providePlugins.postal = 'postal';
}

if (PARAMS.jsFramework === 'backbone') {
    providePlugins.Backbone = 'backbone';
    providePlugins._ = 'lodash';
}

var aliases = {};

if (PARAMS.cssFramework === 'bootstrap') {
    aliases.bootstrap = path.resolve(__dirname, 'node_modules/bootstrap-styl/js');
}

var LOADERS = [{
    test: /scripts\/vendor\/.+\.js$/,
    loaders: ['imports?this=>window']
}, {
    test: /\.jsx?$/,
    exclude: /node_modules|scripts\/vendor/,
    loaders: [
        'babel?stage=0',
        'eslint'
        ]
}];

module.exports = {
    entry: ENTRY,

    output: {
        filename: 'main.js',
        path: DEST + '/javascript/',
        publicPath: '/javascript/'
    },

    stats: {
        colors: true,
        reasons: false
    },

    plugins: [
        new webpack.ProvidePlugin(providePlugins)
    ],

    resolve: {
        aliases: aliases,
        modulesDirectories: ['local_modules', 'node_modules'],
        extensions: ['', '.js', '.jsx']
    },

    eslint: {
        configFile: './scripts/.eslintrc'
    },

    module: {
        loaders: LOADERS
    }
};
<|endoftext|>


<commit_before>'use strict';

angular.module('exampleAppApp', [
  'ngCookies',
  'ngResource',
  'ngSanitize',
  'ngRoute'
])
.controller('UserController', function($scope,$route,$routeParams, $location){

})

  .config(['$routeProvider','$locationProvider', function ($routeProvider,$locationProvider) {
    $routeProvider
 	.when('/api/locators/by/id',{
             templateUrl: '/views/api/by/id.html',
	})
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });

$locationProvider.html5Mode(true);

  }]);
<commit_msg>templateurl function for locators<commit_after>'use strict';

angular.module('exampleAppApp', [
  'ngCookies',
  'ngResource',
  'ngSanitize',
  'ngRoute'
])
.controller('UserController', function($scope,$route,$routeParams, $location){

})

  .config(['$routeProvider','$locationProvider', function ($routeProvider,$locationProvider) {
    $routeProvider
 	.when('/api/:dir1/:file',{
             templateUrl: function(routeParams){
return '/views/api/' + routeParams.dir1 + '/' + '/' + routeParams.file +'.html';},
	})
 	.when('/api/locators/by/:file',{
             templateUrl: function(routeParams){
return '/views/api/locators/' +  routeParams.file +'.html';},
	})
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });

$locationProvider.html5Mode(true);

  }]);
<|endoftext|>


<commit_before>(function() {
  function config($stateProvider, $locationProvider) {
    $locationProvider
      .html5Mode({
        enabled: true,
        requireBase: false
      });

    $stateProvider
      .state('landing', {
        url: '/',
        controller: 'LandingCtrl as landing',
        templateUrl: '/templates/landing.html'
      })
      .state('album', {
        url: '/album',
        controller: 'CollectionCtrl as collection',
        templateUrl: '/templates/album.html'
      })
      .state('collection', {
        url: '/collection',
        controller: 'AlbumCtrl as album',
        templateUrl: 'templates/collection.html'
      });
  }

  angular
    .module('blocJams', ['ui.router'])
    .config(config);
})();

<commit_msg>Found error with switch controller reference in app.js<commit_after>(function() {
  function config($stateProvider, $locationProvider) {
    $locationProvider
      .html5Mode({
        enabled: true,
        requireBase: false
      });

    $stateProvider
      .state('landing', {
        url: '/',
        controller: 'LandingCtrl as landing',
        templateUrl: '/templates/landing.html'
      })
      .state('album', {
        url: '/album',
        controller: 'AlbumCtrl as album',
        templateUrl: '/templates/album.html'
      })
      .state('collection', {
        url: '/collection',
        controller: 'CollectionCtrl as collection',
        templateUrl: 'templates/collection.html'
      });
  }

  angular
    .module('blocJams', ['ui.router'])
    .config(config);
})();

<|endoftext|>


<commit_before>'use strict';

angular.module('assigntu', [
  'ngCookies',
  'ngResource',
  'ngSanitize',
  'ngRoute',
  'firebase',
])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .when('/lists', {
        templateUrl: 'views/lists/lists.html',
        controller: 'ListsCtrl'
      })
      .when('/lists/new', {
        templateUrl: 'views/lists/new.html',
        controller: 'NewListCtrl'
      })
      .when('/lists/:id', {
        templateUrl: 'views/show.html',
        controller: 'ListCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  });
<commit_msg>Added commented out html5Mode block<commit_after>'use strict';

angular.module('assigntu', [
  'ngCookies',
  'ngResource',
  'ngSanitize',
  'ngRoute',
  'firebase',
])
  .config(function ($routeProvider, $locationProvider) {
    //$locationProvider.html5Mode(true);
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .when('/lists', {
        templateUrl: 'views/lists/lists.html',
        controller: 'ListsCtrl'
      })
      .when('/lists/new', {
        templateUrl: 'views/lists/new.html',
        controller: 'NewListCtrl'
      })
      .when('/lists/:id', {
        templateUrl: 'views/show.html',
        controller: 'ListCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  });
<|endoftext|>


<commit_before>'use strict';

angular.module('searchApp', [
  'ngCookies',
  'ngSanitize',
  'ngRoute',
  'ngAnimate',
  'ui.bootstrap'
])
  .config(function ($routeProvider, $locationProvider) {
    $routeProvider
      .when('/:site?', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl',
        reloadOnSearch: false,
      })
      .when('/embed', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl',
        reloadOnSearch: false,
      })
      .when('/basic/search', {
        templateUrl: 'views/basic-search.html',
        controller: 'BasicSearchCtrl',
      })
      .otherwise({
        redirectTo: '/'
      });

      // enable html5 mode
      //$locationProvider.html5Mode(true).hashPrefix('!');

  });
<commit_msg>remove basic-search endpoint<commit_after>'use strict';

angular.module('searchApp', [
  'ngCookies',
  'ngSanitize',
  'ngRoute',
  'ngAnimate',
  'ui.bootstrap'
])
  .config(function ($routeProvider, $locationProvider) {
    $routeProvider
      .when('/:site?', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl',
        reloadOnSearch: false,
      })
      .when('/embed', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl',
        reloadOnSearch: false,
      })
      .otherwise({
        redirectTo: '/'
      });

      // enable html5 mode
      //$locationProvider.html5Mode(true).hashPrefix('!');

  });
<|endoftext|>


<commit_before>var glide = glide || {};

glide.duration = 2000;
glide.picsJson = "pics.json";

glide.nextPic = function () {
    if (glide.i == glide.max) {
        glide.i = 0;
    } else {
        glide.i++;
    }
    return [{"key": glide.i, "src": glide.dataset.pics[glide.i]}];
};

glide.prevPic = function () {
    if (glide.i == 0) {
        glide.i = glide.max;
    } else {
        glide.i--;
    }
    return [{"key": glide.i, "src": glide.dataset.pics[glide.i]}];
};

glide.key = function (d) {
    return d.key;
};

glide.calcImgPosAndDims = function (img) {

    var height, width, x, y;

    if (img != null) {
        var h = img.naturalHeight;
        var w = img.naturalWidth;

        var wh = window.innerHeight;
        var ww = window.innerWidth;

        if (h <= wh && w <= ww) {          // image fits
            height = h;
            width = w;
        } else {                           // scale
            var widthScale = ww / w;
            var heightScale = wh / h;
            var scale = Math.min(widthScale, heightScale);
            width = Math.round(w * scale);
            height = Math.round(h * scale);
        }

        x = (ww - width) / 2;
        y = (wh - height) / 2;
    }

    return {"width": width, "height": height, "x": x, "y": y};
};

glide.loadPic = function (nextPicSpec, pics) {
    var img = new Image();
    img.onload = function () {
        var posAndDims = glide.calcImgPosAndDims(img);
        pics.enter()
           .append("image")
           .attr("xlink:href", function(d) { return d.src })
           .attr("id", function(d) { return "pic_" + d.key })
           .transition()
           .duration(glide.duration)
           .attr("width", posAndDims.width)
           .attr("height", posAndDims.height)
           .attr("x", posAndDims.x)
           .attr("y", posAndDims.y);
    };
    img.src = nextPicSpec[0].src;
}

glide.setupCanvas = function () {
    glide.svg = d3.select("body")
                  .append("svg")
                  .attr("width", window.innerWidth)
                  .attr("height", window.innerHeight)
                  .attr("id", "canvas");
};

glide.nextSlide = function () {
    // get pic...
    var nextPicSpec = glide.nextPic();

    // show slide...
    glide.showSlide(nextPicSpec);
};

glide.prevSlide = function () {
    // get pic...
    var nextPicSpec = glide.prevPic();

    // show slide...
    glide.showSlide(nextPicSpec);
};

glide.showSlide = function (nextPicSpec) {

    // select pics
    var pics = glide.svg.selectAll("image")
                        .data(nextPicSpec, glide.key);

    // remove old pic (if exists)
    pics.exit()
        .transition()
        .duration(glide.duration)
        .attr("x", window.innerWidth + 10)
        .remove();

    // load new pic
    glide.loadPic(nextPicSpec, pics);
};

// On click on body:
d3.select("body").on("click", function(e) {
    glide.nextSlide();
});

// On key press:
document.onkeypress = function (e) {
    e = e || window.event;
    switch (e.key) {
    case " ":   // Space
        glide.nextSlide();
      break;
    case "Backspace":
      glide.prevSlide();
      break;
    case "ArrowDown":
      glide.prevSlide();
      break;
    case "ArrowUp":
      glide.nextSlide();
      break;
    case "ArrowLeft":
      glide.prevSlide();
      break;
    case "ArrowRight":
      glide.nextSlide();
      break;
    case "Enter":
      glide.nextSlide();
      break;
    default:
      return;
  }
};

// On page load:
d3.json(glide.picsJson, function(data) {
    glide.dataset = data;
    glide.max = glide.dataset.pics.length - 1;
    glide.i = -1;
    glide.svg = null;
    glide.setupCanvas();
    glide.nextSlide();
});
<commit_msg>added support for window resizing<commit_after>var glide = glide || {};

glide.duration = 2000;
glide.picsJson = "pics.json";

glide.nextPic = function () {
    if (glide.i == glide.max) {
        glide.i = 0;
    } else {
        glide.i++;
    }
    return [{"key": glide.i, "src": glide.dataset.pics[glide.i]}];
};

glide.prevPic = function () {
    if (glide.i == 0) {
        glide.i = glide.max;
    } else {
        glide.i--;
    }
    return [{"key": glide.i, "src": glide.dataset.pics[glide.i]}];
};

glide.key = function (d) {
    return d.key;
};

glide.calcImgPosAndDims = function (img) {

    var height, width, x, y;

    if (img != null) {  // new image
        glide.naturalHeight = img.naturalHeight;
        glide.naturalWidth = img.naturalWidth;
    }

    var wh = window.innerHeight;
    var ww = window.innerWidth;

    if (glide.naturalHeight <= wh && glide.naturalWidth <= ww) {  // image fits
        height = glide.naturalHeight;
        width = glide.naturalWidth;
    } else {    // scale
        var widthScale = ww / glide.naturalWidth;
        var heightScale = wh / glide.naturalHeight;
        var scale = Math.min(widthScale, heightScale);
        width = Math.round(glide.naturalWidth * scale);
        height = Math.round(glide.naturalHeight * scale);
    }

    x = (ww - width) / 2;
    y = (wh - height) / 2;

    return { "width": width,
             "height": height,
             "x": x,
             "y": y };
};

glide.loadPic = function (nextPicSpec, pics) {
    var img = new Image();
    img.onload = function () {
        var posAndDims = glide.calcImgPosAndDims(img);
        pics.enter()
           .append("image")
           .attr("xlink:href", function(d) { return d.src })
           .attr("id", function(d) { return "pic_" + d.key })
           .transition()
           .duration(glide.duration)
           .attr("width", posAndDims.width)
           .attr("height", posAndDims.height)
           .attr("x", posAndDims.x)
           .attr("y", posAndDims.y);
    };
    img.src = nextPicSpec[0].src;
}

glide.setupCanvas = function () {
    glide.svg = d3.select("body")
                  .append("svg")
                  .attr("width", window.innerWidth)
                  .attr("height", window.innerHeight)
                  .attr("id", "canvas");
};

glide.nextSlide = function () {
    // get pic...
    var nextPicSpec = glide.nextPic();

    // show slide...
    glide.showSlide(nextPicSpec);
};

glide.prevSlide = function () {
    // get pic...
    var nextPicSpec = glide.prevPic();

    // show slide...
    glide.showSlide(nextPicSpec);
};

glide.showSlide = function (nextPicSpec) {

    // select pics
    var pics = glide.svg.selectAll("image")
                        .data(nextPicSpec, glide.key);

    // remove old pic (if exists)
    pics.exit()
        .transition()
        .duration(glide.duration)
        .attr("x", window.innerWidth + 10)
        .remove();

    // load new pic
    glide.loadPic(nextPicSpec, pics);
};

// On click on body:
d3.select("body").on("click", function(e) {
    glide.nextSlide();
});

// On key press:
document.onkeypress = function (e) {
    e = e || window.event;
    switch (e.key) {
    case " ":   // Space
        glide.nextSlide();
      break;
    case "Backspace":
      glide.prevSlide();
      break;
    case "ArrowDown":
      glide.prevSlide();
      break;
    case "ArrowUp":
      glide.nextSlide();
      break;
    case "ArrowLeft":
      glide.prevSlide();
      break;
    case "ArrowRight":
      glide.nextSlide();
      break;
    case "Enter":
      glide.nextSlide();
      break;
    default:
      return;
  }
};

// On window resize:
window.onresize = function(e) {

    // resize canvas
    glide.svg.attr("width", window.innerWidth)
             .attr("height", window.innerHeight);

    // resize pic
    var posAndDims = glide.calcImgPosAndDims();
    glide.svg.selectAll("image")
           .attr("width", posAndDims.width)
           .attr("height", posAndDims.height)
           .attr("x", posAndDims.x)
           .attr("y", posAndDims.y);
};

// On page load:
d3.json(glide.picsJson, function(data) {
    glide.dataset = data;
    glide.max = glide.dataset.pics.length - 1;
    glide.i = -1;
    //glide.svg = null;
    glide.setupCanvas();
    glide.nextSlide();
});
<|endoftext|>


<commit_before>/*
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/

(function(document) {
	'use strict';

	// Grab a reference to our auto-binding template
	// and give it some initial binding values
	// Learn more about auto-binding templates at http://goo.gl/Dx1u2g

	let app = document.querySelector('#app');
	/**
	 * localization start
	 */

	// // for dom if binding, if localization data is not ready then main dom should not render
	// // just render setting and toast boxes
	// app.localizationReady =false;

	// //get global variable
	// app.getGlobalValues = function(){
	// 	var setting = document.querySelector('#setting');
	// 	if(setting.globals){
	// 		// console.log(setting.globals);
	// 		app.basicUrl = setting.globals.basicUrl;
	// 		app.user = setting.globals.user;
	// 		app.locale = setting.globals.locale;
	// 	};
	// };
	// //get locale from user
	// app.getUserLocale = function () {
	// 	 return app.locale?app.locale:null;
	// };

	// //get locale from browser
	// app.getBrowserLocale = function () {
	// 	var locale;

	// 	locale = navigator.language||navigator.userLanguage;
	// 	locale = locale=="ko"?"ko-KR": locale;

	// 	return  locale;
	// };
	// /**
	//  * make locale value
	//  */
	// app.getLocale = function (user) {
	// 	app.locale = app.getUserLocale()?app.getUserLocale():app.getBrowserLocale();
	// 	return app.locale;
	// };

	// /**
	//  * for localization xhr request prameters, use terminologies/resource
	//  */
	// app.getRequestValue = function(){
	// 	var requestValue= {};
	// 	if(app.user){
	// 		requestValue = {"domain" : app.user.domain_id,
	// 						"locale" : app.getLocale()};
	// 	}else{
	// 		requestValue = {"domian":1}
	// 	}

	// 	return JSON.stringify(requestValue);
	// };
	// /**
	//  * compute terminologies url with app.globals.basicUrl
	//  */
	// app.computeUrl = function(){
	// 	return app.basicUrl+'/terminologies/resource';
	// };
	// *
	//  * get language information from server

	// app.getLanguageInfo = function () {
	// 	//1. a sign global values to app;
	// 	app.getGlobalValues();

	// 	//2. create xhr requesst
	// 	var xhr = new XMLHttpRequest();
	// 	xhr.open('POST', app.computeUrl() , true);
	// 	xhr.setRequestHeader("Content-type", "application/json");
	// 	xhr.withCredentials = true;

	// 	//3. make domain object and send request
	// 	xhr.send(app.getRequestValue());

	// 	//4. monitor xhr request response and status, change localization ready value to true and
	// 	//   let index file to render menu and main contents
	// 	xhr.onreadystatechange = function (Evt) {
	// 		if (xhr.readyState == 4) {
	// 			if(xhr.status == 200){
	// 				app.langs = JSON.parse(xhr.responseText);
	// 				app.terminologies = app.langs[app.getLocale()];
	// 				app.localizationReady =true;
	// 			}else{
	// 				// console.log('Error localization xhr page');
	// 				app.$.toast.text = 'Error localization xhr page';
 //    				app.$.toast.open();
	// 			}
	// 		}
	// 	};
	// };

	// /**
	//  * parameter with category and keyname
	//  * returns translated value, if there's not translated data return "categroy.keyname"
	//  */
	// app.getTransaltedString = function (category, keyname){
	// 	var result = '"'+ category + '.'+ keyname+'"';
	// 	var lang = app.terminologies;

	// 	if(lang){
	// 		if(lang[category]&&lang[category][keyname]){
	// 			result = lang[category][keyname]
	// 		}
	// 	}else{
	// 		app.$.toast.text = 'Translate object is not assigned!!';
	// 		app.$.toast.open();
	// 	}

	// 	return result;
	// };

	/** localization finish*/

	app.displayInstalledToast = () => {
		// Check to make sure caching is actually enabled—it won't be in the dev environment.
		if (!Polymer.dom(document).querySelector('platinum-sw-cache').disabled) {
			Polymer.dom(document).querySelector('#toast').text = 'Caching complete! This app will work offline.';
			Polymer.dom(document).querySelector('#toast').show();
		}
	};

	// Listen for template bound event to know when bindings
	// have resolved and content has been stamped to the page
	app.addEventListener('dom-change', () => {
		// console.log('Our app is ready to rock!');
		// console.log(setting.globa)
		// app.getLanguageInfo();
		// app.localizationReady =true;
	});

	// See https://github.com/Polymer/polymer/issues/1381
	window.addEventListener('WebComponentsReady', () => {
		I18nMsg.lang = dataGlobal.locale || document.documentElement.lang;
		I18nMsg.url = dataGlobal.basicUrl
		I18nMsg.domain = dataGlobal.user.domain_id||'1';
    	// Platform.performMicrotaskCheckpoint();
		/* imports are loaded and elements have been registered */
		// console.log('Our web components are ready!');
	});

	// Main area's paper-scroll-header-panel custom condensing transformation of
	// the appName in the middle-container and the bottom title in the bottom-container.
	// The appName is moved to top and shrunk on condensing. The bottom sub title
	// is shrunk to nothing on condensing.
	window.addEventListener('paper-header-transform', e => {
		let appName = Polymer.dom(document).querySelector('.Main-headerTitle');
		let middleContainer = Polymer.dom(document).querySelector('.Main-headerMiddleContent');
		let bottomContainer = Polymer.dom(document).querySelector('.Main-headerBottomContent');
		let detail = e.detail;
		let heightDiff = detail.height - detail.condensedHeight;
		let yRatio = Math.min(1, detail.y / heightDiff);
		let maxMiddleScale = 0.50;  // appName max size when condensed. The smaller the number the smaller the condensed size.
		let scaleMiddle = Math.max(maxMiddleScale, (heightDiff - detail.y) / (heightDiff / (1-maxMiddleScale))  + maxMiddleScale);
		let scaleBottom = 1 - yRatio;

		// Move/translate middleContainer
		Polymer.Base.transform(`translate3d(0,${yRatio * 100}%,0)`, middleContainer);

		// Scale bottomContainer and bottom sub title to nothing and back
		Polymer.Base.transform(`scale(${scaleBottom}) translateZ(0)`, bottomContainer);

		// Scale middleContainer appName
		Polymer.Base.transform(`scale(${scaleMiddle}) translateZ(0)`, appName);
	});

	// Close drawer after menu item is selected if drawerPanel is narrow
	app.onDataRouteClick = function() {
		let drawerPanel = Polymer.dom(document).querySelector('#paperDrawerPanel');
		if (drawerPanel.narrow) {
			drawerPanel.closeDrawer();
		}
	};

	// Hide toastConfirm after tap on OK button
	app.onToastConfirmTap = () => app.$.toastConfirm.hide();

	// Scroll page to top and expand header
	app.scrollPageToTop = () => {
		app.$.headerPanelMain.scrollToTop(true)
	};

})(document);
<commit_msg>clear old translate method<commit_after>/*
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/

(function(document) {
	'use strict';

	// Grab a reference to our auto-binding template
	// and give it some initial binding values
	// Learn more about auto-binding templates at http://goo.gl/Dx1u2g

	let app = document.querySelector('#app');

	app.displayInstalledToast = () => {
		// Check to make sure caching is actually enabled—it won't be in the dev environment.
		if (!Polymer.dom(document).querySelector('platinum-sw-cache').disabled) {
			Polymer.dom(document).querySelector('#toast').text = 'Caching complete! This app will work offline.';
			Polymer.dom(document).querySelector('#toast').show();
		}
	};

	// Listen for template bound event to know when bindings
	// have resolved and content has been stamped to the page
	app.addEventListener('dom-change', () => {

	});

	// See https://github.com/Polymer/polymer/issues/1381
	window.addEventListener('WebComponentsReady', () => {
		I18nMsg.lang = dataGlobal.locale || document.documentElement.lang;
		I18nMsg.url = dataGlobal.basicUrl
		I18nMsg.domain = dataGlobal.user.domain_id||'1';
    	// Platform.performMicrotaskCheckpoint();
		/* imports are loaded and elements have been registered */
		// console.log('Our web components are ready!');
	});

	// Main area's paper-scroll-header-panel custom condensing transformation of
	// the appName in the middle-container and the bottom title in the bottom-container.
	// The appName is moved to top and shrunk on condensing. The bottom sub title
	// is shrunk to nothing on condensing.
	window.addEventListener('paper-header-transform', e => {
		let appName = Polymer.dom(document).querySelector('.Main-headerTitle');
		let middleContainer = Polymer.dom(document).querySelector('.Main-headerMiddleContent');
		let bottomContainer = Polymer.dom(document).querySelector('.Main-headerBottomContent');
		let detail = e.detail;
		let heightDiff = detail.height - detail.condensedHeight;
		let yRatio = Math.min(1, detail.y / heightDiff);
		let maxMiddleScale = 0.50;  // appName max size when condensed. The smaller the number the smaller the condensed size.
		let scaleMiddle = Math.max(maxMiddleScale, (heightDiff - detail.y) / (heightDiff / (1-maxMiddleScale))  + maxMiddleScale);
		let scaleBottom = 1 - yRatio;

		// Move/translate middleContainer
		Polymer.Base.transform(`translate3d(0,${yRatio * 100}%,0)`, middleContainer);

		// Scale bottomContainer and bottom sub title to nothing and back
		Polymer.Base.transform(`scale(${scaleBottom}) translateZ(0)`, bottomContainer);

		// Scale middleContainer appName
		Polymer.Base.transform(`scale(${scaleMiddle}) translateZ(0)`, appName);
	});

	// Close drawer after menu item is selected if drawerPanel is narrow
	app.onDataRouteClick = function() {
		let drawerPanel = Polymer.dom(document).querySelector('#paperDrawerPanel');
		if (drawerPanel.narrow) {
			drawerPanel.closeDrawer();
		}
	};

	// Hide toastConfirm after tap on OK button
	app.onToastConfirmTap = () => app.$.toastConfirm.hide();

	// Scroll page to top and expand header
	app.scrollPageToTop = () => {
		app.$.headerPanelMain.scrollToTop(true)
	};

})(document);
<|endoftext|>