1 /* This file is part of Syj, Copyright (c) 2010-2011 Arnaud Renevier,
2 and is published under the AGPL license. */
6 // avoid openlayers alerts
7 OpenLayers.Console.userError = function(error) {
8 SYJView.messenger.setMessage(error, "error");
11 OpenLayers.Layer.Vector.prototype.renderers = ["SVG2", "VML", "Canvas"];
17 $("geom_title").observe('contentchange', this.enableSubmit.bindAsEventListener(this));
22 if (this.status === "enabled") {
26 $("geom_title").disabled = false;
27 $("geom_title").activate();
28 $$("#geom_accept_container, #geom_title_container").invoke('removeClassName', "disabled");
29 this.status = "enabled";
34 if (this.status === "disabled") {
38 $("geom_title").blur();
39 $("geom_title").disabled = true;
40 $$("#geom_accept_container, #geom_title_container").invoke('addClassName', "disabled");
41 this.status = "disabled";
45 enableSubmit: function() {
46 $("geom_submit").disabled = false;
47 $("geom_accept").disabled = false;
48 this.status = "partial";
52 disableSubmit: function() {
53 $("geom_submit").blur();
54 $("geom_submit").disabled = true;
55 $("geom_accept").blur();
56 $("geom_accept").disabled = true;
57 this.status = "partial";
62 var SYJPathLength = (function(){
65 var pathLength = 0, unit;
66 if (SYJView.mode === 'view') {
67 if (SYJView.viewLayer.features.length) {
68 pathLength = SYJView.viewLayer.features[0].geometry.getGeodesicLength(Mercator);
71 pathLength = SYJView.editControl.handler.line.geometry.getGeodesicLength(Mercator);
74 if (pathLength === 0) {
75 $("path-length").hide();
78 $("path-length").show();
80 if (pathLength < 1000) {
82 pathLength = Math.round(pathLength * 100) / 100;
86 pathLength = Math.round(pathLength) / 1000;
89 $("path-length-content").update(pathLength + ' ' + unit);
94 var SYJDataUi = (function() {
97 getdeck = function() {
99 deck = new Deck("data_controls");
103 getinfotoggler = function() {
105 infotoggler = new Toggler('path-infos-content');
106 $("path-infos-toggler").insert({bottom: infotoggler.element});
107 var anchor = $("path-infos-anchor");
108 var parent = anchor.up('.menu-item');
112 anchor.observe('click', function(evt) {
114 infotoggler.toggle(evt);
116 document.observe('toggler:open', function(evt) {
117 if (evt.memo === infotoggler) {
118 // XXX: update informations
125 viewmode: function() {
126 getdeck().setIndex(0);
127 if ($("path-infos")) {
129 getinfotoggler().close();
130 $("path-infos").show();
133 editmode: function() {
134 getdeck().setIndex(1);
135 if ($("path-infos")) {
136 $("path-infos").hide();
142 OpenLayers.Handler.SyjModifiablePath = OpenLayers.Class(OpenLayers.Handler.ModifiablePath, {
143 mouseup: function(evt) {
144 // do not add a point when navigating
145 var mapControls = this.control.map.controls, idx, ctrl;
147 for (idx = mapControls.length; idx-->0; ) {
148 ctrl = mapControls[idx];
149 if (this.isCtrlNavigationActive(ctrl, evt)) {
153 return OpenLayers.Handler.ModifiablePath.prototype.mouseup.apply(this, arguments);
156 addPoints: function(pixel) {
157 // redraw before last point. As we have a special style for last point, we
158 // need to redraw before last point after adding a new point (otherwise, it
159 // keeps special style forever)
160 var oldpoint = this.point;
161 OpenLayers.Handler.ModifiablePath.prototype.addPoints.apply(this, arguments);
162 this.layer.drawFeature(oldpoint);
165 isCtrlNavigationActive: function(ctrl, evt) {
166 var tolerance = 4, xDiff, yDiff;
168 if (!(ctrl instanceof OpenLayers.Control.Navigation)) {
173 ctrl.zoomBox.active &&
174 ctrl.zoomBox.handler &&
175 ctrl.zoomBox.handler.active &&
176 ctrl.zoomBox.handler.dragHandler &&
177 ctrl.zoomBox.handler.dragHandler.start) {
182 !ctrl.dragPan.active ||
183 !ctrl.dragPan.handler ||
184 !ctrl.dragPan.handler.started ||
185 !ctrl.dragPan.handler.start) {
189 // if mouse moved 4 or less pixels, consider it has not moved.
192 xDiff = evt.xy.x - ctrl.dragPan.handler.start.x;
193 yDiff = evt.xy.y - ctrl.dragPan.handler.start.y;
195 if (Math.sqrt(Math.pow(xDiff,2) + Math.pow(yDiff,2)) <= tolerance) {
201 finalize: function(cancel) {
202 // do nothing. We don't want to finalize path
207 edit: new OpenLayers.StyleMap({
208 "default": new OpenLayers.Style({
209 pointRadius: "${radius}", // sized according to type attribute
210 fillColor: "#ffcc66",
211 strokeColor: "#ff9933",
213 strokeOpacity: "${opacity}",
214 fillOpacity: "${opacity}"
218 radius: function(feature) {
221 if (!(feature.geometry instanceof OpenLayers.Geometry.Point)) {
224 if (feature.type === "middle") {
227 features = feature.layer.features;
228 if (OpenLayers.Util.indexOf(features, feature) === 0) {
230 } else if (OpenLayers.Util.indexOf(features, feature) === features.length - 1) {
235 opacity: function (feature) {
236 if (feature.type === "middle") {
245 "select": new OpenLayers.Style({
246 externalGraphic: "icons/delete.png",
250 "select_for_canvas": new OpenLayers.Style({
252 fillColor: "lightblue"
257 view: new OpenLayers.StyleMap({
258 "default": new OpenLayers.Style({
266 var WGS84 = new OpenLayers.Projection("EPSG:4326");
267 var Mercator = new OpenLayers.Projection("EPSG:900913");
273 wkt: new OpenLayers.Format.WKT({ internalProjection: Mercator, externalProjection: WGS84 }),
274 needsFormResubmit: false,
279 var externalGraphic, baseURL, mapnikLayer, mapquestLayer, layerOptions, hidemessenger, layerCode, parameters;
281 // is svg context, opera does not resolve links with base element is svg context
282 externalGraphic = styleMap.edit.styles.select.defaultStyle.externalGraphic;
283 baseURL = document.getElementsByTagName("base")[0].href;
284 styleMap.edit.styles.select.defaultStyle.externalGraphic = baseURL + externalGraphic;
286 this.map = new OpenLayers.Map('map', {
288 new OpenLayers.Control.Navigation(),
289 new OpenLayers.Control.PanZoom(),
290 this.createLayerSwitcher(),
291 new OpenLayers.Control.Attribution()
296 mapnikLayer = new OpenLayers.Layer.OSM("Mapnik", [
297 'http://a.tile.openstreetmap.org/${z}/${x}/${y}.png',
298 'http://b.tile.openstreetmap.org/${z}/${x}/${y}.png',
299 'http://c.tile.openstreetmap.org/${z}/${x}/${y}.png'],
300 { attribution: SyjStrings.osmAttribution, layerCode: 'M' });
302 mapquestLayer = new OpenLayers.Layer.OSM("MapQuest", [
303 'http://otile1.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.png',
304 'http://otile2.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.png',
305 'http://otile3.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.png',
306 'http://otile4.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.png'],
307 { attribution: SyjStrings.mapquestAttribution, layerCode: 'Q'});
309 layerOptions = {format: OpenLayers.Format.WKT,
311 styleMap: styleMap.view,
312 attribution: SyjStrings.geomAttribution };
314 this.viewLayer = new OpenLayers.Layer.Vector("View Layer", layerOptions);
315 this.map.addLayers([mapnikLayer, mapquestLayer, this.viewLayer]);
317 this.map.setBaseLayer(mapnikLayer);
319 parameters = OpenLayers.Util.getParameters(window.location.href);
320 if (parameters.layer) {
321 layerCode = parameters.layer;
323 store.remove('baselayer');
327 layerCode = store.get('baselayer');
332 layerCode = layerCode.toUpperCase();
334 $([mapnikLayer, mapquestLayer]).each(function(layer) {
335 if (layer.layerCode === layerCode) {
336 self.map.setBaseLayer(layer);
341 this.map.events.register("changebaselayer", this, this.saveBaseLayer);
344 $("edit-btn").observe('click', function() {
345 $("geom_submit").value = SyjStrings.editAction;
346 this.messenger.clearMessages();
352 if ($("create-btn")) {
353 $("create-btn").observe('click', function() {
354 $("geom_submit").value = SyjStrings.createAction;
355 this.messenger.clearMessages();
357 this.mode = 'create';
361 if ($("clone-btn")) {
362 $("clone-btn").observe('click', function() {
363 $("geom_submit").value = SyjStrings.cloneAction;
364 $("geom_title").value = "";
365 this.messenger.clearMessages();
367 this.mode = 'create';
371 $("geomform").ajaxize({
372 presubmit: this.prepareForm.bind(this),
373 onSuccess: this.saveSuccess.bind(this),
374 onFailure: this.saveFailure.bind(this)
378 this.messenger = $('message');
379 hidemessenger = this.messenger.empty();
380 new CloseBtn(this.messenger, {
386 this.messenger.hide();
389 if (typeof gInitialGeom !== "undefined" && typeof gInitialGeom.data !== "undefined") {
390 this.viewLayer.addFeatures([this.wkt.read(gInitialGeom.data)]);
391 // XXX: ie has not guessed height of map main div yet during map
392 // initialisation. Now, it will read it correctly.
393 this.map.updateSize();
394 this.map.zoomToExtent(this.viewLayer.getDataExtent());
396 this.initMaPos(gInitialPos);
399 $("map-overlay").hide();
400 $("geom_upload").observe('change', function(evt) {
401 var file = null, reader = null, readerror = null;
402 if (window.FileList && window.FileReader) {
403 file = evt.target.files[0];
404 reader = new FileReader();
405 readerror = function() {
406 this.messenger.setMessage(SyjStrings.uploadFileError, "warn");
408 reader.onload = function(evt) {
409 var data = null, results = null, engine = null, vector = null, i = 0, format = null, formats = ['KML', 'GPX', 'GeoJSON'];
411 $("geom_upload_container").removeClassName("disabled");
412 $("geom_upload").disabled = false;
417 data = evt.target.result;
419 for (i = 0; i < formats.length; i++) {
421 engine = new OpenLayers.Format[format]({ internalProjection: Mercator, externalProjection: WGS84 });
423 results = engine.read(data);
426 if (results && results.length) {
430 if (!results || !results.length) {
436 if (vector.geometry.CLASS_NAME !== "OpenLayers.Geometry.LineString") {
440 // merge linestrings for gpx containting multiple trkseg elements.
441 if (format === 'GPX') {
442 for (i = 1; i < results.length; i++) {
443 vector.geometry.addComponents(results[i].geometry.components);
446 this.viewLayer.addFeatures([vector]);
447 this.map.zoomToExtent(this.viewLayer.getDataExtent());
450 $("edit-btn").click();
451 } else if ($("create-btn")) {
452 $("create-btn").click();
455 if (this.editControl.handler.realPoints.length < 2) {
461 if (vector.data && vector.data.name) {
462 $("geom_title").value = vector.data.name;
465 $("geom_upload_container").addClassName("disabled");
466 $("geom_upload").disabled = true;
467 reader.readAsText(file);
470 $("map-overlay").show();
472 this.editControl.deactivate();
475 document.observe('simplebox:shown', this.observer.bindAsEventListener(this));
476 SYJPathLength.update();
479 saveBaseLayer: function(data) {
481 store.set('baselayer', data.layer.layerCode);
485 createLayerSwitcher: function() {
486 var control = new OpenLayers.Control.LayerSwitcher({roundedCorner: false});
487 // XXX: we need to "live-patch" LayerSwitcher to use our icons. We use
488 // a regexp instead of a string in case OpenLayers is modified and in
489 // case browsers modify the function representation
490 control.loadContents = eval('(function() { return (' + control.loadContents.toString().replace(
491 /\s*=\s*imgLocation\s*\+\s*['"]layer-switcher-maximize\.png['"]\s*;/,
492 " = 'icons/layer-switcher-maximize-flipped.png';"
494 var oldMaximizeControl = control.maximizeControl;
496 control.maximizeControl = (function(oldfunc) {
498 oldfunc.apply(control, arguments);
499 self.messenger.hide();
501 }(control.maximizeControl));
506 initMaPos: function (aPos) {
507 var extent = null, center = null, zoom = 0;
509 if (aPos.hasOwnProperty('lon') && aPos.hasOwnProperty('lat') && aPos.hasOwnProperty('zoom')) {
510 center = new OpenLayers.LonLat(parseFloat(aPos.lon), parseFloat(aPos.lat)).transform(WGS84, Mercator);
511 zoom = parseInt(aPos.zoom, 10);
512 } else if (aPos.hasOwnProperty('minlon') && aPos.hasOwnProperty('minlat')
513 && aPos.hasOwnProperty('maxlon') && aPos.hasOwnProperty('maxlat')) {
514 extent = new OpenLayers.Bounds(aPos.minlon, aPos.minlat, aPos.maxlon, aPos.maxlat)
515 .transform(WGS84, Mercator);
517 extent = new OpenLayers.Bounds(-160, -70, 160, 70).transform(WGS84, Mercator);
521 this.map.zoomToExtent(extent);
523 this.map.setCenter(center, zoom);
527 observer: function(evt) {
528 if (evt.eventName === "simplebox:shown" && evt.memo.element !== $("termsofusearea")) {
529 this.messenger.clearMessages();
533 prepareForm: function(form) {
534 if (!LoginMgr.logged && !$("geom_accept").checked) {
535 this.messenger.setMessage(SyjStrings.acceptTermsofuseWarn, "warn");
536 $("geom_accept_container").highlight('#F08080');
537 $("geom_accept").activate();
541 var line, realPoints, idx;
543 line = new OpenLayers.Geometry.LineString();
544 realPoints = this.editControl.handler.realPoints;
545 for (idx = 0; idx < realPoints.length; idx++) {
546 line.addComponent(realPoints[idx].geometry.clone());
548 this.viewLayer.addFeatures(new OpenLayers.Feature.Vector(line));
552 if (line.components.length) {
553 $("geom_data").value = this.wkt.write(new OpenLayers.Feature.Vector(line));
555 $("geom_data").value = "";
558 if (this.mode === "edit" && typeof gLoggedInfo.pathid !== "undefined") {
559 $("geomform").setAttribute("action", "path/" + gLoggedInfo.pathid.toString() + '/update');
561 $("geomform").setAttribute("action", "path");
563 this.needsFormResubmit = false;
564 SyjSaveUI.disable.bind(SyjSaveUI).defer();
565 this.messenger.clearMessages();
569 viewMode: function() {
570 var handler = this.editControl.handler;
571 OpenLayers.Handler.ModifiablePath.prototype.finalize.apply(handler, arguments);
572 // we need to recreate them on next createFeature; otherwise
573 // they'll reference destroyed features
574 delete(handler.handlers.drag);
575 delete(handler.handlers.feature);
576 this.editControl.deactivate();
579 editMode: function() {
580 var components, point0, point, pixels, pixel, idx;
582 this.initEditControl();
584 this.editControl.activate();
585 if (this.viewLayer.features.length) {
586 components = this.viewLayer.features[0].geometry.components;
587 point0 = components[0];
589 pixel = this.map.getPixelFromLonLat(new OpenLayers.LonLat(point0.x, point0.y));
590 this.editControl.handler.createFeature(pixel);
591 this.editControl.handler.lastUp = pixel;
593 for (idx = 1; idx < components.length; idx++) {
594 point = components[idx];
595 pixels.push(this.map.getPixelFromLonLat(new OpenLayers.LonLat(point.x, point.y)));
597 this.editControl.handler.addPoints(pixels);
599 this.unsavedRoute = {
600 features: this.viewLayer.features.invoke('clone'),
601 title: $("geom_title").value
605 this.viewLayer.destroyFeatures();
607 SYJDataUi.editmode();
608 if (this.editControl.handler.realPoints && this.editControl.handler.realPoints.length >= 2) {
609 SyjSaveUI.disableSubmit();
615 initEditControl: function() {
618 if (this.editControl) {
622 this.editControl = new OpenLayers.Control.DrawFeature(new OpenLayers.Layer.Vector(), OpenLayers.Handler.SyjModifiablePath, {
624 modify: function(f, line) {
625 SYJPathLength.update();
627 var npoints = this.handler.realPoints.length;
629 $("geom_upload_container").show();
630 SYJView.unsavedRoute = null;
632 if (!SYJView.unsavedRoute) {
633 SYJView.unsavedRoute = {};
643 create: function(f, line) {
644 this.messenger.clearMessages();
645 $("geom_upload_container").hide();
651 styleMap: styleMap.edit
655 this.map.addControl(this.editControl);
656 if (this.editControl.layer.renderer instanceof OpenLayers.Renderer.Canvas) {
657 // using externalGraphic with canvas renderer is definitively too buggy
658 styles = this.editControl.handler.layerOptions.styleMap.styles;
659 styles.select = styles.select_for_canvas;
663 saveSuccess: function(transport) {
664 // server sends and empty response on success. If we get a response, that
665 // probably means an error or warning has been printed by server.
666 if (!transport.responseJSON && transport.responseText.length) {
667 this.saveFailure(null, 500);
671 this.unsavedRoute = null;
672 if (transport.responseJSON && (typeof transport.responseJSON.redirect === "string")) {
673 location = transport.responseJSON.redirect;
677 $('path-profile-content').select('img').each(function(img) {
679 var found = src.match('foo=bar(\\d*)');
682 num = parseInt(found[1], 10);
683 img.src = src.replace(found[0], 'foo=bar' + (num+1));
684 } else if (src.indexOf('?') === -1) {
685 img.src = img.src + '?foo=bar0';
687 img.src = img.src + '&foo=bar0';
691 this.messenger.setMessage(SyjStrings.saveSuccess, "success");
692 SYJDataUi.viewmode();
693 document.title = $('geom_title').value;
696 saveFailure: function(transport, httpCode) {
698 if (typeof httpCode === "undefined") {
699 httpCode = transport? transport.getStatus(): 0;
704 message = SyjStrings.notReachedError;
708 message = SyjStrings.requestError;
712 SYJLogin.messenger.setMessage(SyjStrings.loginNeeded, "warn");
713 SYJLogin.modalbox.show();
714 this.needsFormResubmit = true;
717 message = SyjStrings.gonePathError;
720 message = SyjStrings.serverError;
721 this.needsFormResubmit = true;
724 message = SyjStrings.unknownError;
729 // is some cases, we let the user resubmit, in some other cases, he
730 // needs to modify the path before submitting again
731 if (this.needsFormResubmit) {
735 this.messenger.setMessage(message, "error");
739 var SYJModalClass = Class.create({
743 this.area = $(this.type + '_area');
744 this.messenger = $(this.type + "_message");
745 this.modalbox = new SimpleBox(this.area, {
746 closeMethods: ["onescapekey", "onouterclick", "onbutton"]
749 var anchor = $(this.type + '_control_anchor');
750 var parent = anchor.up('.menu-item');
754 anchor.observe("click", function(evt) {
755 this.modalbox.show();
757 }.bindAsEventListener(this));
759 document.observe('simplebox:shown', this.observer.bindAsEventListener(this));
760 document.observe('simplebox:hidden', this.observer.bindAsEventListener(this));
762 $(this.type + "form").ajaxize({
763 presubmit: this.presubmit.bind(this),
764 onSuccess: this.success.bind(this),
765 onFailure: this.failure.bind(this)
769 checkNotEmpty: function(input, message) {
770 if ($(input).value.strip().empty()) {
771 this.messenger.setMessage(message, "warn");
772 $(input).highlight('#F08080').activate();
778 observer: function(evt) {
779 var simplebox, input;
781 if (evt.eventName === "simplebox:shown" && evt.memo.element !== $("termsofusearea")) {
782 simplebox = evt.memo;
783 if (simplebox === this.modalbox) {
784 input = this.area.select('input[type="text"]')[0];
789 this.modalbox.hide();
792 } else if (evt.eventName === "simplebox:hidden" && evt.memo.element !== $("termsofusearea")) {
793 simplebox = evt.memo;
794 if (simplebox === this.modalbox) {
800 failure: function(transport) {
801 var httpCode = 0, message = SyjStrings.unknownError, input; // default message error
804 httpCode = transport.getStatus();
809 message = SyjStrings.notReachedError;
814 message = SyjStrings.requestError;
817 message = SyjStrings.serverError;
821 this.messenger.setMessage(message, "error");
822 input = this.area.select('input[type="text"]')[0];
823 input.highlight('#F08080').activate();
827 this.messenger.clearMessages();
828 this.area.select('.message').invoke('setMessageStatus', null);
832 var SYJUserClass = Class.create(SYJModalClass, {
836 init: function($super) {
838 $("termsofusearea").hide();
840 var touevt = (function(evt) {
841 if (evt.type === "keyup" && evt.keyCode !== 32) { // 32 = space
842 // allow opening box by pressing space
846 this.toubox = new SimpleBox($("termsofusearea"), {
847 closeMethods: ["onescapekey", "onouterclick", "onbutton"]
851 if (!$("termsofuseiframe").getAttribute("src")) {
852 $("termsofusearea").show();
853 $("termsofuseiframe").setAttribute("src", evt.target.href);
856 }).bindAsEventListener(this);
858 ["click", "keyup"].each(function (evtName) {
859 $$("#user_termsofuse_anchor, #geom_termsofuse_anchor").invoke('observe', evtName, touevt);
862 $$("#login_area_create > a").invoke('observe', 'click',
864 this.modalbox.show();
866 }.bindAsEventListener(this));
868 $("user_pseudo-desc").hide();
869 $("user_pseudo").observe('contentchange', function(evt) {
870 var value = evt.target.value;
871 PseudoChecker.reset();
872 if (value && !(value.match(/^[a-zA-Z0-9_.]+$/))) {
873 $("user_pseudo-desc").show().setMessageStatus("warn");
875 $("user_pseudo-desc").hide();
877 }).timedobserve(function() {
878 PseudoChecker.check();
881 $("user_password").observe('contentchange', function(evt) {
882 if (evt.target.value.length < 6) {
883 $("user_password-desc").setMessageStatus("warn");
885 $("user_password-desc").setMessageStatus("success");
887 }.bindAsEventListener(this));
889 $('account-create-anchor').insert({after: new Toggler('account-info').element});
892 presubmit: function() {
893 this.messenger.clearMessages();
894 PseudoChecker.reset();
895 if (!(this.checkNotEmpty("user_pseudo", SyjStrings.userEmptyWarn))) {
899 if (!($("user_pseudo").value.match(/^[a-zA-Z0-9_.]+$/))) {
900 $("user_pseudo-desc").show().setMessageStatus("warn");
901 $("user_pseudo").highlight('#F08080').activate();
905 if (PseudoChecker.exists[$("user_pseudo").value]) {
906 PseudoChecker.availableMessage(false);
907 $("user_pseudo").highlight('#F08080').activate();
911 if (!(this.checkNotEmpty("user_password", SyjStrings.passwordEmptyWarn))) {
915 if ($("user_password").value.length < 6) {
916 $("user_password-desc").setMessageStatus("warn");
917 $("user_password").highlight('#F08080').activate();
921 if ($("user_password").value !== $("user_password_confirm").value) {
922 this.messenger.setMessage(SyjStrings.passwordNoMatchWarn, "warn");
923 $("user_password").highlight('#F08080').activate();
927 if (!(this.checkNotEmpty("user_email", SyjStrings.emailEmptyWarn))) {
931 if (!$("user_accept").checked) {
932 this.messenger.setMessage(SyjStrings.acceptTermsofuseWarn, "warn");
933 $("user_accept_container").highlight('#F08080');
934 $("user_accept").activate();
942 success: function(transport) {
943 if (!transport.responseJSON ||
944 typeof transport.responseJSON.pseudo !== "string"
946 this.messenger.setMessage(SyjStrings.unknownError, "error");
950 LoginMgr.login(transport.responseJSON.pseudo);
951 SYJView.messenger.setMessage(SyjStrings.userSuccess, "success");
952 this.modalbox.hide();
953 if (SYJView.needsFormResubmit) {
954 SYJView.messenger.addMessage(SyjStrings.canResubmit);
955 $("geom_submit").activate();
959 failure: function($super, transport) {
960 var httpCode = 0, focusInput = null, message = "";
963 httpCode = transport.getStatus();
971 if (transport.responseJSON) {
972 switch (transport.responseJSON.message) {
974 message = SyjStrings.emailInvalidWarn;
975 focusInput = $("user_email");
978 PseudoChecker.availableMessage(false);
979 focusInput = $("user_pseudo");
982 message = SyjStrings.uniqueEmailError;
983 focusInput = $("user_email");
992 this.messenger.setMessage(message, "error");
994 focusInput.highlight('#F08080').activate();
1001 var SYJUser = new SYJUserClass();
1003 var SYJLoginClass = Class.create(SYJModalClass, {
1006 init: function($super) {
1010 presubmit: function() {
1011 this.messenger.clearMessages();
1012 if (!(this.checkNotEmpty("login_user", SyjStrings.userEmptyWarn))) {
1020 success: function(transport) {
1021 if (!transport.responseJSON ||
1022 typeof transport.responseJSON.iscreator !== "boolean" ||
1023 typeof transport.responseJSON.pseudo !== "string"
1025 this.messenger.setMessage(SyjStrings.unknownError, "error");
1028 LoginMgr.login(transport.responseJSON.pseudo, transport.responseJSON.iscreator);
1030 SYJView.messenger.setMessage(SyjStrings.loginSuccess, "success");
1031 this.modalbox.hide();
1032 if (SYJView.needsFormResubmit) {
1033 SYJView.messenger.addMessage(SyjStrings.canResubmit);
1034 $("geom_submit").activate();
1038 failure: function($super, transport) {
1039 var httpCode = 0, focusInput = null, message = "";
1042 httpCode = transport.getStatus();
1050 message = SyjStrings.loginFailure;
1051 focusInput = $("login_user");
1056 this.messenger.setMessage(message, "error");
1058 focusInput.highlight('#F08080').activate();
1066 var SYJLogin = new SYJLoginClass();
1068 var SYJNewpwdClass = Class.create(SYJModalClass, {
1071 presubmit: function() {
1072 if (!(this.checkNotEmpty("newpwd_email", SyjStrings.emailEmptyWarn))) {
1078 success: function(transport) {
1079 SYJView.messenger.setMessage(SyjStrings.newpwdSuccess, "success");
1080 this.modalbox.hide();
1084 var SYJNewpwd = new SYJNewpwdClass();
1086 var LoginMgr = Object.extend(gLoggedInfo, {
1089 updateUI: function() {
1090 if (!this.controlsdeck) {
1091 this.controlsdeck = new Deck("login_controls");
1094 this.controlsdeck.setIndex(1);
1095 $$(".logged-hide").invoke('hide');
1096 $$(".logged-show").invoke('show');
1098 this.controlsdeck.setIndex(0);
1099 $$(".logged-hide").invoke('show');
1100 $$(".logged-show").invoke('hide');
1103 if ($("edit-btn")) {
1104 if (this.iscreator && SYJView.mode === 'view') {
1105 $("edit-btn").show();
1107 $("edit-btn").hide();
1112 login: function(aPseudo, aIsCreator) {
1113 if (typeof aIsCreator === "boolean") {
1114 this.iscreator = aIsCreator;
1117 $$('.logged-pseudo').each(function(elt) {
1118 $A(elt.childNodes).filter(function(node) {
1119 return (node.nodeType === 3 || node.tagName.toLowerCase() === 'br');
1120 }).each(function(node) {
1121 node.nodeValue = node.nodeValue.replace('%s', aPseudo);
1128 var PseudoChecker = {
1135 message: function(str, status, throbber) {
1137 if (!this.messageelt) {
1138 row = new Element('tr');
1139 // we can't use row.update('<td></td><td><div></div></td>')
1140 // because gecko would mangle the <td>s
1141 row.insert(new Element('td'))
1142 .insert((new Element('td')).update(new Element('div')));
1144 $("user_pseudo").up('tr').insert({after: row});
1145 this.messageelt = new Element('span');
1146 this.throbber = new Element("img", { src: "icons/throbber.gif"});
1147 row.down('div').insert(this.throbber).insert(this.messageelt);
1150 this.throbber.show();
1152 this.throbber.hide();
1154 this.messageelt.up().setStyle({visibility: ''});
1155 this.messageelt.className = status;
1156 this.messageelt.update(str);
1159 availableMessage: function(available) {
1160 var message = available ? SyjStrings.availablePseudo: SyjStrings.unavailablePseudo,
1161 status = available ? "success": "warn";
1162 this.message(message, status, false);
1168 this.req = this.currentvalue = null;
1170 if (this.messageelt) {
1171 this.messageelt.up().setStyle({visibility: 'hidden'});
1176 var pseudo = $("user_pseudo").value;
1180 if (!pseudo || !(pseudo.match(/^[a-zA-Z0-9_.]+$/))) {
1184 if (typeof this.exists[pseudo] === "boolean") {
1186 this.availableMessage(!this.exists[pseudo]);
1190 this.message(SyjStrings.pseudoChecking, "", true);
1192 this.currentvalue = pseudo;
1193 this.req = new Ajax.TimedRequest('userexists/' + encodeURIComponent(pseudo), 20, {
1194 onFailure: this.failure.bind(this),
1195 onSuccess: this.success.bind(this)
1199 failure: function(transport) {
1200 var httpCode = 0, value = this.currentvalue;
1203 httpCode = transport.getStatus();
1206 if (httpCode === 404) {
1207 this.exists[value] = false;
1208 this.availableMessage(true);
1213 success: function(transport) {
1214 var httpCode = transport.getStatus(), value = this.currentvalue;
1216 this.exists[value] = true;
1217 this.availableMessage(false);
1221 var Nominatim = (function() {
1222 var presubmit = function() {
1223 var input = $("nominatim-search");
1224 if (input.value.strip().empty()) {
1225 $("nominatim-message").setMessage(SyjStrings.notEmptyField, "warn");
1229 $("nominatim-suggestions").hide();
1230 $("nominatim-message").hide();
1231 $("nominatim-throbber").show();
1235 var zoomToExtent = function(bounds) { // we must call map.setCenter with forceZoomChange to true. See ol#2798
1236 var center = bounds.getCenterLonLat();
1237 if (this.baseLayer.wrapDateLine) {
1238 var maxExtent = this.getMaxExtent();
1239 bounds = bounds.clone();
1240 while (bounds.right < bounds.left) {
1241 bounds.right += maxExtent.getWidth();
1243 center = bounds.getCenterLonLat().wrapDateLine(maxExtent);
1245 this.setCenter(center, this.getZoomForExtent(bounds), false, true);
1248 var success = function(transport) {
1249 $("nominatim-throbber").hide();
1251 if (!transport.responseJSON || !transport.responseJSON.length) {
1252 $("nominatim-message").setMessage(SyjStrings.noResult, 'error');
1253 $("nominatim-search").activate();
1257 var place = transport.responseJSON[0],
1258 bbox = place.boundingbox;
1260 if (!bbox || bbox.length !== 4) {
1261 $("nominatim-message").setMessage(SyjStrings.requestError, 'error');
1265 extent = new OpenLayers.Bounds(bbox[2], bbox[1], bbox[3], bbox[0]).transform(WGS84, Mercator);
1266 zoomToExtent.call(SYJView.map, extent);
1268 $("nominatim-suggestions-list").update();
1270 var clickhandler = function(bbox) {
1271 return function(evt) {
1273 var extent = new OpenLayers.Bounds(bbox[2], bbox[1], bbox[3], bbox[0]).transform(WGS84, Mercator);
1274 $("nominatim-suggestions-list").select("li").invoke('removeClassName', 'current');
1275 evt.target.up('li').addClassName('current');
1276 SYJView.map.zoomToExtent(extent);
1281 for (i = 0; i < transport.responseJSON.length; i++) {
1282 var item = transport.responseJSON[i];
1283 if (item.display_name && item.boundingbox && item.boundingbox.length === 4) {
1284 var li = new Element("li");
1285 var anchor = new Element("a", {
1287 className: "nominatim-suggestions-link"
1290 anchor.observe('click', clickhandler(item.boundingbox));
1291 Element.text(anchor, item.display_name);
1293 var icon = new Element("img", {
1294 className: "nominatim-suggestions-icon",
1295 src: item.icon || 'icons/world.png'
1297 li.insert(icon).insert(anchor);
1298 $("nominatim-suggestions-list").insert(li);
1299 if ($("nominatim-suggestions-list").childNodes.length >= 6) {
1305 if ($("nominatim-suggestions-list").childNodes.length > 1) {
1306 var bottomOffset = $('data_controls').measure('height') + 3;
1307 $("nominatim-suggestions").setStyle({
1308 bottom: (document.viewport.getHeight() - $('data_controls').cumulativeOffset().top + 3).toString() + 'px'
1310 $("nominatim-suggestions-list").select("li:first-child")[0].addClassName('current');
1312 $("nominatim-suggestions").hide();
1317 var failure = function(transport) {
1318 $("nominatim-throbber").hide();
1320 var httpCode = 0, message = SyjStrings.unknownError, input; // default message error
1323 httpCode = transport.getStatus();
1328 message = SyjStrings.notReachedError;
1332 message = SyjStrings.requestError;
1335 message = SyjStrings.serverError;
1339 $("nominatim-message").setMessage(message, 'error');
1344 if (!$("nominatim-form")) {
1347 $("nominatim-controls").hide();
1348 $("nominatim-label").observe('click', function(evt) {
1349 $("nominatim-controls").show();
1350 $("nominatim-search").activate();
1354 $("nominatim-form").ajaxize({
1355 presubmit: presubmit,
1359 new CloseBtn($("nominatim-suggestions"));
1361 $$("#nominatim-message, #nominatim-suggestions, #nominatim-throbber").invoke('hide');
1366 document.observe("dom:loaded", function() {
1369 SYJDataUi.viewmode();
1372 LoginMgr.updateUI();
1376 window.onbeforeunload = function() {
1377 if (SYJView.unsavedRoute) {
1378 return SyjStrings.unsavedConfirmExit;