aboutsummaryrefslogtreecommitdiffstats
path: root/phonegap/www/js/mobile.js
blob: 07d97331519afd20d7db87cbeb53076afbc41224 (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
function touchmove(e) {
    e.preventDefault();
}

function loadingSpinner(method){
    if (method == "on") {
        //Adjust to screen size
        var pHeight = window.innerHeight;
        var pWidth = window.innerWidth;
        var sH = parseInt($('#loadingSpinner').css('height'),10);
        var sW = parseInt($('#loadingSpinner').css('width'),10);
        $('#loadingSpinner').css('top',(pHeight-sH)/2+$('body').scrollTop());
        $('#loadingSpinner').css('left',(pWidth-sW)/2);
        $('#loadingSpinner').css('z-index',1000);
        //Show
        $('#loadingSpinner').show();
    } else if (method == 'off'){
        $('#loadingSpinner').hide();
    }
}

function showBusy( title, msg ) {
    if ( navigator && navigator.notification && typeof navigator.notification.activityStart !== "undefined") {
        navigator.notification.activityStart( title, msg );
    } else {
        loadingSpinner('on');
    }
}

function hideBusy() {
    if ( navigator && navigator.notification && navigator.notification.activityStop) {
        navigator.notification.activityStop();
    } else {
        loadingSpinner('off');
    }
}

function show_around( lat, long ) {
    pc = $('#pc').val();
    localStorage.latitude = lat;
    localStorage.longitude = long;
    localStorage.pc = pc;
    hideBusy();
    window.location='around.html';
    return false;
}

function valid_postcode(pc) {
    var out_pattern = '[A-PR-UWYZ]([0-9]{1,2}|([A-HIK-Y][0-9](|[0-9]|[ABEHMNPRVWXY]))|[0-9][A-HJKSTUW])';
    var in_pattern = '[0-9][ABD-HJLNP-UW-Z]{2}';
    var full_pattern = '^' + out_pattern + in_pattern + '$';
    var postcode_regex = new RegExp(full_pattern);

    pc = pc.toUpperCase().replace(/\s+/, '');
    if ( postcode_regex.test(pc) ) {
        return true;
    }

    return false;
}

function checkConnection() {
    var networkState = navigator.network.connection.type;
    if ( networkState == Connection.NONE || networkState == Connection.UNKNOWN ) {
        $('#main').hide();
        $('#noconnection').show();
    }
}

function use_lat_long( lat, long ) {
    show_around( lat, long );
}

function location_error( msg ) {
    hideBusy();
    if ( msg === '' ) {
        $('#location_error').remove();
        return;
    }

    alert(msg);

    if ( !$('#location_error') ) {
        $('#postcodeForm').after('<p id="location_error"></p>');
    }

    $('#location_error').text( msg );
}

function lookup_string(q) {
    q = q.toLowerCase();
    q = q.replace(/[^\-&\w ']/, ' ');
    q = q.replace(/\s+/, ' ');

    if (!q) {
        hideBusy();
        location_error("Please enter location");
        return false;
    }

    var url = "http://dev.virtualearth.net/REST/v1/Locations?q=" + escape(q);
    url += '&c=en-GB&key=' + CONFIG.BING_API_KEY;
    var x = jQuery.get( url, function(data, status) {
        if ( status == 'success' ) {
            var valid_locations = 0;
            var latitude = 0;
            var longitude = 0;
            var multiple = [];

            for ( i = 0; i < data.resourceSets[0].resources.length; i++ ) {
                var details = data.resourceSets[0].resources[i];
                if ( details.address.countryRegion != 'United Kingdom' ) { continue; }
                var address = details.name;

                latitude = details.point.coordinates[0];
                longitude = details.point.coordinates[1];
                latitude = latitude.toPrecision(6);
                longitude = longitude.toPrecision(6);

                multiple.push( { 'address': address, 'latitude': latitude, 'longitude': longitude } );
                valid_locations += 1;
            }

            if ( valid_locations == 1 ) {
                show_around( latitude, longitude );
            } else if ( valid_locations === 0 ) {
                location_error('Location not found');
                $('#pc').select();
            } else {
                location_error('');
                $('#multiple').remove();
                var multiple_html = '<ul id="multiple"><li>Multiple locations found, please select one:';
                for ( i = 0; i < multiple.length; i++ ) {
                    multiple_html += '<li><a href="#" onclick="use_lat_long( ' + multiple[i].latitude + ',' + multiple[i].longitude +')">' + multiple[i].address + '</a></li>';
                }
                multiple_html += '</ul>';
                $('#front-howto').hide();
                $('#postcodeForm').after( multiple_html );
            }
        } else {
            location_error("Could not find your location");
        }
        hideBusy();
    });
    return false;
}

function locate() {
    $("#multiple").remove();
    var pc = $('#pc').val();

    if (!pc) {
        location_error( "Please enter your location" );
        return false;
    }

    showBusy('Locating', 'Looking up location');

    if ( valid_postcode( pc ) ) {
        jQuery.get( CONFIG.MAPIT_URL + 'postcode/' + pc + '.json', function(data, status) {
            if ( status == 'success' ) {
                //activityStop();
               show_around( data.wgs84_lat, data.wgs84_lon );
           } else {
               activityStop();
               alert('Could not locate postcode');
           }
        });
    } else {
        lookup_string(pc);
    }
    return false;
}

function foundLocation(myLocation) {
    var lat = myLocation.coords.latitude;
    var long = myLocation.coords.longitude;

    show_around( lat, long );
}

function notFoundLocation() { location_error( 'Could not find location' ); }

function getPosition() {
    showBusy( 'Locating', 'Looking up location' );

    navigator.geolocation.getCurrentPosition(foundLocation, notFoundLocation);
}


function takePhotoSuccess(imageURI) {
    $('#form_photo').val(imageURI);
    $('#photo').attr('src', imageURI );
    $('#add_photo').hide();
    $('#display_photo').show();
}

function delPhoto() {
    $('#form_photo').val('');
    $('#photo').attr('src', '' );
    $('#display_photo').hide();
    $('#add_photo').show();
}

function takePhotoFail(message) {
    alert('There was a problem taking your photo');
    console.log('error taking picture: ' + message);
}

function takePhoto(type) {
    navigator.camera.getPicture(takePhotoSuccess, takePhotoFail, { quality: 50, destinationType: Camera.DestinationType.FILE_URI, sourceType: type }); 
}

function check_name( name, msg ) {
    $('#email_label').hide();
    $('#form_email').hide();
    $('#now_submit').hide();
    $('#have_password').hide();
    $('#form_sign_in_yes').hide();
    $('#let_me_confirm').hide();
    $('#password_register').hide();
    $('#password_surround').hide();
    $('#providing_password').hide();
    $('#form_name').val( name );
    if ( msg ) {
        $('#form_name').focus();
        $('#form_name').before('<div class="form-error">' + msg + '</div>' );
    }
}

function fileUploadSuccess(r) {
    if ( r.response ) {
        var data;
        try {
            data = JSON.parse( decodeURIComponent(r.response) );
        }
        catch(err) {
            data = {};
        }
        if ( data.success ) {
            if ( data.report ) {
                localStorage.report = data.report;
                hideBusy();
                window.location = 'report_created.html';
            } else {
                hideBusy();
                window.location = 'email_sent.html';
            }
        } else {
            if ( data.check_name ) {
                check_name( data.check_name, data.errors.name );
            } else {
                alert('Could not submit report');
            }
            $('input[type=submit]').prop("disabled", false);
        }
    } else {
        hideBusy();
        alert('Could not submit report');
        $('input[type=submit]').prop("disabled", false);
    }
}

function fileUploadFail() {
    hideBusy();
    alert('Could not submit report');
    $('input[type=submit]').prop("disabled", false);
}


var submit_clicked = null;

function postReport(e) {
    e.preventDefault();

    // the .stopImmediatePropogation call in invalidHandler should render this
    // redundant but it doesn't seem to work so belt and braces :(
    if ( !$('#mapForm').valid() ) { return; }

    var params = {
        service: 'iphone',
        title: $('#form_title').val(),
        detail: $('#form_detail').val(),
        name: $('#form_name').val(),
                    may_show_name: $('#form_may_show_name').attr('checked') ? 1 : 0,
        email: $('#form_email').val(),
        category: $('#form_category').val(),
        lat: $('#fixmystreet\\.latitude').val(),
        lon: $('#fixmystreet\\.longitude').val(),
        password_sign_in: $('#password_sign_in').val(),
        phone: $('#form_phone').val(),
        pc: $('#pc').val()
    };

    if ( submit_clicked.attr('id') == 'submit_sign_in' ) {
        params.submit_sign_in = 1;
    } else {
        params.submit_register = 1;
    }

    showBusy( 'Sending Report', 'Please wait while your report is sent' );
    if ( $('#form_photo').val() !== '' ) {
        fileURI = $('#form_photo').val();

        var options = new FileUploadOptions();
        options.fileKey="photo";
        options.fileName=fileURI.substr(fileURI.lastIndexOf('/')+1);
        options.mimeType="image/jpeg";
        options.params = params;
        options.chunkedMode = false;

        var ft = new FileTransfer();
        ft.upload(fileURI, CONFIG.FMS_URL + "report/new/mobile", fileUploadSuccess, fileUploadFail, options);
    } else {
        jQuery.ajax( {
            url: CONFIG.FMS_URL + "report/new/mobile",
            type: 'POST',
            data: params, 
            timeout: 30000,
            success: function(data) {
                if ( data.success ) {
                    localStorage.pc = null;
                    localStorage.lat = null;
                    localStorage.long = null;
                    if ( data.report ) {
                        localStorage.report = data.report;
                        hideBusy();
                        window.location = 'report_created.html';
                    } else {
                        hideBusy();
                        window.location = 'email_sent.html';
                    }
                } else {
                    if ( data.check_name ) {
                        check_name( data.check_name, data.errors.name );
                    }
                    $('input[type=submit]').prop("disabled", false);
                    hideBusy();
                }
            },
            error: function (data, status, errorThrown ) {
                hideBusy();
                alert( 'There was a problem submitting your report, please try again (' + status + '): ' + JSON.stringify(data), function(){}, 'Submit report' );
                $('input[type=submit]').prop("disabled", false);
            }
        } );
    }
    return false;
}

function sign_in() {
    showBusy( 'Signing In', 'Please wait while you are signed in' );
    jQuery.ajax( {
        url: CONFIG.FMS_URL + "auth/ajax/sign_in",
        type: 'POST',
        data: {
            email: $('#form_email').val(),
            password_sign_in: $('#password_sign_in').val(),
            remember_me: 1
        },
        success: function(data) {
            console.log(data);
            if ( data.name ) {
                localStorage.name = data.name;
                hideBusy();
                window.location = 'signed_in.html';
                $('#sign_out').show();
                $('#sign_in').hide();
            } else {
                hideBusy();
                $('#form_email').before('<div class="form-error">There was a problem with your email/password combination.</div>');
            }
        }
    } );

}

function display_signed_out_msg() {
    if ( localStorage.signed_out == 1 ) {
        $('#user-meta').html('<p>You&rsquo;ve been signed out.</p>');
        localStorage.signed_out = null;
    }
}

function sign_out() {
    jQuery.ajax( {
        url: CONFIG.FMS_URL + "auth/ajax/sign_out?" + new Date().getTime(),
        type: 'GET',
        success: function(data) {
            if ( data.signed_out ) {
                localStorage.signed_out = 1;
                localStorage.name = null;
                hideBusy();
                document.location = 'sign_in.html';
            }
        }
    } );
}

function sign_out_around() {
    jQuery.ajax( {
        url: CONFIG.FMS_URL + "auth/ajax/sign_out?" + new Date().getTime(),
        type: 'GET',
        success: function(data) {
            $('#user-meta').html('');
            $('#email_label').show();
            $('#form_email').show();
            $('#now_submit').show();
            $('#have_password').show();
            $('#form_sign_in_yes').show();
            $('#let_me_confirm').show();
            $('#password_register').show();
            $('#password_surround').show();
            $('#providing_password').show();
            $('#form_name').val( '' );
            $('.form-focus-hidden').hide();
        }
    } );
}

function check_auth() {
    if ( $('#user-meta').length && localStorage.signed_out != 1 ) {
        var sign_out_function = sign_out;
        if ( $('body').hasClass('mappage') ) {
            sign_out_function = sign_out_around;
        }
        jQuery.ajax( {
            url: CONFIG.FMS_URL + "auth/ajax/check_auth?" + new Date().getTime() ,
            type: 'GET',
            statusCode: {
                200: function(data) {
                    localStorage.name = data.name;
                    $('#user-meta').html('<p>Hi ' + localStorage.name + '<a href="#" id="meta_sign_out">Sign out</a></p>');
                    $('#meta_sign_out').on('click', sign_out_function );
                    $('.mobile-sign-in-banner').show();
                    $('#sign_in').hide();
                    $('#sign_out').show();
                },
                401: function() {
                    $('#user-meta').html('');
                    localStorage.name = '';
                    $('.mobile-sign-in-banner').show();
                    $('#sign_out').hide();
                    $('#sign_in').show();
                    $('#user-meta').html('');
                }
            }
        } );
    }
}

function signed_in() {
    if ( localStorage.name ) {
        if ( $('body').hasClass('signed-in-page') ) {
            var sign_out_function = sign_out;
            if ( $('body').hasClass('mappage') ) {
                sign_out_function = sign_out_around;
            }
            $('#user-meta').html('<p>Hi ' + localStorage.name + '<a href="#" id="meta_sign_out">Sign out</a></p>');
            $('#meta_sign_out').on('click', sign_out_function );
        }

        if ( $('#form_sign_in').length ) {
            check_name( localStorage.name );
            $('.form-focus-hidden').show();
        }
    }
}

function onDeviceReady() {
    var location = document.location + '';
    if ( location.indexOf('no_connection.html') < 0 && (
            navigator.network.connection.type == Connection.NONE ||
            navigator.network.connection.type == Connection.UNKNOWN ) ) {
        document.location = 'no_connection.html';
    }
    $('#postcodeForm').submit(locate);
    $('#mapForm').submit(postReport);
    $('#signInForm').submit(sign_in);
    $('#ffo').click(getPosition);
    $('#mapForm :input[type=submit]').on('click', function() { submit_clicked = $(this); });
    check_auth();
    signed_in();
    hideBusy();
}

document.addEventListener("deviceready", onDeviceReady, false);