]> dev.renevier.net Git - syp.git/blob - js/admin.js
8101799156f8b7ec4c0fda46692df9459e08eb54
[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.closeAddUser();
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.closeAddUser();
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             onsend: function() { $("#editor_throbber").css("visibility", "visible"); }
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             onsend: function() { $("#editor_throbber").css("visibility", "visible"); }
466         });
467     },
468
469     ajaxReply: function (data) {
470         $("#editor_throbber").css("visibility", "hidden");
471         if (!data) {
472             this.commError(SypStrings.ServerError);
473             return;
474         }
475
476         var xml = new OpenLayers.Format.XML().read(data);
477
478         switch (xml.documentElement.nodeName.toLowerCase()) {
479             case "error":
480                 switch (xml.documentElement.getAttribute("reason")) {
481                     case "unauthorized":
482                         pwdMgr.reset();
483                         $("#cookie_warning").show();
484                         this.reset();
485                         Admin.cancelCurrentFeature();
486                         Admin.reset();
487                         userMgr.uninit();
488                     break;
489                     case "server":
490                         this.commError(SypStrings.ServerError);
491                         $("title").focus();
492                     break;
493                     case "unreferenced":
494                         this.commError(SypStrings.UnreferencedError);
495                         Admin.reloadLayer(Admin.dataLayer);
496                         Admin.closeEditor();
497                     break;
498                     case "nochange":
499                         this.commError(SypStrings.NochangeError);
500                         Admin.closeEditor();
501                     break;
502                     case "request":
503                         this.commError(SypStrings.RequestError);
504                         $("title").focus();
505                     break;
506                     case "toobig":
507                         this.commError(SypStrings.ToobigError);
508                         $("#image_file").parent().html($("#image_file").parent().html());
509                         $("#image_file").focus();
510                     break;
511                     case "notimage":
512                         this.commError(SypStrings.NotimageError);
513                         $("#image_file").parent().html($("#image_file").parent().html());
514                         $("#image_file").focus();
515                     break;
516                     default:
517                         this.commError(SypStrings.UnconsistentError);
518                         $("title").focus();
519                     break;
520                 }
521             break;
522             case "success":
523                 switch (xml.documentElement.getAttribute("request")) {
524                     case "del":
525                         this.commSuccess(SypStrings.DelSucces);
526                         var someFeature = false;
527                         var self = this;
528                         $.each($(xml).find("FEATURE,feature"), function () {
529                              someFeature = true;
530                              var id = parseFloat($(this).find("ID:first,id:first").text());
531                              if ((id === null) || isNaN (id)) {
532                                 return;;
533                              }
534                              var features = Admin.dataLayer.features;
535                              for (var idx = 0; idx < features.length; idx++) {
536                                  if (features[idx].fid == id) {
537                                      Admin.dataLayer.removeFeatures([features[idx]]);
538                                  }
539                              }
540                         });
541                         if (someFeature == false) {
542                             this.commError(SypStrings.UnconsistentError);
543                         } else {
544                             Admin.closeEditor();
545                         }
546                     break;
547                     case "update":
548                     case "add":
549                         var someFeature = false;
550                         var self = this;
551                         $.each($(xml).find("FEATURE,feature"), function () {
552                                 someFeature = true;
553                                 var id = parseFloat($(this).find("ID:first,id:first").text());
554                                 if ((id === null) || isNaN (id)) {
555                                     return;;
556                                 }
557
558                                 var lon = parseFloat($(this).find("LON:first,lon:first").text());
559                                 if ((typeof (lon) != "number") || isNaN (lon) ||
560                                         (lon < -180) || (lon > 180)) {
561                                     return;;
562                                 }
563
564                                 var lat = parseFloat($(this).find("LAT:first,lat:first").text());
565                                 if ((typeof (lat) != "number") || isNaN (lat) ||
566                                         (lat < -90) || (lat > 90)) {
567                                     return;;
568                                 }
569
570                                 var mapProj = Admin.map.getProjectionObject();
571                                 var lonlat = new OpenLayers.LonLat (lon, lat).
572                                                 transform( new OpenLayers.Projection("EPSG:4326"), mapProj);
573
574                                 var imgurl = $(this).find("IMGURL:first,imgurl:first").text();
575                                 var title = $(this).find("HEADING:first,heading:first").text();
576                                 var description = $(this).find("DESCRIPTION:first,description:first").text();
577
578                                 feature = self.update (Admin.currentFeature, lonlat, imgurl, title, description); 
579                                 feature.fid = id;
580                         });
581
582                         if (someFeature == false) {
583                             this.commError(SypStrings.UnconsistentError);
584                         } else {
585                             this.commSuccess(SypStrings.UpdateSucces);
586                             Admin.closeEditor();
587                         }
588
589                     break;
590                     default:
591                         this.commError(SypStrings.UnconsistentError);
592                    break;
593                 }
594             break;
595             default:
596                 this.commError(SypStrings.UnconsistentError);
597             break;
598         }
599     },
600
601     commSuccess: function (message) {
602         $("#server_comm").text(message);
603         $("#server_comm").removeClass("error success").addClass("success");
604     },
605
606     commError: function (message) {
607         $("#server_comm").text(message);
608         $("#server_comm").removeClass("error success").addClass("error");
609     }
610 }
611
612 /* maintains a queue of ajax queries, so I'm sure they all execute in the same
613  * order they were defined */
614 var AjaxMgr = {
615     _queue: [],
616
617     running: false,
618
619     add: function(query) {
620         this._queue.push(query);
621         if (this._queue.length > 1) {
622             return;
623         } else {
624             this._runQuery(query);
625         }
626     },
627
628     _runQuery: function(query) {
629         var self = this;
630         $('#api_frame').one("load", function() {
631             self.running = false;
632             self._reqEnd();
633             if (typeof (query.oncomplete) == "function") {
634                 var body = null;
635                 try {
636                     if (this.contentDocument) {
637                         body = this.contentDocument.body;
638                     } else if (this.contentWindow) {
639                         body = this.contentWindow.document.body;
640                     } else {
641                         body = document.frames[this.id].document.body;
642                     }
643                 } catch (e) {}
644                     if (body) {
645                         query.oncomplete(body.innerHTML);
646                     } else {
647                         query.oncomplete(null);
648                     }
649             }
650         });
651         query.form.attr("action", "api.php");
652         query.form.attr("target", "api_frame");
653         query.form.attr("method", "post");
654         this.running = true;
655         query.form.get(0).submit();
656         if (typeof (query.onsend) == "function") {
657             query.onsend();
658         }
659     },
660
661     _reqEnd: function() {
662         this._queue.shift();
663         if (this._queue.length > 0) {
664             this._reqEnd(this._queue[0]);
665         }
666     }
667 }
668
669 var pwdMgr = {
670
671     init: function () {
672         $("#login_form").submit(this.submit);
673         $("#user").focus().select();
674     },
675
676     reset: function() {
677         this.commError ("");
678         $("#login_area").show();
679         $("#password").val("");
680         $("#user").val(sypSettings.loggedUser).focus().select();
681     },
682
683     submit: function () {
684         try {
685             pwdMgr.commError("");
686             var req = {
687                 form:  $("#login_form"),
688                 onsend: function() {
689                     $("#pwd_throbber").css("visibility", "visible");
690                     $("#login_error").hide();
691
692                     // we need a timeout; otherwise those fields will not be submitted
693                     window.setTimeout(function() { 
694                             // removes focus from #password before disabling it. Otherwise, opera
695                             // prevents re-focusing it after re-enabling it.
696                             $("#user, #password").blur(); 
697                             $("#login_submit, #user, #password").attr("disabled", "disabled");
698                     }, 0)
699                 },
700                 oncomplete: OpenLayers.Function.bind(pwdMgr.ajaxReply, pwdMgr)
701             };
702             AjaxMgr.add(req);
703         } catch(e) {}
704         return false;
705     },
706
707     ajaxReply: function (data) {
708         $("#pwd_throbber").css("visibility", "hidden");
709         // here, we need a timeout because onsend timeout sometimes has not been triggered yet
710         window.setTimeout(function() {
711             $("#login_submit, #user, #password").removeAttr("disabled");
712         }, 0);
713
714         if (!data) {
715             this.commError(SypStrings.ServerError);
716             $("#login_error").show();
717             window.setTimeout(function() {
718                     $("#user").focus().select();
719             }, 0);
720             return;
721         }
722         var xml = new OpenLayers.Format.XML().read(data);
723
724         switch (xml.documentElement.nodeName.toLowerCase()) {
725             case "error":
726                 switch (xml.documentElement.getAttribute("reason")) {
727                     case "server":
728                         this.commError(SypStrings.ServerError);
729                     break;
730                     case "unauthorized":
731                         this.commError(SypStrings.UnauthorizedError);
732                     break;
733                     case "request":
734                         this.commError(SypStrings.RequestError);
735                     break;
736                     default:
737                         this.commError(SypStrings.UnconsistentError);
738                     break;
739                 }
740                 $("#login_error").show();
741                 window.setTimeout(function() {
742                         $("#user").focus().select();
743                 }, 0);
744             break;
745             case "success":
746                 $("#login_area").hide();
747
748                 user = $(xml).find("USER,user").text();
749                 sypSettings.loggedUser = user;
750
751                 if (sypSettings.loggedUser == "admin")  {
752                     userMgr.init();
753                 }
754
755                 if (Admin.selFeatureControl) {
756                     Admin.selFeatureControl.destroy();
757                 }
758                 if (Admin.moveFeatureControl) {
759                     Admin.moveFeatureControl.destroy();
760                 }
761                 if (Admin.addFeatureControl) {
762                     Admin.addFeatureControl.destroy();
763                 }
764                 if (Admin.dataLayer) {
765                     Admin.dataLayer.destroy();
766                 }
767
768                 Admin.dataLayer = Admin.createDataLayer(user);
769                 Admin.map.addLayer(Admin.dataLayer);
770                 Admin.reset();
771
772             break;
773             default:
774                 this.commError(SypStrings.UnconsistentError);
775             break;
776         }
777     },
778
779     commError: function (message) {
780         $("#login_error").text(message);
781         if (message) {
782             $("#login_error").show();
783         } else {
784             $("#login_error").hide();
785         }
786     }
787 }
788
789 var userMgr = {
790     _adduserDisplayed: false,
791     _deluserDisplayed: false,
792
793     init: function() {
794         if (sypSettings.loggedUser != "admin") {
795             return;
796         }
797
798         $("#add_user").show();
799
800         $("#add_user").click(function () {
801             userMgr.toggleAddUser();
802             return false;
803         });
804         $("#newuser_close").click(function () {
805             userMgr.closeAddUser()
806         });
807         $("#newuser").submit(function() {
808             try {
809                 userMgr.add();
810             } catch(e) {}
811             return false;
812         });
813     },
814
815     uninit: function() {
816         if (this._adduserDisplayed) {
817             this.closeAddUser();
818         }
819         $("#add_user").unbind("click");
820         $("#add_user").hide();
821         $("#newuser_close").unbind("click");
822         $("#newuser").unbind("submit");
823     },
824
825     toggleAddUser: function() {
826         if (this._adduserDisplayed) {
827             this.closeAddUser();
828         } else {
829             this.showAddUser();
830         }
831     },
832
833     showAddUser: function() {
834         if (!Admin.cancelCurrentFeature()) {
835             return;
836         }
837
838         $(document).unbind("keydown").keydown(function(e) { 
839             if (e.keyCode == 27) {
840                 userMgr.closeAddUser()
841                 e.preventDefault();
842             }
843         });
844
845         Admin.reset();
846         $("#newuser_area").show();
847         $("#newuser_name, #newuser_password, #newuser_password_confirm").val("");
848         $("#newuser_name, #newuser_password, #newuser_password_confirm, #newuser_submit").removeAttr('disabled');
849         $("#newuser_name").focus();;
850         this.commError("");
851
852         this._adduserDisplayed = true;
853     },
854
855     closeAddUser: function() {
856         $("#newuser_area").hide();
857         $(document).unbind("keydown");
858         this._adduserDisplayed = false;
859     },
860
861     add: function() {
862         var newuser_name = $("#newuser_name").val();
863         if (!newuser_name) {
864             this.commError(SypStrings.newUserNonameError);
865             $("#newuser_name").focus();
866             return;
867         }
868
869         var newuser_pass = $("#newuser_password").val();
870         var newuser_pass_confirm = $("#newuser_password_confirm").val();
871         if (newuser_pass != newuser_pass_confirm) {
872             this.commError(SypStrings.newUserPasswordmatchError);
873             $("#newuser_password").focus().select();
874             return;
875         }
876
877         this.commError("");
878
879         AjaxMgr.add({
880             form: $("#newuser"),
881             oncomplete: OpenLayers.Function.bind(this.ajaxReply, this),
882             onsend: function() { $("#newuser_throbber").css("visibility", "visible"); }
883         });
884     },
885
886     ajaxReply: function (data) {
887         $("#newuser_throbber").css("visibility", "hidden");
888         if (!data) {
889             this.commError(SypStrings.ServerError);
890             return;
891         }
892
893         var xml = new OpenLayers.Format.XML().read(data);
894         switch (xml.documentElement.nodeName.toLowerCase()) {
895             case "error":
896                 switch (xml.documentElement.getAttribute("reason")) {
897                     case "unauthorized":
898                         pwdMgr.reset();
899                         $("#cookie_warning").show();
900                         Admin.reset();
901                         this.uninit();
902                     break;
903                     case "server":
904                         this.commError(SypStrings.ServerError);
905                         $("#newuser_name").focus().select();
906                     break;
907                     case "request":
908                         this.commError(SypStrings.RequestError);
909                         $("#newuser_name").focus().select();
910                     break;
911                     case "newuser_exists":
912                         this.commError(SypStrings.newUserExistsError);
913                         $("#newuser_name").focus().select();
914                     break;
915                     default:
916                         this.commError(SypStrings.UnconsistentError);
917                         $("#newuser_name").focus().select();
918                     break;
919                 }
920             break;
921             case "success":
922                 switch (xml.documentElement.getAttribute("request")) {
923                     case "newuser":
924                         this.commSuccess(SypStrings.newUserSuccess);
925                         $("#newuser_name, #newuser_password, #newuser_password_confirm, #newuser_submit").attr('disabled', 'disabled');
926                     break;
927                     default:
928                         this.commError(SypStrings.UnconsistentError);
929                         $("newuser_name").focus().select();
930                     break;
931                 }
932             break;
933             default:
934                 this.commError(SypStrings.UnconsistentError);
935                 $("newuser_name").focus().select();
936             break;
937         }
938     },
939
940     commSuccess: function (message) {
941         $("#newuser_comm").text(message);
942         $("#newuser_comm").removeClass("error success").addClass("success");
943     },
944
945     commError: function (message) {
946         $("#newuser_comm").text(message);
947         $("#newuser_comm").removeClass("error success").addClass("error");
948     }
949 }
950
951 $(window).load(function () {
952     // if using .ready, ie triggers an error when trying to access
953     // document.namespaces
954     pwdMgr.init();
955     $("#newfeature_button").click(function () {
956         Admin.addNewFeature();
957     });
958     $("#editor_close").click(function () {
959         Admin.cancelCurrentFeature()
960     });
961     $("#feature_update").submit(function() {
962         try {
963             FeatureMgr.save(Admin.currentFeature);
964         } catch(e) {}
965         return false;
966     });
967     $("#feature_delete").submit(function() {
968         try {
969             FeatureMgr.del(Admin.currentFeature);
970         } catch(e) {}
971         return false;
972     });
973     $("#image_delete").click(function() {
974             $("#img").removeAttr('src');
975             // needs to rebuild element otherwise some browsers still
976             // display image.
977             $("#img").parent().html($("#img").parent().html());
978             $("#img").parent().hide();
979             $("#image_delete").hide();
980             $("#image_file").parent().show();
981     });
982
983     userMgr.init();
984     Admin.init();
985 });