]> dev.renevier.net Git - syj.git/blob - public/js/syj.js
8c48c99e980bc844773f70dbc6af9a8f9d72b16e
[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       this.messenger.setMessage(SyjStrings.saveSuccess, "success");
678       SYJDataUi.viewmode();
679       document.title = $('geom_title').value;
680     },
681
682     saveFailure: function(transport, httpCode) {
683         var message = "";
684         if (typeof httpCode === "undefined") {
685             httpCode = transport? transport.getStatus(): 0;
686         }
687
688         switch (httpCode) {
689             case 0:
690                 message = SyjStrings.notReachedError;
691             break;
692             case 400:
693             case 404:
694                 message = SyjStrings.requestError;
695             break;
696             case 403:
697                 message = "";
698                 SYJLogin.messenger.setMessage(SyjStrings.loginNeeded, "warn");
699                 SYJLogin.modalbox.show();
700                 this.needsFormResubmit = true;
701             break;
702             case 410:
703                 message = SyjStrings.gonePathError;
704             break;
705             case 500:
706                 message = SyjStrings.serverError;
707                 this.needsFormResubmit = true;
708             break;
709             default:
710                 message = SyjStrings.unknownError;
711             break;
712         }
713
714         this.editMode();
715         // is some cases, we let the user resubmit, in some other cases, he
716         // needs to modify the path before submitting again
717         if (this.needsFormResubmit) {
718             SyjSaveUI.enable();
719         }
720
721         this.messenger.setMessage(message, "error");
722     }
723 };
724
725 var SYJModalClass = Class.create({
726     type: "",
727
728     init: function() {
729         this.area = $(this.type + '_area');
730         this.messenger = $(this.type + "_message");
731         this.modalbox = new SimpleBox(this.area, {
732             closeMethods: ["onescapekey", "onouterclick", "onbutton"]
733         });
734
735         var anchor = $(this.type + '_control_anchor');
736         var parent = anchor.up('.menu-item');
737         if (parent) {
738             anchor = parent;
739         }
740         anchor.observe("click", function(evt) {
741             this.modalbox.show();
742             evt.stop();
743         }.bindAsEventListener(this));
744
745         document.observe('simplebox:shown', this.observer.bindAsEventListener(this));
746         document.observe('simplebox:hidden', this.observer.bindAsEventListener(this));
747
748         $(this.type + "form").ajaxize({
749             presubmit: this.presubmit.bind(this),
750             onSuccess: this.success.bind(this),
751             onFailure: this.failure.bind(this)
752         });
753     },
754
755     checkNotEmpty: function(input, message) {
756         if ($(input).value.strip().empty()) {
757             this.messenger.setMessage(message, "warn");
758             $(input).highlight('#F08080').activate();
759             return false;
760         }
761         return true;
762     },
763
764     observer: function(evt) {
765         var simplebox, input;
766
767         if (evt.eventName === "simplebox:shown" && evt.memo.element !== $("termsofusearea")) {
768             simplebox = evt.memo;
769             if (simplebox === this.modalbox) {
770                 input = this.area.select('input[type="text"]')[0];
771                 (function () {
772                     input.activate();
773                 }.defer());
774             } else {
775                 this.modalbox.hide();
776             }
777
778         } else if (evt.eventName === "simplebox:hidden" && evt.memo.element !== $("termsofusearea")) {
779             simplebox = evt.memo;
780             if (simplebox === this.modalbox) {
781                 this.reset();
782             }
783         }
784     },
785
786     failure: function(transport) {
787         var httpCode = 0, message = SyjStrings.unknownError, input; // default message error
788
789         if (transport) {
790             httpCode = transport.getStatus();
791         }
792
793         switch (httpCode) {
794             case 0:
795                 message = SyjStrings.notReachedError;
796             break;
797             case 400:
798             case 404:
799             case 410:
800                 message = SyjStrings.requestError;
801             break;
802             case 500:
803                 message = SyjStrings.serverError;
804             break;
805         }
806
807         this.messenger.setMessage(message, "error");
808         input = this.area.select('input[type="text"]')[0];
809         input.highlight('#F08080').activate();
810     },
811
812     reset: function() {
813         this.messenger.clearMessages();
814         this.area.select('.message').invoke('setMessageStatus', null);
815     }
816 });
817
818 var SYJUserClass = Class.create(SYJModalClass, {
819     type: "user",
820     toubox: null,
821
822     init: function($super) {
823         $super();
824         $("termsofusearea").hide();
825
826         var touevt = (function(evt) {
827             if (evt.type === "keyup" && evt.keyCode !== 32) { // 32 = space
828                 // allow opening box by pressing space
829                 return;
830             }
831             if (!this.toubox) {
832                 this.toubox = new SimpleBox($("termsofusearea"), {
833                     closeMethods: ["onescapekey", "onouterclick", "onbutton"]
834                 });
835             }
836             this.toubox.show();
837             if (!$("termsofuseiframe").getAttribute("src")) {
838                 $("termsofusearea").show();
839                 $("termsofuseiframe").setAttribute("src", evt.target.href);
840             }
841             evt.stop();
842         }).bindAsEventListener(this);
843
844         ["click", "keyup"].each(function (evtName) {
845             $$("#user_termsofuse_anchor, #geom_termsofuse_anchor").invoke('observe', evtName, touevt);
846         })
847
848         $$("#login_area_create > a").invoke('observe', 'click',
849             function(evt) {
850                 this.modalbox.show();
851                 evt.stop();
852             }.bindAsEventListener(this));
853
854         $("user_pseudo-desc").hide();
855         $("user_pseudo").observe('contentchange', function(evt) {
856             var value = evt.target.value;
857             PseudoChecker.reset();
858             if (value && !(value.match(/^[a-zA-Z0-9_.]+$/))) {
859                 $("user_pseudo-desc").show().setMessageStatus("warn");
860             } else {
861                 $("user_pseudo-desc").hide();
862             }
863         }).timedobserve(function() {
864             PseudoChecker.check();
865         });
866
867         $("user_password").observe('contentchange', function(evt) {
868             if (evt.target.value.length < 6) {
869                 $("user_password-desc").setMessageStatus("warn");
870             } else {
871                 $("user_password-desc").setMessageStatus("success");
872             }
873         }.bindAsEventListener(this));
874
875         $('account-create-anchor').insert({after: new Toggler('account-info').element});
876     },
877
878     presubmit: function() {
879         this.messenger.clearMessages();
880         PseudoChecker.reset();
881         if (!(this.checkNotEmpty("user_pseudo", SyjStrings.userEmptyWarn))) {
882             return false;
883         }
884
885         if (!($("user_pseudo").value.match(/^[a-zA-Z0-9_.]+$/))) {
886             $("user_pseudo-desc").show().setMessageStatus("warn");
887             $("user_pseudo").highlight('#F08080').activate();
888             return false;
889         }
890
891         if (PseudoChecker.exists[$("user_pseudo").value]) {
892             PseudoChecker.availableMessage(false);
893             $("user_pseudo").highlight('#F08080').activate();
894             return false;
895         }
896
897         if (!(this.checkNotEmpty("user_password", SyjStrings.passwordEmptyWarn))) {
898             return false;
899         }
900
901         if ($("user_password").value.length < 6) {
902             $("user_password-desc").setMessageStatus("warn");
903             $("user_password").highlight('#F08080').activate();
904             return false;
905         }
906
907         if ($("user_password").value !== $("user_password_confirm").value) {
908             this.messenger.setMessage(SyjStrings.passwordNoMatchWarn, "warn");
909             $("user_password").highlight('#F08080').activate();
910             return false;
911         }
912
913         if (!(this.checkNotEmpty("user_email", SyjStrings.emailEmptyWarn))) {
914             return false;
915         }
916
917         if (!$("user_accept").checked) {
918             this.messenger.setMessage(SyjStrings.acceptTermsofuseWarn, "warn");
919             $("user_accept_container").highlight('#F08080');
920             $("user_accept").activate();
921             return false;
922         }
923
924         this.reset();
925         return true;
926     },
927
928     success: function(transport) {
929         if (!transport.responseJSON ||
930             typeof transport.responseJSON.pseudo !== "string"
931             ) {
932             this.messenger.setMessage(SyjStrings.unknownError, "error");
933             return;
934         }
935
936         LoginMgr.login(transport.responseJSON.pseudo);
937         SYJView.messenger.setMessage(SyjStrings.userSuccess, "success");
938         this.modalbox.hide();
939         if (SYJView.needsFormResubmit) {
940             SYJView.messenger.addMessage(SyjStrings.canResubmit);
941             $("geom_submit").activate();
942         }
943     },
944
945     failure: function($super, transport) {
946         var httpCode = 0, focusInput = null, message = "";
947
948         if (transport) {
949             httpCode = transport.getStatus();
950         }
951
952         focusInput = null;
953         message = "";
954
955         switch (httpCode) {
956             case 400:
957                 if (transport.responseJSON) {
958                     switch (transport.responseJSON.message) {
959                         case "invalidemail":
960                             message = SyjStrings.emailInvalidWarn;
961                             focusInput = $("user_email");
962                         break;
963                         case "uniquepseudo":
964                             PseudoChecker.availableMessage(false);
965                             focusInput = $("user_pseudo");
966                         break;
967                         case "uniqueemail":
968                             message = SyjStrings.uniqueEmailError;
969                             focusInput = $("user_email");
970                         break;
971                     }
972                 }
973             break;
974         }
975
976         if (focusInput) {
977             if (message) {
978                 this.messenger.setMessage(message, "error");
979             }
980             focusInput.highlight('#F08080').activate();
981             return;
982         }
983
984         $super(transport);
985     }
986 });
987 var SYJUser = new SYJUserClass();
988
989 var SYJLoginClass = Class.create(SYJModalClass, {
990     type: "login",
991
992     init: function($super) {
993         $super();
994     },
995
996     presubmit: function() {
997         this.messenger.clearMessages();
998         if (!(this.checkNotEmpty("login_user", SyjStrings.userEmptyWarn))) {
999             return false;
1000         }
1001
1002         this.reset();
1003         return true;
1004     },
1005
1006     success: function(transport) {
1007         if (!transport.responseJSON ||
1008             typeof transport.responseJSON.iscreator !== "boolean" ||
1009             typeof transport.responseJSON.pseudo !== "string"
1010             ) {
1011             this.messenger.setMessage(SyjStrings.unknownError, "error");
1012             return;
1013         }
1014         LoginMgr.login(transport.responseJSON.pseudo, transport.responseJSON.iscreator);
1015
1016         SYJView.messenger.setMessage(SyjStrings.loginSuccess, "success");
1017         this.modalbox.hide();
1018         if (SYJView.needsFormResubmit) {
1019             SYJView.messenger.addMessage(SyjStrings.canResubmit);
1020             $("geom_submit").activate();
1021         }
1022     },
1023
1024     failure: function($super, transport) {
1025         var httpCode = 0, focusInput = null, message = "";
1026
1027         if (transport) {
1028             httpCode = transport.getStatus();
1029         }
1030
1031         focusInput = null;
1032         message = "";
1033
1034         switch (httpCode) {
1035             case 403:
1036                 message = SyjStrings.loginFailure;
1037                 focusInput = $("login_user");
1038             break;
1039         }
1040
1041         if (message) {
1042             this.messenger.setMessage(message, "error");
1043             if (focusInput) {
1044                 focusInput.highlight('#F08080').activate();
1045             }
1046             return;
1047         }
1048
1049         $super(transport);
1050     }
1051 });
1052 var SYJLogin = new SYJLoginClass();
1053
1054 var SYJNewpwdClass = Class.create(SYJModalClass, {
1055     type: "newpwd",
1056
1057     presubmit: function() {
1058         if (!(this.checkNotEmpty("newpwd_email", SyjStrings.emailEmptyWarn))) {
1059             return false;
1060         }
1061         this.reset();
1062         return true;
1063     },
1064     success: function(transport) {
1065         SYJView.messenger.setMessage(SyjStrings.newpwdSuccess, "success");
1066         this.modalbox.hide();
1067     }
1068
1069 });
1070 var SYJNewpwd = new SYJNewpwdClass();
1071
1072 var LoginMgr = Object.extend(gLoggedInfo, {
1073     controlsdeck: null,
1074
1075     updateUI: function() {
1076         if (!this.controlsdeck) {
1077             this.controlsdeck = new Deck("login_controls");
1078         }
1079         if (this.logged) {
1080             this.controlsdeck.setIndex(1);
1081             $$(".logged-hide").invoke('hide');
1082             $$(".logged-show").invoke('show');
1083         } else {
1084             this.controlsdeck.setIndex(0);
1085             $$(".logged-hide").invoke('show');
1086             $$(".logged-show").invoke('hide');
1087         }
1088
1089         if ($("edit-btn")) {
1090             if (this.iscreator && SYJView.mode === 'view') {
1091                 $("edit-btn").show();
1092             } else {
1093                 $("edit-btn").hide();
1094             }
1095         }
1096     },
1097
1098     login: function(aPseudo, aIsCreator) {
1099         if (typeof aIsCreator === "boolean") {
1100             this.iscreator = aIsCreator;
1101         }
1102         this.logged = true;
1103         $$('.logged-pseudo').each(function(elt) {
1104             $A(elt.childNodes).filter(function(node) {
1105                 return (node.nodeType === 3 || node.tagName.toLowerCase() === 'br');
1106             }).each(function(node) {
1107                 node.nodeValue = node.nodeValue.replace('%s', aPseudo);
1108             });
1109         });
1110         this.updateUI();
1111     }
1112 });
1113
1114 var PseudoChecker = {
1115     req: null,
1116     exists: {},
1117     currentvalue: null,
1118     messageelt: null,
1119     throbber: null,
1120
1121     message: function(str, status, throbber) {
1122         var row;
1123         if (!this.messageelt) {
1124             row = new Element('tr');
1125             // we can't use row.update('<td></td><td><div></div></td>')
1126             // because gecko would mangle the <td>s
1127             row.insert(new Element('td'))
1128                .insert((new Element('td')).update(new Element('div')));
1129
1130             $("user_pseudo").up('tr').insert({after: row});
1131             this.messageelt = new Element('span');
1132             this.throbber = new Element("img", { src: "icons/throbber.gif"});
1133             row.down('div').insert(this.throbber).insert(this.messageelt);
1134         }
1135         if (throbber) {
1136             this.throbber.show();
1137         } else {
1138             this.throbber.hide();
1139         }
1140         this.messageelt.up().setStyle({visibility: ''});
1141         this.messageelt.className = status;
1142         this.messageelt.update(str);
1143     },
1144
1145     availableMessage: function(available) {
1146         var message = available ? SyjStrings.availablePseudo: SyjStrings.unavailablePseudo,
1147             status = available ? "success": "warn";
1148         this.message(message, status, false);
1149     },
1150
1151     reset: function() {
1152         if (this.req) {
1153             this.req.abort();
1154             this.req = this.currentvalue = null;
1155         }
1156         if (this.messageelt) {
1157             this.messageelt.up().setStyle({visibility: 'hidden'});
1158         }
1159     },
1160
1161     check: function() {
1162         var pseudo = $("user_pseudo").value;
1163
1164         this.reset();
1165
1166         if (!pseudo || !(pseudo.match(/^[a-zA-Z0-9_.]+$/))) {
1167             return;
1168         }
1169
1170         if (typeof this.exists[pseudo] === "boolean") {
1171             this.reset();
1172             this.availableMessage(!this.exists[pseudo]);
1173             return;
1174         }
1175
1176         this.message(SyjStrings.pseudoChecking, "", true);
1177
1178         this.currentvalue = pseudo;
1179         this.req = new Ajax.TimedRequest('userexists/' + encodeURIComponent(pseudo), 20, {
1180             onFailure: this.failure.bind(this),
1181             onSuccess: this.success.bind(this)
1182         });
1183     },
1184
1185     failure: function(transport) {
1186         var httpCode = 0, value = this.currentvalue;
1187
1188         if (transport) {
1189             httpCode = transport.getStatus();
1190         }
1191         this.reset();
1192         if (httpCode === 404) {
1193             this.exists[value] = false;
1194             this.availableMessage(true);
1195         }
1196
1197     },
1198
1199     success: function(transport) {
1200         var httpCode = transport.getStatus(), value = this.currentvalue;
1201         this.reset();
1202         this.exists[value] = true;
1203         this.availableMessage(false);
1204     }
1205 };
1206
1207 var Nominatim = (function() {
1208     var presubmit = function() {
1209         var input = $("nominatim-search");
1210         if (input.value.strip().empty()) {
1211             $("nominatim-message").setMessage(SyjStrings.notEmptyField, "warn");
1212             input.activate();
1213             return false;
1214         }
1215         $("nominatim-suggestions").hide();
1216         $("nominatim-message").hide();
1217         $("nominatim-throbber").show();
1218         return true;
1219     };
1220
1221     var zoomToExtent = function(bounds) { // we must call map.setCenter with forceZoomChange to true. See ol#2798
1222         var center = bounds.getCenterLonLat();
1223         if (this.baseLayer.wrapDateLine) {
1224             var maxExtent = this.getMaxExtent();
1225             bounds = bounds.clone();
1226             while (bounds.right < bounds.left) {
1227                 bounds.right += maxExtent.getWidth();
1228             }
1229             center = bounds.getCenterLonLat().wrapDateLine(maxExtent);
1230         }
1231         this.setCenter(center, this.getZoomForExtent(bounds), false, true);
1232     };
1233
1234     var success = function(transport) {
1235         $("nominatim-throbber").hide();
1236
1237         if (!transport.responseJSON || !transport.responseJSON.length) {
1238             $("nominatim-message").setMessage(SyjStrings.noResult, 'error');
1239             $("nominatim-search").activate();
1240             return;
1241         }
1242
1243         var place = transport.responseJSON[0],
1244             bbox = place.boundingbox;
1245
1246         if (!bbox || bbox.length !== 4) {
1247             $("nominatim-message").setMessage(SyjStrings.requestError, 'error');
1248             return;
1249         }
1250
1251         extent = new OpenLayers.Bounds(bbox[2], bbox[1], bbox[3], bbox[0]).transform(WGS84, Mercator);
1252         zoomToExtent.call(SYJView.map, extent);
1253
1254         $("nominatim-suggestions-list").update();
1255
1256         var clickhandler = function(bbox) {
1257             return function(evt) {
1258                 evt.stop();
1259                 var extent = new OpenLayers.Bounds(bbox[2], bbox[1], bbox[3], bbox[0]).transform(WGS84, Mercator);
1260                 $("nominatim-suggestions-list").select("li").invoke('removeClassName', 'current');
1261                 evt.target.up('li').addClassName('current');
1262                 SYJView.map.zoomToExtent(extent);
1263             };
1264         };
1265
1266         var i;
1267         for (i = 0; i < transport.responseJSON.length; i++) {
1268             var item = transport.responseJSON[i];
1269             if (item.display_name && item.boundingbox && item.boundingbox.length === 4) {
1270                 var li = new Element("li");
1271                 var anchor = new Element("a", {
1272                     href: "",
1273                     className: "nominatim-suggestions-link"
1274                 });
1275
1276                 anchor.observe('click', clickhandler(item.boundingbox));
1277                 Element.text(anchor, item.display_name);
1278
1279                 var icon = new Element("img", {
1280                     className: "nominatim-suggestions-icon",
1281                     src: item.icon || 'icons/world.png'
1282                 });
1283                 li.insert(icon).insert(anchor);
1284                 $("nominatim-suggestions-list").insert(li);
1285                 if ($("nominatim-suggestions-list").childNodes.length >= 6) {
1286                     break;
1287                 }
1288             }
1289         }
1290
1291         if ($("nominatim-suggestions-list").childNodes.length > 1) {
1292             var bottomOffset = $('data_controls').measure('height') + 3;
1293             $("nominatim-suggestions").setStyle({
1294                 bottom: (document.viewport.getHeight() - $('data_controls').cumulativeOffset().top + 3).toString() + 'px'
1295             }).show();
1296             $("nominatim-suggestions-list").select("li:first-child")[0].addClassName('current');
1297         } else {
1298             $("nominatim-suggestions").hide();
1299         }
1300
1301     };
1302
1303     var failure = function(transport) {
1304         $("nominatim-throbber").hide();
1305
1306         var httpCode = 0, message = SyjStrings.unknownError, input; // default message error
1307
1308         if (transport) {
1309             httpCode = transport.getStatus();
1310         }
1311
1312         switch (httpCode) {
1313             case 0:
1314                 message = SyjStrings.notReachedError;
1315             break;
1316             case 400:
1317             case 404:
1318                 message = SyjStrings.requestError;
1319             break;
1320             case 500:
1321                 message = SyjStrings.serverError;
1322             break;
1323         }
1324
1325         $("nominatim-message").setMessage(message, 'error');
1326     };
1327
1328     return {
1329         init: function() {
1330             if (!$("nominatim-form")) {
1331                return;
1332             }
1333             $("nominatim-controls").hide();
1334             $("nominatim-label").observe('click', function(evt) {
1335                 $("nominatim-controls").show();
1336                 $("nominatim-search").activate();
1337                 evt.stop();
1338             });
1339
1340             $("nominatim-form").ajaxize({
1341                 presubmit: presubmit,
1342                 onSuccess: success,
1343                 onFailure: failure
1344               });
1345             new CloseBtn($("nominatim-suggestions"));
1346
1347             $$("#nominatim-message, #nominatim-suggestions, #nominatim-throbber").invoke('hide');
1348         }
1349     };
1350 }());
1351
1352 document.observe("dom:loaded", function() {
1353     SYJLogin.init();
1354     SYJUser.init();
1355     SYJDataUi.viewmode();
1356     SYJView.init();
1357     SYJNewpwd.init();
1358     LoginMgr.updateUI();
1359     Nominatim.init();
1360 });
1361
1362 window.onbeforeunload = function() {
1363     if (SYJView.unsavedRoute) {
1364         return SyjStrings.unsavedConfirmExit;
1365     } else {
1366         return undefined;
1367     }
1368 };