
// if(!app){
// 	var app = angular.module('App',[
// 	//'ui.bootstrap',
// 	'LoginService',
// 	'positiontitlesService',
// 	'positiontitlesCtrl',
// 	'positiontitlesEditDirective',
// 	'positiontitlesDeleteDirective',
// 	'positiontitlesDirective',
// 	'positiontitlesAddDirective',
// 	'navDirective',
// 	'ngFileUpload',
// 	'ckDirective',
// 	'datetimepicker',
// 	'modalDirective',
// 	'ui.select',
// 	'ngSanitize'
// 	//'ngSanitize',
// 	//'expDirective',// remove comment if use file explorer.
// 	//'explorerDirective',
// 	//'ui.select'
// 	]);
// }
// 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 positiontitles_pagesize = $('#positiontitles_pagesize');
angular.module('positiontitlesCtrl',[]).controller('positiontitlesController',function( $ionicLoading, $cordovaToast, $ionicPopup,$scope,$http,$window,$interval,Login, Positiontitles,$timeout){

	withoutPopup_Positiontile = $scope;
	$scope.currentPage =1;
	var pager = localStorage.getItem('positiontitles_pagesize');
	$scope.itemsPerPage= pager?pager:50;
	$scope.entryLimit =$scope.itemsPerPage; 
	$scope.searchPositiontitles={rows:$scope.itemsPerPage,current_page:$scope.currentPage,search:""};
	$scope.ShowAll_PositionTitle=false;

	$scope.getPositiontitles = function(){
		$ionicLoading.show({
			template: templateLoading
		});
		Positiontitles.getPaging($scope.searchPositiontitles).success(function(data){
			$ionicLoading.hide();
			$scope.positiontitles= data.data;
			$scope.currentPage = data.page; 
			$scope.itemsPerPage = $scope.searchPositiontitles.rows; 
			positiontitles_pagesize.val($scope.itemsPerPage);
			$scope.totalItems = data.total_rows;
		}).error(function (data, status, headers, config) {
			$ionicLoading.hide();
			console.log('error status: ' + status);
			$cordovaToast.showLongTop('Connection Error!!!');
		});
	};

		// $scope.repalaceres = function(data) {
		// 	setTimeout(function() {
		// 		$scope.$apply(function(val) {
		// 			if (val) {
		// 				$('#tablePositiontitles').tableRespondsive({
		// 					paging: true,
		// 					pagingArg: {
		// 						totalRow: 105,
		// 						rowPerPage: 50,
		// 						currentPage: 2
		// 					}
		// 				});
		// 				$('.dashboard > .tblloader').hide();
		// 				$('#document').show();
		// 				$('#document .tblloader').hide();
		// 				$('#document .tblloader_positiontitle').hide();

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

		// 			}
		// 		});
		// 	}, 1);
		// }
		$scope.autocompleteList={};
		$scope.autocompleteList.refferedDepartAdd=[];
		$scope.autocompleteList.refferedDepartEdit=[];
		$scope.ShowActive_PositionTitle = function(show_all) {
			$scope.searchPositiontitles.show_all = show_all;
			$scope.getPositiontitles();
		}
		$scope.getAllPosition=function(){
			var params = {search: '' };
			Positiontitles.searchDepart(params).success(function(data) {
				$scope.allPosition=data;
			})
		}
		$scope.getAllPosition();
		$scope.filterDepart = function (query, style) {
			var returnValue = {items: [] };
			var listIdArray = style == 'add' ? $scope.autocompleteList.refferedDepartAdd : $scope.autocompleteList.refferedDepartEdit;
			$scope.allPosition.forEach(function (item) {
				if (listIdArray.indexOf(item.id) < 0) {
					if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
						returnValue.items.push(item);
					}
				}
			});
			return returnValue;
		};
		 $scope.onSelectDepart = function (callback, style) { // change assign
		 	if (style == 'add') {
		 		if ($scope.addPositiontitlesData.depart.indexOf(callback.item) < 0)
		 			$scope.addPositiontitlesData.depart.push(callback.item);
		 	} else {
		 		if ($scope.editPositiontitlesData.depart.indexOf(callback.item) < 0)
		 			$scope.editPositiontitlesData.depart.push(callback.item);
		 	}
		 }
		 $scope.onRemoveDepart = function (callback, style) {
		 	if (style == 'add') {
		 		var index = $scope.addPositiontitlesData.depart.indexOf(callback.item);
		 		$scope.addPositiontitlesData.depart.splice(index, 1);
		 	} else {
		 		var index = $scope.editPositiontitlesData.depart.indexOf(callback.item);
		 		$scope.editPositiontitlesData.depart.splice(index, 1);
		 	}
		 }
		 $scope.setValueForDepart = function (modelValue) {
		 	for (var i = 0; i < $scope.allPosition.length; i++) {
		 		if ($scope.allPosition[i].id == modelValue) {
		 			return $scope.allPosition[i];
		 		}
		 	}
		 	return {};
		 };
		// $scope.refreshDepart = function(search) {
		// 	if (search.length > 0) {
		// 		var params = {
		// 			search: search
		// 		};
		// 		Positiontitles.searchDepart(params).success(function(data) {
		// 			var diff = differentArray(data,$scope.addPositiontitlesData.depart);
		// 			$scope.departSelect = diff;
		// 		})
		// 	} else {
		// 		$scope.assignSelect = [];
		// 	}
		// };

		// $scope.refreshDepartEdit = function(search) {
		// 	$('#selectDepartEdit').find('.notif').text('');
		// 	if (search.length > 0) {
		// 		var params = {
		// 			search: search
		// 		};
		// 		Positiontitles.searchDepart(params).success(function(data) {
		// 			var diff = differentArray(data,$scope.editPositiontitlesData.depart);
		// 			$scope.departSelect = diff;
		// 		})
		// 	} else {
		// 		$scope.assignSelect = [];
		// 	}
		// };

		$scope.searchChanged=function(){
			$scope.getPositiontitles();
		}
		
		$scope.sizeChanged = function(){
			$scope.searchPositiontitles.rows = $scope.entryLimit;
			positiontitles_pagesize.val($scope.searchPositiontitles.rows);
			localStorage.setItem('positiontitles_pagesize',$scope.searchPositiontitles.rows);
			$scope.searchPositiontitles.current_page=1;
			$scope.getPositiontitles();
		}
		$scope.pageChanged  = function() {
			console.log($scope.currentPage);
			$scope.searchPositiontitles.current_page = $scope.currentPage;
			$scope.getPositiontitles();
		};
		$scope.getPositiontitles();
		$scope.setPage = function(pageNo) {
			$scope.currentPage = pageNo;
			console.log('doi page');
		};

		$scope.addPositiontitlesData = {};
		$scope.addPositiontitlesData.depart = [];
		$scope.addPositiontitlesData.description = '';
		$scope.createPositiontitles = function(formValidate) {
			if (formValidate.$invalid) {
				$cordovaToast.showLongTop('Please fill all the required information.!!!');
				return;
			}
			$ionicLoading.show({
				template: templateLoading
			});
			Positiontitles.save($scope.addPositiontitlesData).success(function(data){
				$ionicLoading.hide();
				if(data.status){
					closeTarget('#settingPositionTitleManagementAdd');
					$scope.getPositiontitles();
					$scope.addPositiontitlesData.depart = [];
					$scope.initialDepartAdd=[];
					$scope.addPositiontitlesData = {};
					$cordovaToast.showLongTop(data.msg);
				}else{
					$cordovaToast.showLongTop(data.msg);
				}
			});
		}
		$scope.editPositiontitlesData = {};
		$scope.editPositiontitlesData.depart = [];
		$scope.editPositiontitles = function(id){
			$ionicLoading.show({
				template: templateLoading
			});
			Positiontitles.show(id).success(function(data){
				$ionicLoading.hide();
				$scope.editPositiontitlesData.id = data.id;
				$scope.editPositiontitlesData.name = data.name;
				$scope.editPositiontitlesData.description = data.description;
				$scope.initialDepartEdit=_.pluck(data.depart, 'id');
			});
		}
		$scope.updatePositiontitles = function(formValidate){
			if (formValidate.$invalid) {
				$cordovaToast.showLongTop('Please fill all the required information.!!!');
				return;
			}
			var id = $scope.editPositiontitlesData.id;
			$ionicLoading.show({
				template: templateLoading
			});
			Positiontitles.update(id,$scope.editPositiontitlesData).success(function(data){
				$ionicLoading.hide();
				if(data.status){
					closeTarget('#settingPositionTitleManagementEdit');
					$scope.editPositiontitlesData = {};
					$scope.editPositiontitlesData.depart = [];
					$scope.getPositiontitles();
					$cordovaToast.showLongTop(data.msg);
				}else{
					$cordovaToast.showLongTop(data.msg);
				}
			});
		}
		$scope.deletePositiontitlesData = {};
		$scope.confrimPositiontitles = function(item){
			$scope.deletePositiontitlesData=item;
		}

		$scope.deletePositiontitles = function(){
			var id=$scope.deletePositiontitlesData.id;
			var status=$scope.deletePositiontitlesData.status;
			$ionicLoading.show({
				template: templateLoading
			});
			Positiontitles.destroy(id).success(function(data){
				$ionicLoading.hide();
				closeTarget('#settingPositionTitleManagementDelete');
				var idx = _.findLastIndex($scope.positiontitles, {id: id.toString()});
				if (data.status) {
					if ($scope.ShowAll_PositionTitle) {
						$scope.positiontitles[idx].status = status == "1" ? "0" : "1";
					} else {
						$scope.positiontitles.splice(idx, 1);
					}
					$cordovaToast.showLongTop(data.msg);
				} else {
					$cordovaToast.showLongTop(data.msg);
				}
				
			});
		}

		$scope.setIndexViewOptionPositionTitle = function(index){
            $scope.index_option_position_title=index;
            $timeout( function(){
                $('#btn-view-option-position-title-'+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;	
				}
			});			
		}
		
		// $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;
				})	
			}
		};*/

	})