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