<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({}, 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;
                        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.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);
                });

                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);
                    }
                };
                /**
                 * DataStore.onUpdate() is bound to listen any changes in datastore
                 */
                DataStore.onUpdate().then(null, null, onUpdateCallback);

                init();
            }]);
})(window.angular);<commit_msg>Timer set updation for app switching<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.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({}, 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.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);
                });

                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);
                    }
                };
                /**
                 * DataStore.onUpdate() is bound to listen any changes in datastore
                 */
                DataStore.onUpdate().then(null, null, onUpdateCallback);

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


<commit_before>function generatedOrder () {
    var orderNow = [];;
    orderNow[0] = [];
    orderNow[1] = [];
    orderNow[2] = [];

    for (var i = 0; i < Ext.getCmp('columnPos0').items.items.length; i++) {
      orderNow[0][i] = Ext.getCmp('columnPos0').items.items[i].dasInsUid;
    }
    for (var i = 0; i < Ext.getCmp('columnPos1').items.items.length; i++) {
      orderNow[1][i] = Ext.getCmp('columnPos1').items.items[i].dasInsUid;
    }
    for (var i = 0; i < Ext.getCmp('columnPos2').items.items.length; i++) {
      orderNow[2][i] = Ext.getCmp('columnPos2').items.items[i].dasInsUid;
    }

    return orderNow;
}

Ext.onReady(function(){

  Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

  // create some portlet tools using built in Ext tool ids
  var tools = [{
    id:'gear',
    handler: function(){
      Ext.Msg.alert('Message', 'The Settings tool was clicked.');
    }
  },{
    id:'close',
    handler: function(e, target, panel){
        panel.ownerCt.remove(panel, true);
    }
  }];

  var tbDashboard = new Ext.Toolbar({
    height: 30,
    items: [
      {
        xtype: 'tbbutton',
        text : _("ID_DASHBOARD_BTNCOLUMNS3"),
        handler : function(a) {
          Ext.MessageBox.show({
            msg: _('ID_LOADING'),
            width:300,
            wait:true,
            waitConfig: {interval:200},
            animEl: 'mb7'
          });

          var vp = Ext.getCmp('viewportDashboard');
          var pd = Ext.getCmp('portalDashboard');

          pd.items.items[0].columnWidth = 0.33;
          pd.items.items[1].columnWidth = 0.33;
          pd.items.items[2].columnWidth = 0.33;
          pd.doLayout();

          tbDashboard.items.items[0].setDisabled(true);
          tbDashboard.items.items[1].setDisabled(false);

          var orderNow = generatedOrder();
          Ext.Ajax.request({
            params: {
              positionCol0: Ext.encode(orderNow[0]),
              positionCol1: Ext.encode(orderNow[1]),
              positionCol2: Ext.encode(orderNow[2]),
              columns: 3
            },
            url: 'dashboard/saveOrderDashlet',
              success: function (res) {
                var data = Ext.decode(res.responseText);
                if (data.success) {
                  Ext.MessageBox.hide();
                }
              },
              failure: function () {
            	  Ext.MessageBox.alert(_('ID_ERROR'), _('ID_IMPORTING_ERROR'));
              }
          });
        }
      },
      {
        xtype: 'tbbutton',
        text : _("ID_DASHBOARD_BTNCOLUMNS2"),
        handler : function(a) {
          Ext.MessageBox.show({
            msg: _('ID_LOADING'),
            progressText: 'Saving...',
            width:300,
            wait:true,
            waitConfig: {interval:200},
            animEl: 'mb7'
          });

          var vp = Ext.getCmp('viewportDashboard');
          var pd = Ext.getCmp('portalDashboard');

          var dashletMove = new Array();
          for (var i = 0; i < Ext.getCmp('columnPos2').items.items.length; i++) {
            dashletMove.push(Ext.getCmp('columnPos2').items.items[i].id);
          }
          var flag = 0;
          for (var i = 0; i < dashletMove.length; i++) {
            Ext.getCmp('columnPos' + flag).add(Ext.getCmp(dashletMove[i]));
            if (flag == 0) {
              flag = 1;
            } else {
              flag = 0;
            }
          };

          pd.items.items[0].columnWidth = 0.49;
          pd.items.items[1].columnWidth = 0.49;
          pd.items.items[2].columnWidth = 0.01;
          pd.doLayout();

          tbDashboard.items.items[0].setDisabled(false);
          tbDashboard.items.items[1].setDisabled(true);

          var orderNow = generatedOrder();
          Ext.Ajax.request({
            params: {
              positionCol0: Ext.encode(orderNow[0]),
              positionCol1: Ext.encode(orderNow[1]),
              positionCol2: Ext.encode(orderNow[2]),
              columns: 2
            },
            url: 'dashboard/saveOrderDashlet',
              success: function (res) {
                var data = Ext.decode(res.responseText);
                if (data.success) {
                  Ext.MessageBox.hide();
                }
              },
              failure: function () {
                Ext.MessageBox.alert(_('ID_ERROR'), _('ID_IMPORTING_ERROR'));
              }
          });
        }
      }
    ]
  });

  var viewport = new Ext.Viewport({
    layout:'fit',
    name : 'viewportDashboard',
    id   : 'viewportDashboard',
    items:[{
      xtype:'portal',
      region:'center',
      margins:'35 5 5 0',
      tbar: tbDashboard,
      name : 'portalDashboard',
      id   : 'portalDashboard',
      items:[{
        columnWidth:.33,
        id   : 'columnPos0',
        style:'padding:10px 0 10px 10px',
        items:[]
      },{
        columnWidth:.33,
        id   : 'columnPos1',
        style:'padding:10px 0 10px 10px',
        items:[]
      },{
        columnWidth:.33,
        id   : 'columnPos2',
        style:'padding:10px',
        items:[]
      }],
      listeners: {
        'drop': function(e) {
          var orderNow = generatedOrder();
          Ext.MessageBox.show({
            msg: _('ID_LOADING'),
            progressText: 'Saving...',
            width:300,
            wait:true,
            waitConfig: {interval:200},
            animEl: 'mb7'
          });

          if (tbDashboard.items.items[0].disabled == true) {
            var colum = 3;
          } else {
            var colum = 2;
          }
          Ext.Ajax.request({
            params: {
              positionCol0: Ext.encode(orderNow[0]),
              positionCol1: Ext.encode(orderNow[1]),
              positionCol2: Ext.encode(orderNow[2]),
              columns: colum
            },
            url: 'dashboard/saveOrderDashlet',
              success: function (res) {
                var data = Ext.decode(res.responseText);
                if (data.success) {
                  Ext.MessageBox.hide();
                }
              },
              failure: function () {
                Ext.MessageBox.alert(_('ID_ERROR'), _('ID_IMPORTING_ERROR'));
              }
          });
        }
      }
    }]
  });

  var pd = Ext.getCmp('portalDashboard');
  var con = 0;
  for (var i = 0; i < dashletsInstances.length; i++) {
    for(var d = 0; d < dashletsInstances[i].length; d++) {

      var np = new Ext.ux.Portlet({
        title: dashletsInstances[i][d].DAS_TITLE,
        index: con,
        indicei: i,
        indiced: d,
        dasInsUid : dashletsInstances[i][d].DAS_INS_UID,
        html: 'Gauge Placeholder',
        listeners: {
          'resize': function(p, w, h) {
            var template = new Ext.XTemplate(dashletsInstances[p.indicei][p.indiced].DAS_XTEMPLATE).apply({
              id: p.dasInsUid,
              page: 'dashboard/renderDashletInstance',
              width: w - 12,
              random: Math.floor(Math.random() * 1000000)
            })
            p.update(template);
          }
        }
      });
      pd.items.items[i].add(np);

      con++;
    }
  }

  pd.doLayout();

  if (dashletsColumns == 2) {
    tbDashboard.items.items[0].setDisabled(false);
    tbDashboard.items.items[1].setDisabled(true);

    var pd = Ext.getCmp('portalDashboard');

    pd.items.items[0].columnWidth = 0.49;
    pd.items.items[1].columnWidth = 0.49;
    pd.items.items[2].columnWidth = 0.01;
    pd.doLayout();
  } else {
    var pd = Ext.getCmp('portalDashboard');

    pd.items.items[0].columnWidth = 0.33;
    pd.items.items[1].columnWidth = 0.33;
    pd.items.items[2].columnWidth = 0.33;
    pd.doLayout();

    tbDashboard.items.items[0].setDisabled(true);
    tbDashboard.items.items[1].setDisabled(false);
  }
});
<commit_msg>BUG 10084 I added a functionality to save order the dashlet IMPROVEMENT<commit_after>function generatedOrder () {
    var orderNow = [];;
    orderNow[0] = [];
    orderNow[1] = [];
    orderNow[2] = [];

    for (var i = 0; i < Ext.getCmp('columnPos0').items.items.length; i++) {
      orderNow[0][i] = Ext.getCmp('columnPos0').items.items[i].dasInsUid;
    }
    for (var i = 0; i < Ext.getCmp('columnPos1').items.items.length; i++) {
      orderNow[1][i] = Ext.getCmp('columnPos1').items.items[i].dasInsUid;
    }
    for (var i = 0; i < Ext.getCmp('columnPos2').items.items.length; i++) {
      orderNow[2][i] = Ext.getCmp('columnPos2').items.items[i].dasInsUid;
    }

    return orderNow;
}

Ext.onReady(function(){

  Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

  // create some portlet tools using built in Ext tool ids
  var tools = [{
    id:'gear',
    handler: function(){
      Ext.Msg.alert('Message', 'The Settings tool was clicked.');
    }
  },{
    id:'close',
    handler: function(e, target, panel){
        panel.ownerCt.remove(panel, true);
    }
  }];

  var tbDashboard = new Ext.Toolbar({
    height: 30,
    items: [
      {
        xtype: 'tbbutton',
        text : _("ID_DASHBOARD_BTNCOLUMNS3"),
        handler : function(a) {
          Ext.MessageBox.show({
            msg: _('ID_LOADING'),
            width:300,
            wait:true,
            waitConfig: {interval:200},
            animEl: 'mb7'
          });

          var vp = Ext.getCmp('viewportDashboard');
          var pd = Ext.getCmp('portalDashboard');

          pd.items.items[0].columnWidth = 0.33;
          pd.items.items[1].columnWidth = 0.33;
          pd.items.items[2].columnWidth = 0.33;
          pd.doLayout();

          tbDashboard.items.items[0].setDisabled(true);
          tbDashboard.items.items[1].setDisabled(false);

          var orderNow = generatedOrder();
          Ext.Ajax.request({
            params: {
              positionCol0: Ext.encode(orderNow[0]),
              positionCol1: Ext.encode(orderNow[1]),
              positionCol2: Ext.encode(orderNow[2]),
              columns: 3
            },
            url: 'dashboard/saveOrderDashlet',
              success: function (res) {
                var data = Ext.decode(res.responseText);
                if (data.success) {
                  Ext.MessageBox.hide();
                }
              },
              failure: function () {
            	  Ext.MessageBox.alert(_('ID_ERROR'), _('ID_IMPORTING_ERROR'));
              }
          });
        }
      },
      {
        xtype: 'tbbutton',
        text : _("ID_DASHBOARD_BTNCOLUMNS2"),
        handler : function(a) {
          Ext.MessageBox.show({
            msg: _('ID_LOADING'),
            progressText: _('ID_SAVING'),
            width:300,
            wait:true,
            waitConfig: {interval:200},
            animEl: 'mb7'
          });

          var vp = Ext.getCmp('viewportDashboard');
          var pd = Ext.getCmp('portalDashboard');

          var dashletMove = new Array();
          for (var i = 0; i < Ext.getCmp('columnPos2').items.items.length; i++) {
            dashletMove.push(Ext.getCmp('columnPos2').items.items[i].id);
          }
          var flag = 0;
          for (var i = 0; i < dashletMove.length; i++) {
            Ext.getCmp('columnPos' + flag).add(Ext.getCmp(dashletMove[i]));
            if (flag == 0) {
              flag = 1;
            } else {
              flag = 0;
            }
          };

          pd.items.items[0].columnWidth = 0.49;
          pd.items.items[1].columnWidth = 0.49;
          pd.items.items[2].columnWidth = 0.01;
          pd.doLayout();

          tbDashboard.items.items[0].setDisabled(false);
          tbDashboard.items.items[1].setDisabled(true);

          var orderNow = generatedOrder();
          Ext.Ajax.request({
            params: {
              positionCol0: Ext.encode(orderNow[0]),
              positionCol1: Ext.encode(orderNow[1]),
              positionCol2: Ext.encode(orderNow[2]),
              columns: 2
            },
            url: 'dashboard/saveOrderDashlet',
              success: function (res) {
                var data = Ext.decode(res.responseText);
                if (data.success) {
                  Ext.MessageBox.hide();
                }
              },
              failure: function () {
                Ext.MessageBox.alert(_('ID_ERROR'), _('ID_IMPORTING_ERROR'));
              }
          });
        }
      }
    ]
  });

  var viewport = new Ext.Viewport({
    layout:'fit',
    name : 'viewportDashboard',
    id   : 'viewportDashboard',
    items:[{
      xtype:'portal',
      region:'center',
      margins:'35 5 5 0',
      tbar: tbDashboard,
      name : 'portalDashboard',
      id   : 'portalDashboard',
      items:[{
        columnWidth:.33,
        id   : 'columnPos0',
        style:'padding:10px 0 10px 10px',
        items:[]
      },{
        columnWidth:.33,
        id   : 'columnPos1',
        style:'padding:10px 0 10px 10px',
        items:[]
      },{
        columnWidth:.33,
        id   : 'columnPos2',
        style:'padding:10px',
        items:[]
      }],
      listeners: {
        'drop': function(e) {
          var orderNow = generatedOrder();
          Ext.MessageBox.show({
            msg: _('ID_LOADING'),
            progressText: _('ID_SAVING'),
            width:300,
            wait:true,
            waitConfig: {interval:200},
            animEl: 'mb7'
          });

          if (tbDashboard.items.items[0].disabled == true) {
            var colum = 3;
          } else {
            var colum = 2;
          }
          Ext.Ajax.request({
            params: {
              positionCol0: Ext.encode(orderNow[0]),
              positionCol1: Ext.encode(orderNow[1]),
              positionCol2: Ext.encode(orderNow[2]),
              columns: colum
            },
            url: 'dashboard/saveOrderDashlet',
              success: function (res) {
                var data = Ext.decode(res.responseText);
                if (data.success) {
                  Ext.MessageBox.hide();
                }
              },
              failure: function () {
                Ext.MessageBox.alert(_('ID_ERROR'), _('ID_IMPORTING_ERROR'));
              }
          });
        }
      }
    }]
  });

  var pd = Ext.getCmp('portalDashboard');
  var con = 0;
  for (var i = 0; i < dashletsInstances.length; i++) {
    for(var d = 0; d < dashletsInstances[i].length; d++) {

      var np = new Ext.ux.Portlet({
        title: dashletsInstances[i][d].DAS_TITLE,
        index: con,
        indicei: i,
        indiced: d,
        dasInsUid : dashletsInstances[i][d].DAS_INS_UID,
        html: 'Gauge Placeholder',
        listeners: {
          'resize': function(p, w, h) {
            var template = new Ext.XTemplate(dashletsInstances[p.indicei][p.indiced].DAS_XTEMPLATE).apply({
              id: p.dasInsUid,
              page: 'dashboard/renderDashletInstance',
              width: w - 12,
              random: Math.floor(Math.random() * 1000000)
            })
            p.update(template);
          }
        }
      });
      pd.items.items[i].add(np);

      con++;
    }
  }

  pd.doLayout();

  if (dashletsColumns == 2) {
    tbDashboard.items.items[0].setDisabled(false);
    tbDashboard.items.items[1].setDisabled(true);

    var pd = Ext.getCmp('portalDashboard');

    pd.items.items[0].columnWidth = 0.49;
    pd.items.items[1].columnWidth = 0.49;
    pd.items.items[2].columnWidth = 0.01;
    pd.doLayout();
  } else {
    var pd = Ext.getCmp('portalDashboard');

    pd.items.items[0].columnWidth = 0.33;
    pd.items.items[1].columnWidth = 0.33;
    pd.items.items[2].columnWidth = 0.33;
    pd.doLayout();

    tbDashboard.items.items[0].setDisabled(true);
    tbDashboard.items.items[1].setDisabled(false);
  }
});
<|endoftext|>


<commit_before>NGApp.config(['$routeProvider', function($routeProvider) {
	$routeProvider
		.when('/support', {
			action: 'support',
			controller: 'SupportCtrl',
			templateUrl: 'assets/view/support.html',
			title: 'Support',
			reloadOnSearch: false
		})
		.when('/chat', {
			action: 'chat',
			controller: 'ChatCtrl',
			templateUrl: 'assets/view/chat.html',
			title: 'Chat'
		})
		.when('/chat/:room', {
			action: 'chat',
			controller: 'ChatCtrl',
			templateUrl: 'assets/view/chat.html',
			title: 'Chat'
		})
		.when('/support/phone', {
			action: 'support',
			controller: 'SupportPhoneCtrl',
			templateUrl: 'assets/view/support-phone.html',
			title: 'Support',
			reloadOnSearch: false
		});
}]);

NGApp.controller('ChatCtrl', function($scope, $rootScope, $routeParams, SocketService, AccountService) {
	$scope.room = $routeParams.room || 'lobby';

	SocketService.listen('chat.' + $scope.room, $scope)
		.on('message', function(d) {
			console.log(d);
		});
	/*
	$scope.send = function() {
		//SocketService.socket.emit('chat.' + $scope.room, 'message');
		SocketService.socket.emit('event.message', {
			url: 'api/'
		});
	};
	*/
});

NGApp.controller('SideTicketsCtrl', function($scope, $rootScope, $location, TicketService, TicketViewService, AccountService) {

	$scope.params = { status: 'open' };

	var getTickets = function() {
		if (!AccountService || !AccountService.user || !AccountService.user.permissions) {
			return;
		}
		TicketService.shortlist( $scope.params, function(tickets) {
			TicketViewService.scope.tickets = tickets.results;
		});
	};

	if (!TicketViewService.scope.tickets) {
		getTickets();
	}

	$scope.loadTicket = function( id_support ){
		TicketViewService.setViewTicket( id_support );
	}

	$rootScope.$watch('supportMessages', function(newValue, oldValue) {
		if (!newValue) {
			return;
		}
		if (!oldValue || newValue.count != oldValue.count || newValue.timestamp != oldValue.timestamp ) {
			getTickets();
		}
	}, true);
});

NGApp.controller( 'SideTicketCtrl', function($scope, $rootScope, $routeParams, $timeout, TicketService, TicketViewService, SocketService, MainNavigationService ) {

	var id_support = null;

	if (typeof TicketViewService.scope.viewTicket == 'string') {
		id_support = TicketViewService.scope.viewTicket;
	} else {
		id_support = TicketViewService.scope.viewTicket.id;
	}

	TicketViewService.sideInfo.setTicket( id_support );

	var loadData = function(){
		if( TicketViewService.sideInfo.load() ){
			$scope.isLoading = true;
		}
	}

	// $scope.$watchCollection( 'ticket', function( newValue, oldValue ) {
	// 	if( newValue && newValue.total && !$rootScope.supportToggled ){
	// 		$timeout( function(){
	// 			$rootScope.supportToggled = true;
	// 		}, 300 );
	// 	}
	// } );

	$scope.isLoading = false;

	$scope.loadMoreMessages = function(){
		loadData()
	}

	$rootScope.$on( 'triggerTicketInfoUpdated', function(e, data) {
		console.log('$scope.ticket',$scope.ticket);
		console.log('data',data);
		if( $scope.ticket.id_support != data.id_support ){
			$scope.ticket = data;
		} else {
			console.log('update messages');
			$scope.ticket.messages = data.messages;
			$timeout( function(){
				$scope.ticket.has_more = data.has_more;
				$scope.ticket.loaded = data.loaded;
				$scope.ticket.page = data.page;
				$scope.ticket.total = data.total;
				console.log('update everything else');
			 }, 300 );
		}

		$scope.isLoading = false;
		if( !$rootScope.supportToggled ){
			$timeout( function(){ $rootScope.supportToggled = true; }, 300 );
		}
	} );

	$rootScope.$on( 'loadMoreMessages', function(e, data) {
		$scope.loadMoreMessages();
	} );

	var socketStuff = function(){
		SocketService.listen('ticket.' + id_support, TicketViewService.scope ).on('message', function(d) {
			if( d.guid ){
				for ( var x in TicketViewService.sideInfo.data.messages ) {
					if ( TicketViewService.sideInfo.data.messages[x].guid == d.guid ) {
						if( TicketViewService.sideInfo.data.messages[x].sending ){
							TicketViewService.sideInfo.data.messages[x] = d;
							console.log('updated status');
						}
						console.log('message already added!');
						return;
					}
				}
			}
			TicketViewService.sideInfo.add_message( d );
		});
	}

	$rootScope.$on( 'triggerViewTicket', function(e, ticket) {
		if( ticket.id_support != TicketViewService.sideInfo.id_support ){
			TicketViewService.sideInfo.setTicket( 0 );
			TicketViewService.sideInfo.setTicket( ticket.id_support );
			loadData();
			socketStuff();
		}
	} );

	$scope.send = TicketViewService.send;
	loadData();
	socketStuff();

} );

NGApp.controller('SideSupportCtrl', function($scope, $rootScope, TicketViewService) {
	TicketViewService.scope = $scope;
	$scope.setViewTicket = TicketViewService.setViewTicket;
});

NGApp.controller('SideSupportPexCardCtrl', function( $scope, StaffPayInfoService, PexCardService ) {

	$scope.add_funds = function(){
		if( $scope.ticket && $scope.ticket.pexcard && $scope.ticket.pexcard.id_pexcard ){
			if( $scope.form.$invalid ){
				App.alert( 'Please fill in all required fields' );
				$scope.submitted = true;
				return;
			}
			$scope.pexcard.id_pexcard = $scope.ticket.pexcard.id_pexcard;
			$scope.isAdding = true;
			PexCardService.add_funds( $scope.pexcard, function( data ){
				if( data.error ){
					App.alert( data.error);
					$scope.isAdding = false;
					return;
				} else {
					$scope.isAdding = false;
					$scope.flash.setMessage( 'Funds Added!' );
					$scope.pexcard = {};
					$scope.isLoadingBalance = true;
					setTimeout( function(){ $scope.current_balanced(); }, 3000 );
				}
			} );
		} else {
			App.alert( 'Oops, it seems the driver doesn\'t have a PexCard!' );
		}
	}

	$scope.current_balanced = function(){
		if( $scope.ticket && $scope.ticket.pexcard && $scope.ticket.pexcard.card_serial ){

			$scope.isLoadingBalance = true;

			PexCardService.pex_id( $scope.ticket.pexcard.card_serial,
				function( json ){
					$scope.isLoadingBalance = false;
					if( json.id ){
						$scope.card = json;
					} else {
						$scope.flash.setMessage( json.error, 'error' );
					}
				}
			);
		} else {
			App.alert( 'Oops, it seems the driver doesn\'t have a PexCard!' );
		}
	}

} );

NGApp.controller('SupportPhoneCtrl', function( $scope, $rootScope, StaffService, CallService, MainNavigationService, TwilioService) {

	$scope.call = { staff : '', to : 'customer', _to: CallService.call_to() };
	$scope.sms = { staff : '', to : 'customer', _to: CallService.call_to() };

	$scope.$watch( 'call.staff', function( newValue, oldValue, scope ) {
		$scope.call.phone = newValue.phone;
	}	);

	$scope.$watch( 'sms.staff', function( newValue, oldValue, scope ) {
		$scope.sms.phone = newValue.phone;
		$scope.sms.name = newValue.name;
	}	);

	StaffService.phones( function( response ){
		$scope.staff = response;
	} );

	$scope.formCallSending = false;
	$scope.formSMSSending = false;

	$scope.reset = function(){
		$scope.call.phone = '';
		$scope.sms.phone = '';
		$scope.sms.message = '';
	}

	$scope.sms.send = function(){

		if( $scope.formSMS.$invalid ){
			$scope.formSMSSubmitted = true;
			return;
		}

		$scope.formSMSSending = true;
		CallService.send_sms( $scope.sms, function( json ){
			$scope.formSMSSending = false;
			if( json.success ){
				MainNavigationService.link( '/ticket/' + json.success);
				if( $scope.complete ){
					$scope.complete();
				}
				$scope.reset();
			} else {
				App.alert( json.error );
			}
		} );
	}

	$scope.call.make = function(){
		if( $scope.formCall.$invalid ){
			$scope.formCallSubmitted = true;
			return;
		}
		$scope.formCallSending = true;
		CallService.make_call( $scope.call, function( json ){
			$scope.formCallSending = false;
			if( json.success ){
				App.alert( json.success );
				$scope.reset();
			} else {
				App.alert( json.error );
			}
		} );
	}

	$scope.call.voip = function() {
		TwilioService.call($scope.call.phone);
		App.dialog.close();
	};

	// Reset stuff when calling from modal
	$rootScope.$on('callText', function(e, num) {
		$scope.reset();
		$scope.call.phone = num;
		$scope.sms.phone = num;
	} );

} );

NGApp.controller('SupportCtrl', function($scope, $rootScope, $timeout, TicketService, TicketViewService, CallService) {

	$scope.ticketparams = {
		status: 'open'
	};

	$scope.callparams = {
		status: ['in-progress','ringing'],
		limit: 5,
		today: true
	};

	$scope.closeTicket = function( id_support ){
		TicketService.openClose( id_support, function() { update(); } );
	}

	$rootScope.$watch('supportMessages', function(newValue, oldValue) {
		if (!newValue) {
			return;
		}
		if (!oldValue || newValue.count != oldValue.count || newValue.timestamp != oldValue.timestamp ) {
			update();
		}
	}, true);

	var update = function(){
		TicketService.list($scope.ticketparams, function(d) {
			$scope.lotsoftickets = d.results;
			TicketViewService.scope.tickets = d.results;
		});
	}

	CallService.list($scope.callparams, function(d) {
		$scope.calls = d.results;
	});

	update();
});
<commit_msg>partial #6135<commit_after>NGApp.config(['$routeProvider', function($routeProvider) {
	$routeProvider
		.when('/support', {
			action: 'support',
			controller: 'SupportCtrl',
			templateUrl: 'assets/view/support.html',
			title: 'Support',
			reloadOnSearch: false
		})
		.when('/chat', {
			action: 'chat',
			controller: 'ChatCtrl',
			templateUrl: 'assets/view/chat.html',
			title: 'Chat'
		})
		.when('/chat/:room', {
			action: 'chat',
			controller: 'ChatCtrl',
			templateUrl: 'assets/view/chat.html',
			title: 'Chat'
		})
		.when('/support/phone', {
			action: 'support',
			controller: 'SupportPhoneCtrl',
			templateUrl: 'assets/view/support-phone.html',
			title: 'Support',
			reloadOnSearch: false
		});
}]);

NGApp.controller('ChatCtrl', function($scope, $rootScope, $routeParams, SocketService, AccountService) {
	$scope.room = $routeParams.room || 'lobby';

	SocketService.listen('chat.' + $scope.room, $scope)
		.on('message', function(d) {
			console.log(d);
		});
	/*
	$scope.send = function() {
		//SocketService.socket.emit('chat.' + $scope.room, 'message');
		SocketService.socket.emit('event.message', {
			url: 'api/'
		});
	};
	*/
});

NGApp.controller('SideTicketsCtrl', function($scope, $rootScope, $location, TicketService, TicketViewService, AccountService) {

	$scope.params = { status: 'open' };

	var getTickets = function() {
		if (!AccountService || !AccountService.user || !AccountService.user.permissions) {
			return;
		}
		TicketService.shortlist( $scope.params, function(tickets) {
			TicketViewService.scope.tickets = tickets.results;
		});
	};

	if (!TicketViewService.scope.tickets) {
		getTickets();
	}

	$scope.loadTicket = function( id_support ){
		TicketViewService.setViewTicket( id_support );
	}

	$rootScope.$watch('supportMessages', function(newValue, oldValue) {
		if (!newValue) {
			return;
		}
		if (!oldValue || newValue.count != oldValue.count || newValue.timestamp != oldValue.timestamp ) {
			getTickets();
		}
	}, true);
});

NGApp.controller( 'SideTicketCtrl', function($scope, $rootScope, $routeParams, $timeout, TicketService, TicketViewService, SocketService, MainNavigationService ) {

	var id_support = null;

	if (typeof TicketViewService.scope.viewTicket == 'string') {
		id_support = TicketViewService.scope.viewTicket;
	} else {
		id_support = TicketViewService.scope.viewTicket.id;
	}

	TicketViewService.sideInfo.setTicket( id_support );

	var loadData = function(){
		if( TicketViewService.sideInfo.load() ){
			$scope.isLoading = true;
		}
	}

	// $scope.$watchCollection( 'ticket', function( newValue, oldValue ) {
	// 	if( newValue && newValue.total && !$rootScope.supportToggled ){
	// 		$timeout( function(){
	// 			$rootScope.supportToggled = true;
	// 		}, 300 );
	// 	}
	// } );

	$scope.isLoading = false;

	$scope.loadMoreMessages = function(){
		loadData()
	}

	$rootScope.$on( 'triggerTicketInfoUpdated', function(e, data) {
		console.log('$scope.ticket',$scope.ticket);
		console.log('data',data);
		if( $scope.ticket.id_support != data.id_support ){
			$scope.ticket = data;
		} else {
			console.log('update messages');
			$scope.ticket.messages = data.messages;
			$timeout( function(){
				$scope.ticket.has_more = data.has_more;
				$scope.ticket.loaded = data.loaded;
				$scope.ticket.page = data.page;
				$scope.ticket.total = data.total;
				console.log('update everything else');
			 }, 300 );
		}

		$scope.isLoading = false;
		if( !$rootScope.supportToggled ){
			$timeout( function(){ $rootScope.supportToggled = true; }, 300 );
		}
	} );

	$rootScope.$on( 'loadMoreMessages', function(e, data) {
		$scope.loadMoreMessages();
	} );

	var socketStuff = function(){
		SocketService.listen('ticket.' + id_support, TicketViewService.scope ).on('message', function(d) {
			if( d.guid ){
				for ( var x in TicketViewService.sideInfo.data.messages ) {
					if ( TicketViewService.sideInfo.data.messages[x].guid == d.guid ) {
						// if( TicketViewService.sideInfo.data.messages[x].sending ){
							// TicketViewService.sideInfo.data.messages[x] = d;
							// console.log('updated status');
						// }
						console.log('message already added!');
						return;
					}
				}
			}
			TicketViewService.sideInfo.add_message( d );
		});
	}

	$rootScope.$on( 'triggerViewTicket', function(e, ticket) {
		if( ticket.id_support != TicketViewService.sideInfo.id_support ){
			TicketViewService.sideInfo.setTicket( 0 );
			TicketViewService.sideInfo.setTicket( ticket.id_support );
			loadData();
			socketStuff();
		}
	} );

	$scope.send = TicketViewService.send;
	loadData();
	socketStuff();

} );

NGApp.controller('SideSupportCtrl', function($scope, $rootScope, TicketViewService) {
	TicketViewService.scope = $scope;
	$scope.setViewTicket = TicketViewService.setViewTicket;
});

NGApp.controller('SideSupportPexCardCtrl', function( $scope, StaffPayInfoService, PexCardService ) {

	$scope.add_funds = function(){
		if( $scope.ticket && $scope.ticket.pexcard && $scope.ticket.pexcard.id_pexcard ){
			if( $scope.form.$invalid ){
				App.alert( 'Please fill in all required fields' );
				$scope.submitted = true;
				return;
			}
			$scope.pexcard.id_pexcard = $scope.ticket.pexcard.id_pexcard;
			$scope.isAdding = true;
			PexCardService.add_funds( $scope.pexcard, function( data ){
				if( data.error ){
					App.alert( data.error);
					$scope.isAdding = false;
					return;
				} else {
					$scope.isAdding = false;
					$scope.flash.setMessage( 'Funds Added!' );
					$scope.pexcard = {};
					$scope.isLoadingBalance = true;
					setTimeout( function(){ $scope.current_balanced(); }, 3000 );
				}
			} );
		} else {
			App.alert( 'Oops, it seems the driver doesn\'t have a PexCard!' );
		}
	}

	$scope.current_balanced = function(){
		if( $scope.ticket && $scope.ticket.pexcard && $scope.ticket.pexcard.card_serial ){

			$scope.isLoadingBalance = true;

			PexCardService.pex_id( $scope.ticket.pexcard.card_serial,
				function( json ){
					$scope.isLoadingBalance = false;
					if( json.id ){
						$scope.card = json;
					} else {
						$scope.flash.setMessage( json.error, 'error' );
					}
				}
			);
		} else {
			App.alert( 'Oops, it seems the driver doesn\'t have a PexCard!' );
		}
	}

} );

NGApp.controller('SupportPhoneCtrl', function( $scope, $rootScope, StaffService, CallService, MainNavigationService, TwilioService) {

	$scope.call = { staff : '', to : 'customer', _to: CallService.call_to() };
	$scope.sms = { staff : '', to : 'customer', _to: CallService.call_to() };

	$scope.$watch( 'call.staff', function( newValue, oldValue, scope ) {
		$scope.call.phone = newValue.phone;
	}	);

	$scope.$watch( 'sms.staff', function( newValue, oldValue, scope ) {
		$scope.sms.phone = newValue.phone;
		$scope.sms.name = newValue.name;
	}	);

	StaffService.phones( function( response ){
		$scope.staff = response;
	} );

	$scope.formCallSending = false;
	$scope.formSMSSending = false;

	$scope.reset = function(){
		$scope.call.phone = '';
		$scope.sms.phone = '';
		$scope.sms.message = '';
	}

	$scope.sms.send = function(){

		if( $scope.formSMS.$invalid ){
			$scope.formSMSSubmitted = true;
			return;
		}

		$scope.formSMSSending = true;
		CallService.send_sms( $scope.sms, function( json ){
			$scope.formSMSSending = false;
			if( json.success ){
				MainNavigationService.link( '/ticket/' + json.success);
				if( $scope.complete ){
					$scope.complete();
				}
				$scope.reset();
			} else {
				App.alert( json.error );
			}
		} );
	}

	$scope.call.make = function(){
		if( $scope.formCall.$invalid ){
			$scope.formCallSubmitted = true;
			return;
		}
		$scope.formCallSending = true;
		CallService.make_call( $scope.call, function( json ){
			$scope.formCallSending = false;
			if( json.success ){
				App.alert( json.success );
				$scope.reset();
			} else {
				App.alert( json.error );
			}
		} );
	}

	$scope.call.voip = function() {
		TwilioService.call($scope.call.phone);
		App.dialog.close();
	};

	// Reset stuff when calling from modal
	$rootScope.$on('callText', function(e, num) {
		$scope.reset();
		$scope.call.phone = num;
		$scope.sms.phone = num;
	} );

} );

NGApp.controller('SupportCtrl', function($scope, $rootScope, $timeout, TicketService, TicketViewService, CallService) {

	$scope.ticketparams = {
		status: 'open'
	};

	$scope.callparams = {
		status: ['in-progress','ringing'],
		limit: 5,
		today: true
	};

	$scope.closeTicket = function( id_support ){
		TicketService.openClose( id_support, function() { update(); } );
	}

	$rootScope.$watch('supportMessages', function(newValue, oldValue) {
		if (!newValue) {
			return;
		}
		if (!oldValue || newValue.count != oldValue.count || newValue.timestamp != oldValue.timestamp ) {
			update();
		}
	}, true);

	var update = function(){
		TicketService.list($scope.ticketparams, function(d) {
			$scope.lotsoftickets = d.results;
			TicketViewService.scope.tickets = d.results;
		});
	}

	CallService.list($scope.callparams, function(d) {
		$scope.calls = d.results;
	});

	update();
});
<|endoftext|>


<commit_before><commit_msg>Rendered people list<commit_after>import React from 'react';
import {ScrollView, FlatList} from 'react-native';
import PersonItem from './PersonItem';

export default ({ids}) => (
  <ScrollView contentInsetAdjustmentBehavior="automatic">
    <FlatList
      data={ids}
      keyExtractor={({id}) => id}
      renderItem={({id}) => <PersonItem id={id} />} />
  </ScrollView>
);
<|endoftext|>