var page_location = (window.location.pathname).substring((window.location.pathname).lastIndexOf('/') + 1);
angular.module('chatController', []).controller('chatCtrl', function(dataHtml, $timeout, $ionicPlatform, $cordovaLocalNotification, $cordovaMedia, $cordovaBadge, $focusTest, $state, $window, $ionicLoading, $cordovaToast, $ionicScrollDelegate, $cordovaFileTransfer, $cordovaImagePicker, $cordovaKeyboard, $ionicPopup, $sce, $stateParams, $location, $timeout, $scope, $interval, $rootScope, $http, $window, $interval, Login, Lineitems, Rooms, Users, Sounds, Auth, Chatsettings, Userchatstatuses, external, pouchDB, $cordovaActionSheet, $cordovaCamera, $cordovaInAppBrowser, $compile) {
    $scope.dataChatHtml = {};
    $scope.firstLoadWithParamRomm = true;
    $scope.loadChatHandle = false;
    $scope.pendingId = parseInt(getParameterByName('pendingId'));
    $scope.renderTemplateData = function() {
        $scope.getChatSetting();
    }
    $scope.openByGetTemplate = function(style) {
        $ionicLoading.show({
            template: templateLoading
        });
        $timeout(function() {
            switch (style) {
                case 'popupChooseStatusChat':
                dataHtml.getTemplate('templates/dashboard/chat/chatStatusSettingmodal.tpl').success(function(results) {
                    $scope.dataChatHtml.popupChooseStatusChat = results;
                    appDialogToggle('open', '#popupChooseStatusChat');
                    $ionicLoading.hide();
                });
                break;
                case 'popupChatFilter':
                dataHtml.getTemplate('templates/dashboard/chat/popup/popupChatFilter.tpl').success(function(results) {
                    $scope.dataChatHtml.popupChatFilter = results;
                    $timeout(function() {
                        $scope.showTarget('#popupChatFilter');
                        $ionicLoading.hide();
                    }, 1)
                });
                break;
                case 'popupChatDetailSetting':
                dataHtml.getTemplate('templates/dashboard/chat/popup/popupChatDetailSetting.tpl').success(function(results) {
                    $scope.dataChatHtml.popupChatDetailSetting = results;
                    $timeout(function() {
                        $scope.showTarget('#popupChatDetailSetting');
                        $ionicLoading.hide();
                    }, 1)
                });
                break;
                case 'popupChatDetailFile':
                dataHtml.getTemplate('templates/dashboard/chat/popup/popupChatDetailFile.tpl').success(function(results) {
                    $scope.dataChatHtml.popupChatDetailFile = results;
                    $timeout(function() {
                        $scope.showTarget('#popupChatDetailFile');
                        $ionicLoading.hide();
                    }, 1)
                });
                break;
            }
        }, 500);
    }
    $scope.infoRooms = {};
    $scope.openPopupRoomsOption = function(id) {
        $scope.infoRooms.id = parseInt(id);
        $scope.editRooms(id);
        appDialogToggle('open', '#popupSettingRoomOption')
    }
    $scope.autocompleteList = {};
    $scope.filterUserRoom = function(query, style) {
        var returnValue = {
            items: []
        };
        var listIdArray = style == 'add' ? $scope.autocompleteList.refferedUserAdd : $scope.autocompleteList.refferedUserEdit;
        $scope.allUser.forEach(function(item) {
            if (listIdArray.indexOf(item.id) < 0) {
                if (item.screen_name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                    returnValue.items.push(item);
                } else if (item.id.toString().indexOf(query) > -1) {
                    returnValue.items.push(item);
                }
            }
        });
        return returnValue;
    };
    $scope.initialUser = [];
    $scope.initialUserEdit = [];
    $scope.setValueForUser = function(modelValue) {
        for (var i = 0; i < $scope.allUser.length; i++) {
            if ($scope.allUser[i].id == modelValue) {
                return $scope.allUser[i];
            }
        }
        return {};
    };
    $scope.onSelectUser = function(callback, style) {
        if (style == 'add') {
            if ($scope.addRoomsData.selectusers.indexOf(callback.item) < 0) $scope.addRoomsData.selectusers.push(callback.item);
        } else {
            if (callback.item && callback.item.id) {
                var index = _.findIndex($scope.editRoomsData.selectusers, {
                    id: callback.item.id.toString()
                });
                if (index < 0) $scope.editRoomsData.selectusers.push(callback.item);
            }
        }
    }
    $scope.onRemoveUser = function(callback, style) {
        if (style == 'add') {
            var index = $scope.addRoomsData.selectusers.indexOf(callback.item);
            $scope.addRoomsData.selectusers.splice(index, 1);
        } else {
            if (callback.item && callback.item.id) {
                var index = _.findIndex($scope.editRoomsData.selectusers, {
                    id: callback.item.id.toString()
                });
                if (index >= 0) $scope.editRoomsData.selectusers.splice(index, 1);
            }
        }
    }
    $scope.filterUserSearch = function(query) {
        var users = _.filter($scope.users, function(item) {
            return item.display_name.toLowerCase().indexOf(query.toLowerCase()) >= 0;
        });
        return {
            items: users
        };
    }
    $scope.filterUserSearchRemoved = function(query) {
        return {
            items: []
        };
    }
    $scope.filterUserSearchClicked = function(query) {
        return $scope.dataSearchChat.user = query.item;
    }
    $scope.filterUserSearchClicked2 = function(query) {
        return $scope.dataSearchChat.userInRoom = query.item;
    }
    $scope.setValueForInputSearchUser = function(modelValue) {
        return [];
    };
    $scope.focusInput = function(elmID) {
        $timeout(function() {
            angular.element(document.querySelector('#' + elmID)).focus();
        }, 500)
    }
    $scope.lessThan = function(prop, val) {
        return function(item) {
            return item[prop] < val;
        }
    }
    $scope.listRoom = function() {
        if ($scope.chatinfo.userrooms) {
            $ionicPopup.alert({
                scope: $scope,
                title: $scope.chatinfo.userrooms.length + ' members',
                template: '<span ng-repeat="item in chatinfo.userrooms track by $index"><span ng-if="$index>0">,</span>{{item}}</span>'
            });
        }
    }
    $scope.onSelectUserHastag = function(callback) {}
    $scope.onCancelUserHastag = function(callback) {
        var display_name = '';
        for (var i = 0; i < callback.selectedItems.length; i++) {
            var item = callback.selectedItems[i];
            if (i == 0) {
                display_name = item.display_name.replace(/\s/g, '_');
            } else {
                display_name += " @" + item.display_name.replace(/\s/g, '_');
            }
        };
        $rootScope.$broadcast('hashtag', display_name, $scope.searchHashtag.display_name);
        $scope.focusInput("message");
        $timeout(function() {
            var that = $('#message');
            var textnotrim = that.val();
            $scope.pretext = textnotrim;
        }, 200)
    }
    $scope.filterUserHagtag = function(query) {
        var returnValue = {
            items: []
        };
        $scope.searchHashtag.display_name = query;
        $scope.users.forEach(function(item) {
            if (item.display_name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                returnValue.items.push(item);
            }
        })
        return returnValue;
    }
    $scope.countRecentItem = function(dataRoom, dataUserMessage) {
        var count_rooms = dataRoom.length;
        var dataUser = _.filter(dataUserMessage, function(item) {
            return item.msg
        });
        var count_user_message = _.countBy(dataUser, function(num) {
            return 'count';
        });
        if (!count_user_message['count']) {
            count_user_message = 0;
        } else {
            count_user_message = count_user_message['count']
        }
        $scope.countRecent = count_rooms + count_user_message;
    }
    $ionicPlatform.ready(function() {
        $rootScope.$on('$cordovaLocalNotification:click', function(event, notification, state) {
            var data = JSON.parse(notification.data);
            var user_id = data.user_id;
            var is_room = data.is_room;
            isChatting = true;
            $ionicLoading.show({
                template: templateLoading
            });
            $scope.chatContent(user_id.toString(), is_room);
        });
    });
    $scope.keyboardHeight = 200;
    $scope.role = role;
    $scope.search = {};
    $scope.clearSearch = function() {
        $scope.search.Text = '';
    }
    $scope.tabChatActive = 'Recent';
    $scope.setTabChat = function(tab) {
        $scope.tabChatActive = tab;
    }
    $scope.emoticon = {
        ":)": "resources/images/icons/emoticon/set1/happy-5.png",
        ":~": "resources/images/icons/emoticon/set1/sick-3.png",
        ":b": "resources/images/icons/emoticon/set1/doctor.png",
        ":|": "resources/images/icons/emoticon/set1/angry-2.png",
        "8-)": "resources/images/icons/emoticon/set1/smug-3.png",
        ":-((": "resources/images/icons/emoticon/set1/laughing-2.png",
        ":$": "resources/images/icons/emoticon/set1/smiling-1.png",
        ":X": "resources/images/icons/emoticon/set1/secret.png",
        ":z": "resources/images/icons/emoticon/set1/kiss-1.png",
        ":((": "resources/images/icons/emoticon/set1/crying-3.png",
        ":-|": "resources/images/icons/emoticon/set1/sad-4.png",
        ":-h": "resources/images/icons/emoticon/set1/goofy-1.png",
        ":p": "resources/images/icons/emoticon/set1/wink-1.png",
        ":d": "resources/images/icons/emoticon/set1/laughing-1.png",
        ":o": "resources/images/icons/emoticon/set1/silent.png",
        ":(": "resources/images/icons/emoticon/set1/sad-1.png",
        ":+": "resources/images/icons/emoticon/set1/superhero.png",
        "--b": "resources/images/icons/emoticon/set1/relieved.png",
        ":q": "resources/images/icons/emoticon/set1/happy-10.png",
        ":t": "resources/images/icons/emoticon/set1/yawning-2.png",
        ";p": "resources/images/icons/emoticon/set1/happy-9.png",
        ";-d": "resources/images/icons/emoticon/set1/goofy-4.png",
        ";d": "resources/images/icons/emoticon/set1/smug-4.png",
        ";o": "resources/images/icons/emoticon/set1/sceptic.png",
        ";g": "resources/images/icons/emoticon/set1/happy-7.png",
        "|-)": "resources/images/icons/emoticon/set1/sick-2.png",
        ":!": "resources/images/icons/emoticon/set1/evil.png",
        ":l": "resources/images/icons/emoticon/set1/sad-3.png",
        ":>": "resources/images/icons/emoticon/set1/scared.png",
        ":;": "resources/images/icons/emoticon/set1/ninja.png",
        ";f": "resources/images/icons/emoticon/set1/sceptic-4.png",
        ";-s": "resources/images/icons/emoticon/set1/desperate-1.png",
        ";?": "resources/images/icons/emoticon/set1/thinking.png",
        ";-x": "resources/images/icons/emoticon/set1/shocked-2.png",
        ":-f": "resources/images/icons/emoticon/set1/dazed-2.png",
        ";8": "resources/images/icons/emoticon/set1/dead-4.png",
        ";!": "resources/images/icons/emoticon/set1/superhero-2.png",
        ";-!": "resources/images/icons/emoticon/set1/superhero-3.png",
        ";xx": "resources/images/icons/emoticon/set1/vampire-1.png",
        ":-bye": "resources/images/icons/emoticon/set1/winking.png",
        ":wipe": "resources/images/icons/emoticon/set1/sad-5.png",
        ":-dig": "resources/images/icons/emoticon/set1/confused-3.png",
        ":handclap": "resources/images/icons/emoticon/set1/pirate-2.png",
        "&amp;-(": "resources/images/icons/emoticon/set1/sad-2.png",
        "b-)": "resources/images/icons/emoticon/set1/baby-1.png",
        ":-l": "resources/images/icons/emoticon/set1/gentleman-4.png",
        ":-r": "resources/images/icons/emoticon/set1/rich.png",
        ":-o": "resources/images/icons/emoticon/set1/in-love-4.png",
        ">-|": "resources/images/icons/emoticon/set1/hipster-2.png",
        "p-(": "resources/images/icons/emoticon/set1/creepy.png",
        ":--|": "resources/images/icons/emoticon/set1/rich-1.png",
        "x-)": "resources/images/icons/emoticon/set1/sceptic-5.png",
        ":*": "resources/images/icons/emoticon/set1/nerd-3.png",
        ";-a": "resources/images/icons/emoticon/set1/angel.png",
        "8*": "resources/images/icons/emoticon/set1/angry-3.png",
        "/-showlove": "resources/images/icons/emoticon/set1/in-love-2.png",
        "/-rose": "resources/images/icons/emoticon/set0/flower-1.png",
        "/-fade": "resources/images/icons/emoticon/set0/flower-2.png",
        "/-heart": "resources/images/icons/emoticon/set0/heart.png",
        "/-break": "resources/images/icons/emoticon/set0/broken-heart.png",
        "/-coffee": "resources/images/icons/emoticon/set0/coffee.png",
        "/-cake": "resources/images/icons/emoticon/set0/cake.png",
        "/-li": "resources/images/icons/emoticon/set0/lightning.png",
        "/-bome": "resources/images/icons/emoticon/set0/bomb.png",
        "/-bd": "resources/images/icons/emoticon/set0/cleaver.png",
        "/-shit": "resources/images/icons/emoticon/set0/shit.png",
        "/-strong": "resources/images/icons/emoticon/set6/like-5.png",
        "/-weak": "resources/images/icons/emoticon/set6/dislike-5.png",
        "/-share": "resources/images/icons/emoticon/set6/handshake.png",
        "/-v": "resources/images/icons/emoticon/set6/peace-5.png",
        "/-thanks": "resources/images/icons/emoticon/set6/fist-17.png",
        "/-jj": "resources/images/icons/emoticon/set6/tap-5.png",
        "/-punch": "resources/images/icons/emoticon/set6/fist-23.png",
        "/-bad": "resources/images/icons/emoticon/set6/surf-5.png",
        "/-loveu": "resources/images/icons/emoticon/set6/heavy-metal-11.png",
        "/-no": "resources/images/icons/emoticon/set6/point-17.png",
        "/-ok": "resources/images/icons/emoticon/set6/positive-5.png"
    };
    $scope.countRecent = 0;
    $scope.currentuser = {};
    $scope.chatarea = {};
    $scope.chatinfo = {};
    $scope.chatinfo.name = ":)";
    $scope.currentsetting = {};
    $scope.message = "";
    $scope.applicationtype = aplicationtype;
    $scope.focusManager = {
        focusInputOnBlur: true
    };
    $scope.badge = 0;
    $scope.count_online = 0;
    $scope.count_offline = 0;
    $scope.histories = [];
    $scope.allUser = [];
    $scope.typestatustus = {};
    $scope.typestatustus.prev = "...";
    $scope.typestatustus.disp = "...";
    $scope.typestatustus.current = "...";
    $scope.deleteLineitemsData = {};
    $scope.addLineitemsData = {};
    $scope.editRoomsData = {};
    $scope.editRoomsData.selectusers = [];
    $scope.titlemessage = {};
    $scope.titlemessage.disp = "";
    $scope.titlemessage.org = "Chat";
    $scope.titlemessage.current = "";
    $scope.stopblink = {};
    $scope.role = role;
    $scope.roleName = role;
    $scope.isAdmin = isAdmin;
    $scope.isManager = isManager;
    $scope.isReporter = isReporter;
    $scope.isScheduler = isScheduler;
    $scope.isFieldinstaller = isFieldinstaller;
    $scope.isSalesman = isSalesman;
    $scope.styleIonScroll = '';
    $scope.filter = {};
    $scope.filter.group = true;
    $scope.filter.person = true;
    $scope.filter.online = true;
    $scope.filter.offline = true;
    $scope.userhideall = false;
    $scope.userhide = {};
    $scope.userhide.currentid = 0;
    $scope.userhide.status = false;
    $scope.showlibrary = {
        'all': true,
        'image': true,
        'link': true,
        'pdf': true,
        'other': true
    };
    $scope.dataSearchChat = {};
    $scope.dataSearchChat.in = 'room';
    $scope.dataSearchChat.type = 'exact';
    $scope.dataSearchChat.user = [];
    $scope.Loading_data = false;
    $scope.chatList_data = false;
    $scope.Loading_data_star = true;
    $scope.views = ['pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'csv'];
    $scope.viewer = function(history) {
        var s3_name = history.message ? (history.message.lastIndexOf("/") + 1) : (history.contents.lastIndexOf("/") + 1);
        var index = (history.message ? history.message.substring(s3_name, history.message.length) : history.contents.substring(s3_name, history.contents.length));
        var url = url_server + 'lineitems/download/' + encodeURI(index + '/' + (history.filename || history.content_raw || index));
        if (history.applicationtype == "images") {
            window.open(url, '_system', 'location=no, clearcache=no, toolbar=yes, enableViewportScale=yes, hidden=yes');
            return false;
        }
        var ext = history.message.substring(history.message.lastIndexOf(".") + 1, history.message.length);
        if ($scope.views.indexOf(ext) >= 0) {
            window.open(url, '_system', 'location=no, clearcache=no, toolbar=yes, enableViewportScale=yes, hidden=yes');
            return false;
        }
        return false;
    };
    $scope.downloadFile = function(history) {
        if (!history.message) {
            history.message = history.contents;
        }
        var s3_name = history.message ? (history.message.lastIndexOf("/") + 1) : (history.contents.lastIndexOf("/") + 1);
        var index = (history.message ? history.message.substring(s3_name, history.message.length) : history.contents.substring(s3_name, history.contents.length));
        var url = url_server + 'lineitems/download/' + encodeURI(index + '/' + (history.filename || history.content_raw || index));
        if (history.applicationtype == "images") {
            window.open(history.message, '_system', 'location=no, clearcache=no, toolbar=yes, enableViewportScale=yes, hidden=yes');
            return false;
        }
        var ext = history.message.substring(history.message.lastIndexOf(".") + 1, history.message.length);
        if ($scope.views.indexOf(ext) >= 0) {
            var viewer = "https://docs.google.com/viewer?url=" + history.message;
            window.open(viewer, '_system', 'location=no, clearcache=no, toolbar=yes, enableViewportScale=yes, hidden=yes');
            return false;
        } else {
            var options = {
                location: 'yes',
                clearcache: 'no',
                toolbar: 'yes',
                enableViewportScale: 'yes'
            };
            if (isiOs) {
                window.open(history.message, '_blank', 'location=no, clearcache=no, toolbar=yes, enableViewportScale=yes, hidden=yes');
            } else {
                var ref = window.open(history.message, '_system', 'location=no, clearcache=no, toolbar=yes, enableViewportScale=yes, hidden=yes');
                ref.close();
            }
        }
        return false;
    }
    $scope.filterUser = function(itm) {
        var flag = true;
        if (!$scope.filter.online) {
            if (itm.status) {
                flag = false;
            }
        }
        if (!$scope.filter.offline) {
            if (!itm.status) {
                flag = false;
            }
        }
        return flag;
    };
    $scope.formatDate = function(item, style) {
        if (style == 'timestamp') {
            if (item.time < 0) return;
            return moment(item.time * 1000).format("DD MMM YYYY hh:mm a");
        }
        if (item && item.time) {
            return moment(item.time).format("DD MMM YYYY hh:mm a");
        } else {
            return "test";
        }
    }
    $scope.backToChat = function() {
        $scope.histories = [];
        $scope.shouldNotFocusOnBlur();
        $scope.closeTarget('#chatContent');
    }
    $scope.scrollBottom = function() {
        $timeout(function() {
            $ionicScrollDelegate.$getByHandle('scrollerPopupChatDetail').scrollBottom(true);
            $("#scrollBottom").fadeOut("slow");
        }, 500);
    }
    $scope.checkPositionButton = function() {
        return true;
    }
    $scope.showButton = function() {
        var checkPositionButton = $scope.checkPositionButton();
        if (!checkPositionButton) $("#scrollBottom").fadeOut("slow");
    }
    $scope.getChatSetting = function() {
        Users.getChatSetting(1).then(function(data) {
            $scope.dataUsersRoom = data.data.userrooms;
            if (offline_mode) {
                data = data.title;
            } else {
                data = data.data;
            }
            $scope.settingusers = data.settings;
            $scope.currentuser = {
                id: data.id,
                name: data.first_name + ' ' + data.last_name,
                image: data.image_pic.indexOf('s3.amazonaws.com') > 0 ? data.image_pic : url_site + '/' + data.image_pic
            };
            _.each(data.users, function(item) {
                item.status = false;
                item.gethistories = false;
                item.selected = false;
                item.disturb = false;
                item.idle = false;
                if (item.image_pic.indexOf('http') < 0) {
                    item.image_pic = url_site + '/' + item.image_pic;
                }
                return item;
            });
            data.users = _.sortBy(data.users, 'time').reverse();
            $scope.users = data.users;
            for (var i = 0; i < $scope.users.length; i++) {
                var item = $scope.users[i];
                if (item.msg) {
                    if (item.id != item.msg.from_user) {
                        item.msg.isread = '1';
                    }
                    if (item.msg.isread == 0 && item.userhide == 1) {
                        item.userhide = 0;
                        var showHideContactObj = {
                            'id_currentuser': $scope.currentuser.id,
                            'id_hidecontact': item.id
                        };
                        Chatsettings.showHideContact(showHideContactObj).success(function(data) {
                            $scope.userhide.status = false;
                        });
                    }
                }
            }
            var counter_unread = _.countBy($scope.users, function(item) {
                return item.msg && item.msg.isread == 1 ? 'unread' : 'read';
            });
            var counter_userhide = _.countBy($scope.users, function(item) {
                return item.msg && item.msg.isread == 1 && item.userhide == 1 ? 'hide' : 'unhide';
            });
            if (counter_userhide.hide == counter_unread.unread) {
                $scope.userhideall = true;
            } else {
                $scope.userhideall = false;
            }
            $scope.count_contact = $scope.users.length;
            for (var i = 0; i < $scope.count_contact; i++) {
                if ($scope.users[i].status) {
                    $scope.count_online++;
                } else {
                    $scope.count_offline++;
                }
            }
            _.each(data.rooms, function(item) {
                item.gethistories = false;
                item.selected = false;
                return item;
            });
            _.each(data.createrooms, function(item) {
                item.gethistories = false;
                item.selected = false;
                return item;
            });
            data.rooms = arrayUnion(data.rooms, data.createrooms, function(item1, item2) {
                return item1.id == item2.id;
            });
            data.rooms = _.sortBy(data.rooms, 'time').reverse();
            angular.forEach(data.rooms, function(item) {
                item.userrooms = [];
                if (item.msg) {
                    if ($scope.currentuser.id == item.msg.from_user) {
                        item.msg.isread = '1';
                    }
                }
                angular.forEach(data.userrooms, function(res) {
                    if (item.id == res.id) item.userrooms.push(res.display_name);
                })
                item.display_name = item.name;
                return item;
            })
            $scope.rooms = data.rooms;
            $scope.getNameChat($scope.rooms[0].id, true);
            $scope.count_rooms = $scope.rooms.length;
            $scope.countRecentItem($scope.rooms, $scope.users);
            $scope.sounds = data.sounds;
            $scope.chatstatuses = data.chatstatuses;
            if (data.status) {
                if (data.status.id == "2") {
                    $scope.status = data.status;
                    $scope.notifyStatus(2);
                } else {
                    $scope.status = data.chatstatuses[0];
                }
            } else {
                $scope.status = data.chatstatuses[0];
            }
            setUsername();
            $scope.notifyStatus($scope.status.id);
            var dataPush = $stateParams.dataPush;
            if (dataPush && dataPush != ':dataPush') {
                var arrData = dataPush.split("_");
                $ionicLoading.show({
                    template: templateLoading
                });
                if (arrData[0].toString() != $scope.currentuser.id.toString()) {
                    $scope.chatContent(arrData[0].toString(), arrData[1] ? true : false);
                    $scope.showTarget('#popupChatDetail');
                }
            }
            $timeout(function() {
                $ionicLoading.hide()
            }, 100);
            $timeout(function() {
                if (getParameterByName('room_id') && $scope.firstLoadWithParamRomm) {
                    $scope.firstLoadWithParamRomm = false;
                    $scope.chatContent(getParameterByName('room_id').toString(), true);
                    $scope.showTarget('#popupChatDetail');
                    var mess_sendtodispath = getParameterByName('message');
                    $scope.oppId = parseInt(getParameterByName('opp_id'));
                    if (mess_sendtodispath) {
                        socket.emit('hightlightappointment', {
                            toroom_id: '2',
                            min_id: mess_sendtodispath
                        });
                    }
                }
            }, 500);
        });
}
$scope.hideContact = function(currentstatus) {
    var hideContactObj = {
        'id_currentuser': $scope.currentuser.id,
        'id_hidecontact': $scope.userhide.currentid
    };
    if (currentstatus) {
        Chatsettings.hideContact(hideContactObj).success(function() {
            $scope.getChatSetting();
            $scope.closeTarget('#optionChatPerson');
            currentstatus = false;
        });
    } else {
        var showHideContactObj = {
            'id_currentuser': $scope.currentuser.id,
            'id_hidecontact': $scope.userhide.currentid
        };
        Chatsettings.showHideContact(showHideContactObj).success(function(data) {
            currentstatus = false;
            $scope.closeTarget('#optionChatPerson');
        });
    }
}

function getHashtag(msg) {
    var patt = /([\#@][a-zA-Z0-9\-\_]+)/g;
    var result = msg.match(patt);
    return result;
}
$scope.showpPopupPersion = function(item) {
    $scope.showTarget('#optionChatPerson');
    $scope.userhide.currentid = item.id;
    $scope.userhide.status = false;
    $scope.userhide.name = item.display_name;
    $scope.userhide.is_room = false;
}
$scope.showSearchMessage = function() {
    dataHtml.getTemplate('templates/dashboard/chat/popup/popupChatSearchChat.tpl').success(function(results) {
        $scope.dataChatHtml.popupChatSearchChat = results;
        $scope.showTarget('#popupChatSearchChat');
    });
}
$scope.searchContact = function() {
    var ionAutocompleteElement = document.getElementById("searchContact");
    angular.element(ionAutocompleteElement).controller('ionAutocomplete').fetchSearchQuery("", true);
    angular.element(ionAutocompleteElement).controller('ionAutocomplete').showModal();
}
$scope.onSelectUserSearchContact = function(callback) {
    if (!callback.item.room) {
        callback.item.userhide = false;
        var showHideContactObj = {
            'id_currentuser': $scope.currentuser.id,
            'id_hidecontact': callback.item.id
        };
        Chatsettings.showHideContact(showHideContactObj).success(function(data) {
            currentstatus = false;
            $scope.closeTarget('#optionChatPerson');
        });
    }
    $scope.chatContent(callback.item.id, callback.item.room);
    $scope.showTarget('#popupChatDetail');
}
$scope.filterContact = function(query) {
    var returnValue = {
        items: []
    };
    $scope.searchHashtag.display_name = query;
    $scope.users.forEach(function(item) {
        if (item.display_name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
            item.room = false;
            returnValue.items.push(item);
        }
    })
    $scope.rooms.forEach(function(item) {
        if (item.display_name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
            item.room = true;
            returnValue.items.push(item);
        }
    })
    return returnValue;
}
$scope.showChatSearchChatResult = function() {
    dataHtml.getTemplate('templates/dashboard/chat/popup/popupChatSearchChatResult.tpl').success(function(results) {
        $scope.dataChatHtml.popupChatSearchChatResult = results;
        $scope.showTarget('#popupChatSearchChatResult');
    });
}
$scope.showpPopupSetting = function() {
    $scope.openByGetTemplate('popupChatDetailSetting');
    $scope.closeTarget('#optionChatPerson');
    $scope.currentsetting = getSettingCurrent($scope.userhide.currentid, $scope.userhide.is_room);
}
$scope.showPopupChatSearchList = function(item) {
    dataHtml.getTemplate('templates/dashboard/chat/popup/popupChatSearchChatResultList.tpl').success(function(results) {
        $scope.dataChatHtml.popupChatSearchChatResultList = results;
        $scope.showTarget('#popupChatSearchChatResultList');
        $scope.openContentChat(item);
    });
}
$scope.showpPopupFile = function(searchall) {
    $scope.openByGetTemplate('popupChatDetailFile');
    $scope.userhide.currentid = $scope.chatinfo.id;
    $scope.userhide.status = false;
    $scope.userhide.name = $scope.chatinfo.name || $scope.chatinfo.display_name;
    $scope.userhide.is_room = $scope.chatinfo.name ? true : false;
    if (searchall == '-1') {
        $scope.userhide.status = false;
        $scope.userhide.name = 'Admin';
        $scope.userhide.is_room = true;
    }
    $scope.openPopupFileAlbumChat('', searchall);
}
$scope.dataResultSearch = [];
$scope.beforeSearch = function() {
    $scope.isSubmitSearch = true;
    $scope.dataResultSearch = [];
    $scope.searchchat();
}
$scope.fileFolderViewerChat = function(e) {
    var index = $(e.target).closest('li').index();
    $scope.filesViewer = [];
    for (var i = 0; i < $(e.target).closest('.lst-file').find('> li').length; i++) {
        var itmData = JSON.parse($(e.target).closest('.lst-file').find('> li').eq(i).attr('data-item'));
        var itm = {};
        itm.type = itmData.type;
        if (itm.type != "link") {
            itm.name = itm.type == "image" ? itmData.content_raw : itmData.filename;
            itm.url = itmData.contents;
            $scope.filesViewer.push(itm);
        }
    }
    $timeout(function() {
        fileFolderViewer('#popupFileViewerChat', index);
    }, 1);
    $scope.showTarget('#popupFileViewerChat');
}
$scope.openContentChat = function(message) {
    var roomName = message.roomName;
    var sender = message.sender;
    $scope.getTitlePopup(roomName, sender);
    message.app = 'true';
    $scope.chatList_data = true;
    Lineitems.getContentSearchChat(message).success(function(data) {
        var chatContent = buildingDataContentChat(data.messages_top, message);
        $scope.messages_top = chatContent;
    });
}
$scope.addMessageHashtag = function(name) {
    name = name.split(' ').join('_');
    var hashtag = '@' + name;
    var that = $('#message');
    var a = that[0].selectionStart;
    var b = that.val();
    that.val(b.substring(0, a) + hashtag + b.substring(a));
    that.focus();
}
$scope.getNicknameForGroup = function(item) {
    if ($scope.currentsetting.toroom_id == 0) return;
    item = item + '';
    var user_index = _.findLastIndex($scope.users, {
        id: item
    });
    if (user_index >= 0) {
        return $scope.users[user_index].nick_name;
    }
}

function buildingDataContentChat(data, message) {
    $scope.arrKey = $scope.dataSearchChat.key.split(" ");
    _.each(data, function(item) {
        item.servertime = moment(item.servertime, 'YYYY-MM-DD HH:mm:ss').format('MM/DD/YYYY hh:mm:ss a');
        if (item.from_user == $scope.currentuser.id) {
            item.image = $scope.currentuser.image;
            item.sendername = $scope.currentuser.display_name;
        } else {
            var index = _.findIndex($scope.users, {
                id: item.from_user + ''
            });
            if (index >= 0) {
                var currUser = $scope.users[index];
                item.image = currUser.image_pic;
                item.sendername = currUser.display_name;
            }
        }
        if (message && message.content_raw && item.id == message.id) {
            if ($scope.dataSearchChat.type == 'exact') {
                var reg = new RegExp('(' + $scope.dataSearchChat.key + ')', 'gi');
                item.contents = item.contents.replace(reg, "<span style=\'color:red\'>$1</span>");
            } else {
                for (var i = 0; i < $scope.arrKey.length; i++) {
                    var reg = new RegExp('(' + $scope.arrKey[i] + ')', 'gi');
                    item.contents = item.contents.replace(reg, "<span style=\'color:red\'>$1</span>");
                }
            }
        }
    });
    data = _.sortBy(data, 'id');
    return data;
}
$scope.titleList = '';
$scope.getTitlePopup = function(roomName, sender) {
    var dataSearch = $scope.dataSearch;
    if (dataSearch.type == 'exact') {
        dataSearch.type = 'Exact Match';
    } else {
        dataSearch.type = 'Fuzzy Match';
    }
    dataSearch.key = dataSearch.key.toLowerCase().replace(/\b[a-z]/g, function(letter) {
        return letter.toUpperCase();
    });
    $scope.titleList = "Chat Search - " + roomName + " - " + sender + " - " + dataSearch.from + " - " + dataSearch.to + " - " + dataSearch.type + " - " + dataSearch.key;
}
$scope.LoadMoreSearchChatList = function(direct) {
    if ($scope.messages_top && $scope.messages_top.length > 0) {
        if (direct == 'less') {
            var first = _.first($scope.messages_top);
            if (first) {
                Lineitems.loadMoreMessage({
                    id: first.id,
                    from_user: first.from_user,
                    user_id: first.user_id,
                    room_id: first.room_id,
                    direct: 'less'
                }).success(function(data) {
                    var chatContent = buildingDataContentChat(data.messages_top);
                    $scope.messages_top = chatContent.concat($scope.messages_top);
                    $scope.$broadcast('scroll.refreshComplete');
                });
            } else {
                $scope.$broadcast('scroll.refreshComplete');
            }
        } else {
            var last = _.last($scope.messages_top);
            Lineitems.loadMoreMessage({
                id: last.id,
                from_user: last.from_user,
                user_id: last.user_id,
                room_id: last.room_id,
                direct: 'more'
            }).success(function(data) {
                var chatContent = buildingDataContentChat(data.messages_top);
                if (chatContent.length == 0) {
                    $scope.chatList_data = false;
                }
                $scope.messages_top = $scope.messages_top.concat(chatContent);
                $scope.$broadcast('scroll.infiniteScrollComplete');
            });
        }
    } else {
        $scope.$broadcast('scroll.infiniteScrollComplete');
    }
}
$scope.searchchat = function() {
    var query = {};
    $scope.items_perpage = 10;
    $scope.dataSearchChat['rows'] = $scope.items_perpage;
    if ($scope.isSubmitSearch) {
        $scope.dataSearchChat['current_page'] = 1;
    }
    angular.copy($scope.dataSearchChat, query);
    query.from = moment(query.from).format("MM/DD/YYYY").toString();
    query.to = moment(query.to).format("MM/DD/YYYY").toString();
    if (query.in == "room") {
        if (query.inRoom) {
            query.inRoom = query.inRoom.id;
            if (query.userInRoom) {
                query.userInRoom.name = query.userInRoom.display_name;
            } else {
                delete query.userInRoom;
            }
        } else {
            query.userInRoom = {};
            query.inRoom = 'all';
        }
    }
    $scope.showChatSearchChatResult();
    $scope.searchchatRequest(query);
};
$scope.searchchatRequest = function(query) {
    if ($scope.isSubmitSearch) {
        if ($scope.current_page < 1) {
            $ionicLoading.show({
                template: templateLoading
            });
        }
        $scope.isSubmitSearch = false;
        Lineitems.searchChat(query).success(function(data) {
            $scope.isSubmitSearch = true;
            if ($scope.current_page < 1) {
                $ionicLoading.hide();
            }
            $scope.current_page = data.current_page;
            $scope.items_perpage = $scope.dataSearchChat.rows;
            $scope.total_items = data.total_rows;
            $scope.dataSearch = data.query;
            $scope.arrKey = $scope.dataSearchChat.key.split(" ");
            if (data.data) {
                _.each(data.data, function(item) {
                    var curr = _.find($scope.users, {
                        id: item.from_user
                    });
                    if (curr) {
                        item.image_pic = curr.image_pic;
                    }
                    item.servertime = moment(item.servertime, 'YYYY-MM-DD HH:mm:ss').format('MM/DD/YYYY hh:mm:ss a');
                    if (item.contents.indexOf("</span>") > -1) {
                        item.content_message_raw = item.contents.replace("<span class='hash-tag'>", '').replace("</span>", '');
                    } else {
                        item.content_message_raw = item.contents;
                    }
                    if (item.contents.includes("<span ") > -1) {
                        item.contents = item.contents.replace("<span class='hash-tag'>@", "<div>");
                        item.contents = item.contents.replace("</span>", "</div>");
                    }
                    if ($scope.dataSearchChat.type == 'exact') {
                        var reg = new RegExp('(' + $scope.dataSearchChat.key + ')', 'gi');
                        item.contentsHtml = item.contents.replace(reg, "<p>$1</p>");
                    } else {
                        for (var i = 0; i < $scope.arrKey.length; i++) {
                            if (i == 0) {
                                item.contentsHtml = item.contents;
                            }
                            var reg = new RegExp('(' + $scope.arrKey[i] + ')', 'gi');
                            item.contentsHtml = item.contentsHtml.replace(reg, "<p>$1</p>");
                        }
                    }
                    if (item.contentsHtml.includes("<div>") > -1) {
                        item.contentsHtml = item.contentsHtml.replace("<div>", "<span class='hash-tag'>@");
                        item.contentsHtml = item.contentsHtml.replace("</div>", "</span>");
                    }
                    var regg1 = new RegExp("<p>", 'gi');
                    var regg2 = new RegExp("</p>", 'gi');
                    if (item.contentsHtml.includes("<p>") > -1) {
                        item.contentsHtml = item.contentsHtml.replace(regg1, "<span style='color:#B5607C'>");
                        item.contentsHtml = item.contentsHtml.replace(regg2, "</span>");
                    }
                });
            }
            $scope.dataResultSearch = $scope.dataResultSearch.concat(data.data);
            if ($scope.dataResultSearch == '') {
                $scope.noResultSearch = '<span>No results found.</span>';
            }
            if ($scope.dataResultSearch.length < data.total_rows && $scope.current_page == 1) {
                $timeout(function() {
                    $scope.Loading_data_star = true;
                    $scope.Loading_data = true;
                }, 2000);
                $ionicScrollDelegate.$getByHandle('scrollSearchChat').scrollTop(true);
                $ionicScrollDelegate.$getByHandle('scrollSearchChat').resize;
            }
            if ($scope.dataResultSearch.length >= data.total_rows) {
                $scope.Loading_data_star = false;
                $scope.Loading_data = false;
            }
        });
    }
}
$scope.LoadMoreSearchChat = function() {
    var query = {};
    $scope.items_perpage = 10;
    $scope.dataSearchChat['rows'] = $scope.items_perpage;
    $scope.dataSearchChat['current_page'] = $scope.current_page + 1;
    angular.copy($scope.dataSearchChat, query);
    query.from = moment(query.from).format("MM/DD/YYYY").toString();
    query.to = moment(query.to).format("MM/DD/YYYY").toString();
    if (query.in == "room") {
        if (query.inRoom) {
            query.inRoom = query.inRoom.id;
        } else {
            query.inRoom = 'all';
        }
    }
    $scope.searchchatRequest(query);
    $timeout(function() {
        $scope.$broadcast('scroll.infiniteScrollComplete');
    }, 2000);
}
$scope.hideAllContact = function(userhideall) {
    var id_hidecontact = [];
    for (var i = 0; i < $scope.users.length; i++) {
        id_hidecontact[i] = $scope.users[i].id;
    }
    var hideContactObj = {
        'id_currentuser': $scope.currentuser.id,
        'id_hidecontact': id_hidecontact
    };
    if (!userhideall) {
        hideContactObj.show = true;
    }
    $ionicLoading.show({
        template: templateLoading
    });
    Chatsettings.hideAllContact(hideContactObj).success(function() {
        $ionicLoading.hide();
        $scope.getChatSetting();
    });
}
$scope.showHideContact = function(id_currentuser, id_hidecontact) {
    var showHideContactObj = {
        'id_currentuser': $scope.currentuser.id,
        'id_hidecontact': $scope.userhide.currentid
    };
    Chatsettings.showHideContact(showHideContactObj).success(function(data) {
        $scope.userhide.status = false;
    });
}
$scope.shouldNotFocusOnBlur = function() {
    isKeyboardHide = true;
    $focusTest.setFocusOnBlur(false);
    if (window.StatusBar) {}
}
$scope.insertEmotico = function(key) {
    $rootScope.$broadcast('insertEmotico', key);
}
$scope.getHref = function(item) {
    return 'chats.html?user_id=' + (item.room_id == 0 ? item.from_user : item.room_id) + (item.room_id == 0 ? '' : '&is_room=true');
}
$scope.changeStatus = function(item) {
    $scope.status = item;
    $scope.notifyStatus(item.id);
}
$scope.notifyStatus = function(id) {
    switch (id) {
        case '1':
        case 1:
        mousestopTime = $interval($scope.setIdle, time_idle);
        $interval.cancel(mousestopoffline);
        socket.emit('changestatus', {
            user_id: $scope.currentuser.id,
            status: 1
        })
        break;
        case '2':
        case 2:
        socket.emit('changestatus', {
            user_id: $scope.currentuser.id,
            status: 2
        });
        break;
        case '3':
        case 3:
        socket.emit('changestatus', {
            user_id: $scope.currentuser.id,
            status: 3
        });
        break;
        case '4':
        case 4:
                //thong bao idle
                socket.emit('changestatus', {
                    user_id: $scope.currentuser.id,
                    status: 4
                });
                break;
            }
        }
        $scope.getUserOnline = function() {}
        $scope.getImage = function(user_id) {
            var index = _.findIndex($scope.users, {
                id: user_id + ''
            });
            if (index >= 0) {
                var currUser = $scope.users[index];
                return currUser.image_pic;
            } else {
                return 'resources/images/thumnails/profile-default.png';
            }
        }
        $scope.emoticonChatHandle = function() {
            $('.btn-emoticon').click(function() {
                $scope.showTarget('.chat-emoticon');
                setTimeout(function() {
                    $scope.resizeScroll('scrollerPopupChatDetail');
                }, 250);
            })
            closeOutsideHandle('.btn-emoticon, .chat-emoticon', '.chat-emoticon', function() {
                setTimeout(function() {
                    $scope.resizeScroll('scrollerPopupChatDetail');
                }, 250);
            });
        }
        $scope.chatContent = function(id, isgroup) {
            dataHtml.getTemplate('templates/dashboard/chat/popup/popupChatDetail.tpl').success(function(results) {
                $scope.dataChatHtml.popupChatDetail = results;
                $scope.shouldNotFocusOnBlur();
                var idPush = isgroup ? (1000 + id) : id;
                isChatting = true;
                try {
                    $cordovaLocalNotification.cancel(idPush).then(function() {
                        $cordovaLocalNotification.getAllIds().then(function(ids) {
                            $scope.badge = ids.length;
                            $cordovaBadge.set(ids.length);
                        });
                    })
                } catch (e) {
                    console.log(e);
                }
                $scope.getNameChat(id, isgroup);
                $timeout(function() {
                    $ionicScrollDelegate.$getByHandle('scrollerPopupChatDetail').scrollBottom(true);
                    $("#scrollBottom").hide();
                    $scope.emoticonChatHandle();
                }, 1000);
            });
        }
        $scope.getNameChat = function(id, isgroup) {
            id = id.toString();
            $scope.message = "";
            $scope.isGroup = false;
            $scope.unselected();
            isShowChatContact = true;
            $('.chat-area .chat-contact .task-toggle-button').trigger('click').fadeTo('slow/400/fast', 0.5, function() {});;
            if (isgroup == true) {
                $scope.isGroup = true;
                var room_index = _.findIndex($scope.rooms, {
                    id: (id)
                });
                $scope.chatinfo = $scope.rooms[room_index];
                $scope.currentsetting = getSettingCurrent(id, isgroup);
                $scope.rooms[room_index].selected = true;
                if (!$scope.rooms[room_index].histories) {
                    $scope.rooms[room_index].histories = [];
                }
                if ($scope.rooms[room_index].msg) {
                    $scope.rooms[room_index].msg.isread = '1';
                    socket.emit('markview', $scope.rooms[room_index].msg);
                }
                if (!$scope.rooms[room_index].gethistories) {
                    socket.emit('gethistories', $scope.currentsetting);
                }
                $scope.histories = $scope.rooms[room_index].histories;
                $scope.roomChatData = $scope.rooms[room_index];
                $scope.dataUsersRoomById = _.where($scope.dataUsersRoom, {
                    id: id.toString()
                });
            } else {
                var user_index = _.findLastIndex($scope.users, {
                    id: (id)
                });
                $scope.chatinfo = $scope.users[user_index];
                $scope.currentsetting = getSettingCurrent(id, isgroup);
                $scope.users[user_index].selected = true;
                if ($scope.users[user_index].msg) {
                    $scope.users[user_index].msg.isread = '1';
                    socket.emit('markview', $scope.users[user_index].msg);
                }
                if (!$scope.users[user_index].histories) {
                    $scope.users[user_index].histories = [];
                }
                if (!$scope.users[user_index].gethistories) {
                    socket.emit('gethistories', $scope.currentsetting);
                }
                $scope.histories = $scope.users[user_index].histories;
                $scope.userChatData = $scope.users[user_index];
            }
            if ($scope.histories.length == 0) {
                $scope.histories.push({
                    'message': ''
                });
            }
            $scope.scrollBottom();
            $scope.cleartyping();
            $scope.stopBlink();
        }
        $scope.unselected = function() {
            _.each($scope.users, function(item) {
                item.selected = false;
                return item;
            });
            _.each($scope.rooms, function(item) {
                item.selected = false;
                return item;
            });
        }

        function getSettingCurrent(id, isgroup) {
            if (isgroup == true) {
                var settings = _.where($scope.settingusers, {
                    toroom_id: id
                });
                if (settings.length > 0) {
                    return settings[0];
                } else {
                    return {
                        "fromuser_id": $scope.currentuser.id,
                        "touser_id": 0,
                        "toroom_id": id,
                        "isnotification": settingChat.isnotification,
                        "isnotifybackground": settingChat.isnotifybackground,
                        "issound": settingChat.issound,
                        "sound_id": settingChat.sound_id
                    };
                }
            } else {
                var settings = _.where($scope.settingusers, {
                    touser_id: id
                });
                if (settings.length > 0) {
                    return settings[0];
                } else {
                    return {
                        "fromuser_id": $scope.currentuser.id,
                        "touser_id": id,
                        "toroom_id": 0,
                        "isnotification": settingChat.isnotification,
                        "isnotifybackground": settingChat.isnotifybackground,
                        "issound": settingChat.issound,
                        "sound_id": settingChat.sound_id
                    };
                }
            }
        }
        $scope.changeSetting = function() {
            if (!updateSettingCurrent()) {
                Chatsettings.save($scope.currentsetting).success(function(data) {});
            } else {
                Chatsettings.update($scope.currentsetting.fromuser_id, $scope.currentsetting).success(function(data) {});
            }
        }
        $scope.getSoundName = function(sound_id) {
            var sound = _.find($scope.sounds, {
                id: sound_id
            });
            if (sound) {
                return sound.name;
            }
        }

        function updateSettingCurrent() {
            var curr = $scope.currentsetting;
            var findSetting = _.findLastIndex($scope.settingusers, {
                fromuser_id: curr.fromuser_id,
                touser_id: curr.touser_id,
                toroom_id: curr.toroom_id
            });
            if (findSetting >= 0) {
                $scope.settingusers[findSetting] = curr;
                return true;
            } else {
                curr.touser_id = curr.touser_id.toString();
                $scope.settingusers.push(curr);
                return false;
            }
        }

        function setUsername() {
            var status = ($scope.status.id == 1 || $scope.status.id == '1') ? true : false;
            $scope.currentuser.status = status;
            socket.emit('add user', $scope.currentuser);
        }
    var allowHashTag; // Cho phep Hashtag
    $scope.c;
    $scope.searchHashtag = {};
    $scope.searchHashtag.display_name = '';
    $scope.hashtags = [];
    $scope.pretext = '';
    $scope.checkKeypress = function($event) {
        $scope.c = String.fromCharCode($event.keyCode);
    }
    $scope.keepKeyboardOpen = function($txtInput) {
        $txtInput.one('blur', function() {
            $txtInput[0].focus();
        });
    }
    // edit by haudao
    $scope.sendMessage_mobile = function($event, button) {
        var txtInput = angular.element(document.body.querySelector('textarea#message'));
        $scope.keepKeyboardOpen(txtInput);
        var that = txtInput;
        var keyCode = $event.which || $event.keyCode;
        var text = that.val().trim();
        var textnotrim = that.val();
        
        var curr_postion = that.getCursorPosition();
        var beforeC = text.charAt(curr_postion - 2);
        if (getDifference($scope.pretext, text) == "#" || getDifference($scope.pretext, text) == "@") {
            $scope.initialSearchUser = [];
            if (window.cordova) {
                window.cordova.plugins.Keyboard.close();
            }
            var ionAutocompleteElement = document.getElementById("autohastag");
            angular.element(ionAutocompleteElement).controller('ionAutocomplete').fetchSearchQuery("", true);
            angular.element(ionAutocompleteElement).controller('ionAutocomplete').showModal();
        }
        $scope.pretext = textnotrim;
        if (socket.connected) {
            if (button == 'true' && text.length > 0) {
                txtInput.val('');
                txtInput.selectionStart = 0;
                var hastag = getHashtag(text);
                var content_raw = text.replace(/(\r\n|\n)/g, "<br/>");
                var message = replaceHtml(text);
                message = replaceEmoticon(message);
                message = replaceHashtag(message);
                var msg = {
                    id: '',
                    from_user: $scope.currentsetting.fromuser_id,
                    room_id: $scope.currentsetting.toroom_id,
                    user_id: $scope.currentsetting.touser_id,
                    username: $scope.currentuser.name,
                    contents: message.replace(/(\r\n|\n)/g, "<br/>"),
                    time: moment().format('YYYY-MM-DD HH:mm:ss'),
                    applicationtype: aplicationtype.text,
                    hashtag: (hastag == null ? '' : hastag.toString())
                };
                $timeout(function() {
                    $scope.$apply(function(val) {
                        $scope.keepKeyboardOpen(txtInput);
                        $timeout(function() {
                            if (message.includes('http://') || message.includes('https://')) {
                                $scope.sendLinkCover(msg, content_raw);
                            } else {
                                $scope.sendMessageNoneUrl(msg, content_raw);
                            }
                            $scope.pretext = '';
                            $scope.message = "";
                            // txtInput.val('');
                            // txtInput.selectionStart = 0;
                            $scope.shouldNotFocusOnBlur();
                            $scope.keepKeyboardOpen(txtInput);
                        }, 100);
                    });
                }, 0);
            }
        } else {
            $ionicPopup.alert({
                title: 'ERROR!!!',
                template: 'Connect error, please check your connection!'
            });
        }
    }

    function getDifference(a, b) {
        var i = 0;
        var j = 0;
        var result = "";
        if (b != "" && a != "") {
            while (j < b.length) {
                if (a[i] != b[j] || i == a.length) result += b[j];
                else i++;
                j++;
            }
            return result;
        } else {
            return b;
        }
    }
    $scope.sendMessageNoneUrl = function(msg, content_raw) {
        if ($scope.currentsetting.toroom_id != 0) {
            var room_index = _.findLastIndex($scope.rooms, {
                id: $scope.currentsetting.toroom_id
            })
            $scope.rooms[room_index].time = moment().unix();
            $scope.rooms[room_index].msg = {
                applicationtype: aplicationtype.text,
                contents: msg.contents,
                created_date: null,
                from_user: $scope.currentsetting.fromuser_id,
                hashtag: "",
                isclose: "0",
                isread: "1",
                room_id: $scope.currentsetting.toroom_id,
                time: moment().unix(),
                user_id: $scope.currentsetting.touser_id
            }
        } else {
            var user_index = _.findLastIndex($scope.users, {
                id: $scope.currentsetting.touser_id
            })
            $scope.users[user_index].time = moment().unix();
            $scope.users[user_index].msg = {
                applicationtype: aplicationtype.text,
                contents: msg.contents,
                created_date: null,
                from_user: $scope.currentsetting.fromuser_id,
                hashtag: "",
                isclose: "0",
                isread: "1",
                room_id: "0",
                time: moment().unix(),
                user_id: $scope.currentsetting.touser_id
            };
        }
        socket.emit('new message', {
            from_user: $scope.currentsetting.fromuser_id,
            room_id: $scope.currentsetting.toroom_id,
            user_id: $scope.currentsetting.touser_id,
            contents: msg.contents,
            hashtag: msg.hashtag,
            content_raw: msg.content_raw,
            applicationtype: aplicationtype.text
        });
        $scope.histories.push(msg);
        $scope.scrollBottom();
    }
    $scope.sendLinkCover = function(msg, content_raw) {
        var obj = {
            'url': msg.contents
        }
        Lineitems.getLinkcover(obj).success(function(data) {
            linkcover = "<a href='" + content_raw + "' target='_blank' class='link-message'><img src='" + data.image + "'><div>" + data.title + "</div><p>" + content_raw + "</p></a>";
            if (!$scope.currentsetting.toroom_id && !$scope.currentsetting.touser_id) {
                $ionicPopup.alert({
                    title: 'ERROR!!!',
                    template: 'Sorry, You can\'t send message!'
                });
                return;
            }
            msg['applicationtype'] = aplicationtype.link;
            msg['contents'] = linkcover;
            msg['content_raw'] = content_raw;
            if ($scope.currentsetting.toroom_id != 0) {
                var room_index = _.findLastIndex($scope.rooms, {
                    id: $scope.currentsetting.toroom_id
                })
                $scope.rooms[room_index].time = moment().unix();
                $scope.rooms[room_index].msg = {
                    applicationtype: aplicationtype.text,
                    contents: message,
                    created_date: null,
                    from_user: $scope.currentsetting.fromuser_id,
                    hashtag: "",
                    isclose: "0",
                    isread: "1",
                    room_id: $scope.currentsetting.toroom_id,
                    time: moment().unix(),
                    user_id: $scope.currentsetting.touser_id
                }
            } else {
                var user_index = _.findLastIndex($scope.users, {
                    id: $scope.currentsetting.touser_id
                })
                $scope.users[user_index].time = moment().unix();
                $scope.users[user_index].msg = {
                    applicationtype: aplicationtype.text,
                    contents: message,
                    created_date: null,
                    from_user: $scope.currentsetting.fromuser_id,
                    hashtag: "",
                    isclose: "0",
                    isread: "1",
                    room_id: "0",
                    time: moment().unix(),
                    user_id: $scope.currentsetting.touser_id
                }
            }
            $scope.histories.push(msg);
            delete msg.username;
            delete msg.time;
            delete msg.message;
            socket.emit('new message', msg);
            $scope.scrollBottom();
        });
    }
    // edit by haudao
    $scope.localPush = function(fromuser_id, message, room_id, applicationType, room_name, username) {
        var user_index = _.findLastIndex($scope.users, {
            id: fromuser_id
        });
        if(user_index == -1){
            return;
        };
        var username = $scope.users[user_index].display_name;
        var idPush = room_id == 0 ? fromuser_id : (1000 + room_id);
        var user_id = room_id == 0 ? fromuser_id : room_id;
        var is_room = room_id == 0 ? false : true;
        var prefix = room_id == 0 ? username : '[' + room_name + ']' + username;
        var content = applicationType == 'image' ? '[image]' : message;
        content = prefix + ':' + content;
        $cordovaLocalNotification.getAllIds().then(function(ids) {
            if (ids.indexOf(parseFloat(idPush)) == -1) {
                $timeout(function() {
                    $scope.badge++;
                    $cordovaBadge.increase(1);
                }, 3000);
            }
        });
        $cordovaLocalNotification.schedule({
            id: idPush,
            text: content,
            led: "0000FF",
            icon: cordova.file.applicationDirectory + 'www/resources/images/icons/icon.png',
            sound: cordova.file.applicationDirectory + 'www/sounds/tweeters.ogg',
            data: {
                user_id: user_id,
                is_room: is_room
            }
        })
    }
    $scope.filterHashtag = function(text, curr_postion) {
        var substring = text.substring(0, curr_postion);
        var lastInfdexAt = substring.lastIndexOf('#');
        var lastInfdexhash = substring.lastIndexOf('@');
        if (lastInfdexhash > lastInfdexAt) {
            lastInfdexAt = lastInfdexhash;
        }
        $scope.searchHashtag.display_name = text.substring(lastInfdexAt + 1, curr_postion);
    }

    function openHashtagSuggest(s) {
        $('#hastagpopup').show();
        var pos = $(s).getCaretPosition();
        $('#hastagpopup').css({
            left: pos.left,
            bottom: 75 - pos.top
        });
    }

    function closeHashtagSuggest() {
        $('#hastagpopup').hide();
    }
    $scope.notifylist = [{
        room_id: 0,
        user_id: 0,
        name: "",
        isnotifybackground: 0,
        issound: 0,
        sound_id: "",
        wasplayed: 1,
        message: "",
        close: "1"
    }];
    $scope.playSound = function(index, sound_id) {
        var sound_index = $scope.findIndex($scope.sounds, {
            id: sound_id
        });
        if (sound_index >= 0) {
            var sound = $scope.sounds[sound_index];
            url = sound.file_path;
            url = url.replace("ogg", "mp3");
            if (!isiOs) {
                var url = cordova.file.applicationDirectory + 'www/' + url;
                var media = new Media(url,
                    // success callback
                    function() {},
                    // error callback
                    function(err) {
                        console.log(err);
                    });
                media.play(); // Android
            }
            if (isiOs) {
                var media = new Media(url,
                    // success callback
                    function() {},
                    // error callback
                    function(err) {
                        console.log(err);
                    });
                media.play();
            }
        }
    }
    $scope.lastScroll = 0;
    $scope.isrequest = true;
    $scope.myScrollEvent = function() {
        $('#imgLoading').show();
        $scope.isrequest = false;
        $scope.currentsetting.min_id = _.first($scope.histories).id;
        socket.emit('gethistoriespaging', $scope.currentsetting);
        $scope.$broadcast('scroll.refreshComplete');
        $timeout(function() {
            $('#imgLoading').hide();
        }, 1000);
    }
    $scope.pushNotify = function(obj, message, localPushData, group) {
        var setting = {};
        if (group) {
            setting = $scope.findSetting({
                toroom_id: message.room_id + '',
                touser_id: '0'
            });
        } else {
            setting = $scope.findSetting({
                touser_id: message.from_user,
                fromuser_id: message.user_id
            });
        }
        var notify_index = $scope.findNotify({
            room_id: message.room_id,
            user_id: message.user_id
        });

        var tag = $scope.findHasTag(message.hashtag);
        
        var notify = {
            from_user: message.from_user,
            room_id: message.room_id,
            user_id: message.user_id,
            name: (obj.name || obj.nick_name),
            isnotification: setting.isnotification,
            issound: setting.issound,
            sound_id: setting.sound_id,
            wasplayed: '0',
            message: message.message,
            counter: message.counter,
            close: "1",
            //hashtag: message.hashtag && message.hashtag != '' ? true : false,
            hashtag: tag,
        };
        if (notify_index >= 0) {
            $scope.removeNotify(notify_index);
        }
        message.hashtag = $scope.findHasTag(message.hashtag);
        $scope.localPush(localPushData.from_user, localPushData.message, localPushData.room_id, localPushData.applicationtype, localPushData.room_name, localPushData.username);
        $timeout(function() {
            if (notify.issound == '1') { //chi push khi duoc setting notify la 1
                $scope.playSound(0, setting.sound_id);
            }
            if (notify.isnotification == '1') {
                // var user_index = _.findLastIndex($scope.users, {
                //     id: localPushData.from_user
                // });
                // var username = $scope.users[user_index].display_name;
                // var prefix = localPushData.room_id == 0 ? username : '[' + localPushData.room_name + ']' + username;
                // var content = localPushData.applicationtype == 'image' ? '[image]' : localPushData.message;
                // content = prefix + ':' + content;
                // $cordovaToast.showLongTop(content);
                $scope.notifylist.push(notify);
            }
            // ========== chat head ==============
            chat_head.pullMessage(angular, notify, message, 0, function($arguments1, $arguments2) {
                $scope.objChatHead($scope);
                $scope.obj_chat_head.bubbleArr = chat_head.last_in_bubbles;
                $arguments2[0] ? chat_head.messageToExpand($arguments1, $arguments2) : chat_head.draggableIsExpand($arguments2[0]);
            });
            // ========== end chat head ==============
        }, 2000);
    }
    $scope.findSetting = function(obj) {
        var findSetting = _.findLastIndex($scope.settingusers, obj);
        if (findSetting >= 0) {
            return $scope.settingusers[findSetting];
        } else {
            return settingChat;
        }
    }
    $scope.closeNotify = function(obj) {
        var findSetting = _.findLastIndex($scope.notifylist, obj);
        $scope.notifylist.splice(findSetting, 1);
    }
    $scope.findNotify = function(obj) {
        var findSetting = _.findLastIndex($scope.notifylist, obj);
        return findSetting;
    }
    $scope.removeNotify = function(index) {
        $scope.notifylist.splice(index, 1);
    }
    $scope.findIndex = function(data, obj) {
        return _.findLastIndex(data, obj);
    }
    $scope.findRoomIndex = function(room) {
        return $scope.findIndex($scope.rooms, room);
    }
    $scope.removeRoom = function(room_index) {
        $scope.rooms.splice(room_index, 1);
        $scope.countRecentItem($scope.rooms, $scope.users);
    }
    $scope.addRoom = function(room, room_index, user_index) {
        room.users = [];
        $scope.rooms.push(room);
        $scope.countRecentItem($scope.rooms, $scope.users);
    }
    $scope.updateRoom = function(room, room_index) {
        room.users = [];
        $scope.rooms[room_index].time = room.time ? room.time : $scope.rooms[room_index].time;
        $scope.rooms[room_index].msg = room.msg ? room.msg : $scope.rooms[room_index].msg;
    }
    $scope.shortname = function(history) {
        if (history.message) history.message = history.message.split("%2F").join("/");
        if (history.contents) history.contents = history.contents.split("%2F").join("/");
        var index = history.message ? (history.message.lastIndexOf("/") + 1) : (history.contents.lastIndexOf("/") + 1);
        return (history.message ? history.message.substring(index) : history.contents.substring(index));
    }
    $scope.getLineitems = function() {
        $('.loader').show();
        Lineitems.getPaging($scope.searchLineitems).success(function(data) {
            $scope.lineitems = data.data;
            $scope.currentPage = data.page;
            $scope.itemsPerPage = $scope.searchLineitems.rows;
            lineitems_pagesize.val($scope.itemsPerPage);
            $scope.totalItems = data.total_rows;
            $('#tableLineitems').tableRespondsive();
        });
    };
    $scope.getNickname = function(item) {
        var user_index = _.findLastIndex($scope.users, {
            id: item.toString()
        });
        if (user_index >= 0) {
            return $scope.users[user_index].nick_name;
        } else {
            return "You";
        }
    }
    // edit by haudao
    $scope.cordovaBrowser = function(url1, url2) {
        var url = url1;
        if (!url1) url = url2;
        if (url.indexOf('s3.amazonaws.com') == -1) {
            url = url_site + '/' + url;
        }
        $ionicLoading.show({
            template: templateLoading
        });
        $timeout(function() {
            $ionicLoading.hide();
            var options = {
                location: 'no',
                clearcache: 'no',
                toolbar: 'yes',
                enableViewportScale: 'yes'
            };
            if (isiOs) {
                $cordovaInAppBrowser.open(url, '_blank', options);
            } else {
                $cordovaInAppBrowser.open(url, '_system', options);
            }
        }, 1000);
    }
    $scope.showImagePhone = function(url1, url2) {
        var url = url1;
        if (!url1) url = url2;
        if (url.indexOf('s3.amazonaws.com') > -1) {
            return url;
        } else {
            url = url.replace('./', '');
            return url_site + '/' + url;
        }
    }
    $scope.openActionSheet = function() {
        var options = {
            // title: 'What do you want with this image?',
            buttonLabels: ['Video', 'Camera', 'Photo', 'File'],
            addCancelButtonWithLabel: 'Cancel',
            androidEnableCancelButton: true,
        };
        $cordovaActionSheet.show(options).then(function(index) {
            if (index == 2) {
                $scope.takePicture();
            } else if (index == 3) {
                $scope.openPicker();
            } else if (index == 4) {
                $scope.filePicker();
            } else if (index == 1) {
                $scope.recordVideo();
            }
        });
    }
    $scope.recordVideo = function() {
        // capture callback
        var captureSuccess = function(mediaFiles) {
            $scope.phoneUpload(mediaFiles);
        };
        // capture error callback
        var captureError = function(error) {
            navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
        };
        // start video capture
        navigator.device.capture.captureVideo(captureSuccess, captureError, {
            limit: 1
        });
    }
    $scope.openPicker = function() {
        var options = {
            maximumImagesCount: 50,
            width: 800,
            height: 600,
            quality: 80
        };
        $cordovaImagePicker.getPictures(options).then(function(results) {
            var data = [];
            results.forEach(function(itm) {
                var filename = itm.substr(itm.lastIndexOf('/') + 1);
                data.push({
                    name: filename,
                    type: 'image/jpeg',
                    localURL: itm
                });
            })
            $scope.phoneUpload(data);
        });
    }
    $scope.takePicture = function() {
        styleUpload = 'camera';
        var options = {
            quality: 80,
            destinationType: Camera.DestinationType.FILE_URI,
            sourceType: Camera.PictureSourceType.CAMERA,
            // allowEdit: true,
            // targetWidth: 500,
            // targetHeight: 500,
            encodingType: Camera.EncodingType.JPEG,
            popoverOptions: CameraPopoverOptions,
            saveToPhotoAlbum: true,
            correctOrientation: true
        };
        $cordovaCamera.getPicture(options).then(function(imageData) {
            var filename = imageData.substr(imageData.lastIndexOf('/') + 1);
            $scope.phoneUpload([{
                name: filename,
                type: 'image/jpeg',
                localURL: imageData
            }]);
        }, function(err) {
            $cordovaToast.showLongTop(err);
            console.log(err);
        });
    }
    $scope.filePicker = function() {
        // for IOS
        $timeout(function() {
            FilePicker.pickFile(function(path) {
                var arrFileSplit = path.split(".");
                var type = getFileType(arrFileSplit[arrFileSplit.length - 1].toLowerCase());
                var filename = path.substr(path.lastIndexOf('/') + 1);
                $scope.phoneUpload([{
                    name: filename,
                    type: type,
                    localURL: path
                }]);
                //if error change picker for android
            }, function(err) {
                fileChooser.open(function(uri) {
                    // convert uri include extension
                    window.FilePath.resolveNativePath(uri, function(path) {
                        var arrFileSplit = path.split(".");
                        var type = getFileType(arrFileSplit[arrFileSplit.length - 1].toLowerCase());
                        var filename = path.substr(path.lastIndexOf('/') + 1);
                        $scope.phoneUpload([{
                            name: filename,
                            type: type,
                            localURL: path
                        }]);
                    }, function(errer) {
                        $cordovaToast.showLongTop(errer);
                    });
                }, function(err) {
                    $cordovaToast.showLongTop(err);
                });
            });
        }, 500)
    }
    $scope.phoneUpload = function(fileTransfers) {
        if (fileTransfers.length > 0) {
            $ionicLoading.show({
                template: templateLoading
            });
            $scope.phoneUploadCore(fileTransfers, fileTransfers[0], 0);
        }
    }
    $scope.standarFileName = function(name) {
        name = name.replace(/%2F/g, '-');
        name = name.replace(/%25/g, '-');
        return name;
    }
    $scope.phoneUploadCore = function(fileTransfers, item, index) {
        if (!item) {
            $ionicLoading.hide();
            return;
        }
        var filename = item.name;
        if (storeInCloud) {
            $scope.fileUploadData = {};
            $scope.fileUploadData.type = item.type;
            $scope.fileUploadData.name = $scope.standarFileName(filename);
            $scope.fileUploadData.bucket = bucketName;
            $scope.fileUploadData.acl = aclConfig;
            $scope.fileUploadData.for = 'chats';
            Login.getConfigFileUpload($scope.fileUploadData).success(function(data) {
                var Uoptions = {};
                Uoptions.fileKey = "file";
                Uoptions.fileName = data.folder + '/' + data.microtime + '/' + $scope.standarFileName(filename);
                Uoptions.mimeType = item.type;
                Uoptions.chunkedMode = false;
                Uoptions.headers = {
                    connection: "close"
                };
                Uoptions.params = {
                    "Key": data.folder + '/' + data.microtime + '/' + $scope.standarFileName(filename),
                    "AWSAccessKeyId": data.awsAccessKeyId,
                    "acl": data.acl,
                    "Policy": data.policy,
                    "Signature": data.signature,
                    "success_action_status": data.successActionStatus,
                    "Content-Type": item.type
                };
                $cordovaFileTransfer.upload('http://' + bucketName + '.s3.amazonaws.com/', item.localURL, Uoptions).then(function(return_data) {
                    try {
                        $scope.fileLocation = return_data.headers.Location;
                    } catch (e) {
                        $scope.jsonObject = xml2json.parser(return_data.response);
                        $scope.fileLocation = $scope.jsonObject.postresponse.location;
                    }
                    var type = item.type == 'image/jpeg' ? 'images' : 'file';
                    var data = {
                        from_user: $scope.currentsetting.fromuser_id,
                        room_id: $scope.currentsetting.toroom_id,
                        user_id: $scope.currentsetting.touser_id,
                        hashtag: '',
                        contents: $scope.fileLocation,
                        storeInCloud: storeInCloud,
                        applicationtype: type,
                        phoneApp: true
                    };
                    if (type == 'images') {
                        var thumbnail = {
                            'url': $scope.fileLocation,
                            'filename': $scope.fileUploadData.name,
                            'filetype': type
                        };
                        Lineitems.uploadThumbnail(thumbnail).success(function(response_data) {
                            data['content_raw'] = $scope.fileUploadData.name;
                            if (response_data.thumbnail == "img/file-chat.png") {
                                data.applicationtype = 'file';
                                data.filename = $scope.fileUploadData.name;
                            } else {
                                data['thumbnail'] = response_data.thumbnail;
                            }
                            socket.emit('new message', data);
                            data['time'] = moment().format('YYYY-MM-DD HH:mm:ss');
                            index = index + 1;
                            console.log("thong so:" + index);
                            if (index < fileTransfers.length) {
                                $scope.phoneUploadCore(fileTransfers, fileTransfers[index], index);
                            } else {
                                $ionicLoading.hide();
                            }
                            $scope.histories.push(data);
                            $scope.scrollBottom();
                        });
                    } else {
                        data['filename'] = $scope.fileUploadData.name;
                        socket.emit('new message', data);
                        data['time'] = moment().format('YYYY-MM-DD HH:mm:ss');
                        $scope.histories.push(data);
                        index = index + 1;
                        if (index < fileTransfers.length < index) {
                            $scope.phoneUploadCore(fileTransfers, fileTransfers[index], index);
                        } else {
                            $ionicLoading.hide();
                        }
                    }
                }, function() {
                    index = index + 1;
                    if (index < fileTransfers.length < index) {
                        $scope.phoneUploadCore(fileTransfers, fileTransfers[index], index);
                    } else {
                        $ionicLoading.hide();
                    }
                });
            }).error(function() {
                alert('error');
            });
        } else {
            var type = item.type == 'image/jpeg' ? 'images' : 'file';
            var data = {
                from_user: $scope.currentsetting.fromuser_id,
                room_id: $scope.currentsetting.toroom_id,
                user_id: $scope.currentsetting.touser_id,
                hashtag: '',
                storeInCloud: storeInCloud,
                applicationtype: type,
                phoneApp: true
            };
            $scope.uploadProcess(data, item);
        }
    }
    $scope.uploadProcess = function(data, file) {
        $ionicLoading.show({
            template: templateLoading
        });
        var options = {
            fileName: file.name,
            fileKey: "file",
            params: data,
            mimeType: file.type,
            chunkedMode: false
        }
        $cordovaFileTransfer.upload(url_server + 'lineitems', file.localURL, options).then(function(result) {
            $ionicLoading.hide();
            var data = JSON.parse(result.response);
            data.lineitem.username = $scope.currentuser.name;
            $scope.histories.push(data.lineitem);
            socket.emit('send file', data.lineitem);
            // $scope.progress=-1;   
        }, function(err) {
            $ionicLoading.hide();
            console.log(err);
            console.log("ERROR: " + JSON.stringify(err));
        }, function(progress) {
            $ionicLoading.show({
                template: templateLoading
            });
        });
    }
    $scope.url_site = url_site;
    $scope.formatDate_ = function(item) {
        if (item.id == '') { //message cua user gui se khong lay thoi gian server
            var test = moment(item.time, 'YYYY-MM-DD HH:mm:ss');
            return test.calendar();
        } else { // chuyen doi toi thoi gian cua client
            var test = moment(item.time, ['YYYY-MM-DDTHH:mm:ss.000Z', 'YYYY-MM-DD HH:mm:ss']);
            var d = new Date()
            var n = d.getTimezoneOffset();
            return test.zone(n).calendar();
            // moment().utcOffset
        }
    }
    $scope.buildingDataRoom = function() {
        dataHtml.getTemplate('templates/dashboard/chat/popup/popupAddChatGroup.tpl').success(function(results) {
            $scope.dataChatHtml.popupAddChatGroup = results;
            $scope.showTarget('#popupAddChatGroup');
            if ($scope.allUser.length == 0) {
                $ionicLoading.show({
                    template: templateLoading
                });
                var _param = {
                    rows: 'All'
                }
                Users.getPaging(_param).success(function(data) {
                    _.each(data.data, function(val, index) {
                        nick_name = val.first_name + ' ' + val.last_name;
                        var _item = {
                            id: val.id,
                            screen_name: nick_name + ' - ' + val.positiontitles_name,
                            name: nick_name,
                            imgprofile: pathToPublic + val.image_pic,
                            email: val.email
                        }
                        $scope.allUser.push(_item);
                    });
                    $ionicLoading.hide();
                    $scope.showTarget('#popupAddChatGroup');
                });
            } else {
                //   $scope.showTarget('#popupAddChatGroup');
            }
        })
    }
    $scope.addRoomsData = {};
    $scope.createRooms = function(formValide) {
        if (formValide.$invalid || !$scope.addRoomsData.selectusers || $scope.addRoomsData.selectusers.length == 0) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        $ionicLoading.show({
            template: templateLoading
        });
        Rooms.save($scope.addRoomsData).success(function(data) {
            if (data.status) {
                appDialogToggle('close', '#popupSettingRoomAdd');
                $scope.initialUser = [];
                $scope.addRoomsData = {};
                $scope.addRoomsData.selectusers = [];
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
            if (data.status) {
                $scope.addRoomsData = {};
                $scope.initialUser = [];
                $scope.addRoomsData = {};
                $scope.addRoomsData.selectusers = [];
                $scope.rooms.push(data.room);
                $scope.countRecentItem($scope.rooms, $scope.users);
                socket.emit('create room', data.room);
                $cordovaToast.showLongTop(data.msg);
                $scope.chatContent(data.room.id, true);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
            $ionicLoading.hide();
        });
    }
    // edit by haudao
    $scope.checkAll = function() {
        $scope.addRoomsData.selectusers = angular.copy($scope.users);
    };
    $scope.uncheckAll = function() {
        $scope.addRoomsData.selectusers = [];
    };
    $scope.removeUserInRoom = function(index) {
        $scope.addRoomsData.selectusers.splice(index, 1);
    }
    $scope.editRooms = function(id) {
        dataHtml.getTemplate('templates/dashboard/chat/popup/popupEditChatGroup.tpl').success(function(datahtml) {
            $scope.dataChatHtml.popupEditChatGroup = datahtml;
            if ($scope.allUser.length == 0) {
                $ionicLoading.show({
                    template: templateLoading
                });
                var _param = {
                    rows: 'All'
                }
                Users.getPaging(_param).success(function(data) {
                    _.each(data.data, function(val, index) {
                        nick_name = val.first_name + ' ' + val.last_name;
                        var _item = {
                            id: val.id,
                            screen_name: nick_name + ' - ' + val.positiontitles_name,
                            name: nick_name,
                            imgprofile: pathToPublic + val.image_pic,
                            email: val.email
                        }
                        $scope.allUser.push(_item);
                    });
                    Rooms.show(id).success(function(data) {
                        $scope.editRoomsData = data;
                        $scope.editRoomsData.selectusers = data.users;
                        var arr = [];
                        $scope.editRoomsData.selectusers.forEach(function(item) {
                            arr.push(item.id);
                        });
                        $scope.initialUserEdit = _.uniq(arr);
                        $ionicLoading.hide();
                    });
                });
            } else {
                Rooms.show(id).success(function(data) {
                    $scope.editRoomsData = data;
                    $scope.editRoomsData.selectusers = data.users;
                    var arr = [];
                    $scope.editRoomsData.selectusers.forEach(function(item) {
                        arr.push(item.id);
                    });
                    $scope.initialUserEdit = _.uniq(arr);
                    $ionicLoading.hide();
                });
            }
        });
    }
    $scope.updateRooms = function(formValide) {
        if (formValide.$invalid || !$scope.editRoomsData.selectusers || $scope.editRoomsData.selectusers.length == 0) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        $ionicLoading.show({
            template: templateLoading
        });
        var id = $scope.editRoomsData.id;
        Rooms.update(id, $scope.editRoomsData).success(function(data) {
            ionicLoading.hide();
            if (data.status) {
                $scope.closeTarget('#popupEditChatGroup');
                $scope.editRoomsData = {};
                var room_index = $scope.findRoomIndex({
                    id: data.room.id
                });
                if (room_index >= 0) {
                    socket.emit('create room', data.room);
                    $scope.updateRoom(data.room, room_index);
                }
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        });
    }
    $scope.refreshUserEdit = function(address) {
        if (address.length > 0) {
            var params = {
                search: address
            };
            Users.getSelect2ByChat(params).success(function(data) {
                var diff = differentArray(data, $scope.editRoomsData.selectusers);
                $scope.searchusers = diff;
            })
        } else {
            $scope.searchusers = [];
        }
    };
    $scope.addRoomsData.selectusers = [];
    $scope.refreshAddresses = function(address) {
        if (address.length > 0) {
            var params = {
                search: address
            };
            Users.getSelect2ByChat(params).success(function(data) {
                var diff = differentArray(data, $scope.addRoomsData.selectusers);
                $scope.searchusers = diff;
            })
        } else {
            $scope.searchusers = [];
        }
    };
    /*End Room*/
    $scope.updateResultChatSearch = function() {
        $('.chat-contact .contacts .tab-nav .tab-content > .scrollbar').scrollTop(0);
        //$('.chat-contact .contacts .tab-nav .tab-content > .scrollbar').perfectScrollbar('update');
    }
    /*START SOCKET*/
    socket.on('gethistoriespaging', function(data) {
        $scope.$apply(function() {
            $scope.isrequest = true;
            if (data.histories.length == 0) {
                return;
            }
            //data.histories = data.histories.reverse();
            data.histories = _.sortBy(data.histories, 'id');
            if (data.current.toroom_id != 0) {
                var room_index = _.findIndex($scope.rooms, {
                    id: data.current.toroom_id
                });
                $scope.rooms[room_index].histories = data.histories.concat($scope.rooms[room_index].histories);
                if ($scope.currentsetting.toroom_id == data.current.toroom_id) {
                    $scope.histories = $scope.rooms[room_index].histories;
                }
            } else {
                var user_index = _.findLastIndex($scope.users, {
                    id: (data.current.touser_id)
                });
                $scope.users[user_index].histories = data.histories.concat($scope.users[user_index].histories);
                if ($scope.currentsetting.touser_id == data.current.touser_id) {
                    $scope.histories = $scope.users[user_index].histories;
                }
            }
        });
    })
    socket.on('new message', function(data) {
        //console.log(data);
        //var dataBubble = {};
        var checkPositionButton = $scope.checkPositionButton();
        var localPushData = {};
        localPushData.from_user = data.from_user;
        localPushData.message = data.message;
        localPushData.room_id = data.room_id;
        localPushData.applicationtype = data.applicationtype;
        localPushData.username = data.username;
        localPushData.room_name = '';
        //----------------------------
        if (data.room_id != 0) { //group
            if ($scope.currentsetting.toroom_id == data.room_id) {
                $timeout(function() {
                    $scope.stopBlink();
                    $scope.blink(data.username, data.message);
                    $scope.histories.push(data);
                    if (!isChatting) { //khong o trong cua so chat
                        var room_index = _.findLastIndex($scope.rooms, {
                            id: data.room_id
                        });
                        localPushData.room_name = $scope.rooms[room_index].name;
                        $scope.rooms[room_index].msg = data;
                        $scope.rooms[room_index].msg.contents = data.message;
                        $scope.rooms[room_index].msg.isread = '0';
                        $scope.rooms[room_index].time = moment(data.time, 'YYYY-MM-DD H:mm:ss').valueOf() / 1000;
                        $scope.pushNotify($scope.rooms[room_index], data, localPushData, true);
                    }
                    $scope.scrollBottom();
                }, 0);
            } else {
                $timeout(function() {
                    var room_index = _.findLastIndex($scope.rooms, {
                        id: data.room_id
                    });
                    if (room_index >= 0) { // neu room ton tai thi dua vao
                        if (!$scope.rooms[room_index].histories) {
                            $scope.rooms[room_index].histories = [];
                        }
                        $scope.rooms[room_index].histories.push(data);
                        localPushData.room_name = $scope.rooms[room_index].name;
                        $scope.rooms[room_index].msg = data;
                        $scope.rooms[room_index].msg.contents = data.message;
                        $scope.rooms[room_index].msg.isread = '0';
                        $scope.rooms[room_index].time = moment(data.time, 'YYYY-MM-DD H:mm:ss').valueOf() / 1000;
                        $scope.pushNotify($scope.rooms[room_index], data, localPushData, true);
                    }
                }, 0);
            }
        } else {
            if ($scope.currentsetting.touser_id == data.from_user && $scope.currentuser.id == data.user_id) { //neu thuc su gui cho hien tail
                $timeout(function() {
                    $scope.stopBlink();
                    $scope.blink(data.username, data.message);
                    $scope.histories.push(data);
                    if (!isChatting) { //khong o trong cua so chat
                        var user_index = _.findLastIndex($scope.users, {
                            id: data.from_user
                        });
                        var currentuser = $scope.users[user_index];
                        currentuser.msg = data;
                        currentuser.msg.contents = data.message;
                        currentuser.msg.isread = '0';
                        currentuser.time = moment(data.time, 'YYYY-MM-DD H:mm:ss').valueOf() / 1000;
                        if (currentuser.userhide == true) {
                            var showHideContactObj = {
                                'id_currentuser': $scope.currentuser.id,
                                'id_hidecontact': currentuser.id
                            };
                            currentuser.userhide = false;
                            Chatsettings.showHideContact(showHideContactObj).success(function(data) {
                                currentstatus = false;
                                $scope.closeTarget('#optionChatPerson');
                            });
                        }
                        $scope.pushNotify(currentuser, data, localPushData, false);
                    }
                    $scope.scrollBottom();
                }, 0);
            } else {
                if ($scope.currentuser.id == data.user_id) {
                    $timeout(function() {
                        var user_index = _.findLastIndex($scope.users, {
                            id: data.from_user
                        });
                        if (!$scope.users[user_index].histories) {
                            $scope.users[user_index].histories = [];
                        }
                        var currentuser = $scope.users[user_index];
                        currentuser.histories.push(data);
                        currentuser.msg = data;
                        currentuser.msg.contents = data.message;
                        currentuser.msg.isread = '0';
                        currentuser.time = moment(data.time, 'YYYY-MM-DD H:mm:ss').valueOf() / 1000;
                        $scope.countRecentItem($scope.rooms, $scope.users);
                        if ($scope.users[user_index].userhide == true) {
                            var showHideContactObj = {
                                'id_currentuser': $scope.currentuser.id,
                                'id_hidecontact': currentuser.id
                            };
                            currentuser.userhide = false;
                            Chatsettings.showHideContact(showHideContactObj).success(function(data) {
                                $scope.closeTarget('#optionChatPerson');
                            });
                        }
                        $scope.pushNotify(currentuser, data, localPushData, false);
                    }, 0);
                }
            }
        }
    });
socket.on('create room', function(data) {
    var room = {
        id: data.id
    };
    var user = {
        id: $scope.currentuser.id
    };
    var room_index = $scope.findRoomIndex(room);
    var user_index = _.findLastIndex(data.users, user);
    $timeout(function() {
            //khi user khong so huu phong
            if (room.user_id != $scope.currentuser.id) {
                if (room_index >= 0 && user_index < 0) {
                    $scope.removeRoom(room_index);
                }
                if (room_index >= 0 && user_index >= 0) {
                    $scope.updateRoom(data, room_index);
                }
                if (room_index < 0 && user_index >= 0) {
                    $scope.addRoom(data, room_index, user_index);
                }
            } else {
                if (room_index >= 0 && user_index >= 0) {
                    $scope.updateRoom(data, room_index);
                }
                if (room_index < 0 && user_index >= 0) {
                    $scope.addRoom(data, room_index, user_index);
                }
            }
        }, 0);
});
$scope.stopTyping = {};
socket.on('typing', function(data) {
    $timeout(function() {
        var curr = ((data.toroom_id == 0 && data.fromuser_id == $scope.currentsetting.touser_id) || (data.toroom_id != 0 && data.toroom_id == $scope.currentsetting.toroom_id));
        if (curr == true) {
            $scope.typestatustus.current = data.from_name + ' is typing ...';
            $scope.typestatustus.disp = data.from_name;
            stopTyping = $timeout($scope.typingmessage, 3000);
        }
    }, 0);
});
socket.on('reconnect', function() {
    setUsername();
});
socket.on('gethistories', function(data) {
    data.histories = _.sortBy(data.histories, 'id');
    $timeout(function() {
        _.each(data.histories, function(item) {
            if (item.applicationtype == $scope.applicationtype.image && item.thumbnail && item.thumbnail.indexOf('http') < 0) {
                item.thumbnail = url_site + "/" + item.thumbnail;
            }
            return item;
        });
        if (data.current.toroom_id != 0) {
            var room_index = _.findIndex($scope.rooms, {
                id: (data.current.toroom_id)
            });
            if (!$scope.rooms[room_index].histories) {
                $scope.rooms[room_index].histories = [];
            }
            $scope.rooms[room_index].histories = data.histories;
            $scope.rooms[room_index].gethistories == true;
            if ($scope.currentsetting.toroom_id == data.current.toroom_id) {
                $scope.histories = chat_head == null || (window.location.pathname).substring((window.location.pathname).lastIndexOf('/') + 1) == 'chat.html' ? data.histories : data.histories;
            }
            $ionicLoading.hide();
            if (getParameterByName('message')) {
                if ($scope.historiesOnHightlightAppointment) {
                    $scope.rooms[room_index].histories = $scope.historiesOnHightlightAppointment;
                    $scope.histories = $scope.historiesOnHightlightAppointment;
                    $scope.historiesOnHightlightAppointment = null;
                }
                $ionicScrollDelegate.$getByHandle('scrollerPopupChatDetail').scrollTop(true);
            } else {
                $scope.scrollBottom();
            }
        } else {
            var user_index = _.findLastIndex($scope.users, {
                id: (data.current.touser_id)
            });
            if (!$scope.users[user_index].histories) {
                $scope.users[user_index].histories = [];
            }
            //$scope.users[user_index].histories = data.histories.reverse();
            $scope.users[user_index].histories = _.sortBy(data.histories, 'id');
            $scope.users[user_index].gethistories == true;
            if ($scope.currentsetting.touser_id == data.current.touser_id) {
                $scope.histories = data.histories;
            }
            $ionicLoading.hide();
            $scope.scrollBottom();
        }
    }, 100);
})
socket.on('changestatus', function(data) {
    $timeout(function() {
        var user = {
            id: data.user_id
        };
        if (user.id == $scope.currentuser.id) {
            var status = _.find($scope.chatstatuses, {
                id: data.status + ''
            });
            if (status) {
                $scope.status = status;
            }
            return;
        }
        var index = $scope.findIndex($scope.users, user);
        if (index >= 0) {
                if (data.status == 3) { //offline;
                    $scope.users[index].status = false;
                    $scope.users[index].idle = false;
                    $scope.users[index].disturb = false;
                } else { //1 online, 2 ndisturb, 4 idle;
                    $scope.users[index].status = true;
                    $scope.users[index].idle = (data.status == 4) ? true : false;
                    $scope.users[index].disturb = (data.status == 2) ? true : false;
                }
            }
        }, 10);
        // edit by haudao
        $scope.count_online = 0;
        $scope.count_offline = 0;
        $scope.count_contact = $scope.users.length;
        for (var i = 0; i < $scope.count_contact; i++) {
            if ($scope.users[i].status) {
                $scope.count_online++;
            } else {
                $scope.count_offline++;
            }
        }
    });
socket.on('list online', function(data) {
    $timeout(function() {
        for (var p in data) {
            _.each($scope.users, function(item) {
                if (item.id == p) {
                    item.status = data[p];
                        if (item.status == 3) { //offline;
                            item.status = false;
                            item.idle = false;
                            item.disturb = false;
                        } else { //1 online, 2 ndisturb, 4 idle;
                            item.status = true;
                            item.idle = (data[p] == 4) ? true : false;
                            item.disturb = (data[p] == 2) ? true : false;
                        }
                    }
                    return item;
                });
        }
    }, 10);
})
socket.on('hightlightappointment', function(data) {
    console.log(data)
    $scope.historiesOnHightlightAppointment = data.histories;
    $timeout(function() {
        getHistoriesroom(data);
        var history_length = $scope.histories.length;
        setTimeout(function() {
            $ionicScrollDelegate.$getByHandle('scrollerPopupChatDetail').scrollTop(true);
        }, 1000);
    }, 0);
});
socket.on("logoutsignal",function(data){
    if(data.user_id==$scope.currentuser.id){
        localStorage.setItem("login_status", "0");
        localStorage.setItem("email", "");
        localStorage.setItem("token", "");
        $ionicLoading.hide();
        redirectTo('index.html');
    }
});

function getHistoriesroom(data) {
    if (data.current.toroom_id != 0) {
        var room_index = _.findIndex($scope.rooms, {
            id: (data.current.toroom_id)
        });
        if (!$scope.rooms[room_index].histories) {
            $scope.rooms[room_index].histories = [];
        }
        $scope.rooms[room_index].histories = _.sortBy(data.histories, 'id');
        //$scope.rooms[room_index].histories = data.histories.reverse();
        $scope.rooms[room_index].gethistories == true;
        if ($scope.currentsetting.toroom_id == data.current.toroom_id) {
            $scope.histories = data.histories;
        }
    } else {
        var user_index = _.findLastIndex($scope.users, {
            id: (data.current.touser_id)
        });
        if (!$scope.users[user_index].histories) {
            $scope.users[user_index].histories = [];
        }
        $scope.users[user_index].histories = _.sortBy(data.histories, 'id');
        //$scope.users[user_index].histories = data.histories.reverse();
        $scope.users[user_index].gethistories == true;
        if ($scope.currentsetting.touser_id == data.current.touser_id) {
            $scope.histories = data.histories;
        }
    }
}
/*END SOCKET*/
/*Message converter*/
function replaceEmoticon(msg) {
    for (key in $scope.emoticon) {
        var test = key.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
        var re = new RegExp(test, 'g');
        msg = msg.replace(re, '<img class="emo" src="' + $scope.emoticon[key] + '"/>');
    }
    return msg;
}

function replaceHtml(msg) {
    return msg.replace(/(http|ftp|https:\/\/[\w\-_]+\.{1}[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/gi, '<a class="link" href="$1$2" target="_blank">$1$2</a>');
}

function replaceHashtag(msg) {
    msg = msg.replace(/([\#@][a-zA-Z0-9\-\_]+)/g, "<span class='hash-tag'>$1</span>");
    return msg;
}
/*End Message converter*/
/*typing*/
$scope.typingmessage = function() {
    $scope.typestatustus.current = '...';
}
$scope.cleartyping = function() {
    $scope.typestatustus.current = '...';
    if ($scope.stopTyping) {
        $timeout.cancel($scope.stopTyping);
    }
}
$scope.blink = function(name, message) {
    $scope.titlemessage.disp = name + " say " + message;
    $scope.stopblink = $interval($scope.blinkTitle, 1500);
}
$scope.blinkTitle = function() {
    if ($scope.titlemessage.current == $scope.titlemessage.org) {
        $scope.titlemessage.current = $scope.titlemessage.disp;
    } else {
        $scope.titlemessage.current = $scope.titlemessage.org;
    }
}
$scope.stopBlink = function() {
    var _val = angular.element('#message').val() + "(-.-)";
    angular.element('#message').val(_val);
    angular.element('#message').val(_val.replace("(-.-)", ""));
    $scope.titlemessage.current = "";
    $interval.cancel($scope.stopblink);
}
/*end typing*/
/*Event mouse*/
    // chatstatuses
    var mousestopTime = "";
    var mousestopoffline = "";
    $scope.flag_disturb = false;
    $scope.blur = function() {
        if ($scope.status) {
            if ($scope.status.id == 2) { //non disturb
                $interval.cancel(mousestopTime);
                $interval.cancel(mousestopoffline);
                if (!$scope.flag_disturb) {
                    $scope.notifyStatus(2);
                    $scope.flag_disturb = true;
                }
                return;
            }
            $scope.flag_disturb = false;
            if (mousestopTime || mousestopoffline) {
                $interval.cancel(mousestopTime);
                $interval.cancel(mousestopoffline);
                if ($scope.status.id == 4 || $scope.status.id == 3) {
                    $scope.status = _.find($scope.chatstatuses, function(item) {
                        return item.id == 1;
                    });
                    $scope.notifyStatus(1);
                }
            }
            if ($scope.status.id == 1) {
                mousestopTime = $interval($scope.setIdle, time_idle);
                $interval.cancel(mousestopoffline);
            }
        }
    }
    $scope.setIdle = function() {
        $scope.status = _.find($scope.chatstatuses, function(item) {
            return item.id == 4;
        });
        $scope.notifyStatus(4);
        $interval.cancel(mousestopTime);
        mousestopoffline = $interval($scope.setOffline, time_offline);
    }
    $scope.setOffline = function() {
        $scope.status = _.find($scope.chatstatuses, function(item) {
            return item.id == 3;
        });
        $scope.notifyStatus(3);
    }
    $scope.clearDataPopup = function() {
        $scope.dataFileLibrary = [];
        $scope.data_date = [];
    }
    $scope.openPopupFileAlbumChat = function(history, searchall) {
        $scope.openByGetTemplate('popupChatDetailFile');
        $scope.closeTarget('#optionChatPerson');
        $scope.clearDataPopup();
        $scope.searchLibraryData = {};
        if (!$scope.userhide.is_room) {
            $scope.searchLibraryData.user_id = $scope.userhide.currentid;
            $scope.searchLibraryData.from_user = $scope.currentuser.id;
            $scope.searchLibraryData.room_id = 0;
        } else {
            $scope.searchLibraryData.room_id = $scope.userhide.currentid;
        }
        if (searchall == '-1') {
            $scope.searchLibraryData.room_id = -1;
        }
        $scope.searchLibrary();
    }
    // $scope.showlibrary={'all':true,'image':true,'link':true,'pdf':true,'other':true};
    $scope.activeTabLibrary = function(tab) {
        switch (tab) {
            case 'all':
            $scope.showlibrary.all = true;
            $scope.showlibrary.image = true;
            $scope.showlibrary.link = true;
            $scope.showlibrary.pdf = true;
            $scope.showlibrary.other = true;
            break;
            case 'image':
            $scope.showlibrary.all = false;
            $scope.showlibrary.image = true;
            $scope.showlibrary.link = false;
            $scope.showlibrary.pdf = false;
            $scope.showlibrary.other = false;
            break;
            case 'link':
            $scope.showlibrary.all = false;
            $scope.showlibrary.image = false;
            $scope.showlibrary.link = true;
            $scope.showlibrary.pdf = false;
            $scope.showlibrary.other = false;
            break;
            case 'pdf':
            $scope.showlibrary.all = false;
            $scope.showlibrary.image = false;
            $scope.showlibrary.link = false;
            $scope.showlibrary.pdf = true;
            $scope.showlibrary.other = false;
            break;
            case 'other':
            $scope.showlibrary.all = false;
            $scope.showlibrary.image = false;
            $scope.showlibrary.link = false;
            $scope.showlibrary.pdf = false;
            $scope.showlibrary.other = true;
            break;
        }
    }
    $scope.searchLibraryChange = function() {
        var searchall = $scope.searchLibraryData.room_id;
        $scope.searchLibrary('', searchall);
    }
    $scope.searchLibrary = function() {
        $ionicLoading.show({
            template: templateLoading
        });
        $scope.activeTabLibrary('all');
        Lineitems.searchLibrary($scope.searchLibraryData).success(function(data) {
            $ionicLoading.hide();
            var dataFileLibrary = [];
            var data_date = [];
            var dataFile = data.data;
            if (dataFile == '') {
                $scope.nodata = '<div><span>No Data Found.</span></div>';
            }
            for (var i = 0; i < dataFile.length; i++) {
                if (data_date.indexOf(dataFile[i].date) < 0) {
                    data_date.push(dataFile[i].date);
                }
            }
            $scope.data_date = data_date;
            for (var i = 0; i < dataFile.length; i++) {
                //var datetime = new Date(dataFile[i].servertime);
                var datetime = moment(dataFile[i].servertime, 'YYYY-MM-DD HH:mm:ss').format('hh:mm:ss')
                if (dataFile[i].applicationtype == 'images') {
                    dataFile[i].type = 'image';
                    if (dataFile[i].thumbnail.indexOf('http') < 0) {
                        dataFile[i].thumbnail = url_site + "/" + dataFile[i].thumbnail;;
                    }
                    dataFile[i].time = datetime;
                    dataFileLibrary.push(dataFile[i]);
                } else if (dataFile[i].applicationtype == 'link') {
                    var regex = /<img.*?src='(.*?)'/;
                    if (regex.exec(dataFile[i].contents) != null) {
                        dataFile[i].type = 'link';
                        dataFile[i].src = regex.exec(dataFile[i].contents)[1];
                    } else {
                        dataFile[i].src = null;
                    }
                    dataFile[i].title = $("div", dataFile[i].contents).remove().html();
                    dataFile[i].time = datetime;
                    dataFileLibrary.push(dataFile[i]);
                } else {
                    if (dataFile[i].filename != null) {
                        if (dataFile[i].filename.includes('.pdf')) {
                            dataFile[i].type = 'pdf';
                            dataFile[i].time = datetime;
                            dataFileLibrary.push(dataFile[i]);
                        } else {
                            dataFile[i].type = 'other';
                            dataFile[i].time = datetime;
                            dataFileLibrary.push(dataFile[i]);
                        }
                    }
                }
            }
            $scope.dataFileLibrary = _.sortBy(dataFileLibrary, -'servertime');
        });
    }
    $scope.showListDate = function(item2, item) {
        switch (item) {
            case 'image':
            var showListDate = _.where($scope.dataFileLibrary, {
                type: 'image',
                date: item2
            });
            break;
            case 'pdf':
            var showListDate = _.where($scope.dataFileLibrary, {
                type: 'pdf',
                date: item2
            });
            break;
            case 'link':
            var showListDate = _.where($scope.dataFileLibrary, {
                type: 'link',
                date: item2
            });
            break;
            case 'other':
            var showListDate = _.where($scope.dataFileLibrary, {
                type: 'other',
                date: item2
            });
            break;
        }
        if (showListDate.length > 0) {
            return true;
        } else {
            return false;
        }
    }
    /*end Event mouse*/
    $scope.hideAddGroup = function() {
        switch ($scope.roleName) {
            //saleman
            case $scope.isSalesman:
            return true;
            break;
                //fieldinstaller
                case $scope.isFieldinstaller:
                return true;
                break;
                //admin
                case $scope.isAdmin:
                return false;
                break;
                //manager
                case $scope.isManager:
                return false;
                break;
                //isReporter
                case $scope.isReporter:
                return true;
                break;
                //isScheduler
                case $scope.isScheduler:
                return true;
                break;
                default:
                return true;
            }
        }
    // Tab Emoticon Handle
    //$scope.tabEmoticonChatActive = 'Set1';
    $scope.setTabEmoticonChat = function(tab) {
        $scope.tabEmoticonChatActive = tab;
        $scope.objChatHead($scope);
    }
    $scope.preventHideKeyboard = function() {
        $focusTest.setFocusOnBlur(true);
    }
    $scope.trustAsHtml = function(data) {
        if (data) {
            return $sce.trustAsHtml(data);
        }
    }
    $scope.replaceHtml = function(data) {
        if (data && data.applicationtype == 'link') {
            return data.contents = data.contents.replace(/href="[^"]*"/g, "").replace(/href='[^"]*'/g, "");
        }
    }
    $scope.backToOppId = function(data) {
        redirectTo('opportunity.html?pendingId=' + $scope.pendingId + '#/board/')
    }
    $scope.closePopupChat = function(data) {
        isChatting = false;
        $scope.closeTarget('#popupChatDetail');
    }

    $scope.findHasTag = function(hastag) {

        if (!hastag) {
            return false;
        } else {
            var tag = '@' + $scope.currentuser.name.replace(/ /g, '_');
            var tag2 = '#' + $scope.currentuser.name.replace(/ /g, '_');
            var hashtags = hastag.split(',');
            return hashtags.indexOf(tag) > -1 ? true : false || (hashtags.indexOf(tag2) > -1 ? true : false);
        }
        return false;
    }

    $scope.$on('getJsonData', function(event, args) {
        var jsondata = args.data;
        var index = _.findIndex(jsondata, {
            roletree_id: '77'
        });
        if (jsondata[index].check) {
            $scope.showChangeStatus = jsondata[index].child[0].check;
            $scope.showInputMessege = jsondata[index].child[1].child[0].check;
            $scope.showShareFile = jsondata[index].child[1].child[1].check;
            $scope.showLibrary = jsondata[index].child[1].child[2].check;
            $scope.showChatSetting = jsondata[index].child[1].child[3].check;
            $scope.showButtonHideUser = jsondata[index].child[2].check;
            $scope.showButtonEditChatGroup = jsondata[index].child[3].check;
            $scope.showButtonSearchMessege = jsondata[index].child[4].check;
            $scope.showLibraryOnTop = jsondata[index].child[5].check;
            $scope.getChatSetting();
            if (page && page == "chat.html") $scope.renderTemplateData();
        } else {
            localStorage.setItem("login_status", "0");
            redirectTo('index.html');
        }
    });
    /*for chat head*/
    $scope.$on('$includeContentLoaded', function() { // regis action popupform dĂ¹ng chung lĂ²ng nhau
        if (chat_head == null) {
            return;
        }
        chat_head.initial('.out_chat_container', '.chat_container', '.drop-area', function() {
            if (chat_head.lock_module) {
                $scope.lock_module = chat_head.lock_module;
            }
            chat_head.scope = $scope;
            chat_head.compile = $compile;
            //chat_head.utilities();
            chat_head.refreshLayout('#show_chathead_when_load');
            chat_head.eventlistener();
            $scope.objChatHead($scope);
            $scope.emoticonChatHandle();
        })
    });
});