<commit_before>'use strict';

var templatehandler = require("../engine/templateHandler.js");
var originalprocesspage;
exports.init = function(){
	console.log("Initialisaing preprocessorhook");
	originalprocesspage = templatehandler.processPage;
	templatehandler.processPage = function(errors, page){
		debugger;
		originalprocesspage(errors, page);
		console.log(templatehandler[page.template].tostring());
	}
}

/* //Original Testcode
var A = require("../addons/testbehaviourA.js");
var B = require("../addons/testbehaviourB.js");

exports.init= function(){
	console.log("Test hook is initialising");
	A.behaviour();
	B.behaviour = function(){
		console.log("Modified behaviour");
	};
	A.behaviour();
};*/
<commit_msg>Damn capital letters<commit_after>'use strict';

var templatehandler = require("../engine/templateHandler.js");
var originalprocesspage;
exports.init = function(){
	console.log("Initialisaing preprocessorhook");
	originalprocesspage = templatehandler.processPage;
	templatehandler.processPage = function(errors, page){
		debugger;
		originalprocesspage(errors, page);
		console.log(templatehandler[page.template].toString());
	}
}

/* //Original Testcode
var A = require("../addons/testbehaviourA.js");
var B = require("../addons/testbehaviourB.js");

exports.init= function(){
	console.log("Test hook is initialising");
	A.behaviour();
	B.behaviour = function(){
		console.log("Modified behaviour");
	};
	A.behaviour();
};*/
<|endoftext|>


<commit_before>'use strict';

var toc = require('..');
var utils = require('./utils');
const os = require('os');

/**
 * The basic idea:
 *
 *  1. when front-matter exists, we need to avoid turning its properties into headings.
 *  2. We need to detect toc markers on the page. For now it's a simple HTML code comment
 *     to ensure the markdown is compatible with any parser.
 *
 * @param  {String} `str` Pass a string of markdown
 * @param  {Object} `options` Pass options to toc generation
 * @return {String} Get the same string back with a TOC inserted
 */

module.exports.insert = function(str, options) {
  options = options || {};

  var regex = options.regex || /(?:<!-- toc(?:\s*stop)? .*-->)/g;
  var open = typeof options.open === 'string' ? options.open : '<!-- toc -->\n\n';
  var close = typeof options.close === 'string' ? options.close : '<!-- tocstop -->';
  var obj;

  var newlines = '';
  var m = /\n+$/.exec(str);
  if (m) newlines = m[0];

  // does the file have front-matter?
  if (/^---/.test(str)) {
    // extract it temporarily so the syntax
    // doesn't get mistaken for a heading
    obj = utils.matter(str);
    str = obj.content;
  }

  var sections = split(str, regex);
  console.log(sections)
  if (sections.length > 3) {
    throw new Error('adr-toc only supports one Table of Contents per file.');
  }

  var last = sections[sections.length - 1];
  if (sections.length === 3) {
    sections.splice(1, 1, open + (options.toc || toc(last, options).content));
    sections.splice(2, 0, close);
  }

  if (sections.length === 2) {
    sections.splice(1, 0, open + toc(last, options).content + os.EOL + os.EOL + close);
  }

  var resultString = sections.join('\n\n') + newlines;
  // if front-matter was found, put it back now
  if (obj) {
    return utils.matter.stringify(resultString, obj.data);
  }
  return resultString;
};

module.exports.insertAdrToc = function(str, tocContent, options, dirinsertAdr) {
  options = options || {};

  var regex = options.regex || /(?:<!-- adrlog(?:\s*stop)? .*-->)/g;
  var obj;

  var newlines = '';
  var m = /\n+$/.exec(str);
  if (m) newlines = m[0];

  // does the file have front-matter?
  if (/^---/.test(str)) {
    // extract it temporarily so the syntax
    // doesn't get mistaken for a heading
    obj = utils.matter(str);
    str = obj.content;
  }

  var sections = split(str, regex);

  const start = str.match(/<!-- adrlog .*-->/);
  if (start.length > 0) {
    var open = typeof options.open === 'string' ? options.open : start[0] + os.EOL + os.EOL;
  } else {
    var open = typeof options.open === 'string' ? options.open : '<!-- adrlog -->' + os.EOL + os.EOL;
  }
  const end = str.match(/<!-- adrlogstop .*-->/);
  if (end.length > 0) {
    var close = typeof options.close === 'string' ? options.close : end[0];
  } else {
    var close = typeof options.close === 'string' ? options.close : '<!-- adrlogstop -->';
  }

  if (sections.length > 3) {
    throw new Error('adr-toc only supports one Table of Contents per file.');
  }

  var last = sections[sections.length - 1];
  if (sections.length === 3) {
    sections.splice(1, 1, open + (options.toc || toc(tocContent, options).content));
    sections.splice(2, 0, close);
  }

  if (sections.length === 2) {
    sections.splice(1, 0, open + toc(tocContent, options).content + '\n\n' + close);
  }

  var resultString = sections.join('\n\n') + newlines;
  // if front-matter was found, put it back now
  if (obj) {
    return utils.matter.stringify(resultString, obj.data);
  }
  return resultString;
};

function split(str, re) {
  return str.split(re).map(trim);
}

function trim(str) {
  return str.trim();
}
<commit_msg>Fix error output when there is more than one adrlog requested in the input file<commit_after>'use strict';

var toc = require('..');
var utils = require('./utils');
const os = require('os');

/**
 * The basic idea:
 *
 *  1. when front-matter exists, we need to avoid turning its properties into headings.
 *  2. We need to detect toc markers on the page. For now it's a simple HTML code comment
 *     to ensure the markdown is compatible with any parser.
 *
 * @param  {String} `str` Pass a string of markdown
 * @param  {Object} `options` Pass options to toc generation
 * @return {String} Get the same string back with a TOC inserted
 */

module.exports.insert = function(str, options) {
  options = options || {};

  var regex = options.regex || /(?:<!-- toc(?:\s*stop)? .*-->)/g;
  var open = typeof options.open === 'string' ? options.open : '<!-- toc -->\n\n';
  var close = typeof options.close === 'string' ? options.close : '<!-- tocstop -->';
  var obj;

  var newlines = '';
  var m = /\n+$/.exec(str);
  if (m) newlines = m[0];

  // does the file have front-matter?
  if (/^---/.test(str)) {
    // extract it temporarily so the syntax
    // doesn't get mistaken for a heading
    obj = utils.matter(str);
    str = obj.content;
  }

  var sections = split(str, regex);
  console.log(sections)
  if (sections.length > 3) {
    throw new Error('adr-toc only supports one Table of Contents per file.');
  }

  var last = sections[sections.length - 1];
  if (sections.length === 3) {
    sections.splice(1, 1, open + (options.toc || toc(last, options).content));
    sections.splice(2, 0, close);
  }

  if (sections.length === 2) {
    sections.splice(1, 0, open + toc(last, options).content + os.EOL + os.EOL + close);
  }

  var resultString = sections.join('\n\n') + newlines;
  // if front-matter was found, put it back now
  if (obj) {
    return utils.matter.stringify(resultString, obj.data);
  }
  return resultString;
};

module.exports.insertAdrToc = function(str, tocContent, options, dirinsertAdr) {
  options = options || {};

  var regex = options.regex || /(?:<!-- adrlog(?:\s*stop)? .*-->)/g;
  var obj;

  var newlines = '';
  var m = /\n+$/.exec(str);
  if (m) newlines = m[0];

  // does the file have front-matter?
  if (/^---/.test(str)) {
    // extract it temporarily so the syntax
    // doesn't get mistaken for a heading
    obj = utils.matter(str);
    str = obj.content;
  }

  var sections = split(str, regex);

  const start = str.match(/<!-- adrlog .*-->/);
  if (start.length > 0) {
    var open = typeof options.open === 'string' ? options.open : start[0] + os.EOL + os.EOL;
  } else {
    var open = typeof options.open === 'string' ? options.open : '<!-- adrlog -->' + os.EOL + os.EOL;
  }
  const end = str.match(/<!-- adrlogstop .*-->/);
  if (end.length > 0) {
    var close = typeof options.close === 'string' ? options.close : end[0];
  } else {
    var close = typeof options.close === 'string' ? options.close : '<!-- adrlogstop -->';
  }

  if (sections.length > 3) {
    throw new Error('adr-log only supports one list of ADRs per file.');
  }

  var last = sections[sections.length - 1];
  if (sections.length === 3) {
    sections.splice(1, 1, open + (options.toc || toc(tocContent, options).content));
    sections.splice(2, 0, close);
  }

  if (sections.length === 2) {
    sections.splice(1, 0, open + toc(tocContent, options).content + '\n\n' + close);
  }

  var resultString = sections.join('\n\n') + newlines;
  // if front-matter was found, put it back now
  if (obj) {
    return utils.matter.stringify(resultString, obj.data);
  }
  return resultString;
};

function split(str, re) {
  return str.split(re).map(trim);
}

function trim(str) {
  return str.trim();
}
<|endoftext|>


<commit_before>angular.module('starter.controllers', [])

.controller('AppCtrl', function($scope, $state, $ionicHistory, GameService, AudioService) {
  	$scope.toGame = function() {
		$ionicHistory.nextViewOptions({
			disableBack: true,
			historyRoot: true,
		});
		$state.go('app.game', {});
	}
	$scope.isGameActive = function() {
		return GameService.isActive();
	}

	$scope.isMusicMuted = function() {
		return AudioService.isMusicMuted();
	}
	$scope.isSoundEffectsMuted = function() {
		return AudioService.isEffectsMuted();
	}
	$scope.toggleMusicMute = function() {
		return AudioService.toggleMusicMute();
	}
	$scope.toggleEffectsMute = function() {
		return AudioService.toggleEffectsMute();
	}
})

.controller('IntroCtrl', function($scope, $state, $ionicHistory, $ionicSlideBoxDelegate, GameService) {

	$scope.onPlayGameClick = function() {
		$ionicHistory.nextViewOptions({
			disableBack: true,
			historyRoot: true,
		});
		$state.go('app.game');
	}

	$scope.isActive = function() {
		return GameService.isActive();
	}
})

.controller('RulesCtrl', function($scope, GameService) {
	$scope.costs = [
		{
			name: 'Road',
			cost: '1 wood and 1 clay',
			img: 'img/road.png',
		},
		{
			name: 'Town',
			cost: '1 wood, 1 clay, 1 sheep and 1 grain',
			img: 'img/town.png',
		},
		{
			name: 'City',
			cost: '2 grain and 3 stone',
			img: 'img/city.png',
		},
		{
			name: 'Development Card',
			cost: '1 sheep, 1 grain and 1 stone',
			img: 'img/dev-card-back.png',
		},
	];

	$scope.numSpaceShuttlePartsTarget = GameService.getNumSpaceShuttlePartsTarget();
})

.controller('GameCtrl', function($scope, $stateParams, $ionicModal, GameService, AudioService, ResourceStoreFactory) {

	$scope.locations = []; // List of locations
	$scope.edges = []; // List of edges
	$scope.developmentCards = []; // List of player owned development cards
	$scope.resourceDefs = ['wood', 'clay', 'sheep', 'grain', 'stone'];
	$scope.resourceColors = {wood: '#090', clay: '#faa', sheep: '#5f5', grain: 'yellow', stone: '#999'};
	$scope.resourceTextColors = {wood: '#090', clay: '#c88', sheep: '#2c2', grain: '#990', stone: '#777'};
	$scope.resourceStore = []; // Resources that the player has in the bank
	$scope.lastDiceOutcome = []; // Outcome of last dice throws or null
	$scope.onMoon = false; // Are we on the moon?
	$scope.numTurns = null; // Number of turns
	$scope.numPoints = null; // Number of points
	$scope.detailsLocation = null; // reference to location shown in modal or null
	$scope.detailsEdge = null; // reference to edge shown in modal or null
	$scope.robberResourceList = null; // list of resources to display in robber modal
	$scope.robberNumToKeep = null; // number of resources to keep after being robbed
	$scope.robberAllowClose = null; // is correct number of resources selected so the robber modal can close?
	$scope.edgeModal = null;
	$scope.locationModal = null;
	$scope.developmentCardsModal = null;
	$scope.robberModal = null;
	$scope.tradeModal = null;
	$scope.canBuildRoad = false;
	$scope.canAffordTown = false;
	$scope.canAffordCity = false;
	$scope.canBuyDevelopmentCard = false;
	$scope.canGoToSpace = false;
	$scope.scale = null;   // Draw scale
	$scope.offset = null;  // Draw offset

	var initialize = function() {
		// Edge details modal
		$ionicModal.fromTemplateUrl('templates/edge.html', {
			scope: $scope
		}).then(function(modal) {
			$scope.edgeModal = modal;
		});

		// Location details modal
		$ionicModal.fromTemplateUrl('templates/location.html', {
			scope: $scope
		}).then(function(modal) {
			$scope.locationModal = modal;
		});

		// Development cards modal
		$ionicModal.fromTemplateUrl('templates/development-cards.html', {
			scope: $scope
		}).then(function(modal) {
			$scope.developmentCardsModal = modal;
		});

		// Robber modal
		$ionicModal.fromTemplateUrl('templates/robber.html', {
			scope: $scope
		}).then(function(modal) {
			$scope.robberModal = modal;
		});

		// Trade modal
		$ionicModal.fromTemplateUrl('templates/trade.html', {
			scope: $scope
		}).then(function(modal) {
			$scope.tradeModal = modal;
		});

		// Start game if not started
		if (!GameService.isActive()) {
			AudioService.playMusic();
			GameService.newGame();

		}

		// Update draw offset/scale
		$scope.onWindowResize();
	}

	$scope.updateGameState = function() {
		$scope.locations = GameService.getLocationList();
		$scope.edges = GameService.getEdgeList();
		$scope.developmentCards = GameService.getPlayerDevelopmentCards();
		$scope.resourceStore = GameService.getResourceStore();
		$scope.lastDiceOutcome = GameService.getLastDiceOutcome();
		$scope.canBuildRoad = GameService.canBuildRoad();
		$scope.canAffordTown = GameService.canAffordTown();
		$scope.canAffordCity = GameService.canAffordCity();
		$scope.canBuyDevelopmentCard = GameService.canBuyDevelopmentCard();
		$scope.canGoToSpace = GameService.canGoToSpace();
		$scope.onMoon = GameService.isOnMoon();
		$scope.numTurns = GameService.getNumberOfTurnsPlayed();
		$scope.numPoints = GameService.getNumberOfPoints();
	}

	// Updates draw offset/scale
	$scope.onWindowResize = function() {
		var bar_height = 45;  // top bar takes about 45px
		var win_height = window.innerHeight - bar_height;

		$scope.updateGameState();
		$scope.scale = Math.min(window.innerWidth / GameService.worldWidth() * 0.8, win_height / GameService.worldHeight() * 0.7);
		$scope.xOffset = window.innerWidth / 2;
		$scope.yOffset = win_height / 2 + bar_height;
	}

	$scope.isActive = function() {
		return GameService.isActive();
	}

	$scope.onLocationClick = function(index) {
		var location = $scope.locations[index];
		$scope.showLocationModal(location);
	}
	$scope.onEdgeClick = function(index) {
		var edge = $scope.edges[index];
		$scope.showEdgeModal(edge);
	}
	$scope.onDevelopmentCardsClick = function() {
		$scope.showDevelopmentCardsModal();
	}
	$scope.onTradeClick = function() {
		$scope.showTradeModal();
	}

	$scope.onEndTurnClick = function() {
		GameService.endTurn();
		AudioService.playDiceEffect();
		$scope.updateGameState();

		if ($scope.lastDiceOutcome[0] + $scope.lastDiceOutcome[1] === 7 && $scope.resourceStore.count() > 7) {
			// Show robber modal if have > 7 cards and dice sum was 7
			$scope.showRobberModal();
		}
	}
	$scope.onGoToSpaceClick = function() {
		GameService.goToSpace();
		$scope.updateGameState();
	}
	$scope.onNewGameClick = function() {
		GameService.newGame();
		$scope.updateGameState();
	}

	// Open the edge details modal
	$scope.showEdgeModal = function(edge) {
		$scope.detailsEdge = edge;
		$scope.edgeModal.show();
	};
	$scope.closeEdgeModal = function() {
		$scope.edgeModal.hide();
		$scope.detailsEdge = null;
	};
	$scope.modalEdgeBuildRoad = function() {
		GameService.buildRoad($scope.detailsEdge);
		$scope.closeEdgeModal();
		$scope.updateGameState();
	};

	// Open the location details modal
	$scope.showLocationModal = function(location) {
		$scope.detailsLocation = location;
		$scope.locationModal.show();
	};
	$scope.closeLocationModal = function() {
		$scope.locationModal.hide();
		$scope.detailsLocation = null;
	};
	$scope.modalLocationBuildTown = function() {
		error = {message:''};
		if (!GameService.canBuildTown($scope.detailsLocation, error)) {
			alert(error.message);
			return;
		}
		GameService.buildTown($scope.detailsLocation);
		$scope.updateGameState();
		$scope.closeLocationModal();
	};
	$scope.modalLocationBuildCity = function() {
		error = {message:''};
		if (!GameService.canBuildCity($scope.detailsLocation, error)) {
			alert(error.message);
			return;
		}
		GameService.buildCity($scope.detailsLocation);
		$scope.updateGameState();
		$scope.closeLocationModal();
	};

	// Open the development cards modal
	$scope.showDevelopmentCardsModal = function() {
		$scope.developmentCardsModal.show();
	};
	$scope.closeDevelopmentCardsModal = function() {
		$scope.developmentCardsModal.hide();
	};
	$scope.modalDevelopmentCardsBuyCard = function() {
		GameService.buyDevelopmentCard();
		$scope.updateGameState();
	};
	$scope.modalDevelopmentCardsPlayCard = function(card_obj) {
		GameService.playDevelopmentCard(card_obj);
		$scope.updateGameState();
	};

	// Open the robber modal
	$scope.showRobberModal = function() {
		$scope.robberResourceList = [];
		$scope.robberNumToKeep = 4;
		$scope.robberAllowClose = false;

		// Add one element for each resource into robberResourceList
		$scope.robberResourceList = [];
		var res_def = {wood: null, clay: null, sheep: null, grain: null, stone: null};
		for (res in res_def) {
			for (var i = 0; i < this.resourceStore[res]; i++) {
				$scope.robberResourceList.push({
					type: res,
					selected: false,
				});
			}
		}

		$scope.robberModal.show();
	};
	$scope.modalRobberToggleSelectCard = function(list_item_obj) {
		if (list_item_obj.selected) {
			list_item_obj.selected = false;
			$scope.robberAllowClose = false;
		} else {
			// Ensure we don't select too many cards
			var num_selected = 0;
			for (var i = 0; i < $scope.robberResourceList.length; i++) {
				if ($scope.robberResourceList[i].selected) {
					num_selected++;
				}
			}

			if (num_selected >= $scope.robberNumToKeep) {
				alert('You can only keep ' + $scope.robberNumToKeep + ' resources. Deselect another resource card before you can select this one');
			} else {
				list_item_obj.selected = true;
				num_selected++;

				// Allow close dialog?
				if (num_selected === $scope.robberNumToKeep) {
					$scope.robberAllowClose = true;
				}
			}
		}
	};
	$scope.modalRobberOkay = function() {
		// Count number of resources of each type to give to the robber
		var give_to_robber = ResourceStoreFactory();
		for (var i = 0; i < $scope.robberResourceList.length; i++) {
			if (!$scope.robberResourceList[i].selected) {
				give_to_robber[$scope.robberResourceList[i].type]++;
			}
		}
		GameService.letRobberTake(give_to_robber);

		$scope.robberModal.hide();
	};

	// Open the trade modal
	$scope.showTradeModal = function() {
		$scope.tradeModal.show();
	};
	$scope.closeTradeModal = function() {
		$scope.tradeModal.hide();
	};
	$scope.modalTrade = function() {
	};

	initialize();
})

;
<commit_msg>-Fix: It was possible to dismiss the robber dialog and not give the robber any resources<commit_after>angular.module('starter.controllers', [])

.controller('AppCtrl', function($scope, $state, $ionicHistory, GameService, AudioService) {
  	$scope.toGame = function() {
		$ionicHistory.nextViewOptions({
			disableBack: true,
			historyRoot: true,
		});
		$state.go('app.game', {});
	}
	$scope.isGameActive = function() {
		return GameService.isActive();
	}

	$scope.isMusicMuted = function() {
		return AudioService.isMusicMuted();
	}
	$scope.isSoundEffectsMuted = function() {
		return AudioService.isEffectsMuted();
	}
	$scope.toggleMusicMute = function() {
		return AudioService.toggleMusicMute();
	}
	$scope.toggleEffectsMute = function() {
		return AudioService.toggleEffectsMute();
	}
})

.controller('IntroCtrl', function($scope, $state, $ionicHistory, $ionicSlideBoxDelegate, GameService) {

	$scope.onPlayGameClick = function() {
		$ionicHistory.nextViewOptions({
			disableBack: true,
			historyRoot: true,
		});
		$state.go('app.game');
	}

	$scope.isActive = function() {
		return GameService.isActive();
	}
})

.controller('RulesCtrl', function($scope, GameService) {
	$scope.costs = [
		{
			name: 'Road',
			cost: '1 wood and 1 clay',
			img: 'img/road.png',
		},
		{
			name: 'Town',
			cost: '1 wood, 1 clay, 1 sheep and 1 grain',
			img: 'img/town.png',
		},
		{
			name: 'City',
			cost: '2 grain and 3 stone',
			img: 'img/city.png',
		},
		{
			name: 'Development Card',
			cost: '1 sheep, 1 grain and 1 stone',
			img: 'img/dev-card-back.png',
		},
	];

	$scope.numSpaceShuttlePartsTarget = GameService.getNumSpaceShuttlePartsTarget();
})

.controller('GameCtrl', function($scope, $stateParams, $ionicModal, GameService, AudioService, ResourceStoreFactory) {

	$scope.locations = []; // List of locations
	$scope.edges = []; // List of edges
	$scope.developmentCards = []; // List of player owned development cards
	$scope.resourceDefs = ['wood', 'clay', 'sheep', 'grain', 'stone'];
	$scope.resourceColors = {wood: '#090', clay: '#faa', sheep: '#5f5', grain: 'yellow', stone: '#999'};
	$scope.resourceTextColors = {wood: '#090', clay: '#c88', sheep: '#2c2', grain: '#990', stone: '#777'};
	$scope.resourceStore = []; // Resources that the player has in the bank
	$scope.lastDiceOutcome = []; // Outcome of last dice throws or null
	$scope.onMoon = false; // Are we on the moon?
	$scope.numTurns = null; // Number of turns
	$scope.numPoints = null; // Number of points
	$scope.detailsLocation = null; // reference to location shown in modal or null
	$scope.detailsEdge = null; // reference to edge shown in modal or null
	$scope.robberResourceList = null; // list of resources to display in robber modal
	$scope.robberNumToKeep = null; // number of resources to keep after being robbed
	$scope.robberAllowClose = null; // is correct number of resources selected so the robber modal can close?
	$scope.edgeModal = null;
	$scope.locationModal = null;
	$scope.developmentCardsModal = null;
	$scope.robberModal = null;
	$scope.tradeModal = null;
	$scope.canBuildRoad = false;
	$scope.canAffordTown = false;
	$scope.canAffordCity = false;
	$scope.canBuyDevelopmentCard = false;
	$scope.canGoToSpace = false;
	$scope.scale = null;   // Draw scale
	$scope.offset = null;  // Draw offset

	var initialize = function() {
		// Edge details modal
		$ionicModal.fromTemplateUrl('templates/edge.html', {
			scope: $scope
		}).then(function(modal) {
			$scope.edgeModal = modal;
		});

		// Location details modal
		$ionicModal.fromTemplateUrl('templates/location.html', {
			scope: $scope
		}).then(function(modal) {
			$scope.locationModal = modal;
		});

		// Development cards modal
		$ionicModal.fromTemplateUrl('templates/development-cards.html', {
			scope: $scope
		}).then(function(modal) {
			$scope.developmentCardsModal = modal;
		});

		// Robber modal
		$ionicModal.fromTemplateUrl('templates/robber.html', {
			scope: $scope,
			backdropClickToClose: false,
			hardwareBackButtonClose: false,
		}).then(function(modal) {
			$scope.robberModal = modal;
		});

		// Trade modal
		$ionicModal.fromTemplateUrl('templates/trade.html', {
			scope: $scope
		}).then(function(modal) {
			$scope.tradeModal = modal;
		});

		// Start game if not started
		if (!GameService.isActive()) {
			AudioService.playMusic();
			GameService.newGame();

		}

		// Update draw offset/scale
		$scope.onWindowResize();
	}

	$scope.updateGameState = function() {
		$scope.locations = GameService.getLocationList();
		$scope.edges = GameService.getEdgeList();
		$scope.developmentCards = GameService.getPlayerDevelopmentCards();
		$scope.resourceStore = GameService.getResourceStore();
		$scope.lastDiceOutcome = GameService.getLastDiceOutcome();
		$scope.canBuildRoad = GameService.canBuildRoad();
		$scope.canAffordTown = GameService.canAffordTown();
		$scope.canAffordCity = GameService.canAffordCity();
		$scope.canBuyDevelopmentCard = GameService.canBuyDevelopmentCard();
		$scope.canGoToSpace = GameService.canGoToSpace();
		$scope.onMoon = GameService.isOnMoon();
		$scope.numTurns = GameService.getNumberOfTurnsPlayed();
		$scope.numPoints = GameService.getNumberOfPoints();
	}

	// Updates draw offset/scale
	$scope.onWindowResize = function() {
		var bar_height = 45;  // top bar takes about 45px
		var win_height = window.innerHeight - bar_height;

		$scope.updateGameState();
		$scope.scale = Math.min(window.innerWidth / GameService.worldWidth() * 0.8, win_height / GameService.worldHeight() * 0.7);
		$scope.xOffset = window.innerWidth / 2;
		$scope.yOffset = win_height / 2 + bar_height;
	}

	$scope.isActive = function() {
		return GameService.isActive();
	}

	$scope.onLocationClick = function(index) {
		var location = $scope.locations[index];
		$scope.showLocationModal(location);
	}
	$scope.onEdgeClick = function(index) {
		var edge = $scope.edges[index];
		$scope.showEdgeModal(edge);
	}
	$scope.onDevelopmentCardsClick = function() {
		$scope.showDevelopmentCardsModal();
	}
	$scope.onTradeClick = function() {
		$scope.showTradeModal();
	}

	$scope.onEndTurnClick = function() {
		GameService.endTurn();
		AudioService.playDiceEffect();
		$scope.updateGameState();

		if ($scope.lastDiceOutcome[0] + $scope.lastDiceOutcome[1] === 7 && $scope.resourceStore.count() > 7) {
			// Show robber modal if have > 7 cards and dice sum was 7
			$scope.showRobberModal();
		}
	}
	$scope.onGoToSpaceClick = function() {
		GameService.goToSpace();
		$scope.updateGameState();
	}
	$scope.onNewGameClick = function() {
		GameService.newGame();
		$scope.updateGameState();
	}

	// Open the edge details modal
	$scope.showEdgeModal = function(edge) {
		$scope.detailsEdge = edge;
		$scope.edgeModal.show();
	};
	$scope.closeEdgeModal = function() {
		$scope.edgeModal.hide();
		$scope.detailsEdge = null;
	};
	$scope.modalEdgeBuildRoad = function() {
		GameService.buildRoad($scope.detailsEdge);
		$scope.closeEdgeModal();
		$scope.updateGameState();
	};

	// Open the location details modal
	$scope.showLocationModal = function(location) {
		$scope.detailsLocation = location;
		$scope.locationModal.show();
	};
	$scope.closeLocationModal = function() {
		$scope.locationModal.hide();
		$scope.detailsLocation = null;
	};
	$scope.modalLocationBuildTown = function() {
		error = {message:''};
		if (!GameService.canBuildTown($scope.detailsLocation, error)) {
			alert(error.message);
			return;
		}
		GameService.buildTown($scope.detailsLocation);
		$scope.updateGameState();
		$scope.closeLocationModal();
	};
	$scope.modalLocationBuildCity = function() {
		error = {message:''};
		if (!GameService.canBuildCity($scope.detailsLocation, error)) {
			alert(error.message);
			return;
		}
		GameService.buildCity($scope.detailsLocation);
		$scope.updateGameState();
		$scope.closeLocationModal();
	};

	// Open the development cards modal
	$scope.showDevelopmentCardsModal = function() {
		$scope.developmentCardsModal.show();
	};
	$scope.closeDevelopmentCardsModal = function() {
		$scope.developmentCardsModal.hide();
	};
	$scope.modalDevelopmentCardsBuyCard = function() {
		GameService.buyDevelopmentCard();
		$scope.updateGameState();
	};
	$scope.modalDevelopmentCardsPlayCard = function(card_obj) {
		GameService.playDevelopmentCard(card_obj);
		$scope.updateGameState();
	};

	// Open the robber modal
	$scope.showRobberModal = function() {
		$scope.robberResourceList = [];
		$scope.robberNumToKeep = 4;
		$scope.robberAllowClose = false;

		// Add one element for each resource into robberResourceList
		$scope.robberResourceList = [];
		var res_def = {wood: null, clay: null, sheep: null, grain: null, stone: null};
		for (res in res_def) {
			for (var i = 0; i < this.resourceStore[res]; i++) {
				$scope.robberResourceList.push({
					type: res,
					selected: false,
				});
			}
		}

		$scope.robberModal.show();
	};
	$scope.modalRobberToggleSelectCard = function(list_item_obj) {
		if (list_item_obj.selected) {
			list_item_obj.selected = false;
			$scope.robberAllowClose = false;
		} else {
			// Ensure we don't select too many cards
			var num_selected = 0;
			for (var i = 0; i < $scope.robberResourceList.length; i++) {
				if ($scope.robberResourceList[i].selected) {
					num_selected++;
				}
			}

			if (num_selected >= $scope.robberNumToKeep) {
				alert('You can only keep ' + $scope.robberNumToKeep + ' resources. Deselect another resource card before you can select this one');
			} else {
				list_item_obj.selected = true;
				num_selected++;

				// Allow close dialog?
				if (num_selected === $scope.robberNumToKeep) {
					$scope.robberAllowClose = true;
				}
			}
		}
	};
	$scope.modalRobberOkay = function() {
		// Count number of resources of each type to give to the robber
		var give_to_robber = ResourceStoreFactory();
		for (var i = 0; i < $scope.robberResourceList.length; i++) {
			if (!$scope.robberResourceList[i].selected) {
				give_to_robber[$scope.robberResourceList[i].type]++;
			}
		}
		GameService.letRobberTake(give_to_robber);

		$scope.robberModal.hide();
	};

	// Open the trade modal
	$scope.showTradeModal = function() {
		$scope.tradeModal.show();
	};
	$scope.closeTradeModal = function() {
		$scope.tradeModal.hide();
	};
	$scope.modalTrade = function() {
	};

	initialize();
})

;
<|endoftext|>


<commit_before>'use strict';

angular.module('emission.controllers', ['emission.splash.updatecheck',
                                        'emission.splash.startprefs',
                                        'emission.splash.referral',
                                        'customURLScheme'])

.controller('RootCtrl', function($scope) {})

.controller('DashCtrl', function($scope) {})

.controller('SplashCtrl', function($scope, $state, $interval, $rootScope,
    CustomURLScheme, UpdateCheck, StartPrefs, ReferralHandler) {
  console.log('SplashCtrl invoked');
  alert("attach debugger!");
  CustomURLScheme.onLaunch(function(event, url){
    console.log("GOT URL:"+url);
    var kvList = ReferralHandler.parseURL(url);
    // There are 3 types of users in total
    if (kvList.route == 'join') {
      ReferralHandler.setupGroupReferral(kvList);
    } // can add other routes here if needed
    StartPrefs.loadWithPrefs();
  });
  UpdateCheck.checkForUpdates();
  StartPrefs.startWithPrefs();

  $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
    console.log("Finished changing state from "+JSON.stringify(fromState)
        + " to "+JSON.stringify(toState));
    /*
    if ($rootScope.checkedForUpdates) {
      window.Logger.log(window.Logger.log("Already checked for update, skipping"));
    } else {
      UpdateCheck.checkForUpdates();
      $rootScope.checkedForUpdates = true;
    } */
  });
  $rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error){
    console.log("Error "+error+" while changing state from "+JSON.stringify(fromState)
      +" to "+JSON.stringify(toState));
  });
  $rootScope.$on('$stateNotFound',
    function(event, unfoundState, fromState, fromParams){
        console.log("unfoundState.to = "+unfoundState.to); // "lazy.state"
        console.log("unfoundState.toParams = " + unfoundState.toParams); // {a:1, b:2}
        console.log("unfoundState.options = " + unfoundState.options); // {inherit:false} + default options
  });

  var isInList = function(element, list) {
    return list.indexOf(element) != -1
  }

  $rootScope.$on('$stateChangeStart',
    function(event, toState, toParams, fromState, fromParams, options){
      var personalTabs = ['root.main.common.map',
                          'root.main.control',
                          'root.main.metrics',
                          'root.main.goals',
                          'root.main.diary']
      if (isInList(toState.name, personalTabs)) {
        // toState is in the personalTabs list
        StartPrefs.getPendingOnboardingState().then(function(result) {
          if (result != null) {
            event.preventDefault();
            $state.go(result);
          };
          // else, will do default behavior, which is to go to the tab
        });
      }
  })
  console.log('SplashCtrl invoke finished');
})

.controller('ChatsCtrl', function($scope, Chats) {
  // With the new view caching in Ionic, Controllers are only called
  // when they are recreated or on app start, instead of every page change.
  // To listen for when this page is active (for example, to refresh data),
  // listen for the $ionicView.enter event:
  //
  //$scope.$on('$ionicView.enter', function(e) {
  //});

  $scope.chats = Chats.all();
  $scope.remove = function(chat) {
    Chats.remove(chat);
  };
})

.controller('ChatDetailCtrl', function($scope, $stateParams, Chats) {
  $scope.chat = Chats.get($stateParams.chatId);
})

.controller('AccountCtrl', function($scope) {
  $scope.settings = {
    enableFriends: true
  };
});
<commit_msg>Comment out the debugging alert from the controller<commit_after>'use strict';

angular.module('emission.controllers', ['emission.splash.updatecheck',
                                        'emission.splash.startprefs',
                                        'emission.splash.referral',
                                        'customURLScheme'])

.controller('RootCtrl', function($scope) {})

.controller('DashCtrl', function($scope) {})

.controller('SplashCtrl', function($scope, $state, $interval, $rootScope,
    CustomURLScheme, UpdateCheck, StartPrefs, ReferralHandler) {
  console.log('SplashCtrl invoked');
  // alert("attach debugger!");
  CustomURLScheme.onLaunch(function(event, url){
    console.log("GOT URL:"+url);
    var kvList = ReferralHandler.parseURL(url);
    // There are 3 types of users in total
    if (kvList.route == 'join') {
      ReferralHandler.setupGroupReferral(kvList);
    } // can add other routes here if needed
    StartPrefs.loadWithPrefs();
  });
  UpdateCheck.checkForUpdates();
  StartPrefs.startWithPrefs();

  $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
    console.log("Finished changing state from "+JSON.stringify(fromState)
        + " to "+JSON.stringify(toState));
    /*
    if ($rootScope.checkedForUpdates) {
      window.Logger.log(window.Logger.log("Already checked for update, skipping"));
    } else {
      UpdateCheck.checkForUpdates();
      $rootScope.checkedForUpdates = true;
    } */
  });
  $rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error){
    console.log("Error "+error+" while changing state from "+JSON.stringify(fromState)
      +" to "+JSON.stringify(toState));
  });
  $rootScope.$on('$stateNotFound',
    function(event, unfoundState, fromState, fromParams){
        console.log("unfoundState.to = "+unfoundState.to); // "lazy.state"
        console.log("unfoundState.toParams = " + unfoundState.toParams); // {a:1, b:2}
        console.log("unfoundState.options = " + unfoundState.options); // {inherit:false} + default options
  });

  var isInList = function(element, list) {
    return list.indexOf(element) != -1
  }

  $rootScope.$on('$stateChangeStart',
    function(event, toState, toParams, fromState, fromParams, options){
      var personalTabs = ['root.main.common.map',
                          'root.main.control',
                          'root.main.metrics',
                          'root.main.goals',
                          'root.main.diary']
      if (isInList(toState.name, personalTabs)) {
        // toState is in the personalTabs list
        StartPrefs.getPendingOnboardingState().then(function(result) {
          if (result != null) {
            event.preventDefault();
            $state.go(result);
          };
          // else, will do default behavior, which is to go to the tab
        });
      }
  })
  console.log('SplashCtrl invoke finished');
})

.controller('ChatsCtrl', function($scope, Chats) {
  // With the new view caching in Ionic, Controllers are only called
  // when they are recreated or on app start, instead of every page change.
  // To listen for when this page is active (for example, to refresh data),
  // listen for the $ionicView.enter event:
  //
  //$scope.$on('$ionicView.enter', function(e) {
  //});

  $scope.chats = Chats.all();
  $scope.remove = function(chat) {
    Chats.remove(chat);
  };
})

.controller('ChatDetailCtrl', function($scope, $stateParams, Chats) {
  $scope.chat = Chats.get($stateParams.chatId);
})

.controller('AccountCtrl', function($scope) {
  $scope.settings = {
    enableFriends: true
  };
});
<|endoftext|>


<commit_before>var http = require('http');
var chalk = require('chalk');
var notifier = require('node-notifier');

module.exports = function(urls) {
  var urls = JSON.stringify({objects: urls}),
      headers = {
        'Content-Type': 'application/json',
        'Content-Length': urls.length
      },
      options = {
        host: 'url-caster.appspot.com',
        port: 80,
        path: '/resolve-scan',
        method: 'POST',
        headers: headers
  };

  var req = http.request(options, function(res) {
    res.setEncoding('utf-8');

    var responseString = '';

    res.on('data', function(data) {
      responseString += data;
    });

    res.on('end', function() {
      try {
        var response = JSON.parse(responseString);
        for (var i in response.metadata) {
          var data = response.metadata[i];
          console.log(chalk.underline.bgBlue(' ' + data.title + ' '));
          console.log(chalk.gray(data.description));
          console.log(data.displayUrl);
          console.log();

          notifier.notify({
            title: data.title,
            subtitle: data.displayUrl,
            message: data.description,
            icon: './physicalweb.jpg',
            contentImage: data.icon,
            sound: true,
            wait: true,
            open: data.url
          });
        }
      }
      catch(e) {
        console.log(e);
      }
    });
  });

  req.on('error', function(e) {
    console.log(e);
  });

  req.write(urls);
  req.end();
}<commit_msg>display url only if error getting metadata<commit_after>var http = require('http');
var chalk = require('chalk');
var notifier = require('node-notifier');

module.exports = function(urldata) {
  var urls = JSON.stringify({objects: urldata}),
      headers = {
        'Content-Type': 'application/json',
        'Content-Length': urls.length
      },
      options = {
        host: 'url-caster.appspot.com',
        port: 80,
        path: '/resolve-scan',
        method: 'POST',
        headers: headers
  };

  function urlOnly() {
    var data = JSON.parse(urls);
    for (var i in data.objects) {
      console.log(chalk.underline.bgBlue(' ' + data.objects[i].url + ' '));
      console.log(data.objects[i].url);

      notifier.notify({
        title: data.objects[i].url,
        message: data.objects[i].url,
        icon: './physicalweb.jpg',
        sound: true,
        wait: true,
        open: data.objects[i].url
      });
    }
  }

  var req = http.request(options, function(res) {
    res.setEncoding('utf-8');

    var responseString = '';

    res.on('data', function(data) {
      responseString += data;
    });

    res.on('end', function() {
      try {
        var response = JSON.parse(responseString);
        for (var i in response.metadata) {
          var data = response.metadata[i];
          console.log(chalk.underline.bgBlue(' ' + data.title + ' '));
          console.log(chalk.gray(data.description));
          console.log(data.displayUrl);
          console.log();

          notifier.notify({
            title: data.title,
            subtitle: data.displayUrl,
            message: data.description,
            icon: './physicalweb.jpg',
            contentImage: data.icon,
            sound: true,
            wait: true,
            open: data.url
          });
        }
      }
      catch(e) {
        console.log(e);
        console.log();
        urlOnly();
      }
    });
  });

  req.on('error', function(e) {
    console.log(e);
    console.log();
    urlOnly();
  });

  req.write(urls);
  req.end();
}<|endoftext|>


<commit_before>var GeoCode = (function() {
    var flag= true;

    function init(){
            var address = (document.getElementById('enterlocation'));
            var  autocomplete = new google.maps.places.Autocomplete(address);
            autocomplete.setTypes(['geocode']);
            google.maps.event.addListener(autocomplete, 'place_changed', function() {
                var place = autocomplete.getPlace();
                if (!place.geometry) {
                    return;
                }

            var address = '';
            if (place.address_components) {
                address = [
                    (place.address_components[0] && place.address_components[0].short_name || ''),
                    (place.address_components[1] && place.address_components[1].short_name || ''),
                    (place.address_components[2] && place.address_components[2].short_name || '')
                    ].join(' ');
            }
          });
    }

    function codeAddress(){
        geocoder = new google.maps.Geocoder();
        var address = document.getElementById("enterlocation").value;
        geocoder.geocode( { 'address': address}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {

          //alert("Latitude: "+results[0].geometry.location.lat());
          //alert("Longitude: "+results[0].geometry.location.lng());

    //      document.getElementById("lati").innerHTML = "Latitutde:"+results[0].geometry.location.lat();
    //      document.getElementById("longi").innerHTML = "Longitude:"+results[0].geometry.location.lng();
          if (results[0].geometry.location.lng()>158 && results[0].geometry.location.lng()<160 && results[0].geometry.location.lat()>-32 && results[0].geometry.location.lat()<-31){
                console.log("coordinates match");
                flag = true;
                //alert(flag);
              }
              else{/*alert("Not found");*/ flag=false;}

          }

          else {
            alert("Geocode was not successful for the following reason: " + status);
          }
        });

      // if (flag){alert("Flag is true");}
       //else{alert("Flag is set to false now");}

      }

    $('#enterlocation').onfocus = function(){initialize();};
      // alert("Hi")
      $('#predive').click(function () {
      $.ajax({
             type: "GET",
             // url: "http://api.iobis.org",
             url:"http://api.iobis.org/taxa",
             contentType: "application/json; charset=utf-8",
             dataType: "jsonp",
             data: {

              'geometry': 'POLYGON((158 -31, 158 -32, 160 -32, 160 -31, 158 -31))',
              'limit': 10,
             },
             success: function(data){
              //alert(data.count);
              console.log("data count "+ data.count);
              //var text= $.parseJSON(data);
              // console.log(Object.keys(text));
              var keys = [];
              for(var k in data) keys.push(k);

              console.log("total " + keys.length + " keys: " + keys);
              console.log(data.results);
              //console.log((data.results).length);

              var scientifNameList = [];
              //for (var item in data.results) scientifNameList.push(item['scientificName']);
              for (i=0;i<(data.results).length;i++){

                scientifNameList.push(data.results[i]['species']);
                console.log(scientifNameList[i]);
              }
              console.log(scientifNameList[0]);

            var div_display = document.getElementById('list_display');

            // say that fruits contains all your data
            //var fruits = ['Apples','Bananas','Pineapples','Peaches','Grapes'],
                ul = document.createElement('ul'); // create an arbitrary ul element

            // loop through the fruits array
            for(var i in scientifNameList) {
                    // create an arbitrary li element
              var li = document.createElement('li'),
                 content = document.createTextNode(scientifNameList[i]); // create a textnode to the document

              li.appendChild(content); // append the created textnode above to the li element
              ul.appendChild(li); // append the created li element above to the ul element
            }

            div_display.appendChild(ul); // finally the ul element to the div with an id of placeholder

            },

             error: function (jqXHR, status) {
                 console.log("Problem");
             }
            });
        });
    // $.ajax({
    //     url: 'http://api.iobis.org/',
    //     type: 'GET',
    //     data: {
    //     // 'ID=1&Name=John&Age=10', // or $('#myform').serializeArray()

    //   },
    //     success: function() { alert('GET completed'); }

    // });

    return {
    codeAddress: codeAddress,
    init: init
  };
})();<commit_msg>location check, images pending<commit_after>var GeoCode = (function() {
    var flag= true;
    var location_coordinates = null;
    var f = null;

    function init(){
            var address = (document.getElementById('enterlocation'));
            var  autocomplete = new google.maps.places.Autocomplete(address);
            autocomplete.setTypes(['geocode']);
            google.maps.event.addListener(autocomplete, 'place_changed', function() {
                var place = autocomplete.getPlace();
                if (!place.geometry) {
                    return;
                }

            var address = '';
            if (place.address_components) {
                address = [
                    (place.address_components[0] && place.address_components[0].short_name || ''),
                    (place.address_components[1] && place.address_components[1].short_name || ''),
                    (place.address_components[2] && place.address_components[2].short_name || '')
                    ].join(' ');
            }
          });
    }

    function codeAddress(){
        geocoder = new google.maps.Geocoder();
        var address = document.getElementById("enterlocation").value;
        geocoder.geocode( { 'address': address}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {

          //alert("Latitude: "+results[0].geometry.location.lat());
          //alert("Longitude: "+results[0].geometry.location.lng());
    f = 'POLYGON(('+ String(Math.floor(results[0].geometry.location.lng() -1)) +' '+ String(Math.floor(results[0].geometry.location.lat() -1)) + ',' + ' '+ String(Math.floor(results[0].geometry.location.lng() -1)) + ' ' +String(Math.floor(results[0].geometry.location.lat() +1)) + ',' + ' '+ String(Math.floor(results[0].geometry.location.lng() +1)) + ' ' + String(Math.floor(results[0].geometry.location.lat() +1)) + ',' + ' ' + String(Math.floor(results[0].geometry.location.lng() +1)) + ' ' + String(Math.floor(results[0].geometry.location.lat() -1)) + ',' + ' ' + String(Math.floor(results[0].geometry.location.lng() -1)) + ' ' + String(Math.floor(results[0].geometry.location.lat() -1)) + '))';

              console.log(f);
    //      document.getElementById("lati").innerHTML = "Latitutde:"+results[0].geometry.location.lat();
    //      document.getElementById("longi").innerHTML = "Longitude:"+results[0].geometry.location.lng();
          if (results[0].geometry.location.lng()>158 && results[0].geometry.location.lng()<160 && results[0].geometry.location.lat()>-32 && results[0].geometry.location.lat()<-31){
                console.log("coordinates match");
                flag = true;
                location_coordinates = results[0].geometry.location;
                //alert(flag);
              }
              else{/*alert("Not found");*/ flag=false;
                  location_coordinates = results[0].geometry.location;
                  }

          }

          else {
            alert("Geocode was not successful for the following reason: " + status);
          }
        });

      // if (flag){alert("Flag is true");}
       //else{alert("Flag is set to false now");}

      }

    $('#enterlocation').onfocus = function(){initialize();};
      // alert("Hi")
      $('#predive').click(function () {
          var scientifNameList = [];
      $.ajax({
             type: "GET",
             // url: "http://api.iobis.org",
             url:"http://api.iobis.org/taxa",
             contentType: "application/json; charset=utf-8",
             dataType: "jsonp",
             data: {

              'geometry': String(f),
//                 'geometry': POLYGON(((location_address.lng-1) (location_address),,,))
              'limit': 10,
             },
             success: function(data){

              //alert(data.count);
              console.log("data count "+ data.count);
              //var text= $.parseJSON(data);
              // console.log(Object.keys(text));
              var keys = [];
              for(var k in data) keys.push(k);

              console.log("total " + keys.length + " keys: " + keys);
              console.log(data.results);
              //console.log((data.results).length);

              //for (var item in data.results) scientifNameList.push(item['scientificName']);
              for (i=0;i<(data.results).length;i++){

                scientifNameList.push(data.results[i]['species']);
                console.log(scientifNameList[i]);
              }
              console.log(scientifNameList[0]);
                 if (flag==true){
                     console.log("Flag is true, proceeding to specific display");
                 }
                 else{
                     console.log("Flag is not true, proceed to generic display");
                 }

                // if(window.flag==true){
            var div_display = document.getElementById('list_display');

            // say that fruits contains all your data
            //var fruits = ['Apples','Bananas','Pineapples','Peaches','Grapes'],
                ul = document.createElement('ul'); // create an arbitrary ul element

            // loop through the fruits array
            for(var i in scientifNameList) {
                    // create an arbitrary li element
              var li = document.createElement('li'),
//                  if (scientifNameList[i] == undefined){
//                      continue;
//                  }
                 content = document.createTextNode(scientifNameList[i]); // create a textnode to the document
              console.log(scientifNameList[i]);
              li.appendChild(content); // append the created textnode above to the li element
              ul.appendChild(li); // append the created li element above to the ul element
            }

            div_display.appendChild(ul); // finally the ul element to the div with an id of placeholder

            },

             error: function (jqXHR, status) {
                 console.log("Problem");
             }
            // }
            });
        });
    // $.ajax({
    //     url: 'http://api.iobis.org/',
    //     type: 'GET',
    //     data: {
    //     // 'ID=1&Name=John&Age=10', // or $('#myform').serializeArray()

    //   },
    //     success: function() { alert('GET completed'); }

    // });

    return {
    codeAddress: codeAddress,
    init: init
  };
})();<|endoftext|>


<commit_before>/**
* Copyright (c) Microsoft.  All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

// Module dependencies.
var xmlbuilder = require('xmlbuilder');
var _ = require('underscore');

var azureutil = require('./util');
var Constants = require('./constants');

exports = module.exports;

/*
* Writes a single property for an entry or complex type.
*
* @param {object} parentElement         Parent DOM element under which the property should be added.
* @param {string} name                  Property name.
* @param {object} value                 Property value.
* @return {object} The current DOM element.
*/
function _writeElementValue(parentElement, name, value) {
  var ignored = false;
  var propertyTagName = name;

  if (!azureutil.stringIsEmpty(value) &&
      _.isObject(value) &&
      !_.isDate(value)) {

    if (Array.isArray(value) && value.length > 0) {
      // Example:
      // JSON: element: [ { property1: 'hi there' }, { property2: 'hello there' } ]
      // XML: <element><property1>hi there</property1></element><element><property2>hello there</property2></element>

      Object.keys(value).forEach(function (i) {
        parentElement = _writeElementValue(parentElement, name, value[i]);
      });

      // For an array no element was actually added at this level, so skip uping level.
      ignored = true;
    } else if (value[Constants.XML_METADATA_MARKER] !== undefined &&
      value[Constants.XML_VALUE_MARKER] !== undefined) {
      // Example:
      // JSON: element: { '$': { 'm:type' = 'Edm.String' }, '_': 'hi there' }
      // XML: <element m:type="Edm.String">hi there</element>

      parentElement = parentElement.ele(propertyTagName);
      if (!azureutil.stringIsEmpty(value[Constants.XML_VALUE_MARKER])) {
        if (azureutil.stringStartsWith(value[Constants.XML_VALUE_MARKER], '<![CDATA[')) {
          parentElement = parentElement.raw(value[Constants.XML_VALUE_MARKER]);
        } else {
          parentElement = parentElement.txt(value[Constants.XML_VALUE_MARKER]);
        }
      }
    } else {
      // Example:
      // JSON: element: { '$': { 'metadata' = 'value' }, 'property1': 'hi there', 'property2': 'hello there' }
      // XML: <element metadata="value"><property1>hi there</property1><property2>hello there</property2></element>

      parentElement = parentElement.ele(propertyTagName);
      for (var propertyName in value) {
        if (propertyName !== Constants.XML_METADATA_MARKER && value.hasOwnProperty(propertyName)) {
          parentElement = _writeElementValue(parentElement, propertyName, value[propertyName]);
        }
      }
    }
  } else {
    parentElement = parentElement.ele(propertyTagName);
    if (!azureutil.stringIsEmpty(value)) {
      if (azureutil.stringStartsWith(value.toString().trim(), '<![CDATA[')) {
        parentElement = parentElement.raw(value.toString());
      } else {
        parentElement = parentElement.txt(value.toString());
      }
    }
  }

  if (value && value[Constants.XML_METADATA_MARKER]) {
    // include the metadata
    var attributeList = value[Constants.XML_METADATA_MARKER];
    Object.keys(attributeList).forEach(function (attribute) {
      parentElement = parentElement.att(attribute, attributeList[attribute]);
    });
  }

  if (!ignored) {
    parentElement = parentElement.up();
  }

  return parentElement;
}

exports.serialize = function (entity) {
  if (azureutil.objectKeysLength(entity) !== 1) {
    throw new Error('Invalid XML root element.');
  }

  var doc = xmlbuilder.create();

  var rootElementName = azureutil.objectFirstKey(entity);

  doc = doc.begin(rootElementName, { version: '1.0', encoding: 'utf-8', standalone: 'yes' });

  if (entity[rootElementName][Constants.XML_METADATA_MARKER]) {
    for (var metadata in entity[rootElementName][Constants.XML_METADATA_MARKER]) {
      if (entity[rootElementName][Constants.XML_METADATA_MARKER].hasOwnProperty(metadata)) {
        doc.att(metadata, entity[rootElementName][Constants.XML_METADATA_MARKER][metadata]);
      }
    }
  }

  for (var attribute in entity[rootElementName]) {
    if (attribute !== Constants.XML_METADATA_MARKER && entity[rootElementName].hasOwnProperty(attribute)) {
      doc = _writeElementValue(doc, attribute, entity[rootElementName][attribute]);
    }
  }

  doc = doc.doc();

  return doc.toString();
};

exports._writeElementValue = _writeElementValue;<commit_msg>Remove standalone<commit_after>/**
* Copyright (c) Microsoft.  All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

// Module dependencies.
var xmlbuilder = require('xmlbuilder');
var _ = require('underscore');

var azureutil = require('./util');
var Constants = require('./constants');

exports = module.exports;

/*
* Writes a single property for an entry or complex type.
*
* @param {object} parentElement         Parent DOM element under which the property should be added.
* @param {string} name                  Property name.
* @param {object} value                 Property value.
* @return {object} The current DOM element.
*/
function _writeElementValue(parentElement, name, value) {
  var ignored = false;
  var propertyTagName = name;

  if (!azureutil.stringIsEmpty(value) &&
      _.isObject(value) &&
      !_.isDate(value)) {

    if (Array.isArray(value) && value.length > 0) {
      // Example:
      // JSON: element: [ { property1: 'hi there' }, { property2: 'hello there' } ]
      // XML: <element><property1>hi there</property1></element><element><property2>hello there</property2></element>

      Object.keys(value).forEach(function (i) {
        parentElement = _writeElementValue(parentElement, name, value[i]);
      });

      // For an array no element was actually added at this level, so skip uping level.
      ignored = true;
    } else if (value[Constants.XML_METADATA_MARKER] !== undefined &&
      value[Constants.XML_VALUE_MARKER] !== undefined) {
      // Example:
      // JSON: element: { '$': { 'm:type' = 'Edm.String' }, '_': 'hi there' }
      // XML: <element m:type="Edm.String">hi there</element>

      parentElement = parentElement.ele(propertyTagName);
      if (!azureutil.stringIsEmpty(value[Constants.XML_VALUE_MARKER])) {
        if (azureutil.stringStartsWith(value[Constants.XML_VALUE_MARKER], '<![CDATA[')) {
          parentElement = parentElement.raw(value[Constants.XML_VALUE_MARKER]);
        } else {
          parentElement = parentElement.txt(value[Constants.XML_VALUE_MARKER]);
        }
      }
    } else {
      // Example:
      // JSON: element: { '$': { 'metadata' = 'value' }, 'property1': 'hi there', 'property2': 'hello there' }
      // XML: <element metadata="value"><property1>hi there</property1><property2>hello there</property2></element>

      parentElement = parentElement.ele(propertyTagName);
      for (var propertyName in value) {
        if (propertyName !== Constants.XML_METADATA_MARKER && value.hasOwnProperty(propertyName)) {
          parentElement = _writeElementValue(parentElement, propertyName, value[propertyName]);
        }
      }
    }
  } else {
    parentElement = parentElement.ele(propertyTagName);
    if (!azureutil.stringIsEmpty(value)) {
      if (azureutil.stringStartsWith(value.toString().trim(), '<![CDATA[')) {
        parentElement = parentElement.raw(value.toString());
      } else {
        parentElement = parentElement.txt(value.toString());
      }
    }
  }

  if (value && value[Constants.XML_METADATA_MARKER]) {
    // include the metadata
    var attributeList = value[Constants.XML_METADATA_MARKER];
    Object.keys(attributeList).forEach(function (attribute) {
      parentElement = parentElement.att(attribute, attributeList[attribute]);
    });
  }

  if (!ignored) {
    parentElement = parentElement.up();
  }

  return parentElement;
}

exports.serialize = function (entity) {
  if (azureutil.objectKeysLength(entity) !== 1) {
    throw new Error('Invalid XML root element.');
  }

  var doc = xmlbuilder.create();

  var rootElementName = azureutil.objectFirstKey(entity);

  doc = doc.begin(rootElementName, { version: '1.0', encoding: 'utf-8' });

  if (entity[rootElementName][Constants.XML_METADATA_MARKER]) {
    for (var metadata in entity[rootElementName][Constants.XML_METADATA_MARKER]) {
      if (entity[rootElementName][Constants.XML_METADATA_MARKER].hasOwnProperty(metadata)) {
        doc.att(metadata, entity[rootElementName][Constants.XML_METADATA_MARKER][metadata]);
      }
    }
  }

  for (var attribute in entity[rootElementName]) {
    if (attribute !== Constants.XML_METADATA_MARKER && entity[rootElementName].hasOwnProperty(attribute)) {
      doc = _writeElementValue(doc, attribute, entity[rootElementName][attribute]);
    }
  }

  doc = doc.doc();

  return doc.toString();
};

exports._writeElementValue = _writeElementValue;<|endoftext|>


<commit_before>var App = (function (app, $) {

    app.Geolocation = (function () {

        function formatDate(d) {
            return d.toLocaleTimeString();
        }

        function onRequestSuccess(position) {
            var container = $('.geolocation'),
                date = new Date(position.timestamp);

            $('.geolocation .request').hide();

            $('.latitude', container).text(position.coords.latitude);
            $('.longitude', container).text(position.coords.longitude);
            $('.accuracy', container).text(position.coords.accuracy);
            $('.altitude', container).text(position.coords.altitude);
            $('.altitudeAccuracy', container).text(position.coords.altitudeAccuracy);
            $('.heading', container).text(position.coords.heading);
            $('.speed', container).text(position.coords.speed);
            $('.time', container).text(formatDate(date));
        }

        function onRequestError(error) {
            alert('code: '    + error.code    + '\n' +
                'message: ' + error.message + '\n');
        }

        function requestPosition() {
            $('.geolocation .request').show();
            navigator.geolocation.getCurrentPosition(onRequestSuccess, onRequestError);
        }

        return {
            requestPosition: requestPosition
        };
    }());

    return app;
}(App || {}, jQuery));

<commit_msg>Geolocation: disable status after error<commit_after>var App = (function (app, $) {

    app.Geolocation = (function () {

        function formatDate(d) {
            return d.toLocaleTimeString();
        }

        function onRequestSuccess(position) {
            var container = $('.geolocation'),
                date = new Date(position.timestamp);

            $('.geolocation .request').hide();

            $('.latitude', container).text(position.coords.latitude);
            $('.longitude', container).text(position.coords.longitude);
            $('.accuracy', container).text(position.coords.accuracy);
            $('.altitude', container).text(position.coords.altitude);
            $('.altitudeAccuracy', container).text(position.coords.altitudeAccuracy);
            $('.heading', container).text(position.coords.heading);
            $('.speed', container).text(position.coords.speed);
            $('.time', container).text(formatDate(date));
        }

        function onRequestError(error) {
            $('.geolocation .request').hide();

            alert('code: '    + error.code    + '\n' +
                'message: ' + error.message + '\n');
        }

        function requestPosition() {
            $('.geolocation .request').show();
            navigator.geolocation.getCurrentPosition(onRequestSuccess, onRequestError);
        }

        return {
            requestPosition: requestPosition
        };
    }());

    return app;
}(App || {}, jQuery));

<|endoftext|>


<commit_before>/**
 * This module provides implementations of some of the λ calculus as well as some combinators I use often.
 * @module lambda
 */

var slice = Array.prototype.slice;
var concat = Array.prototype.concat;

/**
 * @function curry
 * @param {function} f The function to curry
 * @param {number} x [x = f.length] The number of arguments to curry
 * @returns {function} Returns a function until all arguments for 'f' are supplied, then returns the result of applying 'f'.
 */
var curry = function curry(f){
  var x = arguments[1] || fn.length;
  return function __curry__(){
    var args = slice.call(arguments);
    return arg.length === x ? fn.apply(null, args) : function(){
       var newArgs = slice.call(arguments);
       return __curry__.apply(null, concat.apply(args, newArgs));
    };
  };
};

/**
 * This is the traditional implementation of compose. It composes two unary functions, passing the result of the first as the argument of the second.
 * @function compose
 * @param {function} f1 The first function to call
 * @param {function} f2 The second function to call, with the result of f1
 * @returns {function} Returns the composition of f1 and f2. Functions are applied from right to left
 *
 * compose :: (b →  c) →  (a →  b) →  a →  c
 */
var compose = function compose(f2, f1){
  return function composed(x){
    return f2(f1(x));
  };
};

/**
 * This is a more robust implementation of compose, allowing for a variadic number of functions to be composed.
 * @function composeMany
 * @param {...function}
 * @returns {function} The composition of all supplied functions, from right to left.
 */
var composeMany = function composeMany(){
  var args = slice.call(arguments);
  if(args.length === 1) return args[0];
  if(args.length === 2) return compose(args[0], args[1]);

  return compose(args.shift, composeMany(args));
};

/**
 * @function before
 * @param {function} d The decorator function
 * @param {function} f The destination function
 * @returns {function} Returns a function (λ) that, when applied, applies function 'd' then function 'f'. Both are called with all arguments passed to λ.
 * @see {link https://leanpub.com/javascript-allonge/read#before}
 */
var before = curry(function before(d, f){
  return function __before__(){
    var args = slice.call(arguments);
    d.apply(null, args);
    f.apply(null, args);
  };
});

module.exports = {
  curry: curry,
  before: before
};
<commit_msg>curry compose<commit_after>/**
 * This module provides implementations of some of the λ calculus as well as some combinators I use often.
 * @module lambda
 */

var slice = Array.prototype.slice;
var concat = Array.prototype.concat;

/**
 * @function curry
 * @param {function} f The function to curry
 * @param {number} x [x = f.length] The number of arguments to curry
 * @returns {function} Returns a function until all arguments for 'f' are supplied, then returns the result of applying 'f'.
 */
var curry = function curry(f){
  var x = arguments[1] || fn.length;
  return function __curry__(){
    var args = slice.call(arguments);
    return arg.length === x ? fn.apply(null, args) : function(){
       var newArgs = slice.call(arguments);
       return __curry__.apply(null, concat.apply(args, newArgs));
    };
  };
};

/**
 * This is the traditional implementation of compose. It composes two unary functions, passing the result of the first as the argument of the second.
 * @function compose
 * @param {function} f1 The first function to call
 * @param {function} f2 The second function to call, with the result of f1
 * @returns {function} Returns the composition of f1 and f2. Functions are applied from right to left
 *
 * compose :: (b →  c) →  (a →  b) →  a →  c
 */
var compose = curry(function compose(f2, f1){
  return function composed(x){
    return f2(f1(x));
  };
});

/**
 * This is a more robust implementation of compose, allowing for a variadic number of functions to be composed.
 * @function composeMany
 * @param {...function}
 * @returns {function} The composition of all supplied functions, from right to left.
 */
var composeMany = function composeMany(){
  var args = slice.call(arguments);
  if(args.length === 1) return args[0];
  if(args.length === 2) return compose(args[0], args[1]);

  return compose(args.shift, composeMany(args));
};

/**
 * @function before
 * @param {function} d The decorator function
 * @param {function} f The destination function
 * @returns {function} Returns a function (λ) that, when applied, applies function 'd' then function 'f'. Both are called with all arguments passed to λ.
 * @see {link https://leanpub.com/javascript-allonge/read#before}
 */
var before = curry(function before(d, f){
  return function __before__(){
    var args = slice.call(arguments);
    d.apply(null, args);
    f.apply(null, args);
  };
});

module.exports = {
  curry: curry,
  before: before
};
<|endoftext|>


<commit_before>/* http://developer.apple.com/safari/library/documentation/iPhone/Conceptual/SafariJSDatabaseGuide/UsingtheJavascriptDatabase/UsingtheJavascriptDatabase.html */

function Migrator(db) {
    var migrations = [];
    var doReload = false;
    this.migration = function(number, func){
        migrations[number] = func;
    };
    var doMigration = function(number){
        if(migrations[number]){
            doReload = true;
            db.changeVersion(db.version, String(number), function(t){
                migrations[number](t);
            }, function(err){
                debug.log('DB changeVersion failed: ' + err.message);
            }, function(){
                debug.log('DB migration to ' + String(number) + ' successfull');
                doMigration(number+1);
            });
        } else {
            // migration done, reload
            if(doReload) {
                debug.log('reloading');
                window.location.reload(true);
            }
        }
    };
    this.doIt = function(){
        var initialVersion = parseInt(db.version) || 0;
        try {
            doMigration(initialVersion+1);
        } catch(e) {
            debug.log(e);
        }
    }
}

RadioDb = function() {

    var that = this;

    var db = null;

    var defaultStations = [
    ['Couleur 3',         'http://stream.srg-ssr.ch/couleur3/mp3_128.m3u', 'a'],
    ['SRF 1',             'http://stream.srg-ssr.ch/drs1/mp3_128.m3u', 'a'],
    ['SRF 2',             'http://stream.srg-ssr.ch/drs2/mp3_128.m3u', 'a'],
    ['SRF 3',             'http://stream.srg-ssr.ch/drs3/mp3_128.m3u', 'a'],
    ['SRF 4 News',        'http://stream.srg-ssr.ch/drs4news/mp3_128.m3u', 'a'],
    ['SRF Virus',         'http://stream.srg-ssr.ch/drsvirus/mp3_128.m3u', 'a'],

    ['Backstageradio',    'http://broadcast.infomaniak.ch/backstageradio-high.mp3.m3u','c'],
    ['Energy Zürich',     'http://statslive.infomaniak.ch/playlist/energyzuerich/energyzuerich-high.mp3/playlist.pls', 'c'],
    ['Energy Bern',       'http://statslive.infomaniak.ch/playlist/energybern/energybern-high.mp3/playlist.pls', 'c'],
    ['Radio 1',           'http://radio.nello.tv:80/128k', 'c'],
    ['Radio 105',         'http://stream.105.ch:8000/105fm','c'],
    ['Radio 24',          'http://audiotx01.mp3.green.ch/', 'c'],
    ['Radio Top',         'http://icecast.radiotop.ch/radiotop','c'],
	['Radio Zürisee',     'http://mp3.radio.ch/radiozuerisee128k','c'],
    ['Radio Swiss Clas…', 'http://stream.srg-ssr.ch/rsc_de/mp3_128.m3u', 'd'],
    ['Radio Swiss Jazz',  'http://stream.srg-ssr.ch/rsj/mp3_128.m3u', 'd'],
    ['Radio Swiss Pop',   'http://stream.srg-ssr.ch/rsp/mp3_128.m3u','d'],
	['SRF Musikwelle',    'http://stream.srg-ssr.ch/drsmw/mp3_128.m3u','d'],
    ['Frequence Banane',  'http://www.frequencebanane.ch/fb_128.m3u', 'e'],
    ['Option Musique',    'http://stream.srg-ssr.ch/option-musique/mp3_128.m3u', 'e'],
    ['RSR La Première',   'http://stream.srg-ssr.ch/la-1ere/mp3_128.m3u', 'e'],
    ['Lounge-radio.com',  'http://www.lounge-radio.com/listen128.m3u','f'],
	['Rock Nation',       'http://105-stream-02.datacomm.ch:8000/rocknation', 'f'],
    ['MagicRadio.CH',     'http://www.magicradio.ch/iphoneAac.m3u','f'],
	['Radio FM1',         'http://radiofm1.ice.infomaniak.ch/playlists/radiofm1-128.mp3.pls','f'],
    ['neo1',              'http://stream-02.neo1.ch/neo1.m3u','f'],
	['Radio X',           'http://mp3.radiox.ch/standard.mp3','f']

    ];

    var ERR_NONDB = 0;
    var ERR_OTHER = 1;
    var ERR_VERSION_MISMATCH = 2;
    var ERR_RESULTSIZE_EXCEEDED = 3;
    var ERR_MAXSIZE_EXCEEDED = 4;
    var ERR_LOCK_ERROR = 5; // contention
    var ERR_CONSTRAINT = 6;

    var upgradeSuccess = function() { debug.log('Successfully upgraded db.'); };
    var upgradeError = function(error) { debug.log('Failed upgrading db.'); return true; /* treat all errs as fatal */ };
    /** Return TRUE for fatal error */
    var errorHandler = function(t, error) {
        if(error.code == ERR_VERSION_MISMATCH) {
            // well, we just log&ignore it.. safari doesn't see the changeVersion effect until restart Oo
            debug.log('ERR_VERSION_MISMATCH');
            return false;
        }
        debug.log('Whoops, DB error: ' + error.message + ' (' + error.code + ')');
        return true; // fatal error
    };

    /** This is used as a data handler for a request that should return no data. */
    var nullDataHandler = function(t, results) {
        return false;
    };

    var insertDefaults = function(t) {
        var insertquery = 'INSERT INTO stations(name, stream, logo, listened_at) VALUES(?, ?, ?, NULL);';
        var selectquery = 'SELECT id, name FROM stations';
        var updatequery = 'UPDATE stations SET stream = ?, logo = ? where id = ?';
        var deletequery = 'DELETE FROM stations where id = ?';
        var defaultStationsName = [];
        for( var i=0; i < defaultStations.length; ++i ) {
            defaultStationsName[defaultStations[i][0]] = defaultStations[i];
            //first we try to insert, then update, this could be improved
            t.executeSql(insertquery, defaultStations[i], nullDataHandler, errorHandler);
        }
        t.executeSql(selectquery, [] , function(t, results) {
            if (results.rows.length == 0) {
                //
            } else {

                for (var j = 0; j < results.rows.length; ++j) {
                    var row = results.rows.item(j);
                    var station = defaultStationsName[row['name']];
                    if (typeof station != 'undefined') {
                        t.executeSql(updatequery,[station[1],station[2],row['id']], nullDataHandler,
                            function(t,error) {
                                console.log("ERRROR UPDATE");
                                console.log(error);
                                return true
                            }
                        );
                    } else {
                        t.executeSql(deletequery ,[row['id']], nullDataHandler,
                            function(t,error) {
                                console.log("ERRROR DELETE");
                                console.log(error);
                                return true
                            }
                        );
                    }

                }

            }
        },
        errorHandler
        );

    };

    this.init = function() {
        try {
            if(!window.openDatabase) {
                alert('Ihr Browser unterstützt kein Local Storage');
            } else {
                db = openDatabase('radios_db', '1', 'Radios Database', 524288); // 512KiB
                debug.log('Current DB Version: ' + db.version);
                db.transaction(function(t) {
                    t.executeSql('CREATE TABLE IF NOT EXISTS stations (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL UNIQUE ON CONFLICT IGNORE, stream TEXT NOT NULL, logo TEXT NOT NULL, listened_at DATE )',
                    [], insertDefaults, errorHandler);
                });
/*
                db = openDatabase('radios_db', '', 'Radios Database', 524288); // 512KiB
                debug.log('Current DB Version: ' + db.version);
                var M = new Migrator(db);
                M.migration(1, function(t) {
                    debug.log('ONE');
                    t.executeSql('CREATE TABLE stations(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL UNIQUE ON CONFLICT IGNORE, stream TEXT NOT NULL, logo TEXT NOT NULL, listened_at DATE )',
                    [], insertDefaults, errorHandler);
                });
                M.doIt();
                */
            }
            return db;
        } catch(e) {
            if(e.code == ERR_VERSION_MISMATCH) {
                debug.log('ERR_VERSION_MISMATCH');
            } else {
                alert('Error: ' + e);
            }
        }
    };

    this.updateListenAt = function(id) {
        db.transaction(function(t) {
            t.executeSql('UPDATE stations SET listened_at = datetime("now","localtime") WHERE id = ?', [ id ], nullDataHandler, errorHandler);
        });
    };

    this.getLastListenedStation = function(resultHandler) {
        db.transaction(function(t) {
            t.executeSql("SELECT id, name, stream, logo, listened_at FROM stations ORDER BY listened_at DESC LIMIT 1", [] , function(t, results) {
                resultHandler( results.rows.length == 0 ? null : results.rows.item(0) );
            }, errorHandler);
        });
    };

    var getStation = function(id, resultHandler, doUpdateListen) {
        if( doUpdateListen )
            that.updateListenAt(id);

        db.transaction(function(t) {
            t.executeSql("SELECT id, name, stream, logo, listened_at FROM stations WHERE id = ?", [ id ] , function(t, results) {
                resultHandler( results.rows.length == 0 ? null : results.rows.item(0) );
            }, errorHandler);
        });
    };

    var getStations = function(resultHandler, filter) {
        var where = '';
        if ( filter ) {
            where = " WHERE name LIKE '%" + filter + "%';"; // FIXME EEEEESCAPE!
        }
        db.transaction(function(t) {
            t.executeSql("SELECT id, name, stream, logo, listened_at FROM stations " + where + " ORDER BY logo ASC, name ASC", [ ] , function(t, results) {
                resultHandler(results.rows);
            }, errorHandler);
        });
    };

    this.insertStation = function(station) {
        db.transaction(function(t) {
            t.executeSql('INSERT INTO stations(name, stream, logo, listened_at) VALUES(?, ?, ?, NULL);', [ station.name, station.stream, station.logo ], nullDataHandler, errorHandler);
        });
    };

    this.autoSearch = function() {
        var searchel = document.getElementById('search-field');
        searchel.onkeyup = function(ev) {
            that.populateStations(searchel.value);
        };
    };

    this.populateStations = function(filter) {
        getStations(function(stations) {
            var ul = document.createElement('ul');
            var li, txt;
            var playing = document.createElement('span');
            var playingOn = document.createTextNode('On');
            playing.setAttribute('class', 'playing');
            playing.appendChild(playingOn);
            radio.playing = playing;
            for( var i=0; i<stations.length; ++i ) {
                li = document.createElement('li');
                txt = document.createTextNode(stations.item(i).name);
                li.appendChild(txt);
                li.setAttribute('id', 'station-'+ stations.item(i).id);
                li.onclick = function(ev) {

                    var id = this.getAttribute('id').split('-')[1];
                    getStation(id, function(station) {
                        var el = document.getElementById('station-'+station.id);

                        if (plugins.AudioStream.getStatus() == 'isPlaying' && station.name == radio.station) {
                            stopSound();
                        } else {
                            radio.station = station.name;
                            radio.stream = station.stream;
                            radio.playingEl = el;
                            radio.clear();
                            radio.noTrack(true);
                            playSound(station.stream);

                        }
                        // remove mute
                        document.getElementById("mute").setAttribute('class', '');
                    }, true);

                };
                ul.appendChild(li);
            }
            // remove current nav
            var statel = document.getElementById("scrollStations");
            if( statel.hasChildNodes() ) {
                while( statel.childNodes.length >= 1 )
                    statel.removeChild(statel.firstChild);
            }
            // append updated nav
            statel.appendChild(ul);
        }, filter);

    };
};

<commit_msg>Added Radio 24 Rock/Pop<commit_after>/* http://developer.apple.com/safari/library/documentation/iPhone/Conceptual/SafariJSDatabaseGuide/UsingtheJavascriptDatabase/UsingtheJavascriptDatabase.html */

function Migrator(db) {
    var migrations = [];
    var doReload = false;
    this.migration = function(number, func){
        migrations[number] = func;
    };
    var doMigration = function(number){
        if(migrations[number]){
            doReload = true;
            db.changeVersion(db.version, String(number), function(t){
                migrations[number](t);
            }, function(err){
                debug.log('DB changeVersion failed: ' + err.message);
            }, function(){
                debug.log('DB migration to ' + String(number) + ' successfull');
                doMigration(number+1);
            });
        } else {
            // migration done, reload
            if(doReload) {
                debug.log('reloading');
                window.location.reload(true);
            }
        }
    };
    this.doIt = function(){
        var initialVersion = parseInt(db.version) || 0;
        try {
            doMigration(initialVersion+1);
        } catch(e) {
            debug.log(e);
        }
    }
}

RadioDb = function() {

    var that = this;

    var db = null;

    var defaultStations = [
    ['Couleur 3',         'http://stream.srg-ssr.ch/couleur3/mp3_128.m3u', 'a'],
    ['SRF 1',             'http://stream.srg-ssr.ch/drs1/mp3_128.m3u', 'a'],
    ['SRF 2',             'http://stream.srg-ssr.ch/drs2/mp3_128.m3u', 'a'],
    ['SRF 3',             'http://stream.srg-ssr.ch/drs3/mp3_128.m3u', 'a'],
    ['SRF 4 News',        'http://stream.srg-ssr.ch/drs4news/mp3_128.m3u', 'a'],
    ['SRF Virus',         'http://stream.srg-ssr.ch/drsvirus/mp3_128.m3u', 'a'],

    ['Backstageradio',    'http://broadcast.infomaniak.ch/backstageradio-high.mp3.m3u','c'],
    ['Energy Zürich',     'http://statslive.infomaniak.ch/playlist/energyzuerich/energyzuerich-high.mp3/playlist.pls', 'c'],
    ['Energy Bern',       'http://statslive.infomaniak.ch/playlist/energybern/energybern-high.mp3/playlist.pls', 'c'],
    ['Radio 1',           'http://radio.nello.tv:80/128k', 'c'],
    ['Radio 105',         'http://stream.105.ch:8000/105fm','c'],
    ['Radio 24',          'http://icecast.radio24.ch/radio24', 'c'],
    ['Radio 24 Rock',     'http://icecast.radio24.ch/radio24rock','c'],
    ['Radio 24 Pop',      'http://icecast.radio24.ch/radio24pop','c'],
    ['Radio Top',         'http://icecast.radiotop.ch/radiotop','c'],
	['Radio Zürisee',     'http://mp3.radio.ch/radiozuerisee128k','c'],
    ['Radio Swiss Clas…', 'http://stream.srg-ssr.ch/rsc_de/mp3_128.m3u', 'd'],
    ['Radio Swiss Jazz',  'http://stream.srg-ssr.ch/rsj/mp3_128.m3u', 'd'],
    ['Radio Swiss Pop',   'http://stream.srg-ssr.ch/rsp/mp3_128.m3u','d'],
	['SRF Musikwelle',    'http://stream.srg-ssr.ch/drsmw/mp3_128.m3u','d'],
    ['Frequence Banane',  'http://www.frequencebanane.ch/fb_128.m3u', 'e'],
    ['Option Musique',    'http://stream.srg-ssr.ch/option-musique/mp3_128.m3u', 'e'],
    ['RSR La Première',   'http://stream.srg-ssr.ch/la-1ere/mp3_128.m3u', 'e'],
    ['Lounge-radio.com',  'http://www.lounge-radio.com/listen128.m3u','f'],
	['Rock Nation',       'http://105-stream-02.datacomm.ch:8000/rocknation', 'f'],
    ['MagicRadio.CH',     'http://www.magicradio.ch/iphoneAac.m3u','f'],
	['Radio FM1',         'http://radiofm1.ice.infomaniak.ch/playlists/radiofm1-128.mp3.pls','f'],
    ['neo1',              'http://stream-02.neo1.ch/neo1.m3u','f'],
	['Radio X',           'http://mp3.radiox.ch/standard.mp3','f']

    ];

    var ERR_NONDB = 0;
    var ERR_OTHER = 1;
    var ERR_VERSION_MISMATCH = 2;
    var ERR_RESULTSIZE_EXCEEDED = 3;
    var ERR_MAXSIZE_EXCEEDED = 4;
    var ERR_LOCK_ERROR = 5; // contention
    var ERR_CONSTRAINT = 6;

    var upgradeSuccess = function() { debug.log('Successfully upgraded db.'); };
    var upgradeError = function(error) { debug.log('Failed upgrading db.'); return true; /* treat all errs as fatal */ };
    /** Return TRUE for fatal error */
    var errorHandler = function(t, error) {
        if(error.code == ERR_VERSION_MISMATCH) {
            // well, we just log&ignore it.. safari doesn't see the changeVersion effect until restart Oo
            debug.log('ERR_VERSION_MISMATCH');
            return false;
        }
        debug.log('Whoops, DB error: ' + error.message + ' (' + error.code + ')');
        return true; // fatal error
    };

    /** This is used as a data handler for a request that should return no data. */
    var nullDataHandler = function(t, results) {
        return false;
    };

    var insertDefaults = function(t) {
        var insertquery = 'INSERT INTO stations(name, stream, logo, listened_at) VALUES(?, ?, ?, NULL);';
        var selectquery = 'SELECT id, name FROM stations';
        var updatequery = 'UPDATE stations SET stream = ?, logo = ? where id = ?';
        var deletequery = 'DELETE FROM stations where id = ?';
        var defaultStationsName = [];
        for( var i=0; i < defaultStations.length; ++i ) {
            defaultStationsName[defaultStations[i][0]] = defaultStations[i];
            //first we try to insert, then update, this could be improved
            t.executeSql(insertquery, defaultStations[i], nullDataHandler, errorHandler);
        }
        t.executeSql(selectquery, [] , function(t, results) {
            if (results.rows.length == 0) {
                //
            } else {

                for (var j = 0; j < results.rows.length; ++j) {
                    var row = results.rows.item(j);
                    var station = defaultStationsName[row['name']];
                    if (typeof station != 'undefined') {
                        t.executeSql(updatequery,[station[1],station[2],row['id']], nullDataHandler,
                            function(t,error) {
                                console.log("ERRROR UPDATE");
                                console.log(error);
                                return true
                            }
                        );
                    } else {
                        t.executeSql(deletequery ,[row['id']], nullDataHandler,
                            function(t,error) {
                                console.log("ERRROR DELETE");
                                console.log(error);
                                return true
                            }
                        );
                    }

                }

            }
        },
        errorHandler
        );

    };

    this.init = function() {
        try {
            if(!window.openDatabase) {
                alert('Ihr Browser unterstützt kein Local Storage');
            } else {
                db = openDatabase('radios_db', '1', 'Radios Database', 524288); // 512KiB
                debug.log('Current DB Version: ' + db.version);
                db.transaction(function(t) {
                    t.executeSql('CREATE TABLE IF NOT EXISTS stations (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL UNIQUE ON CONFLICT IGNORE, stream TEXT NOT NULL, logo TEXT NOT NULL, listened_at DATE )',
                    [], insertDefaults, errorHandler);
                });
/*
                db = openDatabase('radios_db', '', 'Radios Database', 524288); // 512KiB
                debug.log('Current DB Version: ' + db.version);
                var M = new Migrator(db);
                M.migration(1, function(t) {
                    debug.log('ONE');
                    t.executeSql('CREATE TABLE stations(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL UNIQUE ON CONFLICT IGNORE, stream TEXT NOT NULL, logo TEXT NOT NULL, listened_at DATE )',
                    [], insertDefaults, errorHandler);
                });
                M.doIt();
                */
            }
            return db;
        } catch(e) {
            if(e.code == ERR_VERSION_MISMATCH) {
                debug.log('ERR_VERSION_MISMATCH');
            } else {
                alert('Error: ' + e);
            }
        }
    };

    this.updateListenAt = function(id) {
        db.transaction(function(t) {
            t.executeSql('UPDATE stations SET listened_at = datetime("now","localtime") WHERE id = ?', [ id ], nullDataHandler, errorHandler);
        });
    };

    this.getLastListenedStation = function(resultHandler) {
        db.transaction(function(t) {
            t.executeSql("SELECT id, name, stream, logo, listened_at FROM stations ORDER BY listened_at DESC LIMIT 1", [] , function(t, results) {
                resultHandler( results.rows.length == 0 ? null : results.rows.item(0) );
            }, errorHandler);
        });
    };

    var getStation = function(id, resultHandler, doUpdateListen) {
        if( doUpdateListen )
            that.updateListenAt(id);

        db.transaction(function(t) {
            t.executeSql("SELECT id, name, stream, logo, listened_at FROM stations WHERE id = ?", [ id ] , function(t, results) {
                resultHandler( results.rows.length == 0 ? null : results.rows.item(0) );
            }, errorHandler);
        });
    };

    var getStations = function(resultHandler, filter) {
        var where = '';
        if ( filter ) {
            where = " WHERE name LIKE '%" + filter + "%';"; // FIXME EEEEESCAPE!
        }
        db.transaction(function(t) {
            t.executeSql("SELECT id, name, stream, logo, listened_at FROM stations " + where + " ORDER BY logo ASC, name ASC", [ ] , function(t, results) {
                resultHandler(results.rows);
            }, errorHandler);
        });
    };

    this.insertStation = function(station) {
        db.transaction(function(t) {
            t.executeSql('INSERT INTO stations(name, stream, logo, listened_at) VALUES(?, ?, ?, NULL);', [ station.name, station.stream, station.logo ], nullDataHandler, errorHandler);
        });
    };

    this.autoSearch = function() {
        var searchel = document.getElementById('search-field');
        searchel.onkeyup = function(ev) {
            that.populateStations(searchel.value);
        };
    };

    this.populateStations = function(filter) {
        getStations(function(stations) {
            var ul = document.createElement('ul');
            var li, txt;
            var playing = document.createElement('span');
            var playingOn = document.createTextNode('On');
            playing.setAttribute('class', 'playing');
            playing.appendChild(playingOn);
            radio.playing = playing;
            for( var i=0; i<stations.length; ++i ) {
                li = document.createElement('li');
                txt = document.createTextNode(stations.item(i).name);
                li.appendChild(txt);
                li.setAttribute('id', 'station-'+ stations.item(i).id);
                li.onclick = function(ev) {

                    var id = this.getAttribute('id').split('-')[1];
                    getStation(id, function(station) {
                        var el = document.getElementById('station-'+station.id);

                        if (plugins.AudioStream.getStatus() == 'isPlaying' && station.name == radio.station) {
                            stopSound();
                        } else {
                            radio.station = station.name;
                            radio.stream = station.stream;
                            radio.playingEl = el;
                            radio.clear();
                            radio.noTrack(true);
                            playSound(station.stream);

                        }
                        // remove mute
                        document.getElementById("mute").setAttribute('class', '');
                    }, true);

                };
                ul.appendChild(li);
            }
            // remove current nav
            var statel = document.getElementById("scrollStations");
            if( statel.hasChildNodes() ) {
                while( statel.childNodes.length >= 1 )
                    statel.removeChild(statel.firstChild);
            }
            // append updated nav
            statel.appendChild(ul);
        }, filter);

    };
};

<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import {
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';

import coalesceNonElementChildren from './coalesceNonElementChildren';

const systemButtonOpacity = 0.2;

export default class Button extends Component {
    constructor(props) {
    super(props);
  }

  render() {
    var touchableProps = {
      activeOpacity: this._computeActiveOpacity(),
    };
    if (!this.props.disabled) {
      touchableProps.onPress = this.props.onPress;
      touchableProps.onPressIn = this.props.onPressIn;
      touchableProps.onPressOut = this.props.onPressOut;
      touchableProps.onLongPress = this.props.onLongPress;
    }

    return (
      <TouchableOpacity {...touchableProps} testID={this.props.testID} style={this.props.containerStyle}>
        {this._renderGroupedChildren()}
      </TouchableOpacity>
    );
  }

  _renderGroupedChildren() {
    var {disabled} = this.props;
    var style = [
      styles.text,
      disabled ? styles.disabledText : null,
      this.props.style,
      disabled ? this.props.styleDisabled : null,
    ];

    var children = coalesceNonElementChildren(this.props.children, (children, index) => {
      return (
        <Text key={index} style={style}>
          {children}
        </Text>
      );
    });

    switch (children.length) {
      case 0:
        return null;
      case 1:
        return children[0];
      default:
        return <View style={styles.group}>{children}</View>;
    }
  }

  _computeActiveOpacity() {
    if (this.props.disabled) {
      return 1;
    }
    return this.props.activeOpacity != null ?
      this.props.activeOpacity :
      systemButtonOpacity;
  }
};
Button.propTypes = {
      ...TouchableOpacity.propTypes,
    containerStyle: View.propTypes.style,
    disabled: PropTypes.bool,
    style: Text.propTypes.style,
    styleDisabled: Text.propTypes.style,
};
const styles = StyleSheet.create({
  text: {
    color: '#007aff',
    fontFamily: '.HelveticaNeueInterface-MediumP4',
    fontSize: 17,
    fontWeight: 'bold',
    textAlign: 'center',
  },
  disabledText: {
    color: '#dcdcdc',
  },
  group: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
});
<commit_msg>Clean up Button.js<commit_after>import React, { Component, PropTypes } from 'react';
import {
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';

import coalesceNonElementChildren from './coalesceNonElementChildren';

const systemButtonOpacity = 0.2;

export default class Button extends Component {
  static propTypes = {
    ...TouchableOpacity.propTypes,
    containerStyle: View.propTypes.style,
    disabled: PropTypes.bool,
    style: Text.propTypes.style,
    styleDisabled: Text.propTypes.style,
  };

  render() {
    let touchableProps = {
      activeOpacity: this._computeActiveOpacity(),
    };
    if (!this.props.disabled) {
      touchableProps.onPress = this.props.onPress;
      touchableProps.onPressIn = this.props.onPressIn;
      touchableProps.onPressOut = this.props.onPressOut;
      touchableProps.onLongPress = this.props.onLongPress;
    }

    return (
      <TouchableOpacity {...touchableProps} testID={this.props.testID} style={this.props.containerStyle}>
        {this._renderGroupedChildren()}
      </TouchableOpacity>
    );
  }

  _renderGroupedChildren() {
    let { disabled } = this.props;
    let style = [
      styles.text,
      disabled ? styles.disabledText : null,
      this.props.style,
      disabled ? this.props.styleDisabled : null,
    ];

    let children = coalesceNonElementChildren(this.props.children, (children, index) => {
      return (
        <Text key={index} style={style}>
          {children}
        </Text>
      );
    });

    switch (children.length) {
      case 0:
        return null;
      case 1:
        return children[0];
      default:
        return <View style={styles.group}>{children}</View>;
    }
  }

  _computeActiveOpacity() {
    if (this.props.disabled) {
      return 1;
    }
    return this.props.activeOpacity != null ?
      this.props.activeOpacity :
      systemButtonOpacity;
  }
};

const styles = StyleSheet.create({
  text: {
    color: '#007aff',
    fontFamily: '.HelveticaNeueInterface-MediumP4',
    fontSize: 17,
    fontWeight: 'bold',
    textAlign: 'center',
  },
  disabledText: {
    color: '#dcdcdc',
  },
  group: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
});
<|endoftext|>