// file:///Users/francoisbeaufils/Downloads/geocoder-demo-master/index.html
var app = angular.module('application', ['ngMaterial', 'adaptive.detection', 'ui.bootstrap.typeahead']);
app.directive('skrollr', function() {
var directiveDefinitionObject = {
link: function() {
skrollr.init();
}
};
return directiveDefinitionObject;
});
navigator.sayswho = (function(){
var ua= navigator.userAgent, tem,
M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if(/trident/i.test(M[1])){
tem= /\brv[ :]+(\d+)/g.exec(ua) || [];
return 'IE '+(tem[1] || '');
}
if(M[1]=== 'Chrome'){
tem= ua.match(/\b(OPR|Edge)\/(\d+)/);
if(tem!== null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
}
M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
if((tem= ua.match(/version\/(\d+)/i))!== null) M.splice(1, 1, tem[1]);
return M.join(' ');
})();
if(navigator.sayswho === 'IE 6' || navigator.sayswho === 'IE 7' || navigator.sayswho === 'IE 8') {
$(document).ready(function() {
$('body').html('
Votre navigateur ' + navigator.sayswho + " n'est pas supporté, vous devez avoir au minimum la version 9.
");
});
}
app.controller('mainController', function($scope, $detection, $http, $mdSidenav, $timeout, $sce, $mdToast) {
$scope.title = "Manche Numerique";
$scope.$sce = $sce;
var getGeoCodeInProgress = false,
nbJoursFTTH = 244,
siteName = 'Eligibilité Manche Numérique',
siteUrl = 'http://eligibilite.manchenumerique.fr',
siteEmail = 'ftth@manchenumerique.fr',
siteAddresse = '235, rue Joseph Cugnot Zone Delta, 50000 SAINT LÔ',
siteTel = '02.33.77.83.60',
layer = {},
currentMarker, searchExtent;
var catTypeVoie = [
{
"name": "Allée",
"id" : "allee"
},
{
"name": "Avenue",
"id" : "avenue"
},
{
"name": "Boulevard",
"id" : "boulevard"
},
{
"name": "Carrefour",
"id" : "carrefour"
},
{
"name": "Chemin",
"id" : "chemin"
},
{
"name": "Cité",
"id" : "cite"
},
{
"name": "Hammeau",
"id" : "hammeau"
},
{
"name": "Impasse",
"id" : "impasse"
},
{
"name": "Lieu-dit",
"id" : "lieu_dit"
},
{
"name": "Lotissement",
"id" : "lotissement"
},
{
"name": "Place",
"id" : "place"
},
{
"name": "Résidence",
"id" : "residence"
},
{
"name": "Route",
"id" : "route"
},
{
"name": "Rue",
"id" : "rue"
},
{
"name": "Villa",
"id" : "villa"
},
{
"name": "Village",
"id" : "village"
}
];
var catVousEtes = [
{
"name": "Locataire de ce logement",
"id" : "locataire"
},
{
"name": "Occupant à titre gratuit de ce logement",
"id" : "occupant_gratuit"
},
{
"name": "Propriétaire de ce logement",
"id" : "proprietaire"
}
];
var catCeLogementEst = [
{
"name": "Votre résidence principale",
"id" : "residence_principale"
},
{
"name": "Votre résidence secondaire",
"id" : "residence_secondaire"
}
];
var catAccord = [
{
"name": "J’ai l’intention de souscrire à une offre Très Haut Débit après le pré-raccordement",
"id" : "avec_souscription"
},
{
"name": "Je n’ai pas l’intention de souscrire à une offre Très Haut Débit après le pré-raccordement",
"id" : "sans_souscription"
}
];
$scope.formulaires = {
"eligibilite": {
"sections": [
{
"name": "Générale",
"visible": false,
"lines": [
{
"ctrls": [
{
"name" : "Prénom",
"id" : "prenom",
"type" : "text",
"width" : "50%",
"require": true,
"isValid": function(value) {
return !!value && value.length > 2;
},
"msg" : 'Prénom invalide'
},
{
"name" : "Nom",
"id" : "nom",
"type" : "text",
"width" : "50%",
"require": true,
"isValid": function(value) {
return !!value && value.length > 2;
},
"msg" : 'Nom invalide'
}
]
},
{
"ctrls": [
{
"name" : "Email",
"id" : "email",
"type" : "text",
"width" : null,
"require": true,
"isValid": function(value) {
function validateEmail(email) {
var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return re.test(email);
}
return validateEmail(value);
},
"msg" : 'Email invalide.'
}
]
},
{
"ctrls": [
{
"name" : "Téléphone fixe",
"id" : "telephone_fixe",
"type" : "text",
"width" : "50%",
"require": false
},
{
"name" : "Téléphone portable",
"id" : "telephone_portable",
"type" : "text",
"width" : "50%",
"require": false
}
]
}
]
},
{
"name": "Adresse",
"visible": true,
"lines": [
{
"ctrls": [
{
"name" : "Numero",
"id" : "numero_voie",
"type" : "text",
"width" : "80px",
"require": false
},
{
"name" : "Type voie",
"id" : "type_voie",
"type" : "select",
"width" : "106px",
"require": false,
"options": {
"categories": catTypeVoie
}
},
{
"name" : "Nom voie",
"id" : "nom_voie",
"type" : "text",
"width" : "378px",
"require": true,
"isValid": function(value) {
return !!value;
},
"msg" : 'Nom de voie invalide.'
}
]
},
{
"ctrls": [
{
"name" : "Complément Adresse",
"id" : "complement_addresse",
"type" : "textarea",
"width" : null,
"require": false
}
]
},
{
"ctrls": [
{
"name" : "Bâtiment",
"id" : "batiment",
"type" : "text",
"width" : "50%",
"require": false
},
{
"name" : "Cage escalier",
"id" : "cage_escalier",
"type" : "text",
"width" : "50%",
"require": false
}
]
},
{
"ctrls": [
{
"name" : "Etage / Niveau",
"id" : "etage",
"type" : "text",
"width" : "50%",
"require": false
},
{
"name" : "Numero appartement / porte",
"id" : "numero_appartement",
"type" : "text",
"width" : "50%",
"require": false
}
]
},
{
"ctrls": [
{
"name" : "Code postal",
"id" : "code_postal",
"type" : "text",
"width" : "50%",
"require": true,
"isValid": function(value) {
if(!value || value.length !== 5 || isNaN(parseInt(value, 10))) {
return false;
}
return true;
},
"msg" : 'Non valide'
},
{
"name" : "Ville",
"id" : "ville",
"type" : "text",
"width" : "50%",
"require": true,
"isValid": function(value) {
return !!value && value.length > 2;
},
"msg" : 'Ville invalide.'
}
]
}
]
},
{
"name": "Logement",
"visible": true,
"lines": [
{
"ctrls": [
{
"name" : "Vous êtes",
"id" : "vous_etes",
"type" : "radio",
"width" : null,
"require": true,
"other" : true,
"options": {
"categories": catVousEtes,
"alertes": {
"locataire": "Si vous êtes locataire, vous devez impérativement avertir votre propriétaire que vous souhaitez bénéficier du pré-raccordement à la fibre optique."
}
},
"isValid": function(value, other) {
return !!value && value !== 'autre' || !!other;
},
"msg" : 'Choix incomplet.'
}
]
},
{
"ctrls": [
{
"name" : "Ce logement est",
"id" : "ce_logement_est",
"type" : "radio",
"width" : null,
"require": true,
"other" : true,
"options": {
"categories": catCeLogementEst
},
"isValid": function(value, other) {
return !!value && value !== 'autre' || !!other;
},
"msg" : 'Choix incomplet.'
}
]
}
]
},
{
"name": "Conditions pour le raccordement final d’abonné dans un immeuble individuel",
"visible": true,
"lines": [
{
"text": "Manche Numérique propose aux personnes qui le souhaitent, de faire d’ores et déjà raccorder leur logement ou local à usage professionnel, au futur réseau de communications électroniques à Très Haut Débit FTTH. Le montant de ce raccordement s’élevera à 50 € pour les personnes qui souscriront à une offre Très Haut Débit auprès d’un opérateur et de 400 € pour ceux qui demanderont uniquement la pose de la prise, sans souscription d’un abonnement.
Remarque : Ce raccordement s’appuiera sur vos infrastructures existantes, le coût lié à leur remise en état sera à votre charge en supplément des 50€ ou 400€.",
"ctrls": [
{
"name" : "Accord",
"id" : "accord",
"options": {
"categories": catAccord,
},
"type" : "radio",
"width" : null,
"require": true,
"other" : false,
"isValid": function(value) {
return !!value;
},
"msg" : 'Choix incorrect.',
"note" : 'IMPORTANT : le règlement ne vous sera demandé qu’après travaux effectués'
}
]
}
]
},
{
"name": "Informatique et libertés",
"visible": false,
"lines": [
{
"ctrls": [
{
"name" : "Informatique et libertés",
"id" : "info_et_libertes",
"libelle": 'La personne responsable du traitement de la présente demande de pré-raccordement est le représentant du Syndicat Mixte Manche Numérique, le Président, Monsieur Serge DESLANDES. Les informations portées sur ce formulaire sont obligatoires. Elles font l’objet d’un traitement informatisé destiné au raccordement final de l’usager à la fibre optique (FTTH) ainsi qu’à l’exploitation du réseau optique. Les destinataires des données sont : le Syndicat Mixte Manche Numérique, les entreprises en charge de réaliser les travaux de raccordement, ainsi que l’exploitant du réseau optique. Conformément à la loi "informatique et libertés" du 6 janvier 1978 modifiée, vous bénéficiez d’un droit d’accès, de rectification aux informations qui vous concernent, d’opposition au traitement de vos données personnelles. Si vous souhaitez exercer ce droit et obtenir communication des informations vous concernant, veuillez-vous adresser au Syndicat Mixte Manche Numérique ftth@manchenumerique.fr. Dans l’hypothèse où le présent formulaire est incomplet et/ou illisible, la présente demande de raccordement ne sera pas traitée.',
"type" : "checkbox",
"width" : null,
"require": true,
"isValid": function(value) {
return !!value;
},
"msg" : 'Vous devez accepter.'
}
]
}
]
}
]
}
};
var addCurrentMarker = function(withReverse) {
if(currentMarker) {
map.removeLayer(currentMarker);
}
currentMarker = L.marker([$scope.geoCode.y, $scope.geoCode.x], {draggable: true, title: "texst"}).addTo(map); //.bindPopup(data.locations[0].name).openPopup();
currentMarker.bindPopup("L'adresse que vous nous avez fournie est localisée sur la carte. Il se peut que la position réelle de votre logement soit un peu différente. Dans ce cas, merci de déplacer le pointeur sur la carte pour le positionner à l'emplacement de votre logement.").openPopup();
if(withReverse) {
$scope.magicKey = null;
reverseLocation($scope.geoCode, null, function(address) {
$scope.address = address;
});
}
currentMarker.on('dragend', function(event) {
var p = currentMarker.getLatLng();
//console.log('dragend', p);
$scope.magicKey = null;
$scope.geoCode = {
x: p.lng,
y: p.lat
};
reverseLocation($scope.geoCode, null, function(address) {
$scope.address = address;
getResults();
});
});
};
var computeDateFTTH = function() {
if(!$scope.results.ftth) {return;}
// A date already exists
if($scope.results.ftth.DATE_OUV_SERVICE_REEL || $scope.results.ftth.DATE_OUV_SERVICE_PREV) {
$scope.results.ftth.date = $scope.results.ftth.DATE_OUV_SERVICE_REEL || $scope.results.ftth.DATE_OUV_SERVICE_PREV;
return;
}
else if($scope.results.ftth.DATE_FIN_TRAV_PREV) {
// Compute Date
var momentDate = moment($scope.results.ftth.DATE_FIN_TRAV_PREV, 'DD/MM/YY');
momentDate.add(nbJoursFTTH, 'days');
$scope.results.ftth.date = momentDate.format('DD/MM/YYYY');
}
};
var computeFullAddress = function() {
return $scope.result.eligibilite.complement_addresse;
};
var formatDate = function(value) {
return moment(value, 'DD/MM/YY');
};
var getFullAddress = function(callback) {
if($scope.magicKey) {
var findURL = 'http://api-adresse.data.gouv.fr/search/?';
var url = findURL + "q=" + $scope.address;
$.get(
url,
function(data, status) {
var next = function(record) {
reverseLocation($scope.geoCode, null, function(string, address) {
if(record) {
address.StreetNumber = record.housenumber;
address.Match_addr = $scope.address;
}
callback(null, address);
});
};
if(data && data.features && data.features[0] && data.features[0].properties) {
next(data.features[0].properties);
}
else {
next();
}
});
}
else {
reverseLocation($scope.geoCode, null, function(string, address) {
callback(null, address);
});
}
};
var getRecordsFor = function(identifier, coordinates) {
var records = [];
_.each($scope.data[identifier], function(record) {
_.some(record._polygons, function(polygon) {
if(isInside(polygon, coordinates)) {
records.push(record);
return true;
}
});
});
// Debug
var debug = false;
if (debug) {
var colors = ['red', 'green', 'blue', 'black', 'silver', 'yellow'];
var marker = L.marker([coordinates.y, coordinates.x]).addTo(map);
var Lpolygons = [];
_.each(records, function(record, i) {
var style = {
color : colors[i],
fillColor: colors[i],
weight : 4
};
_.each(record._polygons, function(polygon) {
Lpolygons.push(L.polygon(polygon, style).bindPopup($scope.getHtmlContent(identifier, record)));
});
});
L.layerGroup(Lpolygons).addTo(map);
}
return records;
};
var getResults = function() {
$scope.results = {};
$.ajax({
method : "POST",
url : "ajax/oracle.php",
data : $scope.geoCode
})
.error(function(err) {
console.error('Oracle issue', err);
//[{"ID_ZAPM_PARTIELLE":"119CP0","DATE_OUV_SERVICE_REEL":null,"DATE_OUV_SERVICE_PREV":null,"DATE_FIN_TRAV_PREV":null}]
// Debug without Oracle access
onResults('{"x":-1.1060984089996,"y":49.119046582,"ftth":[{"ID_ZAPM_PARTIELLE":"203AP0","DATE_OUV_SERVICE_REEL":null,"DATE_OUV_SERVICE_PREV":null,"DATE_FIN_TRAV_PREV":"04\/05\/16"}],"adsl":[{"ID_FT_ADSL":"656","LEGENDE":"TV sur ADSL","NATURE":"0 - 37"}],"mimo":null}');
})
.done(function( msg ) {
onResults(msg);
});
var onResults = function(results) {
try {
$scope.results = JSON.parse(results);
$scope.results.address = $scope.address;
$scope.results.ftth = parseResults($scope.results.ftth);
$scope.results.adsl = parseResults($scope.results.adsl);
$scope.results.mimo = parseResults($scope.results.mimo);
computeDateFTTH();
}
catch(e) {
console.error(e);
alert('Probleme de connexion à la base de donnée Oracle.');
$scope.hideResultPane();
}
//console.log('$scope.results', results, '=>', $scope.results);
$scope.$apply();
};
$scope.$evalAsync();
};
var init = function() {
var stlo = [49.1154686, -1.0828136000000086];
var map = L.map('map', {zoomControl:false}).setView(stlo, 9);
map.on('dblclick', function(e) {
var p = e.latlng;
//console.log('click', e.latlng); // e is an event object (MouseEvent in this case)
$scope.geoCode = {
x: p.lng,
y: p.lat
};
addCurrentMarker(true);
$scope.showResultPane();
getResults();
});
var maps = {
"carte" : 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}',
"satellite" : 'http://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'
};
var cLayer = L.tileLayer(maps.satellite, {
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
maxZoom: 18
}).addTo(map);
var styleOpts = {
color : 'red',
fillColor: 'red',
weight : 8
};
$scope.data = {};
$scope.colors = {
"ftth": "#8cc474", // green
"mimo": "#f9b256", // orange
"adsl": "#76a7fa" // blue
};
$http({method: 'POST', url: 'data/dictionary.json'}).success(function(data) {
$scope.dictionary = data;
});
$http({method: 'POST', url: 'data/Contour_Manche.json'}).success(function(data) {
var style = {
color : 'blue',
fillColor: 'blue',
weight : 2
};
$scope.data.manche = [{
_polygons : [data.features[0].geometry.coordinates[0]],
_style : style,
_properties : {
name : {string: 'Manche'}
}
}];
var mancheCoordinates = data && data.features && data.features[0] && data.features[0].geometry && data.features[0].geometry.coordinates && data.features[0].geometry.coordinates[0]; // response data
_.each(mancheCoordinates, function(c, i) {
mancheCoordinates[i] = [c[1], c[0]];
});
// Rectangle coordinates around Manche
//var mancheCoordinates = [[49.732307856286, -1.97117692088061],[48.4, -1.75],[48.4, -0.5],[49.732307856286, -1.2]];
// Debug: show manche limits
//L.polygon(mancheCoordinates, {color: 'blue', fillColor: 'blue',weight: 8}).addTo(map);
searchExtent = {
"xmin" : _.max(_.map(mancheCoordinates, function(c) {return c[1];})),
"ymin" : _.max(_.map(mancheCoordinates, function(c) {return c[0];})),
"xmax" : _.min(_.map(mancheCoordinates, function(c) {return c[1];})),
"ymax" : _.min(_.map(mancheCoordinates, function(c) {return c[0];})),
"spatialReference" : {"wkid" : 84}
};
var suggestURL = 'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/suggest?f=pjson&searchExtent=' + JSON.stringify(searchExtent);
var i = 0, j = 0;
$scope.suggestLocation = function(val) {
//console.log('__suggestLocation', val);
$scope.suggestionsReady = false;
i++;
return $http.get(suggestURL, {
params: {
text: val
}
}).then(function(response) {
if(val === $scope.address) { // Very important to debounce queries
$scope.suggestionsReady = response.data.suggestions.length !== 0;
$scope.suggestions = _.cloneDeep(response.data.suggestions);
}
return response.data.suggestions.map(function(item){
return item.text;
});
});
};
});
//console.time('FTTH data');
$http({method: 'POST', url: 'data/FTTH_zapm_partielle.json'}).success(function(data) {
var style = {
color : $scope.colors.ftth,
fillColor: $scope.colors.ftth,
weight : 2
};
var properties = {
name : {key: 'ATD'},
hidden: ['ID_PM', 'MARCHE', 'ID_FT_ADSL', 'ID_FTTH_MN_ZAPM_PARTIELLE', 'ID_ZAPM_PARTIELLE', 'ID_ZAPM'],
position: ['DATE_DEB_TRAV_PREV']
};
parseData('ftth', data, style, properties);
//console.timeEnd('FTTH data');
//console.debug('Data for FTTH are ready', data);
if($scope.data.mimo && $scope.data.adsl && $scope.data.ftth) {
$scope.loaded = true;
}
$scope.$evalAsync();
});
//console.time('ADSL data');
$http({method: 'POST', url: 'data/TEL_FT_ADSL.json'}).success(function(data) {
var style = {
color : $scope.colors.adsl,
fillColor: $scope.colors.adsl,
weight : 2
};
var properties = {
name : {key: 'LEGENDE'},
hidden: ['NATURE', 'NRA_CETE', 'NRA_TMP', 'NRA_DPT', 'ID_FT_ADSL']
};
parseData('adsl', data, style, properties);
//console.timeEnd('ADSL data');
//console.debug('Data for ADSL are ready', data);
if($scope.data.mimo && $scope.data.adsl && $scope.data.ftth) {
$scope.loaded = true;
}
$scope.$evalAsync();
});
//console.time('MiMo data');
$http({method: 'POST', url: 'data/Couverture_mimo.json'}).success(function(data) {
var style = {
color : $scope.colors.mimo,
fillColor: $scope.colors.mimo,
weight : 2
};
var properties = {
name : {string: 'Couverture MiMo'},
hidden: ['ID_MIMO_COUVERTURE']
};
parseData('mimo', data, style, properties);
//console.timeEnd('MiMo data');
//console.debug('Data for MIMO are ready', data);
if($scope.data.mimo && $scope.data.adsl && $scope.data.ftth) {
$scope.loaded = true;
}
$scope.$evalAsync();
});
window.map = map;
$scope.mapType = 'Satellite';
$scope.view = {};
$scope.isShown = {};
};
var isDate = function(value) {
return (value.toString().length === 8 && value.toString().substr(2, 1) === "/" && value.toString().substr(5,1) === "/");
};
var isInside = function(polygon, point) {
// ray-casting algorithm based on
// http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
var y = point.x ? point.x : point[0],
x = point.y ? point.y : point[1];
var inside = false;
for (var i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
var xi = polygon[i][0], yi = polygon[i][1];
var xj = polygon[j][0], yj = polygon[j][1];
var intersect = ((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
if (intersect) {
inside = !inside;
}
}
return inside;
};
var parseData = function(identifier, data, style, properties) {
var getPolygonsCoord = function(type, coord) {
var result = [];
if(type === 'Polygon') {
result.push(_.map(coord[0], function(r) {return [r[1], r[0]];}));
}
if(type === 'MultiPolygon') {
var p = [];
_.each(coord, function(c) {
result.push(_.map(c[0], function(r) {return [r[1], r[0]];}));
});
}
return result;
};
var records = [];
_.each(data.features, function(r) {
var record = r.properties;
var polygons = getPolygonsCoord(r.geometry.type, r.geometry.coordinates);
record._coordinates = r.geometry.coordinates;
record._type = r.geometry.type;
record._polygons = polygons;
record._style = style;
record._properties = properties;
records.push(record);
});
$scope.data[identifier] = records;
};
var parseResults = function(records) {
if(!records || !records.length) {
return null;
}
if(records.length === 1) {
return records[0];
}
var result = records[0];
return result;
};
var reverseLocation = function(geoCode, address, callback) {
var reverseGeo = 'http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode?f=pjson&distance=300';
var url = reverseGeo + '&location=' + (geoCode ? $scope.geoCode.x + ',' + $scope.geoCode.y : address) ;
$.get(
url,
function(data, status) {
data = JSON.parse(data);
var adresse = data && data.address && data.address.Match_addr;
if(data && data.address && data.address.Address) {
var i = 0;
var num = '';
while(!isNaN(parseInt(data.address.Address[i], 10))) {
num += data.address.Address[i];
i++;
}
data.address.StreetNumber = num;
data.address.Address = data.address.Address.substr(num.length).trim();
var typeVoie = data.address.Address.substring(0, data.address.Address.indexOf(' ')).toLowerCase();
type = _.find(catTypeVoie, function(c){
if(c.id === typeVoie || c.name.toLowerCase() === typeVoie) {
return true;
}
});
if(type) {
data.address.StreetType = type.id;
data.address.Address = data.address.Address.substr(typeVoie.length).trim();
}
}
//console.debug('Reverse', geoCode, address, '=>', adresse, data.address);
callback(adresse, data.address);
$scope.$evalAsync();
});
};
$scope.changeMap = function(value) {
//console.log('Goto', value);
map.removeLayer(cLayer);
cLayer = L.tileLayer(maps[value], {
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
maxZoom: 18
}).addTo(map);
};
$scope.closeRight = function() {
$mdSidenav('right').close().then(function(){});
};
$scope.computeLayer = function(identifier) {
var Lpolygons = [];
_.each($scope.data[identifier], function(record) {
_.each(record._polygons, function(polygon) {
Lpolygons.push(L.polygon(polygon, record._style).bindPopup($scope.getHtmlContent(identifier, record)));
});
});
layer[identifier] = L.layerGroup(Lpolygons);
};
$scope.formatDateFTTH = function(date) {
if(!date || date === "Invalid date") {return;}
var momentDate = moment(date, 'DD/MM/YYYY');
var result = '';
return $sce.trustAsHtml(result);
};
$scope.formatResults = function(identifier, results) {
return $sce.trustAsHtml($scope.getHtmlContent(identifier, results));
};
$scope.getGeoCode = function(address, magicKey, callback) {
var findURL = 'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/find?f=pjson&searchExtent=' + JSON.stringify(searchExtent);
getGeoCodeInProgress = true;
var url = findURL + "&text=" + address + ((magicKey) ? ("&magicKey=" + magicKey) : ', Basse-Normandie, France');
//console.log('url', url);
$.get(
url,
function(data, status) {
data = JSON.parse(data);
console.debug('address, magicKey', address, magicKey, data);
if (status === 'success' && data.locations[0]) {
if(data.locations[0].extent.xmax < searchExtent.xmin &&
data.locations[0].extent.xmax > searchExtent.xmax &&
data.locations[0].extent.xmin > searchExtent.xmax &&
data.locations[0].extent.xmin > searchExtent.xmax) {
getGeoCodeInProgress = false;
//console.debug('getGeoCode', address, magicKey, '=>', data);
return callback(null, data);
}
getGeoCodeInProgress = false;
//console.debug('getGeoCode', address, magicKey, '=>', 'No result');
callback('No result for ' + address);
} else {
getGeoCodeInProgress = false;
//console.debug('getGeoCode', address, magicKey, '=>', 'No result');
callback(status !== 'success' ? status : 'No result for ' + address);
}
});
};
$scope.getHtmlContent = function(identifier, record) {
//var title = record._properties.name.string ? record._properties.name.string : record[record._properties.name.key];
// Tooltip content
var tooltip = '';
_.each(record, function(value, property) {
if(property.charAt(0) === '_' ||
(property === 'date' && identifier === 'ftth') ||
value === null ||
typeof value === 'undefined') {
return;
}
var label = $scope.dictionary[property] || property;
value = $scope.dictionary[value] || value;
var date;
if(property.substring(0, 5) === 'DATE_' && !$scope.dictionary[value] && isDate(value)) {
date = formatDate(value);
}
tooltip += '';
});
if(identifier === 'adsl') {
tooltip = 'Tester mon éligibilité ADSL avec Ariase.com';
}
return tooltip;
};
$scope.hideLayer = function(identifier) {
map.removeLayer(layer[identifier]);
};
$scope.hideResultPane = function() {
if(!$('#result').height()) {return;}
$('#result').animate({height: 0}, 1000);
$('#map').animate({
height: $('body').height(),
}, 1000, function() {
// Animation complete.
map.invalidateSize();
var centerPoint = $scope.geoCode ? new L.LatLng($scope.geoCode.y, $scope.geoCode.x) : stlo;
map.setView(centerPoint, 14);
});
};
$scope.initPopup = function() {
//console.log('initPopup', $scope.geoCode);
$scope.postForm = null;
getFullAddress(function(err, address) {
if(err) {console.error(err);}
//console.log('add', address);
$scope.result = {eligibilite: {}, autres: {}};
// Debug
// $scope.result.eligibilite.prenom = 'Francois';
// $scope.result.eligibilite.nom = 'Beaufils';
// $scope.result.eligibilite.email = 'francoisbeaufils@zeno-labs.com';
// $scope.result.eligibilite.vous_etes = 'locataire';
// $scope.result.eligibilite.ce_logement_est = 'residence_principale';
// $scope.result.eligibilite.info_et_libertes = true;
// $scope.result.eligibilite.accord = 'avec_souscription';
$scope.result.eligibilite.geo_code = JSON.stringify($scope.geoCode);
$scope.result.eligibilite.code_postal = address.Postal;
$scope.result.eligibilite.complement_addresse = address.Match_addr;
$scope.result.eligibilite.nom_voie = address.Address;
$scope.result.eligibilite.numero_voie = address.StreetNumber;
$scope.result.eligibilite.type_voie = address.StreetType;
$scope.result.eligibilite.ville = address.City;
});
};
$scope.isFormValid = function() {
if(!$scope.result || !$scope.result.eligibilite) {return;}
var isValid = true;
_.each($scope.formulaires.eligibilite.sections, function(section) {
_.each(section.lines, function(line) {
_.each(line.ctrls, function(ctrl) {
ctrl.invalid = false;
if(ctrl.require && !ctrl.isValid($scope.result.eligibilite[ctrl.id], $scope.result.autres[ctrl.id])) {
isValid = false;
ctrl.invalid = true;
}
});
});
});
return isValid;
};
$scope.onSubmitAddress = function($item, $model, $label) {
// console.log('onSubmitAddress address', $scope.address);
// console.log('onSubmitAddress $item', $item);
// console.log('onSubmitAddress $model', $model);
// console.log('onSubmitAddress $label', $label);
// Get magic key
var item = _.find($scope.suggestions, {text: $item});
if(!item) {
item = $scope.suggestions[0];
$scope.address = item.text;
}
$scope.magicKey = item.magicKey;
//console.log('onSubmitAddress -_-item', item, '=>', $scope.magicKey);
$scope.getGeoCode($scope.address, $scope.magicKey, function(err, data) {
$scope.geoCode = data && data.locations && data.locations[0] && data.locations[0].feature.geometry;
if(err) {console.error('Geocode error', err);}
var toast = toast || {
template: ' Oups! Aucun résultat trouvé dans la Manche pour: ' + $scope.address + '',
hideDelay: 3000,
position: 'bottom right'
};
// $mdToast.simple()
// .template(')
// .position('bottom right')
// .hideDelay(3000);
if(err || !$scope.geoCode) {
$scope.hideResultPane();
$mdToast.show(toast);
}
//console.log('Addresses found for', $scope.address, '=>', data, '=> Geocode:', $scope.geoCode);
if($scope.geoCode) {
addCurrentMarker();
$scope.showResultPane();
getResults();
}
});
};
$scope.postFormEl = function() {
$scope.postForm = {inProgress: true};
_.each($scope.result.autres, function(value, key) {
$scope.result.eligibilite[key] = value;
});
//console.log('postForm', $scope.result.eligibilite);
$scope.$evalAsync();
function mysql_real_escape_string (str) {
if(typeof str !== 'string') {return str;}
return str.replace(/[\0\x08\x09\x1a\n\r"'\\\%]/g, function (char) {
switch (char) {
case "\0":
return "\\0";
case "\x08":
return "\\b";
case "\x09":
return "\\t";
case "\x1a":
return "\\z";
case "\n":
return "\\n";
case "\r":
return "\\r";
case "\"":
case "'":
case "\\":
case "%":
return "\\"+char; // prepends a backslash to backslash, percent,
// and double/single quotes
}
});
}
var keys = '';
var values = '';
_.each($scope.result.eligibilite, function(value, key) {
keys += '`' + key + '`, ';
values += "'" + mysql_real_escape_string(value) + "', ";
});
var dateTime = (new Date ((new Date((new Date(new Date())).toISOString() )).getTime() - ((new Date()).getTimezoneOffset()*60000))).toISOString().slice(0, 19).replace('T', ' ');
var query = "INSERT INTO `eligibilite`.`demandes` (`date`," + keys.substring(0, keys.length -2) + ") VALUES ('" + dateTime + "', " + values.substring(0, values.length -2) + ");";
console.log('query', query);
$.ajax({
method : "POST",
url : "ajax/datastores.php",
data : {query: query}
})
.done(function( msg ) {
if(!isNaN(msg)) {
$scope.postForm = {ok: true};
var template = $templateCache.get('nameOfTemplate.html');
var numDemande = moment().format('YYYYMMDD') + msg;
var body = '';
body += 'Bonjour ' + $scope.result.eligibilite.prenom + ' ' + $scope.result.eligibilite.nom + ',
' +
'Nous vous confirmons votre demande de pré-raccordement FTTH.
' +
'Cette demande porte le numéro: ' +
'' + numDemande + '
' +
'Voici le détail de votre demande:' +
'' +
'
';
// _.each($scope.result.eligibilite, function(value, key) {
// body += '';
// body += '| ' + key + ' | ';
// body += '' + value + ' | ';
// body += '
';
// });
// Numero demande
body += '';
body += '| Numéro demande | ';
body += '' + numDemande + ' | ';
body += '
';
// Date demande
body += '';
body += '| Date | ';
body += '' + moment().lang('fr').format('LLLL') + ' | ';
body += '
';
// Demandeur
body += '';
body += '| Demandeur | ';
body += '' + $scope.result.eligibilite.prenom + ' ' + $scope.result.eligibilite.nom + ' | ';
body += '
';
// Email
body += '';
body += '| Email | ';
body += '' + $scope.result.eligibilite.email + ' | ';
body += '
';
// Adresse
body += '';
body += '| Adresse | ';
body += '' + computeFullAddress() + ' | ';
body += '
';
// Vous etes
var cat = _.find(catVousEtes, {id: $scope.result.eligibilite.vous_etes});
var res = cat && cat.name ? cat.name : $scope.result.eligibilite.vous_etes;
body += '';
body += '| Vous êtes | ';
body += '' + res + ' | ';
body += '
';
// Ce logement est
var cat2 = _.find(catCeLogementEst, {id: $scope.result.eligibilite.ce_logement_est});
var res2 = cat2 && cat2.name ? cat2.name : $scope.result.eligibilite.ce_logement_est;
body += '';
body += '| Ce logement est | ';
body += '' + res2 + ' | ';
body += '
';
//console.log('$scope.result', $scope.result);
body += '
';
body += 'Conformément à la loi "informatique et libertés" du 6 janvier 1978 modifiée, vous bénéficiez d’un droit d’accès, de rectification aux informations qui vous concernent, d’opposition au traitement de vos données personnelles. Si vous souhaitez exercer ce droit et obtenir la communication des informations vous concernant, merci de nous contacter :' + '
' +
'' +
' ' +
' | Email | ' + siteEmail + ' | ' +
'
' +
' | Adresse | ' + siteAddresse + ' | ' +
'
' +
' | Tel | ' + siteTel + ' | ' +
'
' +
'
';
body += 'A bientôt sur: ' + siteName + '';
console.log('body', body);
var mail = {
to : $scope.result.eligibilite.email,
sujet : 'Votre demande de pré-raccordement FTTH n° ' + numDemande,
message: body
};
$.ajax({
method : "POST",
url : "ajax/datastores.php",
data : {
siteEmail: siteEmail,
mail : mail}
})
.done(function( msg ) {
console.log('Mail result', msg);
});
$scope.result.eligibilite = {};
$scope.autres = {};
$scope.address = null;
$scope.magicKey = null;
}
else {
$scope.postForm = {error: msg};
}
$scope.hideResultPane();
$scope.$apply();
});
};
$scope.showLayer = function(identifier) {
map.addLayer(layer[identifier]);
};
$scope.showResultPane = function() {
var bodyHeight = $('body').height();
var height = Math.max(300, bodyHeight / 3);
var heightMap = bodyHeight - height;
$('#result').animate({height: height + 'px'}, 1000);
$('#map').animate({
height: heightMap + 'px',
}, 1000, function() {
// Animation complete.
map.invalidateSize();
map.setView(new L.LatLng($scope.geoCode.y, $scope.geoCode.x), 14);
});
};
$scope.toggleResultPane = function() {
if($('#result').height()) {
return $scope.hideResultPane();
}
if($scope.results && $scope.results.ftth) {
return $scope.showResultPane();
}
};
$scope.toggleRight = function() {
$mdSidenav('right').toggle()
.then(function(){});
};
$scope.$watch('view', function(view) {
if(_.isEmpty(view)) {return;}
$('#layer-loading').removeClass('force-hidden').find('.md-inner').show();
setTimeout(function() {
_.each(view, function(value, key) {
if($scope.isShown[key] !== value) {
if(value) {
if(typeof $scope.isShown[key] !== 'undefined') {
$scope.showLayer(key);
$('#layer-loading').find('.md-inner').hide();
}
else {
$timeout(function() {
$scope.computeLayer(key);
$scope.showLayer(key);
$('#layer-loading').find('.md-inner').hide();
}, 500);
}
}
else {
$scope.hideLayer(key);
setTimeout(function() {
$('#layer-loading').find('.md-inner').hide();
}, 1000);
}
$scope.isShown[key] = value;
}
});
});
}, true);
$(window).resize(function() {
if(!$('#result').height()) {return;}
$scope.showResultPane();
});
init();
$scope.toto = 'FB SA RAXCE';
var templateUrl = $sce.getTrustedResourceUrl('html/emailTemplate.html');
$templateRequest(templateUrl).then(function(template) {
// template is the HTML template as a string
// Let's put it into an HTML element and parse any directives and expressions
// in the code. (Note: This is just an example, modifying the DOM from within
// a controller is considered bad style.)
var factory = angular.element(template);
//factory.html();
$compile(factory)($scope);
// get the interpolated HTML asynchronously after the interpolation happens
$timeout(function () {
factory.append('');
html = factory.html();
console.log('template', html);
// ... do whatever you need with the interpolated HTML
});
}, function() {
// An error has occurred
});
});