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