/**
 * BookingsSaleLeadCtrl Controller
 * Extracted from bookings module
 */

Bookings.controller('BookingsSaleLeadCtrl', ['$scope', '$route', '$routeParams', '$ClientsManager', 'BookingsLocationManager', 'SaleLead', 'archAuthService', 'ErrorsHandler', '$window', function ($scope, $route, $routeParams, $ClientsManager, BookingsLocationManager, SaleLead, auth, ErrorsHandler, $window) {

	// ------------------------------------------------------------------------
	//
	//	SCOPE VARIABLES BELOW -->
	//
	// ------------------------------------------------------------------------

	$scope.data = {};
	$scope.max_stars = 5;

	// working with the shared service managers
	$scope.clientManager = $ClientsManager;
	$scope.locationManager = BookingsLocationManager;

	$scope.routeParams = $routeParams;

	// added by nadeem 13.2.17 - if the user use the add task to project button
	// then this will pass the project id forward to the back-end
	// the crated task will then be correctly associated with the correct project
	if (typeof ($scope.$parent.projectId != 'undefined')) {
		$scope.data.project_id = $scope.$parent.projectId;
	}

	// ------------------------------------------------------------------------
	//
	//	WATCHERS AND EVENT LISTENERS BELOW -->
	//
	// ------------------------------------------------------------------------
	$scope.$watch('data.site_user_id', function () {
		$scope.data.direct_dial = BookingsLocationManager.getUserDDI($scope.data.site_user_id);
	});

	$scope.$watch('data.site_id', function () {
		$scope.data.direct_dial = BookingsLocationManager.getUserDDI($scope.data.site_user_id);
	});

	// ------------------------------------------------------------------------
	//
	//	FUNCTIONS BELOW THIS LINE -->
	//
	// ------------------------------------------------------------------------

	$scope.hoveringOver = function (value) {
		$scope.overStar = value;
		$scope.percentage = 100 * (value / $scope.max_stars);
	};

	$scope.save = function () {
		auth.confirm(function (status, helper) {

			// User logged in successfully
			if (status) {

				// Inject the client
				$scope.data.client_id = $ClientsManager.getClient().id;
				$scope.data.client_type = $ClientsManager.getClientType();

				SaleLead.save($scope.data, function (res) {
					$window.onbeforeunload = function () { };
					Messenger("Your sale lead has been successfully created!");
					$window.location.href = "/tasks/sale-lead/" + res.id;
				}, function (a, b) {
					helper.loading = false;
					ErrorsHandler(a, b);
				});
			}
		});
	};
}]);
