<commit_before>// Incident object definition.
function Incident(incidentData) {
	this.ID = incidentData[14];
	this.Address = incidentData[8];
	this.Category = incidentData[9];
	this.DateLogged = new Date(incidentData[10] * 1000);
	this.Lat = incidentData[11];
	this.Lng = incidentData[12];
};

// Store all fetched incident objects in this global array.
window.incidents = [];

var log = {
	RefreshData: function() {
		var dataSource = "http://data.seattle.gov/api/views/kzjm-xkqj/rows.json?jsonp=?&max_rows=100";
		var spinner = $('#spinner');

		$.ajax({
			type : "GET",
			dataType : "JSONP",
			url : dataSource,
			beforeSend: function () {
				spinner.slideDown('slow');
			},
			success: function(result) {
				$.each( result.data, function( i, incidentData ) {
					var thisIncident = new Incident(incidentData);
					window.incidents.push(thisIncident);
				});
			},
			error: function(xhr, status, error) {
			  	console.log(JSON.parse(xhr.responseText));
			}
		}).complete(function(){
			spinner.slideUp('slow');
			log.RefreshTable();
			//Refresh feed every 5 minutes.
	        setTimeout(function(){log.RefreshData();}, 300000);
	    });
	},
	RefreshTable: function () {
		var tableData = [];

		for (var i = 0; i < window.incidents.length; i++) {
			var thisIncident = window.incidents[i];
			tableData.push('
' + thisIncident.ID + '	' + thisIncident.Category + '	' + thisIncident.Address + '	' + thisIncident.DateLogged.toLocaleTimeString() + ' ' + thisIncident.DateLogged.toLocaleDateString() + '
');
		}

		//First remove existing rows.
		$("#log").find('tr:gt(0)').remove();

		//Next append new data.
		$("#log").append(tableData.join(''));
	},
	GetIncident: function(incidentId) {
		if (window.incidents.length > 0) {
			//TODO: see if incident exists in array.
			for (var i = 0; i < window.incidents.length; i++) {
				if (window.incidents[i].ID == incidentId) {
					return incidents[i];
				}
			}
		}
		else {
			//TODO: Get JSON for a single incident.
		}

		return null;
	},
	GetMap: function(lat, lng, incidentId) {
		var incidentLatLng = new google.maps.LatLng(lat,lng);

		var mapOptions = {
		  center: incidentLatLng,
		  zoom: 16
		};

		window.map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

		// Add Marker.
		var marker = new google.maps.Marker({
		    position: incidentLatLng,
		    animation: google.maps.Animation.DROP,
		    map: map,
		    title:("#" + incidentId)
		});

		// Add InfoWindow.
		marker.info = new google.maps.InfoWindow({
		  content: 'Incident: ' + incidentId
		});

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

		// Invert colors.
		// reference: https://developers.google.com/maps/documentation/javascript/styling
		var styles = [
		  {
		    "stylers": [
	      		{ "invert_lightness": true }
	    	]
		  }
		];

		map.setOptions({styles: styles});
	}
};

$(document).ready(function(){
	log.RefreshData();
});

$("#refresh").on('click', function(event){
	event.preventDefault();
	log.RefreshData();
});

$('#incident-modal').on('show.bs.modal', function (e) {
  	var incidentRow = $(e.relatedTarget);
  	var incident = log.GetIncident(incidentRow.attr('id'));
  	var modalWindowTitle = $('#incident-modal-title');

  	log.GetMap(incident.Lat, incident.Lng, incident.ID);
  	modalWindowTitle.text(incident.ID + ": " + incident.Category + ", " + incident.Address);
});

$('#incident-modal').on('shown.bs.modal', function (e) {
	//Resize: http://stackoverflow.com/questions/11742839/showing-a-google-map-in-a-modal-created-with-twitter-bootstrap
	//Recenter: http://stackoverflow.com/a/10002547/1754037
	var incidentRow = $(e.relatedTarget);
  	var incident = log.GetIncident(incidentRow.attr('id'));
	var center = new google.maps.LatLng(incident.Lat, incident.Lng);

    google.maps.event.trigger(document.getElementById("map-canvas"), "resize");
    window.map.setCenter(center);
});<commit_msg>Added sorting to incident array and check if exists before pushing on DataRefresh<commit_after>// Incident object definition.
function Incident(incidentData) {
	this.ID = incidentData[14];
	this.Address = incidentData[8];
	this.Category = incidentData[9];
	this.DateLogged = new Date(incidentData[10] * 1000);
	this.Lat = incidentData[11];
	this.Lng = incidentData[12];
};

// Store all fetched incident objects in this global array.
window.incidents = [];

var log = {
	RefreshData: function() {
		var dataSource = "http://data.seattle.gov/api/views/kzjm-xkqj/rows.json?jsonp=?&max_rows=100";
		var spinner = $('#spinner');

		$.ajax({
			type : "GET",
			dataType : "JSONP",
			url : dataSource,
			beforeSend: function () {
				spinner.slideDown('slow');
			},
			success: function(result) {
				$.each( result.data, function( i, incidentData ) {
					var thisIncident = new Incident(incidentData);

					// Only push if there is not an object in the array with a matching IncidentID.
					if (!isIncidentLogged(thisIncident))
					{
						window.incidents.push(thisIncident);
					}
				});

				window.incidents.sort(compareIncidentsDateLogged)
			},
			error: function(xhr, status, error) {
			  	console.log(JSON.parse(xhr.responseText));
			}
		}).complete(function(){
			spinner.slideUp('slow');
			log.RefreshTable();
			//Refresh feed every 5 minutes.
	        setTimeout(function(){log.RefreshData();}, 300000);
	    });
	},
	RefreshTable: function () {
		var tableData = [];

		for (var i = 0; i < window.incidents.length; i++) {
			var thisIncident = window.incidents[i];
			tableData.push('
' + thisIncident.ID + '	' + thisIncident.Category + '	' + thisIncident.Address + '	' + thisIncident.DateLogged.toLocaleTimeString() + ' ' + thisIncident.DateLogged.toLocaleDateString() + '
');
		}

		//First remove existing rows.
		$("#log").find('tr:gt(0)').remove();

		//Next append new data.
		$("#log").append(tableData.join(''));
	},
	GetIncident: function(incidentId) {
		if (window.incidents.length > 0) {
			//TODO: see if incident exists in array.
			for (var i = 0; i < window.incidents.length; i++) {
				if (window.incidents[i].ID == incidentId) {
					return incidents[i];
				}
			}
		}
		else {
			//TODO: Get JSON for a single incident.
		}

		return null;
	},
	GetMap: function(lat, lng, incidentId) {
		var incidentLatLng = new google.maps.LatLng(lat,lng);

		var mapOptions = {
		  center: incidentLatLng,
		  zoom: 16
		};

		window.map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

		// Add Marker.
		var marker = new google.maps.Marker({
		    position: incidentLatLng,
		    animation: google.maps.Animation.DROP,
		    map: map,
		    title:("#" + incidentId)
		});

		// Add InfoWindow.
		marker.info = new google.maps.InfoWindow({
		  content: 'Incident: ' + incidentId
		});

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

		// Invert colors.
		// Reference: https://developers.google.com/maps/documentation/javascript/styling
		var styles = [
		  {
		    "stylers": [
	      		{ "invert_lightness": true }
	    	]
		  }
		];

		map.setOptions({styles: styles});
	}
};

// Reference: http://stackoverflow.com/questions/1129216/sorting-objects-in-an-array-by-a-field-value-in-javascript
function compareIncidentsDateLogged(a,b) {
  if (a.DateLogged > b.DateLogged)
     return -1;
  if (a.DateLogged < b.DateLogged)
    return 1;
  return 0;
}

function isIncidentLogged(incident) {
	for (var i = 0; i < window.incidents.length; i++)
	{
		if (window.incidents[i].ID == incident.ID)
		{
			return true;
		}
	}
	return false;
}

$(document).ready(function(){
	log.RefreshData();
});

$("#refresh").on('click', function(event){
	event.preventDefault();
	log.RefreshData();
});

$('#incident-modal').on('show.bs.modal', function (e) {
  	var incidentRow = $(e.relatedTarget);
  	var incident = log.GetIncident(incidentRow.attr('id'));
  	var modalWindowTitle = $('#incident-modal-title');

  	log.GetMap(incident.Lat, incident.Lng, incident.ID);
  	modalWindowTitle.text(incident.ID + ": " + incident.Category + ", " + incident.Address);
});

$('#incident-modal').on('shown.bs.modal', function (e) {
	// Resize: http://stackoverflow.com/questions/11742839/showing-a-google-map-in-a-modal-created-with-twitter-bootstrap
	// Recenter: http://stackoverflow.com/a/10002547/1754037
	var incidentRow = $(e.relatedTarget);
  	var incident = log.GetIncident(incidentRow.attr('id'));
	var center = new google.maps.LatLng(incident.Lat, incident.Lng);

    google.maps.event.trigger(document.getElementById("map-canvas"), "resize");
    window.map.setCenter(center);
});<|endoftext|>


<commit_before>var gravity = 0.25;
var velocity = -5;
var position = 200;
var rotation = 0;

$(document).ready(function() {
   var updaterate = 1000.0 / 60.0 ; //60 times a second
   setInterval(mainloop, updaterate);
});

function mainloop() {
   var player = $("#player");
   velocity += gravity;
   position += velocity;

   //bounce (for testing)
   if(position > (player.parent().height() - player.height()))
      velocity = -velocity;

   //rotation
   //-10 and over should be 15 degrees rotated up
   //0 should be flat (obviously)
   //10 and over should be totally face down
   rotation = (velocity / 10) * 90;
   if(rotation > 90)
      rotation = 90;

   player.css({ rotate: rotation });
   player.css('top', position +'px');
}

$(document).click(function(e) {
   //click?
   if (e.button == 0)
      playerJump();
});

$(document).keydown(function(e){
   //space bar!
   if(e.keyCode == 32)
       playerJump();
});

function playerJump()
{
   velocity = -6;
}<commit_msg>Changed to mousedown (for mobile)<commit_after>var gravity = 0.25;
var velocity = -5;
var position = 200;
var rotation = 0;

$(document).ready(function() {
   var updaterate = 1000.0 / 60.0 ; //60 times a second
   setInterval(mainloop, updaterate);
});

function mainloop() {
   var player = $("#player");
   velocity += gravity;
   position += velocity;

   //bounce (for testing)
   if(position > (player.parent().height() - player.height()))
      velocity = -velocity;

   //rotation
   //-10 and over should be 15 degrees rotated up
   //0 should be flat (obviously)
   //10 and over should be totally face down
   rotation = (velocity / 10) * 90;
   if(rotation > 90)
      rotation = 90;

   player.css({ rotate: rotation });
   player.css('top', position +'px');
}

$(document).mousedown(function(e) {
   //click?
   if (e.button == 0)
      playerJump();
});

$(document).keydown(function(e){
   //space bar!
   if(e.keyCode == 32)
       playerJump();
});

function playerJump()
{
   velocity = -6;
}<|endoftext|>


<commit_before>$(function(){

    var userName = window.location.hash.substr(1); //Get the section after hash tag from URL, e.g. index.html#Arik return 'Arik'
    if(userName === '') {
        alert('No selected');
    } else {

      $.get('/final-project-fullstack/php/myuser.php?user=' + userName, function(data) { //This code makes an HTTP request to /arik and puts the data in the 'data' variable

          console.log('Got data', data); //We just print whatever we got from the server

          //Basic info
          $('#intro header h1').text(data.basicInfo.firstName); //Let's use the data from server and pub it on page!
          $('#intro header h2').text(data.basicInfo.lastName);
          $('#intro header').append('
'+data.basicInfo.title+'
')

          $('#intro-me').append('
'+data.phone+'
')
          $('#intro-me').append('
'+data.area+'
')
          $('#intro-me').append('
'+data.email+'
')

		  //aboutme
		  $('#about p').text(data.about);

          //Social networks
          $ul = $('
', {
              'id': 'social-networks'
          });

          for(i in data.socialNetworks) { //We also got the social networks from the server, which is acceable from data.socialNetworks.
              var $templi = $('
');

              $templi.append('');
              $templi.append(''+data.socialNetworks[i].name+'');

              $templi.click(function(){
                  alert($(this).children('a').text() + ' clicked!');
              });

              //Add the new li element to the ul
              $ul.append($templi);
          }

          $ul.insertAfter('#intro');

      });

	  	$.get('/final-project-fullstack/php/proskills.php?user=' + userName, function(data)
       { //This code makes an HTTP request to /arik and puts the data in the 'data' variable

          console.log('Got data', data); //We just print whatever we got from the server

		  //clear "loading" text
		  $('#skillname').empty();
		  $('#skillvalue').empty();

		  for ($x = 0; $x <= data.length; $x++)
          {
			$('#skillname').append('
'+data[$x].skillname+'
');
			$('#skillvalue ').append('
<progress max=100 value='+data[$x].skillvalue+'></progress>
');
          }
       });

          $.get('/final-project-fullstack/php/perskills.php?user=' + userName, function(data)
         { //This code makes an HTTP request to /arik and puts the data in the 'data' variable

          console.log('Got data', data); //We just print whatever we got from the server
		  //clear "loading" text

		  for ( $x=0;$x <= data.length; $x++) {
			$('#skillnameper').append('
'+data[$x].skillname+'
');
			$('#skillvalueper ').append('
<progress max=100 value='+data[$x].skillvalue+'></progress>
');
			}
		});

    }

});
<commit_msg>js minor fix<commit_after>$(function(){

    var userName = window.location.hash.substr(1); //Get the section after hash tag from URL, e.g. index.html#Arik return 'Arik'
    if(userName === '') {
        alert('No selected');
    } else {

      $.get('/final-project-fullstack/php/myuser.php?user=' + userName, function(data) { //This code makes an HTTP request to /arik and puts the data in the 'data' variable

          console.log('Got data', data); //We just print whatever we got from the server

          //Basic info
          $('#intro header h1').text(data.basicInfo.firstName); //Let's use the data from server and pub it on page!
          $('#intro header h2').text(data.basicInfo.lastName);
          $('#intro header').append('
'+data.basicInfo.title+'
')

          $('#intro-me').append('
'+data.phone+'
')
          $('#intro-me').append('
'+data.area+'
')
          $('#intro-me').append('
'+data.email+'
')

		  //aboutme
		  $('#about p').text(data.about);

          //Social networks
          $ul = $('
', {
              'id': 'social-networks'
          });

          for(i in data.socialNetworks) { //We also got the social networks from the server, which is acceable from data.socialNetworks.
              var $templi = $('
');

              $templi.append('');
              $templi.append(''+data.socialNetworks[i].name+'');

              $templi.click(function(){
                  alert($(this).children('a').text() + ' clicked!');
              });

              //Add the new li element to the ul
              $ul.append($templi);
          }

          $ul.insertAfter('#intro');

      });

	  	$.get('/final-project-fullstack/php/proskills.php?user=' + userName, function(data)
       { //This code makes an HTTP request to /arik and puts the data in the 'data' variable

          console.log('Got data', data); //We just print whatever we got from the server

		  //clear "loading" text
		  $('#skillname').empty();
		  $('#skillvalue').empty();

		  for ($x = 0; $x <= data.length; $x++)
          {
			$('#skillname').append('
'+data[$x].skillname+'
');
			$('#skillvalue ').append('
<progress max=100 value='+data[$x].skillvalue+'></progress>
');
          }
       });

          $.get('/final-project-fullstack/php/perskills.php?user=' + userName, function(data)
         { //This code makes an HTTP request to /arik and puts the data in the 'data' variable

          console.log('Got data', data); //We just print whatever we got from the server
		  //clear "loading" text
		  $('#skillnameper').empty();
		  $('#skillvalueper').empty();

		  for ( $x=0;$x <= data.length; $x++) {
			$('#skillnameper').append('
'+data[$x].skillname+'
');
			$('#skillvalueper ').append('
<progress max=100 value='+data[$x].skillvalue+'></progress>
');
			}
		});

    }

});
<|endoftext|>


<commit_before>var App;

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

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

			t.start(r);
		});
	}

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

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

		var mods = Object.keys(r.modules);
		for(var i = 0, len = mods.length; i < len; i++){
			var k = mods[i];
			modules[k] = {nombre: k, url:r.modules_path};
		}

		var j = {name: 'Dress code', modules:modules, div:'#content', currentLang: lang};
		this.a = new AppSystem(j);
		App = this.a;

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

		dhtmlHistory.initialize();
		dhtmlHistory.addListener(t.handleHistory);

		this.a.init(function(){
			var initialModule = dhtmlHistory.getCurrentLocation();
			var module = (initialModule === '') ? 'backend' : initialModule;
			t.verifyIdentity(function(r){
				switch(r.success){
					case true:
						t.loadCategory('backend', function(){
							if(module !== 'backend' && module !== 'login'){
								t.loadCategory(module);
							}
						});
					break;
					case false:
						t.loadCategory('login');
					break;
				}
			});
		});
	};

	Main.prototype.verifyIdentity = function(callback) {
		callback = (typeof callback === 'function') ? callback : function(){};
		var j = {
			url: this.a._data.rest+'Members/',
			mode: 'GET',
			div: undefined,
			cache: true,
			response: 'object',
			headerValue: 'application/json'
		}
		new Vi(j).ajax(callback);
	};

	Main.prototype.handleURL = function(url) {
		url = url.match(/([^/]+)/gi);
		return url;
	};

	Main.prototype.handleHistory = function(newLocation, historyData) {
		if(typeof Application.a.current === 'object'){
			Application.loadCategory(newLocation);
		}
	};

	Main.prototype.activeMenuCategory = function(category) {
		this.clearMenu();
		var el = document.querySelector('#side-menu>li>a[data-module="'+category+'"]');
		if(el !== null){
			el = el.parentNode;
			el.className = 'active';
		}
	};

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

	Main.prototype.loadCategory = function(category, callback) {
		console.log('category', category);
		var url = this.handleURL(category);
		if(category !== 'backend'){
			dhtmlHistory.add(category, {message: "Module " +url[0]});

			this.activeMenuCategory(url[0]);
		}

		switch(category){
			case 'backend':
			case 'login':
			case 'setup':
				this.a.div = '#content';
			break;
			default:
				this.a.div = '#modules-content';
			break;
		}

		this.a.getModule(url[0]);
		this.a.current._url = url;

		if(category !== 'backend'){
			var t = this;
			$(this.a.div).fadeOut('fast', function(){
				t.a.current.start(function(){
					$(t.a.div).fadeIn('fast', function(){
						if(typeof callback === 'function'){
							callback();
						}
					});
				});
			});
		}else{
			this.a.current.start(function(){
				if(typeof callback === 'function'){
					callback();
				}
			});
		}
	};

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

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

		return l;
	};

	window.Application = new Main();
})();<commit_msg>Removed console log<commit_after>var App;

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

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

			t.start(r);
		});
	}

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

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

		var mods = Object.keys(r.modules);
		for(var i = 0, len = mods.length; i < len; i++){
			var k = mods[i];
			modules[k] = {nombre: k, url:r.modules_path};
		}

		var j = {name: 'Dress code', modules:modules, div:'#content', currentLang: lang};
		this.a = new AppSystem(j);
		App = this.a;

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

		dhtmlHistory.initialize();
		dhtmlHistory.addListener(t.handleHistory);

		this.a.init(function(){
			var initialModule = dhtmlHistory.getCurrentLocation();
			var module = (initialModule === '') ? 'backend' : initialModule;
			t.verifyIdentity(function(r){
				switch(r.success){
					case true:
						t.loadCategory('backend', function(){
							if(module !== 'backend' && module !== 'login'){
								t.loadCategory(module);
							}
						});
					break;
					case false:
						t.loadCategory('login');
					break;
				}
			});
		});
	};

	Main.prototype.verifyIdentity = function(callback) {
		callback = (typeof callback === 'function') ? callback : function(){};
		var j = {
			url: this.a._data.rest+'Members/',
			mode: 'GET',
			div: undefined,
			cache: true,
			response: 'object',
			headerValue: 'application/json'
		}
		new Vi(j).ajax(callback);
	};

	Main.prototype.handleURL = function(url) {
		url = url.match(/([^/]+)/gi);
		return url;
	};

	Main.prototype.handleHistory = function(newLocation, historyData) {
		if(typeof Application.a.current === 'object'){
			Application.loadCategory(newLocation);
		}
	};

	Main.prototype.activeMenuCategory = function(category) {
		this.clearMenu();
		var el = document.querySelector('#side-menu>li>a[data-module="'+category+'"]');
		if(el !== null){
			el = el.parentNode;
			el.className = 'active';
		}
	};

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

	Main.prototype.loadCategory = function(category, callback) {
		var url = this.handleURL(category);
		if(category !== 'backend'){
			dhtmlHistory.add(category, {message: "Module " +url[0]});
			this.activeMenuCategory(url[0]);
		}

		switch(category){
			case 'backend':
			case 'login':
			case 'setup':
				this.a.div = '#content';
			break;
			default:
				this.a.div = '#modules-content';
			break;
		}

		this.a.getModule(url[0]);
		this.a.current._url = url;

		if(category !== 'backend'){
			var t = this;
			$(this.a.div).fadeOut('fast', function(){
				t.a.current.start(function(){
					$(t.a.div).fadeIn('fast', function(){
						if(typeof callback === 'function'){
							callback();
						}
					});
				});
			});
		}else{
			this.a.current.start(function(){
				if(typeof callback === 'function'){
					callback();
				}
			});
		}
	};

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

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

		return l;
	};

	window.Application = new Main();
})();<|endoftext|>


<commit_before>function on_index_html(html) {
    // Look for patterns like:  href="couchbase-server-community_x86_64_2.0.0c-709-rel.rpm.manifest.xml"

    var urls = {}
    var hier = {} // Hierarchy of maps, keyed by name / version / build / arch / pkg.

    var hrefs = html.match(/href="[^\"]+\.manifest\.xml"/g);
    for (var i = 0; i < hrefs.length; i++) {
        var href = hrefs[i];
        var url = href.split('"')[1];
        var s = url.split('_');
        var name = s[0];
        var arch = s.slice(1, s.length - 1).join("_");
        var suffix = s[s.length - 1].split('-');
        var version = suffix[0];
        var build = suffix[1];
        if (suffix && suffix[2]) {
            var pkg = suffix[2].split('.')[suffix[2].split('.').length - 3];

            var p = { "url": url,
                      "name": name,
                      "version": version,
                      "build": build,
                      "arch": arch,
                      "pkg": pkg };
            urls[url] = p;

            add_entry(hier, [name, version, build, arch, pkg], p);
        }
    }

    var r = gen(hier, [false, false, true, true]);
    var t = [];
    var names = map_keys(hier).sort();
    for (var i = 0; i < names.length; i++) {
        t.push('
' + names[i] + '
');
    }
    var h = '
' + t.join('') + '
';

    h = h + '
' +
        '
name	version	build	arch	pkg
' +
        '
' + r.join('') + '

';

    $('#content').html(h);
}

function add_entry(hier, path, val) {
    for (var i = 0; i < path.length - 1; i++) {
        var m = hier[path[i]];
        if (!m) {
            m = hier[path[i]] = {};
        }
        hier = m;
    }
    hier[path[path.length - 1]] = val;
}

function gen(hier, reversals) {
    var keys = map_keys(hier).sort();
    if (reversals[0]) {
        keys = keys.reverse();
    }
    var child_reversals = reversals.slice(1);
    var r = [];
    for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        var val = hier[key];
        if (reversals.length > 0) {
            var child_r = gen(val, child_reversals);
            if (i > 0) {
                r.push('

');
            }
            var child_n = (child_r.join('').match(/
/g) || []).length + 1;
            r.push('' + key + '	');
            r = r.concat(child_r);
        } else {
            if (val.url) {
                if (i == 0) {
                    r.push('manifest	');
                }
                var pkg_url = val.url.replace('.manifest.xml', '');
                r.push('' + key + '	');
            }
        }
    }
    return r;
}

function map_keys(m) {
    var keys = [];
    for (var key in m) {
        keys[keys.length] = key;
    }
    return keys;
}

function on_ready() {
    if (document.URL.match(/^file:/)) {
        on_index_html('' +
                      '' +
                      '' +
                      '' +
                      '' +
                      '' +
                      '' +
                      '' +
                      '');
        return;
    }

    $.get("../../index.html", null,
          function(response, textStatus, jqXHR){
              on_index_html(response);
          });
}

$(document).ready(on_ready);
<commit_msg>reverse versions again<commit_after>function on_index_html(html) {
    // Look for patterns like:  href="couchbase-server-community_x86_64_2.0.0c-709-rel.rpm.manifest.xml"

    var urls = {}
    var hier = {} // Hierarchy of maps, keyed by name / version / build / arch / pkg.

    var hrefs = html.match(/href="[^\"]+\.manifest\.xml"/g);
    for (var i = 0; i < hrefs.length; i++) {
        var href = hrefs[i];
        var url = href.split('"')[1];
        var s = url.split('_');
        var name = s[0];
        var arch = s.slice(1, s.length - 1).join("_");
        var suffix = s[s.length - 1].split('-');
        var version = suffix[0];
        var build = suffix[1];
        if (suffix && suffix[2]) {
            var pkg = suffix[2].split('.')[suffix[2].split('.').length - 3];

            var p = { "url": url,
                      "name": name,
                      "version": version,
                      "build": build,
                      "arch": arch,
                      "pkg": pkg };
            urls[url] = p;

            add_entry(hier, [name, version, build, arch, pkg], p);
        }
    }

    var r = gen(hier, [false, true, true, true]);
    var t = [];
    var names = map_keys(hier).sort();
    for (var i = 0; i < names.length; i++) {
        t.push('
' + names[i] + '
');
    }
    var h = '
' + t.join('') + '
';

    h = h + '
' +
        '
name	version	build	arch	pkg
' +
        '
' + r.join('') + '

';

    $('#content').html(h);
}

function add_entry(hier, path, val) {
    for (var i = 0; i < path.length - 1; i++) {
        var m = hier[path[i]];
        if (!m) {
            m = hier[path[i]] = {};
        }
        hier = m;
    }
    hier[path[path.length - 1]] = val;
}

function gen(hier, reversals) {
    var keys = map_keys(hier).sort();
    if (reversals[0]) {
        keys = keys.reverse();
    }
    var child_reversals = reversals.slice(1);
    var r = [];
    for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        var val = hier[key];
        if (reversals.length > 0) {
            var child_r = gen(val, child_reversals);
            if (i > 0) {
                r.push('

');
            }
            var child_n = (child_r.join('').match(/
/g) || []).length + 1;
            r.push('' + key + '	');
            r = r.concat(child_r);
        } else {
            if (val.url) {
                if (i == 0) {
                    r.push('manifest	');
                }
                var pkg_url = val.url.replace('.manifest.xml', '');
                r.push('' + key + '	');
            }
        }
    }
    return r;
}

function map_keys(m) {
    var keys = [];
    for (var key in m) {
        keys[keys.length] = key;
    }
    return keys;
}

function on_ready() {
    if (document.URL.match(/^file:/)) {
        on_index_html('' +
                      '' +
                      '' +
                      '' +
                      '' +
                      '' +
                      '' +
                      '' +
                      '');
        return;
    }

    $.get("../../index.html", null,
          function(response, textStatus, jqXHR){
              on_index_html(response);
          });
}

$(document).ready(on_ready);
<|endoftext|>


<commit_before>var backEventListener = null;

var unregister = function() {
    if ( backEventListener !== null ) {
        document.removeEventListener( 'tizenhwkey', backEventListener );
        backEventListener = null;
        window.tizen.application.getCurrentApplication().exit();
    }
}

//Initialize function
var init = function () {
    // register once
    if ( backEventListener !== null ) {
        return;
    }

    // TODO:: Do your initialization job
    console.log("init() called");

    var backEvent = function(e) {
        if ( e.keyName == "back" ) {
            try {
                if ( $.mobile.urlHistory.activeIndex <= 0 ) {
                    // if first page, terminate app
                    unregister();
                } else {
                    // move previous page
                    $.mobile.urlHistory.activeIndex -= 1;
                    $.mobile.urlHistory.clearForward();
                    window.history.back();
                }
            } catch( ex ) {
                unregister();
            }
        }
    }

    // add eventListener for tizenhwkey (Back Button)
    document.addEventListener( 'tizenhwkey', backEvent );
    backEventListener = backEvent;

	/**
	 * TwitterのOauth認証する
	 *
	 */

	$("#oauthButton").click(function(){
	    console.log("oauthButton clicked");
		oauthFunc(function(oauth){
				alert("Successed!");
			},function(e){
				alert("Failed!");
			});
	});
};

$(document).bind( 'pageinit', init );
$(document).unload( unregister );<commit_msg>つぶやき検索に成功 ・キーワードは仮で固定<commit_after>var backEventListener = null;

var unregister = function() {
    if ( backEventListener !== null ) {
        document.removeEventListener( 'tizenhwkey', backEventListener );
        backEventListener = null;
        window.tizen.application.getCurrentApplication().exit();
    }
}

//Initialize function
var init = function () {
    // register once
    if ( backEventListener !== null ) {
        return;
    }

    // TODO:: Do your initialization job
    console.log("init() called");

    var backEvent = function(e) {
        if ( e.keyName == "back" ) {
            try {
                if ( $.mobile.urlHistory.activeIndex <= 0 ) {
                    // if first page, terminate app
                    unregister();
                } else {
                    // move previous page
                    $.mobile.urlHistory.activeIndex -= 1;
                    $.mobile.urlHistory.clearForward();
                    window.history.back();
                }
            } catch( ex ) {
                unregister();
            }
        }
    }

    // add eventListener for tizenhwkey (Back Button)
    document.addEventListener( 'tizenhwkey', backEvent );
    backEventListener = backEvent;

	/**
	 * TwitterのOauth認証する
	 *
	 */

	$("#oauthButton").click(function(){
	    console.log("oauthButton clicked");
		oauthFunc(function(oauth){
			    console.log("oauthFunc Successed!");
				oauth.get("https://api.twitter.com/1.1/search/tweets.json?q=%23githubjp",
						function(data){
							console.log(data.text);
						},
						function(e){
							console.log("oauth.get Failed!");
							console.error(e);
						});
			},function(e){
				console.log("oauthFunc Failed!");
				console.error(e);
			});
	});

};
$(document).bind( 'pageinit', init );
$(document).unload( unregister );<|endoftext|>


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

  var ANNOTATION_TYPE_VIDEO = 'video';
  var ANNOTATION_TYPE_TEXT = 'text';
  var ANNOTATION_TYPE_AUDIO = 'audio';

  // Create annotations manifest
  var annotations = [];
  var videoPlayer = {};

  var appWidth = $('body').css('width');
  var appHeight = $('body').css('height');

  function init() {

    setupFullscreenVideo();
    setupScreenSaver();

    var paintingImg = $('.painting img').first();

    $('.annotations button').each(function() {

      var mediaPath = $(this).attr('media-path');
      var a = { id: $(this).attr('id'),
                btn: this,
                x: parseInt($(this).attr('annotation-x'), 10),
                y: parseInt($(this).attr('annotation-y'), 10),
                type: getMediaType(mediaPath),
                path: mediaPath,
      };

      annotations.push(a);

      // Position & style button (offset for button size)
      $(this).css('left', a.x - 20);
      $(this).css('top', a.y - 20);
      $(this).addClass('btn');
      $(this).append('');

      var cutout = $(this).attr('cutout');
      if (cutout === undefined) {
        cutout = {x:-70, y: -70, w: 140, h: 140};
      } else {
        cutout = getProperJSON(cutout);
      }

      a.cutRect = cutout;
      a.cutout = getCutoutFromImage(a.id, paintingImg, a.x + a.cutRect.x, a.y + a.cutRect.y, a.cutRect.w, a.cutRect.h);

    });

    // Create hit regions by building Vernoi diagram
    console.log(appWidth, appHeight);
    var svgElement = '<svg id="veronoi_ui" width="' + appWidth + '" height="' + appHeight + '"></svg>';
    $('.annotations').prepend(svgElement);

    // Allow time for size recalc...
    setTimeout(function() {
      var vornoi = new VoronoiLayer(annotations, $('#veronoi_ui'), onAnnotationSelected, onAnnotationActive, false);
    }, 200);

    cutoutsGoHome();

  }

  var onAnnotationActive = function(annId, annBtn) {

    for (var i = 0; i < annotations.length; i++) {

      var a = annotations[i];

      if (annId === a.id) {

        $(a.btn).addClass('active');

        break;
      }

    }

  };

  var onAnnotationSelected = function(annId, annBtn) {

    console.log('annotationSelected(): ' + annId);

    for (var i = 0; i < annotations.length; i++) {

      var a = annotations[i];

      if (annId === a.id) {

        // Block mouse/touch interaction
        $('.overlay').css('pointer-events', 'auto');
        $(a.btn).removeClass('active');

        // Transition
        TweenMax.set($(a.btn), {
          zIndex:2,
        });
        TweenMax.to($(a.btn), 0.2, {
          opacity:0,
          onComplete:function() {
            TweenMax.set($(a.btn), {
              zIndex:0,
            });
          },
        });

        TweenMax.to($('.overlay'), 0.6, {
          opacity:1,
          ease:Power2.easeOut,
        });

        $(a.cutout).show();
        TweenMax.set($(a.cutout), {
          boxShadow:'0px 0px 8px 2px rgba(0, 0, 0, 0)',
          zIndex:1,
          backgroundColor:'rgba(0,0,0,0.0)',
          padding:0,
        });

        TweenMax.to($(a.cutout), 1.5, {
          delay: 0,
          left:30,
          top:30,
          padding:15,
          backgroundColor:'rgba(0,0,0,0.75)',
          boxShadow:'0px 1px 6px 2px rgba(0, 0, 0, 0.35)',
          ease:Power2.easeInOut,
          onComplete:showAnnotationContent,
          onCompleteParams:[a],
        });

        break;

      }
    };

  };

  function showAnnotationContent(ann) {

    switch (ann.type) {
      case ANNOTATION_TYPE_VIDEO:
        showFullscreenVideo(ann.path);
        break;
      default:
        console.log('Annotation type:', ann.type, ' has not been built yet.');
        break;
    }

    trackKeenEvent('annotation_selection', { annotation: ann.id, mediaType:ann.type });

  }

  function getCutoutFromImage(id, imgElement, x, y, w, h) {

    id = id + '_cutout';
    var imgSrc = $(imgElement).attr('src');

    var cnvs = '<canvas id="' + id + '" style="position:absolute" width="' + w + '" height="' + h + '"></canvas>';

    $(imgElement).parent().append(cnvs);
    var cnvs = $('#' + id);
    var context = $(cnvs).get(0).getContext('2d');
    var imageObj = new Image();

    imageObj.onload = function() {

      context.drawImage(imageObj, x, y, w, h, 0, 0, w, h);
      TweenMax.set($(cnvs), {left:x, top:y});

    };

    imageObj.src = imgSrc;

    return cnvs;

  }

  function setupFullscreenVideo() {

    // Create video tag
    var options = { controls:false, autoplay: true, loop: false, preload: 'auto' };

    videoPlayer = $('video');

    videoPlayer.on('playing', function() {

      console.log('Video is playing');

      $('.content').show();

      TweenMax.set($('.content'), {
        opacity:0,
      });

      TweenMax.to($('.content'), 0.5, {
        opacity:1,
        ease:Power2.easeIn,
      });

    });

    videoPlayer.on('ended', function() {

      console.log('Video has ended!');

      trackKeenEvent('video_closed', {
        didFinish:true,
        src: videoPlayer.currentSrc,
        timePlayed:videoPlayer.currentTime,
        duration:videoPlayer.duration,
        progress:videoPlayer.duration / videoPlayer.currentTime,
      });

      hideFullscreenVideo();

    });

    // Home button
    $('.home-btn').on('click', function() {

      trackKeenEvent('video_closed', {
        didFinish:false,
        src: videoPlayer.currentSrc,
        timePlayed:videoPlayer.currentTime,
        duration:videoPlayer.duration,
        progress:videoPlayer.duration / videoPlayer.currentTime,
      });

      hideFullscreenVideo();

    });

  }

  function showFullscreenVideo(vidSrc) {

    videoPlayer.attr('src', vidSrc);
    videoPlayer.load();

    trackKeenEvent('play_video', { video: vidSrc });

  }

  function hideFullscreenVideo() {

    $('.content').fadeOut('fast', function() {
      videoPlayer.get(0).pause();
      $('.content').hide();
    });

    cutoutsGoHome();

  }

  function cutoutsGoHome() {

    TweenMax.to($('.overlay'), 0.8, {
      opacity:0,
      delay:0.7,
    });

    for (var i = 0; i < annotations.length; i++) {

      TweenMax.to($(annotations[i].cutout), 1.5, {
        left:annotations[i].x + annotations[i].cutRect.x,
        top:annotations[i].y + annotations[i].cutRect.y,
        backgroundColor:'rgba(0,0,0,0.0)',
        boxShadow:'0px 0px 8px 2px rgba(0, 0, 0, 0)',
        padding:0,
        ease:Power2.easeInOut,
        onCompleteParams:[annotations[i]],
        onComplete:function(a) {
          TweenMax.set($(a.cutout),  {
            zIndex:0,
          });
          TweenMax.to($(a.btn), 0.5, {
            opacity:1,
          });
          $(a.cutout).hide();

          // Unblock mouse/touch interaction
          $('.overlay').css('pointer-events', 'none');
        },
      });

    };

  }

  function setupScreenSaver() {

    var screensaver = new Screensaver(5 * 60, 'videos/ss.mp4', function() {

      console.log('onSleepCallback');
      trackKeenEvent('screensaver_shown', { });

    });

  }

  function getMediaType(mediaPath) {

    var ext = mediaPath.split('.').pop();
    var type = '';

    if (ext === 'mp4' || ext === 'mov') {
      type = ANNOTATION_TYPE_VIDEO;
    } else if (ext === 'mp3' || ext === 'ogg') {
      type = ANNOTATION_TYPE_AUDIO;
    } else if (ext === 'txt' || ext === 'json' || ext === 'xml' || ext === 'html') {
      type = ANNOTATION_TYPE_TEXT;
    } else {
      console.log('Unrecognized media type for file:', mediaPath);
    }

    return type;

  }

  function getProperJSON(improperJSON) {
    var properJSON = improperJSON.replace(/([a-z][^:]*)(?=\s*:)/g, '"$1"');
    return JSON.parse(properJSON);
  }

  function trackKeenEvent(collectionId, trackingEvent) {

    if (keenClient) {

      // Add timestamp
      trackingEvent.keen = { timestamp: new Date().toISOString() };

      // Send it to the <collectionId> collection
      keenClient.addEvent(collectionId, trackingEvent, function(err, res) {
        if (err) {
          console.log(err);
        } else {
          console.log(res);
        }
      });

    } else {
      console.log('Keen not initialized. Copy and modify js/keen.template.js -> js/keen.js')
    }

  }

  // TEMP - Tool for logging annotation points
  $('body').click(function(e) {
    console.log(e.pageX + ' , ' + e.pageY);
  });

  init();

});
<commit_msg>Correctly targeting videoPlayer for tracking<commit_after>$(document).ready(function() {

  var ANNOTATION_TYPE_VIDEO = 'video';
  var ANNOTATION_TYPE_TEXT = 'text';
  var ANNOTATION_TYPE_AUDIO = 'audio';

  // Create annotations manifest
  var annotations = [];
  var videoPlayer = {};

  var appWidth = $('body').css('width');
  var appHeight = $('body').css('height');

  function init() {

    setupFullscreenVideo();
    setupScreenSaver();

    var paintingImg = $('.painting img').first();

    $('.annotations button').each(function() {

      var mediaPath = $(this).attr('media-path');
      var a = { id: $(this).attr('id'),
                btn: this,
                x: parseInt($(this).attr('annotation-x'), 10),
                y: parseInt($(this).attr('annotation-y'), 10),
                type: getMediaType(mediaPath),
                path: mediaPath,
      };

      annotations.push(a);

      // Position & style button (offset for button size)
      $(this).css('left', a.x - 20);
      $(this).css('top', a.y - 20);
      $(this).addClass('btn');
      $(this).append('');

      var cutout = $(this).attr('cutout');
      if (cutout === undefined) {
        cutout = {x:-70, y: -70, w: 140, h: 140};
      } else {
        cutout = getProperJSON(cutout);
      }

      a.cutRect = cutout;
      a.cutout = getCutoutFromImage(a.id, paintingImg, a.x + a.cutRect.x, a.y + a.cutRect.y, a.cutRect.w, a.cutRect.h);

    });

    // Create hit regions by building Vernoi diagram
    console.log(appWidth, appHeight);
    var svgElement = '<svg id="veronoi_ui" width="' + appWidth + '" height="' + appHeight + '"></svg>';
    $('.annotations').prepend(svgElement);

    // Allow time for size recalc...
    setTimeout(function() {
      var vornoi = new VoronoiLayer(annotations, $('#veronoi_ui'), onAnnotationSelected, onAnnotationActive, false);
    }, 200);

    cutoutsGoHome();

  }

  var onAnnotationActive = function(annId, annBtn) {

    for (var i = 0; i < annotations.length; i++) {

      var a = annotations[i];

      if (annId === a.id) {

        $(a.btn).addClass('active');

        break;
      }

    }

  };

  var onAnnotationSelected = function(annId, annBtn) {

    console.log('annotationSelected(): ' + annId);

    for (var i = 0; i < annotations.length; i++) {

      var a = annotations[i];

      if (annId === a.id) {

        // Block mouse/touch interaction
        $('.overlay').css('pointer-events', 'auto');
        $(a.btn).removeClass('active');

        // Transition
        TweenMax.set($(a.btn), {
          zIndex:2,
        });
        TweenMax.to($(a.btn), 0.2, {
          opacity:0,
          onComplete:function() {
            TweenMax.set($(a.btn), {
              zIndex:0,
            });
          },
        });

        TweenMax.to($('.overlay'), 0.6, {
          opacity:1,
          ease:Power2.easeOut,
        });

        $(a.cutout).show();
        TweenMax.set($(a.cutout), {
          boxShadow:'0px 0px 8px 2px rgba(0, 0, 0, 0)',
          zIndex:1,
          backgroundColor:'rgba(0,0,0,0.0)',
          padding:0,
        });

        TweenMax.to($(a.cutout), 1.5, {
          delay: 0,
          left:30,
          top:30,
          padding:15,
          backgroundColor:'rgba(0,0,0,0.75)',
          boxShadow:'0px 1px 6px 2px rgba(0, 0, 0, 0.35)',
          ease:Power2.easeInOut,
          onComplete:showAnnotationContent,
          onCompleteParams:[a],
        });

        break;

      }
    };

  };

  function showAnnotationContent(ann) {

    switch (ann.type) {
      case ANNOTATION_TYPE_VIDEO:
        showFullscreenVideo(ann.path);
        break;
      default:
        console.log('Annotation type:', ann.type, ' has not been built yet.');
        break;
    }

    trackKeenEvent('annotation_selection', { annotation: ann.id, mediaType:ann.type });

  }

  function getCutoutFromImage(id, imgElement, x, y, w, h) {

    id = id + '_cutout';
    var imgSrc = $(imgElement).attr('src');

    var cnvs = '<canvas id="' + id + '" style="position:absolute" width="' + w + '" height="' + h + '"></canvas>';

    $(imgElement).parent().append(cnvs);
    var cnvs = $('#' + id);
    var context = $(cnvs).get(0).getContext('2d');
    var imageObj = new Image();

    imageObj.onload = function() {

      context.drawImage(imageObj, x, y, w, h, 0, 0, w, h);
      TweenMax.set($(cnvs), {left:x, top:y});

    };

    imageObj.src = imgSrc;

    return cnvs;

  }

  function setupFullscreenVideo() {

    // Create video tag
    var options = { controls:false, autoplay: true, loop: false, preload: 'auto' };

    videoPlayer = $('video');

    videoPlayer.on('playing', function() {

      console.log('Video is playing');

      $('.content').show();

      TweenMax.set($('.content'), {
        opacity:0,
      });

      TweenMax.to($('.content'), 0.5, {
        opacity:1,
        ease:Power2.easeIn,
      });

    });

    videoPlayer.on('ended', function() {

      console.log('Video has ended!');

      trackKeenEvent('video_closed', {
        didFinish:true,
        src: videoPlayer.get(0).currentSrc,
        timePlayed:videoPlayer.get(0).currentTime,
        duration:videoPlayer.get(0).duration,
        progress:videoPlayer.get(0).duration / videoPlayer.get(0).currentTime,
      });

      hideFullscreenVideo();

    });

    // Home button
    $('.home-btn').on('click', function() {

      trackKeenEvent('video_closed', {
        didFinish:false,
        src: videoPlayer.get(0).currentSrc,
        timePlayed:videoPlayer.get(0).currentTime,
        duration:videoPlayer.get(0).duration,
        progress:videoPlayer.get(0).duration / videoPlayer.get(0).currentTime,
      });

      hideFullscreenVideo();

    });

  }

  function showFullscreenVideo(vidSrc) {

    videoPlayer.attr('src', vidSrc);
    videoPlayer.load();

    trackKeenEvent('play_video', { video: vidSrc });

  }

  function hideFullscreenVideo() {

    $('.content').fadeOut('fast', function() {
      videoPlayer.get(0).pause();
      $('.content').hide();
    });

    cutoutsGoHome();

  }

  function cutoutsGoHome() {

    TweenMax.to($('.overlay'), 0.8, {
      opacity:0,
      delay:0.7,
    });

    for (var i = 0; i < annotations.length; i++) {

      TweenMax.to($(annotations[i].cutout), 1.5, {
        left:annotations[i].x + annotations[i].cutRect.x,
        top:annotations[i].y + annotations[i].cutRect.y,
        backgroundColor:'rgba(0,0,0,0.0)',
        boxShadow:'0px 0px 8px 2px rgba(0, 0, 0, 0)',
        padding:0,
        ease:Power2.easeInOut,
        onCompleteParams:[annotations[i]],
        onComplete:function(a) {
          TweenMax.set($(a.cutout),  {
            zIndex:0,
          });
          TweenMax.to($(a.btn), 0.5, {
            opacity:1,
          });
          $(a.cutout).hide();

          // Unblock mouse/touch interaction
          $('.overlay').css('pointer-events', 'none');
        },
      });

    };

  }

  function setupScreenSaver() {

    var screensaver = new Screensaver(5 * 60, 'videos/ss.mp4', function() {

      console.log('onSleepCallback');
      trackKeenEvent('screensaver_shown', { });

    });

  }

  function getMediaType(mediaPath) {

    var ext = mediaPath.split('.').pop();
    var type = '';

    if (ext === 'mp4' || ext === 'mov') {
      type = ANNOTATION_TYPE_VIDEO;
    } else if (ext === 'mp3' || ext === 'ogg') {
      type = ANNOTATION_TYPE_AUDIO;
    } else if (ext === 'txt' || ext === 'json' || ext === 'xml' || ext === 'html') {
      type = ANNOTATION_TYPE_TEXT;
    } else {
      console.log('Unrecognized media type for file:', mediaPath);
    }

    return type;

  }

  function getProperJSON(improperJSON) {
    var properJSON = improperJSON.replace(/([a-z][^:]*)(?=\s*:)/g, '"$1"');
    return JSON.parse(properJSON);
  }

  function trackKeenEvent(collectionId, trackingEvent) {

    if (keenClient) {

      // Add timestamp
      trackingEvent.keen = { timestamp: new Date().toISOString() };

      // Send it to the <collectionId> collection
      keenClient.addEvent(collectionId, trackingEvent, function(err, res) {
        if (err) {
          console.log(err);
        } else {
          console.log(res);
        }
      });

    } else {
      console.log('Keen not initialized. Copy and modify js/keen.template.js -> js/keen.js')
    }

  }

  // TEMP - Tool for logging annotation points
  $('body').click(function(e) {
    console.log(e.pageX + ' , ' + e.pageY);
  });

  init();

});
<|endoftext|>


<commit_before>jQuery.fn.updateWithText = function(text, speed)
{
	var dummy = $('
').html(text);

	if ($(this).html() != dummy.html())
	{
		$(this).fadeOut(speed/2, function() {
			$(this).html(text);
			$(this).fadeIn(speed/2, function() {
				//done
			});
		});
	}
}

jQuery.fn.outerHTML = function(s) {
    return s
        ? this.before(s).remove()
        : jQuery("
").append(this.eq(0).clone()).html();
};

function roundVal(temp)
{
	return Math.round(temp * 10) / 10;
}

function kmh2beaufort(kmh)
{
	var speeds = [1, 5, 11, 19, 28, 38, 49, 61, 74, 88, 102, 117, 1000];
	for (var beaufort in speeds) {
		var speed = speeds[beaufort];
		if (speed > kmh) {
			return beaufort;
		}
	}
	return 12;
}

jQuery(document).ready(function($) {

	var news = [];
	var newsIndex = 0;

	var eventList = [];

	var lastCompliment;
	var compliment;

	var socket = io.connect('http://rpi-development.local:8080');
	socket.on('dishwasher', function (dishwasherReady) {
		if (dishwasherReady) {
			$('.dishwasher').fadeIn(2000);
			$('.lower-third').fadeOut(2000);
		} else {
			$('.dishwasher').fadeOut(2000);
			$('.lower-third').fadeIn(2000);
		}
	});

	var weatherParams = {
		'q':'Baarn,Netherlands',
		'units':'metric',
		'lang':'nl'
	};

	(function checkVersion()
	{
		$.getJSON('githash.php', {}, function(json, textStatus) {
			if (json) {
				if (json.gitHash != gitHash) {
					window.location.reload();
					window.location.href=window.location.href;
				}
			}
		});
		setTimeout(function() {
			checkVersion();
		}, 3000);
	})();

	(function updateTime()
	{
		var days = ['zondag','maandag','dinsdag','woensdag','donderdag','vrijdag','zaterdag'];
		var months = ['januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december'];

		var now = new Date();

		var day = now.getDay();
		var date = now.getDate();
		var month = now.getMonth();
		var year = now.getFullYear();

		var date = days[day] + ', ' + date+' ' + months[month] + ' ' + year;

		$('.date').html(date);
		$('.time').html(now.toTimeString().substring(0,5) + ''+now.toTimeString().substring(6,8)+'');

		setTimeout(function() {
			updateTime();
		}, 1000);
	})();

	(function updateCalendarData()
	{
		new ical_parser("calendar.php", function(cal){
        	events = cal.getEvents();
        	eventList = [];

        	for (var i in events) {
        		var e = events[i];
        		for (var key in e) {
        			var value = e[key];
					var seperator = key.search(';');
					if (seperator >= 0) {
						var mainKey = key.substring(0,seperator);
						var subKey = key.substring(seperator+1);

						var dt;
						if (subKey == 'VALUE=DATE') {
							//date
							dt = new Date(value.substring(0,4), value.substring(4,6) - 1, value.substring(6,8));
						} else {
							//time
							dt = new Date(value.substring(0,4), value.substring(4,6) - 1, value.substring(6,8), value.substring(9,11), value.substring(11,13), value.substring(13,15));
						}

						if (mainKey == 'DTSTART') e.startDate = dt;
						if (mainKey == 'DTEND') e.endDate = dt;
					}
        		}

        		var now = new Date();
        		var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        		var days = moment(e.startDate).diff(moment(today), 'days');

        		//only add fututre events
        		if (days >= 0) {
	        		eventList.push({'description':e.SUMMARY,'days':days});
        		}
        	};
        	eventList.sort(function(a,b){return a.days-b.days});

        	setTimeout(function() {
        		updateCalendarData();
        	}, 60000);
    	});
	})();

	(function updateCalendar()
	{
		table = $('
').addClass('xsmall').addClass('calendar-table');
		opacity = 1;

		for (var i in eventList) {
			var e = eventList[i];
			var days = e.days;

			var daysString = (days == 1) ? 'morgen' :  days + ' dagen';
    		if (days == 0) {
    			daysString = 'vandaag';
    		}

			var row = $('
').css('opacity',opacity);
			row.append($('').html(e.description).addClass('description'));
			row.append($('').html(daysString).addClass('days dimmed'));
			table.append(row);

			opacity -= 1 / eventList.length;
		}

		$('.calendar').updateWithText(table,1000);

		setTimeout(function() {
        	updateCalendar();
        }, 1000);
	})();

	(function updateCompliment()
	{

		var compliments = [
			'Hey, handsome!',
			'Hi, sexy!',
			'Hello, beauty!',
			'You look sexy!',
			'Wow, you look hot!',
			'Looking good today!',
			'You look nice!',
			'Enjoy your day!'
		];

		while (compliment == lastCompliment) {
			compliment = Math.floor(Math.random()*compliments.length);
		}

		$('.compliment').updateWithText(compliments[compliment], 4000);

		lastCompliment = compliment;

		setTimeout(function() {
			updateCompliment(true);
		}, 30000);

	})();

	(function updateCurrentWeather()
	{
		var iconTable = {
			'01d':'wi-day-sunny',
			'02d':'wi-day-cloudy',
			'03d':'wi-cloudy',
			'04d':'wi-cloudy-windy',
			'09d':'wi-showers',
			'10d':'wi-rain',
			'11d':'wi-thunderstorm',
			'13d':'wi-snow',
			'50d':'wi-fog',
			'01n':'wi-night-clear',
			'02n':'wi-night-cloudy',
			'03n':'wi-night-cloudy',
			'04n':'wi-night-cloudy',
			'09n':'wi-night-showers',
			'10n':'wi-night-rain',
			'11n':'wi-night-thunderstorm',
			'13n':'wi-night-snow',
			'50n':'wi-night-alt-cloudy-windy'
		}

		$.getJSON('http://api.openweathermap.org/data/2.5/weather', weatherParams, function(json, textStatus) {

			var temp = roundVal(json.main.temp);
			var temp_min = roundVal(json.main.temp_min);
			var temp_max = roundVal(json.main.temp_max);

			var wind = roundVal(json.wind.speed);

			var iconClass = iconTable[json.weather[0].icon];
			var icon = $('').addClass('icon').addClass('dimmed').addClass('wi').addClass(iconClass);
			$('.temp').updateWithText(icon.outerHTML()+temp+'°', 1000);

			// var forecast = 'Min: '+temp_min+'°, Max: '+temp_max+'°';
			// $('.forecast').updateWithText(forecast, 1000);

			var now = new Date();
			var sunrise = new Date(json.sys.sunrise*1000).toTimeString().substring(0,5);
			var sunset = new Date(json.sys.sunset*1000).toTimeString().substring(0,5);

			var windString = ' ' + kmh2beaufort(wind) ;
			var sunString = ' ' + sunrise;
			if (json.sys.sunrise*1000 < now && json.sys.sunset*1000 > now) {
				sunString = ' ' + sunset;
			}

			$('.windsun').updateWithText(windString+' '+sunString, 1000);
		});

		setTimeout(function() {
			updateCurrentWeather();
		}, 60000);
	})();

	(function updateWeatherForecast()
	{
			var dayAbbr = ['zo','ma','di','wo','do','vr','za'];

			$.getJSON('http://api.openweathermap.org/data/2.5/forecast', weatherParams, function(json, textStatus) {

			var forecastData = {};

			for (var i in json.list) {
				var forecast = json.list[i];
				var dateKey  = forecast.dt_txt.substring(0, 10);

				if (forecastData[dateKey] == undefined) {
					forecastData[dateKey] = {
						'timestamp':forecast.dt * 1000,
						'temp_min':forecast.main.temp,
						'temp_max':forecast.main.temp
					};
				} else {
					forecastData[dateKey]['temp_min'] = (forecast.main.temp < forecastData[dateKey]['temp_min']) ? forecast.main.temp : forecastData[dateKey]['temp_min'];
					forecastData[dateKey]['temp_max'] = (forecast.main.temp > forecastData[dateKey]['temp_max']) ? forecast.main.temp : forecastData[dateKey]['temp_max'];
				}

			}

			var forecastTable = $('
').addClass('forecast-table');
			var opacity = 1;
			for (var i in forecastData) {
				var forecast = forecastData[i];
				var dt = new Date(forecast.timestamp);
				var row = $('
').css('opacity', opacity);

				row.append($('').addClass('day').html(dayAbbr[dt.getDay()]));
				row.append($('').addClass('temp-max').html(roundVal(forecast.temp_max)));
				row.append($('').addClass('temp-min').html(roundVal(forecast.temp_min)));

				forecastTable.append(row);
				opacity -= 0.155;
			}

			$('.forecast').updateWithText(forecastTable, 1000);
		});

		setTimeout(function() {
			updateWeatherForecast();
		}, 60000);
	})();

	(function fetchNews() {
		$.feedToJson({
			feed:'http://feeds.nos.nl/nosjournaal?format=rss',
			//feed:'http://www.nu.nl/feeds/rss/achterklap.rss',
			//feed:'http://www.nu.nl/feeds/rss/opmerkelijk.rss',
			success: function(data){
				news = [];
				for (var i in data.item) {
					var item = data.item[i];
					news.push(item.title);
				}
			}
		});
		setTimeout(function() {
			fetchNews();
		}, 60000);
	})();

	(function showNews() {
		var newsItem = news[newsIndex];
		$('.news').updateWithText(newsItem,2000);

		newsIndex--;
		if (newsIndex < 0) newsIndex = news.length - 1;
		setTimeout(function() {
			showNews();
		}, 5500);
	})();

});
<commit_msg>New commit<commit_after>jQuery.fn.updateWithText = function(text, speed)
{
	var dummy = $('
').html(text);

	if ($(this).html() != dummy.html())
	{
		$(this).fadeOut(speed/2, function() {
			$(this).html(text);
			$(this).fadeIn(speed/2, function() {
				//done
			});
		});
	}
}

jQuery.fn.outerHTML = function(s) {
    return s
        ? this.before(s).remove()
        : jQuery("
").append(this.eq(0).clone()).html();
};

function roundVal(temp)
{
	return Math.round(temp * 10) / 10;
}

function kmh2beaufort(kmh)
{
	var speeds = [1, 5, 11, 19, 28, 38, 49, 61, 74, 88, 102, 117, 1000];
	for (var beaufort in speeds) {
		var speed = speeds[beaufort];
		if (speed > kmh) {
			return beaufort;
		}
	}
	return 12;
}

jQuery(document).ready(function($) {

	var news = [];
	var newsIndex = 0;

	var eventList = [];

	var lastCompliment;
	var compliment;

	//connect do Xbee monitor
	var socket = io.connect('http://rpi-development.local:8080');
	socket.on('dishwasher', function (dishwasherReady) {
		if (dishwasherReady) {
			$('.dishwasher').fadeIn(2000);
			$('.lower-third').fadeOut(2000);
		} else {
			$('.dishwasher').fadeOut(2000);
			$('.lower-third').fadeIn(2000);
		}
	});

	var weatherParams = {
		'q':'Baarn,Netherlands',
		'units':'metric',
		'lang':'nl'
	};

	(function checkVersion()
	{
		$.getJSON('githash.php', {}, function(json, textStatus) {
			if (json) {
				if (json.gitHash != gitHash) {
					window.location.reload();
					window.location.href=window.location.href;
				}
			}
		});
		setTimeout(function() {
			checkVersion();
		}, 3000);
	})();

	(function updateTime()
	{
		var days = ['zondag','maandag','dinsdag','woensdag','donderdag','vrijdag','zaterdag'];
		var months = ['januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december'];

		var now = new Date();

		var day = now.getDay();
		var date = now.getDate();
		var month = now.getMonth();
		var year = now.getFullYear();

		var date = days[day] + ', ' + date+' ' + months[month] + ' ' + year;

		$('.date').html(date);
		$('.time').html(now.toTimeString().substring(0,5) + ''+now.toTimeString().substring(6,8)+'');

		setTimeout(function() {
			updateTime();
		}, 1000);
	})();

	(function updateCalendarData()
	{
		new ical_parser("calendar.php", function(cal){
        	events = cal.getEvents();
        	eventList = [];

        	for (var i in events) {
        		var e = events[i];
        		for (var key in e) {
        			var value = e[key];
					var seperator = key.search(';');
					if (seperator >= 0) {
						var mainKey = key.substring(0,seperator);
						var subKey = key.substring(seperator+1);

						var dt;
						if (subKey == 'VALUE=DATE') {
							//date
							dt = new Date(value.substring(0,4), value.substring(4,6) - 1, value.substring(6,8));
						} else {
							//time
							dt = new Date(value.substring(0,4), value.substring(4,6) - 1, value.substring(6,8), value.substring(9,11), value.substring(11,13), value.substring(13,15));
						}

						if (mainKey == 'DTSTART') e.startDate = dt;
						if (mainKey == 'DTEND') e.endDate = dt;
					}
        		}

        		var now = new Date();
        		var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        		var days = moment(e.startDate).diff(moment(today), 'days');

        		//only add fututre events
        		if (days >= 0) {
	        		eventList.push({'description':e.SUMMARY,'days':days});
        		}
        	};
        	eventList.sort(function(a,b){return a.days-b.days});

        	setTimeout(function() {
        		updateCalendarData();
        	}, 60000);
    	});
	})();

	(function updateCalendar()
	{
		table = $('
').addClass('xsmall').addClass('calendar-table');
		opacity = 1;

		for (var i in eventList) {
			var e = eventList[i];
			var days = e.days;

			var daysString = (days == 1) ? 'morgen' :  days + ' dagen';
    		if (days == 0) {
    			daysString = 'vandaag';
    		}

			var row = $('
').css('opacity',opacity);
			row.append($('').html(e.description).addClass('description'));
			row.append($('').html(daysString).addClass('days dimmed'));
			table.append(row);

			opacity -= 1 / eventList.length;
		}

		$('.calendar').updateWithText(table,1000);

		setTimeout(function() {
        	updateCalendar();
        }, 1000);
	})();

	(function updateCompliment()
	{

		var compliments = [
			'Hey, handsome!',
			'Hi, sexy!',
			'Hello, beauty!',
			'You look sexy!',
			'Wow, you look hot!',
			'Looking good today!',
			'You look nice!',
			'Enjoy your day!'
		];

		while (compliment == lastCompliment) {
			compliment = Math.floor(Math.random()*compliments.length);
		}

		$('.compliment').updateWithText(compliments[compliment], 4000);

		lastCompliment = compliment;

		setTimeout(function() {
			updateCompliment(true);
		}, 30000);

	})();

	(function updateCurrentWeather()
	{
		var iconTable = {
			'01d':'wi-day-sunny',
			'02d':'wi-day-cloudy',
			'03d':'wi-cloudy',
			'04d':'wi-cloudy-windy',
			'09d':'wi-showers',
			'10d':'wi-rain',
			'11d':'wi-thunderstorm',
			'13d':'wi-snow',
			'50d':'wi-fog',
			'01n':'wi-night-clear',
			'02n':'wi-night-cloudy',
			'03n':'wi-night-cloudy',
			'04n':'wi-night-cloudy',
			'09n':'wi-night-showers',
			'10n':'wi-night-rain',
			'11n':'wi-night-thunderstorm',
			'13n':'wi-night-snow',
			'50n':'wi-night-alt-cloudy-windy'
		}

		$.getJSON('http://api.openweathermap.org/data/2.5/weather', weatherParams, function(json, textStatus) {

			var temp = roundVal(json.main.temp);
			var temp_min = roundVal(json.main.temp_min);
			var temp_max = roundVal(json.main.temp_max);

			var wind = roundVal(json.wind.speed);

			var iconClass = iconTable[json.weather[0].icon];
			var icon = $('').addClass('icon').addClass('dimmed').addClass('wi').addClass(iconClass);
			$('.temp').updateWithText(icon.outerHTML()+temp+'°', 1000);

			// var forecast = 'Min: '+temp_min+'°, Max: '+temp_max+'°';
			// $('.forecast').updateWithText(forecast, 1000);

			var now = new Date();
			var sunrise = new Date(json.sys.sunrise*1000).toTimeString().substring(0,5);
			var sunset = new Date(json.sys.sunset*1000).toTimeString().substring(0,5);

			var windString = ' ' + kmh2beaufort(wind) ;
			var sunString = ' ' + sunrise;
			if (json.sys.sunrise*1000 < now && json.sys.sunset*1000 > now) {
				sunString = ' ' + sunset;
			}

			$('.windsun').updateWithText(windString+' '+sunString, 1000);
		});

		setTimeout(function() {
			updateCurrentWeather();
		}, 60000);
	})();

	(function updateWeatherForecast()
	{
			var dayAbbr = ['zo','ma','di','wo','do','vr','za'];

			$.getJSON('http://api.openweathermap.org/data/2.5/forecast', weatherParams, function(json, textStatus) {

			var forecastData = {};

			for (var i in json.list) {
				var forecast = json.list[i];
				var dateKey  = forecast.dt_txt.substring(0, 10);

				if (forecastData[dateKey] == undefined) {
					forecastData[dateKey] = {
						'timestamp':forecast.dt * 1000,
						'temp_min':forecast.main.temp,
						'temp_max':forecast.main.temp
					};
				} else {
					forecastData[dateKey]['temp_min'] = (forecast.main.temp < forecastData[dateKey]['temp_min']) ? forecast.main.temp : forecastData[dateKey]['temp_min'];
					forecastData[dateKey]['temp_max'] = (forecast.main.temp > forecastData[dateKey]['temp_max']) ? forecast.main.temp : forecastData[dateKey]['temp_max'];
				}

			}

			var forecastTable = $('
').addClass('forecast-table');
			var opacity = 1;
			for (var i in forecastData) {
				var forecast = forecastData[i];
				var dt = new Date(forecast.timestamp);
				var row = $('
').css('opacity', opacity);

				row.append($('').addClass('day').html(dayAbbr[dt.getDay()]));
				row.append($('').addClass('temp-max').html(roundVal(forecast.temp_max)));
				row.append($('').addClass('temp-min').html(roundVal(forecast.temp_min)));

				forecastTable.append(row);
				opacity -= 0.155;
			}

			$('.forecast').updateWithText(forecastTable, 1000);
		});

		setTimeout(function() {
			updateWeatherForecast();
		}, 60000);
	})();

	(function fetchNews() {
		$.feedToJson({
			feed:'http://feeds.nos.nl/nosjournaal?format=rss',
			//feed:'http://www.nu.nl/feeds/rss/achterklap.rss',
			//feed:'http://www.nu.nl/feeds/rss/opmerkelijk.rss',
			success: function(data){
				news = [];
				for (var i in data.item) {
					var item = data.item[i];
					news.push(item.title);
				}
			}
		});
		setTimeout(function() {
			fetchNews();
		}, 60000);
	})();

	(function showNews() {
		var newsItem = news[newsIndex];
		$('.news').updateWithText(newsItem,2000);

		newsIndex--;
		if (newsIndex < 0) newsIndex = news.length - 1;
		setTimeout(function() {
			showNews();
		}, 5500);
	})();

});
<|endoftext|>


<commit_before>(function(){

  var formatMinutes = '', formatSeconds = '';

  // The timmers for the monsters
  var timers = {
    // 5 minutes
    'campBuff': 300000,
    // 6 minutes
    'dragon': 360000,
    // 7 minutes
    'baron': 420000
  };

  var monster_timer_pool = {
    'monster-1': [],
    'monster-2': [],
    'monster-3': [],
    'monster-4': [],
    'monster-5': [],
    'monster-6': []
  };

  $('.monster').click(function(){
    var $this       = $(this);
    var $monster_id = $(this).attr('data-id');
    var campBuff    = Date.now() + timers[$this.attr('data-type')];

    // We verify if this monster has already a timer
    if (monster_timer_pool[$monster_id].length !== 0) {
      // It has already a timer, lets clear it
      $.each(monster_timer_pool[$monster_id], function(i, timerId){
        window.clearInterval(timerId);
      });
      // Now that the timers has been stopped, lets clear the pool
      monster_timer_pool[$monster_id] = [];
      // Lets clear the element
      $this.find('.timer').empty();
      // Lets stop
      return false;
    }

    var timerId =
      countdown(
        campBuff,
        function(ts) {
          formatMinutes = String("00" + ts.minutes).slice(-2);
          formatSeconds = String("00" + ts.seconds).slice(-2);
          $this.find('.timer').html(formatMinutes + ':' + formatSeconds);
          // We verify if the timer has ran out
          if (ts.minutes === 0 && ts.seconds === 0){
            // We clear the timer interval once the timer has reached 0
            window.clearInterval(timerId);
            // We clear the timer from the timers_pool
            monster_timer_pool[$monster_id] = [];
          }
        },
        countdown.MINUTES|countdown.SECONDS);

    // We add this timer to the monster pool
    // this would be helpful to reset timers and stuff
    monster_timer_pool[$monster_id].push(timerId);

  });

})(window.jQuery);
<commit_msg>Removing the format for the minutes<commit_after>(function(){

  var formatMinutes = '', formatSeconds = '';

  // The timmers for the monsters
  var timers = {
    // 5 minutes
    'campBuff': 300000,
    // 6 minutes
    'dragon': 360000,
    // 7 minutes
    'baron': 420000
  };

  var monster_timer_pool = {
    'monster-1': [],
    'monster-2': [],
    'monster-3': [],
    'monster-4': [],
    'monster-5': [],
    'monster-6': []
  };

  $('.monster').click(function(){
    var $this       = $(this);
    var $monster_id = $(this).attr('data-id');
    var campBuff    = Date.now() + timers[$this.attr('data-type')];

    // We verify if this monster has already a timer
    if (monster_timer_pool[$monster_id].length !== 0) {
      // It has already a timer, lets clear it
      $.each(monster_timer_pool[$monster_id], function(i, timerId){
        window.clearInterval(timerId);
      });
      // Now that the timers has been stopped, lets clear the pool
      monster_timer_pool[$monster_id] = [];
      // Lets clear the element
      $this.find('.timer').empty();
      // Lets stop
      return false;
    }

    var timerId =
      countdown(
        campBuff,
        function(ts) {
          formatSeconds = String("00" + ts.seconds).slice(-2);
          $this.find('.timer').html(ts.minutes + ':' + formatSeconds);
          // We verify if the timer has ran out
          if (ts.minutes === 0 && ts.seconds === 0){
            // We clear the timer interval once the timer has reached 0
            window.clearInterval(timerId);
            // We clear the timer from the timers_pool
            monster_timer_pool[$monster_id] = [];
          }
        },
        countdown.MINUTES|countdown.SECONDS);

    // We add this timer to the monster pool
    // this would be helpful to reset timers and stuff
    monster_timer_pool[$monster_id].push(timerId);

  });

})(window.jQuery);
<|endoftext|>


<commit_before>/* @flow */

"strict";

const React = require("react"),
    Util = require("./util"),
    models = require("./models"),
    APIClient = require("./apiclient"),
    Cache = require("./cache"),
    Downloads = require("./downloads"),
    Storage = require("./storage"),
    chromeViews = require("./views/chrome"),
    {Stack} = require("immutable"),
    {readOptions, resetOptions, writeOptions} = require("./data/app-options"),
    {getId} = require("./data/topic-tree-helper"),
    {readTopicTree} = require("./data/topic-tree"),
    {resetNavInfo} = require("./data/nav-info"),
    Immutable = require("immutable"),
    Cursor = require('immutable/contrib/cursor');

// TODO: remove, just for easy inpsection
window.APIClient = APIClient;
window.Util = Util;
window.models = models;
window.React = React;

document.querySelector("body").addEventListener("contextmenu", function(e) {
    Util.log("contextmenu!");
    e.preventDefault();
});

// App is moving to background
document.addEventListener("visibilitychange", function(e) {
    if (document.hidden) {
        Util.log("visibility changing (hide)");
        // TODO(bbondy): Try to free up resources here for a smaller chance
        // of getting discarded.
    } else {
        Util.log("visibility changing (show)");
    }
});

var MainView = chromeViews.MainView;
var mountNode = document.getElementById("app");

// Start showing the topic tree
var options = readOptions() || resetOptions();
var updateOptionsCursor = (newOptions) => {
    writeOptions(newOptions);
    mainView.setProps({ optionsCursor: Cursor.from(newOptions, updateOptionsCursor) });
};
var optionsCursor = Cursor.from(options, updateOptionsCursor);
var navInfo = resetNavInfo();

var updateNavInfoCursor = (newNavInfo) => {
    mainView.setProps({ navInfoCursor: Cursor.from(newNavInfo, updateNavInfoCursor) });
};
var navInfoCursor = Cursor.from(navInfo, updateNavInfoCursor);

// Render the main app chrome
var mainView = React.render(<MainView optionsCursor={optionsCursor}
                                      navInfoCursor={navInfoCursor} />, mountNode);

// Init everything
Storage.init().then(function() {
    return APIClient.init();
}).then(function() {
    return Promise.all([Downloads.init(), Cache.init()]);
}).then(function() {
    // We don't want to have to wait for results, so just start this and don't wait
    models.CurrentUser.init();

    readTopicTree().then((rootTopicTreeCursor) => {
        // Setup immutable nav info cursor
        navInfoCursor.merge({
            topicTreeCursor: rootTopicTreeCursor,
            rootTopicTreeCursor,
            navStack: Immutable.Stack.of(rootTopicTreeCursor),
        });
    });

}).catch((error) => {
    alert(error);
    if (Util.isFirefoxOS()) {
        Util.quit();
    } else {
        throw error;
    }
});

<commit_msg>Fix lint<commit_after>/* @flow */

"strict";

const React = require("react"),
    Util = require("./util"),
    models = require("./models"),
    APIClient = require("./apiclient"),
    Cache = require("./cache"),
    Downloads = require("./downloads"),
    Storage = require("./storage"),
    chromeViews = require("./views/chrome"),
    {readOptions, resetOptions, writeOptions} = require("./data/app-options"),
    {readTopicTree} = require("./data/topic-tree"),
    {resetNavInfo} = require("./data/nav-info"),
    Immutable = require("immutable"),
    Cursor = require('immutable/contrib/cursor');

// TODO: remove, just for easy inpsection
window.APIClient = APIClient;
window.Util = Util;
window.models = models;
window.React = React;

document.querySelector("body").addEventListener("contextmenu", function(e) {
    Util.log("contextmenu!");
    e.preventDefault();
});

// App is moving to background
document.addEventListener("visibilitychange", function(e) {
    if (document.hidden) {
        Util.log("visibility changing (hide)");
        // TODO(bbondy): Try to free up resources here for a smaller chance
        // of getting discarded.
    } else {
        Util.log("visibility changing (show)");
    }
});

var MainView = chromeViews.MainView;
var mountNode = document.getElementById("app");

// Start showing the topic tree
var options = readOptions() || resetOptions();
var updateOptionsCursor = (newOptions) => {
    writeOptions(newOptions);
    mainView.setProps({ optionsCursor: Cursor.from(newOptions, updateOptionsCursor) });
};
var optionsCursor = Cursor.from(options, updateOptionsCursor);
var navInfo = resetNavInfo();

var updateNavInfoCursor = (newNavInfo) => {
    mainView.setProps({ navInfoCursor: Cursor.from(newNavInfo, updateNavInfoCursor) });
};
var navInfoCursor = Cursor.from(navInfo, updateNavInfoCursor);

// Render the main app chrome
var mainView = React.render(<MainView optionsCursor={optionsCursor}
                                      navInfoCursor={navInfoCursor} />, mountNode);

// Init everything
Storage.init().then(function() {
    return APIClient.init();
}).then(function() {
    return Promise.all([Downloads.init(), Cache.init()]);
}).then(function() {
    // We don't want to have to wait for results, so just start this and don't wait
    models.CurrentUser.init();

    readTopicTree().then((rootTopicTreeCursor) => {
        // Setup immutable nav info cursor
        navInfoCursor.merge({
            topicTreeCursor: rootTopicTreeCursor,
            rootTopicTreeCursor,
            navStack: Immutable.Stack.of(rootTopicTreeCursor),
        });
    });

}).catch((error) => {
    alert(error);
    if (Util.isFirefoxOS()) {
        Util.quit();
    } else {
        throw error;
    }
});

<|endoftext|>


<commit_before>
var sprintf = require('sprintf');
var gutil = require('gulp-util');
var extend = require('object-extend');

var gulpWebpack = require('webpack-stream');
var WebpackDevServer = require("webpack-dev-server");
var HtmlWebpackPlugin = require('html-webpack-plugin')

var gulp = require('gulp');
var src  = gulp.src;
var dest = gulp.dest;

var webpack = require('webpack'),
path = require('path');

var parseArgs = require('minimist');

var options = parseArgs(process.argv, {default: {
  hot: false
}});

/*
 *  Bundle a component
 *
 *  entryPoint        - the entry point for the bundle
 *  outputFileName    - file name for produced bundle
 *  destPath          - destination path for produced bundle,
 *                      relative to the root directory of the project
 *                      being built
 *  pageDefs          - options to pass on into the template
 *                      for each index.html entry point to be
 *                      generated. must be either an array (or null,
 *                      if no index.html:s need to be generated)
 *  watch             - start webpack-dev-server with hot reloading
 *                      setting this true will cause this to block
 */
function bundle(entryPoint, outputFileName, destPath, pageDefs, watch, assetContext, callback) {

  var config = {
     resolve: {
       modulesDirectories: ['node_modules', 'components'],
       root: [path.resolve(__dirname,'../node_modules')]
     },
     module: {
       loaders: getLoaders()
     },
     resolveLoader: {
      root: [path.resolve(__dirname, '../node_modules')],
      modulesDirectories: ['node_modules'],
     },
     output: {
      filename: outputFileName,
      path: process.cwd() + "/" + destPath,
      publicPath: '/' + assetContext
     },
     entry: entryPoint,
     plugins: htmlWebpackPluginsFromPageDefs(pageDefs, watch),
  };

  if (watch) {
    devServerBundle(config, destPath);
    return;
  }
  plainBundle(config, callback);
}

//
// Private functions
// -----------------
//

/*
 * Create HtmlWebpack plugin entries
 * based on given page defs
 */
function htmlWebpackPluginsFromPageDefs(pageDefs, watch) {
    var arr;
    if (Array.isArray(pageDefs)) {
      arr = pageDefs;
    } else {
      return [];
    }

    return arr.map(item => {
        if (!item.path) {
          item.path = '';
        }
        var config = {
            template: 'node_modules/lucify-component-builder/src/www/embed.hbs',
            inject: false,
            filename: path.join(item.path, 'index.html'),
            devServer: watch // note: this is also needed for hot module replacement
        };
        var fullConfig = extend(config, item);
        return new HtmlWebpackPlugin(fullConfig);
    });
}

/*
 * Start webpack dev server for given webpack configuration
 */
function devServerBundle(config, destPath) {
  config.output.publicPath = '/';

  if (!options.hot) {
    // setup for automatic refresh
    // https://webpack.github.io/docs/webpack-dev-server.html#automatic-refresh
    config.entry = ['webpack-dev-server/client?http://localhost:3000', config.entry];

  } else {
    // Experimental setup for hot module replacement
    // enable via --hot option
    //
    // This seems to work correctly, but we get a message that
    // some modules could not be updated, as they would need a
    // full reload. I suspect this is related to the use of higher-order
    // components.
    //
    // https://medium.com/@dan_abramov/the-death-of-react-hot-loader-765fa791d7c4#.wrqoafdic
    // https://gaearon.github.io/react-hot-loader/getstarted/
    // https://webpack.github.io/docs/hot-module-replacement-with-webpack.html
    config.entry = [config.entry, 'webpack/hot/only-dev-server'];
    config.plugins.push(new webpack.HotModuleReplacementPlugin());
  }

  var compiler = webpack(config);
  new WebpackDevServer(compiler, {
      contentBase: destPath,
      noInfo: true
      hot: options.hot,
      colors: true
  }).listen(3000, "localhost", function(err) {
        if(err) {
          throw new gutil.PluginError("webpack-dev-server", err);
        }
        // keep the server alive or continue?
        // callback();
  });
}

/*
 * Create distribution for given webpack configuration
 */
function plainBundle(config, callback) {
  webpack(config, function(err, stats) {
      if (err) {
        gutil.log("[webpack]", err);
        process.exit(1);
      }
      gutil.log("[webpack]", stats.toString({chunks: false}));
      callback();
  });
}

/*
 * Get the webpack loaders object for the webpack configuration
 */
function getLoaders() {
  return [
      {
        test: /\.(js|jsx)$/,
        loader: 'babel',
        //loaders: ['react-hot', 'babel-loader'],
        include: [
          process.cwd() + '/src',
          process.cwd() + '/temp',
          process.cwd() + '/node_modules/lucify-commons/src' // TODO
        ],
        query: {
          presets: [
            // https://github.com/babel/babel-loader/issues/166
            require.resolve('babel-preset-es2015'),
            require.resolve('babel-preset-stage-0'),
            require.resolve('babel-preset-react')
          ]
        }
      },
      {
        test: /\.css$/,
        loaders: [
          'style-loader',
          'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
          'postcss-loader'
        ]
      },
      {
        test: /\.svg$/,
        loader: 'url-loader?limit=10000&mimetype=image/svg+xml'
      },
      {
        test: /\.scss$/,
        loaders: ["style", "css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]", "sass"]
      },
      {
        test: /\.(jpeg|jpg|gif|png|json)$/,
        loaders: ["file-loader?name=[name]-[hash:12].[ext]"]
      },
      {
        test: /\.hbs$/,
        loader: "handlebars"
      }
  ];
}

module.exports = bundle;
<commit_msg>Use require.resolve to find embed.hbs<commit_after>
var sprintf = require('sprintf');
var gutil = require('gulp-util');
var extend = require('object-extend');

var gulpWebpack = require('webpack-stream');
var WebpackDevServer = require("webpack-dev-server");
var HtmlWebpackPlugin = require('html-webpack-plugin')

var gulp = require('gulp');
var src  = gulp.src;
var dest = gulp.dest;

var webpack = require('webpack'),
path = require('path');

var parseArgs = require('minimist');

var options = parseArgs(process.argv, {default: {
  hot: false
}});

/*
 *  Bundle a component
 *
 *  entryPoint        - the entry point for the bundle
 *  outputFileName    - file name for produced bundle
 *  destPath          - destination path for produced bundle,
 *                      relative to the root directory of the project
 *                      being built
 *  pageDefs          - options to pass on into the template
 *                      for each index.html entry point to be
 *                      generated. must be either an array (or null,
 *                      if no index.html:s need to be generated)
 *  watch             - start webpack-dev-server with hot reloading
 *                      setting this true will cause this to block
 */
function bundle(entryPoint, outputFileName, destPath, pageDefs, watch, assetContext, callback) {

  var config = {
     resolve: {
       modulesDirectories: ['node_modules', 'components'],
       root: [path.resolve(__dirname,'../node_modules')]
     },
     module: {
       loaders: getLoaders()
     },
     resolveLoader: {
      root: [path.resolve(__dirname, '../node_modules')],
      modulesDirectories: ['node_modules'],
     },
     output: {
      filename: outputFileName,
      path: process.cwd() + "/" + destPath,
      publicPath: '/' + assetContext
     },
     entry: entryPoint,
     plugins: htmlWebpackPluginsFromPageDefs(pageDefs, watch),
  };

  if (watch) {
    devServerBundle(config, destPath);
    return;
  }
  plainBundle(config, callback);
}

//
// Private functions
// -----------------
//

/*
 * Create HtmlWebpack plugin entries
 * based on given page defs
 */
function htmlWebpackPluginsFromPageDefs(pageDefs, watch) {
    var arr;
    if (Array.isArray(pageDefs)) {
      arr = pageDefs;
    } else {
      return [];
    }

    return arr.map(item => {
        if (!item.path) {
          item.path = '';
        }
        var config = {
            template: require.resolve('lucify-component-builder/src/www/embed.hbs'),
            inject: false,
            filename: path.join(item.path, 'index.html'),
            devServer: watch // note: this is also needed for hot module replacement
        };
        var fullConfig = extend(config, item);
        return new HtmlWebpackPlugin(fullConfig);
    });
}

/*
 * Start webpack dev server for given webpack configuration
 */
function devServerBundle(config, destPath) {
  config.output.publicPath = '/';

  if (!options.hot) {
    // setup for automatic refresh
    // https://webpack.github.io/docs/webpack-dev-server.html#automatic-refresh
    config.entry = ['webpack-dev-server/client?http://localhost:3000', config.entry];

  } else {
    // Experimental setup for hot module replacement
    // enable via --hot option
    //
    // This seems to work correctly, but we get a message that
    // some modules could not be updated, as they would need a
    // full reload. I suspect this is related to the use of higher-order
    // components.
    //
    // https://medium.com/@dan_abramov/the-death-of-react-hot-loader-765fa791d7c4#.wrqoafdic
    // https://gaearon.github.io/react-hot-loader/getstarted/
    // https://webpack.github.io/docs/hot-module-replacement-with-webpack.html
    config.entry = [config.entry, 'webpack/hot/only-dev-server'];
    config.plugins.push(new webpack.HotModuleReplacementPlugin());
  }

  var compiler = webpack(config);
  new WebpackDevServer(compiler, {
      contentBase: destPath,
      noInfo: true
      hot: options.hot,
      colors: true
  }).listen(3000, "localhost", function(err) {
        if(err) {
          throw new gutil.PluginError("webpack-dev-server", err);
        }
        // keep the server alive or continue?
        // callback();
  });
}

/*
 * Create distribution for given webpack configuration
 */
function plainBundle(config, callback) {
  webpack(config, function(err, stats) {
      if (err) {
        gutil.log("[webpack]", err);
        process.exit(1);
      }
      gutil.log("[webpack]", stats.toString({chunks: false}));
      callback();
  });
}

/*
 * Get the webpack loaders object for the webpack configuration
 */
function getLoaders() {
  return [
      {
        test: /\.(js|jsx)$/,
        loader: 'babel',
        //loaders: ['react-hot', 'babel-loader'],
        include: [
          process.cwd() + '/src',
          process.cwd() + '/temp',
          process.cwd() + '/node_modules/lucify-commons/src' // TODO
        ],
        query: {
          presets: [
            // https://github.com/babel/babel-loader/issues/166
            require.resolve('babel-preset-es2015'),
            require.resolve('babel-preset-stage-0'),
            require.resolve('babel-preset-react')
          ]
        }
      },
      {
        test: /\.css$/,
        loaders: [
          'style-loader',
          'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
          'postcss-loader'
        ]
      },
      {
        test: /\.svg$/,
        loader: 'url-loader?limit=10000&mimetype=image/svg+xml'
      },
      {
        test: /\.scss$/,
        loaders: ["style", "css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]", "sass"]
      },
      {
        test: /\.(jpeg|jpg|gif|png|json)$/,
        loaders: ["file-loader?name=[name]-[hash:12].[ext]"]
      },
      {
        test: /\.hbs$/,
        loader: "handlebars"
      }
  ];
}

module.exports = bundle;
<|endoftext|>


<commit_before>'use strict';

function draw_logic(){
    columns = Math.floor(canvas_properties['width'] / core_storage_data['step-x']);
    rows = Math.floor(canvas_properties['height'] / 80);

    let step_x_half = core_storage_data['step-x'] / 2;

    let row = rows;
    do{
        let row_y = canvas_properties['height'] - row * 80 - 50;

        let column = columns;
        do{
            let column_x =
              column * core_storage_data['step-x']
              + (row % 2 === 0 ? step_x_half : 0);

            canvas_draw_path({
              'properties': {
                'fillStyle': color_left,
              },
              'vertices': [
                {
                  'type': 'moveTo',
                  'x': column_x,
                  'y': row_y,
                },
                {
                  'x': column_x + step_x_half,
                  'y': row_y - 30,
                },
                {
                  'x': column_x + step_x_half,
                  'y': row_y + 20,
                },
                {
                  'x': column_x,
                  'y': row_y + 50,
                },
              ],
            });

            column_x =
              column * core_storage_data['step-x']
              - (row % 2 === 0 ? step_x_half : 0);

            canvas_draw_path({
              'properties': {
                'fillStyle': color_right,
              },
              'vertices': [
                {
                  'type': 'moveTo',
                  'x': column_x + step_x_half,
                  'y': row_y - 30,
                },
                {
                  'x': column_x + core_storage_data['step-x'],
                  'y': row_y,
                },
                {
                  'x': column_x + core_storage_data['step-x'],
                  'y': row_y + 50,
                },
                {
                  'x': column_x + step_x_half,
                  'y': row_y + 20,
                },
              ],
            });
        }while(column--);
    }while(row--);
}

function repo_init(){
    core_repo_init({
      'events': {
        'randomize': {
          'onclick': core_repo_reset,
        },
      },
      'globals': {
        'color_left': '',
        'color_right': '',
        'columns': 0,
        'rows': 0,
      },
      'info': '<input id=randomize type=button value="Randomize Colors">',
      'menu': true,
      'reset': update_colors,
      'storage': {
        'step-x': 200,
      },
      'storage-menu': '

<input id=step-x>Step X
',
      'title': 'ColorSteps.htm',
    });
    canvas_init();

    update_colors();
}
<commit_msg>replaced some let with const<commit_after>'use strict';

function draw_logic(){
    columns = Math.floor(canvas_properties['width'] / core_storage_data['step-x']);
    rows = Math.floor(canvas_properties['height'] / 80);

    const step_x_half = core_storage_data['step-x'] / 2;

    let row = rows;
    do{
        const row_y = canvas_properties['height'] - row * 80 - 50;

        let column = columns;
        do{
            let column_x =
              column * core_storage_data['step-x']
              + (row % 2 === 0 ? step_x_half : 0);

            canvas_draw_path({
              'properties': {
                'fillStyle': color_left,
              },
              'vertices': [
                {
                  'type': 'moveTo',
                  'x': column_x,
                  'y': row_y,
                },
                {
                  'x': column_x + step_x_half,
                  'y': row_y - 30,
                },
                {
                  'x': column_x + step_x_half,
                  'y': row_y + 20,
                },
                {
                  'x': column_x,
                  'y': row_y + 50,
                },
              ],
            });

            column_x =
              column * core_storage_data['step-x']
              - (row % 2 === 0 ? step_x_half : 0);

            canvas_draw_path({
              'properties': {
                'fillStyle': color_right,
              },
              'vertices': [
                {
                  'type': 'moveTo',
                  'x': column_x + step_x_half,
                  'y': row_y - 30,
                },
                {
                  'x': column_x + core_storage_data['step-x'],
                  'y': row_y,
                },
                {
                  'x': column_x + core_storage_data['step-x'],
                  'y': row_y + 50,
                },
                {
                  'x': column_x + step_x_half,
                  'y': row_y + 20,
                },
              ],
            });
        }while(column--);
    }while(row--);
}

function repo_init(){
    core_repo_init({
      'events': {
        'randomize': {
          'onclick': core_repo_reset,
        },
      },
      'globals': {
        'color_left': '',
        'color_right': '',
        'columns': 0,
        'rows': 0,
      },
      'info': '<input id=randomize type=button value="Randomize Colors">',
      'menu': true,
      'reset': update_colors,
      'storage': {
        'step-x': 200,
      },
      'storage-menu': '

<input id=step-x>Step X
',
      'title': 'ColorSteps.htm',
    });
    canvas_init();

    update_colors();
}
<|endoftext|>