<commit_before>'use strict';

(function (angular, buildfire, window) {
  angular.module('eventsManualPluginWidget')
    .controller('WidgetEventCtrl', ['$scope', 'DataStore', 'TAG_NAMES', 'LAYOUTS', '$routeParams', '$sce', '$rootScope', 'Buildfire', '$location', 'EventCache',
      function ($scope, DataStore, TAG_NAMES, LAYOUTS, $routeParams, $sce, $rootScope, Buildfire, $location, EventCache) {

        var WidgetEvent = this;
        WidgetEvent.data = {};
        WidgetEvent.event = {};
        var breadCrumbFlag = true;
        var currentListLayout = null;
        $rootScope.deviceHeight = window.innerHeight;
        $rootScope.deviceWidth = window.innerWidth || 320;
        $rootScope.backgroundImage="";
        buildfire.history.get('pluginBreadcrumbsOnly', function (err, result) {
          if(result && result.length) {
            result.forEach(function(breadCrumb) {
              if(breadCrumb.label == 'Event') {
                breadCrumbFlag = false;
              }
            });
          }
          if(breadCrumbFlag) {
            buildfire.history.push('Event', { elementToShow: 'Event' });
          }
        });

        //create new instance of buildfire carousel viewer
        WidgetEvent.view = null;

        var _searchObj = $location.search();

        if ($routeParams.id && !_searchObj.stopSwitch) {
          $rootScope.showFeed = false;
          buildfire.messaging.sendMessageToControl({
            id: $routeParams.id,
            type: 'OpenItem'
          });
        }

        WidgetEvent.listeners = {};
        WidgetEvent.getUTCZone = function () {
          //return moment(new Date()).utc().format("Z");
          return moment(new Date()).format("Z")
        };

        WidgetEvent.partOfTime = function (format, paramTime) {
          return moment(new Date(paramTime)).format(format);
        };

        var getEventDetails = function (url) {
          var success = function (result) {
              $rootScope.showFeed = false;
              WidgetEvent.event = result;
            }
            , error = function (err) {
              $rootScope.showFeed = false;
              console.error('Error In Fetching Event', err);
            };
          if ($routeParams.id) {
            if (EventCache.getCache()) {
              $rootScope.showFeed = false;
              WidgetEvent.event = EventCache.getCache();
            }
            else
              DataStore.getById($routeParams.id, TAG_NAMES.EVENTS_MANUAL).then(success, error);
          }
        };

        /*declare the device width heights*/
        WidgetEvent.deviceHeight = window.innerHeight;
        WidgetEvent.deviceWidth = window.innerWidth;

        /*initialize the device width heights*/
        var initDeviceSize = function (callback) {
          WidgetEvent.deviceHeight = window.innerHeight;
          WidgetEvent.deviceWidth = window.innerWidth;
          if (callback) {
            if (WidgetEvent.deviceWidth == 0 || WidgetEvent.deviceHeight == 0) {
              setTimeout(function () {
                initDeviceSize(callback);
              }, 500);
            } else {
              callback();
              if (!$scope.$$phase && !$scope.$root.$$phase) {
                $scope.$apply();
              }
            }
          }
        };

        /*crop image on the basis of width heights*/
        WidgetEvent.cropImage = function (url, settings) {
          var options = {};
          if (!url) {
            return "";
          }
          else {
            if (settings.height) {
              options.height = settings.height;
            }
            if (settings.width) {
              options.width = settings.width;
            }
            return Buildfire.imageLib.cropImage(url, options);
          }
        };

        WidgetEvent.safeHtml = function (html) {
          if (html)
            return $sce.trustAsHtml(html);
        };

        WidgetEvent.executeActionItem = function (actionItem) {
          buildfire.actionItems.execute(actionItem, function () {

          });
        };

        //Check is description is empty or not
        WidgetEvent.showDescription = function (description) {
          return !(description == '

');
        };

        WidgetEvent.setAddedEventToLocalStorage = function (eventId) {
          var addedEvents = [];
          addedEvents = JSON.parse(localStorage.getItem('localAddedEvents'));
          if (!addedEvents) {
            addedEvents = [];
          }
          addedEvents.push(eventId);
          localStorage.setItem('localAddedEvents', JSON.stringify(addedEvents));
        }

        WidgetEvent.getAddedEventToLocalStorage = function (eventId) {
          var localStorageSavedEvents = [];
          localStorageSavedEvents = JSON.parse(localStorage.getItem('localAddedEvents'));
          if (!localStorageSavedEvents) {
            localStorageSavedEvents = [];
          }
          return localStorageSavedEvents.indexOf(eventId);
        }

        WidgetEvent.addEventsToCalendar = function (event) {
          /*Add to calendar event will add here*/
          var eventStartDate = new Date(event.data.startDate);
          var eventEndDate;
          if (event.data.endDate !== '' && event.data.endDate < event.data.startDate) {
            eventEndDate = new Date(event.data.endDate);
          }
          else {
            eventEndDate = new Date(event.data.startDate + 3600);  //add hour to start date to derive end date
          }
          if (WidgetEvent.getAddedEventToLocalStorage(event.id) != -1) {
            alert("Event already added in calendar");
          }
          console.log("inCal3:", eventEndDate, event);
          if (buildfire.device && buildfire.device.calendar && WidgetEvent.getAddedEventToLocalStorage(event.id) == -1) {
            buildfire.device.calendar.addEvent(
              {
                title: event.data.title
                ,
                location: event.data.address.location
                ,
                notes: event.data.description
                ,
                startDate: new Date(eventStartDate.getFullYear(), eventStartDate.getMonth(), eventStartDate.getDate(), eventStartDate.getHours(), eventStartDate.getMinutes(), eventStartDate.getSeconds())
                ,
                endDate: new Date(eventEndDate.getFullYear(), eventEndDate.getMonth(), eventEndDate.getDate(), eventEndDate.getHours(), eventEndDate.getMinutes(), eventEndDate.getSeconds())
                ,
                options: {
                  firstReminderMinutes: 120
                  ,
                  secondReminderMinutes: 5
                  ,
                  recurrence: event.data.repeat.repeatType
                  ,
                  recurrenceEndDate: event.data.repeat.repeatType ? new Date(event.data.repeat.endOn) : new Date(2025, 6, 1, 0, 0, 0, 0, 0)
                }
              }
              ,
              function (err, result) {
                if (err)
                  console.log("******************" + err);
                else {
                  console.log('worked ' + JSON.stringify(result));
                  WidgetEvent.setAddedEventToLocalStorage(event.id);
                  alert("Event added to calendar");
                  $scope.$digest();
                }
              }
            );
          }
          console.log(">>>>>>>>", event);
        };

        /*update data on change event*/
        var onUpdateCallback = function (event) {
          setTimeout(function () {
            $scope.$digest();
            if (event && event.tag) {
              switch (event.tag) {
                case TAG_NAMES.EVENTS_MANUAL_INFO:
                  WidgetEvent.data = event.data;
                  if (!WidgetEvent.data.design)
                    WidgetEvent.data.design = {};
                  if (!WidgetEvent.data.design.itemDetailsLayout) {
                    WidgetEvent.data.design.itemDetailsLayout = LAYOUTS.itemDetailsLayout[0].name;
                  }
                  currentListLayout = WidgetEvent.data.design.itemDetailsLayout;
                  if(WidgetEvent.data.design.itemDetailsBgImage){
                    $rootScope.backgroundImage = WidgetEvent.data.design.itemDetailsBgImage;
                  }else
                  {
                    $rootScope.backgroundImage = "";
                  }
                  break;
                case TAG_NAMES.EVENTS_MANUAL:
                  WidgetEvent.event.data = event.data;
                  if (WidgetEvent.view) {
                    console.log("_____________________________");
                    WidgetEvent.view.loadItems(WidgetEvent.event.data.carouselImages, null, WidgetEvent.data.design.itemDetailsLayout == 'Event_Item_1' ? "WideScreen" : "Square");
                  }
                  break;
              }
              $scope.$digest();
              $rootScope.$digest();
            }
          }, 0);
        };

        /*
         * Fetch user's data from datastore
         */
        var init = function () {
          var success = function (result) {
              WidgetEvent.data = result.data;
              if (!WidgetEvent.data.design)
                WidgetEvent.data.design = {};
              if (!WidgetEvent.data.design.itemDetailsLayout) {
                WidgetEvent.data.design.itemDetailsLayout = LAYOUTS.itemDetailsLayout[0].name;
              }
              if(WidgetEvent.data.design.itemDetailsBgImage){
                $rootScope.backgroundImage = WidgetEvent.data.design.itemDetailsBgImage;
              }
              else
              {
                $rootScope.backgroundImage = "";
              }
              getEventDetails();
            }
            , error = function (err) {
              console.error('Error while getting data', err);
            };
          DataStore.get(TAG_NAMES.EVENTS_MANUAL_INFO).then(success, error);
        };

        init();

        DataStore.onUpdate().then(null, null, onUpdateCallback);

        WidgetEvent.listeners["Carousel:LOADED"] = $rootScope.$on("Carousel:LOADED", function () {
          WidgetEvent.view = new buildfire.components.carousel.view("#carousel", [], WidgetEvent.data.design.itemDetailsLayout == 'Event_Item_1' ? "WideScreen" : "Square");

          if (WidgetEvent.event.data && WidgetEvent.event.data.carouselImages) {
            WidgetEvent.view.loadItems(WidgetEvent.event.data.carouselImages, null, WidgetEvent.data.design.itemDetailsLayout == 'Event_Item_1' ? "WideScreen" : "Square");
          } else {
            WidgetEvent.view.loadItems([]);
          }
        });

        WidgetEvent.onAddressClick = function (long, lat) {
          buildfire.getContext(function (err, context) {
            if (context) {
              if (context.device && context.device.platform == 'ios')
                window.open("maps://maps.google.com/maps?daddr=" + lat + "," + long);
              else
                window.open("http://maps.google.com/maps?daddr=" + lat + "," + long);
            }
          });
        };
        buildfire.datastore.onRefresh(function () {

        });

        $scope.$on("$destroy", function () {
          DataStore.clearListener();
          $rootScope.$broadcast('ROUTE_CHANGED');
          for (var i in WidgetEvent.listeners) {
            if (WidgetEvent.listeners.hasOwnProperty(i)) {
              WidgetEvent.listeners[i]();
            }
          }
        });

      }]);
})(window.angular, window.buildfire, window);
<commit_msg>Fixed event to check variables.<commit_after>'use strict';

(function (angular, buildfire, window) {
  angular.module('eventsManualPluginWidget')
    .controller('WidgetEventCtrl', ['$scope', 'DataStore', 'TAG_NAMES', 'LAYOUTS', '$routeParams', '$sce', '$rootScope', 'Buildfire', '$location', 'EventCache',
      function ($scope, DataStore, TAG_NAMES, LAYOUTS, $routeParams, $sce, $rootScope, Buildfire, $location, EventCache) {

        var WidgetEvent = this;
        WidgetEvent.data = {};
        WidgetEvent.event = {};
        var breadCrumbFlag = true;
        var currentListLayout = null;
        $rootScope.deviceHeight = window.innerHeight;
        $rootScope.deviceWidth = window.innerWidth || 320;
        $rootScope.backgroundImage="";
        buildfire.history.get('pluginBreadcrumbsOnly', function (err, result) {
          if(result && result.length) {
            result.forEach(function(breadCrumb) {
              if(breadCrumb.label == 'Event') {
                breadCrumbFlag = false;
              }
            });
          }
          if(breadCrumbFlag) {
            buildfire.history.push('Event', { elementToShow: 'Event' });
          }
        });

        //create new instance of buildfire carousel viewer
        WidgetEvent.view = null;

        var _searchObj = $location.search();

        if ($routeParams.id && !_searchObj.stopSwitch) {
          $rootScope.showFeed = false;
          buildfire.messaging.sendMessageToControl({
            id: $routeParams.id,
            type: 'OpenItem'
          });
        }

        WidgetEvent.listeners = {};
        WidgetEvent.getUTCZone = function () {
          //return moment(new Date()).utc().format("Z");
          return moment(new Date()).format("Z")
        };

        WidgetEvent.partOfTime = function (format, paramTime) {
          return moment(new Date(paramTime)).format(format);
        };

        var getEventDetails = function (url) {
          var success = function (result) {
              $rootScope.showFeed = false;
              WidgetEvent.event = result;
            }
            , error = function (err) {
              $rootScope.showFeed = false;
              console.error('Error In Fetching Event', err);
            };
          if ($routeParams.id) {
            if (EventCache.getCache()) {
              $rootScope.showFeed = false;
              WidgetEvent.event = EventCache.getCache();
            }
            else
              DataStore.getById($routeParams.id, TAG_NAMES.EVENTS_MANUAL).then(success, error);
          }
        };

        /*declare the device width heights*/
        WidgetEvent.deviceHeight = window.innerHeight;
        WidgetEvent.deviceWidth = window.innerWidth;

        /*initialize the device width heights*/
        var initDeviceSize = function (callback) {
          WidgetEvent.deviceHeight = window.innerHeight;
          WidgetEvent.deviceWidth = window.innerWidth;
          if (callback) {
            if (WidgetEvent.deviceWidth == 0 || WidgetEvent.deviceHeight == 0) {
              setTimeout(function () {
                initDeviceSize(callback);
              }, 500);
            } else {
              callback();
              if (!$scope.$$phase && !$scope.$root.$$phase) {
                $scope.$apply();
              }
            }
          }
        };

        /*crop image on the basis of width heights*/
        WidgetEvent.cropImage = function (url, settings) {
          var options = {};
          if (!url) {
            return "";
          }
          else {
            if (settings.height) {
              options.height = settings.height;
            }
            if (settings.width) {
              options.width = settings.width;
            }
            return Buildfire.imageLib.cropImage(url, options);
          }
        };

        WidgetEvent.safeHtml = function (html) {
          if (html)
            return $sce.trustAsHtml(html);
        };

        WidgetEvent.executeActionItem = function (actionItem) {
          buildfire.actionItems.execute(actionItem, function () {

          });
        };

        //Check is description is empty or not
        WidgetEvent.showDescription = function (description) {
          return !(description == '

');
        };

        WidgetEvent.setAddedEventToLocalStorage = function (eventId) {
          var addedEvents = [];
          addedEvents = JSON.parse(localStorage.getItem('localAddedEvents'));
          if (!addedEvents) {
            addedEvents = [];
          }
          addedEvents.push(eventId);
          localStorage.setItem('localAddedEvents', JSON.stringify(addedEvents));
        }

        WidgetEvent.getAddedEventToLocalStorage = function (eventId) {
          var localStorageSavedEvents = [];
          localStorageSavedEvents = JSON.parse(localStorage.getItem('localAddedEvents'));
          if (!localStorageSavedEvents) {
            localStorageSavedEvents = [];
          }
          return localStorageSavedEvents.indexOf(eventId);
        }

        WidgetEvent.addEventsToCalendar = function (event) {
          /*Add to calendar event will add here*/
          var eventStartDate = new Date(event.data.startDate);
          var eventEndDate;
          if (event.data.endDate !== '' && event.data.endDate < event.data.startDate) {
            eventEndDate = new Date(event.data.endDate);
          }
          else {
            eventEndDate = new Date(event.data.startDate + 3600);  //add hour to start date to derive end date
          }
          if (WidgetEvent.getAddedEventToLocalStorage(event.id) != -1) {
            alert("Event already added in calendar");
          }
          console.log("inCal3:", eventEndDate, event);
          if (buildfire.device && buildfire.device.calendar && WidgetEvent.getAddedEventToLocalStorage(event.id) == -1) {
            var eventLocation, eventTitle, eventDescr, eventRepeatType, eventRepeatEndOn;
            if (event && event.data && event.data.address && event.data.address.location) {
              eventLocation = event.data.address.location;
            } else {
              eventLocation = "";
            }
            if (event && event.data) {
              if (event.data.title) {
                eventTitle = event.data.title;
              } else {
                eventTitle = "";
              }
              if (event.data.description) {
                eventDescr = event.data.description;
              } else {
                eventDescr = "";
              }
              if (event.data.repeat) {
                if (event.data.repeat.repeatType) {
                  eventRepeatType = event.data.repeat.repeatType;
                } else {
                  eventRepeatType = "";
                }
                if (event.data.repeat.endOn) {
                  eventRepeatEndOn = event.data.repeat.endOn;
                } else {
                  eventRepeatEndOn = "";
                }
              }
            }

            buildfire.device.calendar.addEvent(
              {
                title: eventTitle
                ,
                location: eventLocation
                ,
                notes: eventDescr
                ,
                startDate: new Date(eventStartDate.getFullYear(), eventStartDate.getMonth(), eventStartDate.getDate(), eventStartDate.getHours(), eventStartDate.getMinutes(), eventStartDate.getSeconds())
                ,
                endDate: new Date(eventEndDate.getFullYear(), eventEndDate.getMonth(), eventEndDate.getDate(), eventEndDate.getHours(), eventEndDate.getMinutes(), eventEndDate.getSeconds())
                ,
                options: {
                  firstReminderMinutes: 120
                  ,
                  secondReminderMinutes: 5
                  ,
                  recurrence: eventRepeatType
                  ,
                  recurrenceEndDate: eventRepeatType ? new Date(eventRepeatEndOn) : new Date(2025, 6, 1, 0, 0, 0, 0, 0)
                }
              }
              ,
              function (err, result) {
                if (err)
                  console.log("******************" + err);
                else {
                  console.log('worked ' + JSON.stringify(result));
                  WidgetEvent.setAddedEventToLocalStorage(event.id);
                  alert("Event added to calendar");
                  $scope.$digest();
                }
              }
            );
          }
          console.log(">>>>>>>>", event);
        };

        /*update data on change event*/
        var onUpdateCallback = function (event) {
          setTimeout(function () {
            $scope.$digest();
            if (event && event.tag) {
              switch (event.tag) {
                case TAG_NAMES.EVENTS_MANUAL_INFO:
                  WidgetEvent.data = event.data;
                  if (!WidgetEvent.data.design)
                    WidgetEvent.data.design = {};
                  if (!WidgetEvent.data.design.itemDetailsLayout) {
                    WidgetEvent.data.design.itemDetailsLayout = LAYOUTS.itemDetailsLayout[0].name;
                  }
                  currentListLayout = WidgetEvent.data.design.itemDetailsLayout;
                  if(WidgetEvent.data.design.itemDetailsBgImage){
                    $rootScope.backgroundImage = WidgetEvent.data.design.itemDetailsBgImage;
                  }else
                  {
                    $rootScope.backgroundImage = "";
                  }
                  break;
                case TAG_NAMES.EVENTS_MANUAL:
                  WidgetEvent.event.data = event.data;
                  if (WidgetEvent.view) {
                    console.log("_____________________________");
                    WidgetEvent.view.loadItems(WidgetEvent.event.data.carouselImages, null, WidgetEvent.data.design.itemDetailsLayout == 'Event_Item_1' ? "WideScreen" : "Square");
                  }
                  break;
              }
              $scope.$digest();
              $rootScope.$digest();
            }
          }, 0);
        };

        /*
         * Fetch user's data from datastore
         */
        var init = function () {
          var success = function (result) {
              WidgetEvent.data = result.data;
              if (!WidgetEvent.data.design)
                WidgetEvent.data.design = {};
              if (!WidgetEvent.data.design.itemDetailsLayout) {
                WidgetEvent.data.design.itemDetailsLayout = LAYOUTS.itemDetailsLayout[0].name;
              }
              if(WidgetEvent.data.design.itemDetailsBgImage){
                $rootScope.backgroundImage = WidgetEvent.data.design.itemDetailsBgImage;
              }
              else
              {
                $rootScope.backgroundImage = "";
              }
              getEventDetails();
            }
            , error = function (err) {
              console.error('Error while getting data', err);
            };
          DataStore.get(TAG_NAMES.EVENTS_MANUAL_INFO).then(success, error);
        };

        init();

        DataStore.onUpdate().then(null, null, onUpdateCallback);

        WidgetEvent.listeners["Carousel:LOADED"] = $rootScope.$on("Carousel:LOADED", function () {
          WidgetEvent.view = new buildfire.components.carousel.view("#carousel", [], WidgetEvent.data.design.itemDetailsLayout == 'Event_Item_1' ? "WideScreen" : "Square");

          if (WidgetEvent.event.data && WidgetEvent.event.data.carouselImages) {
            WidgetEvent.view.loadItems(WidgetEvent.event.data.carouselImages, null, WidgetEvent.data.design.itemDetailsLayout == 'Event_Item_1' ? "WideScreen" : "Square");
          } else {
            WidgetEvent.view.loadItems([]);
          }
        });

        WidgetEvent.onAddressClick = function (long, lat) {
          buildfire.getContext(function (err, context) {
            if (context) {
              if (context.device && context.device.platform == 'ios')
                window.open("maps://maps.google.com/maps?daddr=" + lat + "," + long);
              else
                window.open("http://maps.google.com/maps?daddr=" + lat + "," + long);
            }
          });
        };
        buildfire.datastore.onRefresh(function () {

        });

        $scope.$on("$destroy", function () {
          DataStore.clearListener();
          $rootScope.$broadcast('ROUTE_CHANGED');
          for (var i in WidgetEvent.listeners) {
            if (WidgetEvent.listeners.hasOwnProperty(i)) {
              WidgetEvent.listeners[i]();
            }
          }
        });

      }]);
})(window.angular, window.buildfire, window);
<|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.
*/
(function(){
    'use strict';
    /* global myApp */
    myApp.controller('ListCtrl', ['$location', 'notifier', '$scope', '$routeParams', '$q', 'AppsService', 'HarnessServer', function ($location, notifier, $scope, $routeParams, $q, AppsService, HarnessServer) {
        $scope.app = null;
        $scope.ipAddresses = null;
        $scope.port = null;

        function initialise() {
            $scope.$on('$destroy', function() {
                AppsService.onAppListChange = null;
            });
            $scope.port = 2424;
            AppsService.onAppListChange = loadAppsList;
            return loadAppsList()
            .then(function() {
                return HarnessServer.start();
            }).then(function() {
                return HarnessServer.getListenAddress()
                .then(function(value) {
                    $scope.ipAddresses = value.split(', ');
                });
            }, function() {
                $scope.ipAddresses = [];
            });
        }

        function loadAppsList() {
            return AppsService.getAppList()
            .then(function(){
                $scope.app = AppsService.getLastAccessedApp();
            }, function(error){
                notifier.error(error);
            });
        }

        $scope.launchApp = function(app, event){
            event.stopPropagation();
            return AppsService.launchApp(app)
            .then(null, function(error){
                notifier.error(error);
            });
        };

        $scope.removeApp = function(app, event) {
            event.stopPropagation();
            var shouldUninstall = confirm('Are you sure you want to uninstall ' + app.appId + '?');
            if(shouldUninstall) {
                return AppsService.uninstallApp(app)
                .then(null, function(error) {
                    notifier.error(error);
                });
            }
        };

        $scope.showDetails = function(index) {
            $location.path('/details/' + index);
        };

        return initialise();
    }]);
})();

<commit_msg>Replace 'uninstall app', with 'remove app', since we may have install concept some day<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.
*/
(function(){
    'use strict';
    /* global myApp */
    myApp.controller('ListCtrl', ['$location', 'notifier', '$scope', '$routeParams', '$q', 'AppsService', 'HarnessServer', function ($location, notifier, $scope, $routeParams, $q, AppsService, HarnessServer) {
        $scope.app = null;
        $scope.ipAddresses = null;
        $scope.port = null;

        function initialise() {
            $scope.$on('$destroy', function() {
                AppsService.onAppListChange = null;
            });
            $scope.port = 2424;
            AppsService.onAppListChange = loadAppsList;
            return loadAppsList()
            .then(function() {
                return HarnessServer.start();
            }).then(function() {
                return HarnessServer.getListenAddress()
                .then(function(value) {
                    $scope.ipAddresses = value.split(', ');
                });
            }, function() {
                $scope.ipAddresses = [];
            });
        }

        function loadAppsList() {
            return AppsService.getAppList()
            .then(function(){
                $scope.app = AppsService.getLastAccessedApp();
            }, function(error){
                notifier.error(error);
            });
        }

        $scope.launchApp = function(app, event){
            event.stopPropagation();
            return AppsService.launchApp(app)
            .then(null, function(error){
                notifier.error(error);
            });
        };

        $scope.removeApp = function(app, event) {
            event.stopPropagation();
            var shouldUninstall = confirm('Are you sure you want to remove ' + app.appId + '?');
            if(shouldUninstall) {
                return AppsService.uninstallApp(app)
                .then(null, function(error) {
                    notifier.error(error);
                });
            }
        };

        $scope.showDetails = function(index) {
            $location.path('/details/' + index);
        };

        return initialise();
    }]);
})();

<|endoftext|>


<commit_before>'use strict';

(function (angular, buildfire, window) {
  angular.module('couponPluginWidget')
    .controller('WidgetItemCtrl', ['$scope', 'DataStore', 'TAG_NAMES', 'LAYOUTS', '$sce', '$rootScope', 'Buildfire', 'ViewStack', 'UserData', 'PAGINATION', '$modal', '$timeout', '$location',
      function ($scope, DataStore, TAG_NAMES, LAYOUTS, $sce, $rootScope, Buildfire, ViewStack, UserData, PAGINATION, $modal, $timeout, $location) {
        var WidgetItem = this;
        $scope.showRedeemButton  =false;
        $scope.showItemRedeemed  =false;
        WidgetItem.listeners = {};

        var currentView = ViewStack.getCurrentView();

        if (currentView.params && currentView.params.itemId && !currentView.params.stopSwitch) {
          //Track Coupon Plugin Event
          buildfire.analytics.trackAction("coupon_item_view_" + currentView.params.itemId);
          //#
          buildfire.messaging.sendMessageToControl({
            id: currentView.params.itemId,
            type: 'OpenItem'
          });
        }

        buildfire.datastore.onRefresh(function () {
          // Do nothing
        });

        WidgetItem.getItemDetails = function (callback) {
          Buildfire.spinner.show();
          var success = function (result) {
              Buildfire.spinner.hide();
              WidgetItem.item = result;
            callback();
            }
            , error = function (err) {
              Buildfire.spinner.hide();
              console.error('Error In Fetching Event', err);
            };

          if (currentView.params && currentView.params.itemId) {
            DataStore.getById(currentView.params.itemId, TAG_NAMES.COUPON_ITEMS).then(success, error);
          }
        };

        WidgetItem.safeHtml = function (html) {
          if (html) {
            var $html = $('<div />', {html: html});
            $html.find('iframe').each(function (index, element) {
              var src = element.src;
              console.log('element is: ', src, src.indexOf('http'));
              src = src && src.indexOf('file://') != -1 ? src.replace('file://', 'http://') : src;
              element.src = src && src.indexOf('http') != -1 ? src : 'http:' + src;
            });
            return $sce.trustAsHtml($html.html());
          }
        };

        WidgetItem.openLinks = function (actionItems) {
          if (actionItems && actionItems.length) {
            var options = {};
            var callback = function (error, result) {
              if (error) {
                console.error('Error:', error);
              }
            };
            buildfire.actionItems.list(actionItems, options, callback);
          }
        };

        WidgetItem.onAddressClick = function (long, lat) {
          if (WidgetItem.device && WidgetItem.device.platform.toLowerCase() == 'ios')
            buildfire.navigation.openWindow("maps://maps.apple.com?q=" + lat + "," + long, '_system');
          else
            buildfire.navigation.openWindow("http://maps.google.com/maps?daddr=" + lat + "," + long, '_system');
        };

        /**
         * This event listener is bound for "Carousel:LOADED" event broadcast
         */
        WidgetItem.listeners["CarouselLoaded"] = $rootScope.$on("Carousel2:LOADED", function () {
          //  WidgetItem.view = null;
          if (WidgetItem.view)
            WidgetItem.view._destroySlider();
          if (!WidgetItem.view) {
            WidgetItem.view = new Buildfire.components.carousel.view("#carousel2", []);
          }
          if (WidgetItem.item.data && WidgetItem.item.data.carouselImages) {
            WidgetItem.view.loadItems(WidgetItem.item.data.carouselImages);
          } else {
            WidgetItem.view.loadItems([]);
          }
        });

        /**
         * Check for current logged in user, if not show ogin screen
         */
        buildfire.auth.getCurrentUser(function (err, user) {
          console.log("===========LoggedInUser", user);
          if (user) {
            WidgetItem.currentLoggedInUser = user;
          }
        });

        $scope.$on("$destroy", function () {
          for (var i in WidgetItem.listeners) {
            if (WidgetItem.listeners.hasOwnProperty(i)) {
              WidgetItem.listeners[i]();
            }
          }
          DataStore.clearListener();
        });

        WidgetItem.setSavedItem = function () {
          if (WidgetItem.item) {
            for (var save in WidgetItem.saved) {
              if (WidgetItem.saved[save].data.itemId == WidgetItem.item.id) {
                WidgetItem.item.isSaved = true;
                WidgetItem.item.savedId = WidgetItem.saved[save].id;
              }
            }
          }
        };

        WidgetItem.setRedeemedItem = function () {
          if (WidgetItem.item) {
            for (var redeem in WidgetItem.redeemed) {
              if (WidgetItem.redeemed[redeem].data.itemId == WidgetItem.item.id) {
                WidgetItem.item.isRedeemed = true;
                WidgetItem.item.redeemedOn = WidgetItem.redeemed[redeem].data.redeemedOn;
              }
            }
          }
        };

        WidgetItem.getSavedItems = function () {
          Buildfire.spinner.show();
          var err = function (error) {
            Buildfire.spinner.hide();
            console.log("============ There is an error in getting saved items data", error);
          }, result = function (result) {
            Buildfire.spinner.hide();
            WidgetItem.saved = result;
            WidgetItem.setSavedItem();
          };
          UserData.search({}, TAG_NAMES.COUPON_SAVED).then(result, err);
        };

        WidgetItem.getRedeemedCoupons = function () {
          Buildfire.spinner.show();
          var err = function (error) {
            Buildfire.spinner.hide();
            console.log("============ There is an error in getting redeemed coupons data", error);
          }, result = function (result) {
            Buildfire.spinner.hide();
            WidgetItem.redeemed = result;
            WidgetItem.setRedeemedItem();
            $scope.enableRedeemButton();
          };
          UserData.search({}, TAG_NAMES.COUPON_REDEEMED).then(result, err);
        };

        WidgetItem.addToSaved = function (item, isSaved, onlyAdd) {
          Buildfire.spinner.show();
          if (isSaved && item.savedId && !onlyAdd) {
            var successRemove = function (result) {
              Buildfire.spinner.hide();
              WidgetItem.item.isSaved = false;
              WidgetItem.item.savedId = null;
              if (!$scope.$$phase)
                $scope.$digest();
              var removeSavedModal = $modal.open({
                templateUrl: 'templates/Saved_Removed.html',
                size: 'sm',
                backdropClass: "ng-hide"
              });
              $timeout(function () {
                removeSavedModal.close();
              }, 3000);
              $rootScope.$broadcast("ITEM_SAVED_UPDATED");

            }, errorRemove = function () {
              Buildfire.spinner.hide();
              return console.error('There was a problem removing your data');
            };
            UserData.delete(item.savedId, TAG_NAMES.COUPON_SAVED, WidgetItem.currentLoggedInUser._id).then(successRemove, errorRemove)
          } else {
            WidgetItem.savedItem = {
              data: {
                itemId: item.id
              }
            };
            var successItem = function (result) {
              Buildfire.spinner.hide();
              WidgetItem.item.isSaved = true;
              WidgetItem.item.savedId = result.id;
              console.log("Inserted", result);
              var addedSavedModal = $modal.open({
                templateUrl: 'templates/Saved_Confirmation.html',
                size: 'sm',
                backdropClass: "ng-hide"
              });
              $timeout(function () {
                addedSavedModal.close();
              }, 3000);
              $rootScope.$broadcast("ITEM_SAVED_UPDATED");
            }, errorItem = function () {
              Buildfire.spinner.hide();
              return console.error('There was a problem saving your data');
            };
            UserData.insert(WidgetItem.savedItem.data, TAG_NAMES.COUPON_SAVED).then(successItem, errorItem);
          }
        };

        var loginCallback = function () {
          buildfire.auth.getCurrentUser(function (err, user) {
            if (user) {
              WidgetItem.currentLoggedInUser = user;
              $scope.$apply();
              WidgetItem.getSavedItems();
              WidgetItem.getRedeemedCoupons();
            }
          });
        };

        buildfire.auth.onLogin(loginCallback);

        var logoutCallback = function () {
          WidgetItem.currentLoggedInUser = null;
          $scope.$apply();
        };

        buildfire.auth.onLogout(logoutCallback);

        WidgetItem.redeemCoupon = function(item){
          if(WidgetItem.currentLoggedInUser){
            WidgetItem.redeemedItem = {
              data: {
                itemId: item.id,
                redeemedOn: +new Date()
              }
            };
            var successItem = function (result) {
              Buildfire.spinner.hide();
              WidgetItem.item.isRedeemed = true;
              WidgetItem.item.redeemedOn = result.data.redeemedOn;
              $scope.enableRedeemButton();
              var redeemedModal = $modal.open({
                templateUrl: 'templates/Redeem_Confirmation.html',
                size: 'sm',
                backdropClass: "ng-hide"
              });
              WidgetItem.addToSaved(WidgetItem.item, WidgetItem.item.isSaved, true);
              $timeout(function () {
                redeemedModal.close();
              }, 2000);
            }, errorItem = function () {
              Buildfire.spinner.hide();
              return console.error('There was a problem redeeming the coupon');
            };
            UserData.insert(WidgetItem.redeemedItem.data, TAG_NAMES.COUPON_REDEEMED).then(successItem, errorItem);

          }else{
            buildfire.auth.login({}, function () {

            });
          }
        };

        var onUpdateCallback = function (event) {
          setTimeout(function () {
            $scope.$digest();
            if (event && event.tag) {
              console.log("_____________________________", event);
              switch (event.tag) {
                case TAG_NAMES.COUPON_INFO:
                  WidgetItem.data = event.data;
                  if (!WidgetItem.data.design)
                    WidgetItem.data.design = {};
                  if (!WidgetItem.data.settings)
                    WidgetItem.data.settings = {};
                  break;
                case TAG_NAMES.COUPON_ITEMS:
                  if (event.data) {
                    WidgetItem.item.data = event.data;
                    if (WidgetItem.view) {
                      WidgetItem.view.loadItems(WidgetItem.item.data.carouselImages);
                    }
                  }
                  break;
              }
              $scope.$digest();
            }
          }, 500);
        };

        DataStore.onUpdate("item").then(null, null, onUpdateCallback);

        /*
         * Fetch user's data from datastore
         */
        var init = function () {
          Buildfire.spinner.show();
          var success = function (result) {
              Buildfire.spinner.hide();
              WidgetItem.data = result.data;
              if (!WidgetItem.data.design)
                WidgetItem.data.design = {};
              WidgetItem.getItemDetails(function() {
                var getDevice = function (error, data) {
                  if (data)
                    WidgetItem.device = data.device;
                  else
                    console.log("Error while getting the device context data", error)
                };
                buildfire.getContext(getDevice);
                if (WidgetItem.currentLoggedInUser) {
                  WidgetItem.getSavedItems();
                  WidgetItem.getRedeemedCoupons();
                }
                else {
                  buildfire.auth.getCurrentUser(function (err, user) {
                    if (user) {
                      WidgetItem.currentLoggedInUser = user;
                      $scope.$apply();
                      WidgetItem.getSavedItems();
                      WidgetItem.getRedeemedCoupons();
                    }else
                      $scope.enableRedeemButton();//to enable the button when the user not logged in
                  });
                }
              });
            }
            , error = function (err) {
              Buildfire.spinner.hide();
              console.error('Error while getting data', err);
            };
          DataStore.get(TAG_NAMES.COUPON_INFO).then(success, error);
        };

        $scope.$on("$destroy", function() {

          for(var i in WidgetItem.listeners) {
            if(WidgetItem.listeners.hasOwnProperty(i)) {
              WidgetItem.listeners[i]();
            }
          }
          DataStore.clearListener("item");

        });

        $scope.enableRedeemButton=function(){
          $scope.getRedeemedDateText();
          if(WidgetItem.item && WidgetItem.item.isRedeemed) {
            if (WidgetItem.item.data.reuseAfterInMinutes &&WidgetItem.item.data.reuseAfterInMinutes!=-1 && WidgetItem.item.redeemedOn) {
                var redeemedOn = new Date(WidgetItem.item.redeemedOn);
                var resetDate = new Date(redeemedOn);
                resetDate.setMinutes (redeemedOn.getMinutes() + WidgetItem.item.data.reuseAfterInMinutes);
                $scope.showRedeemButton= new Date().getTime() > resetDate.getTime();
              $scope.showItemRedeemed=!$scope.showRedeemButton;
            }
            else {
              $scope.showRedeemButton = false;
              $scope.showItemRedeemed = !$scope.showRedeemButton;

            }
          }
          else {
            $scope.showRedeemButton = true;
            $scope.showItemRedeemed = !$scope.showRedeemButton;
            if (!$scope.$$phase) $scope.$apply();
          }
        };
        $scope.getRedeemedDateText=function(){
          var redeemedDate = new Date(WidgetItem.item.redeemedOn);
          $scope.redeemedDateText =redeemedDate.toDateString() +" at "+redeemedDate.getHours()+":"+redeemedDate.getMinutes();
        };
        init();
      }]);
})(window.angular, window.buildfire, window);
<commit_msg>fix: remove item saved modal<commit_after>'use strict';

(function (angular, buildfire, window) {
  angular.module('couponPluginWidget')
    .controller('WidgetItemCtrl', ['$scope', 'DataStore', 'TAG_NAMES', 'LAYOUTS', '$sce', '$rootScope', 'Buildfire', 'ViewStack', 'UserData', 'PAGINATION', '$modal', '$timeout', '$location',
      function ($scope, DataStore, TAG_NAMES, LAYOUTS, $sce, $rootScope, Buildfire, ViewStack, UserData, PAGINATION, $modal, $timeout, $location) {
        var WidgetItem = this;
        $scope.showRedeemButton  =false;
        $scope.showItemRedeemed  =false;
        WidgetItem.listeners = {};

        var currentView = ViewStack.getCurrentView();

        if (currentView.params && currentView.params.itemId && !currentView.params.stopSwitch) {
          //Track Coupon Plugin Event
          buildfire.analytics.trackAction("coupon_item_view_" + currentView.params.itemId);
          //#
          buildfire.messaging.sendMessageToControl({
            id: currentView.params.itemId,
            type: 'OpenItem'
          });
        }

        buildfire.datastore.onRefresh(function () {
          // Do nothing
        });

        WidgetItem.getItemDetails = function (callback) {
          Buildfire.spinner.show();
          var success = function (result) {
              Buildfire.spinner.hide();
              WidgetItem.item = result;
            callback();
            }
            , error = function (err) {
              Buildfire.spinner.hide();
              console.error('Error In Fetching Event', err);
            };

          if (currentView.params && currentView.params.itemId) {
            DataStore.getById(currentView.params.itemId, TAG_NAMES.COUPON_ITEMS).then(success, error);
          }
        };

        WidgetItem.safeHtml = function (html) {
          if (html) {
            var $html = $('<div />', {html: html});
            $html.find('iframe').each(function (index, element) {
              var src = element.src;
              console.log('element is: ', src, src.indexOf('http'));
              src = src && src.indexOf('file://') != -1 ? src.replace('file://', 'http://') : src;
              element.src = src && src.indexOf('http') != -1 ? src : 'http:' + src;
            });
            return $sce.trustAsHtml($html.html());
          }
        };

        WidgetItem.openLinks = function (actionItems) {
          if (actionItems && actionItems.length) {
            var options = {};
            var callback = function (error, result) {
              if (error) {
                console.error('Error:', error);
              }
            };
            buildfire.actionItems.list(actionItems, options, callback);
          }
        };

        WidgetItem.onAddressClick = function (long, lat) {
          if (WidgetItem.device && WidgetItem.device.platform.toLowerCase() == 'ios')
            buildfire.navigation.openWindow("maps://maps.apple.com?q=" + lat + "," + long, '_system');
          else
            buildfire.navigation.openWindow("http://maps.google.com/maps?daddr=" + lat + "," + long, '_system');
        };

        /**
         * This event listener is bound for "Carousel:LOADED" event broadcast
         */
        WidgetItem.listeners["CarouselLoaded"] = $rootScope.$on("Carousel2:LOADED", function () {
          //  WidgetItem.view = null;
          if (WidgetItem.view)
            WidgetItem.view._destroySlider();
          if (!WidgetItem.view) {
            WidgetItem.view = new Buildfire.components.carousel.view("#carousel2", []);
          }
          if (WidgetItem.item.data && WidgetItem.item.data.carouselImages) {
            WidgetItem.view.loadItems(WidgetItem.item.data.carouselImages);
          } else {
            WidgetItem.view.loadItems([]);
          }
        });

        /**
         * Check for current logged in user, if not show ogin screen
         */
        buildfire.auth.getCurrentUser(function (err, user) {
          console.log("===========LoggedInUser", user);
          if (user) {
            WidgetItem.currentLoggedInUser = user;
          }
        });

        $scope.$on("$destroy", function () {
          for (var i in WidgetItem.listeners) {
            if (WidgetItem.listeners.hasOwnProperty(i)) {
              WidgetItem.listeners[i]();
            }
          }
          DataStore.clearListener();
        });

        WidgetItem.setSavedItem = function () {
          if (WidgetItem.item) {
            for (var save in WidgetItem.saved) {
              if (WidgetItem.saved[save].data.itemId == WidgetItem.item.id) {
                WidgetItem.item.isSaved = true;
                WidgetItem.item.savedId = WidgetItem.saved[save].id;
              }
            }
          }
        };

        WidgetItem.setRedeemedItem = function () {
          if (WidgetItem.item) {
            for (var redeem in WidgetItem.redeemed) {
              if (WidgetItem.redeemed[redeem].data.itemId == WidgetItem.item.id) {
                WidgetItem.item.isRedeemed = true;
                WidgetItem.item.redeemedOn = WidgetItem.redeemed[redeem].data.redeemedOn;
              }
            }
          }
        };

        WidgetItem.getSavedItems = function () {
          Buildfire.spinner.show();
          var err = function (error) {
            Buildfire.spinner.hide();
            console.log("============ There is an error in getting saved items data", error);
          }, result = function (result) {
            Buildfire.spinner.hide();
            WidgetItem.saved = result;
            WidgetItem.setSavedItem();
          };
          UserData.search({}, TAG_NAMES.COUPON_SAVED).then(result, err);
        };

        WidgetItem.getRedeemedCoupons = function () {
          Buildfire.spinner.show();
          var err = function (error) {
            Buildfire.spinner.hide();
            console.log("============ There is an error in getting redeemed coupons data", error);
          }, result = function (result) {
            Buildfire.spinner.hide();
            WidgetItem.redeemed = result;
            WidgetItem.setRedeemedItem();
            $scope.enableRedeemButton();
          };
          UserData.search({}, TAG_NAMES.COUPON_REDEEMED).then(result, err);
        };

        WidgetItem.addToSaved = function (item, isSaved, onlyAdd) {
          Buildfire.spinner.show();
          if (isSaved && item.savedId && !onlyAdd) {
            var successRemove = function (result) {
              Buildfire.spinner.hide();
              WidgetItem.item.isSaved = false;
              WidgetItem.item.savedId = null;
              if (!$scope.$$phase)
                $scope.$digest();
              var removeSavedModal = $modal.open({
                templateUrl: 'templates/Saved_Removed.html',
                size: 'sm',
                backdropClass: "ng-hide"
              });
              $timeout(function () {
                removeSavedModal.close();
              }, 3000);
              $rootScope.$broadcast("ITEM_SAVED_UPDATED");

            }, errorRemove = function () {
              Buildfire.spinner.hide();
              return console.error('There was a problem removing your data');
            };
            UserData.delete(item.savedId, TAG_NAMES.COUPON_SAVED, WidgetItem.currentLoggedInUser._id).then(successRemove, errorRemove)
          } else {
            WidgetItem.savedItem = {
              data: {
                itemId: item.id
              }
            };
            var successItem = function (result) {
              Buildfire.spinner.hide();
              WidgetItem.item.isSaved = true;
              WidgetItem.item.savedId = result.id;
              console.log("Inserted", result);
              $rootScope.$broadcast("ITEM_SAVED_UPDATED");
            }, errorItem = function () {
              Buildfire.spinner.hide();
              return console.error('There was a problem saving your data');
            };
            UserData.insert(WidgetItem.savedItem.data, TAG_NAMES.COUPON_SAVED).then(successItem, errorItem);
          }
        };

        var loginCallback = function () {
          buildfire.auth.getCurrentUser(function (err, user) {
            if (user) {
              WidgetItem.currentLoggedInUser = user;
              $scope.$apply();
              WidgetItem.getSavedItems();
              WidgetItem.getRedeemedCoupons();
            }
          });
        };

        buildfire.auth.onLogin(loginCallback);

        var logoutCallback = function () {
          WidgetItem.currentLoggedInUser = null;
          $scope.$apply();
        };

        buildfire.auth.onLogout(logoutCallback);

        WidgetItem.redeemCoupon = function(item){
          if(WidgetItem.currentLoggedInUser){
            WidgetItem.redeemedItem = {
              data: {
                itemId: item.id,
                redeemedOn: +new Date()
              }
            };
            var successItem = function (result) {
              Buildfire.spinner.hide();
              WidgetItem.item.isRedeemed = true;
              WidgetItem.item.redeemedOn = result.data.redeemedOn;
              $scope.enableRedeemButton();
              var redeemedModal = $modal.open({
                templateUrl: 'templates/Redeem_Confirmation.html',
                size: 'sm',
                backdropClass: "ng-hide"
              });
              WidgetItem.addToSaved(WidgetItem.item, WidgetItem.item.isSaved, true);
              $timeout(function () {
                redeemedModal.close();
              }, 2000);
            }, errorItem = function () {
              Buildfire.spinner.hide();
              return console.error('There was a problem redeeming the coupon');
            };
            UserData.insert(WidgetItem.redeemedItem.data, TAG_NAMES.COUPON_REDEEMED).then(successItem, errorItem);

          }else{
            buildfire.auth.login({}, function () {

            });
          }
        };

        var onUpdateCallback = function (event) {
          setTimeout(function () {
            $scope.$digest();
            if (event && event.tag) {
              console.log("_____________________________", event);
              switch (event.tag) {
                case TAG_NAMES.COUPON_INFO:
                  WidgetItem.data = event.data;
                  if (!WidgetItem.data.design)
                    WidgetItem.data.design = {};
                  if (!WidgetItem.data.settings)
                    WidgetItem.data.settings = {};
                  break;
                case TAG_NAMES.COUPON_ITEMS:
                  if (event.data) {
                    WidgetItem.item.data = event.data;
                    if (WidgetItem.view) {
                      WidgetItem.view.loadItems(WidgetItem.item.data.carouselImages);
                    }
                  }
                  break;
              }
              $scope.$digest();
            }
          }, 500);
        };

        DataStore.onUpdate("item").then(null, null, onUpdateCallback);

        /*
         * Fetch user's data from datastore
         */
        var init = function () {
          Buildfire.spinner.show();
          var success = function (result) {
              Buildfire.spinner.hide();
              WidgetItem.data = result.data;
              if (!WidgetItem.data.design)
                WidgetItem.data.design = {};
              WidgetItem.getItemDetails(function() {
                var getDevice = function (error, data) {
                  if (data)
                    WidgetItem.device = data.device;
                  else
                    console.log("Error while getting the device context data", error)
                };
                buildfire.getContext(getDevice);
                if (WidgetItem.currentLoggedInUser) {
                  WidgetItem.getSavedItems();
                  WidgetItem.getRedeemedCoupons();
                }
                else {
                  buildfire.auth.getCurrentUser(function (err, user) {
                    if (user) {
                      WidgetItem.currentLoggedInUser = user;
                      $scope.$apply();
                      WidgetItem.getSavedItems();
                      WidgetItem.getRedeemedCoupons();
                    }else
                      $scope.enableRedeemButton();//to enable the button when the user not logged in
                  });
                }
              });
            }
            , error = function (err) {
              Buildfire.spinner.hide();
              console.error('Error while getting data', err);
            };
          DataStore.get(TAG_NAMES.COUPON_INFO).then(success, error);
        };

        $scope.$on("$destroy", function() {

          for(var i in WidgetItem.listeners) {
            if(WidgetItem.listeners.hasOwnProperty(i)) {
              WidgetItem.listeners[i]();
            }
          }
          DataStore.clearListener("item");

        });

        $scope.enableRedeemButton=function(){
          $scope.getRedeemedDateText();
          if(WidgetItem.item && WidgetItem.item.isRedeemed) {
            if (WidgetItem.item.data.reuseAfterInMinutes &&WidgetItem.item.data.reuseAfterInMinutes!=-1 && WidgetItem.item.redeemedOn) {
                var redeemedOn = new Date(WidgetItem.item.redeemedOn);
                var resetDate = new Date(redeemedOn);
                resetDate.setMinutes (redeemedOn.getMinutes() + WidgetItem.item.data.reuseAfterInMinutes);
                $scope.showRedeemButton= new Date().getTime() > resetDate.getTime();
              $scope.showItemRedeemed=!$scope.showRedeemButton;
            }
            else {
              $scope.showRedeemButton = false;
              $scope.showItemRedeemed = !$scope.showRedeemButton;

            }
          }
          else {
            $scope.showRedeemButton = true;
            $scope.showItemRedeemed = !$scope.showRedeemButton;
            if (!$scope.$$phase) $scope.$apply();
          }
        };
        $scope.getRedeemedDateText=function(){
          var redeemedDate = new Date(WidgetItem.item.redeemedOn);
          $scope.redeemedDateText =redeemedDate.toDateString() +" at "+redeemedDate.getHours()+":"+redeemedDate.getMinutes();
        };
        init();
      }]);
})(window.angular, window.buildfire, window);
<|endoftext|>


<commit_before>// Copyright (c) 2011 Hewlett-Packard Development Company, L.P. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Build and fly through a 3D world using Three.js

var WebVfx = WebVfx || {};

WebVfx.ThreeWorld = function (width, height, nearPlane, farPlane, animationData, readyCallback, scene) {
    var self = this;

    this.tracker = new WebVfx.Tracker(function () {
        readyCallback();
        delete self.tracker;
    });

    var aspect = width / height;
    this.camera = new WebVfx.AnimatedCamera(aspect, nearPlane, farPlane,
                                            animationData);
    this.scene = scene ? scene : new THREE.Scene();
    this.scene.add(this.camera);

    this.widescreen = aspect > (4 / 3);

    // Create and size canvas ourself, more efficient to size it up front
    var canvas = document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;
    this.renderer = new THREE.WebGLRenderer({ canvas: canvas,
                                              antialias: true });
    // Need to enable this for our shader
    if (!this.renderer.context.getExtension("OES_standard_derivatives"))
        console.log("OES_standard_derivatives not supported");
    this.renderer.setViewport(0, 0, width, height);
    document.body.appendChild(canvas);

    // Treat page load as trackable
    if (document.readyState != "complete") {
        this.tracker.increment();
        window.addEventListener('load', function (event) {
            self.tracker.decrement();
        }, false);
    }
};

WebVfx.ThreeWorld.prototype = {
    // Must be called to start resource tracking
    startTracking: function () {
        this.tracker.start();
    },

    // Optional _callback_ will be passed the Mesh for additional configuring
    addJSONModel: function (url, material, callback) {
        var self = this;
        if (!this.jsonLoader)
            this.jsonLoader = new THREE.JSONLoader();
        this.tracker.increment();
        this.jsonLoader.load(url, function (geometry) {
            var mesh = new THREE.Mesh(geometry, material);
            if (callback)
                callback(mesh);
            self.scene.add(mesh);
            self.tracker.decrement();
        });
    },

    resize: function (width, height) {
        this.renderer.setSize(width, height);
        this.camera.aspect = width / height;
        this.camera.updateProjectionMatrix();
        this.widescreen = this.camera.aspect > (4 / 3);
    },

    render: function (time) {
        this.camera.setAnimationTime(time);
        this.renderer.render(this.scene, this.camera);
    }
};

///////////

WebVfx.loadImageTexture = function (url, tracker) {
    var image = new Image();
    var texture = new THREE.Texture(image);
    WebVfx.trackTextureImage(texture, tracker);
    image.src = url;
    return texture;
};

WebVfx.trackTextureImage = function (texture, tracker) {
    var image = texture.image;
    if (!(image instanceof Image) || image.complete) {
        texture.needsUpdate = true;
        return;
    }
    tracker.increment();
    image.addEventListener("load", function () {
        texture.needsUpdate = true;
        tracker.decrement();
    });
};

///////////

// _options_ includes:
// fontStyle - e.g. "30px Helvetica". If it uses a font loaded with @font-face,
//   then you must use a WebVfx.FontTracker and create the text Texture after
//   the font has loaded.
// textColor - Text color css spec.
// backgroundColor - Background color css spec.
// textAlign - "left", "right" or "center".
// textBaseline - "top", "middle" or "bottom"
// margin - array of [left-right, top-bottom] margins
WebVfx.createTextTexture = function (text, targetWidth, targetHeight, options) {
    var fontStyle = options.fontStyle;
    var textColor = options.textColor;
    var backgroundColor = options.backgroundColor;
    var textAlign = options.textAlign;
    var textBaseline = options.textBaseline;

    // Canvas context provides measureText(), but this only exposes width.
    // So apply same font style to span and measure it.
    // FYI span text looks much better than canvas text because span uses
    // subpixel antialiasing
    var span = document.createElement("span");
    span.style.visibility = "hidden";
    span.style.font = fontStyle;
    span.textContent = text;
    document.body.appendChild(span);
    var textWidth = span.offsetWidth;
    var textHeight = span.offsetHeight;
    document.body.removeChild(span);

    var boxWidth = targetWidth;
    var boxHeight = targetHeight;
    if (options.margin) {
        var margin = options.margin;
        boxWidth -= 2 * margin[0];
        boxHeight -= 2 * margin[1];
    }
    var scale = Math.min(boxWidth / textWidth, boxHeight / textHeight);

    var canvas = document.createElement("canvas");
    canvas.width = targetWidth;
    canvas.height = targetHeight;

    var context = canvas.getContext("2d");
    if (backgroundColor) {
        context.fillStyle = backgroundColor;
        context.fillRect(0, 0, targetWidth, targetHeight);
    }
    // Scale text to fit if too large
    var positionScale = 1;
    if (scale < 1) {
        context.scale(scale, scale);
        positionScale = 1 / scale;
    }
    context.font = fontStyle;
    context.fillStyle = textColor;

    var x = 0, y = 0;

    switch (textAlign) {
    case "right":
        x = targetWidth;
        break;
    case "center":
        x = targetWidth / 2;
        break;
    case "left":
    default:
        textAlign = "left";
        break;
    }
    context.textAlign = textAlign;

    switch (textBaseline) {
    case "middle":
        y = targetHeight / 2;
        break;
    case "bottom":
        y = targetHeight;
        break;
    case "top":
    default:
        textBaseline = "top";
        break;
    }
    context.textBaseline = textBaseline;

    context.fillText(text, x * positionScale, y * positionScale);

    var texture = new THREE.Texture(canvas);
    texture.needsUpdate = true;
    return texture;
}

///////////

WebVfx.updateVideoTexture = function (texture, name) {
    texture.image = webvfx.getImage(name).toImageData();
    texture.needsUpdate = true;
};

// v offset in uv space for top bottom to render 16:9 image in 4:3 mesh.
// 16:12 (4:3) vs 16:9, 12-9=3/2=1.5 so 1.5/9 is offset for top and bottom
WebVfx.vClampOffset = 1.5/9;

///////////

// Set UV coords for given layer, for a single quad
WebVfx.setQuadUvs = function (mesh, layer, u1, v1, u2, v2, u3, v3, u4, v4) {
    var uvs = [new THREE.UV(u1, v1),
               new THREE.UV(u2, v2),
               new THREE.UV(u3, v3),
               new THREE.UV(u4, v4)];
    mesh.geometry.faceVertexUvs[layer] = [uvs];
}

// Map (scale/translate) UVs from _fromLayer_ to _toLayer_
// min/max specifies new UV coordinate space range.
WebVfx.mapUvs = function (mesh, fromLayer, toLayer, minU, minV, maxU, maxV) {
    var uvs = mesh.geometry.faceVertexUvs[fromLayer];
    var length = uvs.length;

    // Find UV space we are mapping from
    var fromMinU = Number.MAX_VALUE;
    var fromMaxU = Number.MIN_VALUE;
    var fromMinV = Number.MAX_VALUE;
    var fromMaxV = Number.MIN_VALUE;
    for (var i = 0; i < length; i++) {
        var faceUv = uvs[i];
        var faceUvLength = faceUv.length;
        for (var j = 0; j < faceUvLength; j++) {
            var uv = faceUv[j];
            fromMinU = Math.min(uv.u, fromMinU);
            fromMaxU = Math.max(uv.u, fromMaxU);
            fromMinV = Math.min(uv.v, fromMinV);
            fromMaxV = Math.max(uv.v, fromMaxV);
        }
    }

    var fromDistU = fromMaxU - fromMinU;
    var fromDistV = fromMaxV - fromMinV;
    var toDistU = maxU - minU;
    var toDistV = maxV - minV;

    var mappedUvs = new Array(length);
    for (var i = 0; i < length; i++) {
        var faceUv = uvs[i];
        var faceUvLength = faceUv.length;
        var mappedFaceUv = new Array(faceUvLength);
        mappedUvs[i] = mappedFaceUv;
        for (var j = 0; j < faceUvLength; j++) {
            var uv = faceUv[j];
            var u = minU + (((uv.u - fromMinU) / fromDistU) * toDistU);
            var v = minV + (((uv.v - fromMinV) / fromDistV) * toDistV);
            mappedFaceUv[j] = new THREE.UV(u, v);
        }
    }

    mesh.geometry.faceVertexUvs[toLayer] = mappedUvs;
}

///////////

WebVfx.AnimatedCamera = function (aspect, nearPlane, farPlane, animationData) {
    var anim = new WebVfx.Animation(animationData);
    this.animation = anim;
    var fov = anim.radians2degrees(anim.verticalFOV(aspect));
    THREE.PerspectiveCamera.call(this, fov, aspect, nearPlane, farPlane);
    // Blender XYZ order is really ZYX
    this.eulerOrder = 'ZYX';
};

WebVfx.AnimatedCamera.prototype = new THREE.PerspectiveCamera();
WebVfx.AnimatedCamera.prototype.constructor = WebVfx.AnimatedCamera;

WebVfx.AnimatedCamera.prototype.setAnimationTime = function (time) {
    var anim = this.animation;
    anim.evaluateTime(time);
    this.position.x = anim.locationX;
    this.position.y = anim.locationY;
    this.position.z = anim.locationZ;
    this.rotation.x = anim.rotationX;
    this.rotation.y = anim.rotationY;
    this.rotation.z = anim.rotationZ;
};

<commit_msg>Handle null image return from webvfx.getImage<commit_after>// Copyright (c) 2011 Hewlett-Packard Development Company, L.P. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Build and fly through a 3D world using Three.js

var WebVfx = WebVfx || {};

WebVfx.ThreeWorld = function (width, height, nearPlane, farPlane, animationData, readyCallback, scene) {
    var self = this;

    this.tracker = new WebVfx.Tracker(function () {
        readyCallback();
        delete self.tracker;
    });

    var aspect = width / height;
    this.camera = new WebVfx.AnimatedCamera(aspect, nearPlane, farPlane,
                                            animationData);
    this.scene = scene ? scene : new THREE.Scene();
    this.scene.add(this.camera);

    this.widescreen = aspect > (4 / 3);

    // Create and size canvas ourself, more efficient to size it up front
    var canvas = document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;
    this.renderer = new THREE.WebGLRenderer({ canvas: canvas,
                                              antialias: true });
    // Need to enable this for our shader
    if (!this.renderer.context.getExtension("OES_standard_derivatives"))
        console.log("OES_standard_derivatives not supported");
    this.renderer.setViewport(0, 0, width, height);
    document.body.appendChild(canvas);

    // Treat page load as trackable
    if (document.readyState != "complete") {
        this.tracker.increment();
        window.addEventListener('load', function (event) {
            self.tracker.decrement();
        }, false);
    }
};

WebVfx.ThreeWorld.prototype = {
    // Must be called to start resource tracking
    startTracking: function () {
        this.tracker.start();
    },

    // Optional _callback_ will be passed the Mesh for additional configuring
    addJSONModel: function (url, material, callback) {
        var self = this;
        if (!this.jsonLoader)
            this.jsonLoader = new THREE.JSONLoader();
        this.tracker.increment();
        this.jsonLoader.load(url, function (geometry) {
            var mesh = new THREE.Mesh(geometry, material);
            if (callback)
                callback(mesh);
            self.scene.add(mesh);
            self.tracker.decrement();
        });
    },

    resize: function (width, height) {
        this.renderer.setSize(width, height);
        this.camera.aspect = width / height;
        this.camera.updateProjectionMatrix();
        this.widescreen = this.camera.aspect > (4 / 3);
    },

    render: function (time) {
        this.camera.setAnimationTime(time);
        this.renderer.render(this.scene, this.camera);
    }
};

///////////

WebVfx.loadImageTexture = function (url, tracker) {
    var image = new Image();
    var texture = new THREE.Texture(image);
    WebVfx.trackTextureImage(texture, tracker);
    image.src = url;
    return texture;
};

WebVfx.trackTextureImage = function (texture, tracker) {
    var image = texture.image;
    if (!(image instanceof Image) || image.complete) {
        texture.needsUpdate = true;
        return;
    }
    tracker.increment();
    image.addEventListener("load", function () {
        texture.needsUpdate = true;
        tracker.decrement();
    });
};

///////////

// _options_ includes:
// fontStyle - e.g. "30px Helvetica". If it uses a font loaded with @font-face,
//   then you must use a WebVfx.FontTracker and create the text Texture after
//   the font has loaded.
// textColor - Text color css spec.
// backgroundColor - Background color css spec.
// textAlign - "left", "right" or "center".
// textBaseline - "top", "middle" or "bottom"
// margin - array of [left-right, top-bottom] margins
WebVfx.createTextTexture = function (text, targetWidth, targetHeight, options) {
    var fontStyle = options.fontStyle;
    var textColor = options.textColor;
    var backgroundColor = options.backgroundColor;
    var textAlign = options.textAlign;
    var textBaseline = options.textBaseline;

    // Canvas context provides measureText(), but this only exposes width.
    // So apply same font style to span and measure it.
    // FYI span text looks much better than canvas text because span uses
    // subpixel antialiasing
    var span = document.createElement("span");
    span.style.visibility = "hidden";
    span.style.font = fontStyle;
    span.textContent = text;
    document.body.appendChild(span);
    var textWidth = span.offsetWidth;
    var textHeight = span.offsetHeight;
    document.body.removeChild(span);

    var boxWidth = targetWidth;
    var boxHeight = targetHeight;
    if (options.margin) {
        var margin = options.margin;
        boxWidth -= 2 * margin[0];
        boxHeight -= 2 * margin[1];
    }
    var scale = Math.min(boxWidth / textWidth, boxHeight / textHeight);

    var canvas = document.createElement("canvas");
    canvas.width = targetWidth;
    canvas.height = targetHeight;

    var context = canvas.getContext("2d");
    if (backgroundColor) {
        context.fillStyle = backgroundColor;
        context.fillRect(0, 0, targetWidth, targetHeight);
    }
    // Scale text to fit if too large
    var positionScale = 1;
    if (scale < 1) {
        context.scale(scale, scale);
        positionScale = 1 / scale;
    }
    context.font = fontStyle;
    context.fillStyle = textColor;

    var x = 0, y = 0;

    switch (textAlign) {
    case "right":
        x = targetWidth;
        break;
    case "center":
        x = targetWidth / 2;
        break;
    case "left":
    default:
        textAlign = "left";
        break;
    }
    context.textAlign = textAlign;

    switch (textBaseline) {
    case "middle":
        y = targetHeight / 2;
        break;
    case "bottom":
        y = targetHeight;
        break;
    case "top":
    default:
        textBaseline = "top";
        break;
    }
    context.textBaseline = textBaseline;

    context.fillText(text, x * positionScale, y * positionScale);

    var texture = new THREE.Texture(canvas);
    texture.needsUpdate = true;
    return texture;
}

///////////

WebVfx.updateVideoTexture = function (texture, name) {
    var image = webvfx.getImage(name);
    if (!image)
        return;
    texture.image = image.toImageData();
    texture.needsUpdate = true;
};

// v offset in uv space for top bottom to render 16:9 image in 4:3 mesh.
// 16:12 (4:3) vs 16:9, 12-9=3/2=1.5 so 1.5/9 is offset for top and bottom
WebVfx.vClampOffset = 1.5/9;

///////////

// Set UV coords for given layer, for a single quad
WebVfx.setQuadUvs = function (mesh, layer, u1, v1, u2, v2, u3, v3, u4, v4) {
    var uvs = [new THREE.UV(u1, v1),
               new THREE.UV(u2, v2),
               new THREE.UV(u3, v3),
               new THREE.UV(u4, v4)];
    mesh.geometry.faceVertexUvs[layer] = [uvs];
}

// Map (scale/translate) UVs from _fromLayer_ to _toLayer_
// min/max specifies new UV coordinate space range.
WebVfx.mapUvs = function (mesh, fromLayer, toLayer, minU, minV, maxU, maxV) {
    var uvs = mesh.geometry.faceVertexUvs[fromLayer];
    var length = uvs.length;

    // Find UV space we are mapping from
    var fromMinU = Number.MAX_VALUE;
    var fromMaxU = Number.MIN_VALUE;
    var fromMinV = Number.MAX_VALUE;
    var fromMaxV = Number.MIN_VALUE;
    for (var i = 0; i < length; i++) {
        var faceUv = uvs[i];
        var faceUvLength = faceUv.length;
        for (var j = 0; j < faceUvLength; j++) {
            var uv = faceUv[j];
            fromMinU = Math.min(uv.u, fromMinU);
            fromMaxU = Math.max(uv.u, fromMaxU);
            fromMinV = Math.min(uv.v, fromMinV);
            fromMaxV = Math.max(uv.v, fromMaxV);
        }
    }

    var fromDistU = fromMaxU - fromMinU;
    var fromDistV = fromMaxV - fromMinV;
    var toDistU = maxU - minU;
    var toDistV = maxV - minV;

    var mappedUvs = new Array(length);
    for (var i = 0; i < length; i++) {
        var faceUv = uvs[i];
        var faceUvLength = faceUv.length;
        var mappedFaceUv = new Array(faceUvLength);
        mappedUvs[i] = mappedFaceUv;
        for (var j = 0; j < faceUvLength; j++) {
            var uv = faceUv[j];
            var u = minU + (((uv.u - fromMinU) / fromDistU) * toDistU);
            var v = minV + (((uv.v - fromMinV) / fromDistV) * toDistV);
            mappedFaceUv[j] = new THREE.UV(u, v);
        }
    }

    mesh.geometry.faceVertexUvs[toLayer] = mappedUvs;
}

///////////

WebVfx.AnimatedCamera = function (aspect, nearPlane, farPlane, animationData) {
    var anim = new WebVfx.Animation(animationData);
    this.animation = anim;
    var fov = anim.radians2degrees(anim.verticalFOV(aspect));
    THREE.PerspectiveCamera.call(this, fov, aspect, nearPlane, farPlane);
    // Blender XYZ order is really ZYX
    this.eulerOrder = 'ZYX';
};

WebVfx.AnimatedCamera.prototype = new THREE.PerspectiveCamera();
WebVfx.AnimatedCamera.prototype.constructor = WebVfx.AnimatedCamera;

WebVfx.AnimatedCamera.prototype.setAnimationTime = function (time) {
    var anim = this.animation;
    anim.evaluateTime(time);
    this.position.x = anim.locationX;
    this.position.y = anim.locationY;
    this.position.z = anim.locationZ;
    this.rotation.x = anim.rotationX;
    this.rotation.y = anim.rotationY;
    this.rotation.z = anim.rotationZ;
};

<|endoftext|>


<commit_before>google.load('visualization', '1', {packages: ['gauge']});

google.setOnLoadCallback(initialize);

var options = {
    width: 175,
    height: 175,
    redFrom: 5,
    redTo: 6,
    yellowFrom: 4.5,
    yellowTo: 5,
    min: 0,
    max: 6,
};

var optionsDutyCycle = {
    width: 175,
    height: 175,
    min: 0,
    max: 100,
};

var gaugesDict = {};
var gaugesDutyCycleDict = {};

function initialize() {
    var intervalID = setInterval(refresh, 5000);
    $.ajax({
        url: url + "/v2/feeds.json?user=wing",
        type: 'GET',
        dataType: 'json',
        cache: false,
        success: function (data) {
            plot(data)
        },
        error: function () {
            alert('boo!');
        },
        beforeSend: setHeader
    });
    function setHeader(xhr) {
        xhr.setRequestHeader('X-PachubeApiKey', key);
    }
}

function refresh() {
    $.ajax({
        url: url + "/v2/feeds.json?user=wing",
        type: 'GET',
        dataType: 'json',
        cache: false,
        success: function (data) {
            plot(data)
        },
        beforeSend: setHeader
    });
    function setHeader(xhr) {
        xhr.setRequestHeader('X-PachubeApiKey', key);
    }
}

function plot(data) {
    var len = Object.keys(gaugesDict).length
    if (len == 0) {
        for (node in data['results']) {
            var id = data['results'][node]['id']
            document.getElementById('feeds').innerHTML += '

Feed: ' + id + ' (view)

Node:
Energino:
Dispatcher:
n.a.

';
        }
    }
    for (node in data['results']) {
        var id = data['results'][node]['id']
        var amperes = "0.0"
        var dutyCycle = "0.0"
        var nbClients = "n.a."
        var energino = "n.a."
        var title = "n.a."
        var dispatcher = "n.a."
        if ('dispatcher' in data['results'][node]) {
            dispatcher = data['results'][node]['dispatcher']
        }
        if ('title' in data['results'][node]) {
            title = data['results'][node]['title']
        }
        if ('energino' in data['results'][node]) {
            energino = data['results'][node]['energino']
        }
        for (datastream in data['results'][node]['datastreams']) {
            if (data['results'][node]['datastreams'][datastream]['id'] == 'watts') {
                amperes = data['results'][node]['datastreams'][datastream]['current_value']
            }
            if (data['results'][node]['datastreams'][datastream]['id'] == 'duty_cycle') {
                dutyCycle = data['results'][node]['datastreams'][datastream]['current_value']
            }
            if (data['results'][node]['datastreams'][datastream]['id'] == 'clients') {
                nbClients = data['results'][node]['datastreams'][datastream]['current_value']
            }
        }
	var aLink = '' + energino + ''
	document.getElementById("chart_energino_" + id).innerHTML = aLink
	document.getElementById("chart_title_" + id).innerHTML = title
	document.getElementById("chart_clients_" + id).innerHTML = nbClients
	document.getElementById("chart_dispatcher_" + id).innerHTML = dispatcher
	if (parseFloat(amperes) < 0) {
		amperes = "0.0"
        }
        var table = google.visualization.arrayToDataTable([
            ['Label', 'Value'],
            ['Power [W]', parseFloat(amperes)]
        ]);
        var tableDutyCycle = google.visualization.arrayToDataTable([
            ['Label', 'Value'],
            ['Duty [%]', parseFloat(dutyCycle)]
        ]);

        if (!(id in gaugesDict)) {
            gaugesDict[id] = new google.visualization.Gauge(document.getElementById("chart" + id));
        }

        if (!(id in gaugesDutyCycleDict)) {
            gaugesDutyCycleDict[id] = new google.visualization.Gauge(document.getElementById("chart_dc" + id));
        }

        gaugesDict[id].draw(table, options);
        gaugesDutyCycleDict[id].draw(tableDutyCycle, optionsDutyCycle);

    }
}
<commit_msg>cosmetic fixes to ui<commit_after>google.load('visualization', '1', {packages: ['gauge']});

google.setOnLoadCallback(initialize);

var options = {
    width: 165,
    height: 165,
    redFrom: 5,
    redTo: 6,
    yellowFrom: 4.5,
    yellowTo: 5,
    min: 0,
    max: 6,
};

var optionsDutyCycle = {
    width: 165,
    height: 165,
    min: 0,
    max: 100,
};

var gaugesDict = {};
var gaugesDutyCycleDict = {};

function initialize() {
    var intervalID = setInterval(refresh, 5000);
    $.ajax({
        url: url + "/v2/feeds.json?user=wing",
        type: 'GET',
        dataType: 'json',
        cache: false,
        success: function (data) {
            plot(data)
        },
        error: function () {
            alert('boo!');
        },
        beforeSend: setHeader
    });
    function setHeader(xhr) {
        xhr.setRequestHeader('X-PachubeApiKey', key);
    }
}

function refresh() {
    $.ajax({
        url: url + "/v2/feeds.json?user=wing",
        type: 'GET',
        dataType: 'json',
        cache: false,
        success: function (data) {
            plot(data)
        },
        beforeSend: setHeader
    });
    function setHeader(xhr) {
        xhr.setRequestHeader('X-PachubeApiKey', key);
    }
}

function plot(data) {
    var len = Object.keys(gaugesDict).length
    if (len == 0) {
        for (node in data['results']) {
            var id = data['results'][node]['id']
            document.getElementById('feeds').innerHTML += '

Feed: ' + id + ' (view)

Node:
Energino:
Dispatcher:
n.a.

';
        }
    }
    for (node in data['results']) {
        var id = data['results'][node]['id']
        var amperes = "0.0"
        var dutyCycle = "0.0"
        var nbClients = "n.a."
        var energino = "n.a."
        var title = "n.a."
        var dispatcher = "n.a."
        if ('dispatcher' in data['results'][node]) {
            dispatcher = data['results'][node]['dispatcher']
        }
        if ('title' in data['results'][node]) {
            title = data['results'][node]['title']
        }
        if ('energino' in data['results'][node]) {
            energino = data['results'][node]['energino']
        }
        for (datastream in data['results'][node]['datastreams']) {
            if (data['results'][node]['datastreams'][datastream]['id'] == 'watts') {
                amperes = data['results'][node]['datastreams'][datastream]['current_value']
            }
            if (data['results'][node]['datastreams'][datastream]['id'] == 'duty_cycle') {
                dutyCycle = data['results'][node]['datastreams'][datastream]['current_value']
            }
            if (data['results'][node]['datastreams'][datastream]['id'] == 'clients') {
                nbClients = data['results'][node]['datastreams'][datastream]['current_value']
            }
        }
	var aLink = '' + energino + ''
	document.getElementById("chart_energino_" + id).innerHTML = aLink
	document.getElementById("chart_title_" + id).innerHTML = title
	document.getElementById("chart_clients_" + id).innerHTML = nbClients
	document.getElementById("chart_dispatcher_" + id).innerHTML = dispatcher
	if (parseFloat(amperes) < 0) {
		amperes = "0.0"
        }
        var table = google.visualization.arrayToDataTable([
            ['Label', 'Value'],
            ['Power [W]', parseFloat(amperes)]
        ]);
        var tableDutyCycle = google.visualization.arrayToDataTable([
            ['Label', 'Value'],
            ['Duty [%]', parseFloat(dutyCycle)]
        ]);

        if (!(id in gaugesDict)) {
            gaugesDict[id] = new google.visualization.Gauge(document.getElementById("chart" + id));
        }

        if (!(id in gaugesDutyCycleDict)) {
            gaugesDutyCycleDict[id] = new google.visualization.Gauge(document.getElementById("chart_dc" + id));
        }

        gaugesDict[id].draw(table, options);
        gaugesDutyCycleDict[id].draw(tableDutyCycle, optionsDutyCycle);

    }
}
<|endoftext|>


<commit_before>var state_running = function(game) {
    return {
        create: function(game) {
            game.score = 0;
            this.graphics = game.add.graphics(0, 0);
            this.firstTouchY = -1;
            this.dragY = -1;

            game.input.onDown.add(this.onDown, this);
            game.input.onUp.add(this.onUp, this);

            var textStyle = {
                fill: colorPalette.text,
                boundsAlignH: "center",
                boundsAlignV: "middle"
            };
            objects.scoreDisplay = game.add.text(game.world.centerX - constants.runnerSize, constants.groundHeight - (constants.runnerSize / 2), game.score, textStyle);
            objects.scoreDisplay.anchor.set(0.5);
            objects.scoreDisplay.setShadow(1, 1, colorPalette.textShadow);
            objects.obstacles = [];
            obstacleGenerator.addObstacleToBack();
        },

        update: function(game) {
            objects.runner.applyGravity();

            var obstacleIndex;
            for (obstacleIndex = 0; obstacleIndex < objects.obstacles.length; ++obstacleIndex) {
                var obstacle = objects.obstacles[obstacleIndex];
                obstacle.applyGravity();
                obstacle.movePolygonBy(constants.hspeed);

                if (objects.runner.intersects(obstacle)) {
                    // Game over
                    game.stateTransition.to('dying', false);
                    return;
                }

                if (this.runnerHasPassedObstacle(obstacle, objects.runner)) {
                    this.scorePoint(obstacle);
                }

            }
            if (objects.obstacles[0].findRightmostPoint() < 0) {
                var removed = objects.obstacles.shift();
                objects.runner.onLand.remove(removed.runnerLandCallback);
            }
            if (objects.obstacles[objects.obstacles.length - 1].findRightmostPoint() < game.world.width) {
                obstacleGenerator.addObstacleToBack();
            }
            this.dragY = this.firstTouchY - game.input.activePointer.worldY;
            var percent = percentOf(this.dragY, game.world.height);
            var charge = chargeLevel(percent);
            objects.runner.updateBeforeDraw(charge);
        },

        runnerHasPassedObstacle: function(obstacle, runner) {
            return !obstacle.hasScored && Math.round(obstacle.findRightmostPoint()) < runner.findLeftmostPoint() - 1;
        },

        scorePoint: function(obstacle) {
            ++game.score;
            objects.scoreDisplay.text = (game.score);
            obstacle.hasScored = true;
        },

        render: function() {
            this.graphics.clear();

            var obstacleIndex;
            for (obstacleIndex = 0; obstacleIndex < objects.obstacles.length; ++obstacleIndex) {
                var obstacle = objects.obstacles[obstacleIndex];
                obstacle.draw(this.graphics);
            }
            objects.runner.draw(this.graphics);
            objects.ground.draw(this.graphics);
            drawDebugText(constants.debugMode);
        },

        onDown: function(pointer, mouseEvent) {
            if (mouseEvent.identifier === 0) {
                if (this.firstTouchY === -1) {
                    this.firstTouchY = pointer.worldY;
                }
            }
        },

        onUp: function(pointer, mouseEvent) {
            // pointer.identifier === 0 Prevents 'mouse leaving the game world' from firing this, too
            if (mouseEvent.identifier === 0) {
                var charge = chargeLevel(percentOf(this.dragY, game.world.height));
                objects.runner.jump(charge);
                this.firstTouchY = -1;
                this.dragY = -1;
            }
        }
    };
};
<commit_msg>polish - hiding score when it's 0<commit_after>var state_running = function(game) {
    return {
        create: function(game) {
            game.score = 0;
            this.graphics = game.add.graphics(0, 0);
            this.firstTouchY = -1;
            this.dragY = -1;

            game.input.onDown.add(this.onDown, this);
            game.input.onUp.add(this.onUp, this);

            var textStyle = {
                fill: colorPalette.text,
                boundsAlignH: "center",
                boundsAlignV: "middle"
            };
            objects.scoreDisplay = game.add.text(game.world.centerX - constants.runnerSize, constants.groundHeight - (constants.runnerSize / 2), game.score, textStyle);
            objects.scoreDisplay.anchor.set(0.5);
            objects.scoreDisplay.setShadow(1, 1, colorPalette.textShadow);
            objects.scoreDisplay.visible = false;
            objects.obstacles = [];
            obstacleGenerator.addObstacleToBack();
        },

        update: function(game) {
            objects.runner.applyGravity();

            var obstacleIndex;
            for (obstacleIndex = 0; obstacleIndex < objects.obstacles.length; ++obstacleIndex) {
                var obstacle = objects.obstacles[obstacleIndex];
                obstacle.applyGravity();
                obstacle.movePolygonBy(constants.hspeed);

                if (objects.runner.intersects(obstacle)) {
                    // Game over
                    game.stateTransition.to('dying', false);
                    return;
                }

                if (this.runnerHasPassedObstacle(obstacle, objects.runner)) {
                    this.scorePoint(obstacle);
                }

            }
            if (objects.obstacles[0].findRightmostPoint() < 0) {
                var removed = objects.obstacles.shift();
                objects.runner.onLand.remove(removed.runnerLandCallback);
            }
            if (objects.obstacles[objects.obstacles.length - 1].findRightmostPoint() < game.world.width) {
                obstacleGenerator.addObstacleToBack();
            }
            this.dragY = this.firstTouchY - game.input.activePointer.worldY;
            var percent = percentOf(this.dragY, game.world.height);
            var charge = chargeLevel(percent);
            objects.runner.updateBeforeDraw(charge);
        },

        runnerHasPassedObstacle: function(obstacle, runner) {
            return !obstacle.hasScored && Math.round(obstacle.findRightmostPoint()) < runner.findLeftmostPoint() - 1;
        },

        scorePoint: function(obstacle) {
            ++game.score;
            objects.scoreDisplay.visible = true;
            objects.scoreDisplay.text = (game.score);
            obstacle.hasScored = true;
        },

        render: function() {
            this.graphics.clear();

            var obstacleIndex;
            for (obstacleIndex = 0; obstacleIndex < objects.obstacles.length; ++obstacleIndex) {
                var obstacle = objects.obstacles[obstacleIndex];
                obstacle.draw(this.graphics);
            }
            objects.runner.draw(this.graphics);
            objects.ground.draw(this.graphics);
            drawDebugText(constants.debugMode);
        },

        onDown: function(pointer, mouseEvent) {
            if (mouseEvent.identifier === 0) {
                if (this.firstTouchY === -1) {
                    this.firstTouchY = pointer.worldY;
                }
            }
        },

        onUp: function(pointer, mouseEvent) {
            // pointer.identifier === 0 Prevents 'mouse leaving the game world' from firing this, too
            if (mouseEvent.identifier === 0) {
                var charge = chargeLevel(percentOf(this.dragY, game.world.height));
                objects.runner.jump(charge);
                this.firstTouchY = -1;
                this.dragY = -1;
            }
        }
    };
};
<|endoftext|>


<commit_before>var express = require('express');

var shortid = require('shortid');

var routes = function(db){
    var cardRouter = express.Router();

    cardRouter.route('/cards')
        .post(function(req,res){
            var newCard = {
                id:shortid.generate(),
                author: req.body.author,
                content: req.body.content
            };
            db.put({
                _id: newCard.id,
                author: newCard.author,
                content: newCard.content
            }, function (err, doc) {
                console.log('put doc', doc);

                if (!err) {
                  db.get(newCard.id).then(function (doc) {
                    console.log('Got doc', JSON.stringify(doc));
                      res.status(201).send(doc);
                  }).catch(function (err) {
                      console.log('get err', err, JSON.stringify(doc));
                  });
                } else {
                  console.log('put error', err);
                }
            });
        })
        .get(function(req, res){
            db.allDocs({
                include_docs: true
                //attachments: true
            }).then(function (result) {
                res.json(result);
            }).catch(function (err) {
                console.log(err);
            });
        });

    cardRouter.route('/cards/:cardId')
        .get(function(req,res){
            db.get(req.params.cardId).then(function (err,doc) {
                if(err)
                    res.status(500).send(err);
                else
                    res.json(doc);
            }).catch(function (err) {
                var responseJson = { result: 'doc not found'};
                res.json(responseJson);
            });
        })
        .put(function(req,res){
            db.get(req.params.cardId).then(function(doc) {
                return db.put({
                    _id: doc._id,
                    _rev: doc._rev,
                    author: req.body.author,
                    content: req.body.content //Update the post card content
                });
            }).then(function(response) {
                var responseJson = { result: 'doc updated'};
                res.json(responseJson);
            }).catch(function (err) {
                console.log(err);
                //Create the new card, if the doc is not available to update
                var newCard = {
                    id:req.params.cardId,
                    author: req.body.author,
                    content: req.body.content
                };
                db.put({
                    _id: newCard.id,
                    author: newCard.author,
                    content: newCard.content
                }, function (err, doc) {
                    var responseJson = { result: 'doc created'};
                    res.json(responseJson);
                });
            });
        })
        .delete(function(req, res){
            db.get(req.params.cardId).then(function(doc) {
                return db.remove(doc._id, doc._rev);
            }).then(function (result) {
                var responseJson = { result: 'doc deleted'};
                res.json(responseJson);
            }).catch(function (err) {
                console.log(err);
            });
        });
    return cardRouter;
};

module.exports = routes;
<commit_msg>Sorting routes<commit_after>var express = require('express');
var shortid = require('shortid');

function routes (db) {
  var cardRouter = express.Router();

  cardRouter.route('/cards')
    .post(function (req, res) {
      var newCard = {
        id:shortid.generate(),
        author: req.body.author,
        content: req.body.content
      };

      db.put({
        _id: newCard.id,
        author: newCard.author,
        content: newCard.content
      }).then(function (response) {
        return db.get(response.id);
      })
      .then(function (doc) {
        res.status(201).send(doc);
      })
      .catch(function (err) {
        res.status(500).send(err);
      });

    })
    .get(function (req, res) {

      db.allDocs({
        include_docs: true
      }).then(function (docs) {
        res.status(200).json(docs);
      }).catch(function (err) {
        res.status(err.status).send(err.message);
      });

    });

    cardRouter.route('/cards/:cardId')
      .get(function (req,res) {

        db.get(req.params.cardId)
          .then(function (doc) {
            res.status(200).json(doc);
          })
          .catch(function (err) {
            res.status(err.status).send(err.message);
          });

      })
      .put(function (req, res) {

        db.get(req.params.cardId)
          .then(function (doc) {
            return db.put({
              _id: doc._id,
              _rev: doc._rev,
              author: req.body.author,
              content: req.body.content
            });
          })
          .then(function (response) {
            res.status(204).end();
          })
          .catch(function (err) {
            res.status(err.status).send(err.message);
          });

      })
      .delete(function(req, res){
        db.get(req.params.cardId)
          .then(function(doc) {
            return db.remove(doc);
          })
          .then(function (result) {
            res.status(204).end();
          }).catch(function (err) {
            res.status(err.status).send(err.message);
          });
      });

  return cardRouter;
};

module.exports = routes;
<|endoftext|>