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