aboutsummaryrefslogtreecommitdiffstats
path: root/web/js/map-OpenLayers.js
blob: baa8d7810ddd05593211639a1d3d6ad693df276e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
// This function might be passed either an OpenLayers.LonLat (so has
// lon and lat) or an OpenLayers.Geometry.Point (so has x and y)
function fixmystreet_update_pin(lonlat) {
    lonlat.transform(
        fixmystreet.map.getProjectionObject(),
        new OpenLayers.Projection("EPSG:4326")
    );
    document.getElementById('fixmystreet.latitude').value = lonlat.lat || lonlat.y;
    document.getElementById('fixmystreet.longitude').value = lonlat.lon || lonlat.x;

    $.getJSON('/report/new/ajax', {
            latitude: $('#fixmystreet\\.latitude').val(),
            longitude: $('#fixmystreet\\.longitude').val()
    }, function(data) {
        if (data.error) {
            if (!$('#side-form-error').length) {
                $('<div id="side-form-error"/>').insertAfter($('#side-form'));
            }
            $('#side-form-error').html('<h1>' + translation_strings.reporting_a_problem + '</h1><p>' + data.error + '</p>').show();
            $('#side-form').hide();
            return;
        }
        $('#side-form, #site-logo').show();
        $('#councils_text').html(data.councils_text);
        $('#form_category_row').html(data.category);
        if ( data.extra_name_info && !$('#form_fms_extra_title').length ) {
            // there might be a first name field on some cobrands
            var lb = $('#form_first_name').prev();
            if ( lb.length === 0 ) { lb = $('#form_name').prev(); }
            lb.before(data.extra_name_info);
        }
    });

    if (!$('#side-form-error').is(':visible')) {
        $('#side-form, #site-logo').show();
    }
}

function fixmystreet_activate_drag() {
    fixmystreet.drag = new OpenLayers.Control.DragFeature( fixmystreet.markers, {
        onComplete: function(feature, e) {
            fixmystreet_update_pin( feature.geometry.clone() );
        }
    } );
    fixmystreet.map.addControl( fixmystreet.drag );
    fixmystreet.drag.activate();
}

// Need to try and fake the 'centre' being 75% from the left
function fixmystreet_midpoint() {
    var $content = $('.content'), mb = $('#map_box'),
        q = ( $content.offset().left - mb.offset().left + $content.width() ) / 2,
        mid_point = q < 0 ? 0 : q;
    return mid_point;
}

function fixmystreet_zoomToBounds(bounds) {
    if (!bounds) { return; }
    var center = bounds.getCenterLonLat();
    var z = fixmystreet.map.getZoomForExtent(bounds);
    if ( z < 13 && $('html').hasClass('mobile') ) {
        z = 13;
    }
    fixmystreet.map.setCenter(center, z);
    if (fixmystreet.state_map && fixmystreet.state_map == 'full') {
        fixmystreet.map.pan(-fixmystreet_midpoint(), -25, { animate: false });
    }
}

function fms_markers_list(pins, transform) {
    var markers = [];
    for (var i=0; i<pins.length; i++) {
        var pin = pins[i];
        var loc = new OpenLayers.Geometry.Point(pin[1], pin[0]);
        if (transform) {
            // The Strategy does this for us, so don't do it in that case.
            loc.transform(
                new OpenLayers.Projection("EPSG:4326"),
                fixmystreet.map.getProjectionObject()
            );
        }
        var marker = new OpenLayers.Feature.Vector(loc, {
            colour: pin[2],
            size: pin[5] || 'normal',
            id: pin[3],
            title: pin[4] || ''
        });
        markers.push( marker );
    }
    return markers;
}

function fixmystreet_onload() {
    if ( fixmystreet.area.length ) {
        for (var i=0; i<fixmystreet.area.length; i++) {
            var area = new OpenLayers.Layer.Vector("KML", {
                strategies: [ new OpenLayers.Strategy.Fixed() ],
                protocol: new OpenLayers.Protocol.HTTP({
                    url: "/mapit/area/" + fixmystreet.area[i] + ".kml?simplify_tolerance=0.0001",
                    format: new OpenLayers.Format.KML()
                })
            });
            fixmystreet.map.addLayer(area);
            if ( fixmystreet.area.length == 1 ) {
                area.events.register('loadend', null, function(a,b,c) {
                    if ( fixmystreet.area_format ) {
                        area.styleMap.styles['default'].defaultStyle = fixmystreet.area_format;
                    }
                    fixmystreet_zoomToBounds( area.getDataExtent() );
                });
            }
        }
    }

    var pin_layer_style_map = new OpenLayers.StyleMap({
        'default': new OpenLayers.Style({
            graphicTitle: "${title}",
            graphicOpacity: 1,
            graphicZIndex: 11,
            backgroundGraphicZIndex: 10
        })
    });
    pin_layer_style_map.addUniqueValueRules('default', 'size', {
        'normal': {
            externalGraphic: fixmystreet.pin_prefix + "pin-${colour}.png",
            graphicWidth: 48,
            graphicHeight: 64,
            graphicXOffset: -24,
            graphicYOffset: -64,
            backgroundGraphic: fixmystreet.pin_prefix + "pin-shadow.png",
            backgroundWidth: 60,
            backgroundHeight: 30,
            backgroundXOffset: -7,
            backgroundYOffset: -30
        },
        'big': {
            externalGraphic: fixmystreet.pin_prefix + "pin-${colour}-big.png",
            graphicWidth: 78,
            graphicHeight: 105,
            graphicXOffset: -39,
            graphicYOffset: -105,
            backgroundGraphic: fixmystreet.pin_prefix + "pin-shadow-big.png",
            backgroundWidth: 88,
            backgroundHeight: 40,
            backgroundXOffset: -10,
            backgroundYOffset: -35
        }
    });
    var pin_layer_options = {
        rendererOptions: {
            yOrdering: true
        },
        styleMap: pin_layer_style_map
    };
    if (fixmystreet.page == 'around') {
        fixmystreet.bbox_strategy = fixmystreet.bbox_strategy || new OpenLayers.Strategy.BBOX({ ratio: 1 });
        pin_layer_options.strategies = [ fixmystreet.bbox_strategy ];
        pin_layer_options.protocol = new OpenLayers.Protocol.HTTP({
            url: '/ajax',
            params: fixmystreet.all_pins ? { all_pins: 1 } : { },
            format: new OpenLayers.Format.FixMyStreet()
        });
    }
    fixmystreet.markers = new OpenLayers.Layer.Vector("Pins", pin_layer_options);
    fixmystreet.markers.events.register( 'loadend', fixmystreet.markers, function(evt) {
        if (fixmystreet.map.popups.length) {
            fixmystreet.map.removePopup(fixmystreet.map.popups[0]);
        }
    });

    var markers = fms_markers_list( fixmystreet.pins, true );
    fixmystreet.markers.addFeatures( markers );
    function onPopupClose(evt) {
        fixmystreet.select_feature.unselect(selectedFeature);
        OpenLayers.Event.stop(evt);
    }
    if (fixmystreet.page == 'around' || fixmystreet.page == 'reports' || fixmystreet.page == 'my') {
        fixmystreet.select_feature = new OpenLayers.Control.SelectFeature( fixmystreet.markers );
        var selectedFeature;
        fixmystreet.markers.events.register( 'featureunselected', fixmystreet.markers, function(evt) {
            var feature = evt.feature, popup = feature.popup;
            fixmystreet.map.removePopup(popup);
            popup.destroy();
            feature.popup = null;
        });
        fixmystreet.markers.events.register( 'featureselected', fixmystreet.markers, function(evt) {
            var feature = evt.feature;
            selectedFeature = feature;
            var popup = new OpenLayers.Popup.FramedCloud("popup",
                feature.geometry.getBounds().getCenterLonLat(),
                null,
                feature.attributes.title + "<br><a href=/report/" + feature.attributes.id + ">" + translation_strings.more_details + "</a>",
                { size: new OpenLayers.Size(0,0), offset: new OpenLayers.Pixel(0,-40) },
                true, onPopupClose);
            feature.popup = popup;
            fixmystreet.map.addPopup(popup);
        });
        fixmystreet.map.addControl( fixmystreet.select_feature );
        fixmystreet.select_feature.activate();
    } else if (fixmystreet.page == 'new') {
        fixmystreet_activate_drag();
    }
    fixmystreet.map.addLayer(fixmystreet.markers);

    if ( fixmystreet.zoomToBounds ) {
        fixmystreet_zoomToBounds( fixmystreet.markers.getDataExtent() );
    }

    $('#hide_pins_link').click(function(e) {
        e.preventDefault();
        var showhide = [
            'Show pins', 'Hide pins',
            'Dangos pinnau', 'Cuddio pinnau',
            "Vis nåler", "Skjul nåler",
            "Zeige Stecknadeln", "Stecknadeln ausblenden"
        ];
        for (var i=0; i<showhide.length; i+=2) {
            if (this.innerHTML == showhide[i]) {
                fixmystreet.markers.setVisibility(true);
                fixmystreet.select_feature.activate();
                this.innerHTML = showhide[i+1];
            } else if (this.innerHTML == showhide[i+1]) {
                fixmystreet.markers.setVisibility(false);
                fixmystreet.select_feature.deactivate();
                this.innerHTML = showhide[i];
            }
        }
    });

    $('#all_pins_link').click(function(e) {
        e.preventDefault();
        fixmystreet.markers.setVisibility(true);
        var texts = [
            'en', 'Show old', 'Hide old',
            'nb', 'Vis gamle', 'Skjul gamle',
            'cy', 'Cynnwys hen adroddiadau', 'Cuddio hen adroddiadau'
        ];
        for (var i=0; i<texts.length; i+=3) {
            if (this.innerHTML == texts[i+1]) {
                this.innerHTML = texts[i+2];
                fixmystreet.markers.protocol.options.params = { all_pins: 1 };
                fixmystreet.markers.refresh( { force: true } );
                lang = texts[i];
            } else if (this.innerHTML == texts[i+2]) {
                this.innerHTML = texts[i+1];
                fixmystreet.markers.protocol.options.params = { };
                fixmystreet.markers.refresh( { force: true } );
                lang = texts[i];
            }
        }
        if (lang == 'cy') {
            document.getElementById('hide_pins_link').innerHTML = 'Cuddio pinnau';
        } else if (lang == 'nb') {
            document.getElementById('hide_pins_link').innerHTML = 'Skjul nåler';
        } else {
            document.getElementById('hide_pins_link').innerHTML = 'Hide pins';
        }
    });

}

$(function(){

    // Set specific map config - some other JS included in the
    // template should define this
    set_map_config(); 

    // Create the basics of the map
    fixmystreet.map = new OpenLayers.Map(
        "map", OpenLayers.Util.extend({
            controls: fixmystreet.controls,
            displayProjection: new OpenLayers.Projection("EPSG:4326")
        }, fixmystreet.map_options)
    );

    // Need to do this here, after the map is created
    if ($('html').hasClass('mobile')) {
        if (fixmystreet.page == 'around') {
            $('#fms_pan_zoom').css({ top: '2.75em' });
        }
    } else {
        $('#fms_pan_zoom').css({ top: '4.75em' });
    }

    // Set it up our way

    var layer;
    if (!fixmystreet.layer_options) {
        fixmystreet.layer_options = [ {} ];
    }
    for (var i=0; i<fixmystreet.layer_options.length; i++) {
        fixmystreet.layer_options[i] = OpenLayers.Util.extend({
            // This option is used by XYZ-based layers
            zoomOffset: fixmystreet.zoomOffset,
            // This option is used by FixedZoomLevels-based layers
            minZoomLevel: fixmystreet.zoomOffset,
            // This option is thankfully used by them both
            numZoomLevels: fixmystreet.numZoomLevels
        }, fixmystreet.layer_options[i]);
        if (fixmystreet.layer_options[i].matrixIds) {
            layer = new fixmystreet.map_type(fixmystreet.layer_options[i]);
        } else {
            layer = new fixmystreet.map_type("", fixmystreet.layer_options[i]);
        }
        fixmystreet.map.addLayer(layer);
    }

    if (!fixmystreet.map.getCenter()) {
        var centre = new OpenLayers.LonLat( fixmystreet.longitude, fixmystreet.latitude );
        centre.transform(
            new OpenLayers.Projection("EPSG:4326"),
            fixmystreet.map.getProjectionObject()
        );
        fixmystreet.map.setCenter(centre, fixmystreet.zoom || 3);
    }

    if (fixmystreet.state_map && fixmystreet.state_map == 'full') {
        fixmystreet.map.pan(-fixmystreet_midpoint(), -25, { animate: false });
    }

    if (document.getElementById('mapForm')) {
        var click = new OpenLayers.Control.Click();
        fixmystreet.map.addControl(click);
        click.activate();
    }

    $(window).hashchange(function(){
        if (location.hash == '#report' && $('.rap-notes').is(':visible')) {
            $('.rap-notes-close').click();
            return;
        }

        if (location.hash && location.hash != '#') {
            return;
        }

        // Okay, back to around view.
        fixmystreet.bbox_strategy.activate();
        fixmystreet.markers.refresh( { force: true } );
        if ( fixmystreet.state_pins_were_hidden ) {
            // If we had pins hidden when we clicked map (which had to show the pin layer as I'm doing it in one layer), hide them again.
            $('#hide_pins_link').click();
        }
        fixmystreet.drag.deactivate();
        $('#side-form').hide();
        $('#side').show();
        $('#sub_map_links').show();
        //only on mobile
        $('#mob_sub_map_links').remove();
        $('.mobile-map-banner').html('<a href="/">' + translation_strings.home + '</a> ' + translation_strings.place_pin_on_map);
        fixmystreet.page = 'around';
    });

    // Vector layers must be added onload as IE sucks
    if ($.browser.msie) {
        $(window).load(fixmystreet_onload);
    } else {
        fixmystreet_onload();
    }
});

/* Overridding the buttonDown function of PanZoom so that it does
   zoomTo(0) rather than zoomToMaxExtent()
*/
OpenLayers.Control.PanZoomFMS = OpenLayers.Class(OpenLayers.Control.PanZoom, {
    onButtonClick: function (evt) {
        var btn = evt.buttonElement;
        switch (btn.action) {
            case "panup":
                this.map.pan(0, -this.getSlideFactor("h"));
                break;
            case "pandown":
                this.map.pan(0, this.getSlideFactor("h"));
                break;
            case "panleft":
                this.map.pan(-this.getSlideFactor("w"), 0);
                break;
            case "panright":
                this.map.pan(this.getSlideFactor("w"), 0);
                break;
            case "zoomin":
            case "zoomout":
            case "zoomworld":
                var mid_point = 0;
                if (fixmystreet.state_map && fixmystreet.state_map == 'full') {
                    mid_point = fixmystreet_midpoint();
                }
                var size = this.map.getSize(),
                    xy = { x: size.w / 2 + mid_point, y: size.h / 2 };
                switch (btn.action) {
                    case "zoomin":
                        this.map.zoomTo(this.map.getZoom() + 1, xy);
                        break;
                    case "zoomout":
                        this.map.zoomTo(this.map.getZoom() - 1, xy);
                        break;
                    case "zoomworld":
                        this.map.zoomTo(0, xy);
                        break;
                }
        }
    }
});

/* Overriding Permalink so that it can pass the correct zoom to OSM */
OpenLayers.Control.PermalinkFMS = OpenLayers.Class(OpenLayers.Control.Permalink, {
    _updateLink: function(alter_zoom) {
        var separator = this.anchor ? '#' : '?';
        var href = this.base;
        if (href.indexOf(separator) != -1) {
            href = href.substring( 0, href.indexOf(separator) );
        }

        var center = this.map.getCenter();
        if ( center && fixmystreet.state_map && fixmystreet.state_map == 'full' ) {
            // Translate the permalink co-ords so that 'centre' is accurate
            var mid_point = fixmystreet_midpoint();
            var p = this.map.getViewPortPxFromLonLat(center);
            p.x += mid_point;
            p.y += 25;
            center = this.map.getLonLatFromViewPortPx(p);
        }

        var zoom = this.map.getZoom();
        if ( alter_zoom ) {
            zoom += fixmystreet.zoomOffset;
        }
        href += separator + OpenLayers.Util.getParameterString(this.createParams(center, zoom));
        // Could use mlat/mlon here as well if we are on a page with a marker
        if (this.anchor && !this.element) {
            window.location.href = href;
        }
        else {
            this.element.href = href;
        }
    },
    updateLink: function() {
        this._updateLink(0);
    }
});
OpenLayers.Control.PermalinkFMSz = OpenLayers.Class(OpenLayers.Control.PermalinkFMS, {
    updateLink: function() {
        this._updateLink(1);
    }
});

/* Pan data handler */
OpenLayers.Format.FixMyStreet = OpenLayers.Class(OpenLayers.Format.JSON, {
    read: function(json, filter) {
        if (typeof json == 'string') {
            obj = OpenLayers.Format.JSON.prototype.read.apply(this, [json, filter]);
        } else {
            obj = json;
        }
        var current, current_near;
        if (typeof(obj.current) != 'undefined' && (current = document.getElementById('current'))) {
            current.innerHTML = obj.current;
        }
        if (typeof(obj.current_near) != 'undefined' && (current_near = document.getElementById('current_near'))) {
            current_near.innerHTML = obj.current_near;
        }
        var markers = fms_markers_list( obj.pins, false );
        return markers;
    },
    CLASS_NAME: "OpenLayers.Format.FixMyStreet"
});

/* Click handler */
OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {                
    defaultHandlerOptions: {
        'single': true,
        'double': false,
        'pixelTolerance': 0,
        'stopSingle': false,
        'stopDouble': false
    },

    initialize: function(options) {
        this.handlerOptions = OpenLayers.Util.extend(
            {}, this.defaultHandlerOptions);
        OpenLayers.Control.prototype.initialize.apply(
            this, arguments
        ); 
        this.handler = new OpenLayers.Handler.Click(
            this, {
                'click': this.trigger
            }, this.handlerOptions);
    }, 

    trigger: function(e) {
        var cobrand = $('meta[name="cobrand"]').attr('content');
        if (typeof fixmystreet.nav_control != 'undefined') {
            fixmystreet.nav_control.disableZoomWheel();
        }
        var lonlat = fixmystreet.map.getLonLatFromViewPortPx(e.xy);
        if (fixmystreet.page == 'new') {
            /* Already have a pin */
            fixmystreet.markers.features[0].move(lonlat);
        } else {
            var markers = fms_markers_list( [ [ lonlat.lat, lonlat.lon, 'green' ] ], false );
            fixmystreet.bbox_strategy.deactivate();
            fixmystreet.markers.removeAllFeatures();
            fixmystreet.markers.addFeatures( markers );
            fixmystreet_activate_drag();
        }

        // check to see if markers are visible. We click the
        // link so that it updates the text in case they go
        // back
        if ( ! fixmystreet.markers.getVisibility() ) {
            fixmystreet.state_pins_were_hidden = true;
            $('#hide_pins_link').click();
        }

        // Store pin location in form fields, and check coverage of point
        fixmystreet_update_pin(lonlat);

        // Already did this first time map was clicked, so no need to do it again.
        if (fixmystreet.page == 'new') {
            return;
        }

        fixmystreet.map.updateSize(); // might have done, and otherwise Firefox gets confused.
        /* For some reason on IOS5 if you use the jQuery show method it
         * doesn't display the JS validation error messages unless you do this
         * or you cause a screen redraw by changing the phone orientation.
         * NB: This has to happen after the call to show() */
        if ( navigator.userAgent.match(/like Mac OS X/i)) {
            document.getElementById('side-form').style.display = 'block';
        }
        $('#side').hide();
        if (typeof heightFix !== 'undefined') {
            heightFix('#report-a-problem-sidebar', '.content', 26);
        }

        // If we clicked the map somewhere inconvenient
        var sidebar = $('#report-a-problem-sidebar');
        if (sidebar.css('position') == 'absolute') {
            var w = sidebar.width(), h = sidebar.height(),
                o = sidebar.offset(),
                $map_boxx = $('#map_box'), bo = $map_boxx.offset();
            // e.xy is relative to top left of map, which might not be top left of page
            e.xy.x += bo.left;
            e.xy.y += bo.top;

            // 24 and 64 is the width and height of the marker pin
            if (e.xy.y <= o.top || (e.xy.x >= o.left && e.xy.x <= o.left + w + 24 && e.xy.y >= o.top && e.xy.y <= o.top + h + 64)) {
                // top of the page, pin hidden by header;
                // or underneath where the new sidebar will appear
                lonlat.transform(
                    new OpenLayers.Projection("EPSG:4326"),
                    fixmystreet.map.getProjectionObject()
                );
                var p = fixmystreet.map.getViewPortPxFromLonLat(lonlat);
                p.x -= ( o.left - bo.left + w ) / 2;
                lonlat = fixmystreet.map.getLonLatFromViewPortPx(p);
                fixmystreet.map.panTo(lonlat);
            }
        }

        $('#sub_map_links').hide();
        if ($('html').hasClass('mobile')) {
            var $map_box = $('#map_box'),
                width = $map_box.width(),
                height = $map_box.height();
            $map_box.append( '<p id="mob_sub_map_links">' + '<a href="#" id="try_again">' + translation_strings.try_again + '</a>' + '<a href="#ok" id="mob_ok">' + translation_strings.ok + '</a>' + '</p>' ).css({ position: 'relative', width: width, height: height, marginBottom: '1em' });
            // Making it relative here makes it much easier to do the scrolling later

            $('.mobile-map-banner').html('<a href="/">' + translation_strings.home + '</a> ' + translation_strings.right_place);

            // mobile user clicks 'ok' on map
            $('#mob_ok').toggle(function(){
                //scroll the height of the map box instead of the offset
                //of the #side-form or whatever as we will probably want
                //to do this on other pages where #side-form might not be
                $('html, body').animate({ scrollTop: height-60 }, 1000, function(){
                    $('#mob_sub_map_links').addClass('map_complete');
                    $('#mob_ok').text(translation_strings.map);
                });
            }, function(){
                $('html, body').animate({ scrollTop: 0 }, 1000, function(){
                    $('#mob_sub_map_links').removeClass('map_complete');
                    $('#mob_ok').text(translation_strings.ok);
                });
            });
        }

        fixmystreet.page = 'new';
        location.hash = 'report';
        if ( typeof ga !== 'undefined' && cobrand == 'fixmystreet' ) {
            ga('send', 'pageview', { 'page': '/map_click' } );
        }
    }
});
s="p">[element.name] = message; }, addWrapper: function(toToggle) { if ( this.settings.wrapper ) toToggle = toToggle.add( toToggle.parent( this.settings.wrapper ) ); return toToggle; }, defaultShowErrors: function() { for ( var i = 0; this.errorList[i]; i++ ) { var error = this.errorList[i]; this.settings.highlight && this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass ); this.showLabel( error.element, error.message ); } if( this.errorList.length ) { this.toShow = this.toShow.add( this.containers ); } if (this.settings.success) { for ( var i = 0; this.successList[i]; i++ ) { this.showLabel( this.successList[i] ); } } if (this.settings.unhighlight) { for ( var i = 0, elements = this.validElements(); elements[i]; i++ ) { this.settings.unhighlight.call( this, elements[i], this.settings.errorClass, this.settings.validClass ); } } this.toHide = this.toHide.not( this.toShow ); this.hideErrors(); this.addWrapper( this.toShow ).show(); }, validElements: function() { return this.currentElements.not(this.invalidElements()); }, invalidElements: function() { return $(this.errorList).map(function() { return this.element; }); }, showLabel: function(element, message) { var label = this.errorsFor( element ); if ( label.length ) { // refresh error/success class label.removeClass( this.settings.validClass ).addClass( this.settings.errorClass ); // check if we have a generated label, replace the message then label.attr("generated") && label.html(message); } else { // create label label = $("<" + this.settings.errorElement + "/>") .attr({"for": this.idOrName(element), generated: true}) .addClass(this.settings.errorClass) .html(message || ""); if ( this.settings.wrapper ) { // make sure the element is visible, even in IE // actually showing the wrapped element is handled elsewhere label = label.hide().show().wrap("<" + this.settings.wrapper + "/>").parent(); } if ( !this.labelContainer.append(label).length ) this.settings.errorPlacement ? this.settings.errorPlacement(label, $(element) ) : label.insertAfter(element); } if ( !message && this.settings.success ) { label.text(""); typeof this.settings.success == "string" ? label.addClass( this.settings.success ) : this.settings.success( label ); } this.toShow = this.toShow.add(label); }, errorsFor: function(element) { var name = this.idOrName(element); return this.errors().filter(function() { return $(this).attr('for') == name; }); }, idOrName: function(element) { return this.groups[element.name] || (this.checkable(element) ? element.name : element.id || element.name); }, validationTargetFor: function(element) { // if radio/checkbox, validate first element in group instead if (this.checkable(element)) { element = this.findByName( element.name ).not(this.settings.ignore)[0]; } return element; }, checkable: function( element ) { return /radio|checkbox/i.test(element.type); }, findByName: function( name ) { // select by name and filter by form for performance over form.find("[name=...]") var form = this.currentForm; return $(document.getElementsByName(name)).map(function(index, element) { return element.form == form && element.name == name && element || null; }); }, getLength: function(value, element) { switch( element.nodeName.toLowerCase() ) { case 'select': return $("option:selected", element).length; case 'input': if( this.checkable( element) ) return this.findByName(element.name).filter(':checked').length; } return value.length; }, depend: function(param, element) { return this.dependTypes[typeof param] ? this.dependTypes[typeof param](param, element) : true; }, dependTypes: { "boolean": function(param, element) { return param; }, "string": function(param, element) { return !!$(param, element.form).length; }, "function": function(param, element) { return param(element); } }, optional: function(element) { return !$.validator.methods.required.call(this, $.trim(element.value), element) && "dependency-mismatch"; }, startRequest: function(element) { if (!this.pending[element.name]) { this.pendingRequest++; this.pending[element.name] = true; } }, stopRequest: function(element, valid) { this.pendingRequest--; // sometimes synchronization fails, make sure pendingRequest is never < 0 if (this.pendingRequest < 0) this.pendingRequest = 0; delete this.pending[element.name]; if ( valid && this.pendingRequest == 0 && this.formSubmitted && this.form() ) { $(this.currentForm).submit(); this.formSubmitted = false; } else if (!valid && this.pendingRequest == 0 && this.formSubmitted) { $(this.currentForm).triggerHandler("invalid-form", [this]); this.formSubmitted = false; } }, previousValue: function(element) { return $.data(element, "previousValue") || $.data(element, "previousValue", { old: null, valid: true, message: this.defaultMessage( element, "remote" ) }); } }, classRuleSettings: { required: {required: true}, email: {email: true}, url: {url: true}, date: {date: true}, dateISO: {dateISO: true}, dateDE: {dateDE: true}, number: {number: true}, numberDE: {numberDE: true}, digits: {digits: true}, creditcard: {creditcard: true} }, addClassRules: function(className, rules) { className.constructor == String ? this.classRuleSettings[className] = rules : $.extend(this.classRuleSettings, className); }, classRules: function(element) { var rules = {}; var classes = $(element).attr('class'); classes && $.each(classes.split(' '), function() { if (this in $.validator.classRuleSettings) { $.extend(rules, $.validator.classRuleSettings[this]); } }); return rules; }, attributeRules: function(element) { var rules = {}; var $element = $(element); for (var method in $.validator.methods) { var value; // If .prop exists (jQuery >= 1.6), use it to get true/false for required if (method === 'required' && typeof $.fn.prop === 'function') { value = $element.prop(method); } else { value = $element.attr(method); } if (value) { rules[method] = value; } else if ($element[0].getAttribute("type") === method) { rules[method] = true; } } // maxlength may be returned as -1, 2147483647 (IE) and 524288 (safari) for text inputs if (rules.maxlength && /-1|2147483647|524288/.test(rules.maxlength)) { delete rules.maxlength; } return rules; }, metadataRules: function(element) { if (!$.metadata) return {}; var meta = $.data(element.form, 'validator').settings.meta; return meta ? $(element).metadata()[meta] : $(element).metadata(); }, staticRules: function(element) { var rules = {}; var validator = $.data(element.form, 'validator'); if (validator.settings.rules) { rules = $.validator.normalizeRule(validator.settings.rules[element.name]) || {}; } return rules; }, normalizeRules: function(rules, element) { // handle dependency check $.each(rules, function(prop, val) { // ignore rule when param is explicitly false, eg. required:false if (val === false) { delete rules[prop]; return; } if (val.param || val.depends) { var keepRule = true; switch (typeof val.depends) { case "string": keepRule = !!$(val.depends, element.form).length; break; case "function": keepRule = val.depends.call(element, element); break; } if (keepRule) { rules[prop] = val.param !== undefined ? val.param : true; } else { delete rules[prop]; } } }); // evaluate parameters $.each(rules, function(rule, parameter) { rules[rule] = $.isFunction(parameter) ? parameter(element) : parameter; }); // clean number parameters $.each(['minlength', 'maxlength', 'min', 'max'], function() { if (rules[this]) { rules[this] = Number(rules[this]); } }); $.each(['rangelength', 'range'], function() { if (rules[this]) { rules[this] = [Number(rules[this][0]), Number(rules[this][1])]; } }); if ($.validator.autoCreateRanges) { // auto-create ranges if (rules.min && rules.max) { rules.range = [rules.min, rules.max]; delete rules.min; delete rules.max; } if (rules.minlength && rules.maxlength) { rules.rangelength = [rules.minlength, rules.maxlength]; delete rules.minlength; delete rules.maxlength; } } // To support custom messages in metadata ignore rule methods titled "messages" if (rules.messages) { delete rules.messages; } return rules; }, // Converts a simple string to a {string: true} rule, e.g., "required" to {required:true} normalizeRule: function(data) { if( typeof data == "string" ) { var transformed = {}; $.each(data.split(/\s/), function() { transformed[this] = true; }); data = transformed; } return data; }, // http://docs.jquery.com/Plugins/Validation/Validator/addMethod addMethod: function(name, method, message) { $.validator.methods[name] = method; $.validator.messages[name] = message != undefined ? message : $.validator.messages[name]; if (method.length < 3) { $.validator.addClassRules(name, $.validator.normalizeRule(name)); } }, methods: { // http://docs.jquery.com/Plugins/Validation/Methods/required required: function(value, element, param) { // check if dependency is met if ( !this.depend(param, element) ) return "dependency-mismatch"; switch( element.nodeName.toLowerCase() ) { case 'select': // could be an array for select-multiple or a string, both are fine this way var val = $(element).val(); return val && val.length > 0; case 'input': if ( this.checkable(element) ) return this.getLength(value, element) > 0; default: return $.trim(value).length > 0; } }, // http://docs.jquery.com/Plugins/Validation/Methods/remote remote: function(value, element, param) { if ( this.optional(element) ) return "dependency-mismatch"; var previous = this.previousValue(element); if (!this.settings.messages[element.name] ) this.settings.messages[element.name] = {}; previous.originalMessage = this.settings.messages[element.name].remote; this.settings.messages[element.name].remote = previous.message; param = typeof param == "string" && {url:param} || param; if ( this.pending[element.name] ) { return "pending"; } if ( previous.old === value ) { return previous.valid; } previous.old = value; var validator = this; this.startRequest(element); var data = {}; data[element.name] = value; $.ajax($.extend(true, { url: param, mode: "abort", port: "validate" + element.name, dataType: "json", data: data, success: function(response) { validator.settings.messages[element.name].remote = previous.originalMessage; var valid = response === true; if ( valid ) { var submitted = validator.formSubmitted; validator.prepareElement(element); validator.formSubmitted = submitted; validator.successList.push(element); validator.showErrors(); } else { var errors = {}; var message = response || validator.defaultMessage( element, "remote" ); errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message; validator.showErrors(errors); } previous.valid = valid; validator.stopRequest(element, valid); } }, param)); return "pending"; }, // http://docs.jquery.com/Plugins/Validation/Methods/minlength minlength: function(value, element, param) { return this.optional(element) || this.getLength($.trim(value), element) >= param; }, // http://docs.jquery.com/Plugins/Validation/Methods/maxlength maxlength: function(value, element, param) { return this.optional(element) || this.getLength($.trim(value), element) <= param; }, // http://docs.jquery.com/Plugins/Validation/Methods/rangelength rangelength: function(value, element, param) { var length = this.getLength($.trim(value), element); return this.optional(element) || ( length >= param[0] && length <= param[1] ); }, // http://docs.jquery.com/Plugins/Validation/Methods/min min: function( value, element, param ) { return this.optional(element) || value >= param; }, // http://docs.jquery.com/Plugins/Validation/Methods/max max: function( value, element, param ) { return this.optional(element) || value <= param; }, // http://docs.jquery.com/Plugins/Validation/Methods/range range: function( value, element, param ) { return this.optional(element) || ( value >= param[0] && value <= param[1] ); }, // http://docs.jquery.com/Plugins/Validation/Methods/email email: function(value, element) { // contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/ return this.optional(element) || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(value); }, // http://docs.jquery.com/Plugins/Validation/Methods/url url: function(value, element) { // contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/ return this.optional(element) || /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value); }, // http://docs.jquery.com/Plugins/Validation/Methods/date date: function(value, element) { return this.optional(element) || !/Invalid|NaN/.test(new Date(value)); }, // http://docs.jquery.com/Plugins/Validation/Methods/dateISO dateISO: function(value, element) { return this.optional(element) || /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value); }, // http://docs.jquery.com/Plugins/Validation/Methods/number number: function(value, element) { return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value); }, // http://docs.jquery.com/Plugins/Validation/Methods/digits digits: function(value, element) { return this.optional(element) || /^\d+$/.test(value); }, // http://docs.jquery.com/Plugins/Validation/Methods/creditcard // based on http://en.wikipedia.org/wiki/Luhn creditcard: function(value, element) { if ( this.optional(element) ) return "dependency-mismatch"; // accept only spaces, digits and dashes if (/[^0-9 -]+/.test(value)) return false; var nCheck = 0, nDigit = 0, bEven = false; value = value.replace(/\D/g, ""); for (var n = value.length - 1; n >= 0; n--) { var cDigit = value.charAt(n); var nDigit = parseInt(cDigit, 10); if (bEven) { if ((nDigit *= 2) > 9) nDigit -= 9; } nCheck += nDigit; bEven = !bEven; } return (nCheck % 10) == 0; }, // http://docs.jquery.com/Plugins/Validation/Methods/accept accept: function(value, element, param) { param = typeof param == "string" ? param.replace(/,/g, '|') : "png|jpe?g|gif"; return this.optional(element) || value.match(new RegExp(".(" + param + ")$", "i")); }, // http://docs.jquery.com/Plugins/Validation/Methods/equalTo equalTo: function(value, element, param) { // bind to the blur event of the target in order to revalidate whenever the target field is updated // TODO find a way to bind the event just once, avoiding the unbind-rebind overhead var target = $(param).unbind(".validate-equalTo").bind("blur.validate-equalTo", function() { $(element).valid(); }); return value == target.val(); } } }); // deprecated, use $.validator.format instead $.format = $.validator.format; })(jQuery); // ajax mode: abort // usage: $.ajax({ mode: "abort"[, port: "uniqueport"]}); // if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort() ;(function($) { var pendingRequests = {}; // Use a prefilter if available (1.5+) if ( $.ajaxPrefilter ) { $.ajaxPrefilter(function(settings, _, xhr) { var port = settings.port; if (settings.mode == "abort") { if ( pendingRequests[port] ) { pendingRequests[port].abort(); } pendingRequests[port] = xhr; } }); } else { // Proxy ajax var ajax = $.ajax; $.ajax = function(settings) { var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode, port = ( "port" in settings ? settings : $.ajaxSettings ).port; if (mode == "abort") { if ( pendingRequests[port] ) { pendingRequests[port].abort(); } return (pendingRequests[port] = ajax.apply(this, arguments)); } return ajax.apply(this, arguments); }; } })(jQuery); // provides cross-browser focusin and focusout events // IE has native support, in other browsers, use event caputuring (neither bubbles) // provides delegate(type: String, delegate: Selector, handler: Callback) plugin for easier event delegation // handler is only called when $(event.target).is(delegate), in the scope of the jquery-object for event.target ;(function($) { // only implement if not provided by jQuery core (since 1.4) // TODO verify if jQuery 1.4's implementation is compatible with older jQuery special-event APIs if (!jQuery.event.special.focusin && !jQuery.event.special.focusout && document.addEventListener) { $.each({ focus: 'focusin', blur: 'focusout' }, function( original, fix ){ $.event.special[fix] = { setup:function() { this.addEventListener( original, handler, true ); }, teardown:function() { this.removeEventListener( original, handler, true ); }, handler: function(e) { arguments[0] = $.event.fix(e); arguments[0].type = fix; return $.event.handle.apply(this, arguments); } }; function handler(e) { e = $.event.fix(e); e.type = fix; return $.event.handle.call(this, e); } }); }; $.extend($.fn, { validateDelegate: function(delegate, type, handler) { return this.bind(type, function(event) { var target = $(event.target); if (target.is(delegate)) { return handler.apply(target, arguments); } }); } }); })(jQuery);