Listing 2. JavaScript Code for the Sample Application 1 var mobile = 1; 2 var contacts; 3 var current_contact = 0; 4 5 function init () { 6 7 if (mobile == 1) { 8 navigator.contacts.find(["*"], store_contacts); 9 } 10 11 update(); 12 window.setInterval(update, 1000); 13 } 14 15 function update () { 16 var req; 17 18 if (mobile == 1) { 19 navigator.geolocation.getCurrentPosition(set_location,location_error); 20 } else { 21 document.getElementById("lat").value = Math.floor(Math.random()*46) 22 document.getElementById("lon").value = Math.floor(Math.random()*46) 23 } 24 25 req = new XMLHttpRequest(); 26 27 if (!req) { 28 alert("Ajax failed!"); 29 return false; 30 } 31 32 req.open("GET", "http://example.com/test.html", true); 33 req.onreadystatechange = set_quote; 34 req.send(null); 35 36 return true; 37 } 38 39 function store_contacts (c) { 40 contacts = c; 41 display_contact(); 42 return true; 43 } 44 45 function previous_contact () { 46 current_contact = current_contact - 1; 47 if (current_contact < 0) { current_contact = 0; } 48 display_contact(); 49 return true; 50 } 51 52 function next_contact () { 53 current_contact = current_contact + 1; 54 if (current_contact > (contacts.length-1)) { current_contact = contacts.length-1; } 55 display_contact(); 56 return true; 57 } 58 59 function display_contact () { 60 document.getElementById("id").value = " "; 61 document.getElementById("name").value = " "; 62 document.getElementById("phone").value = " "; 63 document.getElementById("email").value = " "; 64 65 document.getElementById("id").value = contacts[current_contact].id; 66 document.getElementById("name").value = contacts[current_contact].displayName; 67 document.getElementById("phone").value = contacts[current_contact].phoneNumbers[0].value; 68 document.getElementById("email").value = contacts[current_contact].emails[0].value; 69 70 return true; 71 } 72 73 function set_location (p) { 74 document.getElementById("lat").value = p.coords.latitude; 75 document.getElementById("lon").value = p.coords.longitude; 76 return true; 77 } 78 79 function location_error (e) { 80 document.getElementById("error").innerHTML = e.message; 81 return true; 82 } 83 84 function set_quote (p) { 85 if (!p) { return 1; } 86 if ((p.status) && (p.status > 299)) { return 1; } 87 document.getElementById("quote").innerHTML = this.responseText; 88 return true; 89 } 90 91 if (mobile == 1) { 92 document.addEventListener("deviceready", init, false); 93 } else { 94 window.onload = init; 95 }