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