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