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