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