]> dev.renevier.net Git - syj.git/blob - public/js/syj.js
separate route to create a new path, and to update an existing one
[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 Element.addMethods('input', {
4     observe : Element.Methods.observe.wrap(function(proceed, element, eventName, handler) {
5         if (eventName === "contentchange") {
6             proceed(element, 'keyup', function(evt) {
7                 if (evt.keyCode === 13) {
8                     return;
9                 }
10                 handler.apply(null, arguments);
11             });
12             proceed(element, 'paste', handler);
13             return proceed(element, 'change', handler);
14         }
15         return proceed(element, eventName, handler);
16     })
17 });
18
19 // avoid openlayers alerts
20 OpenLayers.Console.userError = function(error) {
21     SYJView.messenger.setMessage(error, "error");
22 };
23
24 var SyjSaveUI = {
25     status: "unknown",
26
27     init: function() {
28         $("geom_title").observe('contentchange', this.enableSubmit.bindAsEventListener(this));
29         return this;
30     },
31
32     hide: function() {
33         $("geom_submit").blur();
34         $("geom_title").blur();
35         $("geomform").hide();
36         return this;
37     },
38
39     show: function() {
40         $("geomform").show();
41         return this;
42     },
43
44     enable: function() {
45         if (this.status === "enabled") {
46             return this;
47         }
48         this.enableSubmit();
49         $("geom_title").disabled = false;
50         $("geom_title").activate();
51         $("geomform").removeClassName("disabled");
52         this.status = "enabled";
53         return this;
54     },
55
56     disable: function() {
57         if (this.status === "disabled") {
58             return this;
59         }
60         this.disableSubmit();
61         $("geom_title").blur();
62         $("geom_title").disabled = true;
63         $("geomform").addClassName("disabled");
64         this.status = "disabled";
65         return this;
66     },
67
68     enableSubmit: function() {
69         $("geom_submit").disabled = false;
70         this.status = "partial";
71         return this;
72     },
73
74     disableSubmit: function() {
75         $("geom_submit").blur();
76         $("geom_submit").disabled = true;
77         this.status = "partial";
78         return this;
79     }
80 };
81
82 var SyjEditUI = {
83     hide: function() {
84         $("edit-btn").blur();
85         $("edit-btn").hide();
86         return this;
87     },
88
89     show: function() {
90         $("edit-btn").show();
91         return this;
92     }
93 };
94
95 OpenLayers.Handler.SyjModifiablePath = OpenLayers.Class(OpenLayers.Handler.ModifiablePath, {
96     mouseup: function(evt) {
97         // do not add a point when navigating
98         var mapControls = this.control.map.controls, idx, ctrl;
99
100         for (idx = mapControls.length; idx-->0; ) {
101             ctrl = mapControls[idx];
102             if (this.isCtrlNavigationActive(ctrl, evt)) {
103                 return true;
104             }
105         }
106         return OpenLayers.Handler.ModifiablePath.prototype.mouseup.apply(this, arguments);
107     },
108
109     addPoints: function(pixel) {
110         // redraw before last point. As we have a special style for last point, we
111         // need to redraw before last point after adding a new point (otherwise, it
112         // keeps special style forever)
113         var oldpoint = this.point;
114         OpenLayers.Handler.ModifiablePath.prototype.addPoints.apply(this, arguments);
115         this.layer.drawFeature(oldpoint);
116     },
117
118     isCtrlNavigationActive: function(ctrl, evt) {
119         var tolerance = 4, xDiff, yDiff;
120
121         if (!(ctrl instanceof OpenLayers.Control.Navigation)) {
122             return false;
123         }
124
125         if (ctrl.zoomBox &&
126             ctrl.zoomBox.active &&
127             ctrl.zoomBox.handler &&
128             ctrl.zoomBox.handler.active &&
129             ctrl.zoomBox.handler.dragHandler &&
130             ctrl.zoomBox.handler.dragHandler.start) {
131             return true;
132         }
133
134         if (!ctrl.dragPan ||
135             !ctrl.dragPan.active ||
136             !ctrl.dragPan.handler ||
137             !ctrl.dragPan.handler.started ||
138             !ctrl.dragPan.handler.start) {
139             return false;
140         }
141
142         // if mouse moved 4 or less pixels, consider it has not moved.
143         tolerance = 4;
144
145         xDiff = evt.xy.x - ctrl.dragPan.handler.start.x;
146         yDiff = evt.xy.y - ctrl.dragPan.handler.start.y;
147
148         if (Math.sqrt(Math.pow(xDiff,2) + Math.pow(yDiff,2)) <= tolerance) {
149             return false;
150         }
151         return true;
152     },
153
154     finalize: function(cancel) {
155         // do nothing. We don't want to finalize path
156     }
157 });
158
159 var styleMap = {
160     edit: new OpenLayers.StyleMap({
161         "default": new OpenLayers.Style({
162             pointRadius: "${radius}", // sized according to type attribute
163             fillColor: "#ffcc66",
164             strokeColor: "#ff9933",
165             strokeWidth: 2,
166             strokeOpacity: "${opacity}",
167             fillOpacity: "${opacity}"
168         },
169         {
170             context: {
171                 radius: function(feature) {
172                     var features;
173
174                     if (!(feature.geometry instanceof OpenLayers.Geometry.Point)) {
175                         return 0;
176                     }
177                     if (feature.type === "middle") {
178                         return 4;
179                     }
180                     features = feature.layer.features;
181                     if (OpenLayers.Util.indexOf(features, feature) === 0) {
182                         return 5;
183                     } else if (OpenLayers.Util.indexOf(features, feature) === features.length - 1) {
184                         return 5;
185                     }
186                     return 3;
187                 },
188                 opacity: function (feature) {
189                     if (feature.type === "middle") {
190                         return 0.5;
191                     } else {
192                         return 1;
193                     }
194                 }
195             }
196         }),
197
198         "select": new OpenLayers.Style({
199             externalGraphic: "icons/delete.png",
200             graphicHeight: 16
201         }),
202
203         "select_for_canvas": new OpenLayers.Style({
204             strokeColor: "blue",
205             fillColor: "lightblue"
206         })
207
208     }),
209
210     view: new OpenLayers.StyleMap({
211         "default": new OpenLayers.Style({
212             strokeColor: "blue",
213             strokeWidth: 5,
214             strokeOpacity: 0.7
215         })
216     })
217 };
218
219 var WGS84 = new OpenLayers.Projection("EPSG:4326");
220 var Mercator = new OpenLayers.Projection("EPSG:900913");
221
222 var SYJView = {
223     viewLayer: null,
224     editControl: null,
225     map: null,
226     wkt: new OpenLayers.Format.WKT({ internalProjection: Mercator, externalProjection: WGS84 }),
227     needsFormResubmit: false,
228     hasInitialGeom: false,
229
230     init: function() {
231         var externalGraphic, baseURL, baseLayer, layerOptions, extent, hidemessenger;
232
233         // is svg context, opera does not resolve links with base element is svg context
234         externalGraphic = styleMap.edit.styles.select.defaultStyle.externalGraphic;
235         baseURL = document.getElementsByTagName("base")[0].href;
236         styleMap.edit.styles.select.defaultStyle.externalGraphic = baseURL + externalGraphic;
237
238         this.map = new OpenLayers.Map('map', {
239             controls: [
240                 new OpenLayers.Control.Navigation(),
241                 new OpenLayers.Control.PanZoom(),
242                 new OpenLayers.Control.Attribution()
243             ],
244             theme: null
245         });
246
247         baseLayer = new OpenLayers.Layer.OSM("OSM", null, { wrapDateLine: true , attribution: SyjStrings.osmAttribution });
248
249         layerOptions = {format:     OpenLayers.Format.WKT,
250                         projection: WGS84,
251                         styleMap:   styleMap.view};
252         if (gLoggedInfo.creatorname) {
253             layerOptions.attribution = SyjStrings.routeBy + ' ' + '<strong>' + gLoggedInfo.creatorname + '</strong>';
254         }
255
256         this.viewLayer = new OpenLayers.Layer.Vector("View Layer", layerOptions);
257         this.map.addLayers([baseLayer, this.viewLayer]);
258
259         $("edit-btn").observe('click', (function() {
260             this.messenger.hide();
261             this.editMode();
262         }).bind(this));
263
264         $("geomform").ajaxize({
265                 presubmit: this.prepareForm.bind(this),
266                 onSuccess: this.saveSuccess.bind(this),
267                 onFailure: this.saveFailure.bind(this)
268                 });
269         SyjSaveUI.init().hide();
270
271         this.messenger = $('message');
272         hidemessenger = this.messenger.empty();
273         new CloseBtn(this.messenger, {
274             style: {
275                 margin: "-1em"
276             }
277         });
278         if (hidemessenger) {
279             this.messenger.hide();
280         }
281
282         if ($("geom_data").value) {
283             this.viewLayer.addFeatures([this.wkt.read($("geom_data").value)]);
284             extent = this.viewLayer.getDataExtent();
285             // XXX: ie has not guessed height of map main div yet during map
286             // initialisation. Now, it will read it correctly.
287             this.map.updateSize();
288             this.hasInitialGeom = true;
289         } else {
290             extent = new OpenLayers.Bounds(gMaxExtent.minlon, gMaxExtent.minlat, gMaxExtent.maxlon, gMaxExtent.maxlat)
291                                          .transform(WGS84, Mercator);
292         }
293         this.map.zoomToExtent(extent);
294         document.observe('simplebox:shown', this.observer.bindAsEventListener(this));
295     },
296
297     observer: function(evt) {
298         if (evt.eventName === "simplebox:shown" && evt.memo.element !== $("termsofusearea")) {
299             this.messenger.hide();
300         }
301     },
302
303     prepareForm: function(form) {
304         if (!loginMgr.logged && !$("geom_accept").checked) {
305             this.messenger.setMessage(SyjStrings.acceptTermsofuseWarn, "warn");
306             $("geom_accept_container").highlight('#F08080');
307             $("geom_accept").activate();
308             return false;
309         }
310
311         var line, realPoints, idx, handler;
312
313         line = new OpenLayers.Geometry.LineString();
314         realPoints = this.editControl.handler.realPoints;
315         for (idx = 0; idx < realPoints.length; idx++) {
316             line.addComponent(realPoints[idx].geometry.clone());
317         }
318         this.viewLayer.addFeatures(new OpenLayers.Feature.Vector(line));
319         handler = this.editControl.handler;
320         OpenLayers.Handler.ModifiablePath.prototype.finalize.apply(handler, arguments);
321         // we need to recreate them on next createFeature; otherwise
322         // they'll reference destroyed features
323         delete(handler.handlers.drag);
324         delete(handler.handlers.feature);
325         this.editControl.deactivate();
326
327         $("geom_data").value = this.wkt.write(new OpenLayers.Feature.Vector(line));
328         this.needsFormResubmit = false;
329         SyjSaveUI.disable.bind(SyjSaveUI).defer();
330         this.messenger.hide();
331         return true;
332     },
333
334     editMode: function() {
335         var components, point0, point, pixels, pixel, idx;
336
337         this.initEditControl();
338
339         this.editControl.activate();
340         if (this.viewLayer.features.length) {
341             components = this.viewLayer.features[0].geometry.components;
342             point0 = components[0];
343             if (point0) {
344                 pixel = this.map.getPixelFromLonLat(new OpenLayers.LonLat(point0.x, point0.y));
345                 this.editControl.handler.createFeature(pixel);
346                 this.editControl.handler.lastUp = pixel;
347                 pixels = [];
348                 for (idx = 1; idx < components.length; idx++) {
349                     point = components[idx];
350                     pixels.push(this.map.getPixelFromLonLat(new OpenLayers.LonLat(point.x, point.y)));
351                 }
352                 this.editControl.handler.addPoints(pixels);
353             }
354         }
355
356         this.viewLayer.destroyFeatures();
357
358         SyjEditUI.hide();
359         if (this.editControl.handler.realPoints && this.editControl.handler.realPoints.length >= 2) {
360             SyjSaveUI.show().disableSubmit();
361         } else {
362             SyjSaveUI.show().disable();
363         }
364     },
365
366     initEditControl: function() {
367         var styles;
368
369         if (this.editControl) {
370             return;
371         }
372
373         this.editControl = new OpenLayers.Control.DrawFeature(new OpenLayers.Layer.Vector(), OpenLayers.Handler.SyjModifiablePath, {
374             callbacks: {
375                 modify: function(f, line) {
376                     if (this.handler.realPoints.length < 2) {
377                         SyjSaveUI.show().disable();
378                     } else {
379                         SyjSaveUI.show().enable();
380                     }
381                 }
382             },
383
384             handlerOptions: {
385                 layerOptions: {
386                     styleMap: styleMap.edit
387                 }
388             }
389         });
390         this.map.addControl(this.editControl);
391         if (this.editControl.layer.renderer instanceof OpenLayers.Renderer.Canvas) {
392             // using externalGraphic with canvas renderer is definitively too buggy
393             styles = this.editControl.handler.layerOptions.styleMap.styles;
394             styles.select = styles.select_for_canvas;
395         }
396     },
397
398     saveSuccess: function(transport) {
399       if (!this.hasInitialGeom) { // we have created a new path, change location
400           location = "idx/" + transport.responseText;
401           return;
402       }
403
404       this.messenger.setMessage(SyjStrings.saveSuccess, "success");
405       SyjSaveUI.hide();
406       SyjEditUI.show();
407       document.title = $('geom_title').value;
408     },
409
410     saveFailure: function(transport) {
411         var httpCode = 0, message = "";
412
413         if (transport) {
414             httpCode = transport.getStatus();
415         }
416         switch (httpCode) {
417             case 0:
418                 message = SyjStrings.notReachedError;
419             break;
420             case 400:
421             case 404:
422                 message = SyjStrings.requestError; // default message
423                 if (transport.responseJSON) {
424                     switch (transport.responseJSON.message) {
425                         case "uniquepath":
426                             message = SyjStrings.uniquePathError;
427                         break;
428                         default:
429                         break;
430                     }
431                 }
432             break;
433             case 410:
434                 message = SyjStrings.gonePathError;
435             break;
436             case 500:
437                 message = SyjStrings.serverError;
438                 this.needsFormResubmit = true;
439             break;
440             default:
441                 message = SyjStrings.unknownError;
442             break;
443         }
444
445         this.editMode();
446         // is some cases, we let the user resubmit, in some other cases, he
447         // needs to modify the path before submitting again
448         if (this.needsFormResubmit) {
449             SyjSaveUI.enable();
450         }
451
452         this.messenger.setMessage(message, "error");
453     }
454 };
455
456 var SYJModalClass = Class.create({
457     type: "",
458
459     init: function() {
460         this.area = $(this.type + '_area');
461         this.messenger = $(this.type + "_message");
462         this.modalbox = new SimpleBox(this.area, {
463             closeMethods: ["onescapekey", "onouterclick", "onbutton"]
464         });
465
466         $(this.type + "_control_anchor").observe("click", function(evt) {
467             this.modalbox.show();
468             evt.stop();
469         }.bindAsEventListener(this));
470
471         document.observe('simplebox:shown', this.observer.bindAsEventListener(this));
472         document.observe('simplebox:hidden', this.observer.bindAsEventListener(this));
473
474         $(this.type + "form").ajaxize({
475             presubmit: this.presubmit.bind(this),
476             onSuccess: this.success.bind(this),
477             onFailure: this.failure.bind(this)
478         });
479     },
480
481     checkNotEmpty: function(input, message) {
482         if ($(input).value.strip().empty()) {
483             this.messenger.setMessage(message, "warn");
484             $(input).highlight('#F08080').activate();
485             return false;
486         }
487         return true;
488     },
489
490     observer: function(evt) {
491         var simplebox, input;
492
493         if (evt.eventName === "simplebox:shown" && evt.memo.element !== $("termsofusearea")) {
494             simplebox = evt.memo;
495             if (simplebox === this.modalbox) {
496                 input = this.area.select('input[type="text"]')[0];
497                 (function () {
498                     input.activate();
499                 }).defer();
500             } else {
501                 this.modalbox.hide();
502             }
503
504         } else if (evt.eventName === "simplebox:hidden" && evt.memo.element !== $("termsofusearea")) {
505             simplebox = evt.memo;
506             if (simplebox === this.modalbox) {
507                 this.reset();
508             }
509         }
510     },
511
512     failure: function(transport) {
513         var httpCode = 0, message = SyjStrings.unknownError, input; // default message error
514
515         if (transport) {
516             httpCode = transport.getStatus();
517         }
518
519         switch (httpCode) {
520             case 0:
521                 message = SyjStrings.notReachedError;
522             break;
523             case 400:
524             case 404:
525             case 410:
526                 message = SyjStrings.requestError;
527             break;
528             case 500:
529                 message = SyjStrings.serverError;
530             break;
531         }
532
533         this.messenger.setMessage(message, "error");
534         input = this.area.select('input[type="text"]')[0];
535         input.highlight('#F08080').activate();
536     },
537
538     reset: function() {
539         this.messenger.hide();
540         this.area.select('.message').invoke('setMessageStatus', null);
541     }
542 });
543
544 var SYJUserClass = Class.create(SYJModalClass, {
545     type: "user",
546     toubox: null,
547
548     init: function($super) {
549         $super();
550         $("termsofusearea").hide();
551
552         $$("#user_termsofuse_anchor, #geom_termsofuse_anchor").invoke('observe', "click", function(evt) {
553             if (!this.toubox) {
554                 $("termsofusearea").show();
555                 $("termsofuseiframe").setAttribute("src", evt.target.href);
556                 this.toubox = new SimpleBox($("termsofusearea"), {
557                     closeMethods: ["onescapekey", "onouterclick", "onbutton"]
558                 });
559             }
560             this.toubox.show();
561             evt.stop();
562         }.bindAsEventListener(this));
563
564         $$("#login_area_create > a").invoke('observe', 'click',
565             function(evt) {
566                 this.modalbox.show();
567                 evt.stop();
568             }.bindAsEventListener(this));
569
570         $("user_password").observe('contentchange', function(evt) {
571             if (evt.target.value.length < 6) {
572                 $("user_password-desc").setMessageStatus("warn");
573             } else {
574                 $("user_password-desc").setMessageStatus("success");
575             }
576         }.bindAsEventListener(this));
577
578         $("account-info").hide();
579         $("account-info-bullet").observe('click', function(evt) {
580             var elt = $("account-info");
581             if (elt.visible()) {
582                 evt.target.src = "icons/bullet_arrow_right.png";
583                 elt.hide();
584             } else {
585                 evt.target.src = "icons/bullet_arrow_down.png";
586                 elt.show();
587             }
588             evt.stop();
589         });
590     },
591
592     presubmit: function() {
593         if (!(this.checkNotEmpty("user_pseudo", SyjStrings.userEmptyWarn))) {
594             return false;
595         }
596
597         if (!($("user_pseudo").value.match(/^[a-zA-Z0-9_.]+$/))) {
598             this.messenger.setMessage(SyjStrings.invalidPseudo, "warn");
599             $("user_pseudo").highlight('#F08080').activate();
600             return false;
601         }
602
603         if (!(this.checkNotEmpty("user_password", SyjStrings.passwordEmptyWarn))) {
604             return false;
605         }
606
607         if ($("user_password").value.length < 6) {
608             $("user_password-desc").setMessageStatus("warn");
609             $("user_password").highlight('#F08080').activate();
610             return false;
611         }
612
613         if ($("user_password").value !== $("user_password_confirm").value) {
614             this.messenger.setMessage(SyjStrings.passwordNoMatchWarn, "warn");
615             $("user_password").highlight('#F08080').activate();
616             return false;
617         }
618
619         if (!(this.checkNotEmpty("user_email", SyjStrings.emailEmptyWarn))) {
620             return false;
621         }
622
623         if (!$("user_accept").checked) {
624             this.messenger.setMessage(SyjStrings.acceptTermsofuseWarn, "warn");
625             $("user_accept_container").highlight('#F08080');
626             $("user_accept").activate();
627             return false;
628         }
629
630         this.reset();
631         return true;
632     },
633
634     success: function(transport) {
635         loginMgr.login();
636         SYJView.messenger.setMessage(SyjStrings.userSuccess, "success");
637         this.modalbox.hide();
638         if (SYJView.needsFormResubmit) {
639             SYJView.messenger.addMessage(SyjStrings.canResubmit);
640             $("geom_submit").activate();
641         }
642     },
643
644     failure: function($super, transport) {
645         var httpCode = 0, focusInput = null, message = "";
646
647         if (transport) {
648             httpCode = transport.getStatus();
649         }
650
651         focusInput = null;
652         message = "";
653
654         switch (httpCode) {
655             case 400:
656                 if (transport.responseJSON) {
657                     switch (transport.responseJSON.message) {
658                         case "invalidemail":
659                             message = SyjStrings.emailInvalidWarn;
660                             focusInput = $("user_email");
661                         break;
662                         case "uniquepseudo":
663                             message = SyjStrings.uniqueUserError;
664                             focusInput = $("user_pseudo");
665                         break;
666                         case "uniqueemail":
667                             message = SyjStrings.uniqueEmailError;
668                             focusInput = $("user_email");
669                         break;
670                     }
671                 }
672             break;
673         }
674
675         if (message) {
676             this.messenger.setMessage(message, "error");
677             if (focusInput) {
678                 focusInput.highlight('#F08080').activate();
679             }
680             return;
681         }
682
683         $super(transport);
684     }
685 });
686 var SYJUser = new SYJUserClass();
687
688 var SYJLoginClass = Class.create(SYJModalClass, {
689     type: "login",
690
691     init: function($super) {
692         $super();
693     },
694
695     presubmit: function() {
696         if (!(this.checkNotEmpty("login_user", SyjStrings.userEmptyWarn))) {
697             return false;
698         }
699
700         this.reset();
701         return true;
702     },
703
704     success: function(transport) {
705         if (transport.responseText === "1") {
706             loginMgr.login(true);
707         } else {
708             loginMgr.login();
709         }
710         SYJView.messenger.setMessage(SyjStrings.loginSuccess, "success");
711         this.modalbox.hide();
712         if (SYJView.needsFormResubmit) {
713             SYJView.messenger.addMessage(SyjStrings.canResubmit);
714             $("geom_submit").activate();
715         }
716     },
717
718     failure: function($super, transport) {
719         var httpCode = 0, focusInput = null, message = "";
720
721         if (transport) {
722             httpCode = transport.getStatus();
723         }
724
725         focusInput = null;
726         message = "";
727
728         switch (httpCode) {
729             case 403:
730                 message = SyjStrings.loginFailure;
731                 focusInput = $("login_user");
732             break;
733         }
734
735         if (message) {
736             this.messenger.setMessage(message, "error");
737             if (focusInput) {
738                 focusInput.highlight('#F08080').activate();
739             }
740             return;
741         }
742
743         $super(transport);
744     }
745 });
746 var SYJLogin = new SYJLoginClass();
747
748 var SYJNewpwdClass = Class.create(SYJModalClass, {
749     type: "newpwd",
750
751     presubmit: function() {
752         if (!(this.checkNotEmpty("newpwd_email", SyjStrings.emailEmptyWarn))) {
753             return false;
754         }
755         this.reset();
756         return true;
757     },
758     success: function(transport) {
759         SYJView.messenger.setMessage(SyjStrings.newpwdSuccess, "success");
760         this.modalbox.hide();
761     }
762
763 });
764 var SYJNewpwd = new SYJNewpwdClass();
765
766 var loginMgr = Object.extend(gLoggedInfo, {
767     controlsdeck: null,
768
769     updateUI: function() {
770         if (!this.controlsdeck) {
771             this.controlsdeck = new Deck("login_controls");
772         }
773         if (this.logged) {
774             this.controlsdeck.setIndex(1);
775             $$(".logged-hide").invoke('hide');
776             $$(".logged-show").invoke('show');
777         } else {
778             this.controlsdeck.setIndex(0);
779             $$(".logged-hide").invoke('show');
780             $$(".logged-show").invoke('hide');
781         }
782
783         if (this.iscreator) {
784             $("data_controls").show();
785         } else {
786             $("data_controls").hide();
787         }
788     },
789
790     login: function(aIsCreator) {
791         if (typeof aIsCreator === "boolean") {
792             this.iscreator = aIsCreator;
793         }
794         this.logged = true;
795         this.updateUI();
796     }
797 });
798
799 document.observe("dom:loaded", function() {
800     SYJLogin.init();
801     SYJUser.init();
802     SYJView.init();
803     SYJNewpwd.init();
804     loginMgr.updateUI();
805 });