]> dev.renevier.net Git - syj.git/blob - public/js/syj.js
add mapquest layer
[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         this.resizeMap();
516     },
517
518     resizeMap: function() {
519         var map = $('map');
520         map.style.width = map.offsetWidth.toString() + 'px';
521         map.style.height = map.offsetHeight.toString() + 'px';
522     },
523
524     observer: function(evt) {
525         if (evt.eventName === "simplebox:shown" && evt.memo.element !== $("termsofusearea")) {
526             this.messenger.hide();
527         }
528     },
529
530     prepareForm: function(form) {
531         if (!LoginMgr.logged && !$("geom_accept").checked) {
532             this.messenger.setMessage(SyjStrings.acceptTermsofuseWarn, "warn");
533             $("geom_accept_container").highlight('#F08080');
534             $("geom_accept").activate();
535             return false;
536         }
537
538         var line, realPoints, idx;
539
540         line = new OpenLayers.Geometry.LineString();
541         realPoints = this.editControl.handler.realPoints;
542         for (idx = 0; idx < realPoints.length; idx++) {
543             line.addComponent(realPoints[idx].geometry.clone());
544         }
545         this.viewLayer.addFeatures(new OpenLayers.Feature.Vector(line));
546
547         this.viewMode();
548
549         if (line.components.length) {
550             $("geom_data").value = this.wkt.write(new OpenLayers.Feature.Vector(line));
551         } else {
552             $("geom_data").value = "";
553         }
554
555         if (this.mode === "edit" && typeof gLoggedInfo.pathid !== "undefined") {
556             $("geomform").setAttribute("action", "path/" + gLoggedInfo.pathid.toString() + '/update');
557         } else {
558             $("geomform").setAttribute("action", "path");
559         }
560         this.needsFormResubmit = false;
561         SyjSaveUI.disable.bind(SyjSaveUI).defer();
562         this.messenger.hide();
563         return true;
564     },
565
566     viewMode: function() {
567         var handler = this.editControl.handler;
568         OpenLayers.Handler.ModifiablePath.prototype.finalize.apply(handler, arguments);
569         // we need to recreate them on next createFeature; otherwise
570         // they'll reference destroyed features
571         delete(handler.handlers.drag);
572         delete(handler.handlers.feature);
573         this.editControl.deactivate();
574     },
575
576     editMode: function() {
577         var components, point0, point, pixels, pixel, idx;
578
579         this.initEditControl();
580
581         this.editControl.activate();
582         if (this.viewLayer.features.length) {
583             components = this.viewLayer.features[0].geometry.components;
584             point0 = components[0];
585             if (point0) {
586                 pixel = this.map.getPixelFromLonLat(new OpenLayers.LonLat(point0.x, point0.y));
587                 this.editControl.handler.createFeature(pixel);
588                 this.editControl.handler.lastUp = pixel;
589                 pixels = [];
590                 for (idx = 1; idx < components.length; idx++) {
591                     point = components[idx];
592                     pixels.push(this.map.getPixelFromLonLat(new OpenLayers.LonLat(point.x, point.y)));
593                 }
594                 this.editControl.handler.addPoints(pixels);
595             }
596             this.unsavedRoute = {
597                 features: this.viewLayer.features.invoke('clone'),
598                 title: $("geom_title").value
599             };
600         }
601
602         this.viewLayer.destroyFeatures();
603
604         SYJDataUi.editmode();
605         if (this.editControl.handler.realPoints && this.editControl.handler.realPoints.length >= 2) {
606             SyjSaveUI.disableSubmit();
607         } else {
608             SyjSaveUI.disable();
609         }
610     },
611
612     initEditControl: function() {
613         var styles;
614
615         if (this.editControl) {
616             return;
617         }
618
619         this.editControl = new OpenLayers.Control.DrawFeature(new OpenLayers.Layer.Vector(), OpenLayers.Handler.SyjModifiablePath, {
620             callbacks: {
621                 modify: function(f, line) {
622                     SYJPathLength.update();
623
624                     var npoints = this.handler.realPoints.length;
625                     if (npoints === 0) {
626                         $("geom_upload_container").show();
627                         SYJView.unsavedRoute = null;
628                     } else {
629                         if (!SYJView.unsavedRoute) {
630                             SYJView.unsavedRoute = {};
631                         }
632                     }
633
634                     if (npoints < 2) {
635                         SyjSaveUI.disable();
636                     } else {
637                         SyjSaveUI.enable();
638                     }
639                 },
640                 create: function(f, line) {
641                     this.messenger.hide();
642                     $("geom_upload_container").hide();
643                 }.bind(this)
644             },
645
646             handlerOptions: {
647                 layerOptions: {
648                     styleMap: styleMap.edit
649                 }
650             }
651         });
652         this.map.addControl(this.editControl);
653         if (this.editControl.layer.renderer instanceof OpenLayers.Renderer.Canvas) {
654             // using externalGraphic with canvas renderer is definitively too buggy
655             styles = this.editControl.handler.layerOptions.styleMap.styles;
656             styles.select = styles.select_for_canvas;
657         }
658     },
659
660     saveSuccess: function(transport) {
661       // server sends and empty response on success. If we get a response, that
662       // probably means an error or warning has been printed by server.
663       if (!transport.responseJSON && transport.responseText.length) {
664           this.saveFailure(null, 500);
665           return;
666       }
667
668       this.unsavedRoute = null;
669       if (transport.responseJSON && (typeof transport.responseJSON.redirect === "string")) {
670           location = transport.responseJSON.redirect;
671           return;
672       }
673
674       this.messenger.setMessage(SyjStrings.saveSuccess, "success");
675       SYJDataUi.viewmode();
676       document.title = $('geom_title').value;
677     },
678
679     saveFailure: function(transport, httpCode) {
680         var message = "";
681         if (typeof httpCode === "undefined") {
682             httpCode = transport? transport.getStatus(): 0;
683         }
684
685         switch (httpCode) {
686             case 0:
687                 message = SyjStrings.notReachedError;
688             break;
689             case 400:
690             case 404:
691                 message = SyjStrings.requestError;
692             break;
693             case 403:
694                 message = "";
695                 SYJLogin.messenger.setMessage(SyjStrings.loginNeeded, "warn");
696                 SYJLogin.modalbox.show();
697                 this.needsFormResubmit = true;
698             break;
699             case 410:
700                 message = SyjStrings.gonePathError;
701             break;
702             case 500:
703                 message = SyjStrings.serverError;
704                 this.needsFormResubmit = true;
705             break;
706             default:
707                 message = SyjStrings.unknownError;
708             break;
709         }
710
711         this.editMode();
712         // is some cases, we let the user resubmit, in some other cases, he
713         // needs to modify the path before submitting again
714         if (this.needsFormResubmit) {
715             SyjSaveUI.enable();
716         }
717
718         this.messenger.setMessage(message, "error");
719     }
720 };
721
722 var SYJModalClass = Class.create({
723     type: "",
724
725     init: function() {
726         this.area = $(this.type + '_area');
727         this.messenger = $(this.type + "_message");
728         this.modalbox = new SimpleBox(this.area, {
729             closeMethods: ["onescapekey", "onouterclick", "onbutton"]
730         });
731
732         var anchor = $(this.type + '_control_anchor');
733         var parent = anchor.up('.menu-item');
734         if (parent) {
735             anchor = parent;
736         }
737         anchor.observe("click", function(evt) {
738             this.modalbox.show();
739             evt.stop();
740         }.bindAsEventListener(this));
741
742         document.observe('simplebox:shown', this.observer.bindAsEventListener(this));
743         document.observe('simplebox:hidden', this.observer.bindAsEventListener(this));
744
745         $(this.type + "form").ajaxize({
746             presubmit: this.presubmit.bind(this),
747             onSuccess: this.success.bind(this),
748             onFailure: this.failure.bind(this)
749         });
750     },
751
752     checkNotEmpty: function(input, message) {
753         if ($(input).value.strip().empty()) {
754             this.messenger.setMessage(message, "warn");
755             $(input).highlight('#F08080').activate();
756             return false;
757         }
758         return true;
759     },
760
761     observer: function(evt) {
762         var simplebox, input;
763
764         if (evt.eventName === "simplebox:shown" && evt.memo.element !== $("termsofusearea")) {
765             simplebox = evt.memo;
766             if (simplebox === this.modalbox) {
767                 input = this.area.select('input[type="text"]')[0];
768                 (function () {
769                     input.activate();
770                 }.defer());
771             } else {
772                 this.modalbox.hide();
773             }
774
775         } else if (evt.eventName === "simplebox:hidden" && evt.memo.element !== $("termsofusearea")) {
776             simplebox = evt.memo;
777             if (simplebox === this.modalbox) {
778                 this.reset();
779             }
780         }
781     },
782
783     failure: function(transport) {
784         var httpCode = 0, message = SyjStrings.unknownError, input; // default message error
785
786         if (transport) {
787             httpCode = transport.getStatus();
788         }
789
790         switch (httpCode) {
791             case 0:
792                 message = SyjStrings.notReachedError;
793             break;
794             case 400:
795             case 404:
796             case 410:
797                 message = SyjStrings.requestError;
798             break;
799             case 500:
800                 message = SyjStrings.serverError;
801             break;
802         }
803
804         this.messenger.setMessage(message, "error");
805         input = this.area.select('input[type="text"]')[0];
806         input.highlight('#F08080').activate();
807     },
808
809     reset: function() {
810         this.messenger.hide();
811         this.area.select('.message').invoke('setMessageStatus', null);
812     }
813 });
814
815 var SYJUserClass = Class.create(SYJModalClass, {
816     type: "user",
817     toubox: null,
818
819     init: function($super) {
820         $super();
821         $("termsofusearea").hide();
822
823         $$("#user_termsofuse_anchor, #geom_termsofuse_anchor").invoke('observe', "click", function(evt) {
824             if (!this.toubox) {
825                 this.toubox = new SimpleBox($("termsofusearea"), {
826                     closeMethods: ["onescapekey", "onouterclick", "onbutton"]
827                 });
828             }
829             this.toubox.show();
830             if (!$("termsofuseiframe").getAttribute("src")) {
831                 $("termsofusearea").show();
832                 $("termsofuseiframe").setAttribute("src", evt.target.href);
833             }
834             evt.stop();
835         }.bindAsEventListener(this));
836
837         $$("#login_area_create > a").invoke('observe', 'click',
838             function(evt) {
839                 this.modalbox.show();
840                 evt.stop();
841             }.bindAsEventListener(this));
842
843         $("user_pseudo-desc").hide();
844         $("user_pseudo").observe('contentchange', function(evt) {
845             var value = evt.target.value;
846             PseudoChecker.reset();
847             if (value && !(value.match(/^[a-zA-Z0-9_.]+$/))) {
848                 $("user_pseudo-desc").show().setMessageStatus("warn");
849             } else {
850                 $("user_pseudo-desc").hide();
851             }
852         }).timedobserve(function() {
853             PseudoChecker.check();
854         });
855
856         $("user_password").observe('contentchange', function(evt) {
857             if (evt.target.value.length < 6) {
858                 $("user_password-desc").setMessageStatus("warn");
859             } else {
860                 $("user_password-desc").setMessageStatus("success");
861             }
862         }.bindAsEventListener(this));
863
864         $('account-create-anchor').insert({after: new Toggler('account-info').element});
865     },
866
867     presubmit: function() {
868         this.messenger.hide();
869         PseudoChecker.reset();
870         if (!(this.checkNotEmpty("user_pseudo", SyjStrings.userEmptyWarn))) {
871             return false;
872         }
873
874         if (!($("user_pseudo").value.match(/^[a-zA-Z0-9_.]+$/))) {
875             $("user_pseudo-desc").show().setMessageStatus("warn");
876             $("user_pseudo").highlight('#F08080').activate();
877             return false;
878         }
879
880         if (PseudoChecker.exists[$("user_pseudo").value]) {
881             PseudoChecker.availableMessage(false);
882             $("user_pseudo").highlight('#F08080').activate();
883             return false;
884         }
885
886         if (!(this.checkNotEmpty("user_password", SyjStrings.passwordEmptyWarn))) {
887             return false;
888         }
889
890         if ($("user_password").value.length < 6) {
891             $("user_password-desc").setMessageStatus("warn");
892             $("user_password").highlight('#F08080').activate();
893             return false;
894         }
895
896         if ($("user_password").value !== $("user_password_confirm").value) {
897             this.messenger.setMessage(SyjStrings.passwordNoMatchWarn, "warn");
898             $("user_password").highlight('#F08080').activate();
899             return false;
900         }
901
902         if (!(this.checkNotEmpty("user_email", SyjStrings.emailEmptyWarn))) {
903             return false;
904         }
905
906         if (!$("user_accept").checked) {
907             this.messenger.setMessage(SyjStrings.acceptTermsofuseWarn, "warn");
908             $("user_accept_container").highlight('#F08080');
909             $("user_accept").activate();
910             return false;
911         }
912
913         this.reset();
914         return true;
915     },
916
917     success: function(transport) {
918         if (!transport.responseJSON ||
919             typeof transport.responseJSON.pseudo !== "string"
920             ) {
921             this.messenger.setMessage(SyjStrings.unknownError, "error");
922             return;
923         }
924
925         LoginMgr.login(transport.responseJSON.pseudo);
926         SYJView.messenger.setMessage(SyjStrings.userSuccess, "success");
927         this.modalbox.hide();
928         if (SYJView.needsFormResubmit) {
929             SYJView.messenger.addMessage(SyjStrings.canResubmit);
930             $("geom_submit").activate();
931         }
932     },
933
934     failure: function($super, transport) {
935         var httpCode = 0, focusInput = null, message = "";
936
937         if (transport) {
938             httpCode = transport.getStatus();
939         }
940
941         focusInput = null;
942         message = "";
943
944         switch (httpCode) {
945             case 400:
946                 if (transport.responseJSON) {
947                     switch (transport.responseJSON.message) {
948                         case "invalidemail":
949                             message = SyjStrings.emailInvalidWarn;
950                             focusInput = $("user_email");
951                         break;
952                         case "uniquepseudo":
953                             PseudoChecker.availableMessage(false);
954                             focusInput = $("user_pseudo");
955                         break;
956                         case "uniqueemail":
957                             message = SyjStrings.uniqueEmailError;
958                             focusInput = $("user_email");
959                         break;
960                     }
961                 }
962             break;
963         }
964
965         if (focusInput) {
966             if (message) {
967                 this.messenger.setMessage(message, "error");
968             }
969             focusInput.highlight('#F08080').activate();
970             return;
971         }
972
973         $super(transport);
974     }
975 });
976 var SYJUser = new SYJUserClass();
977
978 var SYJLoginClass = Class.create(SYJModalClass, {
979     type: "login",
980
981     init: function($super) {
982         $super();
983     },
984
985     presubmit: function() {
986         this.messenger.hide();
987         if (!(this.checkNotEmpty("login_user", SyjStrings.userEmptyWarn))) {
988             return false;
989         }
990
991         this.reset();
992         return true;
993     },
994
995     success: function(transport) {
996         if (!transport.responseJSON ||
997             typeof transport.responseJSON.iscreator !== "boolean" ||
998             typeof transport.responseJSON.pseudo !== "string"
999             ) {
1000             this.messenger.setMessage(SyjStrings.unknownError, "error");
1001             return;
1002         }
1003         LoginMgr.login(transport.responseJSON.pseudo, transport.responseJSON.iscreator);
1004
1005         SYJView.messenger.setMessage(SyjStrings.loginSuccess, "success");
1006         this.modalbox.hide();
1007         if (SYJView.needsFormResubmit) {
1008             SYJView.messenger.addMessage(SyjStrings.canResubmit);
1009             $("geom_submit").activate();
1010         }
1011     },
1012
1013     failure: function($super, transport) {
1014         var httpCode = 0, focusInput = null, message = "";
1015
1016         if (transport) {
1017             httpCode = transport.getStatus();
1018         }
1019
1020         focusInput = null;
1021         message = "";
1022
1023         switch (httpCode) {
1024             case 403:
1025                 message = SyjStrings.loginFailure;
1026                 focusInput = $("login_user");
1027             break;
1028         }
1029
1030         if (message) {
1031             this.messenger.setMessage(message, "error");
1032             if (focusInput) {
1033                 focusInput.highlight('#F08080').activate();
1034             }
1035             return;
1036         }
1037
1038         $super(transport);
1039     }
1040 });
1041 var SYJLogin = new SYJLoginClass();
1042
1043 var SYJNewpwdClass = Class.create(SYJModalClass, {
1044     type: "newpwd",
1045
1046     presubmit: function() {
1047         if (!(this.checkNotEmpty("newpwd_email", SyjStrings.emailEmptyWarn))) {
1048             return false;
1049         }
1050         this.reset();
1051         return true;
1052     },
1053     success: function(transport) {
1054         SYJView.messenger.setMessage(SyjStrings.newpwdSuccess, "success");
1055         this.modalbox.hide();
1056     }
1057
1058 });
1059 var SYJNewpwd = new SYJNewpwdClass();
1060
1061 var LoginMgr = Object.extend(gLoggedInfo, {
1062     controlsdeck: null,
1063
1064     updateUI: function() {
1065         if (!this.controlsdeck) {
1066             this.controlsdeck = new Deck("login_controls");
1067         }
1068         if (this.logged) {
1069             this.controlsdeck.setIndex(1);
1070             $$(".logged-hide").invoke('hide');
1071             $$(".logged-show").invoke('show');
1072         } else {
1073             this.controlsdeck.setIndex(0);
1074             $$(".logged-hide").invoke('show');
1075             $$(".logged-show").invoke('hide');
1076         }
1077
1078         if ($("edit-btn")) {
1079             if (this.iscreator && SYJView.mode === 'view') {
1080                 $("edit-btn").show();
1081             } else {
1082                 $("edit-btn").hide();
1083             }
1084         }
1085     },
1086
1087     login: function(aPseudo, aIsCreator) {
1088         if (typeof aIsCreator === "boolean") {
1089             this.iscreator = aIsCreator;
1090         }
1091         this.logged = true;
1092         $$('.logged-pseudo').each(function(elt) {
1093             $A(elt.childNodes).filter(function(node) {
1094                 return (node.nodeType === 3 || node.tagName.toLowerCase() === 'br');
1095             }).each(function(node) {
1096                 node.nodeValue = node.nodeValue.replace('%s', aPseudo);
1097             });
1098         });
1099         this.updateUI();
1100     }
1101 });
1102
1103 var PseudoChecker = {
1104     req: null,
1105     exists: {},
1106     currentvalue: null,
1107     messageelt: null,
1108     throbber: null,
1109
1110     message: function(str, status, throbber) {
1111         var row;
1112         if (!this.messageelt) {
1113             row = new Element('tr');
1114             // we can't use row.update('<td></td><td><div></div></td>')
1115             // because gecko would mangle the <td>s
1116             row.insert(new Element('td'))
1117                .insert((new Element('td')).update(new Element('div')));
1118
1119             $("user_pseudo").up('tr').insert({after: row});
1120             this.messageelt = new Element('span');
1121             this.throbber = new Element("img", { src: "icons/throbber.gif"});
1122             row.down('div').insert(this.throbber).insert(this.messageelt);
1123         }
1124         if (throbber) {
1125             this.throbber.show();
1126         } else {
1127             this.throbber.hide();
1128         }
1129         this.messageelt.up().setStyle({visibility: ''});
1130         this.messageelt.className = status;
1131         this.messageelt.update(str);
1132     },
1133
1134     availableMessage: function(available) {
1135         var message = available ? SyjStrings.availablePseudo: SyjStrings.unavailablePseudo,
1136             status = available ? "success": "warn";
1137         this.message(message, status, false);
1138     },
1139
1140     reset: function() {
1141         if (this.req) {
1142             this.req.abort();
1143             this.req = this.currentvalue = null;
1144         }
1145         if (this.messageelt) {
1146             this.messageelt.up().setStyle({visibility: 'hidden'});
1147         }
1148     },
1149
1150     check: function() {
1151         var pseudo = $("user_pseudo").value;
1152
1153         this.reset();
1154
1155         if (!pseudo || !(pseudo.match(/^[a-zA-Z0-9_.]+$/))) {
1156             return;
1157         }
1158
1159         if (typeof this.exists[pseudo] === "boolean") {
1160             this.reset();
1161             this.availableMessage(!this.exists[pseudo]);
1162             return;
1163         }
1164
1165         this.message(SyjStrings.pseudoChecking, "", true);
1166
1167         this.currentvalue = pseudo;
1168         this.req = new Ajax.TimedRequest('userexists/' + encodeURIComponent(pseudo), 20, {
1169             onFailure: this.failure.bind(this),
1170             onSuccess: this.success.bind(this)
1171         });
1172     },
1173
1174     failure: function(transport) {
1175         var httpCode = 0, value = this.currentvalue;
1176
1177         if (transport) {
1178             httpCode = transport.getStatus();
1179         }
1180         this.reset();
1181         if (httpCode === 404) {
1182             this.exists[value] = false;
1183             this.availableMessage(true);
1184         }
1185
1186     },
1187
1188     success: function(transport) {
1189         var httpCode = transport.getStatus(), value = this.currentvalue;
1190         this.reset();
1191         this.exists[value] = true;
1192         this.availableMessage(false);
1193     }
1194 };
1195
1196 var Nominatim = (function() {
1197     var presubmit = function() {
1198         var input = $("nominatim-search");
1199         if (input.value.strip().empty()) {
1200             $("nominatim-message").setMessage(SyjStrings.notEmptyField, "warn");
1201             input.activate();
1202             return false;
1203         }
1204         $("nominatim-suggestions").hide();
1205         $("nominatim-message").hide();
1206         $("nominatim-throbber").show();
1207         return true;
1208     };
1209
1210     var zoomToExtent = function(bounds) { // we must call map.setCenter with forceZoomChange to true. See ol#2798
1211         var center = bounds.getCenterLonLat();
1212         if (this.baseLayer.wrapDateLine) {
1213             var maxExtent = this.getMaxExtent();
1214             bounds = bounds.clone();
1215             while (bounds.right < bounds.left) {
1216                 bounds.right += maxExtent.getWidth();
1217             }
1218             center = bounds.getCenterLonLat().wrapDateLine(maxExtent);
1219         }
1220         this.setCenter(center, this.getZoomForExtent(bounds), false, true);
1221     };
1222
1223     var success = function(transport) {
1224         $("nominatim-throbber").hide();
1225
1226         if (!transport.responseJSON || !transport.responseJSON.length) {
1227             $("nominatim-message").setMessage(SyjStrings.noResult, 'error');
1228             $("nominatim-search").activate();
1229             return;
1230         }
1231
1232         var place = transport.responseJSON[0],
1233             bbox = place.boundingbox;
1234
1235         if (!bbox || bbox.length !== 4) {
1236             $("nominatim-message").setMessage(SyjStrings.requestError, 'error');
1237             return;
1238         }
1239
1240         extent = new OpenLayers.Bounds(bbox[2], bbox[1], bbox[3], bbox[0]).transform(WGS84, Mercator);
1241         zoomToExtent.call(SYJView.map, extent);
1242
1243         $("nominatim-suggestions-list").update();
1244
1245         var clickhandler = function(bbox) {
1246             return function(evt) {
1247                 evt.stop();
1248                 var extent = new OpenLayers.Bounds(bbox[2], bbox[1], bbox[3], bbox[0]).transform(WGS84, Mercator);
1249                 $("nominatim-suggestions-list").select("li").invoke('removeClassName', 'current');
1250                 evt.target.up('li').addClassName('current');
1251                 SYJView.map.zoomToExtent(extent);
1252             };
1253         };
1254
1255         var i;
1256         for (i = 0; i < transport.responseJSON.length; i++) {
1257             var item = transport.responseJSON[i];
1258             if (item.display_name && item.boundingbox && item.boundingbox.length === 4) {
1259                 var li = new Element("li");
1260                 var anchor = new Element("a", {
1261                     href: "",
1262                     className: "nominatim-suggestions-link"
1263                 });
1264
1265                 anchor.observe('click', clickhandler(item.boundingbox));
1266                 Element.text(anchor, item.display_name);
1267
1268                 var icon = new Element("img", {
1269                     className: "nominatim-suggestions-icon",
1270                     src: item.icon || 'icons/world.png'
1271                 });
1272                 li.insert(icon).insert(anchor);
1273                 $("nominatim-suggestions-list").insert(li);
1274                 if ($("nominatim-suggestions-list").childNodes.length >= 6) {
1275                     break;
1276                 }
1277             }
1278         }
1279
1280         if ($("nominatim-suggestions-list").childNodes.length > 1) {
1281             var bottomOffset = $('data_controls').measure('height') + 3;
1282             $("nominatim-suggestions").setStyle({
1283                 bottom: (document.viewport.getHeight() - $('data_controls').cumulativeOffset().top + 3).toString() + 'px'
1284             }).show();
1285             $("nominatim-suggestions-list").select("li:first-child")[0].addClassName('current');
1286         } else {
1287             $("nominatim-suggestions").hide();
1288         }
1289
1290     };
1291
1292     var failure = function(transport) {
1293         $("nominatim-throbber").hide();
1294
1295         var httpCode = 0, message = SyjStrings.unknownError, input; // default message error
1296
1297         if (transport) {
1298             httpCode = transport.getStatus();
1299         }
1300
1301         switch (httpCode) {
1302             case 0:
1303                 message = SyjStrings.notReachedError;
1304             break;
1305             case 400:
1306             case 404:
1307                 message = SyjStrings.requestError;
1308             break;
1309             case 500:
1310                 message = SyjStrings.serverError;
1311             break;
1312         }
1313
1314         $("nominatim-message").setMessage(message, 'error');
1315     };
1316
1317     return {
1318         init: function() {
1319             if (!$("nominatim-form")) {
1320                return;
1321             }
1322             $("nominatim-controls").hide();
1323             $("nominatim-label").observe('click', function(evt) {
1324                 $("nominatim-controls").show();
1325                 $("nominatim-search").activate();
1326                 evt.stop();
1327             });
1328
1329             $("nominatim-form").ajaxize({
1330                 presubmit: presubmit,
1331                 onSuccess: success,
1332                 onFailure: failure
1333               });
1334             new CloseBtn($("nominatim-suggestions"));
1335
1336             $$("#nominatim-message, #nominatim-suggestions, #nominatim-throbber").invoke('hide');
1337         }
1338     };
1339 }());
1340
1341 document.observe("dom:loaded", function() {
1342     SYJLogin.init();
1343     SYJUser.init();
1344     SYJDataUi.viewmode();
1345     SYJView.init();
1346     SYJNewpwd.init();
1347     LoginMgr.updateUI();
1348     Nominatim.init();
1349 });
1350
1351 window.onbeforeunload = function() {
1352     if (SYJView.unsavedRoute) {
1353         return SyjStrings.unsavedConfirmExit;
1354     } else {
1355         return undefined;
1356     }
1357 };
1358
1359 window.onresize = function() {
1360     SYJView.resizeMap();
1361 };