]> dev.renevier.net Git - syp.git/blob - js/admin.js
interface to change password
[syp.git] / js / admin.js
1 /* Copyright (c) 2009 Arnaud Renevier, Inc, published under the modified BSD
2  * license. */
3
4 // drag feature with tolerance
5 OpenLayers.Control.SypDragFeature = OpenLayers.Class (OpenLayers.Control.DragFeature, {
6     startPixel: null,
7     dragStart: null,
8     pixelTolerance : 0,
9     timeTolerance: 300,
10
11     downFeature: function(pixel) {
12         OpenLayers.Control.DragFeature.prototype.downFeature.apply(this, arguments);
13         this.dragStart = (new Date()).getTime(); 
14         this.startPixel = pixel; 
15     },
16
17     doneDragging: function(pixel) {
18         OpenLayers.Control.DragFeature.prototype.doneDragging.apply(this, arguments);
19         // Check tolerance. 
20         var passesTimeTolerance =  
21                     (new Date()).getTime() > this.dragStart + this.timeTolerance; 
22
23         var xDiff = this.startPixel.x - pixel.x; 
24         var yDiff = this.startPixel.y - pixel.y; 
25
26         var passesPixelTolerance =  
27         Math.sqrt(Math.pow(xDiff,2) + Math.pow(yDiff,2)) > this.pixelTolerance; 
28
29         if(passesTimeTolerance && passesPixelTolerance){ 
30             this.onComplete(this.feature, pixel);    
31         } else { 
32             var feature = this.feature; 
33             var res = this.map.getResolution(); 
34             this.feature.geometry.move(res * (this.startPixel.x - this.lastPixel.x), 
35                     res * (this.lastPixel.y - this.startPixel.y)); 
36             this.layer.drawFeature(this.feature); 
37         }
38         this.layer.drawFeature(this.feature, "select");
39     },
40
41     moveFeature: function(pixel) {
42         OpenLayers.Control.DragFeature.prototype.moveFeature.apply(this, arguments);
43         this.layer.drawFeature(this.feature, "temporary");
44     },
45
46     overFeature: function (feature) {
47         // can only drag and drop currently selected feature
48         if (feature != Admin.currentFeature) {
49             return;
50         }
51         OpenLayers.Control.DragFeature.prototype.overFeature.apply(this, arguments);
52     },
53
54     CLASS_NAME: "OpenLayers.Control.SypDragFeature"
55 });
56
57 var Admin = {
58     Markers: {
59         ICON: "media/marker-normal.png",
60         SELECT_ICON: "media/marker-selected.png",
61         TEMPORARY_ICON: "media/marker-temp.png",
62         HEIGHT: 25
63     },
64
65     map: null,
66     baseLayer: null,
67     dataLayer: null,
68     selFeatureControl: null,
69     moveFeatureControl: null,
70     addFeatureControl: null,
71
72     currentFeature: null,
73     currentFeatureLocation: null,
74
75     init: function () {
76         this.map = new OpenLayers.Map ("map", {
77                 controls:[
78                     new OpenLayers.Control.Navigation (),
79                     new OpenLayers.Control.PanZoom ()
80                 ],
81                 projection: new OpenLayers.Projection("EPSG:900913"),
82                 displayProjection: new OpenLayers.Projection("EPSG:4326")
83          });
84
85          this.baseLayer = this.createBaseLayer ();
86          this.map.addLayer(this.baseLayer);
87
88          this.map.setCenter(new OpenLayers.LonLat(0, 0), 0);
89          if (sypSettings.loggedUser) {
90             this.dataLayer = this.createDataLayer (sypSettings.loggedUser);
91             this.map.addLayer(this.dataLayer);
92             this.reset();
93          }
94     },
95
96     reset: function() {
97         this.addFeatureControl.deactivate();
98         this.moveFeatureControl.deactivate();
99         this.selFeatureControl.activate();
100         this.checkForFeatures();
101         $("#newfeature_button").show().val(SypStrings.AddItem);
102         $("#newfeature_button").unbind("click").click(function () {
103             Admin.addNewFeature();
104         });
105     },
106
107     createBaseLayer: function () {
108         return new OpenLayers.Layer.OSM("OSM");
109     },
110
111     createDataLayer: function (user) {
112         var styleMap = new OpenLayers.StyleMap (
113                         {"default": {
114                              externalGraphic: this.Markers.ICON,
115                              graphicHeight: this.Markers.HEIGHT || 32 
116                                 },
117                          "temporary": { 
118                              externalGraphic: this.Markers.TEMPORARY_ICON,
119                              graphicHeight: this.Markers.HEIGHT || 32 
120                          },
121                          "select": { 
122                              externalGraphic: this.Markers.SELECT_ICON,
123                              graphicHeight: this.Markers.HEIGHT || 32 
124                     }});
125
126         var layer = new OpenLayers.Layer.GML("KML", "items.php?from_user=" + encodeURIComponent(user),
127            {
128             styleMap: styleMap,
129             format: OpenLayers.Format.KML, 
130             projection: this.map.displayProjection,
131             eventListeners: { scope: this,
132                 loadend: this.dataLayerEndLoad
133             }
134        });
135
136         // controls
137         this.selFeatureControl = this.createSelectFeatureControl(layer)
138         this.map.addControl(this.selFeatureControl);
139         this.moveFeatureControl = this.createMoveFeatureControl(layer)
140         this.map.addControl(this.moveFeatureControl);
141         this.addFeatureControl = this.createNewfeatureControl();
142         this.map.addControl(this.addFeatureControl);
143
144         return layer;
145     },
146
147     createMoveFeatureControl: function (layer) {
148         var control = new OpenLayers.Control.SypDragFeature(
149                 layer, {
150                          });
151         return control;
152     },
153
154     createSelectFeatureControl: function (layer) {
155         var control = new OpenLayers.Control.SelectFeature(
156                 layer, {
157                         onSelect: OpenLayers.Function.bind(this.onFeatureSelect, this)
158                          });
159         return control;
160     },
161
162     createNewfeatureControl: function () {
163         var control = new OpenLayers.Control ();
164         var handler = new OpenLayers.Handler.Click(control, {
165                 'click': OpenLayers.Function.bind(FeatureMgr.add, FeatureMgr)
166             });
167         control.handler = handler;
168         return control;
169     },
170
171     onFeatureSelect: function (feature) {
172         this.showEditor(feature);
173         FeatureMgr.reset();
174         this.selFeatureControl.deactivate();
175         this.moveFeatureControl.activate();
176     },
177
178     closeEditor: function() {
179         if ($("#editor").css("display") == "none") {
180             return;
181         }
182         if (this.currentFeature && this.currentFeature.layer) {
183             this.selFeatureControl.unselect(this.currentFeature);
184         }
185         this.currentFeature = null;
186         this.currentFeatureLocation = null;
187         $("#img").removeAttr('src');
188         $("#img").parent().html($("#img").parent().html());
189         $("#img").parent().show();
190         $("#title, #description").val("");
191         $("#editor").hide();
192         // do it once before hidding and once after hidding to work in all cases
193         $("#title, #description").val(""); 
194         $("#image_file").parent().html($("#image_file").parent().html());
195         $(document).unbind("keydown");
196         this.checkForFeatures();
197         this.reset();
198     },
199
200     showEditor: function (feature) {
201         $("#newfeature_button").hide();
202         userMgr.close();
203
204         if (feature.fid) {
205             $("#delete").show();
206         } else {
207             $("#delete").hide();
208         }
209         $(document).unbind("keydown").keydown(function(e) { 
210             if (e.keyCode == 27) {
211                 Admin.cancelCurrentFeature()
212                 e.preventDefault();
213             }
214         });
215         this.currentFeature = feature;
216         this.currentFeatureLocation = new OpenLayers.Pixel(feature.geometry.x, feature.geometry.y);
217         $("#editor").show();
218         $("#instructions").text(SypStrings.DragDropHowto);
219         $("#title").val(feature.attributes.name);
220         var fullDesc = $(feature.attributes.description).parent();
221         $("#description").val(fullDesc.find('p').text());
222         var src = fullDesc.find('img').attr('src');
223         if (src) {
224             $("#img").parent().show();
225             $("#img").attr('src', src);
226             $("#image_file").parent().hide();
227             $("#image_delete").show();
228         } else {
229             $("#img").parent().hide();
230             $("#image_file").parent().show();
231             $("#image_delete").hide();
232         }
233         $("#title").select().focus(); 
234     },
235
236     dataLayerEndLoad: function() {
237         // only set zoom extent once
238         this.dataLayer.events.unregister('loadend', this, this.dataLayerEndLoad);
239         this.dataLayer.events.register('loadend', this, this.checkForFeatures);
240
241         if (!this.checkForFeatures()) {
242             return;
243         }
244
245         var map = this.map;
246         var orig = this.Utils.mbr (this.dataLayer);
247         var centerBounds = new OpenLayers.Bounds();
248
249         var mapProj = map.getProjectionObject();
250         var sypOrigProj = new OpenLayers.Projection("EPSG:4326");
251
252         var bottomLeft = new OpenLayers.LonLat(orig[0],orig[1]);
253         bottomLeft = bottomLeft.transform(sypOrigProj, mapProj);
254         var topRight = new OpenLayers.LonLat(orig[2],orig[3])
255         topRight = topRight.transform(sypOrigProj, mapProj);
256
257         centerBounds.extend(bottomLeft);
258         centerBounds.extend(topRight);
259         map.zoomToExtent(centerBounds);
260     },
261
262     checkForFeatures: function () {
263         var features = this.dataLayer.features;
264         if (features.length != 0) {
265             $("#instructions").text(SypStrings.SelectHowto);
266         }
267         return !!features.length;
268     },
269
270     addNewFeature: function () {
271         userMgr.close();
272
273         function cancel() {
274             $(document).unbind("keydown");
275             Admin.reset()
276         }
277         $(document).unbind("keydown").keydown(function(e) { 
278             if (e.keyCode == 27) {
279                 e.preventDefault();
280                 cancel();
281             }
282         });
283
284         $("#newfeature_button").val("annuler");
285         $("#newfeature_button").unbind("click").click(cancel);
286
287         $("#instructions").text(SypStrings.AddHowto);
288         this.selFeatureControl.deactivate();
289         this.addFeatureControl.activate();
290         FeatureMgr.reset();
291     },
292
293     cancelCurrentFeature: function() {
294         if (AjaxMgr.running) {
295             return false;
296         }
297         var feature = this.currentFeature;
298         if (feature) {
299             if (feature.fid) {
300                 FeatureMgr.move (feature, this.currentFeatureLocation);
301             } else {
302                 this.dataLayer.removeFeatures([feature]);
303             }
304         }
305         this.closeEditor();
306         return true;
307     },
308
309     reloadLayer: function (layer) {
310         layer.destroyFeatures();
311         layer.loaded = false;
312         layer.loadGML();
313     },
314
315     Utils: {
316         /* minimum bounds rectangle containing all feature locations.
317          * FIXME: if two features are close, but separated by 180th meridian,
318          * their mbr will span the whole earth. Actually, 179° lon and -170°
319          * lon are considerated very near.
320          */
321         mbr: function (layer) {
322             var features = [];
323             var map = layer.map;
324
325             var mapProj = map.getProjectionObject();
326             var sypOrigProj = new OpenLayers.Projection("EPSG:4326");
327
328             for (var i =0; i < layer.features.length; i++) {
329                 if (layer.features[i].cluster) {
330                     features = features.concat(layer.features[i].cluster);
331                 } else {
332                     features = features.concat(layer.features);
333                 }
334             }
335
336             var minlon = 180;
337             var minlat = 88;
338             var maxlon = -180;
339             var maxlat = -88;
340
341             if (features.length == 0) {
342                 // keep default values
343             } else if (features.length == 1) {
344                 // in case there's only one feature, we show an area of at least 
345                 // 4 x 4 degrees
346                 var pos = features[0].geometry.getBounds().getCenterLonLat().clone();
347                 var lonlat = pos.transform(mapProj, sypOrigProj);
348
349                 minlon = Math.max (lonlat.lon - 2, -180);
350                 maxlon = Math.min (lonlat.lon + 2, 180);
351                 minlat = Math.max (lonlat.lat - 2, -90);
352                 maxlat = Math.min (lonlat.lat + 2, 90);
353             } else {
354                 for (var i = 0; i < features.length; i++) {
355                     var pos = features[i].geometry.getBounds().getCenterLonLat().clone();
356                     var lonlat = pos.transform(mapProj, sypOrigProj);
357                     minlon = Math.min (lonlat.lon, minlon);
358                     minlat = Math.min (lonlat.lat, minlat);
359                     maxlon = Math.max (lonlat.lon, maxlon);
360                     maxlat = Math.max (lonlat.lat, maxlat);
361                 }
362             }
363
364             return [minlon, minlat, maxlon, maxlat];
365
366         },
367
368
369         escapeHTML: function (str) {
370             if (!str) {
371                 return "";
372             }
373             return str.
374              replace(/&/gm, '&amp;').
375              replace(/'/gm, '&#39;').
376              replace(/"/gm, '&quot;').
377              replace(/>/gm, '&gt;').
378              replace(/</gm, '&lt;');
379         },
380
381         startsWith: function (str, prefix) {
382             return (str.slice(0, prefix.length) == prefix);
383         },
384
385         indexOf: function (array, item) {
386             if (array.indexOf !== undefined) {
387                 return array.indexOf(item);
388             } else {
389                 return OpenLayers.Util.indexOf(array, item);
390             }
391         }
392     }
393 }
394
395 var FeatureMgr = {
396     reset: function() {
397         this.commError("");
398     },
399
400     add: function(evt) {
401         var map = Admin.map;
402         var pos = map.getLonLatFromViewPortPx(evt.xy);
403         feature = this.update (null, pos, "", "", "");
404         Admin.addFeatureControl.deactivate();
405         Admin.selFeatureControl.select(feature);
406     },
407
408     move: function (feature, aLocation) {
409         if (!feature || !aLocation) {
410             return;
411         }
412         var curLoc = feature.geometry;
413         feature.geometry.move(aLocation.x - curLoc.x, aLocation.y - curLoc.y);
414         feature.layer.drawFeature(feature); 
415     },
416
417     update: function(feature, lonlat, imgurl, title, description) {
418         var point = new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat);
419         if (!feature) {
420             feature = new OpenLayers.Feature.Vector(point);
421             Admin.dataLayer.addFeatures([feature]);
422         } else {
423             this.move (feature, point);
424         }
425         feature.attributes.name = title;
426         feature.attributes.description = "<p>" + Admin.Utils.escapeHTML(description) + "</p>"
427                                 + "<img src=\"" + imgurl + "\">"
428         return feature;
429     },
430
431     del: function (feature) {
432         var form = $("#feature_delete");
433         form.find('input[name="fid"]').val(feature.fid);
434         AjaxMgr.add({
435             form: form,
436             oncomplete: OpenLayers.Function.bind(this.ajaxReply, this),
437             throbberid: "editor_throbber"
438         });
439     },
440
441     save: function (feature) {
442         var x = feature.geometry.x;
443         var y = feature.geometry.y;
444
445         var mapProj = feature.layer.map.getProjectionObject();
446         var lonlat = new OpenLayers.LonLat(x, y).
447                                     transform(mapProj,
448                                               new OpenLayers.Projection("EPSG:4326"));
449         var form = $("#feature_update");
450         form.find('input[name="lon"]').val(lonlat.lon);
451         form.find('input[name="lat"]').val(lonlat.lat);
452         form.find('input[name="fid"]').val(feature.fid);
453         form.find('input[name="keep_img"]').val(
454             $("#img").attr("src") ? "yes": "no"
455         );
456
457         if (feature.fid) {
458             form.find('input[name="request"]').val("update");
459         } else {
460             form.find('input[name="request"]').val("add");
461         }
462         AjaxMgr.add({
463             form: form,
464             oncomplete: OpenLayers.Function.bind(this.ajaxReply, this),
465             throbberid: "editor_throbber"
466         });
467     },
468
469     ajaxReply: function (data) {
470         if (!data) {
471             this.commError(SypStrings.ServerError);
472             return;
473         }
474
475         var xml = new OpenLayers.Format.XML().read(data);
476
477         switch (xml.documentElement.nodeName.toLowerCase()) {
478             case "error":
479                 switch (xml.documentElement.getAttribute("reason")) {
480                     case "unauthorized":
481                         pwdMgr.reset();
482                         $("#cookie_warning").show();
483                         this.reset();
484                         Admin.cancelCurrentFeature();
485                         Admin.reset();
486                         userMgr.uninit();
487                     break;
488                     case "server":
489                         this.commError(SypStrings.ServerError);
490                         $("title").focus();
491                     break;
492                     case "unreferenced":
493                         this.commError(SypStrings.UnreferencedError);
494                         Admin.reloadLayer(Admin.dataLayer);
495                         Admin.closeEditor();
496                     break;
497                     case "nochange":
498                         this.commError(SypStrings.NochangeError);
499                         Admin.closeEditor();
500                     break;
501                     case "request":
502                         this.commError(SypStrings.RequestError);
503                         $("title").focus();
504                     break;
505                     case "toobig":
506                         this.commError(SypStrings.ToobigError);
507                         $("#image_file").parent().html($("#image_file").parent().html());
508                         $("#image_file").focus();
509                     break;
510                     case "notimage":
511                         this.commError(SypStrings.NotimageError);
512                         $("#image_file").parent().html($("#image_file").parent().html());
513                         $("#image_file").focus();
514                     break;
515                     default:
516                         this.commError(SypStrings.UnconsistentError);
517                         $("title").focus();
518                     break;
519                 }
520             break;
521             case "success":
522                 switch (xml.documentElement.getAttribute("request")) {
523                     case "del":
524                         this.commSuccess(SypStrings.DelSucces);
525                         var someFeature = false;
526                         var self = this;
527                         $.each($(xml).find("FEATURE,feature"), function () {
528                              someFeature = true;
529                              var id = parseFloat($(this).find("ID:first,id:first").text());
530                              if ((id === null) || isNaN (id)) {
531                                 return;;
532                              }
533                              var features = Admin.dataLayer.features;
534                              for (var idx = 0; idx < features.length; idx++) {
535                                  if (features[idx].fid == id) {
536                                      Admin.dataLayer.removeFeatures([features[idx]]);
537                                  }
538                              }
539                         });
540                         if (someFeature == false) {
541                             this.commError(SypStrings.UnconsistentError);
542                         } else {
543                             Admin.closeEditor();
544                         }
545                     break;
546                     case "update":
547                     case "add":
548                         var someFeature = false;
549                         var self = this;
550                         $.each($(xml).find("FEATURE,feature"), function () {
551                                 someFeature = true;
552                                 var id = parseFloat($(this).find("ID:first,id:first").text());
553                                 if ((id === null) || isNaN (id)) {
554                                     return;;
555                                 }
556
557                                 var lon = parseFloat($(this).find("LON:first,lon:first").text());
558                                 if ((typeof (lon) != "number") || isNaN (lon) ||
559                                         (lon < -180) || (lon > 180)) {
560                                     return;;
561                                 }
562
563                                 var lat = parseFloat($(this).find("LAT:first,lat:first").text());
564                                 if ((typeof (lat) != "number") || isNaN (lat) ||
565                                         (lat < -90) || (lat > 90)) {
566                                     return;;
567                                 }
568
569                                 var mapProj = Admin.map.getProjectionObject();
570                                 var lonlat = new OpenLayers.LonLat (lon, lat).
571                                                 transform( new OpenLayers.Projection("EPSG:4326"), mapProj);
572
573                                 var imgurl = $(this).find("IMGURL:first,imgurl:first").text();
574                                 var title = $(this).find("HEADING:first,heading:first").text();
575                                 var description = $(this).find("DESCRIPTION:first,description:first").text();
576
577                                 feature = self.update (Admin.currentFeature, lonlat, imgurl, title, description); 
578                                 feature.fid = id;
579                         });
580
581                         if (someFeature == false) {
582                             this.commError(SypStrings.UnconsistentError);
583                         } else {
584                             this.commSuccess(SypStrings.UpdateSucces);
585                             Admin.closeEditor();
586                         }
587
588                     break;
589                     default:
590                         this.commError(SypStrings.UnconsistentError);
591                    break;
592                 }
593             break;
594             default:
595                 this.commError(SypStrings.UnconsistentError);
596             break;
597         }
598     },
599
600     commSuccess: function (message) {
601         $("#server_comm").text(message);
602         $("#server_comm").removeClass("error success").addClass("success");
603     },
604
605     commError: function (message) {
606         $("#server_comm").text(message);
607         $("#server_comm").removeClass("error success").addClass("error");
608     }
609 }
610
611 /* maintains a queue of ajax queries, so I'm sure they all execute in the same
612  * order they were defined */
613 var AjaxMgr = {
614     _queue: [],
615
616     running: false,
617
618     add: function(query) {
619         this._queue.push(query);
620         if (this._queue.length > 1) {
621             return;
622         } else {
623             this._runQuery(query);
624         }
625     },
626
627     _runQuery: function(query) {
628         var self = this;
629         $('#api_frame').one("load", function() {
630             self.running = false;
631             self._reqEnd();
632             if (query.throbberid) {
633                 $("#" + query.throbberid).css("visibility", "hidden");
634             }
635             if (typeof (query.oncomplete) == "function") {
636                 var body = null;
637                 try {
638                     if (this.contentDocument) {
639                         body = this.contentDocument.body;
640                     } else if (this.contentWindow) {
641                         body = this.contentWindow.document.body;
642                     } else {
643                         body = document.frames[this.id].document.body;
644                     }
645                 } catch (e) {}
646                     if (body) {
647                         query.oncomplete(body.innerHTML);
648                     } else {
649                         query.oncomplete(null);
650                     }
651             }
652         });
653         query.form.attr("action", "api.php");
654         query.form.attr("target", "api_frame");
655         query.form.attr("method", "post");
656         this.running = true;
657         query.form.get(0).submit();
658         if (query.throbberid) {
659             $("#" + query.throbberid).css("visibility", "visible");
660         }
661         if (typeof (query.onsend) == "function") {
662             query.onsend();
663         }
664     },
665
666     _reqEnd: function() {
667         this._queue.shift();
668         if (this._queue.length > 0) {
669             this._reqEnd(this._queue[0]);
670         }
671     }
672 }
673
674 var pwdMgr = {
675
676     init: function () {
677         $("#login_form").submit(this.submit);
678         $("#user").focus().select();
679     },
680
681     reset: function() {
682         this.commError ("");
683         $("#login_area").show();
684         $("#password").val("");
685         $("#user").val(sypSettings.loggedUser).focus().select();
686     },
687
688     submit: function () {
689         try {
690             pwdMgr.commError("");
691             var req = {
692                 form:  $("#login_form"),
693                 throbberid: "pwd_throbber",
694                 onsend: function() {
695                     $("#login_error").hide();
696
697                     // we need a timeout; otherwise those fields will not be submitted
698                     window.setTimeout(function() { 
699                             // removes focus from #password before disabling it. Otherwise, opera
700                             // prevents re-focusing it after re-enabling it.
701                             $("#user, #password").blur(); 
702                             $("#login_submit, #user, #password").attr("disabled", "disabled");
703                     }, 0)
704                 },
705                 oncomplete: OpenLayers.Function.bind(pwdMgr.ajaxReply, pwdMgr)
706             };
707             AjaxMgr.add(req);
708         } catch(e) {}
709         return false;
710     },
711
712     ajaxReply: function (data) {
713         // here, we need a timeout because onsend timeout sometimes has not been triggered yet
714         window.setTimeout(function() {
715             $("#login_submit, #user, #password").removeAttr("disabled");
716         }, 0);
717
718         if (!data) {
719             this.commError(SypStrings.ServerError);
720             $("#login_error").show();
721             window.setTimeout(function() {
722                     $("#user").focus().select();
723             }, 0);
724             return;
725         }
726         var xml = new OpenLayers.Format.XML().read(data);
727
728         switch (xml.documentElement.nodeName.toLowerCase()) {
729             case "error":
730                 switch (xml.documentElement.getAttribute("reason")) {
731                     case "server":
732                         this.commError(SypStrings.ServerError);
733                     break;
734                     case "unauthorized":
735                         this.commError(SypStrings.UnauthorizedError);
736                     break;
737                     case "request":
738                         this.commError(SypStrings.RequestError);
739                     break;
740                     default:
741                         this.commError(SypStrings.UnconsistentError);
742                     break;
743                 }
744                 $("#login_error").show();
745                 window.setTimeout(function() {
746                         $("#user").focus().select();
747                 }, 0);
748             break;
749             case "success":
750                 $("#login_area").hide();
751
752                 user = $(xml).find("USER,user").text();
753                 sypSettings.loggedUser = user;
754
755                 if (sypSettings.loggedUser == "admin")  {
756                     userMgr.init();
757                 }
758
759                 if (Admin.selFeatureControl) {
760                     Admin.selFeatureControl.destroy();
761                 }
762                 if (Admin.moveFeatureControl) {
763                     Admin.moveFeatureControl.destroy();
764                 }
765                 if (Admin.addFeatureControl) {
766                     Admin.addFeatureControl.destroy();
767                 }
768                 if (Admin.dataLayer) {
769                     Admin.dataLayer.destroy();
770                 }
771
772                 Admin.dataLayer = Admin.createDataLayer(user);
773                 Admin.map.addLayer(Admin.dataLayer);
774                 Admin.reset();
775
776             break;
777             default:
778                 this.commError(SypStrings.UnconsistentError);
779             break;
780         }
781     },
782
783     commError: function (message) {
784         $("#login_error").text(message);
785         if (message) {
786             $("#login_error").show();
787         } else {
788             $("#login_error").hide();
789         }
790     }
791 }
792
793 var userMgr = {
794     _adduserDisplayed: false,
795     _changepassDisplayed: false,
796
797     init: function() {
798         $("#user_close").unbind("click").click(function () {
799             userMgr.close()
800         });
801
802         $("#change_pass").unbind("click").click(function() {
803             userMgr.toggleChangePass();
804             return false;
805         });
806         $("#changepass").unbind("submit").submit(function() {
807             try {
808                 userMgr.changepass();
809             } catch(e) {}
810             return false;
811         });
812
813         if (sypSettings.loggedUser != "admin") {
814             return;
815         }
816
817         $("#add_user").show();
818         $("#add_user").unbind("click").click(function () {
819             userMgr.toggleAddUser();
820             return false;
821         });
822         $("#newuser").unbind("submit").submit(function() {
823             try {
824                 userMgr.add();
825             } catch(e) {}
826             return false;
827         });
828
829     },
830
831     disableForms: function() {
832         $("#newuser_name, #newuser_password, #newuser_password_confirm, #newuser_submit").attr("disabled", "disabled");
833         $("#pass_current, #pass_new, #pass_new_confirm, #pass_submit").attr("disabled", "disabled");
834     },
835
836     enableForms: function() {
837         $("#newuser_name, #newuser_password, #newuser_password_confirm, #newuser_submit").removeAttr("disabled");
838         $("#pass_current, #pass_new, #pass_new_confirm, #pass_submit").removeAttr("disabled");
839     },
840
841     resetForms: function() {
842         $("#newuser_name, #newuser_password, #newuser_password_confirm").val("");
843         $("#pass_current, #pass_new, #pass_new_confirm").val("");
844     },
845
846     uninit: function() {
847         this.close();
848         $("#add_user").unbind("click");
849         $("#add_user").hide();
850         $("#change_pass").unbind("click");
851         $("#user_close").unbind("click");
852         $("#newuser").unbind("submit");
853         $("#changepass").unbind("submit");
854     },
855
856     close: function() {
857         this.closeChangePass();
858         this.closeAddUser();
859     },
860
861     toggleChangePass: function() {
862         if (this._changepassDisplayed) {
863             this.closeChangePass();
864         } else {
865             this.showChangePass();
866         }
867     },
868
869     showChangePass: function() {
870         if (!Admin.cancelCurrentFeature()) {
871             return;
872         }
873         this.closeAddUser();
874
875         $(document).unbind("keydown").keydown(function(e) { 
876             if (e.keyCode == 27) {
877                 userMgr.closeChangePass()
878                 e.preventDefault();
879             }
880         });
881
882         this.resetForms();
883         this.enableForms();
884         $("#user_area, #changepass").show();
885         this.commError("");
886
887         // XXX: setTimeout needed because otherwise, map becomes hidden in IE. Why ??
888         window.setTimeout(function() { 
889             $("#pass_current").focus();
890         }, 0);
891
892         this._changepassDisplayed = true;
893     },
894
895     closeChangePass: function() {
896         if (!this._changepassDisplayed) {
897             return;
898         }
899         $("#user_area, #changepass").hide();
900         $(document).unbind("keydown");
901         this._changepassDisplayed = false;
902     },
903
904     changepass: function() {
905         var newpass = $("#pass_new").val();
906         var newpass_confirm = $("#pass_new_confirm").val();
907         if (newpass != newpass_confirm) {
908             this.commError(SypStrings.userPasswordmatchError);
909             $("#pass_new").focus().select();
910             return;
911         }
912
913         var curpass = $("#pass_current").val();
914         if (newpass == curpass) {
915             this.commError(SypStrings.changeSamePass);
916             $("#pass_new").focus().select();
917             return;
918         }
919
920         this.commError("");
921
922         AjaxMgr.add({
923             form: $("#changepass"),
924             oncomplete: OpenLayers.Function.bind(this.ajaxReply, this),
925             throbberid: "user_throbber",
926             onsend: function() { 
927                 // we need a timeout; otherwise those fields will not be submitted
928                 window.setTimeout(function() {
929                     // removes focus from #password before disabling it. Otherwise, opera
930                     // prevents re-focusing it after re-enabling it.
931                     $("#pass_current, #pass_new, #pass_new_confirm").blur(); 
932                     userMgr.disableForms();
933                 }, 0);
934             }
935         });
936     },
937
938     toggleAddUser: function() {
939         if (this._adduserDisplayed) {
940             this.closeAddUser();
941         } else {
942             this.showAddUser();
943         }
944     },
945
946     showAddUser: function() {
947         if (!Admin.cancelCurrentFeature()) {
948             return;
949         }
950
951         this.closeChangePass();
952
953         $(document).unbind("keydown").keydown(function(e) { 
954             if (e.keyCode == 27) {
955                 userMgr.closeAddUser()
956                 e.preventDefault();
957             }
958         });
959
960         $("#user_area, #newuser").show();
961         this.resetForms();
962         this.enableForms();
963         this.commError("");
964
965         // XXX: setTimeout needed because otherwise, map becomes hidden in IE. Why ??
966         window.setTimeout(function() { 
967             $("#newuser_name").focus();
968         }, 0);
969
970         this._adduserDisplayed = true;
971     },
972
973     closeAddUser: function() {
974         if (!this._adduserDisplayed) {
975             return;
976         }
977         $("#user_area, #newuser").hide();
978         $(document).unbind("keydown");
979         this._adduserDisplayed = false;
980     },
981
982     add: function() {
983         var newuser_name = $("#newuser_name").val();
984         if (!newuser_name) {
985             this.commError(SypStrings.newUserNonameError);
986             $("#newuser_name").focus();
987             return;
988         }
989
990         var newuser_pass = $("#newuser_password").val();
991         var newuser_pass_confirm = $("#newuser_password_confirm").val();
992         if (newuser_pass != newuser_pass_confirm) {
993             this.commError(SypStrings.userPasswordmatchError);
994             $("#newuser_password").focus().select();
995             return;
996         }
997
998         this.commError("");
999
1000         AjaxMgr.add({
1001             form: $("#newuser"),
1002             oncomplete: OpenLayers.Function.bind(this.ajaxReply, this),
1003             throbberid: "user_throbber",
1004             onsend: function() { 
1005                 // we need a timeout; otherwise those fields will not be submitted
1006                 window.setTimeout(function() {
1007                     // removes focus from #password before disabling it. Otherwise, opera
1008                     // prevents re-focusing it after re-enabling it.
1009                     $("#newuser_name, #newuser_password, #newuser_password_confirm").blur(); 
1010                     userMgr.disableForms();
1011                 }, 0);
1012             }
1013         });
1014     },
1015
1016     ajaxReply: function (data) {
1017         if (!data) {
1018             // here, we need a timeout because onsend timeout sometimes has not been triggered yet
1019             var self = this;
1020             window.setTimeout(function() {
1021                 self.enableForms();
1022              }, 0);
1023             this.commError(SypStrings.ServerError);
1024             return;
1025         }
1026
1027         var needFormEnabling = true;
1028         var focusEl = null;
1029
1030         var xml = new OpenLayers.Format.XML().read(data);
1031         switch (xml.documentElement.nodeName.toLowerCase()) {
1032             case "error":
1033                 switch (xml.documentElement.getAttribute("reason")) {
1034                     case "unauthorized":
1035                         pwdMgr.reset();
1036                         $("#cookie_warning").show();
1037                         Admin.reset();
1038                         this.uninit();
1039                     break;
1040                     case "server":
1041                         this.commError(SypStrings.ServerError);
1042                         if (this._adduserDisplayed) {
1043                             focusEl = $("#newuser_name");
1044                         } else if (this._changepassDisplayed) {
1045                             focusEl = $("#pass_current");
1046                         }
1047                     break;
1048                     case "request":
1049                         this.commError(SypStrings.RequestError);
1050                         if (this._adduserDisplayed) {
1051                             focusEl = $("#newuser_name");
1052                         } else if (this._changepassDisplayed) {
1053                             focusEl = $("#pass_current");
1054                         }
1055                     break;
1056                     case "wrongpass":
1057                         this.commError(SypStrings.changePassBadPass);
1058                         focusEl = $("#pass_current");
1059                     break;
1060                     case "newuser_exists":
1061                         this.commError(SypStrings.newUserExistsError);
1062                         focusEl = $("#newuser_name");
1063                     break;
1064                     default:
1065                         this.commError(SypStrings.UnconsistentError);
1066                         if (this._adduserDisplayed) {
1067                             focusEl = $("#newuser_name");
1068                         } else if (this._changepassDisplayed) {
1069                             focusEl = $("#pass_current");
1070                         }
1071                     break;
1072                 }
1073             break;
1074             case "success":
1075                 switch (xml.documentElement.getAttribute("request")) {
1076                     case "newuser":
1077                         this.commSuccess(SypStrings.newUserSuccess);
1078                         needFormEnabling = false;
1079                     break;
1080                     case "changepass":
1081                         this.commSuccess(SypStrings.changePassSuccess);
1082                         needFormEnabling = false;
1083                     break;
1084                     default:
1085                         this.commError(SypStrings.UnconsistentError);
1086                         focusEl = $("newuser_name");
1087                     break;
1088                 }
1089             break;
1090             default:
1091                 this.commError(SypStrings.UnconsistentError);
1092                 focusEl = $("newuser_name");
1093             break;
1094         }
1095
1096         if (needFormEnabling) {
1097             // here, we need a timeout because onsend timeout sometimes has not been triggered yet
1098             var self = this;
1099             window.setTimeout(function() {
1100                 self.enableForms();
1101                 if (focusEl) {
1102                     focusEl.select().focus();
1103                 }
1104              }, 0);
1105         } else {
1106             if (focusEl) {
1107                 focusEl.focus().select();
1108             }
1109         }
1110
1111     },
1112
1113     commSuccess: function (message) {
1114         $("#user_comm").text(message);
1115         $("#user_comm").removeClass("error success").addClass("success");
1116     },
1117
1118     commError: function (message) {
1119         $("#user_comm").text(message);
1120         $("#user_comm").removeClass("error success").addClass("error");
1121     }
1122 }
1123
1124 $(window).load(function () {
1125     // if using .ready, ie triggers an error when trying to access
1126     // document.namespaces
1127     pwdMgr.init();
1128     $("#newfeature_button").click(function () {
1129         Admin.addNewFeature();
1130     });
1131     $("#editor_close").click(function () {
1132         Admin.cancelCurrentFeature()
1133     });
1134     $("#feature_update").submit(function() {
1135         try {
1136             FeatureMgr.save(Admin.currentFeature);
1137         } catch(e) {}
1138         return false;
1139     });
1140     $("#feature_delete").submit(function() {
1141         try {
1142             FeatureMgr.del(Admin.currentFeature);
1143         } catch(e) {}
1144         return false;
1145     });
1146     $("#image_delete").click(function() {
1147             $("#img").removeAttr('src');
1148             // needs to rebuild element otherwise some browsers still
1149             // display image.
1150             $("#img").parent().html($("#img").parent().html());
1151             $("#img").parent().hide();
1152             $("#image_delete").hide();
1153             $("#image_file").parent().show();
1154     });
1155
1156     userMgr.init();
1157     Admin.init();
1158 });