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