// if(!app){
// var app = angular.module('App',[
//  //'ui.bootstrap',
//  'LoginService',
//  'supplieritemsService',
//  'supplieritemsCtrl',
//  'supplieritemsEditDirective',
//  'supplieritemsDeleteDirective',
//  'supplieritemsDirective',
//  'supplieritemsAddDirective',
//  'navDirective',
//  'ngFileUpload',
//  'ckDirective',
//  'datetimepicker',
//  'modalDirective',
//  //'ngSanitize',
//  //'expDirective',// remove comment if use file explorer.
//  //'explorerDirective',
//  //'ui.select'
//  ]).config([
//  'datetimepickerProvider',
//  function (datetimepickerProvider) {
//      datetimepickerProvider.setOptions({
//          locale: 'en'
//      });
//  }
//  ])
//  .run([
//      '$rootScope',
//      function ($rootScope) {
//          $rootScope.scoped = {
//              format: 'HH:mm:ss'
//          };
//          $rootScope.vm = {
//              datetime: '05/13/2011 6:30 AM'
//          }
//      }
//      ]);
// 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 {
//                 // Let the output be the input untouched
//                 out = items;
//             }
//             return out;
//         };
//     });

// }
var supplieritems_pagesize = $('#supplieritems_pagesize');
angular.module('supplieritemsCtrl', []).controller('supplieritemsController', function($ionicPopup, $cordovaToast, //
    $ionicLoading, $scope, $http, $window, $interval, Login, Supplieritems,$ionicScrollDelegate,$timeout) {

    $scope.currentPage = 1;
    // var pager = localStorage.getItem('supplieritems_pagesize');
    // $scope.itemsPerPage = pager ? pager : 200;
    $scope.itemsPerPage = 200;
    $scope.entryLimit = $scope.itemsPerPage;
    $scope.searchSupplieritems = { rows: $scope.itemsPerPage, current_page: $scope.currentPage, search: "", show_all: false };
    withoutPopup_SUP = $scope;
    /*$scope.getUsers = function(){
        User.get().success(function(data){
            $scope.users= data;
        });
    }
    $scope.getUsers();
    */


    $scope.getSupplieritems = function() {
        $ionicLoading.show({
            template: templateLoading
        });
        Supplieritems.getPaging($scope.searchSupplieritems).success(function(data) {
            $ionicLoading.hide();
            $scope.supplieritems = data.data;
            $scope.currentPage = data.page;
            $scope.itemsPerPage = $scope.searchSupplieritems.rows;
            supplieritems_pagesize.val($scope.itemsPerPage);
            $scope.totalItems = data.total_rows;
            $ionicScrollDelegate.$getByHandle('scrollSupplieritems').resize();
        }).error(function (data, status, headers, config) {
                    $ionicLoading.hide();
                    console.log('error status: ' + status);
                    $cordovaToast.showLongTop('Connection Error!!!');
                });
    };

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

    $scope.ShowActive_SUP = function(show_all) {
        $scope.searchSupplieritems.show_all = show_all;
        $scope.getSupplieritems();
    }

    /*$scope.getSelectSupplieritems = function(){
        Supplieritems.getSelect().success(function(data){
            $scope.selectSupplieritems = data;
        });
    }
    $scope.getSelecSupplieritems();*/
    /*
    xem demo upload file tai day:
    http://jsfiddle.net/danialfarid/1m6fn6re/
    $scope.upload = function (file) {
        Upload.upload({
            url: '/todo',
            fields: $scope.todoData,
            file: file
        }).progress(function (evt) {
            var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
            console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name);
        }).success(function (data, status, headers, config) {
            console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
        }).error(function (data, status, headers, config) {
            console.log('error status: ' + status);
        })
    };
    */

    $scope.sizeChanged = function() {
        $scope.searchSupplieritems.rows = $scope.entryLimit;
        supplieritems_pagesize.val($scope.searchSupplieritems.rows);
        localStorage.setItem('supplieritems_pagesize', $scope.searchSupplieritems.rows);
        $scope.searchSupplieritems.current_page = 1;
        $scope.getSupplieritems();
    }
    $scope.pageChanged = function() {
        console.log($scope.currentPage);
        $scope.searchSupplieritems.current_page = $scope.currentPage;
        $scope.getSupplieritems();
    };
    // $scope.getSupplieritems();
    $scope.setPage = function(pageNo) {
        $scope.currentPage = pageNo;
        console.log('doi page');
    };

    $scope.addSupplieritemsData = {};
    $scope.createSupplieritems = function(formValide) {
        if (formValide.$invalid) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        $ionicLoading.show({
            template: templateLoading
        });
        Supplieritems.save($scope.addSupplieritemsData).success(function(data) {
            $scope.getSupplieritems();
            closeTarget('#settingSupplierManagementAdd');
            if (data.status) {
                $scope.addSupplieritemsData = {};
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }

        });
    }
    $scope.editSupplieritemsData = {};
    $scope.editSupplieritems = function(id) {
        Supplieritems.show(id).success(function(data) {
            $scope.editSupplieritemsData = data;
        }).error(function (data, status, headers, config) {
                    $ionicLoading.hide();
                    console.log('error status: ' + status);
                    $cordovaToast.showLongTop('Connection Error!!!');
                });
    }
    $scope.updateSupplieritems = function(formValide) {
            if (formValide.$invalid) {
                $cordovaToast.showLongTop('Please fill all the required information.!!!');
                return;
            }
            $ionicLoading.show({
                template: templateLoading
            });
            var id = $scope.editSupplieritemsData.id;

            Supplieritems.update(id, $scope.editSupplieritemsData).success(function(data) {
                $scope.getSupplieritems();
                closeTarget('#settingSupplierManagementEdit');
                if (data.status) {
                    $scope.editSupplieritemsData = {};
                    $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.deleteSupplieritemsData = {};
    $scope.confrimSupplieritems = function(item) {
        $scope.deleteSupplieritemsData = item;

    }
    $scope.deleteSupplieritems = function() {
        var id=$scope.deleteSupplieritemsData.id;
        var status=$scope.deleteSupplieritemsData.status;
        $ionicLoading.show({
            template: templateLoading
        });
        Supplieritems.destroy(id, status).success(function(data) {
            closeTarget('#settingSupplierManagementDelete');
            $ionicLoading.hide();
            var idx = _.findLastIndex($scope.supplieritems, { id: id.toString() });
            if (data.status) {
                if ($scope.searchSupplieritems.show_all) {
                    $scope.supplieritems[idx].status = status == "1" ? "0" : "1";
                } else {
                    $scope.supplieritems.splice(idx, 1);
                }
                $ionicScrollDelegate.$getByHandle('scrollSupplieritems').resize();
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        });
    }

    $scope.setIndexViewOptionSupplierItem = function(index){
            $scope.index_option_supplier_item=index;
            $timeout( function(){
                $('#btn-view-option-supplier-item-'+index).next('.quick-popup').addClass('show');
            }, 100);

        }


    $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);
                if ($.trim(displayname) == "") {
                    $scope.displayname = "Hello, " + data.email;
                } else {
                    $scope.displayname = "Hello, " + displayname;
                }
            }

        });
    }

    // $scope.getUserLogin();

    $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;
                }
            });
        }
        // edit by haudao
    $scope.infoSupplier = {};
    $scope.openPopupApptGroupOption = function(id, status) {
            $scope.infoSupplier.id = parseInt(id);
            $scope.infoSupplier.status = status;
            $scope.editSupplieritems(id);
            appDialogToggle('open', '#popupSettingSupplierOption')
        }
        // end edit
        // $scope.checkLogin();

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

    /*
    <p>Selected: {{address.selectAddesses}}</p>
            <ui-select multiple 
                ng-model="address.selectAddesses"
                theme="bootstrap"
                ng-disabled="false" 
                close-on-select="false" 
                style="width: 300px;"
                title="Choose an address">
                <ui-select-match placeholder="Enter an address...">{{$item.name}}</ui-select-match>
                <ui-select-choices repeat="add in addresses| propsFilter: {name: $select.search, id: $select.search}"
                    refresh="refreshAddresses($select.search)"
                    refresh-delay="0">
                    <div ng-bind-html="add.name | highlight: $select.search"></div>
                </ui-select-choices>
            </ui-select> 
    $scope.address = {};
    $scope.address.selectAddesses = [{id:"1",name:"abc"}];
    $scope.refreshAddresses = function(address) {
        if(address.length>0){
            var params = {search: address};
            Colors.getSelect2(params).success(function(data){
             var diff = differentArray(data,$scope.address.selectAddesses);
                $scope.addresses =diff;
            })  
        }
    };*/

})
