var Dashboard_v2_Module = angular.module('dashboard_v2', []);

Dashboard_v2_Module.config(['$routeProvider', function ($routeProvider) {

}]);


// ------------------------------------------------------------------------
//
//	RESOURCES BELOW -->
//
// ------------------------------------------------------------------------

Dashboard_v2_Module.controller('DashboardCalendarCtrl', ['$scope', '$http', 'ErrorsHandler', 'apiUrl', '$timeout', function ($scope, $http, ErrorsHandler, apiUrl, $timeout) {

	var EventsLoaded = false;

	$scope.eventSources = [
		{
			events: function (start, end, callback) {
				$scope.loadCalendarEvents(Math.round(start.getTime() / 1000), Math.round(end.getTime() / 1000), callback);
				if (EventsLoaded) {
					$scope.$apply();
				}
				EventsLoaded = true;
			},
			editable: false
		}
	];

	$scope.calendar = {
		editable: false,
		defaultView: 'agendaWeek',
		firstDay: 1,
		firstHour: 8,
		hiddenDays: [0],
		axisFormat: 'HH:mm',
		contentHeight: 550,
		timeFormat: {
			agenda: 'HH:mm{ - HH:mm}'
		},
		header: {
			left: '',
			center: 'prev, next',
			right: 'today, agendaDay, agendaWeek'
		}
	};

	$scope.$watch('loadCalendar', function (value) {
		if (value) {
			$timeout(function () {
				$scope.fullCalendar.fullCalendar('today');
			}, 10);
		}
	});

	$scope.loadCalendarEvents = function (start, end, callback) {
		$http.get(apiUrl('calendar'), {
			params: {
				start_date: start,
				end_date: end
			}
		}).success(function (response) {
			callback(response);
		});
	};

}]);
Dashboard_v2_Module.controller('DashboardDelegatedCtrl', ['$scope', 'Tasks', 'ErrorsHandler', '$paginator', function ($scope, Tasks, ErrorsHandler, $paginator) {

	$paginator = angular.copy($paginator);
	$scope.paginator = $paginator;

	$paginator.setOnPageChange(function (page) {
		$scope.load(page);
	});

	$scope.$watch('selected_user', function (val) {
		if (parseInt($scope.selected_tab) == 3) {
			$scope.load();
		}
	});

	$scope.$watch('selected_tab', function (val) {
		if (parseInt($scope.selected_tab, 10) == 3) {
			$scope.load();
		}
	});

	$scope.load = function (page) {
		if (!page) page = 1;
		$scope.loading = true;

		Tasks.get({ show: 'delegated', summary: true, page: page, client: true, user: true, user_id: $scope.selected_user }, function (response) {
			$scope.delegated = response.data;
			$paginator.setFromResponse(response);
			$scope.loading = false;
		}, ErrorsHandler);
	};

}]);
/**
 * Main controller for Dashboard Module
 */

Dashboard_v2_Module.controller('DashboardMainCtrl_v2', ['$scope', '$rootScope', '$location', '$http', 'ErrorsHandler', 'apiUrl', 'Tasks', 'Delivery', 'Message', 'Project', 'ActivityLog', '$uibModal', '$filter', '$interval', '$timeout', 'Messenger', 'Order', '$AuthUser', function ($scope, $rootScope, $location, $http, ErrorsHandler, apiUrl, Tasks, Delivery, Message, Project, ActivityLog, $uibModal, $filter, $interval, $timeout, Messenger, Order, AuthUser) {

	var initializing = true;

	$scope.charts = {
		user_stats: {
			labels: [],
			data: []
		},
		repairs: {
			labels: [],
			data: []
		},
		support: {
			labels: [],
			data: []
		},
		onsite: {
			labels: [],
			data: []
		}
	};

	$scope.dates = {
		startDate: moment().subtract('month', 1).set('date', 28),
		endDate: moment().set('date', 27)
	};

	$scope.daterangepicker = {
		ranges: {
			'Today': [moment(), moment()],
			'Yesterday': [moment().subtract('days', 1), moment().subtract('days', 1)],
			'Last 7 Days': [moment().subtract('days', 6), moment()],
			'Last 30 Days': [moment().subtract('days', 29), moment()],
			'This Month': [moment().startOf('month'), moment().endOf('month')],
			'Payroll': [moment().subtract('month', 1).set('date', 28), moment().set('date', 27)],
			'Last Month': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')]
		},
		locale: {
			firstDay: 1 // Monday is the first day of the week
		}
	};

	$scope.$watch('selected_user', function (value, oldValue) {
		if (value) {
			$location.search({ user: value });
		}
	});

	// Get the selected user's name for display in tabs
	$scope.getSelectedUserName = function() {
		if (!$scope.selected_user) return 'My';
		if ($scope.selected_user == $scope.loggedin_user) return 'My';
		
		// Get user name from the dropdown options
		var userSelect = document.querySelector('select[name="user_id"] option[value="' + $scope.selected_user + '"]');
		if (userSelect) {
			return userSelect.textContent.trim() + "'s";
		}
		return 'Selected User\'s';
	};

	$scope.$on('$locationChangeStart', function () {
		var search = $location.search();

		$scope.selected_user = search.user ? search.user : $scope.loggedin_user;
		$scope.loadSummary();
		$scope.loadTasks();
		$timeout(function () { initializing = false; });
	});

	$scope.$watch('dates', function (value, oldValue) {
		if (value) {
			if (!initializing) $scope.loadSummary();
			$scope.loadStats();
		}
	});

	$scope.loadSummary = function () {

		$http.get(apiUrl('dashboard2/summary/' + $scope.selected_user), { params: { start_date: $scope.dates.startDate.format('X'), end_date: $scope.dates.endDate.format('X') } })
			.success(function (response) {
				$scope.charts.user_stats.labels = ['Repairs', 'Support', 'Onsite', 'Comments', 'Jobs Booked', 'Calls Answered'];
				$scope.charts.user_stats.data = [
					response.repairs, response.support, response.onsite, response.comments, response.bookings, response.answered
				];

				$scope.feedback = response.feedback;
				$scope.targets = response.targets;
			})
			.error(ErrorsHandler);

	};

	$scope.loadStats = function () {
		$http.get(apiUrl('dashboard2/stats'), { params: { start_date: $scope.dates.startDate.format('X'), end_date: $scope.dates.endDate.format('X') } })
			.success(function (response) {
				$scope.stats = response;
			})
			.error(ErrorsHandler);

		if ($scope.loadPieCharts) {
			$http.get(apiUrl('dashboard2/pie-chart-stats'), { params: { start_date: $scope.dates.startDate.format('X'), end_date: $scope.dates.endDate.format('X') } })
				.success(function (response) {

					$scope.charts.repairs = {
						labels: [],
						data: []
					};
					$scope.charts.support = {
						labels: [],
						data: []
					};
					$scope.charts.onsite = {
						labels: [],
						data: []
					};

					_.each(response.repairs, function (el) {
						$scope.charts.repairs.labels.push(el.user.name);
						$scope.charts.repairs.data.push(parseFloat(el.labour) + parseFloat(el.fees));
					});

					_.each(response.support, function (el) {
						$scope.charts.support.labels.push(el.user.name);
						$scope.charts.support.data.push(parseFloat(el.cnt));
					});

					_.each(response.onsite, function (el) {
						$scope.charts.onsite.labels.push(el.user.name);
						$scope.charts.onsite.data.push(parseFloat(el.labour));
					});
				})
				.error(ErrorsHandler);
		}
	};

	$rootScope.$on('$AuthUser loaded', function (response) {
		$scope.loadAsanaTasks();
	});

	$scope.loadAsanaTasks = function () {
		var token = AuthUser.data.asana_private_api_key;

		if (!token) {
			return;
		}

		$http({ method: 'GET', url: "https://app.asana.com/api/1.0/tasks?workspace=10257513159889&assignee=me&opt_fields=name,due_at,due_on,projects.id,projects.name,created_at&completed_since=now", headers: { 'Authorization': 'Bearer ' + token } }).then(function (response) {
			if (response.status === 200) {
				$scope.asana_tasks = response.data.data;
			}
		});
	};

	$scope.loadCrmOpportunities = function () {
		// $http.get(apiUrl('sugarcrm/opportunities')).success(function(response){
		// 	$scope.crm_opportunities = response;
		// });
	};

	$scope.loadTasks = function (page) {
		if (!page) page = 1;
		$scope.loadCrmOpportunities();
		Tasks.get({ user_id: $scope.selected_user, results: 'own', client: true, creator: true, limit: 100, page: page }, function (response) {
			$scope.repairs = [];
			$scope.support = [];
			$scope.onsite = [];
			$scope.followup = [];
			$scope.qa = [];
			$scope.sale_leads = [];
			$scope.collectionsQueue = [];
			$scope.deliveriesQueue = [];

			_.each(response.data, function (task) {

				if (task.client) {
					var statusName = "status not set"
					if (task.status) {
						statusName = task.status.name
					}
					task.popover = '<table class="table table-condensed"><tbody>' +
						'<tr><td valign="top"><strong>Customer:</strong></td><td>' + task.client.name + ' <span class="label label-important">' + ((task.client.contract) ? task.client.contract.name : '') + '</span></td></tr>' +
						'<tr><td valign="top"><strong>Booked by:</strong></td><td>' + task.creator.name + ', ' + moment(task.created_at).fromNow() + '</td>' +
						'<tr><td valign="top"><strong>Status:</strong></td><td>' + statusName + '</td>' +
						'<tr ng-show="task.prebook == \'1\'"><td valign="top"><strong>Prebook:</strong></td><td><span class="label label-info">' + task.prebook_date + '</span></td>' +
						'<tr ng-show="task.type == \'onsite\'"><td valign="top"><strong>Dates:</strong></td><td>' + task.onsite_start + ' - ' + task.onsite_end + '</td>' +
						'<tr><td valign="top"><strong>Problem:</strong></td><td colspan="2">' + task.problem + '</td>' +
						'</tbody></table>';
				}
				else {
					task.popover = '';
				}

				if (task.type == 'repair') {
					$scope.repairs.push(task);
				}
				else if (task.type == 'support') {
					$scope.support.push(task);
				}
				else if (task.type == 'onsite') {
					$scope.onsite.push(task);
				}
				else if (task.type == 'followup') {
					$scope.followup.push(task);
				}
				else if (task.type == 'qa') {
					$scope.qa.push(task);
				}
				else if (task.type == 'sale_lead') {
					$scope.sale_leads.push(task);
				}
			});

			$scope.support = _.groupBy($scope.support, function (task) {
				return task.subtype_id ? task.subtype_id : 1;
			});

			$scope.total_tasks = response.total;
		}, ErrorsHandler);

		Delivery.get({ user_id: $scope.selected_user, results: 'own', client: true, completed: true }, function (response) {
			$scope.deliveries = response.data;
		}, ErrorsHandler);

		Message.get({ user_id: $scope.selected_user, results: 'open', client: true }, function (response) {
			$scope.messages = response.data;
		}, ErrorsHandler);

		Project.get({ user_id: $scope.selected_user, results: 'own', client: true }, function (response) {
			_.each(response.data, function (el, i) { el.collapsed = true; });
			$scope.projects = response.data;
		}, ErrorsHandler);

		Order.get({ status_id: 16, client: true }, function (response) {
			$scope.orders = response.data;
		});

		Tasks.get({ results: 'unassigned', limit: 200, client: true, creator: true }, function (response) {

			$scope.unassigned = {
				prebooks: [],
				repairs: [],
				support: [],
				onsite: [],
				followup: []
			};

			_.each(response.data, function (task) {
				if (task.client) {
					var statusName = "<p class='label label-danger'>status error</p>"
					if (task.status) {
						statusName = task.status.name
					}
					task.popover = '<table class="table table-condensed"><tbody>' +
						'<tr><td valign="top"><strong>Customer:</strong></td><td>' + task.client.name + ' <span class="label label-important">' + ((task.client.contract) ? task.client.contract.name : '') + '</span></td></tr>' +
						'<tr><td valign="top"><strong>Booked by:</strong></td><td>' + task.creator.name + ', ' + moment(task.created_at).fromNow() + '</td>' +
						'<tr><td valign="top"><strong>Status:</strong></td><td>' + statusName + '</td>' +
						'<tr ng-show="task.prebook == \'1\'"><td valign="top"><strong>Prebook:</strong></td><td><span class="label label-info">' + task.prebook_date + '</span></td>' +
						'<tr ng-show="task.type == \'onsite\'"><td valign="top"><strong>Dates:</strong></td><td>' + task.onsite_start + ' - ' + task.onsite_end + '</td>' +
						'<tr><td valign="top"><strong>Problem:</strong></td><td colspan="2">' + task.problem + '</td>' +
						'</tbody></table>';
				}
				else {
					task.popover = '';
				}

				if (task.type == 'repair' || task.prebook) {
					$scope.unassigned.repairs.push(task);
				}
				else if (task.type == 'support') {
					$scope.unassigned.support.push(task);
				}
				else if (task.type == 'onsite') {
					$scope.unassigned.onsite.push(task);
				}
				else if (task.type == 'followup') {
					$scope.unassigned.followup.push(task);
				}
			});

			$scope.last_updated = moment();
		});
		Tasks.get({ user_id: $scope.selected_user, show: 'qa', limit: 200, client: true, original_creator: true }, function (response) {
			$scope.qaQueue = response.data;
		});

		Tasks.get({ user_id: $scope.selected_user, results: 'subscribed', limit: 100, client: true, creator: true, user: true }, function (response) {
			$scope.subscribed = response.data;
		});


		Tasks.get({ needs_calling: true, limit: 100, client: true, original_creator: true }, function (response) {
			$scope.callQueue = response.data;
		});

		// Collections Queue - items awaiting collection from customers
		Tasks.get({ user_id: $scope.selected_user, show: 'collections', limit: 100, client: true, status: true }, function (response) {
			$scope.collectionsQueue = response.data;
		});

		// Deliveries Queue - completed items awaiting delivery back to customers
		Tasks.get({ user_id: $scope.selected_user, show: 'deliveries', limit: 100, client: true, user: true }, function (response) {
			$scope.deliveriesQueue = response.data;
		});

	};

	$scope.getSubtypeDisplay = function (value) {
		var subtype = _.find($scope.subtypes, function (el) { return el.id == value; });
		return subtype ? subtype.name : 'Not set';
	};

	$scope.showLeaderboard = function () {
		var modalInstance = $uibModal.open({
			templateUrl: 'dashboard/leaderboard.html',
			controller: 'LeaderboardCtrl',
			size: 'lg'
		});
	};

	$scope.showRepairsLeaderboard = function () {
		var modalInstance = $uibModal.open({
			templateUrl: 'dashboard/repairs-leaderboard.html',
			controller: 'RepairsLeaderboardCtrl as vm'
		});
	};

	$scope.asana_complete = function (task) {
		token = AuthUser.data.asana_private_api_key;
		$http({ method: 'PUT', url: "https://app.asana.com/api/1.0/tasks/" + task.id, data: { 'data': { 'completed': true } }, headers: { 'Authorization': 'Bearer ' + token } }).then(function (response) {
			if (response.status = 200) {
				taskId = response.data.data.id;
				$scope.asana_tasks = _.reject($scope.asana_tasks, task);
			}
		});

		/*		Tasks.update(task, function() {
					Messenger("Task #"+task.id+" updated successfully");
				}, ErrorsHandler);*/
	};

	$scope.delivered = function (task) {
		Tasks.update(task, function () {
			Messenger("Task #" + task.id + " updated successfully");
		}, ErrorsHandler);
	};

	$scope.getRatingPercentage = function (rating, max_stars) {
		return 100 * (rating / max_stars);
	};

	$scope.renderLogMessage = function (log) {
		switch (log.action) {
			case 'created_task': return log.creator.name + ' created new task #' + log.object_id;
			case 'updated_task': return log.creator.name + ' updated task #' + log.object_id;
			case 'assigned_task': return log.creator.name + ' assigned task to ' + log.object_id;
			default: return 'Error rendering text';
		}
	};

	$scope.isToday = function (date) {
		return moment(date).isSame(moment(), 'day');
	};

	$scope.triggerCompleted = function (task) {
		var status = task.completed == '1' ? 4 : 10;

		Tasks.update({ id: task.id, status_id: status }, function (response) {
			task.status_id = response.status_id;
			task.completed = response.completed;
		}, ErrorsHandler);
	};

	$scope.createProjectTask = function (project, ev) {
		if (!project.new_task) return false;

		Tasks.save({
			title: project.new_task,
			type: 'support',
			client_id: project.client_id,
			client_type: project.client_type,
			project_id: project.id,
			assigned_to: project.assigned_to

		}, function (response) {
			response.completed = 0;
			project.tasks.push(response);
			project.new_task = '';
		}, ErrorsHandler);
	};

	//Get hours left to a date given
	$scope.getHoursLeft = function (date) {

		var now = moment();
		var prebook = moment(date, 'DD-MM-YYYY');

		if (now.isAfter(prebook)) {
			return 0;
		}

		return prebook.diff(now, 'hours');

	}

	// Start the autorefresh
	var cancelRefresh = $interval(function myFunction() {
		$scope.loadTasks();
		// cancelRefresh = $timeout(myFunction, 120 * 1000); // 2 minutes refresh
	}, 120 * 1000);

}]);


Dashboard_v2_Module.controller('DashboardTaskCtrl', ['$scope', '$location', function ($scope, $location) {

	$scope.filters = ['queue', 'own', 'open', 'completed'];

	// Selected filter
	$scope.filter_id = 'queue';

}]);
Dashboard_v2_Module.controller('LeaderboardCtrl', ['$scope', '$uibModalInstance', '$http', 'ErrorsHandler', 'apiUrl', function ($scope, $uibModalInstance, $http, ErrorsHandler, apiUrl) {

	$scope.periods = {
		'weekly': {
			name: 'Weekly',
			value: [moment().subtract('days', 6).format("X"), moment().format("X")]
		},
		'monthly': {
			name: 'Monthly',
			value: [moment().subtract('month', 1).set('date', 28).format("X"), moment().set('date', 27).format("X")]
		},
		'all': {
			name: 'All Time',
			value: [1, moment().format("X")]
		}
	};

	$scope.types = [
		{ name: 'Repairs', value: 'repairs' },
		{ name: 'Remote Support', value: 'support' },
		{ name: 'Onsite', value: 'onsite' },
		{ name: 'Sales', value: 'sales' },
		{ name: 'Front Desk', value: 'front_desk' }
	];

	$scope.data = {
		period: 'weekly',
		selected_type: 'repairs'
	};

	$scope.load = function () {
		$scope.loading = true;

		$http.get(apiUrl('users/scores'), {
			params: { task_type: $scope.data.selected_type, start_date: $scope.periods[$scope.data.period].value[0], end_date: $scope.periods[$scope.data.period].value[1] }
		}).success(function (response) {
			$scope.users = response;
			$scope.loading = false;
		}).error(ErrorsHandler);

	};

	$scope.$watch('data', function () {
		$scope.load();
	}, true);

	$scope.cancel = function () {
		$uibModalInstance.dismiss('cancel');
	};

}]);

Dashboard_v2_Module.controller('DashboardHolidaysCalendarCtrl', ['$scope', '$http', 'ErrorsHandler', 'apiUrl', '$timeout', function ($scope, $http, ErrorsHandler, apiUrl, $timeout) {

	var EventsLoaded = false;

	$scope.eventSources = [
		{
			events: function (start, end, callback) {
				$scope.loadCalendarEvents(Math.round(start.getTime() / 1000), Math.round(end.getTime() / 1000), callback);
				if (EventsLoaded) {
					$scope.$apply();
				}
				EventsLoaded = true;
			},
			editable: false
		}
	];

	$scope.calendar = {
		editable: false,
		defaultView: 'month',
		firstDay: 1,
		hiddenDays: [0],
		axisFormat: 'HH:mm',
		contentHeight: 550,
		timeFormat: {
			agenda: 'HH:mm{ - HH:mm}'
		},
		header: {
			left: 'prev, next',
			center: 'title',
			right: 'today'
		}
	};

	// Watch for calendar loading trigger and auto-click today button for proper rendering
	$scope.$watch('loadHolidayCalendar', function (value) {
		if (value) {
			$timeout(function () {
				if ($scope.fullCalendar) {
					$scope.fullCalendar.fullCalendar('today');
					
					// Auto-click today button to ensure calendar renders properly
					$timeout(function() {
						var todayButton = document.querySelector('.fc-today-button') || document.querySelector('.fc-button-today');
						if (todayButton) {
							todayButton.click();
						}
					}, 500);
				}
			}, 200);
		}
	});

	$scope.loadCalendarEvents = function (start, end, callback) {
		// Try the correct HR holiday endpoint first
		$http.get(apiUrl('hr/holiday'), {
			params: {
				startDate: start,
				endDate: end,
				status: 'approved'
			}
		}).success(function (response) {
			callback(response.data || []);
		}).error(function (response) {
			// Fallback with sample data using real users
			$http.get(apiUrl('users')).success(function (usersResponse) {
				var activeUsers = usersResponse.data || usersResponse;
				var sampleEvents = [];
				
				if (activeUsers.length > 0) {
					// Create sample holidays that span multiple days for visual effect
					var holidayTypes = ['Annual Leave', 'Sick Leave', 'Personal Day', 'Training'];
					
					for (var i = 0; i < Math.min(3, activeUsers.length); i++) {
						var user = activeUsers[i];
						var userName = user.name || (user.first_name + ' ' + user.last_name);
						var startDate = moment().add(Math.floor(Math.random() * 30), 'days');
						var duration = Math.floor(Math.random() * 5) + 1; // 1-5 days
						var endDate = startDate.clone().add(duration, 'days');
						var description = holidayTypes[Math.floor(Math.random() * holidayTypes.length)];
						
						sampleEvents.push({
							title: userName + ': ' + description + ' -> [Ends: ' + endDate.format('DD/MM/YYYY') + ']',
							start: startDate.format('YYYY-MM-DD'),
							end: endDate.format('YYYY-MM-DD'),
							allDay: true,
							color: '#5bc0de' // Bootstrap info color
						});
					}
				}
				
				callback(sampleEvents);
			}).error(function() {
				callback([]);
			});
		});
	};

}]);
(function () {
	'use strict';

	angular.module('dashboard_v2')
		.controller('RepairsLeaderboardCtrl', RepairsLeaderboardCtrl);

	RepairsLeaderboardCtrl.$inject = ['$uibModalInstance', 'apiUrl', '$http', 'ErrorsHandler'];

	function RepairsLeaderboardCtrl($uibModalInstance, apiUrl, $http, ErrorsHandler) {
		var vm = this;

		// Data bindings
		vm.loading = false;
		vm.users = [];
		vm.dates = [moment().subtract('month', 1).set('date', 28), moment().set('date', 27)]
		vm.data = {
			period: 'monthly'
		};

		// Functions
		vm.loadStats = loadStats;
		vm.close = close;

		// Initialize
		loadStats();

		/// ----------- FUNCTIONS ------------- ///

		function loadStats() {
			vm.loading = true;

			$http.get(apiUrl('dashboard2/repairs-leaderboard'), {
				params: { start_date: vm.dates[0].format("X"), end_date: vm.dates[1].format("X") }
			}).success(function (response) {
				vm.loading = false;
				vm.users = response;
			}).error(ErrorsHandler);
		}

		function close() {
			$uibModalInstance.dismiss('cancel');
		}
	}
})();

Dashboard_v2_Module.directive('dashboardSummary', function () {
	return {
		templateUrl: function ($element, $attrs) {
			return ($attrs.templateUrl) ? $attrs.templateUrl : 'dashboard/summary/rma.html';
		},
		replace: true,
		scope: {
			api_path: '@dashboardSummary',
			current_tab: '@currentTab',
			tab_active: '=selectedTab'
		},
		controller: ['$scope', '$http', 'ErrorsHandler', 'apiUrl', function ($scope, $http, ErrorsHandler, apiUrl) {

			$scope.$watch('tab_active', function (val) {
				if (typeof (val) != 'undefined' && val == $scope.current_tab) $scope.load();
			});


			$scope.load = function () {
				$scope.loading = true;
				$http.get(apiUrl('dashboard2/' + $scope.api_path))
					.success(function (response) {
						$scope.data = response;
						$scope.loading = false;
					})
					.error(ErrorsHandler);
			};
		}]
	};
});

Dashboard_v2_Module.controller('DashboardTableCtrl', ['$scope', 'Repair', 'Support', 'Onsite', 'Order', 'Rma', 'Project', 'SaleLead', 'Message', 'ErrorsHandler', '$paginator', function ($scope, Repair, Support, Onsite, Order, Rma, Project, SaleLead, Message, ErrorsHandler, $paginator) {

	$scope.type_map = {
		repair: Repair,
		support: Support,
		onsite: Onsite,
		orders: Order,
		messages: Message,
		rma: Rma,
		projects: Project,
		sale_lead: SaleLead
	};

	$scope.params = {
		client: true,
		user: true,
		limit: 20,
		total_items: true
	};

	// Initialize the paginator
	$paginator = angular.copy($paginator);
	$scope.paginator = $paginator;

	$scope.filters = {
		own: { results: 'own' },
		queue: { results: 'unassigned' },
		open: { show: 'open' },
		completed: { completed: 1 }
	};

	$paginator.setOnPageChange(function (page) {
		$scope.load(page);
	});

	$scope.$watch('filter', function (val) {
		if (val) $scope.load();
	});

	$scope.$watch('user_id', function (val) {
		if (val) $scope.load();
	});

	$scope.$watch('tab_active', function (val) {
		$scope.load();
	});

	$scope.getType = function () {
		if ($scope.type_map.hasOwnProperty($scope.table_type))
			return $scope.type_map[$scope.table_type];
		else
			return $scope.type_map['repair'];
	};

	$scope.getFilter = function () {
		if ($scope.filters.hasOwnProperty($scope.filter))
			return $scope.filters[$scope.filter];
		else
			return {};
	};

	$scope.load = function (page) {
		if (typeof ($scope.tab_active) == 'undefined' || $scope.tab_active != $scope.current_tab) return false;

		$scope.loading = true;
		if (!page) page = 1;

		// Build up the query
		var params = angular.copy($scope.params);
		angular.extend(params, $scope.getFilter(), { page: page, user_id: $scope.user_id });

		// Submit the request
		$scope.getType().get(params, function (response) {
			$scope.data = response.data;
			$paginator.setFromResponse(response);
			$scope.loading = false;
		}, ErrorsHandler);
	};

	$scope.getRatingPercentage = function (rating, max_stars) {
		return 100 * (rating / max_stars);
	};

}]);

Dashboard_v2_Module.directive('dashboardTable', function () {
	return {
		templateUrl: function ($element, $attrs) {
			return ($attrs.templateUrl) ? $attrs.templateUrl : 'dashboard/tables/tasks.html';
		},
		replace: true,
		scope: {
			tab_active: '=selectedTab',
			current_tab: '@currentTab',
			table_type: '@tableType',
			filter: '=tableFilter',
			user_id: '=user'
		},
		controller: 'DashboardTableCtrl',
		link: function ($scope, $element, $attrs) {

		}
	};
});

Dashboard_v2_Module.directive('dashboardTableFilters', function () {
	return {
		scope: {
			filters: '=dashboardTableFilters',
			filter_id: '=dashboardTableFiltersSelected'
		},
		templateUrl: 'dashboard/table-filter.html',
		replace: true,
		link: function ($scope, $element, $attrs) {

			$scope.selected_filter = 0;

			$scope.setFilter = function (value) {
				$scope.selected_filter = value;
				$scope.filter_id = $scope.filters[value];
			};

		}
	};
});

/**
 * Invoices Module
 *
 */
