/* Copyright (c) 2009 Arnaud Renevier, Inc, published under the modified BSD * license. */ // drag feature with tolerance OpenLayers.Control.SypDragFeature = OpenLayers.Class (OpenLayers.Control.DragFeature, { startPixel: null, dragStart: null, pixelTolerance : 0, timeTolerance: 300, downFeature: function(pixel) { OpenLayers.Control.DragFeature.prototype.downFeature.apply(this, arguments); this.dragStart = (new Date()).getTime(); this.startPixel = pixel; }, doneDragging: function(pixel) { OpenLayers.Control.DragFeature.prototype.doneDragging.apply(this, arguments); // Check tolerance. var passesTimeTolerance = (new Date()).getTime() > this.dragStart + this.timeTolerance; var xDiff = this.startPixel.x - pixel.x; var yDiff = this.startPixel.y - pixel.y; var passesPixelTolerance = Math.sqrt(Math.pow(xDiff,2) + Math.pow(yDiff,2)) > this.pixelTolerance; if(passesTimeTolerance && passesPixelTolerance){ this.onComplete(this.feature, pixel); } else { var feature = this.feature; var res = this.map.getResolution(); this.feature.geometry.move(res * (this.startPixel.x - this.lastPixel.x), res * (this.lastPixel.y - this.startPixel.y)); this.layer.drawFeature(this.feature); } this.layer.drawFeature(this.feature, "select"); }, moveFeature: function(pixel) { OpenLayers.Control.DragFeature.prototype.moveFeature.apply(this, arguments); this.layer.drawFeature(this.feature, "temporary"); }, overFeature: function (feature) { // can only drag and drop currently selected feature if (feature != Admin.currentFeature) { return; } OpenLayers.Control.DragFeature.prototype.overFeature.apply(this, arguments); }, CLASS_NAME: "OpenLayers.Control.SypDragFeature" }); var Admin = { Settings: { MARKER_ICON: "openlayers/img/marker-blue.png", MARKER_ICON_HEIGHT: 25, MARKER_SELECT_ICON: "openlayers/img/marker-green.png", MARKER_SELECT_ICON_HEIGHT: 25, MARKER_TEMPORARY_ICON: "openlayers/img/marker-gold.png", MARKER_TEMPORARY_ICON_HEIGHT: 25 }, map: null, baseLayer: null, dataLayer: null, selFeatureControl: null, moveFeatureControl: null, addFeatureControl: null, currentFeature: null, currentFeatureLocation: null, init: function () { this.map = new OpenLayers.Map ("map", { controls:[ new OpenLayers.Control.Navigation (), new OpenLayers.Control.PanZoom () ], projection: new OpenLayers.Projection("EPSG:900913"), displayProjection: new OpenLayers.Projection("EPSG:4326") }); this.baseLayer = this.createBaseLayer (); this.dataLayer = this.createDataLayer (); this.map.addLayers([this.baseLayer, this.dataLayer]); // controls this.selFeatureControl = this.createSelectFeatureControl(); this.map.addControl(this.selFeatureControl); this.moveFeatureControl = this.createMoveFeatureControl(); this.map.addControl(this.moveFeatureControl); this.addFeatureControl = this.createNewfeatureControl(); this.map.addControl(this.addFeatureControl); // position var centerBounds = new OpenLayers.Bounds(); var mapProj = this.map.getProjectionObject(); var sypOrigProj = new OpenLayers.Projection("EPSG:4326"); var bottomLeft = new OpenLayers.LonLat(sypOrig[0],sypOrig[1]); bottomLeft = bottomLeft.transform(sypOrigProj, mapProj); var topRight = new OpenLayers.LonLat(sypOrig[2],sypOrig[3]) topRight = topRight.transform(sypOrigProj, mapProj); centerBounds.extend(bottomLeft); centerBounds.extend(topRight); // at that moment, ie does not know size of the map, we need to update // manually this.map.updateSize(); this.map.zoomToExtent(centerBounds); this.reset(); }, reset: function() { this.addFeatureControl.deactivate(); this.moveFeatureControl.deactivate(); this.selFeatureControl.activate(); this.checkForFeatures(); $("#newfeature_button").show().val("ajouter un emplacement"); $("#newfeature_button").unbind("click").click(function () { Admin.addNewFeature(); }); }, createBaseLayer: function () { return new OpenLayers.Layer.OSM("OSM"); }, createDataLayer: function () { var styleMap = new OpenLayers.StyleMap ( {"default": { externalGraphic: this.Settings.MARKER_ICON, graphicHeight: this.Settings.MARKER_ICON_HEIGHT || 32 }, "temporary": { externalGraphic: this.Settings.MARKER_TEMPORARY_ICON, graphicHeight: this.Settings.MARKER_TEMPORARY_ICON_HEIGHT || 32 }, "select": { externalGraphic: this.Settings.MARKER_SELECT_ICON, graphicHeight: this.Settings.MARKER_SELECT_ICON_HEIGHT || 32 }}); var layer = new OpenLayers.Layer.GML("KML", "items.php", { styleMap: styleMap, format: OpenLayers.Format.KML, projection: this.map.displayProjection, eventListeners: { scope: this, loadend: this.checkForFeatures } }); return layer; }, createMoveFeatureControl: function () { var control = new OpenLayers.Control.SypDragFeature( this.dataLayer, { }); return control; }, createSelectFeatureControl: function () { var control = new OpenLayers.Control.SelectFeature( this.dataLayer, { onSelect: OpenLayers.Function.bind(this.onFeatureSelect, this) }); return control; }, createNewfeatureControl: function () { var control = new OpenLayers.Control (); var handler = new OpenLayers.Handler.Click(control, { 'click': OpenLayers.Function.bind(FeatureMgr.add, FeatureMgr) }); control.handler = handler; return control; }, onFeatureSelect: function (feature) { this.showEditor(feature); FeatureMgr.reset(); this.selFeatureControl.deactivate(); this.moveFeatureControl.activate(); }, closeEditor: function() { if (this.currentFeature && this.currentFeature.layer) { this.selFeatureControl.unselect(this.currentFeature); } this.currentFeature = null; this.currentFeatureLocation = null; $("#img").removeAttr('src'); $("#img").parent().html($("#img").parent().html()); $("#img").parent().show(); $("#title, #description").val(""); $("#editor").hide(); // do it once before hidding and once after hidding to work in all cases $("#title, #description").val(""); $("#image_file").parent().html($("#image_file").parent().html()); $(document).unbind("keydown"); this.checkForFeatures(); this.reset(); }, showEditor: function (feature) { $("#newfeature_button").hide(); if (feature.fid) { $("#delete").show(); } else { $("#delete").hide(); } $(document).unbind("keydown").keydown(function(e) { if (e.keyCode == 27) { Admin.cancelCurrentFeature() e.preventDefault(); } }); this.currentFeature = feature; this.currentFeatureLocation = new OpenLayers.Pixel(feature.geometry.x, feature.geometry.y); $("#editor").show(); $("#instructions").text("Vous pouvez déplacer le marqueur en effectuant un glisser-déposer."); $("#title").val(feature.attributes.name); var fullDesc = $(feature.attributes.description).parent(); $("#description").val(fullDesc.find('p').text()); var src = fullDesc.find('img').attr('src'); if (src) { $("#img").parent().show(); $("#img").attr('src', src); $("#image_file").parent().hide(); $("#image_delete").show(); } else { $("#img").parent().hide(); $("#image_file").parent().show(); $("#image_delete").hide(); } $("#title").select().focus(); }, checkForFeatures: function () { if (this.dataLayer.features.length != 0) { $("#instructions").text("Pour modifier les données d'une image, sélectionnez le marqueur correspondant."); } }, addNewFeature: function () { function cancel() { $(document).unbind("keydown"); Admin.reset() } $(document).unbind("keydown").keydown(function(e) { if (e.keyCode == 27) { e.preventDefault(); cancel(); } }); $("#newfeature_button").val("annuler"); $("#newfeature_button").unbind("click").click(cancel); $("#instructions").text("Cliquez sur la carte pour ajouter un marqueur."); this.selFeatureControl.deactivate(); this.addFeatureControl.activate(); FeatureMgr.reset(); }, cancelCurrentFeature: function() { if (AjaxMgr.running) { return; } var feature = this.currentFeature; if (feature.fid) { FeatureMgr.move (feature, this.currentFeatureLocation); } else { this.dataLayer.removeFeatures([feature]); } this.closeEditor(); }, reloadLayer: function (layer) { layer.destroyFeatures(); layer.loaded = false; layer.loadGML(); }, Utils: { escapeHTML: function (str) { if (!str) { return ""; } return str. replace(/&/gm, '&'). replace(/'/gm, '''). replace(/"/gm, '"'). replace(/>/gm, '>'). replace(/" + Admin.Utils.escapeHTML(description) + "
" + "" return feature; }, del: function (feature) { var form = $("#feature_delete"); form.find('input[name="fid"]').val(feature.fid); AjaxMgr.add({ form: form, oncomplete: OpenLayers.Function.bind(this.ajaxReply, this) }); }, save: function (feature) { var x = feature.geometry.x; var y = feature.geometry.y; var mapProj = feature.layer.map.getProjectionObject(); var lonlat = new OpenLayers.LonLat(x, y). transform(mapProj, new OpenLayers.Projection("EPSG:4326")); var form = $("#feature_update"); form.find('input[name="lon"]').val(lonlat.lon); form.find('input[name="lat"]').val(lonlat.lat); form.find('input[name="fid"]').val(feature.fid); form.find('input[name="keep_img"]').val( $("#img").attr("src") ? "yes": "no" ); if (feature.fid) { form.find('input[name="request"]').val("update"); } else { form.find('input[name="request"]').val("add"); } AjaxMgr.add({ form: form, oncomplete: OpenLayers.Function.bind(this.ajaxReply, this) }); }, ajaxReply: function (data) { if (!data) { this.commError("Il s'est produit une erreur serveur."); return; } var xml = new OpenLayers.Format.XML().read(data); switch (xml.documentElement.nodeName.toLowerCase()) { case "error": switch (xml.documentElement.getAttribute("reason")) { case "unauthorized": $("#login_area").show(); this.reset(); Admin.reset(); break; case "server": this.commError("Il s'est produit une erreur serveur."); $("title").focus(); break; case "unreferenced": this.commError("La fiche n'était pas référencée sur le serveur."); Admin.reloadLayer(Admin.dataLayer); Admin.closeEditor(); break; case "nochange": this.commError("Aucun changement n'a été effectué."); Admin.closeEditor(); break; case "request": this.commError("Le serveur n'a pas compris la requête. Il s'agit probablement d'un bug dans SYP."); $("title").focus(); break; case "toobig": this.commError("L'image est trop grande et n'a pas été acceptée par le serveur."); $("#image_file").parent().html($("#image_file").parent().html()); $("#image_file").focus(); break; case "notimage": this.commError("Le fichier ne semble pas être une image."); $("#image_file").parent().html($("#image_file").parent().html()); $("#image_file").focus(); break; default: this.commError("Il s'est produit une erreur inconnue."); $("title").focus(); break; } break; case "success": switch (xml.documentElement.getAttribute("request")) { case "del": this.commSuccess("La suppression s'est déroulée correctement."); var someFeature = false; var self = this; $.each($(xml).find("FEATURE,feature"), function () { someFeature = true; var id = parseFloat($(this).find("ID:first,id:first").text()); if ((id === null) || isNaN (id)) { return;; } var features = Admin.dataLayer.features; for (var idx = 0; idx < features.length; idx++) { if (features[idx].fid == id) { Admin.dataLayer.removeFeatures([features[idx]]); } } }); if (someFeature == false) { this.commError("Le serveur a fait une réponse incohérente."); } else { Admin.closeEditor(); } break; case "update": case "add": var someFeature = false; var self = this; $.each($(xml).find("FEATURE,feature"), function () { someFeature = true; var id = parseFloat($(this).find("ID:first,id:first").text()); if ((id === null) || isNaN (id)) { return;; } var lon = parseFloat($(this).find("LON:first,lon:first").text()); if ((typeof (lon) != "number") || isNaN (lon) || (lon < -180) || (lon > 180)) { return;; } var lat = parseFloat($(this).find("LAT:first,lat:first").text()); if ((typeof (lat) != "number") || isNaN (lat) || (lat < -90) || (lat > 90)) { return;; } var mapProj = Admin.map.getProjectionObject(); var lonlat = new OpenLayers.LonLat (lon, lat). transform( new OpenLayers.Projection("EPSG:4326"), mapProj); var imgurl = $(this).find("IMGURL:first,imgurl:first").text(); var title = $(this).find("HEADING:first,heading:first").text(); var description = $(this).find("DESCRIPTION:first,description:first").text(); feature = self.update (Admin.currentFeature, lonlat, imgurl, title, description); feature.fid = id; }); if (someFeature == false) { this.commError("Le serveur a fait une réponse incohérente."); } else { this.commSuccess("La sauvegarde s'est déroulée correctement."); Admin.closeEditor(); } break; default: this.commError("Le serveur a fait une réponse incohérente."); break; } break; default: this.commError("Le serveur a fait une réponse incohérente."); break; } }, commSuccess: function (message) { $("#server_comm").text(message); $("#server_comm").removeClass().addClass("success"); }, commError: function (message) { $("#server_comm").text(message); $("#server_comm").removeClass().addClass("error"); if (message.length) { // this.move(Admin.currentFeature, Admin.currentFeatureLocation); // Admin.reset(); } } } /* maintains a queue of ajax queries, so I'm sure they all execute in the same * order they were defined */ var AjaxMgr = { _queue: [], running: false, add: function(query) { this._queue.push(query); if (this._queue.length > 1) { return; } else { this._runQuery(query); } }, _runQuery: function(query) { var self = this; $('#api_frame').one("load", function() { self.running = false; self._reqEnd(); if (typeof (query.oncomplete) == "function") { var body = null; try { if (this.contentDocument) { body = this.contentDocument.body; } else if (this.contentWindow) { body = this.contentWindow.document.body; } else { body = document.frames[this.id].document.body; } } catch (e) {} if (body) { query.oncomplete(body.innerHTML); } else { query.oncomplete(null); } } }); query.form.attr("action", "api.php"); query.form.attr("target", "api_frame"); query.form.attr("method", "post"); this.running = true; query.form.get(0).submit(); if (typeof (query.onsend) == "function") { query.onsend(); } }, _reqEnd: function() { this._queue.shift(); if (this._queue.length > 0) { this._reqEnd(this._queue[0]); } } } var pwdMgr = { init: function () { $("#login_form").submit(this.submit); $("#password").focus().select(); }, reset: function() { this.commError (""); }, submit: function () { try { pwdMgr.commError(""); var req = { form: $("#login_form"), onsend: function() { $("#pwd_throbber").css("visibility", "visible"); $("#login_error").hide(); // we need a timeout; otherwise those fields will not be submitted window.setTimeout(function() { // removes focus from #password before disabling it. Otherwise, opera // prevents re-focusing it after re-enabling it. $("#password").blur(); $("#login_submit, #password").attr("disabled", "disabled"); }, 0) }, oncomplete: OpenLayers.Function.bind(pwdMgr.ajaxReply, pwdMgr) }; AjaxMgr.add(req); } catch(e) {} return false; }, ajaxReply: function (data) { $("#pwd_throbber").css("visibility", "hidden"); // here, we need a timeout because onsend timeout sometimes has not been triggered yet window.setTimeout(function() { $("#login_submit, #password").removeAttr("disabled"); }, 0); if (!data) { this.commError("Il s'est produit une erreur serveur."); $("#login_error").show(); window.setTimeout(function() { $("#password").focus().select(); }, 0); return; } var xml = new OpenLayers.Format.XML().read(data); switch (xml.documentElement.nodeName.toLowerCase()) { case "error": switch (xml.documentElement.getAttribute("reason")) { case "server": this.commError("Il s'est produit une erreur serveur."); break; case "unauthorized": this.commError("Le mot de passe n'est pas correct."); break; case "request": this.commError("Le serveur n'a pas compris la requête. Il s'agit probablement d'un bug dans SYP."); break; default: this.commError("Il s'est produit une erreur inconnue."); break; } $("#login_error").show(); window.setTimeout(function() { $("#password").focus().select(); }, 0); break; case "success": this.reset(); $("#login_area").hide(); break; default: this.commError("Le serveur a fait une réponse incohérente."); break; } }, commError: function (message) { $("#login_error").text(message); if (message) { $("#login_error").show(); } else { $("#login_error").hide(); } } } $(window).load(function () { // if using .ready, ie triggers an error when trying to access // document.namespaces pwdMgr.init(); $("#newfeature_button").click(function () { Admin.addNewFeature(); }); $("#editor_close").click(function () { Admin.cancelCurrentFeature() }); $("#feature_update").submit(function() { try { FeatureMgr.save(Admin.currentFeature); } catch(e) {} return false; }); $("#feature_delete").submit(function() { try { FeatureMgr.del(Admin.currentFeature); } catch(e) {} return false; }); $("#image_delete").click(function() { $("#img").removeAttr('src'); // needs to rebuild element otherwise some browsers still // display image. $("#img").parent().html($("#img").parent().html()); $("#img").parent().hide(); $("#image_delete").hide(); $("#image_file").parent().show(); }); Admin.init(); });