<commit_before>'use strict';

(function (angular,buildfire) {
  angular.module('vimeoPluginWidget')
    .controller('WidgetFeedCtrl', ['$scope', 'Buildfire', 'DataStore', 'TAG_NAMES', 'STATUS_CODE', 'VimeoApi', 'VIDEO_COUNT', '$sce', 'Location', '$rootScope', 'LAYOUTS', 'CONTENT_TYPE', 'VideoCache',
      function ($scope, Buildfire, DataStore, TAG_NAMES, STATUS_CODE, VimeoApi, VIDEO_COUNT, $sce, Location, $rootScope, LAYOUTS, CONTENT_TYPE, VideoCache) {
        var WidgetFeed = this;

        WidgetFeed.data = null;
        //create new instance of buildfire carousel viewer
        var view = null;
        WidgetFeed.videos = [];
        WidgetFeed.busy = false;
        WidgetFeed.nextPageToken = 1;
        var currentListLayout = null;
        WidgetFeed.currentFeedId = null;
        var feedType = "Channel";
        $rootScope.showFeed = true;

        /*declare the device width heights*/
        $rootScope.deviceHeight = window.innerHeight;
        $rootScope.deviceWidth = window.innerWidth || 320;

        /*
         * Fetch user's data from datastore
         */
        var initData = function(isRefresh) {
            var success = function (result) {
                WidgetFeed.data = result.data;
                if (!WidgetFeed.data.content)
                  WidgetFeed.data.content = {};
                if (!WidgetFeed.data.design)
                  WidgetFeed.data.design = {};
                if (!WidgetFeed.data.content)
                  WidgetFeed.data.content = {};
                if (!WidgetFeed.data.design.itemListLayout) {
                  WidgetFeed.data.design.itemListLayout = LAYOUTS.listLayouts[0].name;
                }
                if (WidgetFeed.data.design.itemListBgImage) {
                  $rootScope.backgroundListImage = WidgetFeed.data.design.itemListBgImage;
                }
                if (!result.id) {
                  WidgetFeed.data.content.feedID = TAG_NAMES.DEFAULT_FEED_ID;
                }
                if (WidgetFeed.data.content.type)
                  $rootScope.contentType = WidgetFeed.data.content.type;
                currentListLayout = WidgetFeed.data.design.itemListLayout;
                if (WidgetFeed.data.content) {
                  WidgetFeed.currentFeedId = WidgetFeed.data.content.feedID;
                }
                if (isRefresh) {
                  if (currentListLayout != WidgetFeed.data.design.itemListLayout && view && WidgetFeed.data.content.carouselImages) {
                    if (WidgetFeed.data.content.carouselImages.length)
                      view._destroySlider();
                    view = null;
                  }
                  else {
                    if (view) {
                      view.loadItems(WidgetFeed.data.content.carouselImages);
                    }
                  }

                  WidgetFeed.loadMore();
                }
                if (!$scope.$$phase)
                  $scope.$digest();
              }
              , error = function (err) {
                if (err && err.code !== STATUS_CODE.NOT_FOUND) {
                  console.error('Error while getting data', err);
                }
              };
            DataStore.get(TAG_NAMES.VIMEO_INFO).then(success, error);
          };
        var init = function () {
          initData(false);
        };
        init();
        $rootScope.$on("Carousel:LOADED", function () {
          if (!view) {
            view = new Buildfire.components.carousel.view("#carousel", []);
          }
          if (WidgetFeed.data.content && WidgetFeed.data.content.carouselImages) {
            view.loadItems(WidgetFeed.data.content.carouselImages);
          } else {
            view.loadItems([]);
          }
        });

        var getFeedVideos = function (_feedId) {
         Buildfire.spinner.show();
          var success = function (result) {
              Buildfire.spinner.hide();
              WidgetFeed.videos = WidgetFeed.videos.length ? WidgetFeed.videos.concat(result.data.data) : result.data.data;
              WidgetFeed.nextPageToken = result.data.page + 1;
              if (WidgetFeed.videos.length < result.data.total) {
                WidgetFeed.busy = false;
              }
            }
            , error = function (err) {
              Buildfire.spinner.hide();
              console.log('Error In Fetching Single Video Details', err);
            };
          if (WidgetFeed.data && WidgetFeed.data.content && WidgetFeed.data.content.type === CONTENT_TYPE.USER_FEED)
            feedType = "User";
          else
            feedType = "Channel";
          VimeoApi.getFeedVideos(feedType, _feedId, VIDEO_COUNT.LIMIT, WidgetFeed.nextPageToken).then(success, error);
        };

        var onUpdateCallback = function (event) {
          if (event && event.tag === TAG_NAMES.VIMEO_INFO) {
            WidgetFeed.data = event.data;
            if (!WidgetFeed.data.content)
              WidgetFeed.data.content = {};
            if (!WidgetFeed.data.design)
              WidgetFeed.data.design = {};
            if (WidgetFeed.data.content.type)
              $rootScope.contentType = WidgetFeed.data.content.type;
            if (!WidgetFeed.data.design.itemListLayout) {
              WidgetFeed.data.design.itemListLayout = LAYOUTS.listLayouts[0].name;
            }
            if (WidgetFeed.data.design.itemListBgImage) {
              $rootScope.backgroundListImage = WidgetFeed.data.design.itemListBgImage;
            }  else{
              $rootScope.backgroundListImage="";
            }
            if (WidgetFeed.data.design && WidgetFeed.data.content) {
              if ((currentListLayout != WidgetFeed.data.design.itemListLayout) && view && WidgetFeed.data.content.carouselImages) {
                if (WidgetFeed.data.content.carouselImages.length)
                  view._destroySlider();
                view = null;
              }
              else {
                if (view) {
                  view.loadItems(WidgetFeed.data.content.carouselImages);
                }
              }
              currentListLayout = WidgetFeed.data.design.itemListLayout;
              WidgetFeed.currentFeedId = WidgetFeed.data.content.feedID;
            }

            if (!WidgetFeed.data.content.rssUrl) {
              WidgetFeed.videos = [];
              WidgetFeed.busy = false;
              WidgetFeed.nextPageToken = 1;
            } else if (!(WidgetFeed.videos.length > 0) && WidgetFeed.data.content.feedID) {
              WidgetFeed.currentFeedId = WidgetFeed.data.content.feedID;
              getFeedVideos(WidgetFeed.data.content.feedID);
            }

            if (WidgetFeed.data.content && WidgetFeed.data.content.feedID) {
              WidgetFeed.currentFeedId = WidgetFeed.data.content.feedID;
              WidgetFeed.videos = [];
              WidgetFeed.busy = false;
              WidgetFeed.nextPageToken = null;
              WidgetFeed.loadMore();
            } else if (WidgetFeed.data.content && WidgetFeed.data.content.videoID)
              Location.goTo("#/video/" + WidgetFeed.data.content.videoID);

            WidgetFeed.currentFeedId = WidgetFeed.data.content.feedID;
          }
        };
        DataStore.onUpdate().then(null, null, onUpdateCallback);

        WidgetFeed.loadMore = function () {
          if (WidgetFeed.busy) return;
          WidgetFeed.busy = true;
          if (WidgetFeed.currentFeedId && WidgetFeed.currentFeedId !== '1') {
            getFeedVideos(WidgetFeed.currentFeedId);
          }
          else {
            if (WidgetFeed.data.content.videoID)
              Location.goTo("#/video/" + WidgetFeed.data.content.videoID);
          }
        };

        WidgetFeed.safeHtml = function (html) {
            if (html) {
                var $html = $('
', {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());
            }
        };

        WidgetFeed.showDescription = function (description) {
          var _retVal = false;
          if (description) {
            description = description.trim();
            if ((description !== '

') && (description !== '

')) {
              _retVal = true;
            }
          }
          return _retVal;
        };

        WidgetFeed.openDetailsPage = function (video) {
          VideoCache.setVideo(video);
          var videoId = video.uri.split("/").pop();
          Location.goTo('#/video/' + videoId);
        };

        $rootScope.$on("ROUTE_CHANGED", function (e, data) {
          WidgetFeed.data = data;
          if (!WidgetFeed.data.design)
            WidgetFeed.data.design = {};
          if (!WidgetFeed.data.content)
            WidgetFeed.data.content = {};
          if (!(WidgetFeed.videos.length > 0) && WidgetFeed.data.content.feedID) {
            WidgetFeed.currentFeedId = WidgetFeed.data.content.feedID;
            getFeedVideos(WidgetFeed.data.content.feedID);
          }
          if (!view) {
            view = new Buildfire.components.carousel.view("#carousel", []);
          }
          if (WidgetFeed.data.design.itemListBgImage) {
            $rootScope.backgroundListImage = WidgetFeed.data.design.itemListBgImage;
          }
          else{
            $rootScope.backgroundListImage="";
          }
          if (view && WidgetFeed.data.content.carouselImages) {
            view.loadItems(WidgetFeed.data.content.carouselImages);
          }
          DataStore.onUpdate().then(null, null, onUpdateCallback);

          buildfire.datastore.onRefresh(function () {
            WidgetFeed.videos = [];
            WidgetFeed.busy = false;
            WidgetFeed.nextPageToken = null;
            initData(true);
          });
        });

        $scope.$on("$destroy", function () {
          DataStore.clearListener();
        });

        buildfire.datastore.onRefresh(function () {
          WidgetFeed.videos = [];
          WidgetFeed.busy = false;
          WidgetFeed.nextPageToken = null;
          initData(true);
        });
      }])
})(window.angular, window.buildfire);
<commit_msg>Fixed issue : If the user changes the layout design while in a specific video, going back to the video list will hide the image carousel<commit_after>'use strict';

(function (angular,buildfire) {
  angular.module('vimeoPluginWidget')
    .controller('WidgetFeedCtrl', ['$scope', 'Buildfire', 'DataStore', 'TAG_NAMES', 'STATUS_CODE', 'VimeoApi', 'VIDEO_COUNT', '$sce', 'Location', '$rootScope', 'LAYOUTS', 'CONTENT_TYPE', 'VideoCache',
      function ($scope, Buildfire, DataStore, TAG_NAMES, STATUS_CODE, VimeoApi, VIDEO_COUNT, $sce, Location, $rootScope, LAYOUTS, CONTENT_TYPE, VideoCache) {
        var WidgetFeed = this;

        WidgetFeed.data = null;
        //create new instance of buildfire carousel viewer
        var view = null;
        WidgetFeed.videos = [];
        WidgetFeed.busy = false;
        WidgetFeed.nextPageToken = 1;
        var currentListLayout = null;
        WidgetFeed.currentFeedId = null;
        var feedType = "Channel";
        $rootScope.showFeed = true;

        /*declare the device width heights*/
        $rootScope.deviceHeight = window.innerHeight;
        $rootScope.deviceWidth = window.innerWidth || 320;

        /*
         * Fetch user's data from datastore
         */
        var initData = function(isRefresh) {
            var success = function (result) {
                WidgetFeed.data = result.data;
                if (!WidgetFeed.data.content)
                  WidgetFeed.data.content = {};
                if (!WidgetFeed.data.design)
                  WidgetFeed.data.design = {};
                if (!WidgetFeed.data.content)
                  WidgetFeed.data.content = {};
                if (!WidgetFeed.data.design.itemListLayout) {
                  WidgetFeed.data.design.itemListLayout = LAYOUTS.listLayouts[0].name;
                }
                if (WidgetFeed.data.design.itemListBgImage) {
                  $rootScope.backgroundListImage = WidgetFeed.data.design.itemListBgImage;
                }
                if (!result.id) {
                  WidgetFeed.data.content.feedID = TAG_NAMES.DEFAULT_FEED_ID;
                }
                if (WidgetFeed.data.content.type)
                  $rootScope.contentType = WidgetFeed.data.content.type;
                currentListLayout = WidgetFeed.data.design.itemListLayout;
                if (WidgetFeed.data.content) {
                  WidgetFeed.currentFeedId = WidgetFeed.data.content.feedID;
                }
                if (isRefresh) {
                  if (currentListLayout != WidgetFeed.data.design.itemListLayout && view && WidgetFeed.data.content.carouselImages) {
                    if (WidgetFeed.data.content.carouselImages.length)
                      view._destroySlider();
                    view = null;
                  }
                  else {
                    if (view) {
                      view.loadItems(WidgetFeed.data.content.carouselImages);
                    }
                  }

                  WidgetFeed.loadMore();
                }
                if (!$scope.$$phase)
                  $scope.$digest();
              }
              , error = function (err) {
                if (err && err.code !== STATUS_CODE.NOT_FOUND) {
                  console.error('Error while getting data', err);
                }
              };
            DataStore.get(TAG_NAMES.VIMEO_INFO).then(success, error);
          };
        var init = function () {
          initData(false);
        };
        init();
        $rootScope.$on("Carousel:LOADED", function () {
          if (!view) {
            view = new Buildfire.components.carousel.view("#carousel", []);
          }
          if (WidgetFeed.data.content && WidgetFeed.data.content.carouselImages) {
            view.loadItems(WidgetFeed.data.content.carouselImages);
          } else {
            view.loadItems([]);
          }
        });

        var getFeedVideos = function (_feedId) {
         Buildfire.spinner.show();
          var success = function (result) {
              Buildfire.spinner.hide();
              WidgetFeed.videos = WidgetFeed.videos.length ? WidgetFeed.videos.concat(result.data.data) : result.data.data;
              WidgetFeed.nextPageToken = result.data.page + 1;
              if (WidgetFeed.videos.length < result.data.total) {
                WidgetFeed.busy = false;
              }
            }
            , error = function (err) {
              Buildfire.spinner.hide();
              console.log('Error In Fetching Single Video Details', err);
            };
          if (WidgetFeed.data && WidgetFeed.data.content && WidgetFeed.data.content.type === CONTENT_TYPE.USER_FEED)
            feedType = "User";
          else
            feedType = "Channel";
          VimeoApi.getFeedVideos(feedType, _feedId, VIDEO_COUNT.LIMIT, WidgetFeed.nextPageToken).then(success, error);
        };

        var onUpdateCallback = function (event) {
          if (event && event.tag === TAG_NAMES.VIMEO_INFO) {
            WidgetFeed.data = event.data;
            if (!WidgetFeed.data.content)
              WidgetFeed.data.content = {};
            if (!WidgetFeed.data.design)
              WidgetFeed.data.design = {};
            if (WidgetFeed.data.content.type)
              $rootScope.contentType = WidgetFeed.data.content.type;
            if (!WidgetFeed.data.design.itemListLayout) {
              WidgetFeed.data.design.itemListLayout = LAYOUTS.listLayouts[0].name;
            }
            if (WidgetFeed.data.design.itemListBgImage) {
              $rootScope.backgroundListImage = WidgetFeed.data.design.itemListBgImage;
            }  else{
              $rootScope.backgroundListImage="";
            }
            if (WidgetFeed.data.design && WidgetFeed.data.content) {
              if ((currentListLayout != WidgetFeed.data.design.itemListLayout) && view && WidgetFeed.data.content.carouselImages) {
                if (WidgetFeed.data.content.carouselImages.length)
                  view._destroySlider();
                view = null;
              }
              else {
                if (view) {
                  view.loadItems(WidgetFeed.data.content.carouselImages);
                }
              }
              currentListLayout = WidgetFeed.data.design.itemListLayout;
              WidgetFeed.currentFeedId = WidgetFeed.data.content.feedID;
            }

            if (!WidgetFeed.data.content.rssUrl) {
              WidgetFeed.videos = [];
              WidgetFeed.busy = false;
              WidgetFeed.nextPageToken = 1;
            } else if (!(WidgetFeed.videos.length > 0) && WidgetFeed.data.content.feedID) {
              WidgetFeed.currentFeedId = WidgetFeed.data.content.feedID;
              getFeedVideos(WidgetFeed.data.content.feedID);
            }

            if (WidgetFeed.data.content && WidgetFeed.data.content.feedID) {
              WidgetFeed.currentFeedId = WidgetFeed.data.content.feedID;
              WidgetFeed.videos = [];
              WidgetFeed.busy = false;
              WidgetFeed.nextPageToken = null;
              WidgetFeed.loadMore();
            } else if (WidgetFeed.data.content && WidgetFeed.data.content.videoID)
              Location.goTo("#/video/" + WidgetFeed.data.content.videoID);

            WidgetFeed.currentFeedId = WidgetFeed.data.content.feedID;
          }
        };
        DataStore.onUpdate().then(null, null, onUpdateCallback);

        WidgetFeed.loadMore = function () {
          if (WidgetFeed.busy) return;
          WidgetFeed.busy = true;
          if (WidgetFeed.currentFeedId && WidgetFeed.currentFeedId !== '1') {
            getFeedVideos(WidgetFeed.currentFeedId);
          }
          else {
            if (WidgetFeed.data.content.videoID)
              Location.goTo("#/video/" + WidgetFeed.data.content.videoID);
          }
        };

        WidgetFeed.safeHtml = function (html) {
            if (html) {
                var $html = $('
', {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());
            }
        };

        WidgetFeed.showDescription = function (description) {
          var _retVal = false;
          if (description) {
            description = description.trim();
            if ((description !== '

') && (description !== '

')) {
              _retVal = true;
            }
          }
          return _retVal;
        };

        WidgetFeed.openDetailsPage = function (video) {
          VideoCache.setVideo(video);
          var videoId = video.uri.split("/").pop();
          Location.goTo('#/video/' + videoId);
        };

        $rootScope.$on("ROUTE_CHANGED", function (e, data) {
          WidgetFeed.data = data;
          if (!WidgetFeed.data.design)
            WidgetFeed.data.design = {};
          if (!WidgetFeed.data.content)
            WidgetFeed.data.content = {};
          if (!(WidgetFeed.videos.length > 0) && WidgetFeed.data.content.feedID) {
            WidgetFeed.currentFeedId = WidgetFeed.data.content.feedID;
            getFeedVideos(WidgetFeed.data.content.feedID);
          }

          if (WidgetFeed.data.design.itemListBgImage) {
            $rootScope.backgroundListImage = WidgetFeed.data.design.itemListBgImage;
          }
          else{
            $rootScope.backgroundListImage="";
          }

          if (currentListLayout && (currentListLayout != WidgetFeed.data.design.itemListLayout) && view && WidgetFeed.data.content.carouselImages) {
            if (WidgetFeed.data.content.carouselImages.length)
              view._destroySlider();
            view = null;
          }
          else {
            if (view) {
              view.loadItems(WidgetFeed.data.content.carouselImages);
            }
          }

          currentListLayout = WidgetFeed.data.design.itemListLayout;

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

          buildfire.datastore.onRefresh(function () {
            WidgetFeed.videos = [];
            WidgetFeed.busy = false;
            WidgetFeed.nextPageToken = null;
            initData(true);
          });
        });

        $scope.$on("$destroy", function () {
          DataStore.clearListener();
        });

        buildfire.datastore.onRefresh(function () {
          WidgetFeed.videos = [];
          WidgetFeed.busy = false;
          WidgetFeed.nextPageToken = null;
          initData(true);
        });
      }])
})(window.angular, window.buildfire);
<|endoftext|>


<commit_before>craftEd.controller('RecsController', ['$scope', '$http', '$location', function($scope, $http, $location){

  var config = {
    headers: {
      'content-type': 'application/json'
    }
  };

  var tokens = {
    headers: {
      "access-token": window.sessionStorage.token,
      "token-type": "Bearer",
      "client": window.sessionStorage.client,
      "expiry": window.sessionStorage.expiry,
      "uid": window.sessionStorage.uid
    }
  };

  var tokensConfig = {
    headers: {
      'content-type': 'application/json',
      "access-token": window.sessionStorage.token,
      "token-type": "Bearer",
      "client": window.sessionStorage.client,
      "expiry": window.sessionStorage.expiry,
      "uid": window.sessionStorage.uid
    }
  };

  $http.get(rootUrl + '/users/:id/beer_types/rec_new', tokens)
    .then(function(response){
      $scope.allNewRecs= response.data
      $scope.rootUrl= rootUrl
    });

  $scope.selectBeer = function(newRecId){
    console.log(rootUrl +'/users/:user_id/beer_types/' + newRecId + '/tried_beer_ratings/new')
    $http.get(rootUrl +'/users/:user_id/beer_types/' + newRecId + '/tried_beer_ratings/new', tokens)
    $location.path('/rating');
  }
}]);
<commit_msg>Update new recs view and controller 2<commit_after>craftEd.controller('RecsController', ['$scope', '$http', '$location', function($scope, $http, $location){

  var config = {
    headers: {
      'content-type': 'application/json'
    }
  };

  var tokens = {
    headers: {
      "access-token": window.sessionStorage.token,
      "token-type": "Bearer",
      "client": window.sessionStorage.client,
      "expiry": window.sessionStorage.expiry,
      "uid": window.sessionStorage.uid
    }
  };

  var tokensConfig = {
    headers: {
      'content-type': 'application/json',
      "access-token": window.sessionStorage.token,
      "token-type": "Bearer",
      "client": window.sessionStorage.client,
      "expiry": window.sessionStorage.expiry,
      "uid": window.sessionStorage.uid
    }
  };

  $http.get(rootUrl + '/users/:id/beer_types/rec_new', tokens)
    .then(function(response){
      $scope.allNewRecs= response.data
      $scope.rootUrl= rootUrl
    });

  $scope.selectBeer = function(newRecId){
    $http.get(rootUrl +'/users/:user_id/beer_types/' + newRecId + '/tried_beer_ratings/new', tokens)
    $location.path('/rating');
  }
}]);
<|endoftext|>


<commit_before>'use strict';

(function (angular) {
    angular
        .module('fixedTimerPluginWidget')
        .controller('WidgetHomeCtrl', ['$scope', '$rootScope', 'Buildfire', 'DataStore', 'TAG_NAMES', 'STATUS_CODE', '$sce', '$timeout',
            function ($scope, $rootScope, Buildfire, DataStore, TAG_NAMES, STATUS_CODE, $sce, $timeout) {
                var WidgetHome = this;
                WidgetHome.data = null;
                WidgetHome.busy = false;
                WidgetHome.allItems = [];
                WidgetHome.isCounterNegative = false;
                WidgetHome.timerRunning = "stop";
                WidgetHome.counter = 5;
                WidgetHome.isPlay = false;
                WidgetHome.stopped = false;
                WidgetHome.stoppedPlus = false;
                WidgetHome.selectedTimerIndex =0;
                WidgetHome.timerObj = {'timerTime': 0, 'lastUpdatedTime': 0, 'isPause': false, 'itemId': 0, 'itemDescription': '', 'itemDefaultTimer': 5};
                WidgetHome.countdown = function () {
                    WidgetHome.timerRunning = "start";
                    if (!WidgetHome.isCounterNegative) {
                        WidgetHome.countdownNeg();
                    }
                    else {
                        WidgetHome.countdownPlus();
                    }
                };

                WidgetHome.countdownNeg = function () {
                    WidgetHome.stopped = $timeout(function () {
                        console.log($scope.counter);
                        var localStorageData = localStorage.getItem('timerObject');
                        localStorageData = localStorageData && JSON.parse(localStorageData);
                        var elapsedTimeInSec;
                        var actualTimerTime;
                        if (WidgetHome.counter <= 0) {
                            WidgetHome.isPlay = true;
                            WidgetHome.timerRunning = '';
                            WidgetHome.isCounterNegative = true;
                            WidgetHome.timerObj.timerTime = WidgetHome.counter - 1;
                            WidgetHome.timerObj.lastUpdatedTime = new Date().getTime();
                            WidgetHome.timerObj.isPause = false;
                            WidgetHome.timerObj.itemId = WidgetHome.selectedTimerIndex || (localStorageData && localStorageData.itemId);
                            WidgetHome.timerObj.itemDescription = WidgetHome.description || (localStorageData && localStorageData.itemDescription);
                            WidgetHome.timerObj.itemDefaultTimer = WidgetHome.counterSetTime || (localStorageData && localStorageData.itemDefaultTimer);
                            localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                            WidgetHome.counter = Math.abs(WidgetHome.counter - 1);
                            WidgetHome.countdownPlus();
                            return;
                        }
                        if(localStorageData && !localStorageData.isPause) {
                            elapsedTimeInSec = (new Date().getTime() - localStorageData.lastUpdatedTime)/1000;
                            actualTimerTime = Math.ceil(localStorageData.timerTime - elapsedTimeInSec);
                            WidgetHome.timerObj = {'timerTime': actualTimerTime, 'lastUpdatedTime': new Date().getTime(), 'isPause': false, 'itemId': localStorageData.itemId, 'itemDescription': localStorageData.itemDescription, 'itemDefaultTimer': localStorageData.itemDefaultTimer};
                            localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                            WidgetHome.counter = Math.abs(actualTimerTime);
                            if(actualTimerTime <= 0) {
                                WidgetHome.isPlay = true;
                                WidgetHome.timerRunning = '';
                                WidgetHome.isCounterNegative = true;
                            }
                        } else {
                            WidgetHome.timerObj.timerTime = WidgetHome.counter - 1;
                            WidgetHome.timerObj.lastUpdatedTime = new Date().getTime();
                            WidgetHome.timerObj.isPause = false;
                            WidgetHome.timerObj.itemId = WidgetHome.selectedTimerIndex;
                            WidgetHome.timerObj.itemDescription = WidgetHome.description;
                            WidgetHome.timerObj.itemDefaultTimer = WidgetHome.counterSetTime;
                            localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                            WidgetHome.counter = Math.abs(WidgetHome.counter - 1);
                        }
                        WidgetHome.countdownNeg();
                    }, 1000);
                };

                WidgetHome.countdownPlus = function () {
                    WidgetHome.stoppedPlus = $timeout(function () {
                        console.log(WidgetHome.counter);
                        var actualTimerTime;
                        var localStorageData = localStorage.getItem('timerObject');
                        localStorageData = localStorageData && JSON.parse(localStorageData);
                        var elapsedTimeInSec;
                        if(localStorageData) {
                            WidgetHome.isCounterNegative = true;
                            if(localStorageData.timerTime == 0 && localStorageData.isPause) {
                                WidgetHome.timerObj.timerTime = WidgetHome.counter - 1;
                                WidgetHome.timerObj.lastUpdatedTime = new Date().getTime();
                                WidgetHome.timerObj.isPause = false;
                                WidgetHome.timerObj.itemId = localStorageData.itemId;
                                WidgetHome.timerObj.itemDescription = localStorageData.itemDescription;
                                WidgetHome.timerObj.itemDefaultTimer = localStorageData.itemDefaultTimer;
                                localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                                WidgetHome.counter = Math.abs(WidgetHome.counter - 1);
                            } else {
                                elapsedTimeInSec = (new Date().getTime() - localStorageData.lastUpdatedTime) / 1000;
                                actualTimerTime = localStorageData.timerTime - elapsedTimeInSec;
                                WidgetHome.timerObj = {'timerTime': actualTimerTime, 'lastUpdatedTime': new Date().getTime(), 'isPause': false, 'itemId': localStorageData.itemId, 'itemDescription': localStorageData.itemDescription, 'itemDefaultTimer': localStorageData.itemDefaultTimer};
                                localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                                WidgetHome.counter = Math.abs(actualTimerTime);
                            }
                        }
//                        WidgetHome.counter++;
                        WidgetHome.countdownPlus();
                    }, 1000);
                };

                WidgetHome.silenceReset = function () {
                    WidgetHome.isPlay = false;
                    WidgetHome.stop();
                    WidgetHome.timerRunning = "stop";
                    WidgetHome.isCounterNegative = false;
                    var localStorageData = localStorage.getItem('timerObject');
                    localStorageData = localStorageData && JSON.parse(localStorageData);
                    if(localStorageData)
                        WidgetHome.counter = localStorageData.itemDefaultTimer;
                    else
                        WidgetHome.counter = WidgetHome.counterSetTime;
                    localStorage.removeItem('timerObject');
                };

                WidgetHome.stop = function () {
                    var localStorageData = localStorage.getItem('timerObject');
                    localStorageData = localStorageData && JSON.parse(localStorageData);
                    localStorageData.isPause = true;
                    localStorage.setItem('timerObject', JSON.stringify(localStorageData));
                    WidgetHome.timerRunning = "pause";
                    WidgetHome.isPlay = false;
                    if (WidgetHome.isCounterNegative) {
                        $timeout.cancel(WidgetHome.stoppedPlus);
                        $timeout.cancel(WidgetHome.stopped);
                    } else {
                        $timeout.cancel(WidgetHome.stopped);
                        $timeout.cancel(WidgetHome.stoppedPlus);
                    }
                };

                WidgetHome.resetTimer = function () {
                    WidgetHome.stop();
                    WidgetHome.timerRunning = "stop";
                    WidgetHome.isCounterNegative = false;
                    var localStorageData = localStorage.getItem('timerObject');
                    localStorageData = localStorageData && JSON.parse(localStorageData);
                    if(localStorageData)
                        WidgetHome.counter = localStorageData.itemDefaultTimer;
                    else
                        WidgetHome.counter = WidgetHome.counterSetTime;
                    localStorage.removeItem('timerObject');
                };

                var getTimerItems = function () {
                    Buildfire.spinner.show();
                    var success = function (result) {
                            WidgetHome.allItems = result;
                            console.log("----------------", WidgetHome.allItems);
                            if(WidgetHome.allItems.length) {
                                WidgetHome.selectTimer(WidgetHome.allItems[0].data.data, 0);
                            }
                            Buildfire.spinner.hide();
                        },
                        error = function () {
                            Buildfire.spinner.hide();
                            console.log("Error fetching events");
                        };
                    DataStore.search({sort:{"data.rank": 1}}, TAG_NAMES.TIMER_ITEMS).then(success, error);
                };

                WidgetHome.loadMore = function () {
                    if (WidgetHome.busy) return;
                    WidgetHome.busy = true;
                    getTimerItems();
                };

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

                /**
                 * init() function invocation to fetch previously saved user's data from datastore.
                 */
                var init = function () {

                    /*declare the device width heights*/
                    $rootScope.deviceHeight = window.innerHeight;
                    $rootScope.deviceWidth = window.innerWidth;
                    $rootScope.backgroundImage = "";

                    var success = function (result) {
                            WidgetHome.data = result.data;
                            if (!WidgetHome.data.content)
                                WidgetHome.data.content = {};
                            if (!WidgetHome.data.design)
                                WidgetHome.data.design = {};
                            $rootScope.backgroundImage = WidgetHome.data.design.backgroundImage ? WidgetHome.data.design.backgroundImage : "";
                            updateTimer();
                        }
                        , error = function (err) {
                            if (err && err.code !== STATUS_CODE.NOT_FOUND) {
                                console.error('Error while getting data', err);
                            }
                        };
                    getTimerItems();
                    DataStore.get(TAG_NAMES.TIMER_INFO).then(success, error);
                };

                function updateTimer() {
                    var elapsedTimeInSec;
                    var actualTimerTime;
                    var localStorageData = localStorage.getItem('timerObject');
                    localStorageData = localStorageData && JSON.parse(localStorageData);
                    if(localStorageData && !localStorageData.isPause) {
                        elapsedTimeInSec = (new Date().getTime() - localStorageData.lastUpdatedTime)/1000;
                        actualTimerTime = Math.ceil(localStorageData.timerTime - elapsedTimeInSec);
                        WidgetHome.timerObj = {'timerTime': actualTimerTime, 'lastUpdatedTime': new Date().getTime(), 'isPause': false, 'itemId': localStorageData.itemId, 'itemDescription': localStorageData.itemDescription, 'itemDefaultTimer': localStorageData.itemDefaultTimer};
                        localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                        WidgetHome.counter = Math.abs(actualTimerTime);
                        WidgetHome.description = localStorageData.itemDescription;
                        WidgetHome.selectedTimerIndex = localStorageData.itemId;
                        WidgetHome.counterSetTime = localStorageData.itemDefaultTimer;
                        if(actualTimerTime <= 0) {
                            WidgetHome.timerRunning = "";
                            WidgetHome.isPlay = true;
                            WidgetHome.countdownPlus();
                        }
                        else {
                            WidgetHome.timerRunning = "start";
                            WidgetHome.countdownNeg();
                        }
                    } else {
                        localStorage.removeItem('timerObject');
                    }
                }

                var onUpdateCallback = function (event) {

                    setTimeout(function () {
                        if (event) {
                            switch (event.tag) {
                                case TAG_NAMES.TIMER_INFO:
                                    WidgetHome.data = event.data;
                                    if (!WidgetHome.data.design)
                                        WidgetHome.data.design = {};
                                    if (!WidgetHome.data.content)
                                        WidgetHome.data.content = {};
                                    if (!event.data.design.backgroundImage) {
                                        $rootScope.backgroundImage = "";
                                    } else {
                                        $rootScope.backgroundImage = event.data.design.backgroundImage;
                                    }
                                    break;
                                case TAG_NAMES.TIMER_ITEMS:
                                    if (event.id && !event.data) {
                                        WidgetHome.allItems = $.grep(WidgetHome.allItems, function (e, i) {
                                            return e.id !== event.id;
                                        });
                                        WidgetHome.timerRunning="stop";
                                        WidgetHome.resetTimer();
                                        WidgetHome.selectTimer(WidgetHome.allItems[0].data.data, 0);
                                    }
                                    console.log("---------------", event);
                                    //if(event.data) {
                                    //    WidgetHome.selectTimer(event.data.data);
                                    //}
                                    //else
                                    // if(WidgetHome.allItems.length){
                                    //   WidgetHome.selectTimer(WidgetHome.allItems.data);
                                    //}
                                    $scope.$apply();
                                    break;
                            }
                            $rootScope.$digest();
                        }
                    }, 0);
                };

                $rootScope.$on('TIMER_ADDED', function (e, item) {
                    console.log("============= inside timer added", WidgetHome.allItems, item);
                    WidgetHome.allItems.push(item);
                    WidgetHome.description = item.data && item.data.data && item.data.data.description;
                    WidgetHome.counterSetTime = item.data && item.data.data && item.data.data.timer && WidgetHome.covertToMS(item.data.data.timer);
                    WidgetHome.counter = item.data && item.data.data && item.data.data.timer && WidgetHome.covertToMS(item.data.data.timer);
                    console.log("=============", WidgetHome.allItems, item, WidgetHome.allItems.lastIndexOf(item));
                    WidgetHome.selectTimer (item.data.data, WidgetHome.allItems.lastIndexOf(item))
                    $scope.$digest();
                });
                $rootScope.$on('TIMER_UPDATED', function (e, item) {
                    console.log("============= inside timer updated", WidgetHome.allItems, item);
                    WidgetHome.allItems.forEach(function (itemData, index) {
                        if (itemData.id == item.id) {
                            WidgetHome.allItems[index] = item;
                            WidgetHome.description = item.data && item.data.data && item.data.data.description;
                            WidgetHome.counterSetTime = item.data && item.data.data && item.data.data.timer && WidgetHome.covertToMS(item.data.data.timer);
                            WidgetHome.counter = item.data && item.data.data && item.data.data.timer && WidgetHome.covertToMS(item.data.data.timer);
                            WidgetHome.selectTimer(item.data.data, index)
                            return false;
                        }
                    });
//              $rootScope.$digest();
                    console.log("=============", WidgetHome.allItems, item);
                });
                $rootScope.$on('ITEMS_REARRANGE', function (e, item) {
                    console.log('inside items rearrange event==========');
                    getTimerItems();
                });

                WidgetHome.covertToMS = function (data) {

                    if (!data.hrs) {
                        data.hrs = 0;
                    }
                    else {
                        data.hrs = Number(data.hrs);
                    }
                    if (!data.min) {
                        data.min = 0;
                    }
                    else {
                        data.min = Number(data.min);
                    }
                    if (!data.sec) {
                        data.sec = 0;
                    }
                    else {
                        data.sec = Number(data.sec);
                    }
                    console.log(data);
                    var timeInMS = data.hrs * 3600 + data.min * 60 + data.sec;
                    return timeInMS;
                };
                WidgetHome.selectTimer = function (data, elementId) {
                   if(WidgetHome.timerRunning!="start" && WidgetHome.timerRunning!="") {
                        WidgetHome.selectedTimerIndex = elementId;
                        console.log(WidgetHome.counter);
                        WidgetHome.description = data.description;
                        WidgetHome.counterSetTime = WidgetHome.covertToMS(data.timer);
                        WidgetHome.counter = WidgetHome.covertToMS(data.timer);
                        WidgetHome.timerRunning = "stop";
                        WidgetHome.isPlay = false;
                    }
                };
                /**
                 * DataStore.onUpdate() is bound to listen any changes in datastore
                 */
                DataStore.onUpdate().then(null, null, onUpdateCallback);

                init();
            }]);
})(window.angular);<commit_msg>Added instanceId in localStorage to load running timer's time only for that instanceId app<commit_after>'use strict';

(function (angular) {
    angular
        .module('fixedTimerPluginWidget')
        .controller('WidgetHomeCtrl', ['$scope', '$rootScope', 'Buildfire', 'DataStore', 'TAG_NAMES', 'STATUS_CODE', '$sce', '$timeout',
            function ($scope, $rootScope, Buildfire, DataStore, TAG_NAMES, STATUS_CODE, $sce, $timeout) {
                var WidgetHome = this;
                WidgetHome.data = null;
                WidgetHome.instanceId = null;
                WidgetHome.busy = false;
                WidgetHome.allItems = [];
                WidgetHome.isCounterNegative = false;
                WidgetHome.timerRunning = "stop";
                WidgetHome.counter = 5;
                WidgetHome.isPlay = false;
                WidgetHome.stopped = false;
                WidgetHome.stoppedPlus = false;
                WidgetHome.selectedTimerIndex =0;
                WidgetHome.timerObj = {'timerTime': 0, 'lastUpdatedTime': 0, 'isPause': false, 'itemId': 0, 'itemDescription': '', 'itemDefaultTimer': 5, 'instanceId': ''};
                WidgetHome.countdown = function () {
                    WidgetHome.timerRunning = "start";
                    if (!WidgetHome.isCounterNegative) {
                        WidgetHome.countdownNeg();
                    }
                    else {
                        WidgetHome.countdownPlus();
                    }
                };

                WidgetHome.countdownNeg = function () {
                    WidgetHome.stopped = $timeout(function () {
                        console.log($scope.counter);
                        var localStorageData = localStorage.getItem('timerObject');
                        localStorageData = localStorageData && JSON.parse(localStorageData);
                        var elapsedTimeInSec;
                        var actualTimerTime;
                        if (WidgetHome.counter <= 0) {
                            WidgetHome.isPlay = true;
                            WidgetHome.timerRunning = '';
                            WidgetHome.isCounterNegative = true;
                            WidgetHome.timerObj.timerTime = WidgetHome.counter - 1;
                            WidgetHome.timerObj.lastUpdatedTime = new Date().getTime();
                            WidgetHome.timerObj.isPause = false;
                            WidgetHome.timerObj.itemId = WidgetHome.selectedTimerIndex || (localStorageData && localStorageData.itemId);
                            WidgetHome.timerObj.itemDescription = WidgetHome.description || (localStorageData && localStorageData.itemDescription);
                            WidgetHome.timerObj.itemDefaultTimer = WidgetHome.counterSetTime || (localStorageData && localStorageData.itemDefaultTimer);
                            WidgetHome.timerObj.instanceId = WidgetHome.instanceId || '';
                            localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                            WidgetHome.counter = Math.abs(WidgetHome.counter - 1);
                            WidgetHome.countdownPlus();
                            return;
                        }
                        if(localStorageData && !localStorageData.isPause) {
                            elapsedTimeInSec = (new Date().getTime() - localStorageData.lastUpdatedTime)/1000;
                            actualTimerTime = Math.ceil(localStorageData.timerTime - elapsedTimeInSec);
                            WidgetHome.timerObj = {'timerTime': actualTimerTime, 'lastUpdatedTime': new Date().getTime(), 'isPause': false, 'itemId': localStorageData.itemId, 'itemDescription': localStorageData.itemDescription, 'itemDefaultTimer': localStorageData.itemDefaultTimer, 'instanceId': WidgetHome.instanceId};
                            localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                            WidgetHome.counter = Math.abs(actualTimerTime);
                            if(actualTimerTime <= 0) {
                                WidgetHome.isPlay = true;
                                WidgetHome.timerRunning = '';
                                WidgetHome.isCounterNegative = true;
                            }
                        } else {
                            WidgetHome.timerObj.timerTime = WidgetHome.counter - 1;
                            WidgetHome.timerObj.lastUpdatedTime = new Date().getTime();
                            WidgetHome.timerObj.isPause = false;
                            WidgetHome.timerObj.itemId = WidgetHome.selectedTimerIndex;
                            WidgetHome.timerObj.itemDescription = WidgetHome.description;
                            WidgetHome.timerObj.itemDefaultTimer = WidgetHome.counterSetTime;
                            WidgetHome.timerObj.instanceId = WidgetHome.instanceId || '';
                            localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                            WidgetHome.counter = Math.abs(WidgetHome.counter - 1);
                        }
                        WidgetHome.countdownNeg();
                    }, 1000);
                };

                WidgetHome.countdownPlus = function () {
                    WidgetHome.stoppedPlus = $timeout(function () {
                        console.log(WidgetHome.counter);
                        var actualTimerTime;
                        var localStorageData = localStorage.getItem('timerObject');
                        localStorageData = localStorageData && JSON.parse(localStorageData);
                        var elapsedTimeInSec;
                        if(localStorageData) {
                            WidgetHome.isCounterNegative = true;
                            if(localStorageData.timerTime == 0 && localStorageData.isPause) {
                                WidgetHome.timerObj.timerTime = WidgetHome.counter - 1;
                                WidgetHome.timerObj.lastUpdatedTime = new Date().getTime();
                                WidgetHome.timerObj.isPause = false;
                                WidgetHome.timerObj.itemId = localStorageData.itemId;
                                WidgetHome.timerObj.itemDescription = localStorageData.itemDescription;
                                WidgetHome.timerObj.itemDefaultTimer = localStorageData.itemDefaultTimer;
                                WidgetHome.timerObj.instanceId = WidgetHome.instanceId || '';
                                localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                                WidgetHome.counter = Math.abs(WidgetHome.counter - 1);
                            } else {
                                elapsedTimeInSec = (new Date().getTime() - localStorageData.lastUpdatedTime) / 1000;
                                actualTimerTime = localStorageData.timerTime - elapsedTimeInSec;
                                WidgetHome.timerObj = {'timerTime': actualTimerTime, 'lastUpdatedTime': new Date().getTime(), 'isPause': false, 'itemId': localStorageData.itemId, 'itemDescription': localStorageData.itemDescription, 'itemDefaultTimer': localStorageData.itemDefaultTimer, 'instanceId': WidgetHome.instanceId};
                                localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                                WidgetHome.counter = Math.abs(actualTimerTime);
                            }
                        }
//                        WidgetHome.counter++;
                        WidgetHome.countdownPlus();
                    }, 1000);
                };

                WidgetHome.silenceReset = function () {
                    WidgetHome.isPlay = false;
                    WidgetHome.stop();
                    WidgetHome.timerRunning = "stop";
                    WidgetHome.isCounterNegative = false;
                    var localStorageData = localStorage.getItem('timerObject');
                    localStorageData = localStorageData && JSON.parse(localStorageData);
                    if(localStorageData)
                        WidgetHome.counter = localStorageData.itemDefaultTimer;
                    else
                        WidgetHome.counter = WidgetHome.counterSetTime;
                    localStorage.removeItem('timerObject');
                };

                WidgetHome.stop = function () {
                    var localStorageData = localStorage.getItem('timerObject');
                    localStorageData = localStorageData && JSON.parse(localStorageData);
                    localStorageData.isPause = true;
                    localStorage.setItem('timerObject', JSON.stringify(localStorageData));
                    WidgetHome.timerRunning = "pause";
                    WidgetHome.isPlay = false;
                    if (WidgetHome.isCounterNegative) {
                        $timeout.cancel(WidgetHome.stoppedPlus);
                        $timeout.cancel(WidgetHome.stopped);
                    } else {
                        $timeout.cancel(WidgetHome.stopped);
                        $timeout.cancel(WidgetHome.stoppedPlus);
                    }
                };

                WidgetHome.resetTimer = function () {
                    WidgetHome.stop();
                    WidgetHome.timerRunning = "stop";
                    WidgetHome.isCounterNegative = false;
                    var localStorageData = localStorage.getItem('timerObject');
                    localStorageData = localStorageData && JSON.parse(localStorageData);
                    if(localStorageData)
                        WidgetHome.counter = localStorageData.itemDefaultTimer;
                    else
                        WidgetHome.counter = WidgetHome.counterSetTime;
                    localStorage.removeItem('timerObject');
                };

                var getTimerItems = function () {
                    Buildfire.spinner.show();
                    var success = function (result) {
                            WidgetHome.allItems = result;
                            console.log("----------------", WidgetHome.allItems);
                            if(WidgetHome.allItems.length) {
                                WidgetHome.selectTimer(WidgetHome.allItems[0].data.data, 0);
                            }
                            Buildfire.spinner.hide();
                        },
                        error = function () {
                            Buildfire.spinner.hide();
                            console.log("Error fetching events");
                        };
                    DataStore.search({sort:{"data.rank": 1}}, TAG_NAMES.TIMER_ITEMS).then(success, error);
                };

                WidgetHome.loadMore = function () {
                    if (WidgetHome.busy) return;
                    WidgetHome.busy = true;
                    getTimerItems();
                };

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

                /**
                 * init() function invocation to fetch previously saved user's data from datastore.
                 */
                var init = function () {

                    /*declare the device width heights*/
                    $rootScope.deviceHeight = window.innerHeight;
                    $rootScope.deviceWidth = window.innerWidth;
                    $rootScope.backgroundImage = "";

                    var success = function (result) {
                            WidgetHome.data = result.data;
                            if (!WidgetHome.data.content)
                                WidgetHome.data.content = {};
                            if (!WidgetHome.data.design)
                                WidgetHome.data.design = {};
                            $rootScope.backgroundImage = WidgetHome.data.design.backgroundImage ? WidgetHome.data.design.backgroundImage : "";
                            Buildfire.getContext(function (err, data) {
                               if(data) {
                                   console.log('get context data is:::::::::::::::::', data);
                                   WidgetHome.instanceId = data.instanceId;
                               }
                                updateTimer();
                            });
                        }
                        , error = function (err) {
                            if (err && err.code !== STATUS_CODE.NOT_FOUND) {
                                console.error('Error while getting data', err);
                            }
                        };
                    getTimerItems();
                    DataStore.get(TAG_NAMES.TIMER_INFO).then(success, error);
                };

                function updateTimer() {
                    var elapsedTimeInSec;
                    var actualTimerTime;
                    var localStorageData = localStorage.getItem('timerObject');
                    localStorageData = localStorageData && JSON.parse(localStorageData);
                    if(localStorageData && !localStorageData.isPause && WidgetHome.instanceId == localStorageData.instanceId) {
                        elapsedTimeInSec = (new Date().getTime() - localStorageData.lastUpdatedTime)/1000;
                        actualTimerTime = Math.ceil(localStorageData.timerTime - elapsedTimeInSec);
                        WidgetHome.timerObj = {'timerTime': actualTimerTime, 'lastUpdatedTime': new Date().getTime(), 'isPause': false, 'itemId': localStorageData.itemId, 'itemDescription': localStorageData.itemDescription, 'itemDefaultTimer': localStorageData.itemDefaultTimer, 'instanceId': WidgetHome.instanceId};
                        localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                        WidgetHome.counter = Math.abs(actualTimerTime);
                        WidgetHome.description = localStorageData.itemDescription;
                        WidgetHome.selectedTimerIndex = localStorageData.itemId;
                        WidgetHome.counterSetTime = localStorageData.itemDefaultTimer;
                        if(actualTimerTime <= 0) {
                            WidgetHome.timerRunning = "";
                            WidgetHome.isPlay = true;
                            WidgetHome.countdownPlus();
                        }
                        else {
                            WidgetHome.timerRunning = "start";
                            WidgetHome.countdownNeg();
                        }
                    } else {
                        localStorage.removeItem('timerObject');
                    }
                }

                var onUpdateCallback = function (event) {

                    setTimeout(function () {
                        if (event) {
                            switch (event.tag) {
                                case TAG_NAMES.TIMER_INFO:
                                    WidgetHome.data = event.data;
                                    if (!WidgetHome.data.design)
                                        WidgetHome.data.design = {};
                                    if (!WidgetHome.data.content)
                                        WidgetHome.data.content = {};
                                    if (!event.data.design.backgroundImage) {
                                        $rootScope.backgroundImage = "";
                                    } else {
                                        $rootScope.backgroundImage = event.data.design.backgroundImage;
                                    }
                                    break;
                                case TAG_NAMES.TIMER_ITEMS:
                                    if (event.id && !event.data) {
                                        WidgetHome.allItems = $.grep(WidgetHome.allItems, function (e, i) {
                                            return e.id !== event.id;
                                        });
                                        WidgetHome.timerRunning="stop";
                                        WidgetHome.resetTimer();
                                        WidgetHome.selectTimer(WidgetHome.allItems[0].data.data, 0);
                                    }
                                    console.log("---------------", event);
                                    //if(event.data) {
                                    //    WidgetHome.selectTimer(event.data.data);
                                    //}
                                    //else
                                    // if(WidgetHome.allItems.length){
                                    //   WidgetHome.selectTimer(WidgetHome.allItems.data);
                                    //}
                                    $scope.$apply();
                                    break;
                            }
                            $rootScope.$digest();
                        }
                    }, 0);
                };

                $rootScope.$on('TIMER_ADDED', function (e, item) {
                    console.log("============= inside timer added", WidgetHome.allItems, item);
                    WidgetHome.allItems.push(item);
                    WidgetHome.description = item.data && item.data.data && item.data.data.description;
                    WidgetHome.counterSetTime = item.data && item.data.data && item.data.data.timer && WidgetHome.covertToMS(item.data.data.timer);
                    WidgetHome.counter = item.data && item.data.data && item.data.data.timer && WidgetHome.covertToMS(item.data.data.timer);
                    console.log("=============", WidgetHome.allItems, item, WidgetHome.allItems.lastIndexOf(item));
                    WidgetHome.selectTimer (item.data.data, WidgetHome.allItems.lastIndexOf(item))
                    $scope.$digest();
                });
                $rootScope.$on('TIMER_UPDATED', function (e, item) {
                    console.log("============= inside timer updated", WidgetHome.allItems, item);
                    WidgetHome.allItems.forEach(function (itemData, index) {
                        if (itemData.id == item.id) {
                            WidgetHome.allItems[index] = item;
                            WidgetHome.description = item.data && item.data.data && item.data.data.description;
                            WidgetHome.counterSetTime = item.data && item.data.data && item.data.data.timer && WidgetHome.covertToMS(item.data.data.timer);
                            WidgetHome.counter = item.data && item.data.data && item.data.data.timer && WidgetHome.covertToMS(item.data.data.timer);
                            WidgetHome.selectTimer(item.data.data, index)
                            return false;
                        }
                    });
//              $rootScope.$digest();
                    console.log("=============", WidgetHome.allItems, item);
                });
                $rootScope.$on('ITEMS_REARRANGE', function (e, item) {
                    console.log('inside items rearrange event==========');
                    getTimerItems();
                });

                WidgetHome.covertToMS = function (data) {

                    if (!data.hrs) {
                        data.hrs = 0;
                    }
                    else {
                        data.hrs = Number(data.hrs);
                    }
                    if (!data.min) {
                        data.min = 0;
                    }
                    else {
                        data.min = Number(data.min);
                    }
                    if (!data.sec) {
                        data.sec = 0;
                    }
                    else {
                        data.sec = Number(data.sec);
                    }
                    console.log(data);
                    var timeInMS = data.hrs * 3600 + data.min * 60 + data.sec;
                    return timeInMS;
                };
                WidgetHome.selectTimer = function (data, elementId) {
                   if(WidgetHome.timerRunning!="start" && WidgetHome.timerRunning!="") {
                        WidgetHome.selectedTimerIndex = elementId;
                        console.log(WidgetHome.counter);
                        WidgetHome.description = data.description;
                        WidgetHome.counterSetTime = WidgetHome.covertToMS(data.timer);
                        WidgetHome.counter = WidgetHome.covertToMS(data.timer);
                        WidgetHome.timerRunning = "stop";
                        WidgetHome.isPlay = false;
                    }
                };
                /**
                 * DataStore.onUpdate() is bound to listen any changes in datastore
                 */
                DataStore.onUpdate().then(null, null, onUpdateCallback);

                init();
            }]);
})(window.angular);<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var Campaign = require('../models/campaign');
var moment = require('moment');

/* GET campaigns default get route page. */
router.get('/', function (req, res) {

    Campaign.find({}, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to pull the campaigns ' + err});
        }

        else{
        res.status(201).json({ success: true,result:result, message: 'Successfully pulled the Campaigns ' });
        }
    })

});

router.post('/', function (req, res) {
    console.log(req.body);

    if(!req.body.name || !req.body.type || !req.body.description || !req.body.enabled || !req.body.expiring
        || !req.body.image || !req.body.tags )
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }
    else
    {
        const campaign = new Campaign({
            name: req.body.name,
            type: req.body.type,
            description: req.body.description,
            enabled : req.body.enabled,
            expiring : req.body.expiring,
            image : req.body.image,
            thumbnail:req.body.thumbnail,
            tags : req.body.tags,
            wantin: req.body.wantin
        });

        console.log('Saving Campaign :  ' + req.body.name);

        campaign.save(function(err){
            if(err)
            {
                console.log(err);
                return res.status(400).json({ success: false, message: 'An error occurred on trying to save campaign, please try again later ' + err});
            }

            res.status(201).json({ success: true, message: 'Successfully created Campaign ' + req.body.name });
        })
    }

});

/*
 Like Campaign

 */
router.post('/likeCampaign', function(req,res){
    console.log(req.body);

    if(!req.body.email || !req.body.campaignid)
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }
    else{
    console.log( moment.utc().format('YYYY-MM-DD HH:mm:ss'));
    Campaign.findOneAndUpdate({_id:req.body.campaignid}, { $push: { likes : {"email" : req.body.email, "timestamp" : moment.utc().format('YYYY-MM-DD HH:mm:ss') } } }, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to update campaign ' + err});
        }

        res.status(201).json({ success: true,result:result, message: 'Successfully added users to the list of user likes for this campaign ' });
    })
    }
});

router.post('/shareCampaign', function(req,res){
    console.log(req.body);

    if(!req.body.email || !req.body.campaignid)
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }
    else{

    Campaign.findOneAndUpdate({_id:req.body.campaignid}, { $push: { share : {"email" : req.body.email, "timestamp" : moment.utc().format('YYYY-MM-DD HH:mm:ss') } } }, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to update the share for this campaign ' + err});
        }
        else{
        res.status(201).json({ success: true,result:result, message: 'Successfully added users to the list of user share for this campaign ' });
        }
    })
    }

});

router.post('/wantinCampaign', function(req,res){
    console.log(req.body);

    if(!req.body.email || !req.body.campaignid)
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }
    else{
    Campaign.findOneAndUpdate({_id:req.body.campaignid}, { $push: { wantin : {"email" : req.body.email, "timestamp" : moment.utc().format('YYYY-MM-DD HH:mm:ss') } } }, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to update the share for this campaign ' + err});
        }

        res.status(201).json({ success: true,result:result, message: 'Successfully added users to the list of wantin for this campaign ' });
    })
    }

});

//Update Campaign details
router.put('/', function(req, res){
    console.log(req.body);

    if(!req.body.field || !req.body.value || !req.body.newValue){
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }

    var field = req.body.field;
    var value = req.body.value;
    Campaign.findOne({field :value }, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to pull the campaigns ' + err});
        }

    })
});

//Get the top trending campaigns on Shoppa
router.get('/getTopCampaigns', function (req, res) {
    console.log(req);

    Campaign.find({likes: { $gte: 10 }}, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to pull the campaigns ' + err});
        }
        else{

        res.status(200).json({ success: true,result:result, message: 'Successfully created Campaign ' + req.body.name });
        }
    })

});

/*
Get campaigns that would displayed on user timeline
*/
router.post('/getUserCampaigns', function (req, res) {

    console.log(req.body);

    if(!req.body.email)
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }
    else
    {
   //Get all campaigns that user has not liked or opted in to
            Campaign.find({"likes" : { "$not": { "$all": [req.body.email] } }}, function (err, result) {
                if (err) {
                    console.log(err);
                    return res.status(400).json({
                        success: false,
                        message: 'An error occurred on trying to pull the campaigns ' + err
                    });
                }

                res.status(200).json({success: true, result: result, message: 'Successfully pulled the Campaigns '});
            }).limit(3);
        }
        });

/*
Get Campaigns liked by User
*/
router.post('/userCampaignLikes', function (req, res) {

     console.log(req.body);

    if(!req.body.email)
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }

     Campaign.find({"likes":{"$all": [req.body.email]}}, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to pull the campaigns ' + err});
        }

        res.status(200).json({ success: true,result:result, message: 'Successfully pulled the Campaigns ' });
    })

});

/*
Get expiring campaigns by number of days

*/

router.get('/getExpiringCampaigns', function (req, res) {

    res.sendStatus(200);

});

module.exports = router;
<commit_msg>Testing Scenarios<commit_after>var express = require('express');
var router = express.Router();
var Campaign = require('../models/campaign');
var moment = require('moment');

/* GET campaigns default get route page. */
router.get('/', function (req, res) {

    Campaign.find({}, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to pull the campaigns ' + err});
        }

        else{
        res.status(201).json({ success: true,result:result, message: 'Successfully pulled the Campaigns ' });
        }
    })

});

router.post('/', function (req, res) {
    console.log(req.body);

    if(!req.body.name || !req.body.type || !req.body.description || !req.body.enabled || !req.body.expiring
        || !req.body.image || !req.body.tags )
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }
    else
    {
        const campaign = new Campaign({
            name: req.body.name,
            type: req.body.type,
            description: req.body.description,
            enabled : req.body.enabled,
            expiring : req.body.expiring,
            image : req.body.image,
            thumbnail:req.body.thumbnail,
            tags : req.body.tags,
            wantin: req.body.wantin
        });

        console.log('Saving Campaign :  ' + req.body.name);

        campaign.save(function(err){
            if(err)
            {
                console.log(err);
                return res.status(400).json({ success: false, message: 'An error occurred on trying to save campaign, please try again later ' + err});
            }

            res.status(201).json({ success: true, message: 'Successfully created Campaign ' + req.body.name });
        })
    }

});

/*
 Like Campaign

 */
router.post('/likeCampaign', function(req,res){
    console.log(req.body);

    if(!req.body.email || !req.body.campaignid)
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }
    else{
    console.log( moment.utc().format('YYYY-MM-DD HH:mm:ss'));
    Campaign.findOneAndUpdate({_id:req.body.campaignid}, { $push: { likes : {"email" : req.body.email, "timestamp" : moment.utc().format('YYYY-MM-DD HH:mm:ss') } } }, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to update campaign ' + err});
        }

        res.status(201).json({ success: true,result:result, message: 'Successfully added users to the list of user likes for this campaign ' });
    })
    }
});

router.post('/shareCampaign', function(req,res){
    console.log(req.body);

    if(!req.body.email || !req.body.campaignid)
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }
    else{

    Campaign.findOneAndUpdate({_id:req.body.campaignid}, { $push: { share : {"email" : req.body.email, "timestamp" : moment.utc().format('YYYY-MM-DD HH:mm:ss') } } }, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to update the share for this campaign ' + err});
        }
        else{
        res.status(201).json({ success: true,result:result, message: 'Successfully added users to the list of user share for this campaign ' });
        }
    })
    }

});

router.post('/wantinCampaign', function(req,res){
    console.log(req.body);

    if(!req.body.email || !req.body.campaignid)
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }
    else{
    Campaign.findOneAndUpdate({_id:req.body.campaignid}, { $push: { wantin : {"email" : req.body.email, "timestamp" : moment.utc().format('YYYY-MM-DD HH:mm:ss') } } }, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to update the share for this campaign ' + err});
        }

        res.status(201).json({ success: true,result:result, message: 'Successfully added users to the list of wantin for this campaign ' });
    })
    }

});

//Update Campaign details
router.put('/', function(req, res){
    console.log(req.body);

    if(!req.body.field || !req.body.value || !req.body.newValue){
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }

    var field = req.body.field;
    var value = req.body.value;
    Campaign.findOne({field :value }, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to pull the campaigns ' + err});
        }

    })
});

//Get the top trending campaigns on Shoppa
router.get('/getTopCampaigns', function (req, res) {
    console.log(req);

    Campaign.find({likes: { $gte: 10 }}, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to pull the campaigns ' + err});
        }
        else{

        res.status(200).json({ success: true,result:result, message: 'Successfully created Campaign ' + req.body.name });
        }
    })

});

/*
Get campaigns that would displayed on user timeline
*/
router.post('/getUserCampaigns', function (req, res) {

    console.log(req.body);

    if(!req.body.email)
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }
    else
    {
   //Get all campaigns that user has not liked or opted in to
            Campaign.find({"likes" : { "$not": { "$all": [req.body.email] } }}, function (err, result) {
                if (err) {
                    console.log(err);
                    return res.status(400).json({
                        success: false,
                        message: 'An error occurred on trying to pull the campaigns ' + err
                    });
                }

                res.status(200).json({success: true, result: result, message: 'Successfully pulled the Campaigns '});
            }).limit(20);
        }
        });

/*
Get Campaigns liked by User
*/
router.post('/userCampaignLikes', function (req, res) {

     console.log(req.body);

    if(!req.body.email)
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }

     Campaign.find({"likes":{"$all": [req.body.email]}}, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to pull the campaigns ' + err});
        }

        res.status(200).json({ success: true,result:result, message: 'Successfully pulled the Campaigns ' });
    })

});

/*
Get expiring campaigns by number of days

*/

router.get('/getExpiringCampaigns', function (req, res) {

    res.sendStatus(200);

});

module.exports = router;
<|endoftext|>


<commit_before>angular.module("omniFactories")
	.factory("Orderbook",["$http","DExOrder","DExOffer","Transaction","Account","Wallet","ModalManager","MIN_MINER_FEE", "WHOLE_UNIT", "SATOSHI_UNIT",
		function OrderbookFactory($http,DExOrder,DExOffer,Transaction,Account,Wallet,ModalManager,MIN_MINER_FEE,WHOLE_UNIT,SATOSHI_UNIT){
			var Orderbook = function(tradingPair){
				var self = this;

				self.initialize = function(){
					self.tradingPair=tradingPair;
					self.title = "Trade " + tradingPair.selling.name + " for " + tradingPair.desired.name;
					self.active = true;
					self.disabled = !self.active;
					self.buyOrder = {};
					self.sellOrder = {};

					self.selling = tradingPair.selling;
					self.desired = tradingPair.desired;

					// TODO:  list only addresses with balance > 0
					self.addresses = Wallet.addresses.filter(function(address){
						return ((address.privkey && address.privkey.length == 58) || address.pubkey)
					});
					self.buyAddresses = self.addresses.filter(function(address){
						return address.getBalance(self.desired.propertyid) > 0;
					});
					self.sellAddresses = self.addresses.filter(function(address){
						return address.getBalance(self.selling.propertyid) > 0;
					});

					self.buyBook = []
					self.sellBook = []

					$http.get("/v1/markets/"+tradingPair.desired.propertyid+"/"+tradingPair.selling.propertyid)
						.then(function(response){
							if(response.status != "200" || response.data.status !="OK")
								return // handle errors

							var offers = response.data.orderbook
							offers.forEach(function(offerData){
								var order = null;
								var offer = new DExOffer(offerData);
								self.buyBook.forEach(function(orderData){
									if(orderData.price.eq(offer.price)){
										order = orderData;
										order.addOffer(offer)
									}

								})

								if(order == null){
									order = new DExOrder(offer);
									self.buyBook.push(order);
								}

							});

							self.buyBook.sort(function(a, b) {
					          var priceA = a.price;
					          var priceB = b.price;
					          return priceA.gt(priceB) ? -1 : priceA.lt(priceB) ? 1 : 0;
					        });
						})
					$http.get("/v1/markets/"+tradingPair.selling.propertyid+"/"+tradingPair.desired.propertyid)
						.then(function(response){
							if(response.status != "200" || response.data.status !="OK")
								return // handle errors

							var offers = response.data.orders
							offers.forEach(function(offerData){
								var order = null;
								var offer = new DExOffer(offerData);
								self.sellBook.forEach(function(orderData){
									if(orderData.price.eq(offer.price)){
										order = orderData;
										order.addOffer(offer)
									}
								})
								if(order == null){
									order = new DExOrder(offer);
									self.sellBook.push(order);
								}

							});

							self.sellBook.sort(function(a, b) {
					          var priceA = a.price;
					          var priceB = b.price;
					          return priceA.lt(priceB) ? -1 : priceA.gt(priceB) ? 1 : 0;
					        });
						})

				};

				self.setBuyAddress = function(address){
					$scope.orderbook.buyOrder.address = address;
				};

				self.setSellAddress = function(address){
					$scope.orderbook.sellOrder.address = address;
				};

				self.updateAmount = function(offer) {
					offer.amounts.desired= offer.amounts.selling * offer.price
				}

				self.submitBuyOffer = function(){
					// TODO: Validations
					var fee = Account.settings.minerFee || MIN_MINER_FEE;
					var dexOffer = new Transaction(25,self.buyOrder.address,fee,{
							transaction_version:0,
							propertyidforsale:self.tradingPair.desired.propertyid,
							amountforsale: self.tradingPair.desired.divisible ? new Big(self.sellOrder.amounts.desired).times(SATOSHI_UNIT).valueOf() : new Big(self.sellOrder.amounts.desired).valueOf(),
							propertiddesired:self.tradingPair.selling.propertyid,
							amountdesired: self.tradingPair.selling.divisible ? new Big(self.sellOrder.amounts.selling).times(SATOSHI_UNIT).valueOf() : new Big(self.sellOrder.amounts.selling).times(SATOSHI_UNIT).valueOf()
						});
					ModalManager.openConfirmationModal({
						dataTemplate: '/views/modals/partials/dex_offer.html',
						scope: {
							title:"Confirm DEx Transaction",
							address:self.buyOrder.address,
							saleCurrency:self.tradingPair.desired.propertyid,
							saleAmount:self.buyOrder.amounts.desired,
							desiredCurrency:self.tradingPair.selling.propertyid,
							desiredAmount:self.buyOrder.amounts.selling,
							totalCost:dexOffer.totalCost,
							action:"Add",
							confirmText: "Create Transaction",
							successMessage: "Your order was placed successfully"
						},
						transaction:dexOffer
					})
				};

				self.submitSellOffer = function(){
					// TODO: Validations
					var fee = Account.settings.minerFee || MIN_MINER_FEE;
					var dexOffer = new Transaction(25,self.sellOrder.address,fee,{
							transaction_version:0,
							propertyidforsale:self.tradingPair.selling.propertyid,
							amountforsale: self.tradingPair.selling.divisible ? new Big(self.sellOrder.amounts.selling).times(SATOSHI_UNIT).valueOf() : new Big(self.sellOrder.amounts.selling).valueOf(),
							propertiddesired:self.tradingPair.desired.propertyid,
							amountdesired: self.tradingPair.desired.divisible ? new Big(self.sellOrder.amounts.desired).times(SATOSHI_UNIT).valueOf() : new Big(self.sellOrder.amounts.desired).times(SATOSHI_UNIT).valueOf()
						});
					ModalManager.openConfirmationModal({
						dataTemplate: '/views/modals/partials/dex_offer.html',
						scope: {
							title:"Confirm DEx Transaction",
							address:self.sellOrder.address,
							saleCurrency:self.tradingPair.selling.propertyid,
							saleAmount:self.sellOrder.amounts.selling,
							desiredCurrency:self.tradingPair.desired.propertyid,
							desiredAmount:self.sellOrder.amounts.desired,
							totalCost:dexOffer.totalCost,
							action:"Add",
							confirmText: "Create Transaction",
							successMessage: "Your order was placed successfully"
						},
						transaction:dexOffer
					})
				};

				self.getBalance = function(address, assetId){
					return address && address.getBalance(assetId) ? new Big(address.getBalance(assetId)).times(WHOLE_UNIT).valueOf() : 0;
				}

				self.initialize();
			}

			return Orderbook;
		}]);<commit_msg>Initialize addresses<commit_after>angular.module("omniFactories")
	.factory("Orderbook",["$http","DExOrder","DExOffer","Transaction","Account","Wallet","ModalManager","MIN_MINER_FEE", "WHOLE_UNIT", "SATOSHI_UNIT",
		function OrderbookFactory($http,DExOrder,DExOffer,Transaction,Account,Wallet,ModalManager,MIN_MINER_FEE,WHOLE_UNIT,SATOSHI_UNIT){
			var Orderbook = function(tradingPair){
				var self = this;

				self.initialize = function(){
					self.tradingPair=tradingPair;
					self.title = "Trade " + tradingPair.selling.name + " for " + tradingPair.desired.name;
					self.active = true;
					self.disabled = !self.active;
					self.buyOrder = {};
					self.sellOrder = {};

					self.selling = tradingPair.selling;
					self.desired = tradingPair.desired;

					// TODO:  list only addresses with balance > 0
					self.addresses = Wallet.addresses.filter(function(address){
						return ((address.privkey && address.privkey.length == 58) || address.pubkey)
					});
					self.buyAddresses = self.addresses.filter(function(address){
						return address.getBalance(self.desired.propertyid) > 0;
					});
					self.buyOrder.address = self.buyAddresses.length > 0 ? self.buyAddresses[0] : undefined;
					self.sellAddresses = self.addresses.filter(function(address){
						return address.getBalance(self.selling.propertyid) > 0;
					});
					self.sellOrder.address = self.sellAddresses.length > 0 ? self.sellAddresses[0] : undefined;

					self.buyBook = []
					self.sellBook = []

					$http.get("/v1/markets/"+tradingPair.desired.propertyid+"/"+tradingPair.selling.propertyid)
						.then(function(response){
							if(response.status != "200" || response.data.status !="OK")
								return // handle errors

							var offers = response.data.orderbook
							offers.forEach(function(offerData){
								var order = null;
								var offer = new DExOffer(offerData);
								self.buyBook.forEach(function(orderData){
									if(orderData.price.eq(offer.price)){
										order = orderData;
										order.addOffer(offer)
									}

								})

								if(order == null){
									order = new DExOrder(offer);
									self.buyBook.push(order);
								}

							});

							self.buyBook.sort(function(a, b) {
					          var priceA = a.price;
					          var priceB = b.price;
					          return priceA.gt(priceB) ? -1 : priceA.lt(priceB) ? 1 : 0;
					        });
						})
					$http.get("/v1/markets/"+tradingPair.selling.propertyid+"/"+tradingPair.desired.propertyid)
						.then(function(response){
							if(response.status != "200" || response.data.status !="OK")
								return // handle errors

							var offers = response.data.orders
							offers.forEach(function(offerData){
								var order = null;
								var offer = new DExOffer(offerData);
								self.sellBook.forEach(function(orderData){
									if(orderData.price.eq(offer.price)){
										order = orderData;
										order.addOffer(offer)
									}
								})
								if(order == null){
									order = new DExOrder(offer);
									self.sellBook.push(order);
								}

							});

							self.sellBook.sort(function(a, b) {
					          var priceA = a.price;
					          var priceB = b.price;
					          return priceA.lt(priceB) ? -1 : priceA.gt(priceB) ? 1 : 0;
					        });
						})

				};

				self.setBuyAddress = function(address){
					$scope.orderbook.buyOrder.address = address;
				};

				self.setSellAddress = function(address){
					$scope.orderbook.sellOrder.address = address;
				};

				self.updateAmount = function(offer) {
					offer.amounts.desired= offer.amounts.selling * offer.price
				}

				self.submitBuyOffer = function(){
					// TODO: Validations
					var fee = Account.settings.minerFee || MIN_MINER_FEE;
					var dexOffer = new Transaction(25,self.buyOrder.address,fee,{
							transaction_version:0,
							propertyidforsale:self.tradingPair.desired.propertyid,
							amountforsale: self.tradingPair.desired.divisible ? new Big(self.sellOrder.amounts.desired).times(SATOSHI_UNIT).valueOf() : new Big(self.sellOrder.amounts.desired).valueOf(),
							propertiddesired:self.tradingPair.selling.propertyid,
							amountdesired: self.tradingPair.selling.divisible ? new Big(self.sellOrder.amounts.selling).times(SATOSHI_UNIT).valueOf() : new Big(self.sellOrder.amounts.selling).times(SATOSHI_UNIT).valueOf()
						});
					ModalManager.openConfirmationModal({
						dataTemplate: '/views/modals/partials/dex_offer.html',
						scope: {
							title:"Confirm DEx Transaction",
							address:self.buyOrder.address,
							saleCurrency:self.tradingPair.desired.propertyid,
							saleAmount:self.buyOrder.amounts.desired,
							desiredCurrency:self.tradingPair.selling.propertyid,
							desiredAmount:self.buyOrder.amounts.selling,
							totalCost:dexOffer.totalCost,
							action:"Add",
							confirmText: "Create Transaction",
							successMessage: "Your order was placed successfully"
						},
						transaction:dexOffer
					})
				};

				self.submitSellOffer = function(){
					// TODO: Validations
					var fee = Account.settings.minerFee || MIN_MINER_FEE;
					var dexOffer = new Transaction(25,self.sellOrder.address,fee,{
							transaction_version:0,
							propertyidforsale:self.tradingPair.selling.propertyid,
							amountforsale: self.tradingPair.selling.divisible ? new Big(self.sellOrder.amounts.selling).times(SATOSHI_UNIT).valueOf() : new Big(self.sellOrder.amounts.selling).valueOf(),
							propertiddesired:self.tradingPair.desired.propertyid,
							amountdesired: self.tradingPair.desired.divisible ? new Big(self.sellOrder.amounts.desired).times(SATOSHI_UNIT).valueOf() : new Big(self.sellOrder.amounts.desired).times(SATOSHI_UNIT).valueOf()
						});
					ModalManager.openConfirmationModal({
						dataTemplate: '/views/modals/partials/dex_offer.html',
						scope: {
							title:"Confirm DEx Transaction",
							address:self.sellOrder.address,
							saleCurrency:self.tradingPair.selling.propertyid,
							saleAmount:self.sellOrder.amounts.selling,
							desiredCurrency:self.tradingPair.desired.propertyid,
							desiredAmount:self.sellOrder.amounts.desired,
							totalCost:dexOffer.totalCost,
							action:"Add",
							confirmText: "Create Transaction",
							successMessage: "Your order was placed successfully"
						},
						transaction:dexOffer
					})
				};

				self.getBalance = function(address, assetId){
					return address && address.getBalance(assetId) ? new Big(address.getBalance(assetId)).times(WHOLE_UNIT).valueOf() : 0;
				}

				self.initialize();
			}

			return Orderbook;
		}]);<|endoftext|>