<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

 /*
 Not 100% stable. More a 80% thing. Need a better check if the device is still available before the app crashes.

 How to use:
 cordova platform add android
 cordova run android

 */

'use strict';

var barometer = {
    service: "F000AA40-0451-4000-B000-000000000000",
    data: "F000AA41-0451-4000-B000-000000000000",
    notification: "F0002902-0451-4000-B000-000000000000",
    configuration: "F000AA42-0451-4000-B000-000000000000",
    period: "F000AA43-0451-4000-B000-000000000000"
};

var app = {
	// Application Constructor
    initialize: function() {
        this.bindEvents();
        devicePage.hidden = true;
    },
	// Bind Event Listeners
	//
	// Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
        //onBTenabled is called as soon as the user enables Bluetooth
        addEventListener('BluetoothStatus.enabled', this.onBTenabled, false);
        SensorTagList.addEventListener('touchstart', this.connect, false);
		btnRefresh.addEventListener('touchstart', this.refreshSensorTagList, false);
        disconnectButton.addEventListener('touchstart', this.disconnect, false);
    },
    onDeviceReady: function() {
        //check if the device supports Bluetooth Low Energy
        //Android: initPlugin sets the values of BluetoothStatus. It will fail if the BluetoothManager class is not present
        //Android 4.3 is required as earlier versions dont have this class. Also for BTLE support at least Android 4.3 is needed
        cordova.plugins.BluetoothStatus.initPlugin();
        //dirty hack: wait for 1 second as otherwise the hasBTLE will not be set. Moving this into another event also wont work
        setTimeout(function() {
            if(!cordova.plugins.BluetoothStatus.hasBTLE){
                //as hasBTLE defaults to false we can still use it even if initPlugin fails,
                //which should only happen if the device has an Android version below 4.3
                navigator.notification.alert("Sorry. Your device does not support BTLE!", function(){navigator.app.exitApp();});
                return;
            }
            else
            {
                ble.isEnabled(
                    function() {
                        //BT was already enabled when the app started. this function is called if BT is currently enabled
                        app.onBTenabled();
                    },
                    function() {
                        //this function is called if BT is not enabled
                        navigator.notification.alert("Bluetooth is not enabled on your phone. Please turn it on to continue!", function(){});
                        ble.enable(
                            function() {
                                app.onBTenabled();
                            },
                            function() {
                                navigator.notification.alert("Sorry. This app only works with Bluetooth enabled.", function(){navigator.app.exitApp();});
                            }
                        );
            }
        );
            }
        }, 1000);

    },
    onBTenabled: function () {
        // Scan for SensorTags, after Bluetooth was enabled
        app.refreshSensorTagList();
    },
	// Update the List of Devices
    refreshSensorTagList: function() {
        SensorTagList.innerHTML = '';
        // scan for all devices. need to put something in ble(['filter']) to scan only for CC2560 SensorTags, not sure what
        ble.scan([], 5, app.onDiscoverDevice, app.onError);
    },
	// Show details of a device
    onDiscoverDevice: function(device) {
        var listItem = document.createElement('li'),
            html = '' + device.name + '
' +
                'RSSI: ' + device.rssi + ' | ' +
                device.id;

        listItem.dataset.deviceId = device.id;
        listItem.innerHTML = html;
        SensorTagList.appendChild(listItem);
    },
    connect: function(e) {
        var deviceId = e.target.dataset.deviceId,
            onConnect = function() {

                //Subscribe to barometer service
                ble.startNotification(deviceId, barometer.service, barometer.data, app.onBarometerData, app.onError);

                //Turn on barometer
                var barometerConfig = new Uint8Array(1);
                barometerConfig[0] = 0x01;
                ble.write(deviceId, barometer.service, barometer.configuration, barometerConfig.buffer,
                    function() { console.log("Started barometer."); },app.onError);

                //Associate the deviceID with the disconnect button
                disconnectButton.dataset.deviceId = deviceId;
                app.showDevicePage();
            };

        ble.connect(deviceId, onConnect, app.onError);
    },

    sensorBarometerConvert: function(data){
        return (data / 100);

    },
    onBarometerData: function(data) {
         console.log(data);
         var message;
         var a = new Uint8Array(data);

         //0-2 Temp
         //3-5 Pressure
         message =  "Temperature
" +
                    app.sensorBarometerConvert( a[0] | (a[1] << 8) | (a[2] << 16)) + "°C

" +
                    "Pressure
" +
                    app.sensorBarometerConvert( a[3] | (a[4] << 8) | (a[5] << 16)) + "hPa

" ;

        barometerData.innerHTML = message;

    },
    disconnect: function(event) {
        var deviceId = event.target.dataset.deviceId;
        ble.disconnect(deviceId, app.showOverviewPage, app.onError);
    },
    showOverviewPage: function() {
        overviewPage.hidden = false;
        devicePage.hidden = true;
    },
    showDevicePage: function() {
        overviewPage.hidden = true;
        devicePage.hidden = false;
    },
    onError: function(reason) {
        alert("ERROR: " + reason);
    }

};

app.initialize();
<commit_msg>Reconnect to default device<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

 /*
 Not 100% stable. More a 80% thing. Need a better check if the device is still available before the app crashes.

 How to use:
 cordova platform add android
 cordova run android

 */

'use strict';

var barometer = {
    service: "F000AA40-0451-4000-B000-000000000000",
    data: "F000AA41-0451-4000-B000-000000000000",
    notification: "F0002902-0451-4000-B000-000000000000",
    configuration: "F000AA42-0451-4000-B000-000000000000",
    period: "F000AA43-0451-4000-B000-000000000000"
};

var app = {
	// Application Constructor
    initialize: function() {
        this.bindEvents();
        devicePage.hidden = true;
    },
	// Bind Event Listeners
	//
	// Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
        //onBTenabled is called as soon as the user enables Bluetooth
        addEventListener('BluetoothStatus.enabled', this.onBTenabled, false);
        SensorTagList.addEventListener('touchstart', this.connect, false);
        SensorTagList.addEventListener('touchstart', this.wrap_connect, false);
		btnRefresh.addEventListener('touchstart', this.refreshSensorTagList, false);
        disconnectButton.addEventListener('touchstart', this.disconnect, false);
    },
    onDeviceReady: function() {
        //check if the device supports Bluetooth Low Energy
        //Android: initPlugin sets the values of BluetoothStatus. It will fail if the BluetoothManager class is not present
        //Android 4.3 is required as earlier versions dont have this class. Also for BTLE support at least Android 4.3 is needed
        cordova.plugins.BluetoothStatus.initPlugin();
        //dirty hack: wait for 1 second as otherwise the hasBTLE will not be set. Moving this into another event also wont work
        setTimeout(function() {
            if(!cordova.plugins.BluetoothStatus.hasBTLE){
                //as hasBTLE defaults to false we can still use it even if initPlugin fails,
                //which should only happen if the device has an Android version below 4.3
                navigator.notification.alert("Sorry. Your device does not support BTLE!", function(){navigator.app.exitApp();});
                return;
            }
            else
            {
                ble.isEnabled(
                    function() {
                        //BT was already enabled when the app started. this function is called if BT is currently enabled
                        app.onBTenabled();
                    },
                    function() {
                        //this function is called if BT is not enabled
                        navigator.notification.alert("Bluetooth is not enabled on your phone. Please turn it on to continue!", function(){});
                        ble.enable(
                            function() {
                                app.onBTenabled();
                            },
                            function() {
                                navigator.notification.alert("Sorry. This app only works with Bluetooth enabled.", function(){navigator.app.exitApp();});
                            }
                        );
                    }
                );
            }
        }, 1000);
    },
    onBTenabled: function () {
        // Scan for SensorTags, after Bluetooth was enabled
        ble.scan([], 1, app.oldConnection, app.onError);
    },
	// Update the List of Devices
    refreshSensorTagList: function() {
        SensorTagList.innerHTML = '';
        // scan for all devices. need to put something in ble(['filter']) to scan only for CC2560 SensorTags, not sure what
        ble.scan([], 5, app.onDiscoverDevice, app.onError);
    },
	// Restore old Connection
    oldConnection: function(device) {
        if(device.id == "B0:B4:48:D2:EC:03")
		{
			reconnectMessage.innerHTML = "Reconnecting...";
			app.connect(device.id);
		}

		// Make the List on Startup-Page
		app.onDiscoverDevice(device);
    },
	// Show details of a device
    onDiscoverDevice: function(device) {
        var listItem = document.createElement('li'),
            html = '' + device.name + '
' +
                'RSSI: ' + device.rssi + ' | ' +
                device.id;

        listItem.dataset.deviceId = device.id;
        listItem.innerHTML = html;
        SensorTagList.appendChild(listItem);
    },
	wrap_connect: function(e) {
        var deviceId = e.target.dataset.deviceId;
		app.connect(deviceId);
	},
	connect: function(deviceId) {

		var onConnect = function() {

			//Subscribe to barometer service
			ble.startNotification(deviceId, barometer.service, barometer.data, app.onBarometerData, app.onError);

			//Turn on barometer
			var barometerConfig = new Uint8Array(1);
			barometerConfig[0] = 0x01;
			ble.write(deviceId, barometer.service, barometer.configuration, barometerConfig.buffer,
				function() { console.log("Started barometer."); },app.onError);

			//Associate the deviceID with the disconnect button
			disconnectButton.dataset.deviceId = deviceId;
			app.showDevicePage();
            };

        ble.connect(deviceId, onConnect, app.onError);
    },

    sensorBarometerConvert: function(data){
        return (data / 100);

    },
    onBarometerData: function(data) {
         console.log(data);
         var message;
         var a = new Uint8Array(data);

         //0-2 Temp
         //3-5 Pressure
         message =  "Temperature
" +
                    app.sensorBarometerConvert( a[0] | (a[1] << 8) | (a[2] << 16)) + "°C

" +
                    "Pressure
" +
                    app.sensorBarometerConvert( a[3] | (a[4] << 8) | (a[5] << 16)) + "hPa

" ;

        barometerData.innerHTML = message;

    },
    disconnect: function(event) {
        var deviceId = event.target.dataset.deviceId;
        ble.disconnect(deviceId, app.showOverviewPage, app.onError);
    },
    showOverviewPage: function() {
        overviewPage.hidden = false;
        devicePage.hidden = true;
    },
    showDevicePage: function() {
		reconnectMessage.innerHTML = '';
        overviewPage.hidden = true;
        devicePage.hidden = false;
    },
    onError: function(reason) {
        alert("ERROR: " + reason);
    }

};

app.initialize();
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var deleteThisFile = {}; //Global object for image taken, to be deleted
var centralPairingUrl = "https://atomjump.com/med-genid.php";

var app = {

    // Application Constructor
    initialize: function() {

        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicity call 'app.receivedEvent(...);'
    onDeviceReady: function() {
          app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');
        console.log('Received Event: ' + id);
    },

    takePicture: function() {
      var _this = this;

      navigator.camera.getPicture( function( imageURI ) {
          _this.uploadPhoto(imageURI);
        },
       function( message ) {
        _this.notify( message );
       },
       {
        quality: 100,
        destinationType: Camera.DestinationType.FILE_URI
       });
    },

   get: function(url, cb) {
        var request = new XMLHttpRequest();
        request.open("GET", url, true);

        request.onreadystatechange = function() {
            if (request.readyState == 4) {
                if (request.status == 200 || request.status == 0) {

                    cb(url, request.responseText);   // -> request.responseText <- is a result
                }
            }
        }
        request.send();
    },

    scanlan: function(port, cb) {
     var _this = this;

      if(this.lan) {

       var lan = this.lan;

       for(var cnt=0; cnt< 255; cnt++){
          var machine = cnt.toString();
          var url = 'http://' + lan + machine + ':' + port;
          this.get(url, function(goodurl, resp) {
              if(resp) {
                 _this.foundServer = goodurl;
                 clearTimeout(scanning);
                 cb(goodurl, null);
              }
          });

       }

       //timeout after 5 secs
       var scanning = setTimeout(function() {
                _this.notify('Timeout finding your server. Please ensure your server is on the same wifi network as your device, or enter a custom http://serverip:port. The port is likely 5566.');
                document.getElementById('override-form').style.display = 'block';
       }, 5000);

      } else {

         cb(null,'Sorry, please connect to your Wifi network.');
      }
    },

    notify: function(msg) {
        //Set the user message
        document.getElementById("notify").innerHTML = msg;
    },

    uploadPhoto: function(imageURIin) {

        var _this = this;

        if(_this.foundServer) {

          window.resolveLocalFileSystemURI(imageURIin, function(fileEntry) {

            deleteThisFile = fileEntry; //Store globally

            var imageURI = fileEntry.toURL();
            var options = new FileUploadOptions();
            options.fileKey="file1";

            var tempName = document.getElementById("id-entered").value;
            if(_this.defaultDir) {
                //A hash code signifies a directory to write to
                tempName = "#" + _this.defaultDir + " " + tempName;
            }

            var myoutFile = tempName.replace(/ /g,'-');

			var mydt = navigator.globalization.dateToString(
			  new Date(),
			  function (date) {
				  var mydt = date.value.replace(/:/g,'-');
				  mydt = mydt.replace(/ /g,'-');
				  mydt = mydt.replace(/\//g,'-');

				  var aDate = new Date();
				  var seconds = aDate.getSeconds();
				  mydt = mydt + "-" + seconds;

				  options.fileName = myoutFile + '-' + mydt + '.jpg';

				  options.mimeType="image/jpeg";

				  var params = new Object();
				  params.title = document.getElementById("id-entered").value;

				  options.params = params;
				  options.chunkedMode = false;

				  var ft = new FileTransfer();

				  _this.notify("Uploading to " + _this.foundServer);
				  var serverReq = _this.foundServer + '/api/photo';

            	  ft.upload(imageURI, serverReq, _this.win, _this.fail, options);

			  },
			  function () {alert('Error getting dateString\n');},
			  {formatLength:'medium', selector:'date and time'}
			);

          } );
        } else {
            _this.notify('No server known');
        }
    },

    win: function(r) {
            console.log("Code = " + r.responseCode);
            console.log("Response = " + r.response);
            console.log("Sent = " + r.bytesSent);
            document.getElementById("notify").innerHTML = 'Image transferred.';
            document.getElementById("override-form").style.display = 'none';    //Hide any url entry

            //and delete phone version
            deleteThisFile.remove();

    },

    fail: function(error) {

        switch(error.code)
        {
            case 1:
                this.notify("Sorry the photo file was not found on your phone.");
            break;

            case 2:
                this.notify("Sorry you have tried to send it to an invalid URL.");
            break;

            case 3:
                this.notify("You cannot connect to the server at this time. Check if it is running, and try again.");
            break;

            case 4:
                this.notify("Sorry, your image transfer was aborted.");
            break;

            default:
                this.notify("An error has occurred: Code = " + error.code);
            break;
        }
    },

    getip: function(cb) {

           var _this = this;

           //timeout after 3 secs -rerun this.findServer()
           var iptime = setTimeout(function() {
                  var err = "You don't appear to be connected to your wifi. Please connect and try again, or override with your server's url and port.";
                  document.getElementById('override-form').style.display = 'block';
                  cb(err);
           }, 5000);

           networkinterface.getIPAddress(function(ip) {
               _this.ip = ip;
               var len =  ip.lastIndexOf('\.') + 1;
                _this.lan = ip.substr(0,len);
                clearTimeout(iptime);
                cb(null);
           });
    },

    clearOverride: function() {
        localStorage.clear();
        this.foundServer = null;
        document.getElementById("override").value = "";
        alert("Cleared default server.");

    },

    checkDefaultDir: function(server) {
        //Check if the default server has a default dir eg. http://123.123.123.123:5566/write/hello
        var requiredStr = "/write/";
        var startsAt = server.indexOf(requiredStr);
        if(startsAt >= 0) {
            //Get the default dir after the /write/ string
            var startFrom = startsAt + requiredStr.length;
            this.defaultDir = server.substr(startFrom);
            var properServer = server.substr(0, startsAt);
            return properServer;
        } else {
            return server;
        }

    },

    startup: function(overrideServer) {

        //First called at startup time.
        var _this = this;
        if((document.getElementById("override").value) &&
          (document.getElementById("override").value != '')&&
          (!overrideServer)) {

           overrideCode = document.getElementById("override").value;
           var pairUrl = centralPairingUrl + '?compare=' + overrideCode;
           _this.notify("Pairing with " + pairUrl);
           var requestGuid = _this.get(pairUrl, function(url, resp) {

			  if(resp == 'nomatch') {
				 	_this.notify("Sorry, there was no match for that code.");
		  	  } else {

				  var server = res;

				  _this.notify("Paired success with " + server);

				  var overrideServer = server;

				  //And save this server
				  localStorage.setItem("overrideServer",overrideServer);

				  //Rerun again, this time with new default
				  _this.startup(overrideServer);
		   	   }

           });

           return;
        } else {
            //Check if there is a saved server
            overrideServer = localStorage.getItem("overrideServer");

        }

        if(overrideServer) {
            overrideServer = this.checkDefaultDir(overrideServer);       //Check for a default upload directory
            this.overrideServer = overrideServer;

        }

        if(this.foundServer) {

          //We have already found the server
          var server = this.foundServer;

          //OK we already know the server, or did at least
          //try connecting to it

          _this.notify("Trying to connect..");
          this.get(server, function(url, resp) {

             //ok connected alright

             _this.notify("Connected.");
             clearTimeout(cnct);
             _this.takePicture();

          });

          //timeout after 5 secs
          var cnct = setTimeout(function() {
              _this.notify('Timeout connecting. Please try again.');
              _this.foundServer = null;
           }, 5000);

        } else {

            //Otherwise, first time we are running the app this session
            _this.notify("Looking for server");

             this.findServer(function(err) {

                 if(err) {

                   _this.notify(err);
                 } else {
                    _this.notify("Found server");
                   _this.takePicture();
                 }
             });

        }

    },

    findServer: function(cb) {

       var _this = this;

       if((this.overrideServer)&&(this.overrideServer != "")) {
           //on a user set override, or a dev set override

           var goodurl = this.overrideServer;
           this.foundServer = goodurl;

           _this.notify("Using server: " + goodurl);
           cb(null);
           return;
       }

       _this.notify("Checking Wifi connection");

       this.getip(function(ip, err) {

          if(err) {
             cb(err);
             return;
          }

          _this.notify("Scanning Wifi");

          _this.scanlan('5566', function(url, err) {

             if(err) {
               cb(err);
             } else {
               cb(null);
             }

          });
       });

    }

};
<commit_msg>first working ver<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var deleteThisFile = {}; //Global object for image taken, to be deleted
var centralPairingUrl = "https://atomjump.com/med-genid.php";

var app = {

    // Application Constructor
    initialize: function() {

        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicity call 'app.receivedEvent(...);'
    onDeviceReady: function() {
          app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');
        console.log('Received Event: ' + id);
    },

    takePicture: function() {
      var _this = this;

      navigator.camera.getPicture( function( imageURI ) {
          _this.uploadPhoto(imageURI);
        },
       function( message ) {
        _this.notify( message );
       },
       {
        quality: 100,
        destinationType: Camera.DestinationType.FILE_URI
       });
    },

   get: function(url, cb) {
        var request = new XMLHttpRequest();
        request.open("GET", url, true);

        request.onreadystatechange = function() {
            if (request.readyState == 4) {
				_this.notify("Trying ready state 4  status: " + request.status);
                if (request.status == 200 || request.status == 0) {

                    cb(url, request.responseText);   // -> request.responseText <- is a result
                }
            }
        }
        request.send();
    },

    scanlan: function(port, cb) {
     var _this = this;

      if(this.lan) {

       var lan = this.lan;

       for(var cnt=0; cnt< 255; cnt++){
          var machine = cnt.toString();
          var url = 'http://' + lan + machine + ':' + port;
          this.get(url, function(goodurl, resp) {
              if(resp) {
                 _this.foundServer = goodurl;
                 clearTimeout(scanning);
                 cb(goodurl, null);
              }
          });

       }

       //timeout after 5 secs
       var scanning = setTimeout(function() {
                _this.notify('Timeout finding your server. Please ensure your server is on the same wifi network as your device, or enter a custom http://serverip:port. The port is likely 5566.');
                document.getElementById('override-form').style.display = 'block';
       }, 5000);

      } else {

         cb(null,'Sorry, please connect to your Wifi network.');
      }
    },

    notify: function(msg) {
        //Set the user message
        document.getElementById("notify").innerHTML = msg;
    },

    uploadPhoto: function(imageURIin) {

        var _this = this;

        if(_this.foundServer) {

          window.resolveLocalFileSystemURI(imageURIin, function(fileEntry) {

            deleteThisFile = fileEntry; //Store globally

            var imageURI = fileEntry.toURL();
            var options = new FileUploadOptions();
            options.fileKey="file1";

            var tempName = document.getElementById("id-entered").value;
            if(_this.defaultDir) {
                //A hash code signifies a directory to write to
                tempName = "#" + _this.defaultDir + " " + tempName;
            }

            var myoutFile = tempName.replace(/ /g,'-');

			var mydt = navigator.globalization.dateToString(
			  new Date(),
			  function (date) {
				  var mydt = date.value.replace(/:/g,'-');
				  mydt = mydt.replace(/ /g,'-');
				  mydt = mydt.replace(/\//g,'-');

				  var aDate = new Date();
				  var seconds = aDate.getSeconds();
				  mydt = mydt + "-" + seconds;

				  options.fileName = myoutFile + '-' + mydt + '.jpg';

				  options.mimeType="image/jpeg";

				  var params = new Object();
				  params.title = document.getElementById("id-entered").value;

				  options.params = params;
				  options.chunkedMode = false;

				  var ft = new FileTransfer();

				  _this.notify("Uploading to " + _this.foundServer);
				  var serverReq = _this.foundServer + '/api/photo';

            	  ft.upload(imageURI, serverReq, _this.win, _this.fail, options);

			  },
			  function () {alert('Error getting dateString\n');},
			  {formatLength:'medium', selector:'date and time'}
			);

          } );
        } else {
            _this.notify('No server known');
        }
    },

    win: function(r) {
            console.log("Code = " + r.responseCode);
            console.log("Response = " + r.response);
            console.log("Sent = " + r.bytesSent);
            document.getElementById("notify").innerHTML = 'Image transferred.';
            document.getElementById("override-form").style.display = 'none';    //Hide any url entry

            //and delete phone version
            deleteThisFile.remove();

    },

    fail: function(error) {

        switch(error.code)
        {
            case 1:
                this.notify("Sorry the photo file was not found on your phone.");
            break;

            case 2:
                this.notify("Sorry you have tried to send it to an invalid URL.");
            break;

            case 3:
                this.notify("You cannot connect to the server at this time. Check if it is running, and try again.");
            break;

            case 4:
                this.notify("Sorry, your image transfer was aborted.");
            break;

            default:
                this.notify("An error has occurred: Code = " + error.code);
            break;
        }
    },

    getip: function(cb) {

           var _this = this;

           //timeout after 3 secs -rerun this.findServer()
           var iptime = setTimeout(function() {
                  var err = "You don't appear to be connected to your wifi. Please connect and try again, or override with your server's url and port.";
                  document.getElementById('override-form').style.display = 'block';
                  cb(err);
           }, 5000);

           networkinterface.getIPAddress(function(ip) {
               _this.ip = ip;
               var len =  ip.lastIndexOf('\.') + 1;
                _this.lan = ip.substr(0,len);
                clearTimeout(iptime);
                cb(null);
           });
    },

    clearOverride: function() {
        localStorage.clear();
        this.foundServer = null;
        document.getElementById("override").value = "";
        alert("Cleared default server.");

    },

    checkDefaultDir: function(server) {
        //Check if the default server has a default dir eg. http://123.123.123.123:5566/write/hello
        var requiredStr = "/write/";
        var startsAt = server.indexOf(requiredStr);
        if(startsAt >= 0) {
            //Get the default dir after the /write/ string
            var startFrom = startsAt + requiredStr.length;
            this.defaultDir = server.substr(startFrom);
            var properServer = server.substr(0, startsAt);
            return properServer;
        } else {
            return server;
        }

    },

    startup: function(overrideServer) {

        //First called at startup time.
        var _this = this;
        if((document.getElementById("override").value) &&
          (document.getElementById("override").value != '')&&
          (!overrideServer)) {

           overrideCode = document.getElementById("override").value;
           var pairUrl = centralPairingUrl + '?compare=' + overrideCode;
           _this.notify("Pairing with " + pairUrl);
           var requestGuid = _this.get(pairUrl, function(url, resp) {

			  if(resp == 'nomatch') {
				 	_this.notify("Sorry, there was no match for that code.");
		  	  } else {

				  var server = res;

				  _this.notify("Paired success with " + server);

				  var overrideServer = server;

				  //And save this server
				  localStorage.setItem("overrideServer",overrideServer);

				  //Rerun again, this time with new default
				  _this.startup(overrideServer);
		   	   }

           });

           return;
        } else {
            //Check if there is a saved server
            overrideServer = localStorage.getItem("overrideServer");

        }

        if(overrideServer) {
            overrideServer = this.checkDefaultDir(overrideServer);       //Check for a default upload directory
            this.overrideServer = overrideServer;

        }

        if(this.foundServer) {

          //We have already found the server
          var server = this.foundServer;

          //OK we already know the server, or did at least
          //try connecting to it

          _this.notify("Trying to connect..");
          this.get(server, function(url, resp) {

             //ok connected alright

             _this.notify("Connected.");
             clearTimeout(cnct);
             _this.takePicture();

          });

          //timeout after 5 secs
          var cnct = setTimeout(function() {
              _this.notify('Timeout connecting. Please try again.');
              _this.foundServer = null;
           }, 5000);

        } else {

            //Otherwise, first time we are running the app this session
            _this.notify("Looking for server");

             this.findServer(function(err) {

                 if(err) {

                   _this.notify(err);
                 } else {
                    _this.notify("Found server");
                   _this.takePicture();
                 }
             });

        }

    },

    findServer: function(cb) {

       var _this = this;

       if((this.overrideServer)&&(this.overrideServer != "")) {
           //on a user set override, or a dev set override

           var goodurl = this.overrideServer;
           this.foundServer = goodurl;

           _this.notify("Using server: " + goodurl);
           cb(null);
           return;
       }

       _this.notify("Checking Wifi connection");

       this.getip(function(ip, err) {

          if(err) {
             cb(err);
             return;
          }

          _this.notify("Scanning Wifi");

          _this.scanlan('5566', function(url, err) {

             if(err) {
               cb(err);
             } else {
               cb(null);
             }

          });
       });

    }

};
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {

		// onSuccess Callback
// This method accepts a Position object, which contains the
// current GPS coordinates
//
		// onSuccess Callback
//   This method accepts a `Position` object, which contains
//   the current GPS coordinates
//
function onSuccess(position) {

	var pos1
	var pos2
	var pos3
    $('#ubi').hide()
	var cordenadas = position.coords.latitude+", "+position.coords.longitude

	var Result0 = $.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.placefinder%20where%20text=%22"+cordenadas+"%22%20and%20gflags=%22R%22&format=json", "",
    function (data0)
    {
		pos1 = data0.query.results.Result.city
		pos2 = data0.query.results.Result.countrycode

		localStorage.setItem("ciudad", data0.query.results.Result.city);
		localStorage.setItem("codigo", data0.query.results.Result.countrycode);

		var Result1 = $.getJSON("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22"+pos1+", "+pos2+"%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys", "",
		function (data1)
		{
			$('#tt1').html(data1.query.results.channel.location.city)
			$('#tt2').html(""+data1.query.results.channel.item.forecast[0].day+" "+data1.query.results.channel.item.forecast[0].date+", "+data1.query.results.channel.item.condition.text)
			$('#grados').html(data1.query.results.channel.item.condition.temp+'°')
			grados = data1.query.results.channel.item.condition.temp

			$('#dia1').html(data1.query.results.channel.item.forecast[0].day)
			$('#ic1').attr('src', 'iconos/'+data1.query.results.channel.item.forecast[0].code+'.svg');

			$('#dia2').html(data1.query.results.channel.item.forecast[1].day)
			$('#ic2').attr('src', 'iconos/'+data1.query.results.channel.item.forecast[1].code+'.svg');

			$('#dia3').html(data1.query.results.channel.item.forecast[2].day)
			$('#ic3').attr('src', 'iconos/'+data1.query.results.channel.item.forecast[2].code+'.svg');

			$('#dia4').html(data1.query.results.channel.item.forecast[3].day)
			$('#ic4').attr('src', 'iconos/'+data1.query.results.channel.item.forecast[3].code+'.svg');

			$('#dia5').html(data1.query.results.channel.item.forecast[4].day)
			$('#ic5').attr('src', 'iconos/'+data1.query.results.channel.item.forecast[4].code+'.svg');
			//$("body").append("SuntSet: " + data.query.results.channel.astronomy.sunset + "
");
			var ico = data1.query.results.channel.item.condition.code
			 $('#icono').attr('src', 'iconos/'+data1.query.results.channel.item.condition.code+'.svg');
			 $('#pollo').animate({opacity:'0.0'}, 0);
			 $('#pollo').delay(1000).animate({opacity:'1'}, 800);
			 if(ico==3 || ico==27 || ico==29 || ico==31 || ico==33 || ico==38 || ico==39){
				$('#pollo').attr('src', 'animaciones/an'+data1.query.results.channel.item.condition.code+'/an1.html');
			 }else{
				$('#pollo').attr('src', 'animaciones/an1/an1.html');
			 }

			 if(gg==1){
		 		gr = (grados -32)/1.8
				gr = Math.round(gr)
				$('#grados').html(gr+'°')
		 	 }

			 if(ico==1 || ico==2 || ico==3 || ico==4 || ico==27 || ico==29 || ico==31 || ico==33 || ico==34 || ico==45 || ico==3200){
		 	$('#fondo1, #fondo2, #fondo3, #fondo4, #fondo5, #fondo6').fadeOut()
		 	$('#fondo5').fadeIn()
		 	$('#clima').css('background-color','#022f4b')
		 }else if(ico==0 || ico==5 || ico==6 || ico==7 || ico==8 || ico==9 || ico==10 || ico==13 || ico==14 || ico==15 || ico==16 || ico==17 || ico==18 || ico==20 || ico==22 || ico==35 || ico==37 || ico==38 || ico==39 || ico==40 || ico==41 || ico==42 || ico==43 || ico==46 || ico==47){
		 	$('#fondo1, #fondo2, #fondo3, #fondo4, #fondo5, #fondo6').fadeOut()
		 	$('#fondo6').fadeIn()
		 	$('#clima').css('background-color','#3f5b76')
		 }else if(ico==11 || ico==12 || ico==19 || ico==21 || ico==23 || ico==24 || ico==25 || ico==26 || ico==28 || ico==30 || ico==44){
		 	$('#fondo1, #fondo2, #fondo3, #fondo4, #fondo5, #fondo6').fadeOut()
		 	$('#fondo4').fadeIn()
		 	$('#clima').css('background-color','#2d97c7')
		 }else if(ico==36){
		 	$('#fondo1, #fondo2, #fondo3, #fondo4, #fondo5, #fondo6').fadeOut()
		 	$('#fondo1').fadeIn()
		 	$('#clima').css('background-color','#be1414')
		 }else if(ico==32){
		 	$('#fondo1, #fondo2, #fondo3, #fondo4, #fondo5, #fondo6').fadeOut()
		 	$('#fondo3').fadeIn()
		 	$('#clima').css('background-color','#eab344')
		 }
		});
    });

}

// onError Callback receives a PositionError object
//
function onError(error) {

}

// Options: throw an error if no update is received every 30 seconds.
//
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, {enableHighAccuracy: true});

    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    }

};

<commit_msg>sin<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {

		// onSuccess Callback
// This method accepts a Position object, which contains the
// current GPS coordinates
//
		// onSuccess Callback
//   This method accepts a `Position` object, which contains
//   the current GPS coordinates
//
function onSuccess(position) {

	var pos1
	var pos2
	var pos3
    $('#ubi').hide()
	var cordenadas = position.coords.latitude+", "+position.coords.longitude

	navigator.geolocation.clearWatch(watchID);

	var Result0 = $.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.placefinder%20where%20text=%22"+cordenadas+"%22%20and%20gflags=%22R%22&format=json", "",
    function (data0)
    {
		pos1 = data0.query.results.Result.city
		pos2 = data0.query.results.Result.countrycode

		localStorage.setItem("ciudad", data0.query.results.Result.city);
		localStorage.setItem("codigo", data0.query.results.Result.countrycode);

		var Result1 = $.getJSON("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22"+pos1+", "+pos2+"%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys", "",
		function (data1)
		{
			$('#tt1').html(data1.query.results.channel.location.city)
			$('#tt2').html(""+data1.query.results.channel.item.forecast[0].day+" "+data1.query.results.channel.item.forecast[0].date+", "+data1.query.results.channel.item.condition.text)
			$('#grados').html(data1.query.results.channel.item.condition.temp+'°')
			grados = data1.query.results.channel.item.condition.temp

			$('#dia1').html(data1.query.results.channel.item.forecast[0].day)
			$('#ic1').attr('src', 'iconos/'+data1.query.results.channel.item.forecast[0].code+'.svg');

			$('#dia2').html(data1.query.results.channel.item.forecast[1].day)
			$('#ic2').attr('src', 'iconos/'+data1.query.results.channel.item.forecast[1].code+'.svg');

			$('#dia3').html(data1.query.results.channel.item.forecast[2].day)
			$('#ic3').attr('src', 'iconos/'+data1.query.results.channel.item.forecast[2].code+'.svg');

			$('#dia4').html(data1.query.results.channel.item.forecast[3].day)
			$('#ic4').attr('src', 'iconos/'+data1.query.results.channel.item.forecast[3].code+'.svg');

			$('#dia5').html(data1.query.results.channel.item.forecast[4].day)
			$('#ic5').attr('src', 'iconos/'+data1.query.results.channel.item.forecast[4].code+'.svg');
			//$("body").append("SuntSet: " + data.query.results.channel.astronomy.sunset + "
");
			var ico = data1.query.results.channel.item.condition.code
			 $('#icono').attr('src', 'iconos/'+data1.query.results.channel.item.condition.code+'.svg');
			 $('#pollo').animate({opacity:'0.0'}, 0);
			 $('#pollo').delay(1000).animate({opacity:'1'}, 800);
			 if(ico==3 || ico==27 || ico==29 || ico==31 || ico==33 || ico==38 || ico==39){
				$('#pollo').attr('src', 'animaciones/an'+data1.query.results.channel.item.condition.code+'/an1.html');
			 }else{
				$('#pollo').attr('src', 'animaciones/an1/an1.html');
			 }

			 if(gg==1){
		 		gr = (grados -32)/1.8
				gr = Math.round(gr)
				$('#grados').html(gr+'°')
		 	 }

			 if(ico==1 || ico==2 || ico==3 || ico==4 || ico==27 || ico==29 || ico==31 || ico==33 || ico==34 || ico==45 || ico==3200){
		 	$('#fondo1, #fondo2, #fondo3, #fondo4, #fondo5, #fondo6').fadeOut()
		 	$('#fondo5').fadeIn()
		 	$('#clima').css('background-color','#022f4b')
		 }else if(ico==0 || ico==5 || ico==6 || ico==7 || ico==8 || ico==9 || ico==10 || ico==13 || ico==14 || ico==15 || ico==16 || ico==17 || ico==18 || ico==20 || ico==22 || ico==35 || ico==37 || ico==38 || ico==39 || ico==40 || ico==41 || ico==42 || ico==43 || ico==46 || ico==47){
		 	$('#fondo1, #fondo2, #fondo3, #fondo4, #fondo5, #fondo6').fadeOut()
		 	$('#fondo6').fadeIn()
		 	$('#clima').css('background-color','#3f5b76')
		 }else if(ico==11 || ico==12 || ico==19 || ico==21 || ico==23 || ico==24 || ico==25 || ico==26 || ico==28 || ico==30 || ico==44){
		 	$('#fondo1, #fondo2, #fondo3, #fondo4, #fondo5, #fondo6').fadeOut()
		 	$('#fondo4').fadeIn()
		 	$('#clima').css('background-color','#2d97c7')
		 }else if(ico==36){
		 	$('#fondo1, #fondo2, #fondo3, #fondo4, #fondo5, #fondo6').fadeOut()
		 	$('#fondo1').fadeIn()
		 	$('#clima').css('background-color','#be1414')
		 }else if(ico==32){
		 	$('#fondo1, #fondo2, #fondo3, #fondo4, #fondo5, #fondo6').fadeOut()
		 	$('#fondo3').fadeIn()
		 	$('#clima').css('background-color','#eab344')
		 }
		});
    });

}

// onError Callback receives a PositionError object
//
function onError(error) {

}

// Options: throw an error if no update is received every 30 seconds.
//
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, {enableHighAccuracy: true});

    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    }

};

<|endoftext|>


<commit_before>var BodyColor = function () {
  var hex =  function () {
    var values = '0123456789ABCDEF';
    return values[Math.floor(Math.random() * values.length)];
  };

  var newColor = function (existingColor) {
    var color;

    // not ideal: knockout passes object through newColor function
    if (typeof existingColor === 'string') {
      color = existingColor;
    } else {
      color = '#';

      var i;
      for (i = 0; i < 6; i++) {
        color += hex();
      }
    }

    var body = document.getElementsByTagName('body')[0];
    body.style.background = color;
    window.localStorage.color = color;
  };

  return {
    initialize: function () {
      newColor(window.localStorage.color);

      return this;
    },
    newColor: newColor
  };
};

var app = {
  // Application Constructor
  initialize: function() {
    this.bindEvents();
  },
  // Bind Event Listeners
  //
  // Bind any events that are required on startup. Common events are:
  // 'load', 'deviceready', 'offline', and 'online'.
  bindEvents: function() {
    var bodyColor = BodyColor().initialize();

    document.addEventListener('deviceready', this.onDeviceReady, false);
    document.getElementById('app').addEventListener('click', function () {
      bodyColor.newColor();
    });
  },
  // deviceready Event Handler
  //
  // The scope of 'this' is the event. In order to call the 'receivedEvent'
  // function, we must explicitly call 'app.receivedEvent(...);'
  onDeviceReady: function() {
    app.receivedEvent('deviceready');
  },
  // Update DOM on a Received Event
  receivedEvent: function(id) {
    var parentElement = document.getElementById(id);
    var listeningElement = parentElement.querySelector('.listening');
    var receivedElement = parentElement.querySelector('.received');

    listeningElement.setAttribute('style', 'display:none;');
    receivedElement.setAttribute('style', 'display:block;');

    console.log('Received Event: ' + id);
  }
};

app.initialize();
<commit_msg>only look for the body tag once<commit_after>var BodyColor = function () {
  var hex =  function () {
    var values = '0123456789ABCDEF';
    return values[Math.floor(Math.random() * values.length)];
  };

  var body = document.getElementsByTagName('body')[0];

  var newColor = function (existingColor) {
    var color;

    // not ideal: knockout passes object through newColor function
    if (typeof existingColor === 'string') {
      color = existingColor;
    } else {
      color = '#';

      var i;
      for (i = 0; i < 6; i++) {
        color += hex();
      }
    }

    body.style.background = color;
    window.localStorage.color = color;
  };

  return {
    initialize: function () {
      newColor(window.localStorage.color);

      return this;
    },
    newColor: newColor
  };
};

var app = {
  // Application Constructor
  initialize: function() {
    this.bindEvents();
  },
  // Bind Event Listeners
  //
  // Bind any events that are required on startup. Common events are:
  // 'load', 'deviceready', 'offline', and 'online'.
  bindEvents: function() {
    var bodyColor = BodyColor().initialize();

    document.addEventListener('deviceready', this.onDeviceReady, false);
    document.getElementById('app').addEventListener('click', function () {
      bodyColor.newColor();
    });
  },
  // deviceready Event Handler
  //
  // The scope of 'this' is the event. In order to call the 'receivedEvent'
  // function, we must explicitly call 'app.receivedEvent(...);'
  onDeviceReady: function() {
    app.receivedEvent('deviceready');
  },
  // Update DOM on a Received Event
  receivedEvent: function(id) {
    var parentElement = document.getElementById(id);
    var listeningElement = parentElement.querySelector('.listening');
    var receivedElement = parentElement.querySelector('.received');

    listeningElement.setAttribute('style', 'display:none;');
    receivedElement.setAttribute('style', 'display:block;');

    console.log('Received Event: ' + id);
  }
};

app.initialize();
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var app = {

    // Application Constructor
    initialize: function() {

        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicity call 'app.receivedEvent(...);'
    onDeviceReady: function() {
          app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    },

    takePicture: function() {
      var _this = this;

      navigator.camera.getPicture( function( imageURI ) {
          _this.uploadPhoto(imageURI);
        },
       function( message ) {
        alert( message );
       },
       {
        quality: 100,
        destinationType: Camera.DestinationType.FILE_URI
       });
    },

   get: function(url, cb) {
        var request = new XMLHttpRequest();
        request.open("GET", url, true);

        request.onreadystatechange = function() {
            if (request.readyState == 4) {
                if (request.status == 200 || request.status == 0) {

                    cb(url, request.responseText);

                    // -> request.responseText <- is a result
                }
            }
        }
        request.send();
    },

    scanlan: function(port, cb) {
     var _this = this;

      if(this.lan) {

       var lan = this.lan;

       for(var cnt=0; cnt< 255; cnt++){
          var machine = cnt.toString();
          var url = 'http://' + lan + machine + ':' + port;
          this.get(url, function(goodurl, resp) {
              if(resp) {
                 _this.foundServer = goodurl + '/api/photo';
                 clearTimeout(scanning);
                 cb(goodurl, null);
              }
          });

       }

       //timeout after 5 secs
       var scanning = setTimeout(function() {
                alert('Timeout finding your server. Please ensure your server is on the same wifi network as your device, or enter a custom http://serverip:port. The port is likely 5566.');
                document.getElementById('override-form').style.display = 'block';
       }, 5000);

      } else {

         cb(null,'Sorry, please connect to your Wifi network.');
      }
    },

    uploadPhoto: function(imageURIin) {

        var _this = this;

        if(_this.foundServer) {

          window.resolveLocalFileSystemURI(imageURIin, function(fileEntry) {

            var imageURI = fileEntry.toURL();
            var options = new FileUploadOptions();
            options.fileKey="file1";
            options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
            options.mimeType="image/jpeg";

            var params = new Object();
            params.title = document.getElementById("id-entered").value;

            options.params = params;
            options.chunkedMode = false;

            var ft = new FileTransfer();
            ft.upload(imageURI, _this.foundServer, _this.win, _this.fail, options);
          } );
        } else {
            alert('No server known');
        }
    },

    win: function(r) {
            console.log("Code = " + r.responseCode);
            console.log("Response = " + r.response);
            console.log("Sent = " + r.bytesSent);
            alert('Image transferred.');
    },

    fail: function(error) {
            alert("An error has occurred: Code = " + error.code);
    },

    getip: function(cb) {

           var _this = this;

           networkinterface.getIPAddress(function(ip) {
               _this.ip = ip;
               var len =  ip.lastIndexOf('\.') + 1;
                _this.lan = ip.substr(0,len);
                cb(ip);
           });
    },

    startup: function(overrideServer) {
        var _this = this;
        if((document.getElementById("override").value) &&
          (document.getElementById("override").value != '')) {

           overrideServer = document.getElementById("override").value;
        }

        if(overrideServer) {
            this.overrideServer = overrideServer;
        }

        if(this.foundServer) {

          var server = this.foundServer;

              //OK we already know the server, or did at least
              //try connecting to it
              this.get(server, function(url, resp) {

                 //ok connected alright
                 clearTimeout(cnct);
                 _this.takePicture();

              });

              //timeout after 3 secs -rerun this.findServer()
              var cnct = setTimeout(function() {
                  alert('Timeout connecting. Please try again.');
                  _this.foundServer = null;
               }, 3000);

        } else {
             this.findServer(function(err) {

                 if(err) {
                   alert(err);
                 } else {
                   _this.takePicture();
                 }
             });

        }

    },

    findServer: function(cb) {

       var _this = this;

       if((this.overrideServer)&&(this.overrideServer != "")) {
           //on a user set override, or a dev set override

           var goodurl = this.overrideServer;
           this.foundServer = goodurl + '/api/photo';
           cb(null);
           return;
       }

       this.getip(function() {

          _this.scanlan('5566', function(url, err) {

             if(err) {
               cb(err);
             } else {
               cb(null);
             }

          });
       });

    }

};
<commit_msg>timeout on no lan<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var app = {

    // Application Constructor
    initialize: function() {

        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicity call 'app.receivedEvent(...);'
    onDeviceReady: function() {
          app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    },

    takePicture: function() {
      var _this = this;

      navigator.camera.getPicture( function( imageURI ) {
          _this.uploadPhoto(imageURI);
        },
       function( message ) {
        alert( message );
       },
       {
        quality: 100,
        destinationType: Camera.DestinationType.FILE_URI
       });
    },

   get: function(url, cb) {
        var request = new XMLHttpRequest();
        request.open("GET", url, true);

        request.onreadystatechange = function() {
            if (request.readyState == 4) {
                if (request.status == 200 || request.status == 0) {

                    cb(url, request.responseText);

                    // -> request.responseText <- is a result
                }
            }
        }
        request.send();
    },

    scanlan: function(port, cb) {
     var _this = this;

      if(this.lan) {

       var lan = this.lan;

       for(var cnt=0; cnt< 255; cnt++){
          var machine = cnt.toString();
          var url = 'http://' + lan + machine + ':' + port;
          this.get(url, function(goodurl, resp) {
              if(resp) {
                 _this.foundServer = goodurl + '/api/photo';
                 clearTimeout(scanning);
                 cb(goodurl, null);
              }
          });

       }

       //timeout after 5 secs
       var scanning = setTimeout(function() {
                alert('Timeout finding your server. Please ensure your server is on the same wifi network as your device, or enter a custom http://serverip:port. The port is likely 5566.');
                document.getElementById('override-form').style.display = 'block';
       }, 5000);

      } else {

         cb(null,'Sorry, please connect to your Wifi network.');
      }
    },

    uploadPhoto: function(imageURIin) {

        var _this = this;

        if(_this.foundServer) {

          window.resolveLocalFileSystemURI(imageURIin, function(fileEntry) {

            var imageURI = fileEntry.toURL();
            var options = new FileUploadOptions();
            options.fileKey="file1";
            options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
            options.mimeType="image/jpeg";

            var params = new Object();
            params.title = document.getElementById("id-entered").value;

            options.params = params;
            options.chunkedMode = false;

            var ft = new FileTransfer();
            ft.upload(imageURI, _this.foundServer, _this.win, _this.fail, options);
          } );
        } else {
            alert('No server known');
        }
    },

    win: function(r) {
            console.log("Code = " + r.responseCode);
            console.log("Response = " + r.response);
            console.log("Sent = " + r.bytesSent);
            alert('Image transferred.');
    },

    fail: function(error) {
            alert("An error has occurred: Code = " + error.code);
    },

    getip: function(cb) {

           var _this = this;

           //timeout after 3 secs -rerun this.findServer()
           var iptime = setTimeout(function() {
                  alert("You don't appear to be connected to your wifi. Please connect and try again, or override with your server's url and port.');
                  document.getElementById('override-form').style.display = 'block';

           }, 3000);

           networkinterface.getIPAddress(function(ip) {
               _this.ip = ip;
               var len =  ip.lastIndexOf('\.') + 1;
                _this.lan = ip.substr(0,len);
                clearTimeout(iptime);
                cb(ip);
           });
    },

    startup: function(overrideServer) {
        var _this = this;
        if((document.getElementById("override").value) &&
          (document.getElementById("override").value != '')) {

           overrideServer = document.getElementById("override").value;
        }

        if(overrideServer) {
            this.overrideServer = overrideServer;
        }

        if(this.foundServer) {

          var server = this.foundServer;

              //OK we already know the server, or did at least
              //try connecting to it
              this.get(server, function(url, resp) {

                 //ok connected alright
                 clearTimeout(cnct);
                 _this.takePicture();

              });

              //timeout after 3 secs -rerun this.findServer()
              var cnct = setTimeout(function() {
                  alert('Timeout connecting. Please try again.');
                  _this.foundServer = null;
               }, 3000);

        } else {
             this.findServer(function(err) {

                 if(err) {
                   alert(err);
                 } else {
                   _this.takePicture();
                 }
             });

        }

    },

    findServer: function(cb) {

       var _this = this;

       if((this.overrideServer)&&(this.overrideServer != "")) {
           //on a user set override, or a dev set override

           var goodurl = this.overrideServer;
           this.foundServer = goodurl + '/api/photo';
           cb(null);
           return;
       }

       this.getip(function() {

          _this.scanlan('5566', function(url, err) {

             if(err) {
               cb(err);
             } else {
               cb(null);
             }

          });
       });

    }

};
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.deviceList = document.getElementById("deviceList");
        app.refreshButton = document.getElementById("refreshButton");
        app.updateNamesButton = document.getElementById("updateNames");
        app.refreshDeviceList();

        app.refreshButton.addEventListener("click", app.refreshDeviceList);
        app.updateNamesButton.addEventListener("click", app.updateNames);
    },
    refreshDeviceList: function() {

        app.deviceList.innerHTML = ''; // empties the list
        rfduino.discover(5, app.onDiscoverDevice, app.onError);
    },
    updateNames: function() {
        app.deviceIds = [];
        rfduino.list(function(devices) {
          devices.forEach(function(device) {
            app.deviceIds.push(device.uuid);
          });
          app.updateNames2();
        }, app.onError);
    },
    updateNames2: function() {
        if(app.deviceIds.length == 0){
            return
        }
        app.currentDeviceId = app.deviceIds.pop();
        rfduino.connect(app.currentDeviceId, function (){
          setTimeout(app.updateName3, 1000);
        }, app.onError);
    },
    updateName3: function(){
      console.log("updating: " + app.currentDeviceId);
      var encoder = new TextEncoder("utf-8");
      var customName = app.currentDeviceId.slice(-5);
      var command = "n" + customName;
      rfduino.write(encoder.encode(command).buffer, function (){
        console.log(" disconnecting");
        rfduino.disconnect(function (){
          setTimeout(app.updateNames2, 500);
        }, app.onError);
      }, app.onError);
    },
    onDiscoverDevice: function(device) {
        var listItem = document.createElement('li'),
            html = '' + device.name + '
' +
                device.uuid;
        listItem.setAttribute('uuid', device.uuid);
        listItem.innerHTML = html;
        app.deviceList.appendChild(listItem);
    },
    onError: function(error) {
        console.log(error);
    }
};

app.initialize();<commit_msg>increase timeout more<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.deviceList = document.getElementById("deviceList");
        app.refreshButton = document.getElementById("refreshButton");
        app.updateNamesButton = document.getElementById("updateNames");
        app.refreshDeviceList();

        app.refreshButton.addEventListener("click", app.refreshDeviceList);
        app.updateNamesButton.addEventListener("click", app.updateNames);
    },
    refreshDeviceList: function() {

        app.deviceList.innerHTML = ''; // empties the list
        rfduino.discover(5, app.onDiscoverDevice, app.onError);
    },
    updateNames: function() {
        app.deviceIds = [];
        rfduino.list(function(devices) {
          devices.forEach(function(device) {
            app.deviceIds.push(device.uuid);
          });
          app.updateNames2();
        }, app.onError);
    },
    updateNames2: function() {
        if(app.deviceIds.length == 0){
            return
        }
        app.currentDeviceId = app.deviceIds.pop();
        rfduino.connect(app.currentDeviceId, function (){
          setTimeout(app.updateName3, 2000);
        }, app.onError);
    },
    updateName3: function(){
      console.log("updating: " + app.currentDeviceId);
      var encoder = new TextEncoder("utf-8");
      var customName = app.currentDeviceId.slice(-5);
      var command = "n" + customName;
      rfduino.write(encoder.encode(command).buffer, function (){
        console.log(" disconnecting");
        rfduino.disconnect(function (){
          setTimeout(app.updateNames2, 1000);
        }, app.onError);
      }, app.onError);
    },
    onDiscoverDevice: function(device) {
        var listItem = document.createElement('li'),
            html = '' + device.name + '
' +
                device.uuid;
        listItem.setAttribute('uuid', device.uuid);
        listItem.innerHTML = html;
        app.deviceList.appendChild(listItem);
    },
    onError: function(error) {
        console.log(error);
    }
};

app.initialize();<|endoftext|>


<commit_before>
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var readingsArray = [];
var readings = [];
var reading = {};

if (localStorage.getItem("readings") == null) {

	//alert('Reading Empty');

	//readingsArray = [ { 'summary' : 'Test event ', 'begin' : new Date(), 'end' : new Date() } ];

} else {

	//alert('Reading NOT Empty');

	//localStorage.removeItem('readings');

	reading = { 'summary' : 'Today', 'begin' : new Date(y, m, d), 'end' : new Date(y, m, d) };

	readingsArray.push(reading);
	// = [ { "summary" : "Test event", "begin" : new Date(), "end" : new Date() } ];

	readings = JSON.parse(localStorage.getItem("readings"));

	var bdate = date.getDate();
	var edate = date.getDate();
	var bd = date.getDate();
	var bm = date.getMonth();
	var by = date.getFullYear();
	var ed = date.getDate();
	var em = date.getMonth();
	var ey = date.getFullYear();

    for (i = 0; i < readings.length; i++) {

      reading = JSON.parse(readings[i]);

      bd = parseInt(reading.begin.substring(0, 4));
	  bm = parseInt(reading.begin.substring(5, 7));
	  by = parseInt(reading.begin.substring(8, 10));
	  ed = parseInt(reading.end.substring(0, 4));
	  em = parseInt(reading.end.substring(5, 7));
	  ey = parseInt(reading.end.substring(8, 10));

      readingsArray.push( { 'summary' : reading.summary, 'begin' : new Date(y, m, d), 'end' : new Date(y, m, d) } );

    }

    //alert(readings[readings.length - 1]);

}

// Create an array that will contain the events
var events = [];

$(function() {

	setProfile();
	setupCalendar();

	$('#profile_save').click( function() {

		// Store
		saveProfile();
		setProfile();
	});

	$('#reading_save').click( function() {
		//var today = new Date();
		//alert(today.getUTCMonth());
		var date = new Date();
		var d = date.getDate();
		var m = date.getMonth();
		var y = date.getFullYear();
		var type = $('#reading_type').val();
		var value = $('#reading_value').val();
		var units = '';

	   switch (type) {
		    case "Weight":
        		units = "lbs";
        		break;
		}

		date = new Date();
		d = date.getDate();
		m = date.getMonth();
 		y = date.getFullYear();

		reading = { "summary" : type + ":" + value + " " + units, "begin" : new Date(y, m, d), "end": new Date(y, m, d) };
		readingsArray.push(reading);
		$('#calendar').trigger('refresh');
		readings.push(JSON.stringify(reading));
		localStorage.setItem('readings', JSON.stringify(readings));
		//localStorage.setItem("readings", JSON.stringify(readingsArray));

		$('.ui-li-static').each(function() {
		//alert('decoding HTML');
    		$( this ).decHTML();
  			//alert($(this).html());
    	});

		$('#calendar .ui-btn').click(function() {
    	$('.ui-li-static').each(function() {
    		$( this ).decHTML();
  			//alert($(this).html());
    	});
    });

	});

	$('#craving_type').change( function() {

		var values = $(this).val();
		var arrayLength = values.length;
		$('#craving_tip').html('');

		for (var i = 0; i < arrayLength; i++) {

			switch (values[i]) {
			    case 'Bready':
			        $('#craving_tip').append('Sugary: Insecurity, soothes dissatisfaction.

');
        		break;
			    case 'Chewy':
			        $('#craving_tip').append('Chewy: Relieves Tension stress, slowdown so you can unwind.

');
		        break;
			    case 'Creamy':
			        $('#craving_tip').append('Creamy: Helps satisfy need to be nurtured and to receive comfort.

');
		        break;
			    case 'Crunchy':
			        $('#craving_tip').append('Crunchy: Helps release anxiety pressure.

');
		        break;
			    case 'Salty':
			        $('#craving_tip').append('Salty: Redirects anger, frustration and violence.

');
		        break;
			    case 'Sugary':
			        $('#craving_tip').append('Sugary: Substitutes for missing Love, affection ability to give and receive love.

');
		        break;
			}

    		//alert(myStringArray[i]);
    		//Do something
		}
		//var values = $(this).val().split(',');
		//alert('The first value in the array is ' + values[0]);
	});

	$('#journal_save').click( function() {
		//var today = new Date();
		//alert(today.getUTCMonth());
		var date = new Date();
		var d = date.getDate();
		var m = date.getMonth();
		var y = date.getFullYear();
		var mood = $('#journal_mood').val();
		var note = $('#journal_note').val();
		var icon = '';

	   switch (mood) {
		    case "Happy":
        		icon = "img/emoticons/PNG/icontexto-emoticons-03-032x032.png";
        		//alert(icon);
        		break;
        	case "Sad":
        		icon = "img/emoticons/PNG/icontexto-emoticons-13-032x032.png";
        		//alert(icon);
        		break;
        	case "Sick":
        		icon = "img/emoticons/PNG/icontexto-emoticons-11-032x032.png";
        		//alert(icon);
        		break;
		}

		date = new Date();
		d = date.getDate();
		m = date.getMonth();
 		y = date.getFullYear();

		reading = { 'summary' : mood + ' :' + note, 'begin' : new Date(y, m, d), 'end': new Date(y, m, d) };
		readingsArray.push(reading);
		$('#calendar').trigger('refresh');
		readings.push(JSON.stringify(reading));
		localStorage.setItem('readings', JSON.stringify(readings));
		//localStorage.setItem("readings", JSON.stringify(readingsArray));

		$('.ui-li-static').each(function() {
			//alert('decoding html');
    		$( this ).decHTML();
  			//alert($(this).html());
    	});

	});

	$('#calendar .ui-btn').click(function() {

    	$('.ui-li-static').each(function() {
    		$( this ).decHTML();
  			//alert($(this).html());
    	});
    });

});

$(document).on("pagecreate", function(){
    var opts = $("#journal_mood option");
    $( "#journal_mood-listbox-popup" ).on( "popupafteropen", function( event, ui ) {
        $("#journal_mood-menu li").each(function(index){
            if ($(this).find("img").length == 0){
                var imageURL = opts.eq(index).data("image");
                var imgElem = '';
                $(this).find("a").prepend(imgElem);
            }
        });
    });
});

function saveProfile() {
	//alert($('#profile_breakfast').val());
	localStorage.setItem("name", $('#profile_name').val());
	localStorage.setItem("age", $('#profile_age').val() + " years");
	localStorage.setItem("weight", $('#profile_weight').val());
	localStorage.setItem("breakfast", $('#profile_breakfast').val());
	localStorage.setItem("lunch", $('#profile_lunch').val());
	localStorage.setItem("dinner", $('#profile_dinner').val());
	localStorage.setItem("sugar", $('#profile_sugar').val());
	localStorage.setItem("sugar_fasting", $('#profile_sugar_fasting').val());
	calendar_events();

}

function setProfile() {

	//alert('Setting profile field');

	setProfilefield('name');
	setProfilefield('age');
	setProfilefield('breakfast');
	setProfilefield('lunch');
	setProfilefield('dinner');
	//setProfilefield('weight');
	//setProfilefield('sugar');
	//setProfilefield('sugar_fasting');

}

function setProfilefield(fieldName) {

	if (localStorage.getItem(fieldName) === null) {
		//alert('field IS empty');
		$('#profile' + fieldName).html('');
		//$('#profile_' + fieldName).val('');
	} else {
		//alert(fieldName + ' field is NOT empty');
		$('#profile' + fieldName).html(localStorage.getItem(fieldName));
		$('#profile_' + fieldName).val(localStorage.getItem(fieldName));
		//if ($('#profile_' + fieldName).attr('type') == 'range') {
			//$('#profile_' + fieldName).val(localStorage.getItem(fieldName)).slider('disabled', true).slider('refresh');
			//$('#profile_' + fieldName).val(localStorage.getItem(fieldName)).slider("refresh");
		//}
	}

}

function setupCalendar() {

	//alert(JSON.stringify(readingsArray[readingsArray.length - 1]));

    $("#calendar").jqmCalendar({
        events: readingsArray,
        months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
        days: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
        startOfWeek: 0
    });

    $('#calendar').trigger('refresh');

    //alert('setting up calendar');

    $('.ui-li-static').each(function() {
    	$( this ).decHTML();
  		//alert($(this).html());
    });

    $('#calendar .ui-btn').click(function() {
    	$('.ui-li-static').each(function() {
    		$( this ).decHTML();
  			//alert($(this).html());
    	});
    });
}

function createNotifications() {

	/* Set Break Hour in 24hr Notation */
	var breakHour=9;
	/* Set Break Minute */
	var breakMinute=5;
	/* Set Break Message */
	var breakMessage="Reports! Take Your Break!";

	var theDate=new Date();

	if (Math.abs(theDate.getHours())==breakHour&&Math.abs(theDate.getMinutes())==breakMinute) {
		this.focus();
		clearInterval(breakInt);
		alert(breakMessage);
	}

	var breakInt=setInterval("breakTime()",58000);

}

function calendar_events() {

  alert('adding calendar event');
  //alert($('#profile_lunch').val());

  var startDate = new Date();

  startDate.setMinutes(startDate.getMinutes() + 20);

  //startDate.setDate(startDate.getDate() + 1);
  ///startDate.setHours(parseInt($('#profile_lunch').val().substring(0, 2)));
  //startDate.setMinutes(parseInt($('#profile_lunch').val().substring(3, 5)));

  alert(startDate.toString());

  var endDate = startDate;
  endDate.setMinutes(endDate.getMinutes() + 80);
  var title = "Lunch Time";
  var location = "Unknown";
  var notes = 'Please enter your craving';
  var success = function(message) { alert("Success: " + JSON.stringify(message)); };
  var error = function(message) { alert("Error: " + message); };

  //var calOptions = window.plugins.calendar.getCalendarOptions();

  //calOptions.recurrence = "daily"; // supported are: daily, weekly, monthly, yearly
  //eventEnd = startDate;
  //eventEnd.setFullYear(startDate.getFullYear() + 1);
  //calOptions.recurrenceEndDate = eventEnd;

  //alert(startDate.toString());

  //  window.plugins.calendar.createCalendar(calendarName,success,error);
  window.plugins.calendar.createEvent(title,location,notes,startDate,endDate,success,error);

}

<commit_msg>add 1 to current date<commit_after>
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var readingsArray = [];
var readings = [];
var reading = {};

if (localStorage.getItem("readings") == null) {

	//alert('Reading Empty');

	//readingsArray = [ { 'summary' : 'Test event ', 'begin' : new Date(), 'end' : new Date() } ];

} else {

	//alert('Reading NOT Empty');

	//localStorage.removeItem('readings');

	reading = { 'summary' : 'Today', 'begin' : new Date(y, m, d), 'end' : new Date(y, m, d) };

	readingsArray.push(reading);
	// = [ { "summary" : "Test event", "begin" : new Date(), "end" : new Date() } ];

	readings = JSON.parse(localStorage.getItem("readings"));

	var bdate = date.getDate();
	var edate = date.getDate();
	var bd = date.getDate();
	var bm = date.getMonth();
	var by = date.getFullYear();
	var ed = date.getDate();
	var em = date.getMonth();
	var ey = date.getFullYear();

    for (i = 0; i < readings.length; i++) {

      reading = JSON.parse(readings[i]);

      bd = parseInt(reading.begin.substring(0, 4));
	  bm = parseInt(reading.begin.substring(5, 7));
	  by = parseInt(reading.begin.substring(8, 10));
	  ed = parseInt(reading.end.substring(0, 4));
	  em = parseInt(reading.end.substring(5, 7));
	  ey = parseInt(reading.end.substring(8, 10));

      readingsArray.push( { 'summary' : reading.summary, 'begin' : new Date(y, m, d), 'end' : new Date(y, m, d) } );

    }

    //alert(readings[readings.length - 1]);

}

// Create an array that will contain the events
var events = [];

$(function() {

	setProfile();
	setupCalendar();

	$('#profile_save').click( function() {

		// Store
		saveProfile();
		setProfile();
	});

	$('#reading_save').click( function() {
		//var today = new Date();
		//alert(today.getUTCMonth());
		var date = new Date();
		var d = date.getDate();
		var m = date.getMonth();
		var y = date.getFullYear();
		var type = $('#reading_type').val();
		var value = $('#reading_value').val();
		var units = '';

	   switch (type) {
		    case "Weight":
        		units = "lbs";
        		break;
		}

		date = new Date();
		d = date.getDate();
		m = date.getMonth();
 		y = date.getFullYear();

		reading = { "summary" : type + ":" + value + " " + units, "begin" : new Date(y, m, d), "end": new Date(y, m, d) };
		readingsArray.push(reading);
		$('#calendar').trigger('refresh');
		readings.push(JSON.stringify(reading));
		localStorage.setItem('readings', JSON.stringify(readings));
		//localStorage.setItem("readings", JSON.stringify(readingsArray));

		$('.ui-li-static').each(function() {
		//alert('decoding HTML');
    		$( this ).decHTML();
  			//alert($(this).html());
    	});

		$('#calendar .ui-btn').click(function() {
    	$('.ui-li-static').each(function() {
    		$( this ).decHTML();
  			//alert($(this).html());
    	});
    });

	});

	$('#craving_type').change( function() {

		var values = $(this).val();
		var arrayLength = values.length;
		$('#craving_tip').html('');

		for (var i = 0; i < arrayLength; i++) {

			switch (values[i]) {
			    case 'Bready':
			        $('#craving_tip').append('Sugary: Insecurity, soothes dissatisfaction.

');
        		break;
			    case 'Chewy':
			        $('#craving_tip').append('Chewy: Relieves Tension stress, slowdown so you can unwind.

');
		        break;
			    case 'Creamy':
			        $('#craving_tip').append('Creamy: Helps satisfy need to be nurtured and to receive comfort.

');
		        break;
			    case 'Crunchy':
			        $('#craving_tip').append('Crunchy: Helps release anxiety pressure.

');
		        break;
			    case 'Salty':
			        $('#craving_tip').append('Salty: Redirects anger, frustration and violence.

');
		        break;
			    case 'Sugary':
			        $('#craving_tip').append('Sugary: Substitutes for missing Love, affection ability to give and receive love.

');
		        break;
			}

    		//alert(myStringArray[i]);
    		//Do something
		}
		//var values = $(this).val().split(',');
		//alert('The first value in the array is ' + values[0]);
	});

	$('#journal_save').click( function() {
		//var today = new Date();
		//alert(today.getUTCMonth());
		var date = new Date();
		var d = date.getDate();
		var m = date.getMonth();
		var y = date.getFullYear();
		var mood = $('#journal_mood').val();
		var note = $('#journal_note').val();
		var icon = '';

	   switch (mood) {
		    case "Happy":
        		icon = "img/emoticons/PNG/icontexto-emoticons-03-032x032.png";
        		//alert(icon);
        		break;
        	case "Sad":
        		icon = "img/emoticons/PNG/icontexto-emoticons-13-032x032.png";
        		//alert(icon);
        		break;
        	case "Sick":
        		icon = "img/emoticons/PNG/icontexto-emoticons-11-032x032.png";
        		//alert(icon);
        		break;
		}

		date = new Date();
		d = date.getDate();
		m = date.getMonth();
 		y = date.getFullYear();

		reading = { 'summary' : mood + ' :' + note, 'begin' : new Date(y, m, d), 'end': new Date(y, m, d) };
		readingsArray.push(reading);
		$('#calendar').trigger('refresh');
		readings.push(JSON.stringify(reading));
		localStorage.setItem('readings', JSON.stringify(readings));
		//localStorage.setItem("readings", JSON.stringify(readingsArray));

		$('.ui-li-static').each(function() {
			//alert('decoding html');
    		$( this ).decHTML();
  			//alert($(this).html());
    	});

	});

	$('#calendar .ui-btn').click(function() {

    	$('.ui-li-static').each(function() {
    		$( this ).decHTML();
  			//alert($(this).html());
    	});
    });

});

$(document).on("pagecreate", function(){
    var opts = $("#journal_mood option");
    $( "#journal_mood-listbox-popup" ).on( "popupafteropen", function( event, ui ) {
        $("#journal_mood-menu li").each(function(index){
            if ($(this).find("img").length == 0){
                var imageURL = opts.eq(index).data("image");
                var imgElem = '';
                $(this).find("a").prepend(imgElem);
            }
        });
    });
});

function saveProfile() {
	//alert($('#profile_breakfast').val());
	localStorage.setItem("name", $('#profile_name').val());
	localStorage.setItem("age", $('#profile_age').val() + " years");
	localStorage.setItem("weight", $('#profile_weight').val());
	localStorage.setItem("breakfast", $('#profile_breakfast').val());
	localStorage.setItem("lunch", $('#profile_lunch').val());
	localStorage.setItem("dinner", $('#profile_dinner').val());
	localStorage.setItem("sugar", $('#profile_sugar').val());
	localStorage.setItem("sugar_fasting", $('#profile_sugar_fasting').val());
	calendar_events();

}

function setProfile() {

	//alert('Setting profile field');

	setProfilefield('name');
	setProfilefield('age');
	setProfilefield('breakfast');
	setProfilefield('lunch');
	setProfilefield('dinner');
	//setProfilefield('weight');
	//setProfilefield('sugar');
	//setProfilefield('sugar_fasting');

}

function setProfilefield(fieldName) {

	if (localStorage.getItem(fieldName) === null) {
		//alert('field IS empty');
		$('#profile' + fieldName).html('');
		//$('#profile_' + fieldName).val('');
	} else {
		//alert(fieldName + ' field is NOT empty');
		$('#profile' + fieldName).html(localStorage.getItem(fieldName));
		$('#profile_' + fieldName).val(localStorage.getItem(fieldName));
		//if ($('#profile_' + fieldName).attr('type') == 'range') {
			//$('#profile_' + fieldName).val(localStorage.getItem(fieldName)).slider('disabled', true).slider('refresh');
			//$('#profile_' + fieldName).val(localStorage.getItem(fieldName)).slider("refresh");
		//}
	}

}

function setupCalendar() {

	//alert(JSON.stringify(readingsArray[readingsArray.length - 1]));

    $("#calendar").jqmCalendar({
        events: readingsArray,
        months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
        days: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
        startOfWeek: 0
    });

    $('#calendar').trigger('refresh');

    //alert('setting up calendar');

    $('.ui-li-static').each(function() {
    	$( this ).decHTML();
  		//alert($(this).html());
    });

    $('#calendar .ui-btn').click(function() {
    	$('.ui-li-static').each(function() {
    		$( this ).decHTML();
  			//alert($(this).html());
    	});
    });
}

function createNotifications() {

	/* Set Break Hour in 24hr Notation */
	var breakHour=9;
	/* Set Break Minute */
	var breakMinute=5;
	/* Set Break Message */
	var breakMessage="Reports! Take Your Break!";

	var theDate=new Date();

	if (Math.abs(theDate.getHours())==breakHour&&Math.abs(theDate.getMinutes())==breakMinute) {
		this.focus();
		clearInterval(breakInt);
		alert(breakMessage);
	}

	var breakInt=setInterval("breakTime()",58000);

}

function calendar_events() {

  alert('adding calendar event');
  //alert($('#profile_lunch').val());

  var startDate = new Date();

  startDate.setMinutes(startDate.getMinutes() + 20);

  startDate.setDate(startDate.getDate() + 1);
  alert(parseInt(startDate.getDate()));
  ///startDate.setHours(parseInt($('#profile_lunch').val().substring(0, 2)));
  //startDate.setMinutes(parseInt($('#profile_lunch').val().substring(3, 5)));

  alert(startDate.toString());

  var endDate = startDate;
  endDate.setMinutes(endDate.getMinutes() + 80);
  var title = "Lunch Time";
  var location = "Unknown";
  var notes = 'Please enter your craving';
  var success = function(message) { alert("Success: " + JSON.stringify(message)); };
  var error = function(message) { alert("Error: " + message); };

  //var calOptions = window.plugins.calendar.getCalendarOptions();

  //calOptions.recurrence = "daily"; // supported are: daily, weekly, monthly, yearly
  //eventEnd = startDate;
  //eventEnd.setFullYear(startDate.getFullYear() + 1);
  //calOptions.recurrenceEndDate = eventEnd;

  //alert(startDate.toString());

  //  window.plugins.calendar.createCalendar(calendarName,success,error);
  window.plugins.calendar.createEvent(title,location,notes,startDate,endDate,success,error);

}

<|endoftext|>