]> dev.renevier.net Git - syj.git/blob - public/js/syj.js
routes profile
[syj.git] / public / js / syj.js
1 /*  This file is part of Syj, Copyright (c) 2010-2011 Arnaud Renevier,
2     and is published under the AGPL license. */
3
4 "use strict";
5
6 // avoid openlayers alerts
7 OpenLayers.Console.userError = function(error) {
8     SYJView.messenger.setMessage(error, "error");
9 };
10
11 OpenLayers.Layer.Vector.prototype.renderers = ["SVG2", "VML", "Canvas"];
12
13 var SyjSaveUI = {
14     status: "unknown",
15
16     init: function() {
17         $("geom_title").observe('contentchange', this.enableSubmit.bindAsEventListener(this));
18         return this;
19     },
20
21     enable: function() {
22         if (this.status === "enabled") {
23             return this;
24         }
25         this.enableSubmit();
26         $("geom_title").disabled = false;
27         $("geom_title").activate();
28         $$("#geom_accept_container, #geom_title_container").invoke('removeClassName', "disabled");
29         this.status = "enabled";
30         return this;
31     },
32
33     disable: function() {
34         if (this.status === "disabled") {
35             return this;
36         }
37         this.disableSubmit();
38         $("geom_title").blur();
39         $("geom_title").disabled = true;
40         $$("#geom_accept_container, #geom_title_container").invoke('addClassName', "disabled");
41         this.status = "disabled";
42         return this;
43     },
44
45     enableSubmit: function() {
46         $("geom_submit").disabled = false;
47         $("geom_accept").disabled = false;
48         this.status = "partial";
49         return this;
50     },
51
52     disableSubmit: function() {
53         $("geom_submit").blur();
54         $("geom_submit").disabled = true;
55         $("geom_accept").blur();
56         $("geom_accept").disabled = true;
57         this.status = "partial";
58         return this;
59     }
60 };
61
62 var SYJPathLength = (function(){
63     return {
64         update: function() {
65             var pathLength = 0, unit;
66             if (SYJView.mode === 'view') {
67                 if (SYJView.viewLayer.features.length) {
68                     pathLength = SYJView.viewLayer.features[0].geometry.getGeodesicLength(Mercator);
69                 }
70             } else {
71                 pathLength = SYJView.editControl.handler.line.geometry.getGeodesicLength(Mercator);
72             }
73
74             if (pathLength === 0) {
75                 $("path-length").hide();
76                 return;
77             }
78             $("path-length").show();
79
80             if (pathLength < 1000) {
81                 // precision: 1 cm
82                 pathLength = Math.round(pathLength * 100) / 100;
83                 unit = 'm';
84             } else {
85                 // precision: 1 m
86                 pathLength = Math.round(pathLength) / 1000;
87                 unit = 'km';
88             }
89             $("path-length-content").update(pathLength + ' ' + unit);
90         }
91     };
92 }());
93
94 var SYJDataUi = (function() {
95     var deck = null,
96         infotoggler = null,
97         getdeck = function() {
98             if (!deck) {
99                 deck = new Deck("data_controls");
100             }
101             return deck;
102         },
103         getinfotoggler = function() {
104             if (!infotoggler) {
105                 infotoggler = new Toggler('path-infos-content');
106                 $("path-infos-toggler").insert({bottom: infotoggler.element});
107                 var anchor = $("path-infos-anchor");
108                 var parent = anchor.up('.menu-item');
109                 if (parent) {
110                     anchor = parent;
111                 }
112                 anchor.observe('click', function(evt) {
113                     evt.stop();
114                     infotoggler.toggle(evt);
115                 });
116                 document.observe('toggler:open', function(evt) {
117                     if (evt.memo === infotoggler) {
118                         // XXX: update informations
119                     }
120                 });
121             }
122             return infotoggler;
123         };
124     return {
125         viewmode: function() {
126             getdeck().setIndex(0);
127             if ($("path-infos")) {
128                 getinfotoggler();
129                 getinfotoggler().close();
130                 $("path-infos").show();
131             }
132         },
133         editmode: function() {
134             getdeck().setIndex(1);
135             if ($("path-infos")) {
136                 $("path-infos").hide();
137             }
138         }
139     };
140 }());
141
142 OpenLayers.Handler.SyjModifiablePath = OpenLayers.Class(OpenLayers.Handler.ModifiablePath, {
143     mouseup: function(evt) {
144         // do not add a point when navigating
145         var mapControls = this.control.map.controls, idx, ctrl;
146
147         for (idx = mapControls.length; idx-->0; ) {
148             ctrl = mapControls[idx];
149             if (this.isCtrlNavigationActive(ctrl, evt)) {
150                 return true;
151             }
152         }
153         return OpenLayers.Handler.ModifiablePath.prototype.mouseup.apply(this, arguments);
154     },
155
156     addPoints: function(pixel) {
157         // redraw before last point. As we have a special style for last point, we
158         // need to redraw before last point after adding a new point (otherwise, it
159         // keeps special style forever)
160         var oldpoint = this.point;
161         OpenLayers.Handler.ModifiablePath.prototype.addPoints.apply(this, arguments);
162         this.layer.drawFeature(oldpoint);
163     },
164
165     isCtrlNavigationActive: function(ctrl, evt) {
166         var tolerance = 4, xDiff, yDiff;
167
168         if (!(ctrl instanceof OpenLayers.Control.Navigation)) {
169             return false;
170         }
171
172         if (ctrl.zoomBox &&
173             ctrl.zoomBox.active &&
174             ctrl.zoomBox.handler &&
175             ctrl.zoomBox.handler.active &&
176             ctrl.zoomBox.handler.dragHandler &&
177             ctrl.zoomBox.handler.dragHandler.start) {
178             return true;
179         }
180
181         if (!ctrl.dragPan ||
182             !ctrl.dragPan.active ||
183             !ctrl.dragPan.handler ||
184             !ctrl.dragPan.handler.started ||
185             !ctrl.dragPan.handler.start) {
186             return false;
187         }
188
189         // if mouse moved 4 or less pixels, consider it has not moved.
190         tolerance = 4;
191
192         xDiff = evt.xy.x - ctrl.dragPan.handler.start.x;
193         yDiff = evt.xy.y - ctrl.dragPan.handler.start.y;
194
195         if (Math.sqrt(Math.pow(xDiff,2) + Math.pow(yDiff,2)) <= tolerance) {
196             return false;
197         }
198         return true;
199     },
200
201     finalize: function(cancel) {
202         // do nothing. We don't want to finalize path
203     }
204 });
205
206 var styleMap = {
207     edit: new OpenLayers.StyleMap({
208         "default": new OpenLayers.Style({
209             pointRadius: "${radius}", // sized according to type attribute
210             fillColor: "#ffcc66",
211             strokeColor: "#ff9933",
212             strokeWidth: 2,
213             strokeOpacity: "${opacity}",
214             fillOpacity: "${opacity}"
215         },
216         {
217             context: {
218                 radius: function(feature) {
219                     var features;
220
221                     if (!(feature.geometry instanceof OpenLayers.Geometry.Point)) {
222                         return 0;
223                     }
224                     if (feature.type === "middle") {
225                         return 4;
226                     }
227                     features = feature.layer.features;
228                     if (OpenLayers.Util.indexOf(features, feature) === 0) {
229                         return 5;
230                     } else if (OpenLayers.Util.indexOf(features, feature) === features.length - 1) {
231                         return 5;
232                     }
233                     return 3;
234                 },
235                 opacity: function (feature) {
236                     if (feature.type === "middle") {
237                         return 0.5;
238                     } else {
239                         return 1;
240                     }
241                 }
242             }
243         }),
244
245         "select": new OpenLayers.Style({
246             externalGraphic: "icons/delete.png",
247             graphicHeight: 16
248         }),
249
250         "select_for_canvas": new OpenLayers.Style({
251             strokeColor: "blue",
252             fillColor: "lightblue"
253         })
254
255     }),
256
257     view: new OpenLayers.StyleMap({
258         "default": new OpenLayers.Style({
259             strokeColor: "blue",
260             strokeWidth: 5,
261             strokeOpacity: 0.7
262         })
263     })
264 };
265
266 var WGS84 = new OpenLayers.Projection("EPSG:4326");
267 var Mercator = new OpenLayers.Projection("EPSG:900913");
268
269 var SYJView = {
270     viewLayer: null,
271     editControl: null,
272     map: null,
273     wkt: new OpenLayers.Format.WKT({ internalProjection: Mercator, externalProjection: WGS84 }),
274     needsFormResubmit: false,
275     unsavedRoute: null,
276     mode: 'view',
277
278     init: function() {
279         var externalGraphic, baseURL, mapnikLayer, mapquestLayer, layerOptions, hidemessenger, layerCode, parameters;
280
281         // is svg context, opera does not resolve links with base element is svg context
282         externalGraphic = styleMap.edit.styles.select.defaultStyle.externalGraphic;
283         baseURL = document.getElementsByTagName("base")[0].href;
284         styleMap.edit.styles.select.defaultStyle.externalGraphic = baseURL + externalGraphic;
285
286         this.map = new OpenLayers.Map('map', {
287             controls: [
288                 new OpenLayers.Control.Navigation(),
289                 new OpenLayers.Control.PanZoom(),
290                 this.createLayerSwitcher(),
291                 new OpenLayers.Control.Attribution()
292             ],
293             theme: null
294         });
295
296         mapnikLayer = new OpenLayers.Layer.OSM("Mapnik", [
297                 'http://a.tile.openstreetmap.org/${z}/${x}/${y}.png',
298                 'http://b.tile.openstreetmap.org/${z}/${x}/${y}.png',
299                 'http://c.tile.openstreetmap.org/${z}/${x}/${y}.png'],
300                 { attribution: SyjStrings.osmAttribution, layerCode: 'M' });
301
302         mapquestLayer = new OpenLayers.Layer.OSM("MapQuest", [
303             'http://otile1.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.png',
304             'http://otile2.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.png',
305             'http://otile3.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.png',
306             'http://otile4.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.png'],
307                 { attribution: SyjStrings.mapquestAttribution, layerCode: 'Q'});
308
309         layerOptions = {format:     OpenLayers.Format.WKT,
310                         projection: WGS84,
311                         styleMap:   styleMap.view,
312                         attribution: SyjStrings.geomAttribution };
313
314         this.viewLayer = new OpenLayers.Layer.Vector("View Layer", layerOptions);
315         this.map.addLayers([mapnikLayer, mapquestLayer, this.viewLayer]);
316
317         this.map.setBaseLayer(mapnikLayer);
318         layerCode = null;
319         parameters = OpenLayers.Util.getParameters(window.location.href);
320         if (parameters.layer) {
321             layerCode = parameters.layer;
322             try {
323                 store.remove('baselayer');
324             } catch(e) {}
325         } else {
326             try {
327                 layerCode = store.get('baselayer');
328             } catch(e) {}
329         }
330
331         if (layerCode) {
332             layerCode = layerCode.toUpperCase();
333             var self = this;
334             $([mapnikLayer, mapquestLayer]).each(function(layer) {
335                 if (layer.layerCode === layerCode) {
336                     self.map.setBaseLayer(layer);
337                 }
338             });
339         }
340
341         this.map.events.register("changebaselayer", this, this.saveBaseLayer);
342
343         if ($("edit-btn")) {
344             $("edit-btn").observe('click', function() {
345                 $("geom_submit").value = SyjStrings.editAction;
346                 this.messenger.clearMessages();
347                 this.editMode();
348                 this.mode = 'edit';
349             }.bind(this));
350         }
351
352         if ($("create-btn")) {
353             $("create-btn").observe('click', function() {
354                 $("geom_submit").value = SyjStrings.createAction;
355                 this.messenger.clearMessages();
356                 this.editMode();
357                 this.mode = 'create';
358             }.bind(this));
359         }
360
361         if ($("clone-btn")) {
362             $("clone-btn").observe('click', function() {
363                 $("geom_submit").value = SyjStrings.cloneAction;
364                 $("geom_title").value = "";
365                 this.messenger.clearMessages();
366                 this.editMode();
367                 this.mode = 'create';
368             }.bind(this));
369         }
370
371         $("geomform").ajaxize({
372                 presubmit: this.prepareForm.bind(this),
373                 onSuccess: this.saveSuccess.bind(this),
374                 onFailure: this.saveFailure.bind(this)
375                 });
376         SyjSaveUI.init();
377
378         this.messenger = $('message');
379         hidemessenger = this.messenger.empty();
380         new CloseBtn(this.messenger, {
381             style: {
382                 margin: "-1em"
383             }
384         });
385         if (hidemessenger) {
386             this.messenger.hide();
387         }
388
389         if (typeof gInitialGeom !== "undefined" && typeof gInitialGeom.data !== "undefined") {
390             this.viewLayer.addFeatures([this.wkt.read(gInitialGeom.data)]);
391             // XXX: ie has not guessed height of map main div yet during map
392             // initialisation. Now, it will read it correctly.
393             this.map.updateSize();
394             this.map.zoomToExtent(this.viewLayer.getDataExtent());
395         } else {
396             this.initMaPos(gInitialPos);
397         }
398
399         $("map-overlay").hide();
400         $("geom_upload").observe('change', function(evt) {
401             var file = null, reader = null, readerror = null;
402             if (window.FileList && window.FileReader) {
403                 file = evt.target.files[0];
404                 reader = new FileReader();
405                 readerror = function() {
406                     this.messenger.setMessage(SyjStrings.uploadFileError, "warn");
407                 }.bind(this);
408                 reader.onload = function(evt) {
409                     var data = null, results = null, engine = null, vector = null, i = 0, format = null, formats = ['KML', 'GPX', 'GeoJSON'];
410
411                     $("geom_upload_container").removeClassName("disabled");
412                     $("geom_upload").disabled = false;
413                     if (evt.error) {
414                         readerror();
415                         return;
416                     }
417                     data = evt.target.result;
418
419                     for (i = 0; i < formats.length; i++) {
420                         format = formats[i];
421                         engine = new OpenLayers.Format[format]({ internalProjection: Mercator, externalProjection: WGS84 });
422                         try {
423                             results = engine.read(data);
424                         } catch(e) {
425                         }
426                         if (results && results.length) {
427                             break;
428                         }
429                     }
430                     if (!results || !results.length) {
431                         readerror();
432                         return;
433                     }
434
435                     vector = results[0];
436                     if (vector.geometry.CLASS_NAME !== "OpenLayers.Geometry.LineString") {
437                         readerror();
438                         return;
439                     }
440                     // merge linestrings for gpx containting multiple trkseg elements.
441                     if (format === 'GPX') {
442                       for (i = 1; i < results.length; i++) {
443                         vector.geometry.addComponents(results[i].geometry.components);
444                       }
445                     }
446                     this.viewLayer.addFeatures([vector]);
447                     this.map.zoomToExtent(this.viewLayer.getDataExtent());
448
449                     if ($("edit-btn")) {
450                         $("edit-btn").click();
451                     } else if ($("create-btn")) {
452                         $("create-btn").click();
453                     }
454
455                     if (this.editControl.handler.realPoints.length < 2) {
456                         SyjSaveUI.disable();
457                     } else {
458                        SyjSaveUI.enable();
459                     }
460
461                     if (vector.data && vector.data.name) {
462                         $("geom_title").value = vector.data.name;
463                     }
464                 }.bind(this);
465                 $("geom_upload_container").addClassName("disabled");
466                 $("geom_upload").disabled = true;
467                 reader.readAsText(file);
468                 return;
469             }
470             $("map-overlay").show();
471             SyjSaveUI.enable();
472             this.editControl.deactivate();
473         }.bind(this));
474
475         document.observe('simplebox:shown', this.observer.bindAsEventListener(this));
476         SYJPathLength.update();
477     },
478
479     saveBaseLayer: function(data) {
480         try {
481             store.set('baselayer', data.layer.layerCode);
482         } catch(e) {}
483     },
484
485     createLayerSwitcher: function() {
486         var control = new OpenLayers.Control.LayerSwitcher({roundedCorner: false});
487         // XXX: we need to "live-patch" LayerSwitcher to use our icons. We use
488         // a regexp instead of a string in case OpenLayers is modified and in
489         // case browsers modify the function representation
490         control.loadContents = eval('(function() { return (' + control.loadContents.toString().replace(
491                     /\s*=\s*imgLocation\s*\+\s*['"]layer-switcher-maximize\.png['"]\s*;/,
492                     " = 'icons/layer-switcher-maximize-flipped.png';"
493                     ) + ')}())');
494         var oldMaximizeControl = control.maximizeControl;
495         var self = this;
496         control.maximizeControl = (function(oldfunc) {
497             return function() {
498                 oldfunc.apply(control, arguments);
499                 self.messenger.hide();
500             };
501         }(control.maximizeControl));
502
503         return control;
504     },
505
506     initMaPos: function (aPos) {
507         var extent = null, center = null, zoom = 0;
508
509         if (aPos.hasOwnProperty('lon') && aPos.hasOwnProperty('lat') && aPos.hasOwnProperty('zoom')) {
510             center = new OpenLayers.LonLat(parseFloat(aPos.lon), parseFloat(aPos.lat)).transform(WGS84, Mercator);
511             zoom = parseInt(aPos.zoom, 10);
512         } else if (aPos.hasOwnProperty('minlon') && aPos.hasOwnProperty('minlat')
513                     && aPos.hasOwnProperty('maxlon') && aPos.hasOwnProperty('maxlat')) {
514             extent = new OpenLayers.Bounds(aPos.minlon, aPos.minlat, aPos.maxlon, aPos.maxlat)
515                                          .transform(WGS84, Mercator);
516         } else {
517             extent = new OpenLayers.Bounds(-160, -70, 160, 70).transform(WGS84, Mercator);
518         }
519
520         if (extent) {
521             this.map.zoomToExtent(extent);
522         } else {
523             this.map.setCenter(center, zoom);
524         }
525     },
526
527     observer: function(evt) {
528         if (evt.eventName === "simplebox:shown" && evt.memo.element !== $("termsofusearea")) {
529             this.messenger.clearMessages();
530         }
531     },
532
533     prepareForm: function(form) {
534         if (!LoginMgr.logged && !$("geom_accept").checked) {
535             this.messenger.setMessage(SyjStrings.acceptTermsofuseWarn, "warn");
536             $("geom_accept_container").highlight('#F08080');
537             $("geom_accept").activate();
538             return false;
539         }
540
541         var line, realPoints, idx;
542
543         line = new OpenLayers.Geometry.LineString();
544         realPoints = this.editControl.handler.realPoints;
545         for (idx = 0; idx < realPoints.length; idx++) {
546             line.addComponent(realPoints[idx].geometry.clone());
547         }
548         this.viewLayer.addFeatures(new OpenLayers.Feature.Vector(line));
549
550         this.viewMode();
551
552         if (line.components.length) {
553             $("geom_data").value = this.wkt.write(new OpenLayers.Feature.Vector(line));
554         } else {
555             $("geom_data").value = "";
556         }
557
558         if (this.mode === "edit" && typeof gLoggedInfo.pathid !== "undefined") {
559             $("geomform").setAttribute("action", "path/" + gLoggedInfo.pathid.toString() + '/update');
560         } else {
561             $("geomform").setAttribute("action", "path");
562         }
563         this.needsFormResubmit = false;
564         SyjSaveUI.disable.bind(SyjSaveUI).defer();
565         this.messenger.clearMessages();
566         return true;
567     },
568
569     viewMode: function() {
570         var handler = this.editControl.handler;
571         OpenLayers.Handler.ModifiablePath.prototype.finalize.apply(handler, arguments);
572         // we need to recreate them on next createFeature; otherwise
573         // they'll reference destroyed features
574         delete(handler.handlers.drag);
575         delete(handler.handlers.feature);
576         this.editControl.deactivate();
577     },
578
579     editMode: function() {
580         var components, point0, point, pixels, pixel, idx;
581
582         this.initEditControl();
583
584         this.editControl.activate();
585         if (this.viewLayer.features.length) {
586             components = this.viewLayer.features[0].geometry.components;
587             point0 = components[0];
588             if (point0) {
589                 pixel = this.map.getPixelFromLonLat(new OpenLayers.LonLat(point0.x, point0.y));
590                 this.editControl.handler.createFeature(pixel);
591                 this.editControl.handler.lastUp = pixel;
592                 pixels = [];
593                 for (idx = 1; idx < components.length; idx++) {
594                     point = components[idx];
595                     pixels.push(this.map.getPixelFromLonLat(new OpenLayers.LonLat(point.x, point.y)));
596                 }
597                 this.editControl.handler.addPoints(pixels);
598             }
599             this.unsavedRoute = {
600                 features: this.viewLayer.features.invoke('clone'),
601                 title: $("geom_title").value
602             };
603         }
604
605         this.viewLayer.destroyFeatures();
606
607         SYJDataUi.editmode();
608         if (this.editControl.handler.realPoints && this.editControl.handler.realPoints.length >= 2) {
609             SyjSaveUI.disableSubmit();
610         } else {
611             SyjSaveUI.disable();
612         }
613     },
614
615     initEditControl: function() {
616         var styles;
617
618         if (this.editControl) {
619             return;
620         }
621
622         this.editControl = new OpenLayers.Control.DrawFeature(new OpenLayers.Layer.Vector(), OpenLayers.Handler.SyjModifiablePath, {
623             callbacks: {
624                 modify: function(f, line) {
625                     SYJPathLength.update();
626
627                     var npoints = this.handler.realPoints.length;
628                     if (npoints === 0) {
629                         $("geom_upload_container").show();
630                         SYJView.unsavedRoute = null;
631                     } else {
632                         if (!SYJView.unsavedRoute) {
633                             SYJView.unsavedRoute = {};
634                         }
635                     }
636
637                     if (npoints < 2) {
638                         SyjSaveUI.disable();
639                     } else {
640                         SyjSaveUI.enable();
641                     }
642                 },
643                 create: function(f, line) {
644                     this.messenger.clearMessages();
645                     $("geom_upload_container").hide();
646                 }.bind(this)
647             },
648
649             handlerOptions: {
650                 layerOptions: {
651                     styleMap: styleMap.edit
652                 }
653             }
654         });
655         this.map.addControl(this.editControl);
656         if (this.editControl.layer.renderer instanceof OpenLayers.Renderer.Canvas) {
657             // using externalGraphic with canvas renderer is definitively too buggy
658             styles = this.editControl.handler.layerOptions.styleMap.styles;
659             styles.select = styles.select_for_canvas;
660         }
661     },
662
663     saveSuccess: function(transport) {
664       // server sends and empty response on success. If we get a response, that
665       // probably means an error or warning has been printed by server.
666       if (!transport.responseJSON && transport.responseText.length) {
667           this.saveFailure(null, 500);
668           return;
669       }
670
671       this.unsavedRoute = null;
672       if (transport.responseJSON && (typeof transport.responseJSON.redirect === "string")) {
673           location = transport.responseJSON.redirect;
674           return;
675       }
676
677         $('path-profile-content').select('img').each(function(img) {
678             var src = img.src;
679             var found = src.match('foo=bar(\\d*)');
680             var num;
681             if (found) {
682                 num = parseInt(found[1], 10);
683                 img.src = src.replace(found[0], 'foo=bar' + (num+1));
684             } else if (src.indexOf('?') === -1) {
685                 img.src = img.src + '?foo=bar0';
686             } else {
687                 img.src = img.src + '&foo=bar0';
688             }
689         });
690
691       this.messenger.setMessage(SyjStrings.saveSuccess, "success");
692       SYJDataUi.viewmode();
693       document.title = $('geom_title').value;
694     },
695
696     saveFailure: function(transport, httpCode) {
697         var message = "";
698         if (typeof httpCode === "undefined") {
699             httpCode = transport? transport.getStatus(): 0;
700         }
701
702         switch (httpCode) {
703             case 0:
704                 message = SyjStrings.notReachedError;
705             break;
706             case 400:
707             case 404:
708                 message = SyjStrings.requestError;
709             break;
710             case 403:
711                 message = "";
712                 SYJLogin.messenger.setMessage(SyjStrings.loginNeeded, "warn");
713                 SYJLogin.modalbox.show();
714                 this.needsFormResubmit = true;
715             break;
716             case 410:
717                 message = SyjStrings.gonePathError;
718             break;
719             case 500:
720                 message = SyjStrings.serverError;
721                 this.needsFormResubmit = true;
722             break;
723             default:
724                 message = SyjStrings.unknownError;
725             break;
726         }
727
728         this.editMode();
729         // is some cases, we let the user resubmit, in some other cases, he
730         // needs to modify the path before submitting again
731         if (this.needsFormResubmit) {
732             SyjSaveUI.enable();
733         }
734
735         this.messenger.setMessage(message, "error");
736     }
737 };
738
739 var SYJModalClass = Class.create({
740     type: "",
741
742     init: function() {
743         this.area = $(this.type + '_area');
744         this.messenger = $(this.type + "_message");
745         this.modalbox = new SimpleBox(this.area, {
746             closeMethods: ["onescapekey", "onouterclick", "onbutton"]
747         });
748
749         var anchor = $(this.type + '_control_anchor');
750         var parent = anchor.up('.menu-item');
751         if (parent) {
752             anchor = parent;
753         }
754         anchor.observe("click", function(evt) {
755             this.modalbox.show();
756             evt.stop();
757         }.bindAsEventListener(this));
758
759         document.observe('simplebox:shown', this.observer.bindAsEventListener(this));
760         document.observe('simplebox:hidden', this.observer.bindAsEventListener(this));
761
762         $(this.type + "form").ajaxize({
763             presubmit: this.presubmit.bind(this),
764             onSuccess: this.success.bind(this),
765             onFailure: this.failure.bind(this)
766         });
767     },
768
769     checkNotEmpty: function(input, message) {
770         if ($(input).value.strip().empty()) {
771             this.messenger.setMessage(message, "warn");
772             $(input).highlight('#F08080').activate();
773             return false;
774         }
775         return true;
776     },
777
778     observer: function(evt) {
779         var simplebox, input;
780
781         if (evt.eventName === "simplebox:shown" && evt.memo.element !== $("termsofusearea")) {
782             simplebox = evt.memo;
783             if (simplebox === this.modalbox) {
784                 input = this.area.select('input[type="text"]')[0];
785                 (function () {
786                     input.activate();
787                 }.defer());
788             } else {
789                 this.modalbox.hide();
790             }
791
792         } else if (evt.eventName === "simplebox:hidden" && evt.memo.element !== $("termsofusearea")) {
793             simplebox = evt.memo;
794             if (simplebox === this.modalbox) {
795                 this.reset();
796             }
797         }
798     },
799
800     failure: function(transport) {
801         var httpCode = 0, message = SyjStrings.unknownError, input; // default message error
802
803         if (transport) {
804             httpCode = transport.getStatus();
805         }
806
807         switch (httpCode) {
808             case 0:
809                 message = SyjStrings.notReachedError;
810             break;
811             case 400:
812             case 404:
813             case 410:
814                 message = SyjStrings.requestError;
815             break;
816             case 500:
817                 message = SyjStrings.serverError;
818             break;
819         }
820
821         this.messenger.setMessage(message, "error");
822         input = this.area.select('input[type="text"]')[0];
823         input.highlight('#F08080').activate();
824     },
825
826     reset: function() {
827         this.messenger.clearMessages();
828         this.area.select('.message').invoke('setMessageStatus', null);
829     }
830 });
831
832 var SYJUserClass = Class.create(SYJModalClass, {
833     type: "user",
834     toubox: null,
835
836     init: function($super) {
837         $super();
838         $("termsofusearea").hide();
839
840         var touevt = (function(evt) {
841             if (evt.type === "keyup" && evt.keyCode !== 32) { // 32 = space
842                 // allow opening box by pressing space
843                 return;
844             }
845             if (!this.toubox) {
846                 this.toubox = new SimpleBox($("termsofusearea"), {
847                     closeMethods: ["onescapekey", "onouterclick", "onbutton"]
848                 });
849             }
850             this.toubox.show();
851             if (!$("termsofuseiframe").getAttribute("src")) {
852                 $("termsofusearea").show();
853                 $("termsofuseiframe").setAttribute("src", evt.target.href);
854             }
855             evt.stop();
856         }).bindAsEventListener(this);
857
858         ["click", "keyup"].each(function (evtName) {
859             $$("#user_termsofuse_anchor, #geom_termsofuse_anchor").invoke('observe', evtName, touevt);
860         })
861
862         $$("#login_area_create > a").invoke('observe', 'click',
863             function(evt) {
864                 this.modalbox.show();
865                 evt.stop();
866             }.bindAsEventListener(this));
867
868         $("user_pseudo-desc").hide();
869         $("user_pseudo").observe('contentchange', function(evt) {
870             var value = evt.target.value;
871             PseudoChecker.reset();
872             if (value && !(value.match(/^[a-zA-Z0-9_.]+$/))) {
873                 $("user_pseudo-desc").show().setMessageStatus("warn");
874             } else {
875                 $("user_pseudo-desc").hide();
876             }
877         }).timedobserve(function() {
878             PseudoChecker.check();
879         });
880
881         $("user_password").observe('contentchange', function(evt) {
882             if (evt.target.value.length < 6) {
883                 $("user_password-desc").setMessageStatus("warn");
884             } else {
885                 $("user_password-desc").setMessageStatus("success");
886             }
887         }.bindAsEventListener(this));
888
889         $('account-create-anchor').insert({after: new Toggler('account-info').element});
890     },
891
892     presubmit: function() {
893         this.messenger.clearMessages();
894         PseudoChecker.reset();
895         if (!(this.checkNotEmpty("user_pseudo", SyjStrings.userEmptyWarn))) {
896             return false;
897         }
898
899         if (!($("user_pseudo").value.match(/^[a-zA-Z0-9_.]+$/))) {
900             $("user_pseudo-desc").show().setMessageStatus("warn");
901             $("user_pseudo").highlight('#F08080').activate();
902             return false;
903         }
904
905         if (PseudoChecker.exists[$("user_pseudo").value]) {
906             PseudoChecker.availableMessage(false);
907             $("user_pseudo").highlight('#F08080').activate();
908             return false;
909         }
910
911         if (!(this.checkNotEmpty("user_password", SyjStrings.passwordEmptyWarn))) {
912             return false;
913         }
914
915         if ($("user_password").value.length < 6) {
916             $("user_password-desc").setMessageStatus("warn");
917             $("user_password").highlight('#F08080').activate();
918             return false;
919         }
920
921         if ($("user_password").value !== $("user_password_confirm").value) {
922             this.messenger.setMessage(SyjStrings.passwordNoMatchWarn, "warn");
923             $("user_password").highlight('#F08080').activate();
924             return false;
925         }
926
927         if (!(this.checkNotEmpty("user_email", SyjStrings.emailEmptyWarn))) {
928             return false;
929         }
930
931         if (!$("user_accept").checked) {
932             this.messenger.setMessage(SyjStrings.acceptTermsofuseWarn, "warn");
933             $("user_accept_container").highlight('#F08080');
934             $("user_accept").activate();
935             return false;
936         }
937
938         this.reset();
939         return true;
940     },
941
942     success: function(transport) {
943         if (!transport.responseJSON ||
944             typeof transport.responseJSON.pseudo !== "string"
945             ) {
946             this.messenger.setMessage(SyjStrings.unknownError, "error");
947             return;
948         }
949
950         LoginMgr.login(transport.responseJSON.pseudo);
951         SYJView.messenger.setMessage(SyjStrings.userSuccess, "success");
952         this.modalbox.hide();
953         if (SYJView.needsFormResubmit) {
954             SYJView.messenger.addMessage(SyjStrings.canResubmit);
955             $("geom_submit").activate();
956         }
957     },
958
959     failure: function($super, transport) {
960         var httpCode = 0, focusInput = null, message = "";
961
962         if (transport) {
963             httpCode = transport.getStatus();
964         }
965
966         focusInput = null;
967         message = "";
968
969         switch (httpCode) {
970             case 400:
971                 if (transport.responseJSON) {
972                     switch (transport.responseJSON.message) {
973                         case "invalidemail":
974                             message = SyjStrings.emailInvalidWarn;
975                             focusInput = $("user_email");
976                         break;
977                         case "uniquepseudo":
978                             PseudoChecker.availableMessage(false);
979                             focusInput = $("user_pseudo");
980                         break;
981                         case "uniqueemail":
982                             message = SyjStrings.uniqueEmailError;
983                             focusInput = $("user_email");
984                         break;
985                     }
986                 }
987             break;
988         }
989
990         if (focusInput) {
991             if (message) {
992                 this.messenger.setMessage(message, "error");
993             }
994             focusInput.highlight('#F08080').activate();
995             return;
996         }
997
998         $super(transport);
999     }
1000 });
1001 var SYJUser = new SYJUserClass();
1002
1003 var SYJLoginClass = Class.create(SYJModalClass, {
1004     type: "login",
1005
1006     init: function($super) {
1007         $super();
1008     },
1009
1010     presubmit: function() {
1011         this.messenger.clearMessages();
1012         if (!(this.checkNotEmpty("login_user", SyjStrings.userEmptyWarn))) {
1013             return false;
1014         }
1015
1016         this.reset();
1017         return true;
1018     },
1019
1020     success: function(transport) {
1021         if (!transport.responseJSON ||
1022             typeof transport.responseJSON.iscreator !== "boolean" ||
1023             typeof transport.responseJSON.pseudo !== "string"
1024             ) {
1025             this.messenger.setMessage(SyjStrings.unknownError, "error");
1026             return;
1027         }
1028         LoginMgr.login(transport.responseJSON.pseudo, transport.responseJSON.iscreator);
1029
1030         SYJView.messenger.setMessage(SyjStrings.loginSuccess, "success");
1031         this.modalbox.hide();
1032         if (SYJView.needsFormResubmit) {
1033             SYJView.messenger.addMessage(SyjStrings.canResubmit);
1034             $("geom_submit").activate();
1035         }
1036     },
1037
1038     failure: function($super, transport) {
1039         var httpCode = 0, focusInput = null, message = "";
1040
1041         if (transport) {
1042             httpCode = transport.getStatus();
1043         }
1044
1045         focusInput = null;
1046         message = "";
1047
1048         switch (httpCode) {
1049             case 403:
1050                 message = SyjStrings.loginFailure;
1051                 focusInput = $("login_user");
1052             break;
1053         }
1054
1055         if (message) {
1056             this.messenger.setMessage(message, "error");
1057             if (focusInput) {
1058                 focusInput.highlight('#F08080').activate();
1059             }
1060             return;
1061         }
1062
1063         $super(transport);
1064     }
1065 });
1066 var SYJLogin = new SYJLoginClass();
1067
1068 var SYJNewpwdClass = Class.create(SYJModalClass, {
1069     type: "newpwd",
1070
1071     presubmit: function() {
1072         if (!(this.checkNotEmpty("newpwd_email", SyjStrings.emailEmptyWarn))) {
1073             return false;
1074         }
1075         this.reset();
1076         return true;
1077     },
1078     success: function(transport) {
1079         SYJView.messenger.setMessage(SyjStrings.newpwdSuccess, "success");
1080         this.modalbox.hide();
1081     }
1082
1083 });
1084 var SYJNewpwd = new SYJNewpwdClass();
1085
1086 var LoginMgr = Object.extend(gLoggedInfo, {
1087     controlsdeck: null,
1088
1089     updateUI: function() {
1090         if (!this.controlsdeck) {
1091             this.controlsdeck = new Deck("login_controls");
1092         }
1093         if (this.logged) {
1094             this.controlsdeck.setIndex(1);
1095             $$(".logged-hide").invoke('hide');
1096             $$(".logged-show").invoke('show');
1097         } else {
1098             this.controlsdeck.setIndex(0);
1099             $$(".logged-hide").invoke('show');
1100             $$(".logged-show").invoke('hide');
1101         }
1102
1103         if ($("edit-btn")) {
1104             if (this.iscreator && SYJView.mode === 'view') {
1105                 $("edit-btn").show();
1106             } else {
1107                 $("edit-btn").hide();
1108             }
1109         }
1110     },
1111
1112     login: function(aPseudo, aIsCreator) {
1113         if (typeof aIsCreator === "boolean") {
1114             this.iscreator = aIsCreator;
1115         }
1116         this.logged = true;
1117         $$('.logged-pseudo').each(function(elt) {
1118             $A(elt.childNodes).filter(function(node) {
1119                 return (node.nodeType === 3 || node.tagName.toLowerCase() === 'br');
1120             }).each(function(node) {
1121                 node.nodeValue = node.nodeValue.replace('%s', aPseudo);
1122             });
1123         });
1124         this.updateUI();
1125     }
1126 });
1127
1128 var PseudoChecker = {
1129     req: null,
1130     exists: {},
1131     currentvalue: null,
1132     messageelt: null,
1133     throbber: null,
1134
1135     message: function(str, status, throbber) {
1136         var row;
1137         if (!this.messageelt) {
1138             row = new Element('tr');
1139             // we can't use row.update('<td></td><td><div></div></td>')
1140             // because gecko would mangle the <td>s
1141             row.insert(new Element('td'))
1142                .insert((new Element('td')).update(new Element('div')));
1143
1144             $("user_pseudo").up('tr').insert({after: row});
1145             this.messageelt = new Element('span');
1146             this.throbber = new Element("img", { src: "icons/throbber.gif"});
1147             row.down('div').insert(this.throbber).insert(this.messageelt);
1148         }
1149         if (throbber) {
1150             this.throbber.show();
1151         } else {
1152             this.throbber.hide();
1153         }
1154         this.messageelt.up().setStyle({visibility: ''});
1155         this.messageelt.className = status;
1156         this.messageelt.update(str);
1157     },
1158
1159     availableMessage: function(available) {
1160         var message = available ? SyjStrings.availablePseudo: SyjStrings.unavailablePseudo,
1161             status = available ? "success": "warn";
1162         this.message(message, status, false);
1163     },
1164
1165     reset: function() {
1166         if (this.req) {
1167             this.req.abort();
1168             this.req = this.currentvalue = null;
1169         }
1170         if (this.messageelt) {
1171             this.messageelt.up().setStyle({visibility: 'hidden'});
1172         }
1173     },
1174
1175     check: function() {
1176         var pseudo = $("user_pseudo").value;
1177
1178         this.reset();
1179
1180         if (!pseudo || !(pseudo.match(/^[a-zA-Z0-9_.]+$/))) {
1181             return;
1182         }
1183
1184         if (typeof this.exists[pseudo] === "boolean") {
1185             this.reset();
1186             this.availableMessage(!this.exists[pseudo]);
1187             return;
1188         }
1189
1190         this.message(SyjStrings.pseudoChecking, "", true);
1191
1192         this.currentvalue = pseudo;
1193         this.req = new Ajax.TimedRequest('userexists/' + encodeURIComponent(pseudo), 20, {
1194             onFailure: this.failure.bind(this),
1195             onSuccess: this.success.bind(this)
1196         });
1197     },
1198
1199     failure: function(transport) {
1200         var httpCode = 0, value = this.currentvalue;
1201
1202         if (transport) {
1203             httpCode = transport.getStatus();
1204         }
1205         this.reset();
1206         if (httpCode === 404) {
1207             this.exists[value] = false;
1208             this.availableMessage(true);
1209         }
1210
1211     },
1212
1213     success: function(transport) {
1214         var httpCode = transport.getStatus(), value = this.currentvalue;
1215         this.reset();
1216         this.exists[value] = true;
1217         this.availableMessage(false);
1218     }
1219 };
1220
1221 var Nominatim = (function() {
1222     var presubmit = function() {
1223         var input = $("nominatim-search");
1224         if (input.value.strip().empty()) {
1225             $("nominatim-message").setMessage(SyjStrings.notEmptyField, "warn");
1226             input.activate();
1227             return false;
1228         }
1229         $("nominatim-suggestions").hide();
1230         $("nominatim-message").hide();
1231         $("nominatim-throbber").show();
1232         return true;
1233     };
1234
1235     var zoomToExtent = function(bounds) { // we must call map.setCenter with forceZoomChange to true. See ol#2798
1236         var center = bounds.getCenterLonLat();
1237         if (this.baseLayer.wrapDateLine) {
1238             var maxExtent = this.getMaxExtent();
1239             bounds = bounds.clone();
1240             while (bounds.right < bounds.left) {
1241                 bounds.right += maxExtent.getWidth();
1242             }
1243             center = bounds.getCenterLonLat().wrapDateLine(maxExtent);
1244         }
1245         this.setCenter(center, this.getZoomForExtent(bounds), false, true);
1246     };
1247
1248     var success = function(transport) {
1249         $("nominatim-throbber").hide();
1250
1251         if (!transport.responseJSON || !transport.responseJSON.length) {
1252             $("nominatim-message").setMessage(SyjStrings.noResult, 'error');
1253             $("nominatim-search").activate();
1254             return;
1255         }
1256
1257         var place = transport.responseJSON[0],
1258             bbox = place.boundingbox;
1259
1260         if (!bbox || bbox.length !== 4) {
1261             $("nominatim-message").setMessage(SyjStrings.requestError, 'error');
1262             return;
1263         }
1264
1265         extent = new OpenLayers.Bounds(bbox[2], bbox[1], bbox[3], bbox[0]).transform(WGS84, Mercator);
1266         zoomToExtent.call(SYJView.map, extent);
1267
1268         $("nominatim-suggestions-list").update();
1269
1270         var clickhandler = function(bbox) {
1271             return function(evt) {
1272                 evt.stop();
1273                 var extent = new OpenLayers.Bounds(bbox[2], bbox[1], bbox[3], bbox[0]).transform(WGS84, Mercator);
1274                 $("nominatim-suggestions-list").select("li").invoke('removeClassName', 'current');
1275                 evt.target.up('li').addClassName('current');
1276                 SYJView.map.zoomToExtent(extent);
1277             };
1278         };
1279
1280         var i;
1281         for (i = 0; i < transport.responseJSON.length; i++) {
1282             var item = transport.responseJSON[i];
1283             if (item.display_name && item.boundingbox && item.boundingbox.length === 4) {
1284                 var li = new Element("li");
1285                 var anchor = new Element("a", {
1286                     href: "",
1287                     className: "nominatim-suggestions-link"
1288                 });
1289
1290                 anchor.observe('click', clickhandler(item.boundingbox));
1291                 Element.text(anchor, item.display_name);
1292
1293                 var icon = new Element("img", {
1294                     className: "nominatim-suggestions-icon",
1295                     src: item.icon || 'icons/world.png'
1296                 });
1297                 li.insert(icon).insert(anchor);
1298                 $("nominatim-suggestions-list").insert(li);
1299                 if ($("nominatim-suggestions-list").childNodes.length >= 6) {
1300                     break;
1301                 }
1302             }
1303         }
1304
1305         if ($("nominatim-suggestions-list").childNodes.length > 1) {
1306             var bottomOffset = $('data_controls').measure('height') + 3;
1307             $("nominatim-suggestions").setStyle({
1308                 bottom: (document.viewport.getHeight() - $('data_controls').cumulativeOffset().top + 3).toString() + 'px'
1309             }).show();
1310             $("nominatim-suggestions-list").select("li:first-child")[0].addClassName('current');
1311         } else {
1312             $("nominatim-suggestions").hide();
1313         }
1314
1315     };
1316
1317     var failure = function(transport) {
1318         $("nominatim-throbber").hide();
1319
1320         var httpCode = 0, message = SyjStrings.unknownError, input; // default message error
1321
1322         if (transport) {
1323             httpCode = transport.getStatus();
1324         }
1325
1326         switch (httpCode) {
1327             case 0:
1328                 message = SyjStrings.notReachedError;
1329             break;
1330             case 400:
1331             case 404:
1332                 message = SyjStrings.requestError;
1333             break;
1334             case 500:
1335                 message = SyjStrings.serverError;
1336             break;
1337         }
1338
1339         $("nominatim-message").setMessage(message, 'error');
1340     };
1341
1342     return {
1343         init: function() {
1344             if (!$("nominatim-form")) {
1345                return;
1346             }
1347             $("nominatim-controls").hide();
1348             $("nominatim-label").observe('click', function(evt) {
1349                 $("nominatim-controls").show();
1350                 $("nominatim-search").activate();
1351                 evt.stop();
1352             });
1353
1354             $("nominatim-form").ajaxize({
1355                 presubmit: presubmit,
1356                 onSuccess: success,
1357                 onFailure: failure
1358               });
1359             new CloseBtn($("nominatim-suggestions"));
1360
1361             $$("#nominatim-message, #nominatim-suggestions, #nominatim-throbber").invoke('hide');
1362         }
1363     };
1364 }());
1365
1366 document.observe("dom:loaded", function() {
1367     SYJLogin.init();
1368     SYJUser.init();
1369     SYJDataUi.viewmode();
1370     SYJView.init();
1371     SYJNewpwd.init();
1372     LoginMgr.updateUI();
1373     Nominatim.init();
1374 });
1375
1376 window.onbeforeunload = function() {
1377     if (SYJView.unsavedRoute) {
1378         return SyjStrings.unsavedConfirmExit;
1379     } else {
1380         return undefined;
1381     }
1382 };