X-Git-Url: https://dev.renevier.net/gitweb.cgi?p=syp.git;a=blobdiff_plain;f=js%2Fadmin.js;h=c7be3dbb00abedaf53790952a4459e23bee1ea39;hp=0709878efef7476b55ea339c6e93b5166df4bdd3;hb=57511b4efd7402ef58de66ac1fe2c01ed1b1d7b5;hpb=7282fabcfef34ef95b8c6bd414f34d77037451e1 diff --git a/js/admin.js b/js/admin.js index 0709878..c7be3db 100644 --- a/js/admin.js +++ b/js/admin.js @@ -1,160 +1,57 @@ /* Copyright (c) 2009 Arnaud Renevier, Inc, published under the modified BSD * license. */ -OpenLayers.Control.SelectDragFeature = - OpenLayers.Class (OpenLayers.Control.SelectFeature, { - - lastPixel: null, - dragFeature: null, - - startPixel : null, +// drag feature with tolerance +OpenLayers.Control.SypDragFeature = OpenLayers.Class (OpenLayers.Control.DragFeature, { + startPixel: null, + dragStart: null, pixelTolerance : 0, timeTolerance: 300, - dragStart: null, - - onComplete: function (feature, pixel) {}, - onCancel: function (feature, pixel) {}, - - initialize: function (layers, options) { - var callbacks = { - over: this.overFeature, - out: this.outFeature - }; - this.callbacks = OpenLayers.Util.extend(callbacks, this.callbacks); - - OpenLayers.Control.SelectFeature.prototype.initialize.apply(this, - arguments); - - var handlers = { - drag: new OpenLayers.Handler.Drag( - this, OpenLayers.Util.extend({ - down: this.downFeature, - move: this.moveFeature, - up: this.upFeature, - out: this.cancel, - done: this.doneDragging - }) - ) - }; - this.handlers = OpenLayers.Util.extend(handlers, this.handlers); - }, - - doneDragging: function (pixel) { - 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.dragFeature, pixel); - } else { - var res = this.map.getResolution (); - this.dragFeature.geometry.move(res * (this.startPixel.x - pixel.x), - res * (pixel.y - this.startPixel.y)); - this.onCancel(this.dragFeature,pixel); - } - this.layer.drawFeature(this.dragFeature, "select"); + downFeature: function(pixel) { + OpenLayers.Control.DragFeature.prototype.downFeature.apply(this, arguments); + this.dragStart = (new Date()).getTime(); + this.startPixel = pixel; }, - cancel: function () { - this.handlers.drag.deactivate (); - this.over = false; - }, + doneDragging: function(pixel) { + OpenLayers.Control.DragFeature.prototype.doneDragging.apply(this, arguments); + // Check tolerance. + var passesTimeTolerance = + (new Date()).getTime() > this.dragStart + this.timeTolerance; - clickFeature: function (feature) { - OpenLayers.Control.SelectFeature.prototype.clickFeature.apply(this, - arguments); - if (Admin.Utils.indexOf(this.layer.selectedFeatures, feature) == -1) { - this.dragDisable (); - } - }, + var xDiff = this.startPixel.x - pixel.x; + var yDiff = this.startPixel.y - pixel.y; - upFeature: function (pixel) { - }, + var passesPixelTolerance = + Math.sqrt(Math.pow(xDiff,2) + Math.pow(yDiff,2)) > this.pixelTolerance; - moveFeature: function (pixel) { - if (Admin.Utils.indexOf(this.layer.selectedFeatures, - this.dragFeature) != -1) { - var res = this.map.getResolution (); - this.dragFeature.geometry.move(res * (pixel.x - this.lastPixel.x), - res * (this.lastPixel.y - pixel.y)); - this.layer.drawFeature(this.dragFeature, "temporary"); - this.lastPixel = pixel; + 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"); }, - downFeature: function (pixel) { - this.handlers.feature.down = pixel; - - if (Admin.Utils.indexOf(this.layer.selectedFeatures, - this.dragFeature) != -1) { - this.dragStart = (new Date ()).getTime (); - this.startPixel = pixel; - this.lastPixel = pixel; - } - }, - - deactivate: function () { - this.dragDisable (); - return OpenLayers.Control.SelectFeature.prototype.deactivate.apply( - this, arguments - ); + moveFeature: function(pixel) { + OpenLayers.Control.DragFeature.prototype.moveFeature.apply(this, arguments); + this.layer.drawFeature(this.feature, "temporary"); }, overFeature: function (feature) { - if (Admin.Utils.indexOf(this.layer.selectedFeatures, feature) != -1) { - this.dragEnable(feature); - } - OpenLayers.Control.SelectFeature.prototype.overFeature.apply(this, - arguments); - }, - - outFeature: function (feature) { - this.dragDisable (); - OpenLayers.Control.SelectFeature.prototype.outFeature.apply(this, - arguments); - }, - - select: function (feature) { - this.dragEnable(feature); - OpenLayers.Control.SelectFeature.prototype.select.apply(this, - arguments); - }, - - dragDisable: function () { - this.over = false; - if(!this.handlers.drag.dragging) { - this.handlers.drag.deactivate (); - OpenLayers.Element.removeClass( - this.map.viewPortDiv, this.displayClass + "Over" - ); - this.dragFeature = null; - } - }, - - dragEnable: function (feature) { - if(!this.handlers.drag.dragging) { - this.dragFeature = feature; - this.handlers.drag.activate (); - this.over = true; - OpenLayers.Element.addClass(this.map.viewPortDiv, this.displayClass + "Over"); - } else { - if(this.dragFeature.id == feature.id) { - this.over = true; - } else { - this.over = false; - } + // can only drag and drop currently selected feature + if (feature != Admin.currentFeature) { + return; } + OpenLayers.Control.DragFeature.prototype.overFeature.apply(this, arguments); }, - setMap: function (map) { - this.handlers.drag.setMap(map); - OpenLayers.Control.SelectFeature.prototype.setMap.apply(this, arguments); - }, - - CLASS_NAME: "OpenLayers.Control.SelectDragFeature" + CLASS_NAME: "OpenLayers.Control.SypDragFeature" }); var Admin = { @@ -170,8 +67,12 @@ var Admin = { map: null, baseLayer: null, dataLayer: null, - selectControl: null, - clickControl: null, + selFeatureControl: null, + moveFeatureControl: null, + addFeatureControl: null, + + currentFeature: null, + currentFeatureLocation: null, init: function () { this.map = new OpenLayers.Map ("map", { @@ -187,14 +88,16 @@ var Admin = { this.dataLayer = this.createDataLayer (); this.map.addLayers([this.baseLayer, this.dataLayer]); - this.selectControl = this.createSelectDragControl (); - this.map.addControl(this.selectControl); - this.selectControl.activate (); + // 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); - this.clickControl = this.createClickControl (); - this.map.addControl(this.clickControl); - - var centerBounds = new OpenLayers.Bounds (); + // position + var centerBounds = new OpenLayers.Bounds(); var mapProj = this.map.getProjectionObject(); var sypOrigProj = new OpenLayers.Projection("EPSG:4326"); @@ -206,7 +109,24 @@ var Admin = { 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 () { @@ -237,332 +157,148 @@ var Admin = { format: OpenLayers.Format.KML, projection: this.map.displayProjection, eventListeners: { scope: this, - loadend: this.checkForFeatures, - featureremoved: this.checkForFeatures, - featureadded: this.checkForFeatures + loadend: this.checkForFeatures } }); return layer; }, - createSelectDragControl: function () { - var control = new OpenLayers.Control.SelectDragFeature( + createMoveFeatureControl: function () { + var control = new OpenLayers.Control.SypDragFeature( this.dataLayer, { - onSelect: this.onFeatureSelect, - onUnselect: this.onFeatureUnselect, - onComplete: OpenLayers.Function.bind(this.onDragComplete.action, - this.onDragComplete), - toggle: true, - clickout: false - }); + }); return control; }, - checkForFeatures: function () { - var features = this.dataLayer.features; - if (features.length == 0) { - $("#modify_howto").css("visibility", "hidden"); - } else { - $("#modify_howto").css("visibility", "visible"); - } + createSelectFeatureControl: function () { + var control = new OpenLayers.Control.SelectFeature( + this.dataLayer, { + onSelect: OpenLayers.Function.bind(this.onFeatureSelect, this) + }); + return control; }, - createClickControl: function () { + createNewfeatureControl: function () { var control = new OpenLayers.Control (); - var handler = new OpenLayers.Handler.Click(control, {}); + var handler = new OpenLayers.Handler.Click(control, { + 'click': OpenLayers.Function.bind(FeatureMgr.add, FeatureMgr) + }); control.handler = handler; return control; }, - addMarkerNewImage: function (imgurl) { - return function (evt) { - FeatureMgr.itemDeleter.lock(imgurl); - var pos = this.map.getLonLatFromViewPortPx(evt.xy); - var point = new OpenLayers.Geometry.Point(pos.lon, pos.lat); - var desc = ''; - var feature = new OpenLayers.Feature.Vector(point, { - name: '', - description: desc - }); - Admin.dataLayer.addFeatures([feature]); - Admin.selectControl.activate (); - - // When adding a feature and then selecting it, we set render style - // to "default" and right after, we set it to "select". When - // rendering backend is SVG, that triggers a modification of href - // attribute right after having inserted image with a different - // href. Unfortunately, webkit does not like that (see - // webkit#26392). That's why we need to wrap selection in a - // timeout. - var renderer = Admin.dataLayer.renderer; - if (renderer && renderer.CLASS_NAME == "OpenLayers.Renderer.SVG") { - window.setTimeout(function () { - Admin.selectControl.select(feature); - Admin.saveFeature(feature); - } ,0); - } else { - Admin.selectControl.select(feature); - Admin.saveFeature(feature); - } - $("#addphoto_button").val("ajouter une autre image"); - } - }, - onFeatureSelect: function (feature) { - Admin.closeNewimage(); - - $("#img").attr('src', ''); - $("#editor").show(); - $("#features_success").css("visibility", "hidden"); - - // we use the real onclick method otherwise: jquery method would not - // execute because of input.change method - $("#deletephoto_button").get(0).onclick = function () { - Admin.clearChangeTimeouts(); - var imgurl = $("#img").attr("src"); - Admin.deleteFeature(feature, imgurl); - }; - - $("#title_input").val(feature.attributes.name); - - var fullDesc = $(feature.attributes.description).parent(); - $("#desc_input").val(fullDesc.find('p').text()); - $("#img").attr('src', fullDesc.find('img').attr('src')); - - $(".input").each(function () { - this.curVal = this.value; - }); - - // Change event happens if an input has change if we leave that field. - // But we want data to be saved even if user does not blur input field - // (for example, he types something in the box and then does not touch - // it's computer). So, every 60 seconds, we check if value of input - // has changed. More precisely, every 60 seconds, we wait 3 seconds to - // see if input value is still changing and if not, it probably means - // user is not modifying data anymore. In that case, we save. - - $(".input").focus(function (evt) { - var self = this; - this.curVal = this.value; - this.checkTimer = window.setInterval(function () { - if (self.value != self.curVal) { - $("#features_success").css("visibility", "hidden"); - var newVal = self.value; - this.saveTimeout = window.setTimeout(function () { - if (self.value == newVal) { - self.curVal = self.value; - Admin.saveFeature(feature); - } - }, 3 * 1000); - } - }, 6 * 1000); - }) - - $(".input").blur(function (evt) { - if (this.checkTimer) { - window.clearInterval(this.checkTimer); - this.checkTimer = null; - } - if (this.saveTimeout) { - window.clearTimeout(this.saveTimeout); - this.saveTimeout = null; - } - }); - - $(".input").change(function (evt) { - if (this.curVal != this.value) { - $("#features_success").css("visibility", "hidden"); - this.curVal = this.value; - Admin.saveFeature(feature); - } - }); - - $("#title_input").blur() - $("#title_input").focus() - $("#title_input").select() - - $("#dragdrop_howto").css("visibility", "visible"); + this.showEditor(feature); + FeatureMgr.reset(); + this.selFeatureControl.deactivate(); + this.moveFeatureControl.activate(); }, - onFeatureUnselect: function (feature) { - Admin.closeEditor(); - $("#features_connect_error").hide(); - $("#deletephoto_button").get(0).onclick = null; - - // if user unselects feature, save modifications without waiting - var needsSaving = Admin.onDragComplete.timeout ? true: false; - $(".input").each(function () { - if (this.value != this.curVal) { - needsSaving = true; - } - if (this.checkTimer) { - window.clearInterval(this.checkTimer); - this.checkTimer = null; - } - if (this.saveTimeout) { - window.clearTimeout(this.saveTimeout); - this.saveTimeout = null; - } - }); - - if (needsSaving) { - $("#features_success").css("visibility", "hidden"); - Admin.saveFeature(feature); + closeEditor: function() { + if (this.currentFeature && this.currentFeature.layer) { + this.selFeatureControl.unselect(this.currentFeature); } - - window.clearTimeout(Admin.onDragComplete.timeout); - Admin.onDragComplete.timeout = null; - }, - - addNewFeature: function () { - this.selectControl.unselectAll(); - $("#features_success").css("visibility", "hidden"); - $("#features_connect_error").hide(); - $("#addphoto_button").attr("disabled", "disabled"); - $("#newimage").show(); - $("#file_form").show(); - $("#file_form").get(0).reset(); - $("#newimage_input").change(function () { - $("#newimage_error").hide(); - if (OpenLayers.Util.getBrowserName() == "msie") { - if ($("#file_form").find('input[type="submit"]').length == 0) { - $("#file_form").append( - '
' + - '
'); - $('#file_form > div > input[type="submit"]').focus(); - $("#file_form").one("submit", function () { - $("#file_form").find('input[type="submit"]'). - parent().remove(); - $("#newimage_throbber").css("visibility", "visible"); - }); - } - } else { - $("#file_form").submit(); - $("#newimage_throbber").css("visibility", "visible"); + 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(); } - $("#fileframe").one("load", FeatureMgr.fileFrameLoad); }); - // works in webkit and in ie - // XXX: we want to call - // the real click method of newimage_input, not jquery click method - // because jquery click method prevents change listener to be called - // click event is running. - if (OpenLayers.Util.getBrowserName() != "msie") { - // XXX: in ie, it prevents submiting form - $("#newimage_input").get(0).click(); + 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(); } - // works in opera - $("#newimage_input").focus(); + $("#title").select().focus(); }, - closeNewimage: function () { - if ($("#newimage").css("display") == "none") { - return; + checkForFeatures: function () { + if (this.dataLayer.features.length != 0) { + $("#instructions").text("Pour modifier les données d'une image, sélectionnez le marqueur correspondant."); } - $("#newimage_input").unbind('change'); - $("#fileframe").unbind('load'); - $("#addphoto_button").removeAttr("disabled"); - $("#newimage_error").hide(); - $("#newimage_throbber").css("visibility", "hidden").show(); - $("#newimage_input").val(''); - FeatureMgr.itemDeleter.add($("#newimage_preview").attr("src")); - $("#newimage").hide(); - $("#newimage_preview").removeAttr("src"); - $("#newimage_preview").hide(); - $("#modify_howto").css("visibility", "visible"); - $("#newimage_warn").hide(); - this.clickControl.handler.callbacks.click = null; - this.clickControl.deactivate(); - this.selectControl.activate(); - }, - - closeEditor: function () { - $("#editor").hide(); - $(".input").unbind('change'); - $(".input").unbind('focus'); - $(".input").unbind('blur'); - $("#dragdrop_howto").css("visibility", "hidden"); }, - clearChangeTimeouts: function () { - $(".input").each(function (){ - if (this.checkTimer) { - window.clearInterval(this.checkTimer); - this.checkTimer = null; - } - if (this.saveTimeout) { - window.clearTimeout(this.saveTimeout); - this.saveTimeout = null; + addNewFeature: function () { + function cancel() { + $(document).unbind("keydown"); + Admin.reset() + } + $(document).unbind("keydown").keydown(function(e) { + if (e.keyCode == 27) { + e.preventDefault(); + cancel(); } }); - }, - - onDragComplete: { - timeout: null, - // we wait 3 seconds before saving in case user drags marker again - action: function (feature, pixel) { - if (this.timeout) { - window.clearTimeout(this.timeout); - } - var self = this; - this.timeout = window.setTimeout(function () { - self.timeout = null; - Admin.saveFeature(feature); - }, 3000); - } - }, - - saveFeature: function (feature) { - var imgurl = $("#img").attr("src"); - var title = $("#title_input").val(); - var description = $("#desc_input").val(); - - feature.attributes.name = this.Utils.escapeHTML(title); - feature.attributes.description = "

" + - this.Utils.escapeHTML(description) + - "

" + - ""; - var x = feature.geometry.x; - var y = feature.geometry.y; + $("#newfeature_button").val("annuler"); + $("#newfeature_button").unbind("click").click(cancel); - var mapProj = feature.layer.map.getProjectionObject(); - var lonlat = new OpenLayers.LonLat(x, y). - transform(mapProj, - new OpenLayers.Projection("EPSG:4326")); - - FeatureMgr.itemDeleter.unlock(imgurl); - FeatureMgr.saveFeature(feature, imgurl, title, description, lonlat); + $("#instructions").text("Cliquez sur la carte pour ajouter un marqueur."); + this.selFeatureControl.deactivate(); + this.addFeatureControl.activate(); + FeatureMgr.reset(); }, - deleteFeature: function (feature, imgurl) { - Admin.dataLayer.destroyFeatures([feature]); - FeatureMgr.deleteFeature(imgurl); + 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(); - this.closeEditor(); - }, - - connectErrorMsg: function (textStatus) { - if (textStatus == undefined) { - textStatus = "inconnue"; - } - return "Une erreur de type " + - textStatus + - " est survenue lors de la connexion au serveur." + - " Veuillez réessayer ou contacter l'administrateur du site."; }, Utils: { escapeHTML: function (str) { + if (!str) { + return ""; + } return str. replace(/&/gm, '&'). replace(/'/gm, '''). @@ -585,250 +321,217 @@ var Admin = { } } -var pwdMgr = { - - init: function () { - $("#login_form").submit(this.submit); - $("#user_pwd").focus().select(); +var FeatureMgr = { + reset: function() { + this.commError(""); }, - submit: function () { - // removes focus from #user_pwd before disabling it. Otherwise, opera - // prevents re-focusing it after re-enabling it. - $("#user_pwd").blur(); - $("#login_submit, #user_pwd").attr("disabled", "disabled"); - $("#login_connect_error, #login_password_error").hide(); - $("#pwd_throbber").css("visibility", "visible"); - - var req = { - type: this.method, - url: this.action, - data: { user_pwd: this.user_pwd.value }, - success: pwdMgr.postSuccessCallback, - error: pwdMgr.postErrorCallback, - timeout: 10000 - }; - - AjaxMgr.add(req); - return false; + add: function(evt) { + var map = Admin.map; + var pos = map.getLonLatFromViewPortPx(evt.xy); + feature = this.update (null, pos, "", "", ""); + Admin.addFeatureControl.deactivate(); + Admin.selFeatureControl.select(feature); }, - postErrorCallback: function (data, textStatus) { - $("#pwd_throbber").css("visibility", "hidden"); - $("#login_submit, #user_pwd").removeAttr("disabled"); - var errorText = Admin.connectErrorMsg(textStatus); - $("#login_connect_error").text(errorText).show(); - $("#user_pwd").focus().select(); + move: function (feature, aLocation) { + if (!feature || !aLocation) { + return; + } + var curLoc = feature.geometry; + feature.geometry.move(aLocation.x - curLoc.x, aLocation.y - curLoc.y); + feature.layer.drawFeature(feature); }, - postSuccessCallback: function (data) { - $("#pwd_throbber").css("visibility", "hidden"); - $("#login_submit, #user_pwd").removeAttr("disabled"); - if (data == "access allowed") { - $("#login_area").hide(); + update: function(feature, lonlat, imgurl, title, description) { + var point = new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat); + if (!feature) { + feature = new OpenLayers.Feature.Vector(point); + Admin.dataLayer.addFeatures([feature]); } else { - $("#login_password_error").show(); - $("#user_pwd").focus().select(); + this.move (feature, point); } - } -} - -var FeatureMgr = { - saveFeature: function (feature, imgurl, title, description, lonlat) { - $("#features_success").text("La sauvegarde a été réalisée avec succès"); - var req = { - type: "post", - url: "changes.php", - data: { feature_imgurl: imgurl, - feature_title: title, - feature_description: description, - feature_lon: lonlat.lon, - feature_lat: lonlat.lat - }, - success: this.featureSuccessCallback, - error: this.featureErrorCallback, - timeout: 10000 - }; - AjaxMgr.add(req); - }, - - deleteFeature: function (imgurl) { - $("#features_success").text("La suppression a été réalisée avec succès"); - var self = this; - - var req = { - type: "post", - url: "changes.php", - data: { feature_delete: imgurl }, - success: function (data) { - if (data == "request accepted") { - Admin.closeEditor(); - self.itemDeleter.add(imgurl); - } - self.featureSuccessCallback(data); - }, - error: this.featureErrorCallback, - timeout: 10000 - }; - AjaxMgr.add(req); + feature.attributes.name = title; + feature.attributes.description = "

" + 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) + }); }, - featureSuccessCallback: function (data) { - switch (data) { - case "request accepted": // do nothing: everything went fine - $("#features_success").css("visibility", "visible"); - return; - - case "access denied": - $("#login_area, #login_password_error").show(); - break; - - case "request error": - alert("Le serveur a été victime d'une erreur de requête. Il s'agit probablement d'un bug dans SYP."); - break; + save: function (feature) { + var x = feature.geometry.x; + var y = feature.geometry.y; - case "feature unavailable": - alert("La photo n'était pas référencée sur le serveur. Il est possible qu'elle ait été supprimée"); - break; + 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" + ); - case "server error": - default: - var text = Admin.connectErrorMsg(); - $("#features_connect_error").text(text).show(); - break; + if (feature.fid) { + form.find('input[name="request"]').val("update"); + } else { + form.find('input[name="request"]').val("add"); } - Admin.reloadLayer(Admin.dataLayer); - }, - - featureErrorCallback: function (data, textStatus) { - var text = Admin.connectErrorMsg(textStatus); - $("#features_connect_error").text(text).show(); - Admin.reloadLayer(Admin.dataLayer); + AjaxMgr.add({ + form: form, + oncomplete: OpenLayers.Function.bind(this.ajaxReply, this) + }); }, - fileFrameLoad: function () { - $("#newimage_throbber").hide(); - $("#newimage_input").val(''); - - var doc; - if (this.contentDocument) { - var doc = this.contentDocument; - } else if (this.contentWindow) { - var doc = this.contentWindow.document; - } else { - var doc = document.frames[this.id].document; + ajaxReply: function (data) { + if (!data) { + this.commError("Il s'est produit une erreur serveur."); + return; } - var body = $(doc.body); - - if (body.children().length <= 1) { // error are signaled with a simple - // string message - var resp = body.html(); - if (resp == "access denied") { - $("#login_area, #login_password_error").show(); - Admin.closeNewimage(); - } else if (resp == "file too big") { - var text = "L'image était trop grande et n'a pas été acceptée " + - "par le serveur. Veuillez réduire sa taille avant " + - "de l'envoyer."; - $("#newimage_error").text(text).show(); - $("#newimage_input").focus(); - } else if (resp == "not an image") { - var text = "Le fichier ne semble pas être une image."; - $("#newimage_error").text(text).show(); - $("#newimage_input").focus(); - } else { - var text = Admin.connectErrorMsg(); - $("#newimage_error").text(text).show(); - } - } else { // when image is successfully uploaded, informations are - // passed back in document body - var res = body.find('.res'); - if (res.text() == "request accepted") { - $("#newimage_input").unbind('change'); - $("#fileframe").unbind('load'); - $("#file_form").hide(); - - var imgurl = body.find('.infos > .imgurl').text(); - $("#newimage_preview").attr("src", imgurl); - $("#newimage_preview").css("display", "block"); - var text = "Pour valider l'ajout de cette image, vous devez la " + - " positionner sur la carte. Cliquez sur la carte pour " + - "positionner le marqueur."; - $("#newimage_warn").text(text).show(); - - var clickControl = Admin.clickControl; - clickControl.handler.callbacks.click = - Admin.addMarkerNewImage(imgurl); - clickControl.activate(); - - Admin.selectControl.deactivate(); - $("#modify_howto").css("visibility", "hidden"); - } else { - var text = Admin.connectErrorMsg(); - $("#newimage_error").text(text).show(); - } + 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; } }, - itemDeleter: { - _items: [], - _locks: [], - - _pushUnique: function (arr, item) { - if (Admin.Utils.indexOf(arr, item) == -1) { - arr.push(item); - } - }, - - add: function (imgurl) { - if (!imgurl) { - return; - } - if (Admin.Utils.indexOf(this._locks, imgurl) == -1) { - this._pushUnique(this._items, imgurl); - var brName = OpenLayers.Util.getBrowserName(); - // unload event does not work in opera, and webkit does not - // support xmlHttpRequests in unload, so we just don't buffer - // those requests. - if (brName == "opera" || brName == "safari") { - this.flush(); - } - } - }, - - lock: function (imgurl) { - this._pushUnique(this._locks, imgurl); - }, - - unlock: function (imgurl) { - var idx = Admin.Utils.indexOf(this._locks, imgurl); - while (idx != -1) { - this._locks.splice(idx, 1); - idx = Admin.Utils.indexOf(this._locks, imgurl); - } - }, + commSuccess: function (message) { + $("#server_comm").text(message); + $("#server_comm").removeClass().addClass("success"); + }, - flush: function () { - if (this._items.length == 0) { - return; - } - var i = 0; - var data = {}; - for (var i = 0; i < this._items.length; i++) { - data["imgurl_delete_" + i] = this._items[i]; - } - var req = { - type: "post", - url: "changes.php", - data: data, - success: function (data) { - }, - error: function (data) { - } - }; - AjaxMgr.add(req); - this._items = []; + commError: function (message) { + $("#server_comm").text(message); + $("#server_comm").removeClass().addClass("error"); + if (message.length) { + // this.move(Admin.currentFeature, Admin.currentFeatureLocation); + // Admin.reset(); } } } @@ -838,6 +541,8 @@ var FeatureMgr = { var AjaxMgr = { _queue: [], + running: false, + add: function(query) { this._queue.push(query); if (this._queue.length > 1) { @@ -849,20 +554,35 @@ var AjaxMgr = { _runQuery: function(query) { var self = this; - $.ajax({ - type: query.type, - url: query.url, - data: query.data, - success: function(data) { - self._reqEnd(); - query.success.call(query, data); - }, - error: function(data, textStatus) { - self._reqEnd(); - query.error.call(query, data, textStatus); - }, - timeout: query.timeout + $('#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() { @@ -873,19 +593,131 @@ var AjaxMgr = { } } +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(); - $("#newimage_close").click(function () { - Admin.closeNewimage(); - }); - $("#addphoto_button").click(function () { + $("#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(); }); -$(window).unload(function () { - FeatureMgr.itemDeleter.add($("#newimage_preview").attr("src")); - FeatureMgr.itemDeleter.flush(); -});