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