View difference between Paste ID: sZ3Aa8rM and Hwu4NdbU
SHOW: | | - or go back to the newest paste.
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one
3
 * or more contributor license agreements.  See the NOTICE file
4
 * distributed with this work for additional information
5
 * regarding copyright ownership.  The ASF licenses this file
6
 * to you under the Apache License, Version 2.0 (the
7
 * "License"); you may not use this file except in compliance
8
 * with the License.  You may obtain a copy of the License at
9
 *
10
 * http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing,
13
 * software distributed under the License is distributed on an
14
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
 * KIND, either express or implied.  See the License for the
16
 * specific language governing permissions and limitations
17
 * under the License.
18
 */
19
var app = {
20
21
    myFriends: [],
22
    savedCO2: 0,
23
24
    // Application Constructor
25
    initialize: function() {
26
        this.bindEvents();
27
        var self = this;
28-
            // alert("Errore nella richiesta a "+settings.url);
28+
29-
            if (exception != null) {
29+
            console.warn("ERRORE AJAX");
30-
                // alert("Eccezione " + JSON.stringify(exception));
30+
            console.warn(settings.url);
31
            self.showDialog("Network error", "Error connecting to "+settings.url+". <p>"+exception+"</p>");
32
        });
33
        $.ajaxSetup({ contentType: "application/json" });
34
35
        this.initUi();
36
    },
37
38
    // Bind Event Listeners
39
    //
40
    // Bind any events that are required on startup. Common events are:
41-
                phoneNumber: self.getMyPhone(),
41+
42
    bindEvents: function() {
43-
                vehicleType: $("#veicolo input:checked").val()
43+
44
    },
45
46-
            destinazione = $("#offer-destinazione").val();
46+
47
    //
48
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
49
    // function, we must explicity call 'app.receivedEvent(...);'
50
    onDeviceReady: function() {
51
        document.addEventListener('resume', function() {
52
53
            if(callingNumber && callingNumber.length > 0) {
54
                navigator.notification.confirm('Was a real friend or not?', function(found) {
55
                    if(found == 1){
56
                        $.ajax({
57
                            url: 'http://poolmeup.appspot.com/rest/offers/'+callingNumber+'/join',
58
                            type: 'POST',
59
                            success: function(data){
60
                                navigator.notification.alert(data.response, function(){
61
                                    $.mobile.changePage("#rideFound");
62
                                    $('#earnedPoints').text(savedCO2);
63
                                });
64-
            $.post(url, req, function(data) {
64+
                            },
65-
                idOffer = data.idOffer;
65+
                            error: function(jqXHR, textStatus, errorThrown){
66
                                navigator.notification.alert("Errore:" + textStatus, function(){});
67
                            }
68
                        });
69
70-
                self.timeoutID = setInterval(function() { self.longPolling(idOffer); }, 1000*30); 
70+
                    }
71
                }, 'Did you find a ride?', 'Yes, No')
72
            }
73
74
        }, false);
75
76
        // Load friends list
77-
                friends: self.getMyFriends(),
77+
        $.mobile.loading( 'show', {
78-
                numberOfPerson: $("#find-persons").val(),
78+
            text: 'Loading friends list',
79-
                idUtente: self.getMyPhone(),
79+
            textVisible: true,
80
            theme: 'c',
81-
                pathRequest: []
81+
            html: ""
82
        });
83-
            origine = $("#find-origine").val(),
83+
84-
            destinazione = $("#find-destinazione").val();
84+
        var options = new ContactFindOptions();
85
        options.filter = "";
86
        options.multiple = true;
87
        var fields = ["displayName", "phoneNumbers"];
88
        navigator.contacts.find(fields,
89
            function(contacts){
90
91
                for (var i=0; i<contacts.length; i++) {
92
                    var name = contacts[i].displayName;
93
                    var number = "";
94
                    var phoneNumbers = contacts[i].phoneNumbers;
95
                    if(phoneNumbers && phoneNumbers.length>0){
96
                        $.each(phoneNumbers, function(indx, phone){
97
                            if(phone.type == 'mobile') {
98-
        // var url = "addr.json";
98+
                                number = phone.value.replace('+39');
99-
        var url = "http://maps.googleapis.com/maps/api/geocode/json";
99+
                                return false;
100-
        $.get(url, {sensor: false, address: $(id).val()}, function (data) {
100+
                            }
101
                        });
102
                    }
103
104
                    if(name && name.length>0 && number && number.length > 0) {
105
                        myFriends.push({
106
                            name: name,
107
                            phoneNumber: number
108
                        });
109
                    }
110
111
                }
112-
        }, "json");
112+
                $.mobile.loading( 'hide' );
113
            },
114
            function(error) {
115
                $.mobile.loading( 'hide' );
116
                console.log(error);
117-
       $("#dialogtitle").text(title);
117+
                console.log(error.message);
118-
       $("#dialogmessage").html(message);
118+
            }, options
119-
       $.mobile.changePage("#dialog");
119+
        );
120
121
            // Check for user phone number
122
        var myPhoneNumber =  window.localStorage.getItem("poolmeupmyphone");
123-
            "Start": "",
123+
        // myPhoneNumber = "";
124-
            "KeepStraight": "img/direction_up.png",
124+
        if(!myPhoneNumber || myPhoneNumber.length == 0) {
125-
            "TurnSightlyLeft": "img/direction_upleft.png",
125+
            $.mobile.changePage("#popupMyPhone");
126-
            "TurnLeft": "img/direction_upthenleft.png",
126+
            $('#setMyIp').click(function(){
127-
            "TurnRight": "img/direction_upthenright.png",
127+
                myPhoneNumber = $('#myphoneinput').val();
128-
            "TurnSightlyRight": "img/direction_upright.png",
128+
                window.localStorage.setItem("poolmeupmyphone", myPhoneNumber);
129-
            "EnterRoundabout": ""
129+
                $.mobile.changePage("#index");
130
            })
131
        }
132
133
//            console.log("in getMyPhoneNumber");
134
//            var onSuccess = function(result) {
135
//                console.log("My phone number: " + result.phoneNumber);
136
//            }
137
//            var onError = function(err) {
138
//                console.log("Could not get my phone number: " + err);
139
//            }
140
//            MyPhoneNumberPlugin.getMyPhoneNumber(onSuccess, onError);
141
    },
142
143
144-
                         "<h3>"+kind+"</h3><p>percorsi "+dist+"m, sono passati "+time+ " secondi</p></a></li>";
144+
    /**
145
     * Show a list of Contacts, When an element of the list is pressed, a phoneCall is
146
     * done to the selected contact.
147
     * Get in input a list of drivers, and use the phoneNumber to get the photo from the addressBook
148
     * @param drivers
149
     */
150
    showDriverList: function(drivers) {
151
152
        var myself = this;
153
154
        var ul = $('#driversListUl');
155
        ul.empty();
156
157
        $.mobile.changePage($('#driversListPage'));
158
159
        ul.listview();
160
161
        var fields = ["displayName", "name", "phoneNumbers", "photos"];
162
        $.each(drivers, function(indx, driver){
163
164
//            console.info("Processo " + driver.phoneNumber);
165
166-
        return ["pippo", "pluto", "paperino"];
166+
            var options = new ContactFindOptions();
167
            options.filter= driver.phoneNumber;
168
            options.multiple=false;
169
170-
        return 333333333333;
170+
            navigator.contacts.find(fields,
171
                function(contacts) {
172
173
                    for (var i=0; i<contacts.length; i++) {
174
175
//                        console.info("Trovato uno");
176
177
                        var number = "";
178
                        var name = "";
179
                        var img = "/img/noUserImg.png";
180
181
                        // FIXME Per ora visualizzo solo i contatti che hanno un telefono registrato come mobile
182
                        var phoneNumbers = contacts[i].phoneNumbers;
183
                        if(phoneNumbers && phoneNumbers.length>0){
184
                            $.each(phoneNumbers, function(indx, phone){
185
                                if(phone.type == 'mobile') {
186-
        app.receivedEvent('deviceready');
186+
                                    number = phone.value;
187
                                    return false;
188
                                }
189-
    // Update DOM on a Received Event
189+
                            });
190-
    receivedEvent: function(id) {
190+
                        }
191-
        console.log('Received Event: ' + id);
191+
192
                        if(number.length == 0 ) {
193
                            console.warn("Non ho trovato il numero in rubrica per " + contacts[i].phoneNumbers)
194
                            return;
195
                        }
196
197
                        name = contacts[i].displayName;
198
                        if(name.length == 0){
199
                            name = contacts[i].name;
200
                        }
201
202
                        var photos = contacts[i].photos;
203
                        if(photos && photos.length > 0) {
204
                            $.each(photos, function(indx, photo){
205
                                if(photo.value && photo.value.length > 0) {
206
                                    img = photo.value;
207
                                }
208
                            });
209
                        }
210
211
                        console.info(img);
212
//                        console.info("Aggiungo " + name + " con foto " + img);
213
                        var li = '<li phone="'+driver.phoneNumber+'" id="phone_'+name+'">' +
214
                            '<a href="#">' +
215
                            '<img src="'+ img +'" />' +
216
                            '<h3>'+ name +'</h3>' +
217
                            '<p class="phone">tel. '+driver.phoneNumber + '</p>' +
218
                            '<p class="veichle">Veicolo '+driver.vehicleType+'</p>' +
219
                            '</a>' +
220
                            '</li>';
221
                        ul.append(li);
222
                        ul.listview('refresh');
223
224
                        $('#phone_' + name).click(function(){
225
                            var me = $(this);
226
                            console.info(me.attr('phone'));
227
                            console.info('tel:' + me.attr('phone'));
228
                            callingNumber = me.attr('phone');
229
                            console.info(callingNumber);
230
                            document.location.href = 'tel:' + me.attr('phone');
231
                        });
232
                    }
233
234
                    $.mobile.loading( 'hide' );
235
                },
236
                function(error) {
237
                    console.log(error);
238
                    console.log(error.message);
239
                }, options);
240
241
242
        });
243
244
    },
245
246
    initUi: function() {
247
248
        var self = this;
249
250
        $('#listFriendsBtn').click(function(){
251
            console.info("CLICK!");
252
            console.info(myFriends.length);
253
254
        });
255
256
257
        $("#offerride").click(function() {
258
            var req = {
259
                isStartingTime: true,
260
                maxTreshold: parseInt($("#maxtreshold").val()),
261
                numberPlaces: parseInt($("#offer-persons").val()),
262
                pathRequest: [],
263
                phoneNumber: self.getMyPhone() || 3333333333,
264
                userName: "Pippo",
265
                vehicleType: $("#veicolo input:checked").val(),
266
            };
267
            origine = $("#offer-origine").val(),
268
                destinazione = $("#offer-destinazione").val();
269
            if (origine == "" || destinazione == "") {
270
                self.showDialog("Form Incompleto", "I campi <strong>Origine</strong> e <strong>Destinazione</strong> non possono essere vuoti!");
271
                return;
272
            }
273
            var data = /\d\d\/\d\d\/\d{4} \d\d:\d\d/.exec($("#offer-data").val());
274
            if (data == null) {
275
                self.showDialog("Data Invalida", "La data deve essere nel formato <strong>dd/mm/yyyy hh:mm</strong>");
276
                return;
277
            }
278
            req.requestTime = data[0];
279
            if (self.getCoords("#offer-origine", req) === false) return;
280
            if (self.getCoords("#offer-destinazione", req) === false) return;
281
            console.dir(req);
282
            console.log(JSON.stringify(req));
283
284
            var url = "http://poolmeup.appspot.com/rest/offers";
285
            var idOffer = null;
286
            $.post(url, JSON.stringify(req), function(data) {
287
                idOffer = data.idOffer || 1;
288
                var s = self.parseXML(data.pathResponse);
289
                $.mobile.changePage("#viewpath");
290
                $("#actionlist").append(s).listview("refresh");
291
292
                self.timeoutID = setInterval(function() { self.longPolling(idOffer); }, 1000*30);
293
            });
294
        });
295
296
297
        $("#findride").click(function() {
298
299
            // FIXME DEBUG
300
            var drivers = [{
301
                name: 'Minni',
302
                phoneNumber:"3397323027",
303
                vehicleType:"car",
304
                waitingTime:"35"
305
            },{
306
                name: 'Minni',
307
                phoneNumber:"+393397323027",
308
                vehicleType:"motorino",
309
                waitingTime:"75"
310
            },{
311
                name:"Mariella",
312
                phoneNumber:"+393337701783",
313
                vehicleType:"autobus",
314
                waitingTime:"155"
315
            },{
316
                name:"Mariella",
317
                phoneNumber:"+393394745492",
318
                vehicleType:"autobus",
319
                waitingTime:"155"
320
            }];
321
322
            savedCO2 = 500;
323
324
            var req = {
325
                    friends: self.getMyFriends(),
326
                    numberOfPerson: $("#find-persons").val(),
327
                    idUtente: self.getMyPhone() || 333333333,
328
                    userName: "Pippo",
329
                    pathRequest: []
330
                },
331
                origine = $("#find-origine").val(),
332
                destinazione = $("#find-destinazione").val();
333
            if (origine == "" || destinazione == "") {
334
                self.showDialog("Form Incompleto", "I campi <strong>Origine</strong> e <strong>Destinazione</strong> non possono essere vuoti!");
335
                return;
336
            }
337
            if (self.getCoords("#find-origine", req) === false) return;
338
            if (self.getCoords("#find-destinazione", req) === false) return;
339
            console.log(req);
340
341
            var url = "http://poolmeup.appspot.com/rest/rides";
342
            $.post(url, JSON.stringify(req), function(data) {
343
                self.showDriverList(data.offers);
344
            });
345
346
        });
347
    },
348
349
    getCoords: function(id, req) {
350
        var obj = {};
351
        var url = "addr.json";
352
        // var url = "http://maps.googleapis.com/maps/api/geocode/json";
353
        $.ajax({url: url, data: {sensor: false, address: $(id).val()}, success: function (data) {
354
            var status = data.status;
355
            if (status == "ZERO_RESULTS") {
356
                self.showDialog("Zero Risultati", "L'indirizzo insierito è sconosciuto. Riprovare.");
357
                return false;
358
            }
359
            data = data.results[0];
360
            $(id).val(data.formatted_address);
361
            obj.name = data.formatted_address;
362
            obj.lat = data.geometry.location.lat;
363
            obj.long = data.geometry.location.lng;
364
            req.pathRequest.push(obj);
365
        }, dataType: "json", async: false});
366
        return obj;
367
    },
368
369
    showDialog: function(title, message) {
370
        $("#dialogtitle").text(title);
371
        $("#dialogmessage").html(message);
372
        $.mobile.changePage("#dialog");
373
    },
374
375
    ICONS: {
376
        "Start": "",
377
        "KeepStraight": "img/direction_up.png",
378
        "TurnSightlyLeft": "img/direction_upleft.png",
379
        "TurnLeft": "img/direction_upthenleft.png",
380
        "TurnRight": "img/direction_upthenright.png",
381
        "TurnSightlyRight": "img/direction_upright.png",
382
        "EnterRoundabout": ""
383
    },
384
    parseXML: function(url) {
385
        var self = this;
386
        var s = "";
387
        $.get(url, function(data) {
388
            $.each($("actn", data), function(i, el) {
389
                var el = $(el);
390
                var kind = el.attr("kind");
391
                if (kind != null) {
392
                    kind = kind.replace("{street}", el.attr("addr")).replace("{dir}", el.attr("dir"));
393
                    var link = el.parent(),
394
                        dist = /\d+(?:[.]\d{2})?/.exec(link.attr("dist"))[0],
395
                        time = /\d+(?:[.]\d{2})?/.exec(link.attr("time"))[0];
396
                    s += "<li><a href=\"#\"><img src=\""+self.ICONS[el.attr("actc")]+"\">"+
397
                        "<h3>"+kind+"</h3><p>percorsi "+dist+"m, sono passati "+time+ " secondi</p></a></li>";
398
                }
399
            });
400
        });
401
        return s;
402
    },
403
404
    longPolling: function(idOffer) {
405
        var self = this;
406
        var url = "http://poolmeup.appspot.com/rest/offers/";
407
        $.get(url+idOffer, function(data) {
408
            if (data != null && data.pathResponse != null) {
409
                clearInterval(self.timeoutID);
410
                self.showDialog("Richiesta trovata", "Il percorso sarà aggiornato!");
411
                var s = self.parseXML(data.pathResponse);
412
                $.mobile.changePage("#viewpath");
413
                $("#actionlist").html(s).listview("refresh");
414
            }
415
        });
416
    },
417
418
    getMyFriends: function() {
419
        return myFriends;
420
    },
421
422
    getMyPhone: function() {
423
        return window.localStorage.getItem("poolmeupmyphone");
424
    }
425
426
};