<commit_before>/* File: main.js
 *
 * Copyright (c) 2014
 * Centre National d’Enseignement à Distance (Cned), Boulevard Nicephore Niepce, 86360 CHASSENEUIL-DU-POITOU, France
 * (direction-innovation@cned.fr)
 *
 * GNU Affero General Public License (AGPL) version 3.0 or later version
 *
 * This file is part of a program which is free software: you can
 * redistribute it and/or modify it under the terms of the
 * GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program.
 * If not, see <http://www.gnu.org/licenses/>.
 *
 */

'use strict';
/* global $ */
/* global listDocument */

angular.module('cnedApp').controller('listDocumentCtrl', function($scope, $rootScope, serviceCheck, $http, $location, dropbox, $window, configuration) {

	$('#titreCompte').hide();
	$('#titreProfile').hide();
	$('#titreDocument').hide();
	$('#titreAdmin').hide();
	$('#titreListDocument').show();

	$scope.files = [];
	$scope.errorMsg = '';
	$scope.displayDestination = false;

	$scope.files = [];
	$scope.errorMsg = '';

	$scope.afficheErreurModifier = false;
	$scope.videModifier = false;

	$scope.initListDocument = function() {
		if (navigator.onLine) {
			console.log('======== you are online ========');
			if (localStorage.getItem('compteId')) {
				var user = serviceCheck.getData();
				user.then(function(result) {
					console.log(result);
					if (result.loged) {
						console.log('======== you are loged =========');
						if (result.dropboxWarning === false) {
							$rootScope.dropboxWarning = false;
							$scope.missingDropbox = false;
							$rootScope.loged = true;
							$rootScope.admin = result.admin;
							$rootScope.apply; // jshint ignore:line
							if ($location.path() !== '/inscriptionContinue') {
								$location.path('/inscriptionContinue');
							}
						} else {
							console.log('=======  you have full account  ========');
							$rootScope.myUser = result.user;
							$rootScope.loged = true;
							$rootScope.admin = result.admin;
							$rootScope.apply; // jshint ignore:line
							if ($rootScope.myUser.dropbox.accessToken) {
								var tmp5 = dropbox.search('.html', $rootScope.myUser.dropbox.accessToken, 'sandbox');
								tmp5.then(function(data) {
									console.log('=======  getting all .html  ========');
									$scope.listDocument = listDocument;
									$scope.initialLenght = $scope.listDocument.length;
									console.log($scope.listDocument);
									for (var i = 0; i < $scope.listDocument.length; i++) {
										var documentExist = false;
										for (var y = 0; y < data.length; y++) {
											if ($scope.listDocument[i].path === data[y].path) {
												console.log('ce document exist');
												documentExist = true;
											}
										}
										if (!documentExist) {
											console.log('ce document nexist pas');
											$scope.listDocument.splice(i);
										}
									}
									console.log($scope.listDocument);
									if ($scope.initialLenght !== $scope.listDocument.length) {

										var tmp7 = dropbox.download('test.html', $rootScope.myUser.dropbox.accessToken, 'sandbox');
										tmp7.then(function(entirePage) {
											var debut = entirePage.search('var listDocument') + 18;
											var fin = entirePage.indexOf('"}];', debut) + 3;
											entirePage = entirePage.replace(entirePage.substring(debut, fin), '[]');
											entirePage = entirePage.replace('listDocument= []', 'listDocument= ' + angular.toJson($scope.listDocument));
											console.log($scope.listDocument);
											var tmp6 = dropbox.upload('test.html', entirePage, $rootScope.myUser.dropbox.accessToken, 'sandbox');
											tmp6.then(function() {
												var tmp3 = dropbox.download('listDocument.appcache', $rootScope.myUser.dropbox.accessToken, 'sandbox');
												tmp3.then(function(dataFromDownload) {
													console.log(dataFromDownload);
													var newVersion = parseInt(dataFromDownload.charAt(29)) + 1;
													dataFromDownload = dataFromDownload.replace(':v' + dataFromDownload.charAt(29), ':v' + newVersion);
													var tmp4 = dropbox.upload('listDocument.appcache', dataFromDownload, $rootScope.myUser.dropbox.accessToken, 'sandbox');
													tmp4.then(function() {
														console.log('new manifest uploaded');
														// window.location.reload();
														alert('reload');
													});
												});
											});
										});
									}
									$('#listDocumentPage').show();
									$scope.listDocument = listDocument;
									// for (i = 0; i < $scope.listDocument.length; i++) {
									// 	$scope.listDocument[i].path = $scope.listDocument[i].path.replace('/', '');
									// }
								});
							} else {
								$location.path('/');
							}
						}
					}
				});
			}
		} else {
			console.log('you are offline');
			/* jshint ignore:start */
			$scope.listDocument = listDocument;
			// for (var i = 0; i < $scope.listDocument.length; i++) {
			// 	$scope.listDocument[i].path = $scope.listDocument[i].path.replace('/', '');
			// };
			$('#listDocumentPage').show();

			/* jshint ignore:end */
		}
	};

	$scope.open = function(path) {
		$scope.deleteLink = path;
	};

	$scope.suprimeDocument = function() {
		if (localStorage.getItem('compte')) {
			var tmp = dropbox.delete($scope.deleteLink, $rootScope.myUser.dropbox.accessToken, 'sandbox');
			tmp.then(function() {
				$('#myModal').modal('hide');
				$scope.initListDocument();
			});
		}
	};

	$scope.openModifieTitre = function(path) {
		$scope.selectedItem = path;
		$scope.afficheErreurModifier = false;
		$scope.videModifier = false;
		$scope.nouveauTitre = '';
	};

	$scope.modifieTitre = function() {
		if ($scope.nouveauTitre !== '') {
			console.log($scope.selectedItem);
			console.log($scope.nouveauTitre);
			$scope.videModifier = false;
			var documentExist = false;
			for (var i = 0; i < $scope.listDocument.length; i++) {
				if ($scope.listDocument[i].path === $scope.nouveauTitre) {
					documentExist = true;
					break;
				}
			}
			if (documentExist) {
				$scope.afficheErreurModifier = true;
			} else {
				$scope.modifieTitreConfirme();
			}
		} else {
			$scope.videModifier = true;
		}
	};

	$scope.modifieTitreConfirme = function() {
		var tmp = dropbox.rename('/' + $scope.selectedItem, '/' + $scope.nouveauTitre + '.html', $rootScope.myUser.dropbox.accessToken, 'sandbox');
		tmp.then(function(result) {
			$scope.newFile = result;
			var tmp2 = dropbox.delete('/' + $scope.selectedItem, $rootScope.myUser.dropbox.accessToken, 'sandbox');
			tmp2.then(function(deleteResult) {
				$scope.oldFile = deleteResult;
				var tmp3 = dropbox.download('test.html', $rootScope.myUser.dropbox.accessToken, 'sandbox');
				tmp3.then(function(entirePage) {
					for (var i = 0; i < listDocument.length; i++) {
						if (listDocument[i].path === $scope.selectedItem) {
							console.log('element a remplacer trouver');
							listDocument[i] = $scope.newFile;
						} // else {
						// 	listDocument[i].path = '/' + listDocument[i].path;
						// }
					}
					var debut = entirePage.search('var listDocument') + 18;
					var fin = entirePage.indexOf('"}];', debut) + 3;
					entirePage = entirePage.replace(entirePage.substring(debut, fin), '[]');
					entirePage = entirePage.replace('listDocument= []', 'listDocument= ' + angular.toJson(listDocument));
					console.log(entirePage);
					var tmp6 = dropbox.upload('test.html', entirePage, $rootScope.myUser.dropbox.accessToken, 'sandbox');
					tmp6.then(function() {
						var tmp3 = dropbox.download('listDocument.appcache', $rootScope.myUser.dropbox.accessToken, 'sandbox');
						tmp3.then(function(dataFromDownload) {
							console.log(dataFromDownload);
							var newVersion = parseInt(dataFromDownload.charAt(29)) + 1;
							dataFromDownload = dataFromDownload.replace(':v' + dataFromDownload.charAt(29), ':v' + newVersion);
							var tmp4 = dropbox.upload('listDocument.appcache', dataFromDownload, $rootScope.myUser.dropbox.accessToken, 'sandbox');
							tmp4.then(function() {
								console.log('new manifest uploaded');
								//window.location.reload();
								alert('reload');
							});
						});
					});
				});
			});
		});
	};
	$scope.ajouterDocument = function() {
		if (!$scope.doc || !$scope.doc.titre || $scope.doc.titre.length <= 0) {
			$scope.errorMsg = 'Le titre est obligatoire !';
			return;
		}
		var searchApercu = dropbox.search($scope.doc.titre + '.html', localStorage.getItem('compte'), configuration.DROPBOX_TYPE);
		searchApercu.then(function(result) {
			if (result && result.length > 0) {
				$scope.errorMsg = 'Le document existe déja dans Dropbox';
			} else {
				if ((!$scope.doc.lienPdf && $scope.files.length <= 0) || ($scope.doc.lienPdf && $scope.files.length > 0)) {
					$scope.errorMsg = 'Veuillez saisir un lien ou uploader un fichier !';
					return;
				}
				$('#addDocumentModal').modal('hide');
				$('#addDocumentModal').on('hidden.bs.modal', function() {
					if ($scope.files.length > 0) {
						$scope.doc.uploadPdf = $scope.files;
					}
					$rootScope.uploadDoc = $scope.doc;
					$scope.doc = {};
					$window.location.href = $location.absUrl().substring(0, $location.absUrl().indexOf('#/') + 2) + 'workspace';
				});
			}
		});
	};

	$scope.setFiles = function(element) {
		$scope.files = [];
		$scope.$apply(function() {
			for (var i = 0; i < element.files.length; i++) {
				if (element.files[i].type !== 'image/jpeg' && element.files[i].type !== 'image/png' && element.files[i].type !== 'application/pdf') {
					$scope.errorMsg = 'Le type de fichier rattaché est non autorisé. Merci de rattacher que des fichiers PDF ou des images.';
					$scope.files = [];
					break;
				} else {
					$scope.files.push(element.files[i]);
				}
			}
		});
	};

	/*load email form*/
	$scope.loadMail = function() {
		$scope.displayDestination = true;
	};
	/*regex email*/
	$scope.verifyEmail = function(email) {
		var reg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if (reg.test(email)) {
			return true;
		} else {
			return false;
		}
	};

	$scope.docPartage = function(param) {
		$scope.docApartager = param;
		$scope.encodeURI = encodeURIComponent($scope.docApartager.lienApercu);
		if ($scope.docApartager && $scope.docApartager.lienApercu) {
			$scope.encodedLinkFb = $scope.docApartager.lienApercu.replace('#', '%23');

		}
	};

	/*envoi de l'email au destinataire*/
	$scope.sendMail = function() {
		console.log('inside mail send');
		$scope.destination = $scope.destinataire;
		if ($scope.verifyEmail($scope.destination)) {
			console.log('ok verify mail');
			if ($scope.docApartager) {
				console.log('ok $scope.document');
				$scope.documentUri = $scope.docApartager.lienApercu.substring(7, $scope.docApartager.lienApercu.length);
				console.log($scope.docApartager.lienApercu.substring(7, $scope.docApartager.lienApercu.length));

				if ($rootScope.myUser.dropbox.accessToken) {
					console.log('ok accessToken');

					if (configuration.DROPBOX_TYPE) {
						console.log('ok DROPBOX_TYPE');

						console.log('resulllt ==>');
						$scope.sendVar = {
							to: $scope.destinataire,
							content: 'je viens de partager avec vous le lien suivant :' + $scope.documentUri,
							encoded: '<div>je viens de partager avec vous le lien suivant :' + $scope.documentUri + ' </div>'
						};
						$http.post(configuration.URL_REQUEST + '/sendMail', $scope.sendVar)
							.success(function(data) {
								console.log('here');
								$scope.sent = data;
								$('#okEmail').fadeIn('fast').delay(5000).fadeOut('fast');
								console.log('sent ===>');
								console.log(data);
								$scope.destinataire = '';

							});

					}

				}

			}

		} else {
			$('#erreurEmail').fadeIn('fast').delay(5000).fadeOut('fast');

		}

	};
});<commit_msg>correction des serivce et enlevement des localStorage<commit_after>/* File: main.js
 *
 * Copyright (c) 2014
 * Centre National d’Enseignement à Distance (Cned), Boulevard Nicephore Niepce, 86360 CHASSENEUIL-DU-POITOU, France
 * (direction-innovation@cned.fr)
 *
 * GNU Affero General Public License (AGPL) version 3.0 or later version
 *
 * This file is part of a program which is free software: you can
 * redistribute it and/or modify it under the terms of the
 * GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program.
 * If not, see <http://www.gnu.org/licenses/>.
 *
 */

'use strict';
/* global $ */
/* global listDocument */

angular.module('cnedApp').controller('listDocumentCtrl', function($scope, $rootScope, serviceCheck, $http, $location, dropbox, $window, configuration) {

	$('#titreCompte').hide();
	$('#titreProfile').hide();
	$('#titreDocument').hide();
	$('#titreAdmin').hide();
	$('#titreListDocument').show();

	$scope.files = [];
	$scope.errorMsg = '';
	$scope.displayDestination = false;

	$scope.files = [];
	$scope.errorMsg = '';

	$scope.afficheErreurModifier = false;
	$scope.videModifier = false;

	$scope.initListDocument = function() {
		if (navigator.onLine) {
			console.log('======== you are online ========');
			if (localStorage.getItem('compteId')) {
				var user = serviceCheck.getData();
				user.then(function(result) {
					console.log(result);
					if (result.loged) {
						console.log('======== you are loged =========');
						if (result.dropboxWarning === false) {
							$rootScope.dropboxWarning = false;
							$scope.missingDropbox = false;
							$rootScope.loged = true;
							$rootScope.admin = result.admin;
							$rootScope.apply; // jshint ignore:line
							if ($location.path() !== '/inscriptionContinue') {
								$location.path('/inscriptionContinue');
							}
						} else {
							console.log('=======  you have full account  ========');
							$rootScope.myUser = result.user;
							$rootScope.loged = true;
							$rootScope.admin = result.admin;
							$rootScope.apply; // jshint ignore:line
							if ($rootScope.myUser.dropbox.accessToken) {
								var tmp5 = dropbox.search('.html', $rootScope.myUser.dropbox.accessToken, 'sandbox');
								tmp5.then(function(data) {
									console.log('=======  getting all .html  ========');
									$scope.listDocument = listDocument;
									$scope.initialLenght = $scope.listDocument.length;
									console.log($scope.listDocument);
									for (var i = 0; i < $scope.listDocument.length; i++) {
										var documentExist = false;
										for (var y = 0; y < data.length; y++) {
											if ($scope.listDocument[i].path === data[y].path) {
												console.log('ce document exist');
												documentExist = true;
											}
										}
										if (!documentExist) {
											console.log('ce document nexist pas');
											$scope.listDocument.splice(i);
										}
									}
									console.log($scope.listDocument);
									if ($scope.initialLenght !== $scope.listDocument.length) {

										var tmp7 = dropbox.download('test.html', $rootScope.myUser.dropbox.accessToken, 'sandbox');
										tmp7.then(function(entirePage) {
											var debut = entirePage.search('var listDocument') + 18;
											var fin = entirePage.indexOf('"}];', debut) + 3;
											entirePage = entirePage.replace(entirePage.substring(debut, fin), '[]');
											entirePage = entirePage.replace('listDocument= []', 'listDocument= ' + angular.toJson($scope.listDocument));
											console.log($scope.listDocument);
											var tmp6 = dropbox.upload('test.html', entirePage, $rootScope.myUser.dropbox.accessToken, 'sandbox');
											tmp6.then(function() {
												var tmp3 = dropbox.download('listDocument.appcache', $rootScope.myUser.dropbox.accessToken, 'sandbox');
												tmp3.then(function(dataFromDownload) {
													console.log(dataFromDownload);
													var newVersion = parseInt(dataFromDownload.charAt(29)) + 1;
													dataFromDownload = dataFromDownload.replace(':v' + dataFromDownload.charAt(29), ':v' + newVersion);
													var tmp4 = dropbox.upload('listDocument.appcache', dataFromDownload, $rootScope.myUser.dropbox.accessToken, 'sandbox');
													tmp4.then(function() {
														console.log('new manifest uploaded');
														// window.location.reload();
														alert('reload');
													});
												});
											});
										});
									}
									$('#listDocumentPage').show();
									$scope.listDocument = listDocument;
									// for (i = 0; i < $scope.listDocument.length; i++) {
									// 	$scope.listDocument[i].path = $scope.listDocument[i].path.replace('/', '');
									// }
								});
							} else {
								$location.path('/');
							}
						}
					}
				});
			}
		} else {
			console.log('you are offline');
			/* jshint ignore:start */
			$scope.listDocument = listDocument;
			// for (var i = 0; i < $scope.listDocument.length; i++) {
			// 	$scope.listDocument[i].path = $scope.listDocument[i].path.replace('/', '');
			// };
			$('#listDocumentPage').show();

			/* jshint ignore:end */
		}
	};

	$scope.open = function(path) {
		$scope.deleteLink = path;
	};

	$scope.suprimeDocument = function() {
		if (localStorage.getItem('compteId')) {
			var tmp = dropbox.delete($scope.deleteLink, $rootScope.myUser.dropbox.accessToken, 'sandbox');
			tmp.then(function() {
				$('#myModal').modal('hide');
				$scope.initListDocument();
			});
		}
	};

	$scope.openModifieTitre = function(path) {
		$scope.selectedItem = path;
		$scope.afficheErreurModifier = false;
		$scope.videModifier = false;
		$scope.nouveauTitre = '';
	};

	$scope.modifieTitre = function() {
		if ($scope.nouveauTitre !== '') {
			console.log($scope.selectedItem);
			console.log($scope.nouveauTitre);
			$scope.videModifier = false;
			var documentExist = false;
			for (var i = 0; i < $scope.listDocument.length; i++) {
				if ($scope.listDocument[i].path === $scope.nouveauTitre) {
					documentExist = true;
					break;
				}
			}
			if (documentExist) {
				$scope.afficheErreurModifier = true;
			} else {
				$scope.modifieTitreConfirme();
			}
		} else {
			$scope.videModifier = true;
		}
	};

	$scope.modifieTitreConfirme = function() {
		var tmp = dropbox.rename('/' + $scope.selectedItem, '/' + $scope.nouveauTitre + '.html', $rootScope.myUser.dropbox.accessToken, 'sandbox');
		tmp.then(function(result) {
			$scope.newFile = result;
			var tmp2 = dropbox.delete('/' + $scope.selectedItem, $rootScope.myUser.dropbox.accessToken, 'sandbox');
			tmp2.then(function(deleteResult) {
				$scope.oldFile = deleteResult;
				var tmp3 = dropbox.download('test.html', $rootScope.myUser.dropbox.accessToken, 'sandbox');
				tmp3.then(function(entirePage) {
					for (var i = 0; i < listDocument.length; i++) {
						if (listDocument[i].path === $scope.selectedItem) {
							console.log('element a remplacer trouver');
							listDocument[i] = $scope.newFile;
						} // else {
						// 	listDocument[i].path = '/' + listDocument[i].path;
						// }
					}
					var debut = entirePage.search('var listDocument') + 18;
					var fin = entirePage.indexOf('"}];', debut) + 3;
					entirePage = entirePage.replace(entirePage.substring(debut, fin), '[]');
					entirePage = entirePage.replace('listDocument= []', 'listDocument= ' + angular.toJson(listDocument));
					console.log(entirePage);
					var tmp6 = dropbox.upload('test.html', entirePage, $rootScope.myUser.dropbox.accessToken, 'sandbox');
					tmp6.then(function() {
						var tmp3 = dropbox.download('listDocument.appcache', $rootScope.myUser.dropbox.accessToken, 'sandbox');
						tmp3.then(function(dataFromDownload) {
							console.log(dataFromDownload);
							var newVersion = parseInt(dataFromDownload.charAt(29)) + 1;
							dataFromDownload = dataFromDownload.replace(':v' + dataFromDownload.charAt(29), ':v' + newVersion);
							var tmp4 = dropbox.upload('listDocument.appcache', dataFromDownload, $rootScope.myUser.dropbox.accessToken, 'sandbox');
							tmp4.then(function() {
								console.log('new manifest uploaded');
								//window.location.reload();
								alert('reload');
							});
						});
					});
				});
			});
		});
	};
	$scope.ajouterDocument = function() {
		if (!$scope.doc || !$scope.doc.titre || $scope.doc.titre.length <= 0) {
			$scope.errorMsg = 'Le titre est obligatoire !';
			return;
		}
		var searchApercu = dropbox.search($scope.doc.titre + '.html', $rootScope.myUser.dropbox.accessToken, configuration.DROPBOX_TYPE);
		searchApercu.then(function(result) {
			if (result && result.length > 0) {
				$scope.errorMsg = 'Le document existe déja dans Dropbox';
			} else {
				if ((!$scope.doc.lienPdf && $scope.files.length <= 0) || ($scope.doc.lienPdf && $scope.files.length > 0)) {
					$scope.errorMsg = 'Veuillez saisir un lien ou uploader un fichier !';
					return;
				}
				$('#addDocumentModal').modal('hide');
				$('#addDocumentModal').on('hidden.bs.modal', function() {
					if ($scope.files.length > 0) {
						$scope.doc.uploadPdf = $scope.files;
					}
					$rootScope.uploadDoc = $scope.doc;
					$scope.doc = {};
					$window.location.href = $location.absUrl().substring(0, $location.absUrl().indexOf('#/') + 2) + 'workspace';
				});
			}
		});
	};

	$scope.setFiles = function(element) {
		$scope.files = [];
		$scope.$apply(function() {
			for (var i = 0; i < element.files.length; i++) {
				if (element.files[i].type !== 'image/jpeg' && element.files[i].type !== 'image/png' && element.files[i].type !== 'application/pdf') {
					$scope.errorMsg = 'Le type de fichier rattaché est non autorisé. Merci de rattacher que des fichiers PDF ou des images.';
					$scope.files = [];
					break;
				} else {
					$scope.files.push(element.files[i]);
				}
			}
		});
	};

	/*load email form*/
	$scope.loadMail = function() {
		$scope.displayDestination = true;
	};
	/*regex email*/
	$scope.verifyEmail = function(email) {
		var reg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if (reg.test(email)) {
			return true;
		} else {
			return false;
		}
	};

	$scope.docPartage = function(param) {
		$scope.docApartager = param;
		$scope.encodeURI = encodeURIComponent($scope.docApartager.lienApercu);
		if ($scope.docApartager && $scope.docApartager.lienApercu) {
			$scope.encodedLinkFb = $scope.docApartager.lienApercu.replace('#', '%23');

		}
	};

	/*envoi de l'email au destinataire*/
	$scope.sendMail = function() {
		console.log('inside mail send');
		$scope.destination = $scope.destinataire;
		if ($scope.verifyEmail($scope.destination)) {
			console.log('ok verify mail');
			if ($scope.docApartager) {
				console.log('ok $scope.document');
				$scope.documentUri = $scope.docApartager.lienApercu.substring(7, $scope.docApartager.lienApercu.length);
				console.log($scope.docApartager.lienApercu.substring(7, $scope.docApartager.lienApercu.length));

				if ($rootScope.myUser.dropbox.accessToken) {
					console.log('ok accessToken');

					if (configuration.DROPBOX_TYPE) {
						console.log('ok DROPBOX_TYPE');

						console.log('resulllt ==>');
						$scope.sendVar = {
							to: $scope.destinataire,
							content: 'je viens de partager avec vous le lien suivant :' + $scope.documentUri,
							encoded: '<div>je viens de partager avec vous le lien suivant :' + $scope.documentUri + ' </div>'
						};
						$http.post(configuration.URL_REQUEST + '/sendMail', $scope.sendVar)
							.success(function(data) {
								console.log('here');
								$scope.sent = data;
								$('#okEmail').fadeIn('fast').delay(5000).fadeOut('fast');
								console.log('sent ===>');
								console.log(data);
								$scope.destinataire = '';

							});

					}

				}

			}

		} else {
			$('#erreurEmail').fadeIn('fast').delay(5000).fadeOut('fast');

		}

	};
});<|endoftext|>


<commit_before>var query = location.search.slice(1);
var Args = {};
console.log("oi")
var chaveValor = query.split('=');
var chave = chaveValor[0];
var valor = chaveValor[1];
Args[chave] = valor;
var videourl = Args["url"];

var scene = document.querySelector('a-scene');
if (scene.hasLoaded) {
    run();
} else {
    scene.addEventListener('loaded', run);
}

function run() {
    var video = scene.querySelector('video');

    video.setAttribute('src', videourl)

}
<commit_msg>Update showvd.js<commit_after>var query = location.search.slice(1);
var Args = {};
console.log("oi")
var chaveValor = query.split('=');
var chave = chaveValor[0];
var valor = chaveValor[1];
Args[chave] = valor;
var videourl = Args["url"];

var scene = document.querySelector('a-scene');
if (scene.hasLoaded) {
    run();
} else {
    scene.addEventListener('loaded', run);
}

function run() {
    var video = scene.querySelector('a-videosphere');

    video.setAttribute('src', videourl)

}
<|endoftext|>


<commit_before>import firebase from 'firebase';
/* eslint-disable import/no-unresolved */
import five from 'johnny-five';
import chipio from 'chip-io';
/* eslint-enable */
import { logger } from './config';
import * as keys from './keys';
import WakeLight from './wakelight';

logger.debug('initializing firebase app');
firebase.initializeApp(keys.config);

const alarmsRef = firebase.database().ref('/alarms');

// init wakelight
const lillianWakeLight = new WakeLight();
const board = new five.Board({
  io: new chipio() // eslint-disable-line
});
board.on('ready', () => {
  // connect to firebase with email/password auth
  firebase.auth()
  .signInWithEmailAndPassword(keys.email, keys.password)
  .then((user) => {
    logger.debug(`${user.email} signed in`);

    // change handler for the alarm status
    const led = new five.Led('XIO-P0');
    led.blink(500);
    setTimeout(() => {
      led.stop();
    }, 5000);
    lillianWakeLight.on('change', (alarmState, time, name) => {
      logger.debug(`${time} ${name} alarm active? ${alarmState}`);
      if (alarmState) {
        logger.debug('alarm active! turning LED on');
        led.on();
      } else {
        logger.debug('alarm inactive! turning LED off');
        led.off();
      }
    });

    // add firebase reference value listener
    alarmsRef.on('value', (data) => {
      logger.debug('ref updated!');
      lillianWakeLight.addAlarms(data.val().lillian);
      lillianWakeLight.restart();
    });
  })
  .catch((error) => {
    logger.error(error.code, error.message);
  });
});
<commit_msg>debugging<commit_after>import firebase from 'firebase';
/* eslint-disable import/no-unresolved */
import five from 'johnny-five';
import chipio from 'chip-io';
/* eslint-enable */
import { logger } from './config';
import * as keys from './keys';
import WakeLight from './wakelight';

logger.debug('initializing firebase app');
firebase.initializeApp(keys.config);

const alarmsRef = firebase.database().ref('/alarms');

// init wakelight
const lillianWakeLight = new WakeLight();
const board = new five.Board({
  io: new chipio() // eslint-disable-line
});
board.on('ready', () => {
  // connect to firebase with email/password auth
  firebase.auth()
  .signInWithEmailAndPassword(keys.email, keys.password)
  .then((user) => {
    logger.debug(`${user.email} signed in`);

    // change handler for the alarm status
    const led = new five.Led('XIO-P0');
    led.blink(500);
    setTimeout(() => {
      led.stop();
      led.off();
    }, 5000);
    lillianWakeLight.on('change', (alarmState, time, name) => {
      logger.debug(`${time} ${name} alarm active? ${alarmState}`);
      if (alarmState) {
        logger.debug('alarm active! turning LED on');
        led.on();
      } else {
        logger.debug('alarm inactive! turning LED off');
        led.off();
      }
    });

    // add firebase reference value listener
    alarmsRef.on('value', (data) => {
      logger.debug('ref updated!');
      lillianWakeLight.addAlarms(data.val().lillian);
      lillianWakeLight.restart();
    });
  })
  .catch((error) => {
    logger.error(error.code, error.message);
  });
});
<|endoftext|>


<commit_before>import { WebClient } from '@slack/client'
import { getTeam } from './db'
import { animeAttachment } from './anime'
import { mangaAttachment } from './manga'
import { userAttachment } from './user'
import { postAttachment } from './post'
import { commentAttachment } from './comment'
import { reviewAttachment } from './review'
import { feedbackAttachment, getFeedback } from './feedback'
import { pageAttacment } from './page'
import { groupAttachment } from './group'

const route = async (path, route, children) => {
  let match = route.exec(path)
  if (match) {
    let p = path.slice(match.index).replace(route, '')
    let m = match[0].replace(/^\/+|\/+$/g, '')
    await children(p, m)
  }
}

export default async (ctx, next, kitsu) => {
  let { type, challenge } = ctx.request.body
  if (type === 'url_verification') {
    ctx.body = challenge
    return
  }
  let { team_id, event } = ctx.request.body
  let { channel, message_ts, links } = event
  console.log('event: ' + 'link_shared: ' + links.map(link => link.url).join())

  let { token } = await getTeam(team_id)
  let slack = new WebClient(token)

  await Promise.all(links.map(async (link) => {
    let { url } = link
    let unfurl

    const mediaRoute = async (path, match) => {
      let mediaKind = match
      await route(path, /\/[a-z0-9_-]+/, async (path, match) => {
        if (mediaKind === 'anime') {
          let anime = await kitsu.findAnime(match)
          unfurl = animeAttachment(anime)
        } else if (mediaKind === 'manga') {
          let manga = await kitsu.findManga(match)
          unfurl = mangaAttachment(manga)
        }
      })
      if (!unfurl) {
        unfurl = pageAttacment(match)
      }
    }

    await route(url, /\/anime/, mediaRoute)
    await route(url, /\/manga/, mediaRoute)

    await route(url, /\/users/, async (path, match) => {
      await route(path, /\/[a-zA-Z0-9_]+/, async (path, match) => {
        await route(path, /\/library/, async (path, match) => {
          unfurl = { text: 'users/library' }
        })
        if (!unfurl) {
          let user = await kitsu.findUser(match)
          unfurl = userAttachment(user)
        }
      })
    })

    await route(url, /\/posts/, async (path, match) => {
      await route(path, /\/\d+/, async (path, match) => {
        let post = await kitsu.getPost(match)
        unfurl = postAttachment(post)
      })
    })

    await route(url, /\/comments/, async (path, match) => {
      await route(path, /\/\d+/, async (path, match) => {
        let comment = await kitsu.getComment(match)
        unfurl = commentAttachment(comment)
      })
    })

    await route(url, /\/groups/, async (path, match) => {
      await route(path, /\/[a-zA-Z0-9_-]+/, async (path, match) => {
        let group = await kitsu.findGroup(match)
        unfurl = groupAttachment(group)
      })
      if (!unfurl) {
        unfurl = pageAttacment(match)
      }
    })

    await route(url, /\/reviews/, async (path, match) => {
      await route(path, /\/\d+/, async (path, match) => {
        let review = await kitsu.getReview(match)
        unfurl = reviewAttachment(review)
      })
    })

    const boardRoute = async (path, match) => {
      let feedbackKind = match
      await route(path, /\/p/, async (path, match) => {
        await route(path, /\/[a-zA-Z0-9_-]+/, async (path, match) => {
          let feedback = await getFeedback(match, feedbackKind)
          unfurl = feedbackAttachment(feedback)
        })
      })
      if (!unfurl) {
        unfurl = pageAttacment(match)
      }
    }

    const feedbackRoute = async (path, match) => {
      await route(path, /\/bugs/, boardRoute)
      await route(path, /\/feature-requests/, boardRoute)
      if (!unfurl) {
        unfurl = pageAttacment(match)
      }
    }

    await route(url, /\/feedback/, feedbackRoute)

    await feedbackRoute(url)

    await route(url, /\/trending/, async (path, match) => {
      unfurl = pageAttacment(match)
    })

    await route(url, /\/privacy/, async (path, match) => {
      unfurl = pageAttacment(match)
    })

    await route(url, /\/terms/, async (path, match) => {
      unfurl = pageAttacment(match)
    })

    await route(url, /\/about/, async (path, match) => {
      unfurl = pageAttacment(match)
    })

    if (!unfurl) {
      unfurl = pageAttacment('')
    }

    await slack.chat.unfurl(message_ts, channel, {
      [url]: unfurl
    }).catch((err) => { throw new Error(err) })
  }))
}
<commit_msg>Temp disable library unfurl<commit_after>import { WebClient } from '@slack/client'
import { getTeam } from './db'
import { animeAttachment } from './anime'
import { mangaAttachment } from './manga'
import { userAttachment } from './user'
import { postAttachment } from './post'
import { commentAttachment } from './comment'
import { reviewAttachment } from './review'
import { feedbackAttachment, getFeedback } from './feedback'
import { pageAttacment } from './page'
import { groupAttachment } from './group'

const route = async (path, route, children) => {
  let match = route.exec(path)
  if (match) {
    let p = path.slice(match.index).replace(route, '')
    let m = match[0].replace(/^\/+|\/+$/g, '')
    await children(p, m)
  }
}

export default async (ctx, next, kitsu) => {
  let { type, challenge } = ctx.request.body
  if (type === 'url_verification') {
    ctx.body = challenge
    return
  }
  let { team_id, event } = ctx.request.body
  let { channel, message_ts, links } = event
  console.log('event: ' + 'link_shared: ' + links.map(link => link.url).join())

  let { token } = await getTeam(team_id)
  let slack = new WebClient(token)

  await Promise.all(links.map(async (link) => {
    let { url } = link
    let unfurl

    const mediaRoute = async (path, match) => {
      let mediaKind = match
      await route(path, /\/[a-z0-9_-]+/, async (path, match) => {
        if (mediaKind === 'anime') {
          let anime = await kitsu.findAnime(match)
          unfurl = animeAttachment(anime)
        } else if (mediaKind === 'manga') {
          let manga = await kitsu.findManga(match)
          unfurl = mangaAttachment(manga)
        }
      })
      if (!unfurl) {
        unfurl = pageAttacment(match)
      }
    }

    await route(url, /\/anime/, mediaRoute)
    await route(url, /\/manga/, mediaRoute)

    await route(url, /\/users/, async (path, match) => {
      await route(path, /\/[a-zA-Z0-9_]+/, async (path, match) => {
        // await route(path, /\/library/, async (path, match) => {
        //   unfurl = { text: 'users/library' }
        // })
        if (!unfurl) {
          let user = await kitsu.findUser(match)
          unfurl = userAttachment(user)
        }
      })
    })

    await route(url, /\/posts/, async (path, match) => {
      await route(path, /\/\d+/, async (path, match) => {
        let post = await kitsu.getPost(match)
        unfurl = postAttachment(post)
      })
    })

    await route(url, /\/comments/, async (path, match) => {
      await route(path, /\/\d+/, async (path, match) => {
        let comment = await kitsu.getComment(match)
        unfurl = commentAttachment(comment)
      })
    })

    await route(url, /\/groups/, async (path, match) => {
      await route(path, /\/[a-zA-Z0-9_-]+/, async (path, match) => {
        let group = await kitsu.findGroup(match)
        unfurl = groupAttachment(group)
      })
      if (!unfurl) {
        unfurl = pageAttacment(match)
      }
    })

    await route(url, /\/reviews/, async (path, match) => {
      await route(path, /\/\d+/, async (path, match) => {
        let review = await kitsu.getReview(match)
        unfurl = reviewAttachment(review)
      })
    })

    const boardRoute = async (path, match) => {
      let feedbackKind = match
      await route(path, /\/p/, async (path, match) => {
        await route(path, /\/[a-zA-Z0-9_-]+/, async (path, match) => {
          let feedback = await getFeedback(match, feedbackKind)
          unfurl = feedbackAttachment(feedback)
        })
      })
      if (!unfurl) {
        unfurl = pageAttacment(match)
      }
    }

    const feedbackRoute = async (path, match) => {
      await route(path, /\/bugs/, boardRoute)
      await route(path, /\/feature-requests/, boardRoute)
      if (!unfurl) {
        unfurl = pageAttacment(match)
      }
    }

    await route(url, /\/feedback/, feedbackRoute)

    await feedbackRoute(url)

    await route(url, /\/trending/, async (path, match) => {
      unfurl = pageAttacment(match)
    })

    await route(url, /\/privacy/, async (path, match) => {
      unfurl = pageAttacment(match)
    })

    await route(url, /\/terms/, async (path, match) => {
      unfurl = pageAttacment(match)
    })

    await route(url, /\/about/, async (path, match) => {
      unfurl = pageAttacment(match)
    })

    if (!unfurl) {
      unfurl = pageAttacment('')
    }

    await slack.chat.unfurl(message_ts, channel, {
      [url]: unfurl
    }).catch((err) => { throw new Error(err) })
  }))
}
<|endoftext|>


<commit_before>if (typeof Cryptodog === 'undefined') {
    Cryptodog = function () { };
}

Cryptodog.UI = {
    // Set version number in UI.
    setVersion: function () {
        $('#version').text(Cryptodog.version);
    },

    // Handles login failures.
    loginFail: function (message) {
        $('#loginInfo').text(message);
        $('#bubble')
            .animate({ left: '+=5px' }, 130)
            .animate({ left: '-=10px' }, 130)
            .animate({ left: '+=5px' }, 130);
    },

    logout: function () {
        document.title = 'Cryptodog';

        $('#loginInfo').text(Cryptodog.locale['loginMessage']['thankYouUsing']);
        $('#conversationInfo,#optionButtons').fadeOut();
        $('#header').animate({ 'background-color': 'transparent' });
        $('.logo').animate({ margin: '-5px 5px 0 5px' });
        buddyList.cleanUp();

        $('#userInput').fadeOut(function () {
            $('#logoText').fadeIn();
            $('#footer').animate({ height: 14 });

            $('#conversationWrapper').fadeOut(function () {
                $('#info,#loginOptions,#version,#loginInfo').fadeIn();

                $('#login').fadeIn(200, function () {
                    $('#login').css({ opacity: 1 });
                    $('#conversationName').select();
                    $('#conversationName,#nickname').removeAttr('readonly');
                    $('#loginSubmit').removeAttr('readonly');
                });

                $('#dialogBoxClose').click();
                $('#conversationWindow').html('');
            });
        });
    },

    /*
	-------------------
	WINDOW EVENT BINDINGS
	-------------------
    */
    windowEventBindings: function () {
        $(window).ready(function () {
            // Load custom servers.
            storage.getItem('customServers', function (servers) {
                if (servers) {
                    $('#customServerSelector').empty();

                    $.each(servers, function (name) {
                        $('#customServerSelector').append(
                            Mustache.render(template['customServer'], {
                                name: name,
                                domain: servers[name]['domain'],
                                xmpp: servers[name]['xmpp'],
                                relay: servers[name]['relay']
                            })
                        );
                    });
                }
            });

            // Load nickname settings.
            storage.getItem('nickname', function (value) {
                if (value) {
                    $('#nickname').animate({ color: 'transparent' }, function () {
                        $(this).val(value);
                        $(this).animate({ color: '#FFF' });
                    });
                }
            });
        });

        // Prevent accidental window close.
        window.addEventListener('beforeunload', (event) => {
            if (Object.keys(Cryptodog.buddies).length) {
                event.preventDefault();
                event.returnValue = '';
            }
        });

        // Log out on browser close.
        window.onunload = function () {
            net.disconnect();
        };

        // Determine whether we are showing a top margin
        // Depending on window size
        $(window).resize(function () {
            if ($(window).height() < 650) {
                $('#bubble').css('margin-top', '0');
            } else {
                $('#bubble').css('margin-top', '2%');
            }
        });
        $(window).resize();
    },

    show: function () {
        // Show main window.
        $('#bubble').show();
    }
};
<commit_msg>Delete obsolete custom server loading code<commit_after>if (typeof Cryptodog === 'undefined') {
    Cryptodog = function () { };
}

Cryptodog.UI = {
    // Set version number in UI.
    setVersion: function () {
        $('#version').text(Cryptodog.version);
    },

    // Handles login failures.
    loginFail: function (message) {
        $('#loginInfo').text(message);
        $('#bubble')
            .animate({ left: '+=5px' }, 130)
            .animate({ left: '-=10px' }, 130)
            .animate({ left: '+=5px' }, 130);
    },

    logout: function () {
        document.title = 'Cryptodog';

        $('#loginInfo').text(Cryptodog.locale['loginMessage']['thankYouUsing']);
        $('#conversationInfo,#optionButtons').fadeOut();
        $('#header').animate({ 'background-color': 'transparent' });
        $('.logo').animate({ margin: '-5px 5px 0 5px' });
        buddyList.cleanUp();

        $('#userInput').fadeOut(function () {
            $('#logoText').fadeIn();
            $('#footer').animate({ height: 14 });

            $('#conversationWrapper').fadeOut(function () {
                $('#info,#loginOptions,#version,#loginInfo').fadeIn();

                $('#login').fadeIn(200, function () {
                    $('#login').css({ opacity: 1 });
                    $('#conversationName').select();
                    $('#conversationName,#nickname').removeAttr('readonly');
                    $('#loginSubmit').removeAttr('readonly');
                });

                $('#dialogBoxClose').click();
                $('#conversationWindow').html('');
            });
        });
    },

    /*
	-------------------
	WINDOW EVENT BINDINGS
	-------------------
    */
    windowEventBindings: function () {
        $(window).ready(function () {
            // Load nickname settings.
            storage.getItem('nickname', function (value) {
                if (value) {
                    $('#nickname').animate({ color: 'transparent' }, function () {
                        $(this).val(value);
                        $(this).animate({ color: '#FFF' });
                    });
                }
            });
        });

        // Prevent accidental window close.
        window.addEventListener('beforeunload', (event) => {
            if (Object.keys(Cryptodog.buddies).length) {
                event.preventDefault();
                event.returnValue = '';
            }
        });

        // Log out on browser close.
        window.onunload = function () {
            net.disconnect();
        };

        // Determine whether we are showing a top margin
        // Depending on window size
        $(window).resize(function () {
            if ($(window).height() < 650) {
                $('#bubble').css('margin-top', '0');
            } else {
                $('#bubble').css('margin-top', '2%');
            }
        });
        $(window).resize();
    },

    show: function () {
        // Show main window.
        $('#bubble').show();
    }
};
<|endoftext|>


<commit_before>var express = require('express');
var fs = require('fs');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var helmet = require('helmet');

// Config variables.
var VROOM_PATH = '';
var MAX_LOCATION_NUMBER = 50;
var ROUTE_GEOMETRY = false;
var USE_OSRM_V5 = true;
var USE_LIBOSRM = false;
var OSRM_ADDRESS = "0.0.0.0";
var OSRM_PORT = "5000";
var ALLOW_OPTIONS_OVERRIDE = true; // -g only so far.
var LOG_DIRNAME = __dirname + '/..';

// App and loaded modules.
var app = express();

// Enable cross-origin ressource sharing.
app.use(function(req, res, next){
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers",
             "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.use(bodyParser.json());

var accessLogStream = fs.createWriteStream(LOG_DIRNAME + '/access.log',
                                           {flags: 'a'});
app.use(morgan('combined', {stream: accessLogStream}));

app.use(helmet());

// Simple date generator for console output.
var now = function(){
  var date = new Date();
  return date.toUTCString();
}

// Callback for size and some input validity checks.
var sizeCheckCallback = function (req, res, next){
  res.setHeader('Content-Type', 'application/json');

  var correctInput = ('jobs' in req.body)
      && ('vehicles' in req.body)
      && (req.body['vehicles'].length >= 1);

  if(!correctInput){
    res.send({code: 1, error: 'Invalid query.'});
    return;
  }

  var nbLocs = req.body['jobs'].length;
  if('start' in req.body['vehicles'][0]){
    nbLocs += 1;
  }
  if('end' in req.body['vehicles'][0]){
    nbLocs += 1;
  }
  if(nbLocs > MAX_LOCATION_NUMBER){
    console.log(now() + '\n' + 'Too many locs in query (' + nbLocs + ')');
    res.send({code: 1, error: 'Too many locations.'});
    return;
  }
  next();
}

// Cli wrapper and associated callback.
var spawn = require('child_process').spawn;

var vroomCommand = VROOM_PATH + 'vroom';
var options = [];
if(USE_LIBOSRM){
  options.push('-l');
}
else{
  options.push('-a', OSRM_ADDRESS);
  options.push('-p', OSRM_PORT);
}
if(ROUTE_GEOMETRY){
  options.push('-g');
}
if(USE_OSRM_V5){
  // As of v5.1.0, profile name doesn't matter, so car will do until
  // it should be made into a variable.
  options.push('-m', 'car');
}

var execCallback = function (req, res){
  var reqOptions = options.slice();
  if(!ROUTE_GEOMETRY && ALLOW_OPTIONS_OVERRIDE
     && 'options' in req.body && 'g' in req.body['options']
     && req.body['options']['g']){
    reqOptions.push('-g');
  }

  reqOptions.push(JSON.stringify(req.body));
  var vroom = spawn(vroomCommand, reqOptions);

  vroom.stdout.pipe(res);

  vroom.stderr.on('data', function (data){
    console.log(now() + '\n' + data.toString());
  });
}

app.post('/', [sizeCheckCallback, execCallback]);

app.listen(3000, function (){
  console.log('vroom-express listening on port 3000!');
});
<commit_msg>Make the max number of locations a parameter of the size check callback.<commit_after>var express = require('express');
var fs = require('fs');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var helmet = require('helmet');

// Config variables.
var VROOM_PATH = '';
var MAX_LOCATION_NUMBER = 50;
var ROUTE_GEOMETRY = false;
var USE_OSRM_V5 = true;
var USE_LIBOSRM = false;
var OSRM_ADDRESS = "0.0.0.0";
var OSRM_PORT = "5000";
var ALLOW_OPTIONS_OVERRIDE = true; // -g only so far.
var LOG_DIRNAME = __dirname + '/..';

// App and loaded modules.
var app = express();

// Enable cross-origin ressource sharing.
app.use(function(req, res, next){
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers",
             "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.use(bodyParser.json());

var accessLogStream = fs.createWriteStream(LOG_DIRNAME + '/access.log',
                                           {flags: 'a'});
app.use(morgan('combined', {stream: accessLogStream}));

app.use(helmet());

// Simple date generator for console output.
var now = function(){
  var date = new Date();
  return date.toUTCString();
}

// Callback for size and some input validity checks.
var sizeCheckCallback = function(maxLocationNumber){
  return function (req, res, next){
    res.setHeader('Content-Type', 'application/json');

    var correctInput = ('jobs' in req.body)
        && ('vehicles' in req.body)
        && (req.body['vehicles'].length >= 1);

    if(!correctInput){
      res.send({code: 1, error: 'Invalid query.'});
      return;
    }

    var nbLocs = req.body['jobs'].length;
    if('start' in req.body['vehicles'][0]){
      nbLocs += 1;
    }
    if('end' in req.body['vehicles'][0]){
      nbLocs += 1;
    }
    if(nbLocs > maxLocationNumber){
      console.log(now() + '\n' + 'Too many locs in query (' + nbLocs + ')');
      res.send({code: 1, error: 'Too many locations.'});
      return;
    }
    next();
  }
}

// Cli wrapper and associated callback.
var spawn = require('child_process').spawn;

var vroomCommand = VROOM_PATH + 'vroom';
var options = [];
if(USE_LIBOSRM){
  options.push('-l');
}
else{
  options.push('-a', OSRM_ADDRESS);
  options.push('-p', OSRM_PORT);
}
if(ROUTE_GEOMETRY){
  options.push('-g');
}
if(USE_OSRM_V5){
  // As of v5.1.0, profile name doesn't matter, so car will do until
  // it should be made into a variable.
  options.push('-m', 'car');
}

var execCallback = function (req, res){
  var reqOptions = options.slice();
  if(!ROUTE_GEOMETRY && ALLOW_OPTIONS_OVERRIDE
     && 'options' in req.body && 'g' in req.body['options']
     && req.body['options']['g']){
    reqOptions.push('-g');
  }

  reqOptions.push(JSON.stringify(req.body));
  var vroom = spawn(vroomCommand, reqOptions);

  vroom.stdout.pipe(res);

  vroom.stderr.on('data', function (data){
    console.log(now() + '\n' + data.toString());
  });
}

app.post('/', [sizeCheckCallback(MAX_LOCATION_NUMBER), execCallback]);

app.listen(3000, function (){
  console.log('vroom-express listening on port 3000!');
});
<|endoftext|>


<commit_before>// Copyright 2013-2019, University of Colorado Boulder

/**
 * Like Underscore's _.extend, but with hardcoded support for ES5 getters/setters.
 *
 * See https://github.com/documentcloud/underscore/pull/986.
 *
 * @author Jonathan Olson <jonathan.olson@colorado.edu>
 */

define( require => {
  'use strict';

  const phetCore = require( 'PHET_CORE/phetCore' );

  function extend( obj ) {
    _.each( Array.prototype.slice.call( arguments, 1 ), function( source ) {
      if ( source ) {
        for ( const prop in source ) {
          Object.defineProperty( obj, prop, Object.getOwnPropertyDescriptor( source, prop ) );
        }
      }
    } );
    return obj;
  }

  phetCore.register( 'extend', extend );

  return extend;
} );<commit_msg>update doc, https://github.com/phetsims/phet-core/issues/75<commit_after>// Copyright 2013-2019, University of Colorado Boulder

/**
 * Like Underscore's _.extend and PHET_CORE/merge, but with hardcoded support for ES5 getters/setters. In general this
 * type shouldn't be used for phet's options pattern, and instead was designed to support extension for defining
 * mixins and object prototypes.
 *
 * See https://github.com/documentcloud/underscore/pull/986.
 *
 * @author Jonathan Olson <jonathan.olson@colorado.edu>
 */

define( require => {
  'use strict';

  const phetCore = require( 'PHET_CORE/phetCore' );

  function extend( obj ) {
    _.each( Array.prototype.slice.call( arguments, 1 ), function( source ) {
      if ( source ) {
        for ( const prop in source ) {
          Object.defineProperty( obj, prop, Object.getOwnPropertyDescriptor( source, prop ) );
        }
      }
    } );
    return obj;
  }

  phetCore.register( 'extend', extend );

  return extend;
} );<|endoftext|>


<commit_before>import 'whatwg-fetch'

export default function (file, api) {
  const resource = file ? `static/${file}` : api
  return fetch(resource)
    .then(response => {
      const fileSplit = file.split('.')
      if (fileSplit[fileSplit.length - 1] === 'json') {
        return response.json()
      } else {
        return response.text()
      }
    }).then(res => {
      return res
    })
}
<commit_msg>handle non json requests<commit_after>import 'whatwg-fetch'

export default function (file, api) {
  const resource = file ? `static/${file}` : api
  return fetch(resource)
    .then(response => {
      if (file) {
        const fileSplit = file.split('.')
        if (fileSplit[fileSplit.length - 1] === 'json') {
          return response.json()
        } else {
          return response.text()
        }
      } else {
        return response.json()
      }
    }).then(res => {
      return res
    })
}
<|endoftext|>


<commit_before>(function ($) {
    $.fn.slides = function (options) {
        $.extend($.fn.slides.settings, $.fn.slides.defaults, options);

        return this.each(function () {
            $.fn.slides.init(this);
        });
    };

    $.fn.slides.settings = {},
    $.fn.slides.slides = [];
    $.fn.slides.current = 0;

    $.fn.slides.defaults = {
        duration: 0,
        bindings: {
            37: "prev", // left
            38: "prev", // up
            39: "next", // right
            40: "next", // down
            75: "prev", // k
            74: "next", // j
            32: "next", // space
        },
    };

    $.fn.slides.init = function (element) {
        $.fn.slides.root = root = $(element);
        $.fn.slides.header = header = root.find("> header");
        $.fn.slides.footer = footer = root.find("> footer");
        var slides = $.fn.slides.slides;

        /* Hide header, footer and (slides > 1). */
        root.addClass("slides").children("section").each(function () {
            slides.push($(this));
        });
        $.each(slides.slice(1), function () {
            $(this).hide();
        });
        $.fn.slides.gotohash();

        $(document).keydown(function (event) {
            var key = (event.keyCode ? event.keyCode : event.which);
            var fnname = $.fn.slides.settings.bindings[key],
                fn = $.fn.slides[fnname];
            if (fn) {
                fn();
                return false;
            };
        });

        if ("hashchange" in $(window)) {
            $(window).hashchange(function () {
                $.fn.slides.gotohash();
            });
        };
    };

    $.fn.slides.goto = function (index) {
        var slides = $.fn.slides.slides,
            current = $.fn.slides.current,
            settings = $.fn.slides.settings;
        if (index >= slides.length || index < 0 || (index > 1 && index == current))
            return;
        $.fn.slides.hide(slides[current]);
        $.fn.slides.show(slides[index]);
        $.fn.slides.current = index;
        location.hash = "#slide" + (index + 1);
    };

    $.fn.slides.next = function () {
        $.fn.slides.goto($.fn.slides.current + 1);
    }

    $.fn.slides.prev = function () {
        $.fn.slides.goto($.fn.slides.current - 1);
    }

    $.fn.slides.show = function (slide) {
        slide.show($.fn.slides.settings.duration);
    };

    $.fn.slides.hide = function (slide) {
        slide.hide($.fn.slides.settings.duration);
    };

    $.fn.slides.gotohash = function (hash) {
        var hash = hash;
        if (typeof hash == "undefined")
            hash = location.hash || "#slide1";
        var slide = hash.replace(/^#slide/, "");
        $.fn.slides.goto(parseInt(slide, 10) - 1);
    };
})(jQuery);
<commit_msg>Sort bindings.<commit_after>(function ($) {
    $.fn.slides = function (options) {
        $.extend($.fn.slides.settings, $.fn.slides.defaults, options);

        return this.each(function () {
            $.fn.slides.init(this);
        });
    };

    $.fn.slides.settings = {},
    $.fn.slides.slides = [];
    $.fn.slides.current = 0;

    $.fn.slides.defaults = {
        duration: 0,
        bindings: {
            37: "prev", // left
            38: "prev", // up
            75: "prev", // k
            39: "next", // right
            40: "next", // down
            74: "next", // j
            32: "next", // space
        },
    };

    $.fn.slides.init = function (element) {
        $.fn.slides.root = root = $(element);
        $.fn.slides.header = header = root.find("> header");
        $.fn.slides.footer = footer = root.find("> footer");
        var slides = $.fn.slides.slides;

        /* Hide header, footer and (slides > 1). */
        root.addClass("slides").children("section").each(function () {
            slides.push($(this));
        });
        $.each(slides.slice(1), function () {
            $(this).hide();
        });
        $.fn.slides.gotohash();

        $(document).keydown(function (event) {
            var key = (event.keyCode ? event.keyCode : event.which);
            var fnname = $.fn.slides.settings.bindings[key],
                fn = $.fn.slides[fnname];
            if (fn) {
                fn();
                return false;
            };
        });

        if ("hashchange" in $(window)) {
            $(window).hashchange(function () {
                $.fn.slides.gotohash();
            });
        };
    };

    $.fn.slides.goto = function (index) {
        var slides = $.fn.slides.slides,
            current = $.fn.slides.current,
            settings = $.fn.slides.settings;
        if (index >= slides.length || index < 0 || (index > 1 && index == current))
            return;
        $.fn.slides.hide(slides[current]);
        $.fn.slides.show(slides[index]);
        $.fn.slides.current = index;
        location.hash = "#slide" + (index + 1);
    };

    $.fn.slides.next = function () {
        $.fn.slides.goto($.fn.slides.current + 1);
    }

    $.fn.slides.prev = function () {
        $.fn.slides.goto($.fn.slides.current - 1);
    }

    $.fn.slides.show = function (slide) {
        slide.show($.fn.slides.settings.duration);
    };

    $.fn.slides.hide = function (slide) {
        slide.hide($.fn.slides.settings.duration);
    };

    $.fn.slides.gotohash = function (hash) {
        var hash = hash;
        if (typeof hash == "undefined")
            hash = location.hash || "#slide1";
        var slide = hash.replace(/^#slide/, "");
        $.fn.slides.goto(parseInt(slide, 10) - 1);
    };
})(jQuery);
<|endoftext|>


<commit_before>/**
 * Created by taha on 9/1/17.
 */
console.log("app running");
<commit_msg>Update Entry Point<commit_after>/**
 * Created by taha on 9/1/17.
 */
import 'babel-polyfill';
import React from 'react';
import { render } from 'react-dom';
import { Router, browserHistory } from 'react-router';
import routes from './routes';
import './styles/styles.css';
import '../node_modules/bootstrap/dist/css/bootstrap-theme.min.css';

render (
  <Router history={browserHistory} routes={routes} />,
  document.getElementById('app')
);
<|endoftext|>


<commit_before>// debug output
let __DEBUG__
function debug (...args) {
  if (__DEBUG__) {
    if (!console.group) {
      args.unshift('%credux-undo', 'font-style: italic')
    }
    console.log(...args)
  }
}
function debugStart (action, state) {
  if (__DEBUG__) {
    const args = ['action', action.type]
    if (console.group) {
      args.unshift('%credux-undo', 'font-style: italic')
      console.groupCollapsed(...args)
      console.log('received', {state, action})
    } else {
      debug(...args)
    }
  }
}
function debugEnd () {
  if (__DEBUG__) {
    return console.groupEnd && console.groupEnd()
  }
}
// /debug output

// action types
export const ActionTypes = {
  UNDO: '@@redux-undo/UNDO',
  REDO: '@@redux-undo/REDO',
  JUMP_TO_FUTURE: '@@redux-undo/JUMP_TO_FUTURE',
  JUMP_TO_PAST: '@@redux-undo/JUMP_TO_PAST'
}
// /action types

// action creators to change the state
export const ActionCreators = {
  undo () {
    return { type: ActionTypes.UNDO }
  },
  redo () {
    return { type: ActionTypes.REDO }
  },
  jumpToFuture (index) {
    return { type: ActionTypes.JUMP_TO_FUTURE, index }
  },
  jumpToPast (index) {
    return { type: ActionTypes.JUMP_TO_PAST, index }
  }
}
// /action creators

// length: get length of history
function length (history) {
  const { past, future } = history
  return past.length + 1 + future.length
}
// /length

// insert: insert `state` into history, which means adding the current state
//         into `past`, setting the new `state` as `present` and erasing
//         the `future`.
function insert (history, state, limit) {
  debug('insert', {state, history, free: limit - length(history)})

  const { past, present } = history
  const historyOverflow = limit && length(history) >= limit

  if (present === undefined) {
    // init history
    return {
      past: [],
      present: state,
      future: []
    }
  }

  return {
    past: [
      ...past.slice(historyOverflow ? 1 : 0),
      present
    ],
    present: state,
    future: []
  }
}
// /insert

// undo: go back to the previous point in history
function undo (history) {
  debug('undo', {history})

  const { past, present, future } = history

  if (past.length <= 0) return history

  return {
    past: past.slice(0, past.length - 1), // remove last element from past
    present: past[past.length - 1], // set element as new present
    future: [
      present, // old present state is in the future now
      ...future
    ]
  }
}
// /undo

// redo: go to the next point in history
function redo (history) {
  debug('redo', {history})

  const { past, present, future } = history

  if (future.length <= 0) return history

  return {
    future: future.slice(1, future.length), // remove element from future
    present: future[0], // set element as new present
    past: [
      ...past,
      present // old present state is in the past now
    ]
  }
}
// /redo

// jumpToFuture: jump to requested index in future history
function jumpToFuture (history, index) {
  if (index === 0) return redo(history)

  const { past, present, future } = history

  return {
    future: future.slice(index + 1),
    present: future[index],
    past: past.concat([present])
              .concat(future.slice(0, index))
  }
}
// /jumpToFuture

// jumpToPast: jump to requested index in past history
function jumpToPast (history, index) {
  if (index === history.past.length - 1) return undo(history)

  const { past, present, future } = history

  return {
    future: past.slice(index + 1)
                .concat([present])
                .concat(future),
    present: past[index],
    past: past.slice(0, index)
  }
}
// /jumpToPast

// updateState
function updateState (state, history) {
  return {...state, ...history};
}
// /updateState

// createHistory
function createHistory (state) {
  return {
    past: [],
    present: state,
    future: []
  }
}
// /createHistory

// parseActions
export function parseActions (rawActions, defaultValue = []) {
  if (Array.isArray(rawActions)) {
    return rawActions
  } else if (typeof rawActions === 'string') {
    return [rawActions]
  }
  return defaultValue
}
// /parseActions

// redux-undo higher order reducer
export default function undoable (reducer, rawConfig = {}) {
  __DEBUG__ = rawConfig.debug

  const config = {
    initialState: rawConfig.initialState,
    initTypes: parseActions(rawConfig.initTypes, ['@@redux/INIT', '@@INIT']),
    limit: rawConfig.limit,
    filter: rawConfig.filter || () => true,
    undoType: rawConfig.undoType || ActionTypes.UNDO,
    redoType: rawConfig.redoType || ActionTypes.REDO,
    jumpToPastType: rawConfig.jumpToPastType || ActionTypes.JUMP_TO_PAST,
    jumpToFutureType: rawConfig.jumpToFutureType || ActionTypes.JUMP_TO_FUTURE
  }
  config.history = rawConfig.initialHistory || createHistory(config.initialState)

  if (config.initTypes.length === 0) {
    console.warn('redux-undo: supply at least one action type in initTypes to ensure initial state')
  }

  return (state, action) => {
    debugStart(action, state)
    let res
    switch (action.type) {
      case config.undoType:
        res = undo(state)
        debug('after undo', res)
        debugEnd()
        return res ? updateState(state, res) : state

      case config.redoType:
        res = redo(state)
        debug('after redo', res)
        debugEnd()
        return res ? updateState(state, res) : state

      case config.jumpToPastType:
        res = jumpToPast(state, action.index)
        debug('after jumpToPast', res)
        debugEnd()
        return res ? updateState(state, res) : state

      case config.jumpToFutureType:
        res = jumpToFuture(state, action.index)
        debug('after jumpToFuture', res)
        debugEnd()
        return res ? updateState(state, res) : state

      default:
        res = reducer(state && state.present, action)

        if (config.initTypes.some((actionType) => actionType === action.type)) {
          debug('reset history due to init action')
          debugEnd()
          return {
            ...state,
            ...createHistory(res)
          }
        }

        if (config.filter && typeof config.filter === 'function') {
          if (!config.filter(action, res, state && state.present)) {
            debug('filter prevented action, not storing it')
            debugEnd()
            return {
              ...state,
              present: res
            }
          }
        }

        const history = (state && state.present !== undefined) ? state : config.history
        const updatedHistory = insert(history, res, config.limit)
        debug('after insert', {history: updatedHistory, free: config.limit - length(updatedHistory)})
        debugEnd()

        return {
          ...state,
          ...updatedHistory
        }
    }
  }
}
// /redux-undo

// distinctState helper
export function distinctState () {
  return (action, currentState, previousState) => currentState !== previousState
}
// /distinctState

// includeAction helper
export function includeAction (rawActions) {
  const actions = parseActions(rawActions)
  return (action) => actions.indexOf(action.type) >= 0
}
// /includeAction

// excludeAction helper
export function excludeAction (rawActions = []) {
  const actions = parseActions(rawActions)
  return (action) => actions.indexOf(action.type) < 0
}
// /excludeAction
<commit_msg>remove Extra semicolon<commit_after>// debug output
let __DEBUG__
function debug (...args) {
  if (__DEBUG__) {
    if (!console.group) {
      args.unshift('%credux-undo', 'font-style: italic')
    }
    console.log(...args)
  }
}
function debugStart (action, state) {
  if (__DEBUG__) {
    const args = ['action', action.type]
    if (console.group) {
      args.unshift('%credux-undo', 'font-style: italic')
      console.groupCollapsed(...args)
      console.log('received', {state, action})
    } else {
      debug(...args)
    }
  }
}
function debugEnd () {
  if (__DEBUG__) {
    return console.groupEnd && console.groupEnd()
  }
}
// /debug output

// action types
export const ActionTypes = {
  UNDO: '@@redux-undo/UNDO',
  REDO: '@@redux-undo/REDO',
  JUMP_TO_FUTURE: '@@redux-undo/JUMP_TO_FUTURE',
  JUMP_TO_PAST: '@@redux-undo/JUMP_TO_PAST'
}
// /action types

// action creators to change the state
export const ActionCreators = {
  undo () {
    return { type: ActionTypes.UNDO }
  },
  redo () {
    return { type: ActionTypes.REDO }
  },
  jumpToFuture (index) {
    return { type: ActionTypes.JUMP_TO_FUTURE, index }
  },
  jumpToPast (index) {
    return { type: ActionTypes.JUMP_TO_PAST, index }
  }
}
// /action creators

// length: get length of history
function length (history) {
  const { past, future } = history
  return past.length + 1 + future.length
}
// /length

// insert: insert `state` into history, which means adding the current state
//         into `past`, setting the new `state` as `present` and erasing
//         the `future`.
function insert (history, state, limit) {
  debug('insert', {state, history, free: limit - length(history)})

  const { past, present } = history
  const historyOverflow = limit && length(history) >= limit

  if (present === undefined) {
    // init history
    return {
      past: [],
      present: state,
      future: []
    }
  }

  return {
    past: [
      ...past.slice(historyOverflow ? 1 : 0),
      present
    ],
    present: state,
    future: []
  }
}
// /insert

// undo: go back to the previous point in history
function undo (history) {
  debug('undo', {history})

  const { past, present, future } = history

  if (past.length <= 0) return history

  return {
    past: past.slice(0, past.length - 1), // remove last element from past
    present: past[past.length - 1], // set element as new present
    future: [
      present, // old present state is in the future now
      ...future
    ]
  }
}
// /undo

// redo: go to the next point in history
function redo (history) {
  debug('redo', {history})

  const { past, present, future } = history

  if (future.length <= 0) return history

  return {
    future: future.slice(1, future.length), // remove element from future
    present: future[0], // set element as new present
    past: [
      ...past,
      present // old present state is in the past now
    ]
  }
}
// /redo

// jumpToFuture: jump to requested index in future history
function jumpToFuture (history, index) {
  if (index === 0) return redo(history)

  const { past, present, future } = history

  return {
    future: future.slice(index + 1),
    present: future[index],
    past: past.concat([present])
              .concat(future.slice(0, index))
  }
}
// /jumpToFuture

// jumpToPast: jump to requested index in past history
function jumpToPast (history, index) {
  if (index === history.past.length - 1) return undo(history)

  const { past, present, future } = history

  return {
    future: past.slice(index + 1)
                .concat([present])
                .concat(future),
    present: past[index],
    past: past.slice(0, index)
  }
}
// /jumpToPast

// updateState
function updateState (state, history) {
  return {...state, ...history}
}
// /updateState

// createHistory
function createHistory (state) {
  return {
    past: [],
    present: state,
    future: []
  }
}
// /createHistory

// parseActions
export function parseActions (rawActions, defaultValue = []) {
  if (Array.isArray(rawActions)) {
    return rawActions
  } else if (typeof rawActions === 'string') {
    return [rawActions]
  }
  return defaultValue
}
// /parseActions

// redux-undo higher order reducer
export default function undoable (reducer, rawConfig = {}) {
  __DEBUG__ = rawConfig.debug

  const config = {
    initialState: rawConfig.initialState,
    initTypes: parseActions(rawConfig.initTypes, ['@@redux/INIT', '@@INIT']),
    limit: rawConfig.limit,
    filter: rawConfig.filter || (() => true),
    undoType: rawConfig.undoType || ActionTypes.UNDO,
    redoType: rawConfig.redoType || ActionTypes.REDO,
    jumpToPastType: rawConfig.jumpToPastType || ActionTypes.JUMP_TO_PAST,
    jumpToFutureType: rawConfig.jumpToFutureType || ActionTypes.JUMP_TO_FUTURE
  }
  config.history = rawConfig.initialHistory || createHistory(config.initialState)

  if (config.initTypes.length === 0) {
    console.warn('redux-undo: supply at least one action type in initTypes to ensure initial state')
  }

  return (state, action) => {
    debugStart(action, state)
    let res
    switch (action.type) {
      case config.undoType:
        res = undo(state)
        debug('after undo', res)
        debugEnd()
        return res ? updateState(state, res) : state

      case config.redoType:
        res = redo(state)
        debug('after redo', res)
        debugEnd()
        return res ? updateState(state, res) : state

      case config.jumpToPastType:
        res = jumpToPast(state, action.index)
        debug('after jumpToPast', res)
        debugEnd()
        return res ? updateState(state, res) : state

      case config.jumpToFutureType:
        res = jumpToFuture(state, action.index)
        debug('after jumpToFuture', res)
        debugEnd()
        return res ? updateState(state, res) : state

      default:
        res = reducer(state && state.present, action)

        if (config.initTypes.some((actionType) => actionType === action.type)) {
          debug('reset history due to init action')
          debugEnd()
          return {
            ...state,
            ...createHistory(res)
          }
        }

        if (config.filter && typeof config.filter === 'function') {
          if (!config.filter(action, res, state && state.present)) {
            debug('filter prevented action, not storing it')
            debugEnd()
            return {
              ...state,
              present: res
            }
          }
        }

        const history = (state && state.present !== undefined) ? state : config.history
        const updatedHistory = insert(history, res, config.limit)
        debug('after insert', {history: updatedHistory, free: config.limit - length(updatedHistory)})
        debugEnd()

        return {
          ...state,
          ...updatedHistory
        }
    }
  }
}
// /redux-undo

// distinctState helper
export function distinctState () {
  return (action, currentState, previousState) => currentState !== previousState
}
// /distinctState

// includeAction helper
export function includeAction (rawActions) {
  const actions = parseActions(rawActions)
  return (action) => actions.indexOf(action.type) >= 0
}
// /includeAction

// excludeAction helper
export function excludeAction (rawActions = []) {
  const actions = parseActions(rawActions)
  return (action) => actions.indexOf(action.type) < 0
}
// /excludeAction
<|endoftext|>


<commit_before>
var access_token = "";

function saveToken(accessToken) {
  access_token = accessToken;
}

// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {

  console.log('statusChangeCallback');
  console.log(response);

  // Logged into your app and Facebook.
  if (response.status === 'connected') {
    saveToken(response.authResponse.accessToken);
    getProfileInfo();
    updateView();
  } else if (response.status === 'not_authorized') {
    document.getElementById('status').innerHTML = 'Please log into this app.';
  } else {
    FB.login(function(response) {
      if (response.authResponse ) {
        saveToken();
        getProfileInfo();
        updateView();
      }
    });
  }
}

// This function is called when someone finishes with the Login
// Button.  See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  });
}

function getProfileInfo() {
  FB.api('/me?field=name,id', function(response) {
    alert('Successful login for: ' + response.name);
  });
}

function send_request() {

  var myObject = new Object();
  myObject.token = access_token;

  var food_name = new Array("Arrosticini", "Piattone Gigante", "Paninazzo", "Carbonara", "Insalatina");
  var images = new Array(
    "http://www.hermestocchetti.com/sites/default/files/styles/fullsize/public/gallery/4-food-meat/p195bn87uf1gds1qrv1sc3o5c1nv34.jpg?itok=c1-Z_tur",
    "http://www.hermestocchetti.com/sites/default/files/styles/fullsize/public/gallery/4-food-meat/p195bn87ufbhf1fs0ou112464m7.jpg?itok=EKAbMm1x",
    "http://asiastreetfood.com/wp-content/uploads/2014/06/BanhMi.jpg",
    "https://c1.staticflickr.com/5/4001/4283223635_da5e247b5e_b.jpg",
    "https://c4.staticflickr.com/4/3709/9499573644_05a0e270fd_k.jpg"
    );

  var start = new Array(
    "Sei dimagrito rispetto a ieri, ",
    "Sei ingrassato rispetto a ieri, ",
    "Good work, ");
  var middle = new Array(
    "e perche' fuori nevica ",
    "e perche' PEJO e' un bel paesino ",
    "e perche' sono stanco di scrivere ");
  var end = new Array(
    "you deserve:",
    "you are allowed to eat:",
    "today you have to eat:");

  var start_index = Math.floor((Math.random() * 3));
  var middle_index = Math.floor((Math.random() * 3));
  var end_index = Math.floor((Math.random() * 3));
  var food_index = Math.floor((Math.random() * 5));

  var congrats = start[start_index] + middle[middle_index] + end[end_index];

  // alert(access_token);

  $.ajax({
    crossDomain: true,
    type:'POST',
    dataType: 'jsonp',
    url: "http://127.0.0.1:8000/project-director/facebook",
    data: JSON.stringify(myObject),
    success: function(data)
    {
      var obj = jQuery.parseJSON(data);
      alert(obj.id);
      alert(obj.fist_name);
      alert(obj.image_url);
      // $('body').append(data);
      // if(err == "Errore nell'invio dell'e-mail." || err == "E-mail non valida.") {
      //   $('#form-send-message').addClass('form-send-errors')
      // }
      // else {
      //   $('#form-send-message').addClass('form-send-success');
      // }
    }//,
    // error: function(error) {
    //   alert(error);
    // }
  });

  $('#form').hide();
  $('#flickr_bg').css('background-image', 'url("'+ images[food_index] +'")');
  $('#quote').text(congrats);
  $('.motivational_quote').show();
  $('#title').text(food_name[food_index]);
  $('.subtitle').hide();
  $('.center').addClass('results');
  $('.scroll_down').show();
  $('#second').show();
}

function succ(data) {
  var obj = jQuery.parseJSON(data);
  alert(obj.id);
  alert(obj.fist_name);
  alert(obj.image_url);
}

function updateView() {
  $('.fb-login').hide();
  $('#fb-image').show();
  $('#title').text("Hi Roberto. Insert your health profile!");
  $('.subtitle').text("Height is in cm while Weight is in kg.");
  $('#form').show();
}
<commit_msg>commit for heroku<commit_after>
var access_token = "";

function saveToken(accessToken) {
  access_token = accessToken;
}

// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {

  console.log('statusChangeCallback');
  console.log(response);

  // Logged into your app and Facebook.
  if (response.status === 'connected') {
    saveToken(response.authResponse.accessToken);
    getProfileInfo();
    updateView();
  } else if (response.status === 'not_authorized') {
    document.getElementById('status').innerHTML = 'Please log into this app.';
  } else {
    FB.login(function(response) {
      if (response.authResponse ) {
        saveToken();
        getProfileInfo();
        updateView();
      }
    });
  }
}

// This function is called when someone finishes with the Login
// Button.  See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  });
}

function getProfileInfo() {
  FB.api('/me?field=name,id', function(response) {
    alert('Successful login for: ' + response.name);
  });
}

function send_request() {

  var myObject = new Object();
  myObject.token = access_token;

  var food_name = new Array("Arrosticini", "Piattone Gigante", "Paninazzo", "Carbonara", "Insalatina");
  var images = new Array(
    "http://www.hermestocchetti.com/sites/default/files/styles/fullsize/public/gallery/4-food-meat/p195bn87uf1gds1qrv1sc3o5c1nv34.jpg?itok=c1-Z_tur",
    "http://www.hermestocchetti.com/sites/default/files/styles/fullsize/public/gallery/4-food-meat/p195bn87ufbhf1fs0ou112464m7.jpg?itok=EKAbMm1x",
    "http://asiastreetfood.com/wp-content/uploads/2014/06/BanhMi.jpg",
    "https://c1.staticflickr.com/5/4001/4283223635_da5e247b5e_b.jpg",
    "https://c4.staticflickr.com/4/3709/9499573644_05a0e270fd_k.jpg"
    );

  var start = new Array(
    "Sei dimagrito rispetto a ieri, ",
    "Sei ingrassato rispetto a ieri, ",
    "Good work, ");
  var middle = new Array(
    "e perche' fuori nevica ",
    "e perche' PEJO e' un bel paesino ",
    "e perche' sono stanco di scrivere ");
  var end = new Array(
    "you deserve:",
    "you are allowed to eat:",
    "today you have to eat:");

  var start_index = Math.floor((Math.random() * 3));
  var middle_index = Math.floor((Math.random() * 3));
  var end_index = Math.floor((Math.random() * 3));
  var food_index = Math.floor((Math.random() * 5));

  var congrats = start[start_index] + middle[middle_index] + end[end_index];

  // alert(access_token);

  $.ajax({
    crossDomain: true,
    type:'POST',
    dataType: 'json',
    url: "http://127.0.0.1:8000/project-director/facebook",
    data: JSON.stringify(myObject),
    success: function(data)
    {
      var obj = jQuery.parseJSON(data);
      alert(obj.id);
      alert(obj.fist_name);
      alert(obj.image_url);
      // $('body').append(data);
      // if(err == "Errore nell'invio dell'e-mail." || err == "E-mail non valida.") {
      //   $('#form-send-message').addClass('form-send-errors')
      // }
      // else {
      //   $('#form-send-message').addClass('form-send-success');
      // }
    }//,
    // error: function(error) {
    //   alert(error);
    // }
  });

  $('#form').hide();
  $('#flickr_bg').css('background-image', 'url("'+ images[food_index] +'")');
  $('#quote').text(congrats);
  $('.motivational_quote').show();
  $('#title').text(food_name[food_index]);
  $('.subtitle').hide();
  $('.center').addClass('results');
  $('.scroll_down').show();
  $('#second').show();
}

function succ(data) {
  var obj = jQuery.parseJSON(data);
  alert(obj.id);
  alert(obj.fist_name);
  alert(obj.image_url);
}

function updateView() {
  $('.fb-login').hide();
  $('#fb-image').show();
  $('#title').text("Hi Roberto. Insert your health profile!");
  $('.subtitle').text("Height is in cm while Weight is in kg.");
  $('#form').show();
}
<|endoftext|>