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