]> dev.renevier.net Git - syj.git/blob - public/js/syj.js
8f5f509020fd0f6251055213aa3d050169f963fe
[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, baseLayer, layerOptions, hidemessenger;
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                 new OpenLayers.Control.Attribution()
291             ],
292             theme: null
293         });
294
295         baseLayer = new OpenLayers.Layer.OSM("OSM", [
296                 'http://a.tile.openstreetmap.org/${z}/${x}/${y}.png',
297                 'http://b.tile.openstreetmap.org/${z}/${x}/${y}.png',
298                 'http://c.tile.openstreetmap.org/${z}/${x}/${y}.png'],
299                 { attribution: SyjStrings.osmAttribution });
300
301         layerOptions = {format:     OpenLayers.Format.WKT,
302                         projection: WGS84,
303                         styleMap:   styleMap.view,
304                         attribution: SyjStrings.geomAttribution };
305
306         this.viewLayer = new OpenLayers.Layer.Vector("View Layer", layerOptions);
307         this.map.addLayers([baseLayer, this.viewLayer]);
308
309         if ($("edit-btn")) {
310             $("edit-btn").observe('click', function() {
311                 $("geom_submit").value = SyjStrings.editAction;
312                 this.messenger.clearMessages();
313                 this.editMode();
314                 this.mode = 'edit';
315             }.bind(this));
316         }
317
318         if ($("create-btn")) {
319             $("create-btn").observe('click', function() {
320                 $("geom_submit").value = SyjStrings.createAction;
321                 this.messenger.clearMessages();
322                 this.editMode();
323                 this.mode = 'create';
324             }.bind(this));
325         }
326
327         if ($("clone-btn")) {
328             $("clone-btn").observe('click', function() {
329                 $("geom_submit").value = SyjStrings.cloneAction;
330                 $("geom_title").value = "";
331                 this.messenger.clearMessages();
332                 this.editMode();
333                 this.mode = 'create';
334             }.bind(this));
335         }
336
337         $("geomform").ajaxize({
338                 presubmit: this.prepareForm.bind(this),
339                 onSuccess: this.saveSuccess.bind(this),
340                 onFailure: this.saveFailure.bind(this)
341                 });
342         SyjSaveUI.init();
343
344         this.messenger = $('message');
345         hidemessenger = this.messenger.empty();
346         new CloseBtn(this.messenger, {
347             style: {
348                 margin: "-1em"
349             }
350         });
351         if (hidemessenger) {
352             this.messenger.hide();
353         }
354
355         if (typeof gInitialGeom !== "undefined" && typeof gInitialGeom.data !== "undefined") {
356             this.viewLayer.addFeatures([this.wkt.read(gInitialGeom.data)]);
357             // XXX: ie has not guessed height of map main div yet during map
358             // initialisation. Now, it will read it correctly.
359             this.map.updateSize();
360             this.map.zoomToExtent(this.viewLayer.getDataExtent());
361         } else {
362             this.initMaPos(gInitialPos);
363         }
364
365         $("map-overlay").hide();
366         $("geom_upload").observe('change', function(evt) {
367             var file = null, reader = null, readerror = null;
368             if (window.FileList && window.FileReader) {
369                 file = evt.target.files[0];
370                 reader = new FileReader();
371                 readerror = function() {
372                     this.messenger.setMessage(SyjStrings.uploadFileError, "warn");
373                 }.bind(this);
374                 reader.onload = function(evt) {
375                     var data = null, results = null, engine = null, vector = null, i = 0, format = null, formats = ['KML', 'GPX', 'GeoJSON'];
376
377                     $("geom_upload_container").removeClassName("disabled");
378                     $("geom_upload").disabled = false;
379                     if (evt.error) {
380                         readerror();
381                         return;
382                     }
383                     data = evt.target.result;
384
385                     for (i = 0; i < formats.length; i++) {
386                         format = formats[i];
387                         engine = new OpenLayers.Format[format]({ internalProjection: Mercator, externalProjection: WGS84 });
388                         try {
389                             results = engine.read(data);
390                         } catch(e) {
391                         }
392                         if (results && results.length) {
393                             break;
394                         }
395                     }
396                     if (!results || !results.length) {
397                         readerror();
398                         return;
399                     }
400
401                     vector = results[0];
402                     if (vector.geometry.CLASS_NAME !== "OpenLayers.Geometry.LineString") {
403                         readerror();
404                         return;
405                     }
406                     // merge linestrings for gpx containting multiple trkseg elements.
407                     if (format === 'GPX') {
408                       for (i = 1; i < results.length; i++) {
409                         vector.geometry.addComponents(results[i].geometry.components);
410                       }
411                     }
412                     this.viewLayer.addFeatures([vector]);
413                     this.map.zoomToExtent(this.viewLayer.getDataExtent());
414
415                     if ($("edit-btn")) {
416                         $("edit-btn").click();
417                     } else if ($("create-btn")) {
418                         $("create-btn").click();
419                     }
420
421                     if (this.editControl.handler.realPoints.length < 2) {
422                         SyjSaveUI.disable();
423                     } else {
424                        SyjSaveUI.enable();
425                     }
426
427                     if (vector.data && vector.data.name) {
428                         $("geom_title").value = vector.data.name;
429                     }
430                 }.bind(this);
431                 $("geom_upload_container").addClassName("disabled");
432                 $("geom_upload").disabled = true;
433                 reader.readAsText(file);
434                 return;
435             }
436             $("map-overlay").show();
437             SyjSaveUI.enable();
438             this.editControl.deactivate();
439         }.bind(this));
440
441         document.observe('simplebox:shown', this.observer.bindAsEventListener(this));
442         SYJPathLength.update();
443     },
444
445     initMaPos: function (aPos) {
446         var extent = null, center = null, zoom = 0;
447
448         if (aPos.hasOwnProperty('lon') && aPos.hasOwnProperty('lat') && aPos.hasOwnProperty('zoom')) {
449             center = new OpenLayers.LonLat(parseFloat(aPos.lon), parseFloat(aPos.lat)).transform(WGS84, Mercator);
450             zoom = parseInt(aPos.zoom, 10);
451         } else if (aPos.hasOwnProperty('minlon') && aPos.hasOwnProperty('minlat')
452                     && aPos.hasOwnProperty('maxlon') && aPos.hasOwnProperty('maxlat')) {
453             extent = new OpenLayers.Bounds(aPos.minlon, aPos.minlat, aPos.maxlon, aPos.maxlat)
454                                          .transform(WGS84, Mercator);
455         } else {
456             extent = new OpenLayers.Bounds(-160, -70, 160, 70).transform(WGS84, Mercator);
457         }
458
459         if (extent) {
460             this.map.zoomToExtent(extent);
461         } else {
462             this.map.setCenter(center, zoom);
463         }
464     },
465
466     observer: function(evt) {
467         if (evt.eventName === "simplebox:shown" && evt.memo.element !== $("termsofusearea")) {
468             this.messenger.clearMessages();
469         }
470     },
471
472     prepareForm: function(form) {
473         if (!LoginMgr.logged && !$("geom_accept").checked) {
474             this.messenger.setMessage(SyjStrings.acceptTermsofuseWarn, "warn");
475             $("geom_accept_container").highlight('#F08080');
476             $("geom_accept").activate();
477             return false;
478         }
479
480         var line, realPoints, idx;
481
482         line = new OpenLayers.Geometry.LineString();
483         realPoints = this.editControl.handler.realPoints;
484         for (idx = 0; idx < realPoints.length; idx++) {
485             line.addComponent(realPoints[idx].geometry.clone());
486         }
487         this.viewLayer.addFeatures(new OpenLayers.Feature.Vector(line));
488
489         this.viewMode();
490
491         if (line.components.length) {
492             $("geom_data").value = this.wkt.write(new OpenLayers.Feature.Vector(line));
493         } else {
494             $("geom_data").value = "";
495         }
496
497         if (this.mode === "edit" && typeof gLoggedInfo.pathid !== "undefined") {
498             $("geomform").setAttribute("action", "path/" + gLoggedInfo.pathid.toString() + '/update');
499         } else {
500             $("geomform").setAttribute("action", "path");
501         }
502         this.needsFormResubmit = false;
503         SyjSaveUI.disable.bind(SyjSaveUI).defer();
504         this.messenger.clearMessages();
505         return true;
506     },
507
508     viewMode: function() {
509         var handler = this.editControl.handler;
510         OpenLayers.Handler.ModifiablePath.prototype.finalize.apply(handler, arguments);
511         // we need to recreate them on next createFeature; otherwise
512         // they'll reference destroyed features
513         delete(handler.handlers.drag);
514         delete(handler.handlers.feature);
515         this.editControl.deactivate();
516     },
517
518     editMode: function() {
519         var components, point0, point, pixels, pixel, idx;
520
521         this.initEditControl();
522
523         this.editControl.activate();
524         if (this.viewLayer.features.length) {
525             components = this.viewLayer.features[0].geometry.components;
526             point0 = components[0];
527             if (point0) {
528                 pixel = this.map.getPixelFromLonLat(new OpenLayers.LonLat(point0.x, point0.y));
529                 this.editControl.handler.createFeature(pixel);
530                 this.editControl.handler.lastUp = pixel;
531                 pixels = [];
532                 for (idx = 1; idx < components.length; idx++) {
533                     point = components[idx];
534                     pixels.push(this.map.getPixelFromLonLat(new OpenLayers.LonLat(point.x, point.y)));
535                 }
536                 this.editControl.handler.addPoints(pixels);
537             }
538             this.unsavedRoute = {
539                 features: this.viewLayer.features.invoke('clone'),
540                 title: $("geom_title").value
541             };
542         }
543
544         this.viewLayer.destroyFeatures();
545
546         SYJDataUi.editmode();
547         if (this.editControl.handler.realPoints && this.editControl.handler.realPoints.length >= 2) {
548             SyjSaveUI.disableSubmit();
549         } else {
550             SyjSaveUI.disable();
551         }
552     },
553
554     initEditControl: function() {
555         var styles;
556
557         if (this.editControl) {
558             return;
559         }
560
561         this.editControl = new OpenLayers.Control.DrawFeature(new OpenLayers.Layer.Vector(), OpenLayers.Handler.SyjModifiablePath, {
562             callbacks: {
563                 modify: function(f, line) {
564                     SYJPathLength.update();
565
566                     var npoints = this.handler.realPoints.length;
567                     if (npoints === 0) {
568                         $("geom_upload_container").show();
569                         SYJView.unsavedRoute = null;
570                     } else {
571                         if (!SYJView.unsavedRoute) {
572                             SYJView.unsavedRoute = {};
573                         }
574                     }
575
576                     if (npoints < 2) {
577                         SyjSaveUI.disable();
578                     } else {
579                         SyjSaveUI.enable();
580                     }
581                 },
582                 create: function(f, line) {
583                     this.messenger.clearMessages();
584                     $("geom_upload_container").hide();
585                 }.bind(this)
586             },
587
588             handlerOptions: {
589                 layerOptions: {
590                     styleMap: styleMap.edit
591                 }
592             }
593         });
594         this.map.addControl(this.editControl);
595         if (this.editControl.layer.renderer instanceof OpenLayers.Renderer.Canvas) {
596             // using externalGraphic with canvas renderer is definitively too buggy
597             styles = this.editControl.handler.layerOptions.styleMap.styles;
598             styles.select = styles.select_for_canvas;
599         }
600     },
601
602     saveSuccess: function(transport) {
603       // server sends and empty response on success. If we get a response, that
604       // probably means an error or warning has been printed by server.
605       if (!transport.responseJSON && transport.responseText.length) {
606           this.saveFailure(null, 500);
607           return;
608       }
609
610       this.unsavedRoute = null;
611       if (transport.responseJSON && (typeof transport.responseJSON.redirect === "string")) {
612           location = transport.responseJSON.redirect;
613           return;
614       }
615
616       this.messenger.setMessage(SyjStrings.saveSuccess, "success");
617       SYJDataUi.viewmode();
618       document.title = $('geom_title').value;
619     },
620
621     saveFailure: function(transport, httpCode) {
622         var message = "";
623         if (typeof httpCode === "undefined") {
624             httpCode = transport? transport.getStatus(): 0;
625         }
626
627         switch (httpCode) {
628             case 0:
629                 message = SyjStrings.notReachedError;
630             break;
631             case 400:
632             case 404:
633                 message = SyjStrings.requestError;
634             break;
635             case 403:
636                 message = "";
637                 SYJLogin.messenger.setMessage(SyjStrings.loginNeeded, "warn");
638                 SYJLogin.modalbox.show();
639                 this.needsFormResubmit = true;
640             break;
641             case 410:
642                 message = SyjStrings.gonePathError;
643             break;
644             case 500:
645                 message = SyjStrings.serverError;
646                 this.needsFormResubmit = true;
647             break;
648             default:
649                 message = SyjStrings.unknownError;
650             break;
651         }
652
653         this.editMode();
654         // is some cases, we let the user resubmit, in some other cases, he
655         // needs to modify the path before submitting again
656         if (this.needsFormResubmit) {
657             SyjSaveUI.enable();
658         }
659
660         this.messenger.setMessage(message, "error");
661     }
662 };
663
664 var SYJModalClass = Class.create({
665     type: "",
666
667     init: function() {
668         this.area = $(this.type + '_area');
669         this.messenger = $(this.type + "_message");
670         this.modalbox = new SimpleBox(this.area, {
671             closeMethods: ["onescapekey", "onouterclick", "onbutton"]
672         });
673
674         var anchor = $(this.type + '_control_anchor');
675         var parent = anchor.up('.menu-item');
676         if (parent) {
677             anchor = parent;
678         }
679         anchor.observe("click", function(evt) {
680             this.modalbox.show();
681             evt.stop();
682         }.bindAsEventListener(this));
683
684         document.observe('simplebox:shown', this.observer.bindAsEventListener(this));
685         document.observe('simplebox:hidden', this.observer.bindAsEventListener(this));
686
687         $(this.type + "form").ajaxize({
688             presubmit: this.presubmit.bind(this),
689             onSuccess: this.success.bind(this),
690             onFailure: this.failure.bind(this)
691         });
692     },
693
694     checkNotEmpty: function(input, message) {
695         if ($(input).value.strip().empty()) {
696             this.messenger.setMessage(message, "warn");
697             $(input).highlight('#F08080').activate();
698             return false;
699         }
700         return true;
701     },
702
703     observer: function(evt) {
704         var simplebox, input;
705
706         if (evt.eventName === "simplebox:shown" && evt.memo.element !== $("termsofusearea")) {
707             simplebox = evt.memo;
708             if (simplebox === this.modalbox) {
709                 input = this.area.select('input[type="text"]')[0];
710                 (function () {
711                     input.activate();
712                 }.defer());
713             } else {
714                 this.modalbox.hide();
715             }
716
717         } else if (evt.eventName === "simplebox:hidden" && evt.memo.element !== $("termsofusearea")) {
718             simplebox = evt.memo;
719             if (simplebox === this.modalbox) {
720                 this.reset();
721             }
722         }
723     },
724
725     failure: function(transport) {
726         var httpCode = 0, message = SyjStrings.unknownError, input; // default message error
727
728         if (transport) {
729             httpCode = transport.getStatus();
730         }
731
732         switch (httpCode) {
733             case 0:
734                 message = SyjStrings.notReachedError;
735             break;
736             case 400:
737             case 404:
738             case 410:
739                 message = SyjStrings.requestError;
740             break;
741             case 500:
742                 message = SyjStrings.serverError;
743             break;
744         }
745
746         this.messenger.setMessage(message, "error");
747         input = this.area.select('input[type="text"]')[0];
748         input.highlight('#F08080').activate();
749     },
750
751     reset: function() {
752         this.messenger.clearMessages();
753         this.area.select('.message').invoke('setMessageStatus', null);
754     }
755 });
756
757 var SYJUserClass = Class.create(SYJModalClass, {
758     type: "user",
759     toubox: null,
760
761     init: function($super) {
762         $super();
763         $("termsofusearea").hide();
764
765         var touevt = (function(evt) {
766             if (evt.type === "keyup" && evt.keyCode !== 32) { // 32 = space
767                 // allow opening box by pressing space
768                 return;
769             }
770             if (!this.toubox) {
771                 this.toubox = new SimpleBox($("termsofusearea"), {
772                     closeMethods: ["onescapekey", "onouterclick", "onbutton"]
773                 });
774             }
775             this.toubox.show();
776             if (!$("termsofuseiframe").getAttribute("src")) {
777                 $("termsofusearea").show();
778                 $("termsofuseiframe").setAttribute("src", evt.target.href);
779             }
780             evt.stop();
781         }).bindAsEventListener(this);
782
783         ["click", "keyup"].each(function (evtName) {
784             $$("#user_termsofuse_anchor, #geom_termsofuse_anchor").invoke('observe', evtName, touevt);
785         })
786
787         $$("#login_area_create > a").invoke('observe', 'click',
788             function(evt) {
789                 this.modalbox.show();
790                 evt.stop();
791             }.bindAsEventListener(this));
792
793         $("user_pseudo-desc").hide();
794         $("user_pseudo").observe('contentchange', function(evt) {
795             var value = evt.target.value;
796             PseudoChecker.reset();
797             if (value && !(value.match(/^[a-zA-Z0-9_.]+$/))) {
798                 $("user_pseudo-desc").show().setMessageStatus("warn");
799             } else {
800                 $("user_pseudo-desc").hide();
801             }
802         }).timedobserve(function() {
803             PseudoChecker.check();
804         });
805
806         $("user_password").observe('contentchange', function(evt) {
807             if (evt.target.value.length < 6) {
808                 $("user_password-desc").setMessageStatus("warn");
809             } else {
810                 $("user_password-desc").setMessageStatus("success");
811             }
812         }.bindAsEventListener(this));
813
814         $('account-create-anchor').insert({after: new Toggler('account-info').element});
815     },
816
817     presubmit: function() {
818         this.messenger.clearMessages();
819         PseudoChecker.reset();
820         if (!(this.checkNotEmpty("user_pseudo", SyjStrings.userEmptyWarn))) {
821             return false;
822         }
823
824         if (!($("user_pseudo").value.match(/^[a-zA-Z0-9_.]+$/))) {
825             $("user_pseudo-desc").show().setMessageStatus("warn");
826             $("user_pseudo").highlight('#F08080').activate();
827             return false;
828         }
829
830         if (PseudoChecker.exists[$("user_pseudo").value]) {
831             PseudoChecker.availableMessage(false);
832             $("user_pseudo").highlight('#F08080').activate();
833             return false;
834         }
835
836         if (!(this.checkNotEmpty("user_password", SyjStrings.passwordEmptyWarn))) {
837             return false;
838         }
839
840         if ($("user_password").value.length < 6) {
841             $("user_password-desc").setMessageStatus("warn");
842             $("user_password").highlight('#F08080').activate();
843             return false;
844         }
845
846         if ($("user_password").value !== $("user_password_confirm").value) {
847             this.messenger.setMessage(SyjStrings.passwordNoMatchWarn, "warn");
848             $("user_password").highlight('#F08080').activate();
849             return false;
850         }
851
852         if (!(this.checkNotEmpty("user_email", SyjStrings.emailEmptyWarn))) {
853             return false;
854         }
855
856         if (!$("user_accept").checked) {
857             this.messenger.setMessage(SyjStrings.acceptTermsofuseWarn, "warn");
858             $("user_accept_container").highlight('#F08080');
859             $("user_accept").activate();
860             return false;
861         }
862
863         this.reset();
864         return true;
865     },
866
867     success: function(transport) {
868         if (!transport.responseJSON ||
869             typeof transport.responseJSON.pseudo !== "string"
870             ) {
871             this.messenger.setMessage(SyjStrings.unknownError, "error");
872             return;
873         }
874
875         LoginMgr.login(transport.responseJSON.pseudo);
876         SYJView.messenger.setMessage(SyjStrings.userSuccess, "success");
877         this.modalbox.hide();
878         if (SYJView.needsFormResubmit) {
879             SYJView.messenger.addMessage(SyjStrings.canResubmit);
880             $("geom_submit").activate();
881         }
882     },
883
884     failure: function($super, transport) {
885         var httpCode = 0, focusInput = null, message = "";
886
887         if (transport) {
888             httpCode = transport.getStatus();
889         }
890
891         focusInput = null;
892         message = "";
893
894         switch (httpCode) {
895             case 400:
896                 if (transport.responseJSON) {
897                     switch (transport.responseJSON.message) {
898                         case "invalidemail":
899                             message = SyjStrings.emailInvalidWarn;
900                             focusInput = $("user_email");
901                         break;
902                         case "uniquepseudo":
903                             PseudoChecker.availableMessage(false);
904                             focusInput = $("user_pseudo");
905                         break;
906                         case "uniqueemail":
907                             message = SyjStrings.uniqueEmailError;
908                             focusInput = $("user_email");
909                         break;
910                     }
911                 }
912             break;
913         }
914
915         if (focusInput) {
916             if (message) {
917                 this.messenger.setMessage(message, "error");
918             }
919             focusInput.highlight('#F08080').activate();
920             return;
921         }
922
923         $super(transport);
924     }
925 });
926 var SYJUser = new SYJUserClass();
927
928 var SYJLoginClass = Class.create(SYJModalClass, {
929     type: "login",
930
931     init: function($super) {
932         $super();
933     },
934
935     presubmit: function() {
936         this.messenger.clearMessages();
937         if (!(this.checkNotEmpty("login_user", SyjStrings.userEmptyWarn))) {
938             return false;
939         }
940
941         this.reset();
942         return true;
943     },
944
945     success: function(transport) {
946         if (!transport.responseJSON ||
947             typeof transport.responseJSON.iscreator !== "boolean" ||
948             typeof transport.responseJSON.pseudo !== "string"
949             ) {
950             this.messenger.setMessage(SyjStrings.unknownError, "error");
951             return;
952         }
953         LoginMgr.login(transport.responseJSON.pseudo, transport.responseJSON.iscreator);
954
955         SYJView.messenger.setMessage(SyjStrings.loginSuccess, "success");
956         this.modalbox.hide();
957         if (SYJView.needsFormResubmit) {
958             SYJView.messenger.addMessage(SyjStrings.canResubmit);
959             $("geom_submit").activate();
960         }
961     },
962
963     failure: function($super, transport) {
964         var httpCode = 0, focusInput = null, message = "";
965
966         if (transport) {
967             httpCode = transport.getStatus();
968         }
969
970         focusInput = null;
971         message = "";
972
973         switch (httpCode) {
974             case 403:
975                 message = SyjStrings.loginFailure;
976                 focusInput = $("login_user");
977             break;
978         }
979
980         if (message) {
981             this.messenger.setMessage(message, "error");
982             if (focusInput) {
983                 focusInput.highlight('#F08080').activate();
984             }
985             return;
986         }
987
988         $super(transport);
989     }
990 });
991 var SYJLogin = new SYJLoginClass();
992
993 var SYJNewpwdClass = Class.create(SYJModalClass, {
994     type: "newpwd",
995
996     presubmit: function() {
997         if (!(this.checkNotEmpty("newpwd_email", SyjStrings.emailEmptyWarn))) {
998             return false;
999         }
1000         this.reset();
1001         return true;
1002     },
1003     success: function(transport) {
1004         SYJView.messenger.setMessage(SyjStrings.newpwdSuccess, "success");
1005         this.modalbox.hide();
1006     }
1007
1008 });
1009 var SYJNewpwd = new SYJNewpwdClass();
1010
1011 var LoginMgr = Object.extend(gLoggedInfo, {
1012     controlsdeck: null,
1013
1014     updateUI: function() {
1015         if (!this.controlsdeck) {
1016             this.controlsdeck = new Deck("login_controls");
1017         }
1018         if (this.logged) {
1019             this.controlsdeck.setIndex(1);
1020             $$(".logged-hide").invoke('hide');
1021             $$(".logged-show").invoke('show');
1022         } else {
1023             this.controlsdeck.setIndex(0);
1024             $$(".logged-hide").invoke('show');
1025             $$(".logged-show").invoke('hide');
1026         }
1027
1028         if ($("edit-btn")) {
1029             if (this.iscreator && SYJView.mode === 'view') {
1030                 $("edit-btn").show();
1031             } else {
1032                 $("edit-btn").hide();
1033             }
1034         }
1035     },
1036
1037     login: function(aPseudo, aIsCreator) {
1038         if (typeof aIsCreator === "boolean") {
1039             this.iscreator = aIsCreator;
1040         }
1041         this.logged = true;
1042         $$('.logged-pseudo').each(function(elt) {
1043             $A(elt.childNodes).filter(function(node) {
1044                 return (node.nodeType === 3 || node.tagName.toLowerCase() === 'br');
1045             }).each(function(node) {
1046                 node.nodeValue = node.nodeValue.replace('%s', aPseudo);
1047             });
1048         });
1049         this.updateUI();
1050     }
1051 });
1052
1053 var PseudoChecker = {
1054     req: null,
1055     exists: {},
1056     currentvalue: null,
1057     messageelt: null,
1058     throbber: null,
1059
1060     message: function(str, status, throbber) {
1061         var row;
1062         if (!this.messageelt) {
1063             row = new Element('tr');
1064             // we can't use row.update('<td></td><td><div></div></td>')
1065             // because gecko would mangle the <td>s
1066             row.insert(new Element('td'))
1067                .insert((new Element('td')).update(new Element('div')));
1068
1069             $("user_pseudo").up('tr').insert({after: row});
1070             this.messageelt = new Element('span');
1071             this.throbber = new Element("img", { src: "icons/throbber.gif"});
1072             row.down('div').insert(this.throbber).insert(this.messageelt);
1073         }
1074         if (throbber) {
1075             this.throbber.show();
1076         } else {
1077             this.throbber.hide();
1078         }
1079         this.messageelt.up().setStyle({visibility: ''});
1080         this.messageelt.className = status;
1081         this.messageelt.update(str);
1082     },
1083
1084     availableMessage: function(available) {
1085         var message = available ? SyjStrings.availablePseudo: SyjStrings.unavailablePseudo,
1086             status = available ? "success": "warn";
1087         this.message(message, status, false);
1088     },
1089
1090     reset: function() {
1091         if (this.req) {
1092             this.req.abort();
1093             this.req = this.currentvalue = null;
1094         }
1095         if (this.messageelt) {
1096             this.messageelt.up().setStyle({visibility: 'hidden'});
1097         }
1098     },
1099
1100     check: function() {
1101         var pseudo = $("user_pseudo").value;
1102
1103         this.reset();
1104
1105         if (!pseudo || !(pseudo.match(/^[a-zA-Z0-9_.]+$/))) {
1106             return;
1107         }
1108
1109         if (typeof this.exists[pseudo] === "boolean") {
1110             this.reset();
1111             this.availableMessage(!this.exists[pseudo]);
1112             return;
1113         }
1114
1115         this.message(SyjStrings.pseudoChecking, "", true);
1116
1117         this.currentvalue = pseudo;
1118         this.req = new Ajax.TimedRequest('userexists/' + encodeURIComponent(pseudo), 20, {
1119             onFailure: this.failure.bind(this),
1120             onSuccess: this.success.bind(this)
1121         });
1122     },
1123
1124     failure: function(transport) {
1125         var httpCode = 0, value = this.currentvalue;
1126
1127         if (transport) {
1128             httpCode = transport.getStatus();
1129         }
1130         this.reset();
1131         if (httpCode === 404) {
1132             this.exists[value] = false;
1133             this.availableMessage(true);
1134         }
1135
1136     },
1137
1138     success: function(transport) {
1139         var httpCode = transport.getStatus(), value = this.currentvalue;
1140         this.reset();
1141         this.exists[value] = true;
1142         this.availableMessage(false);
1143     }
1144 };
1145
1146 var Nominatim = (function() {
1147     var presubmit = function() {
1148         var input = $("nominatim-search");
1149         if (input.value.strip().empty()) {
1150             $("nominatim-message").setMessage(SyjStrings.notEmptyField, "warn");
1151             input.activate();
1152             return false;
1153         }
1154         $("nominatim-suggestions").hide();
1155         $("nominatim-message").hide();
1156         $("nominatim-throbber").show();
1157         return true;
1158     };
1159
1160     var zoomToExtent = function(bounds) { // we must call map.setCenter with forceZoomChange to true. See ol#2798
1161         var center = bounds.getCenterLonLat();
1162         if (this.baseLayer.wrapDateLine) {
1163             var maxExtent = this.getMaxExtent();
1164             bounds = bounds.clone();
1165             while (bounds.right < bounds.left) {
1166                 bounds.right += maxExtent.getWidth();
1167             }
1168             center = bounds.getCenterLonLat().wrapDateLine(maxExtent);
1169         }
1170         this.setCenter(center, this.getZoomForExtent(bounds), false, true);
1171     };
1172
1173     var success = function(transport) {
1174         $("nominatim-throbber").hide();
1175
1176         if (!transport.responseJSON || !transport.responseJSON.length) {
1177             $("nominatim-message").setMessage(SyjStrings.noResult, 'error');
1178             $("nominatim-search").activate();
1179             return;
1180         }
1181
1182         var place = transport.responseJSON[0],
1183             bbox = place.boundingbox;
1184
1185         if (!bbox || bbox.length !== 4) {
1186             $("nominatim-message").setMessage(SyjStrings.requestError, 'error');
1187             return;
1188         }
1189
1190         extent = new OpenLayers.Bounds(bbox[2], bbox[1], bbox[3], bbox[0]).transform(WGS84, Mercator);
1191         zoomToExtent.call(SYJView.map, extent);
1192
1193         $("nominatim-suggestions-list").update();
1194
1195         var clickhandler = function(bbox) {
1196             return function(evt) {
1197                 evt.stop();
1198                 var extent = new OpenLayers.Bounds(bbox[2], bbox[1], bbox[3], bbox[0]).transform(WGS84, Mercator);
1199                 $("nominatim-suggestions-list").select("li").invoke('removeClassName', 'current');
1200                 evt.target.up('li').addClassName('current');
1201                 SYJView.map.zoomToExtent(extent);
1202             };
1203         };
1204
1205         var i;
1206         for (i = 0; i < transport.responseJSON.length; i++) {
1207             var item = transport.responseJSON[i];
1208             if (item.display_name && item.boundingbox && item.boundingbox.length === 4) {
1209                 var li = new Element("li");
1210                 var anchor = new Element("a", {
1211                     href: "",
1212                     className: "nominatim-suggestions-link"
1213                 });
1214
1215                 anchor.observe('click', clickhandler(item.boundingbox));
1216                 Element.text(anchor, item.display_name);
1217
1218                 var icon = new Element("img", {
1219                     className: "nominatim-suggestions-icon",
1220                     src: item.icon || 'icons/world.png'
1221                 });
1222                 li.insert(icon).insert(anchor);
1223                 $("nominatim-suggestions-list").insert(li);
1224                 if ($("nominatim-suggestions-list").childNodes.length >= 6) {
1225                     break;
1226                 }
1227             }
1228         }
1229
1230         if ($("nominatim-suggestions-list").childNodes.length > 1) {
1231             var bottomOffset = $('data_controls').measure('height') + 3;
1232             $("nominatim-suggestions").setStyle({
1233                 bottom: (document.viewport.getHeight() - $('data_controls').cumulativeOffset().top + 3).toString() + 'px'
1234             }).show();
1235             $("nominatim-suggestions-list").select("li:first-child")[0].addClassName('current');
1236         } else {
1237             $("nominatim-suggestions").hide();
1238         }
1239
1240     };
1241
1242     var failure = function(transport) {
1243         $("nominatim-throbber").hide();
1244
1245         var httpCode = 0, message = SyjStrings.unknownError, input; // default message error
1246
1247         if (transport) {
1248             httpCode = transport.getStatus();
1249         }
1250
1251         switch (httpCode) {
1252             case 0:
1253                 message = SyjStrings.notReachedError;
1254             break;
1255             case 400:
1256             case 404:
1257                 message = SyjStrings.requestError;
1258             break;
1259             case 500:
1260                 message = SyjStrings.serverError;
1261             break;
1262         }
1263
1264         $("nominatim-message").setMessage(message, 'error');
1265     };
1266
1267     return {
1268         init: function() {
1269             if (!$("nominatim-form")) {
1270                return;
1271             }
1272             $("nominatim-controls").hide();
1273             $("nominatim-label").observe('click', function(evt) {
1274                 $("nominatim-controls").show();
1275                 $("nominatim-search").activate();
1276                 evt.stop();
1277             });
1278
1279             $("nominatim-form").ajaxize({
1280                 presubmit: presubmit,
1281                 onSuccess: success,
1282                 onFailure: failure
1283               });
1284             new CloseBtn($("nominatim-suggestions"));
1285
1286             $$("#nominatim-message, #nominatim-suggestions, #nominatim-throbber").invoke('hide');
1287         }
1288     };
1289 }());
1290
1291 document.observe("dom:loaded", function() {
1292     SYJLogin.init();
1293     SYJUser.init();
1294     SYJDataUi.viewmode();
1295     SYJView.init();
1296     SYJNewpwd.init();
1297     LoginMgr.updateUI();
1298     Nominatim.init();
1299 });
1300
1301 window.onbeforeunload = function() {
1302     if (SYJView.unsavedRoute) {
1303         return SyjStrings.unsavedConfirmExit;
1304     } else {
1305         return undefined;
1306     }
1307 };