// if(!app){
// 	var app = angular.module('App',[
// 	'LoginService',
// 	'usersService',
// 	'feedtitlesCtrl',
// 	'navDirective',
// 	'ngFileUpload',
// 	'ckDirective',
// 	'datetimepicker',
// 	'modalDirective',
// 	'lineitemsCtrl',
// 	'punchinsCtrl',
// 	'ui.bootstrap',
// 	'ngSanitize',
// 	'ui.select',
// 	'pickerDirective',
// 	'feedtitlesDirective',
// 	'feedtitlesService',
// 	'feedtitlesaddmodalDirective',
// 	'feedtitleseditmodalDirective']);
// }

// app.filter('propsFilter', function() {
// 	return function(items, props) {
// 		var out = [];
// 		if (angular.isArray(items)) {
// 			var keys = Object.keys(props);
// 			items.forEach(function(item) {
// 				var itemMatches = false;
// 				for (var i = 0; i < keys.length; i++) {
// 					var prop = keys[i];
// 					var text = props[prop].toLowerCase();
// 					if (item[prop] && item[prop].toString().toLowerCase().indexOf(text) !== -1) {
// 						itemMatches = true;
// 						break;
// 					}
// 				}
// 				if (itemMatches) {
// 					out.push(item);
// 				}
// 			});
// 		} else {
// 			out = items;
// 		}
// 		return out;
// 	};
// });
// app.filter('phoneFilter', function() {
// 	return function(items, props) {
// 		var out = [];
// 		if (angular.isArray(items)) {
// 			var keys = Object.keys(props);
// 			items.forEach(function(item) {
// 				var itemMatches = false;
// 				for (var i = 0; i < keys.length; i++) {
// 					var prop = keys[i];
// 					var text = props[prop].toLowerCase();
// 					text = text.replace('-','');
// 					text = text.replace('-','');
// 					if (item[prop] && item[prop].toString().toLowerCase().indexOf(text) !== -1) {
// 						itemMatches = true;
// 						break;
// 					}
// 				}
// 				if (itemMatches) {
// 					out.push(item);
// 				}
// 			});
// 		} else {
//                 // Let the output be the input untouched
//                 out = items;
//             }
//             return out;
//         };
//     });

// /*
//  * angular-elastic v2.5.1
//  * (c) 2014 Monospaced http://monospaced.com
//  * License: MIT
//  */


var customereviews_pagesize = $('#customereviews_pagesize');
angular.module('feedtitlesCtrl', []).controller('feedtitlesController', function($scope, $timeout, $http, $window, $interval, Login, //
    Feedtiltles, $ionicLoading, $cordovaToast, $ionicPopup,$timeout) {
    withoutPopup_Feedttile = $scope;
    $scope.tier = tier;
    withoutPopup = $scope;
    $scope.dataFilterLoaded = false;
    $scope.currentPage = 1;
    var pager = localStorage.getItem('customereviews_pagesize');
    $scope.itemsPerPage = pager ? pager : 50;
    $scope.entryLimit = $scope.itemsPerPage;
    $scope.searchFeedtitles = { rows: $scope.itemsPerPage, current_page: $scope.currentPage, search: "" };

    $scope.currentIdLogin = currentIdLogin;
    $scope.roleName = role;
    $scope.isAdmin = isAdmin;
    $scope.isManager = isManager;
    $scope.isReporter = isReporter;
    $scope.isScheduler = isScheduler;
    $scope.isFieldinstaller = isFieldinstaller;
    $scope.isSalesman = isSalesman;
    $scope.isWarehouse = isWarehouse;

    $scope.coundown = 10;
    $scope.myTime = null;

    $scope.addFeedTitleData = {};
    $scope.editFeedtitleData = {};

    $scope.checkreview = false;
    $scope.checkemployee = false;
    $scope.firstLoad = true;
    $scope.ShowAll_FeedTile=false;
    $scope.setTime = false;

    $scope.getFeedTitle = function() {
        $ionicLoading.show({
            template: templateLoading
        });
        Feedtiltles.getPaging($scope.searchFeedtitles).success(function(data) {
            $ionicLoading.hide();
            $scope.feedtitles = data.data;
            $scope.currentPage = data.page;
            $scope.itemsPerPage = $scope.searchFeedtitles.rows;
            customereviews_pagesize.val($scope.itemsPerPage);
            $scope.totalItems = data.total_rows;
            request_notify_get_chat = true;
            // $scope.repalaceres();
        });
    };
    $scope.ShowActive_FT = function(show_all) {
        $scope.searchFeedtitles.show_all = show_all;
        $scope.getFeedTitle();
    }
    $scope.repalaceres = function(data) {
        setTimeout(function() {
            $scope.$apply(function(val) {
                if (val) {
                    $('#tableFeedtitle').tableRespondsive({
                        paging: true,
                        pagingArg: {
                            totalRow: 105,
                            rowPerPage: 50,
                            currentPage: 2
                        }
                    });
                    $('.dashboard > .tblloader').hide();
                    $('#document').show();
                    $('#document .tblloader').hide();
                    $('#document .tblloader_feedtitle').hide();

                    $('.content .row').show();

                }
            });
        }, 1);
    }

    $scope.getDataFilter = function() {
        if (!$scope.dataFilterLoaded) {
            Reviews.getSelectFilter().success(function(data) {
                $scope.reviewTitle = $scope.initNode('Reviews', data.review);
                $scope.employeeTitle = $scope.initNode('Employee', data.employee);
                $scope.dataFilterLoaded = true;
            });
        }
    }

    $scope.initNode = function(lblRoot, objChild) {
        var _node = [];
        _node = [{
            label: lblRoot,
            selected: true,
            children: []
        }];
        for (var i = 0; i < objChild.length; i++) {
            var _item = {
                label: objChild[i].name,
                selected: true
            };
            _.where(_node[0].children, {
                label: _item.label
            }).length == 0 ? _node[0].children.push(_item) : '';
        }
        return _node;
    }

    $scope.changeCallback = function(node, forFilter) {
        var __where = _.where(node[0].children, {
            selected: true
        });
        var __filter = new Array();
        for (var i = 0; i < __where.length; i++) {
            __filter = _.union(__filter, _.filter($scope.filterClientdata, function(item) {
                if (forFilter == 1) {
                    return item.reviewName === __where[i]['label'];
                } else {
                    return item.empName === __where[i]['label'];
                }
            }));
        }
        return _.intersection($scope.filterClientdata, __filter);
    }

    $scope.getfilterClient = function() {
        $('#document .tblloader').show();
        $('.content .row').hide();
        var _f1 = $scope.changeCallback($scope.reviewTitle, 1);
        var _f2 = $scope.changeCallback($scope.employeeTitle, 2);
        $scope.customereviews = _.intersection(_f1, _f2);
        $scope.repalaceres();
    }

    $scope.order = function(predicate, check) {
        $scope.predicate = predicate;
        if (check == 'Oldest') {
            $scope.reverse = true;
        } else {
            $scope.reverse = false;
        }
        $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
        $scope.predicate = predicate;
    };

    $scope.refreshCustomers = function(customers) {
        if (customers.length > 0) {
            $('#selectCus').find('.notif').text('');
            var params = {
                search: customers
            };
            Customers.getSelect2(params).success(function(data) {
                var diff = differentArray(data, $scope.addCustomereviewsData.selectCustomer);
                $scope.customerses = diff;
            })
        }
    };

    $scope.refreshEmployeeReview = function(search) {
        if (search.length > 0) {
            $('#selectEmployee').find('.notif').text('');
            var params = {
                search: search
            };
            Users.searchAssign(params).success(function(res) {
                var diff = differentArray(res, $scope.employeeReview);
                $scope.employeeReviewSelect = diff;
            })
        } else {
            $scope.employeeReviewSelect = [];
        }
    };

    $scope.searchChanged = function() {
        $scope.getFeedTitle();
    }

    $scope.sizeChanged = function() {
        $scope.searchFeedtitles.rows = $scope.entryLimit;
        customereviews_pagesize.val($scope.searchFeedtitles.rows);
        localStorage.setItem('customereviews_pagesize', $scope.searchFeedtitles.rows);
        $scope.searchFeedtitles.current_page = 1;
        $scope.getFeedTitle();
    }
    $scope.pageChanged = function() {
        console.log($scope.currentPage);
        $scope.searchFeedtitles.current_page = $scope.currentPage;
        $scope.getFeedTitle();
    };
    $scope.setPage = function(pageNo) {
        $scope.currentPage = pageNo;
    };

    $scope.createFeedTitle = function(formValidate) {
        if (formValidate.$invalid) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        $ionicLoading.show({
            template: templateLoading
        });

        Feedtiltles.save($scope.addFeedTitleData).success(function(data) {
            $ionicLoading.hide();
            if (data.status) {
                $scope.getFeedTitle();
                closeTarget("#settingFeedTitleManagementAdd");
                $scope.addFeedTitleData = {};
                closeovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    }
    $scope.infoFeedTitleAction = {};
    $scope.openPopupFeedTitleOption = function(item) {
        $scope.infoFeedTitleAction.id = parseInt(item.id);
        $scope.infoFeedTitleAction.status = parseInt(item.status);
        $scope.editFeedtitle(item.id);
        appDialogToggle('open', '#popupSettingFeedTitleOptions');
    }
    $scope.editFeedtitle = function(id) {
        $ionicLoading.show({
            template: templateLoading
        });
        Feedtiltles.show(id).success(function(data) {
            $scope.editFeedtitleData = data;
            $ionicLoading.hide();
        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    }
    $scope.updateFeedtitle = function(formValidate) {
        if (formValidate.$invalid) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        $ionicLoading.show({
            template: templateLoading
        });
        var id = $scope.editFeedtitleData.id;
        Feedtiltles.update(id, $scope.editFeedtitleData).success(function(data) {
            $ionicLoading.hide();
            if (data.status) {
                var idx = _.findLastIndex($scope.feedtitles, { id: id });
                $scope.feedtitles[idx].feedgroup = $scope.editFeedtitleData.feedgroup;
                $scope.feedtitles[idx].feedtitle = $scope.editFeedtitleData.feedtitle;
                $scope.editFeedtitleData = {};
                // $scope.getFeedTitle();
                closeTarget("#settingFeedTitleManagementEdit");
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    }


    $scope.deleteFeedTileData={};
    $scope.confrimFeedtitle = function(item) {
        $scope.deleteFeedTileData = item;
    }
    $scope.deleteFeedtitle = function() {
        closeTarget("#settingFeedTitleManagementDelete");
        $ionicLoading.show({
            template: templateLoading
        });
        var id=$scope.deleteFeedTileData.id;
        var status=$scope.deleteFeedTileData.status;
        Feedtiltles.destroy(id).success(function(data) {
            $ionicLoading.hide();
            var idx = _.findLastIndex($scope.feedtitles, {id: id});
            if (data.status) {
                if ($scope.ShowAll_FeedTile) {
                    $scope.feedtitles[idx].status = status == "1" ? "0" : "1";
                } else {
                    $scope.feedtitles.splice(idx, 1);
                }
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });

    }

    $scope.setIndexViewOptionFeedTitle = function(index){
            $scope.index_option_feed_title=index;
            $timeout( function(){
                $('#btn-view-option-feed-title-'+index).next('.quick-popup').addClass('show');
            }, 100);
        }
        // $scope.deleteFeedtitle = function(id, confirm) {
        //     Feedtiltles.destroy(id).success(function(data) {
        //         if (data.status) {
        //             $.notification('<div class="text-content">' + data.msg + '</div>', {
        //                 messageType: 'message-success',
        //                 autoClose: true
        //             });
        //             confirm.switchStateDialog("close");
        //         } else {
        //             $.notification('<div class="text-content">' + data.msg + '</div>', {
        //                 messageType: 'message-success',
        //                 autoClose: true
        //             });
        //             confirm.switchStateDialog("close");
        //         }
        //         $scope.getFeedTitle();
        //     });
        // }

    $scope.getUserLogin = function() {
        return Login.getUserLogin().success(function(data) {
            if (data == false) {
                $scope.displayname = "Profile";
            } else {
                var displayname = (data.first_name != null ? data.first_name : '') + ' ' + (data.last_name == null ? '' : data.last_name);
                $scope.imagePath = pathToPublic + data.image_pic;
                if ($.trim(displayname) == "") {
                    $scope.displayname = "Hello, " + data.email;
                } else {
                    $scope.displayname = "Hello, " + displayname;
                }
            }
            if (!$scope.setTime) {
                /*  $('#start_time').val(moment().format('MM/DD/YYYY'));
                  $('#end_time').val(moment().format('MM/DD/YYYY'));*/
            }
            //$scope.getFeedTitle();
        });
    }

    $scope.logout = function() {
        return Login.logout().success(function(data) {
            $window.location.href = url_login;
        });
    }

    $scope.checkLogin = function() {
        return Login.checkLogin().success(function(data) {
            if (data.status == false) {
                $window.location.href = url_login;
            } else {
                $scope.getUserLogin();
            }
        });
    }

    // $scope.checkLogin();
    // stopTime = $interval($scope.checkLogin, time_refresh);
})
