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