var app = angular.module('WebDelivery', ['ngRoute', 'ngStorage', 'ui.event', 'ngMask', 'ui.autocomplete', 'ui.bootstrap']);



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

	$routeProvider
		.when('/', {
			templateUrl: 'views/home/home.html'
		})
		.when('/select-restaurant', {
			templateUrl: 'views/user/select-restaurant.html'
		})
		.when('/select-address', {
			templateUrl: 'views/user/select-address.html',
		})
		.when('/catalog', {
			templateUrl: 'views/catalog/catalog.html',
			'page': 'catalogPage',
			resolve: {
				load: ['verificationInfo', function (verificationInfo) {
					return verificationInfo.preLoad();
				}]
			}
		})
		.when('/cart', {
			templateUrl: 'views/cart/cart.html',
			'page': 'cartPage',
			resolve: {
				load: ['verificationInfo', function (verificationInfo) {
					return verificationInfo.preLoad();
				}]
			}
		})
		.when('/order', {
			templateUrl: 'views/cart/order.html',
			resolve: {
				load: ['verificationInfo', function (verificationInfo) {
					return verificationInfo.preLoad();
				}]
			}
		})
		.when('/payment-result', {
			templateUrl: 'views/payment/result.html'
		})
		.otherwise({
			redirectTo:'/',
			templateUrl:'views/home/home.html'
		});

}]);

app.factory("verificationInfo", ['$rootScope', '$localStorage', '$location', function($rootScope, $localStorage, $location) {
	return {
		preLoad: function() {
			// если не выбран ресторан
			if($localStorage.UserInfo == undefined) {
				$location.path('#/');
			}
		}
	};
}]);

app.run(['$rootScope', '$location', '$localStorage', 'localisation', '$templateCache',
	function($rootScope, $location, $localStorage, localisation, $templateCache) {

		// убираем кеширование
		$rootScope.$on('$routeChangeStart', function(event, next, current) {
			if (typeof(current) !== 'undefined') {
				$templateCache.remove(current.templateUrl);
			}
		});

		/* Подключаем локализацию */
		localisation.loadLocale();
		$rootScope.getLocale = function(str) {
			//if($rootScope.locale){
				return localisation.localize(str);
			//}
		};
		$rootScope.selectLang = function(lang) {
			$rootScope.currentLocal = lang;
		};

		/* Обработка ошибок */
		$rootScope.errorMessage = $('#error-modal');
		$rootScope.fullMessage = {};
		$rootScope.multiButton = false;
		$rootScope.ShowErrorMessage = function(options) {
			options.type = options.type || 'error';

			if(options.type == 'error') {
				$rootScope.multiButton = false;
				$rootScope.TitlePopup = $rootScope.getLocale('Error');
			} else if(options.type == 'warning') {
				$rootScope.TitlePopup = $rootScope.getLocale('Warning');
				$rootScope.multiButton = true;
				$rootScope.callbackOk = options.callbackOk || $rootScope.CloseError();
				$rootScope.callbackCancel = options.callbackCancel || $rootScope.CloseError();
			} else {
				$rootScope.TitlePopup = $rootScope.getLocale('Warning');
			}

			if(options.fullMessage) {
				$rootScope.fullMessage = options.fullMessage;
			}

			$rootScope.Message = options.message;
			$rootScope.errorMessage.show();
		};

		$rootScope.CloseError = function(){
			$rootScope.fullMessage = {};
			$rootScope.Message = '';
			$rootScope.errorMessage.hide();
		};

		/* Сумма к оплате */
		$rootScope.PaymentsMessage = $('#payments-modal');
		$rootScope.ShowPayments = function(payments) {
			$rootScope.TitlePopup = $rootScope.getLocale('Amount for pay');
			$rootScope.AmountForPay = payments;
			$rootScope.PaymentsMessage.show();
		};

		$rootScope.ClosePaymentsMessage = function(){
			$rootScope.AmountForPay = null;
			$rootScope.PaymentsMessage.hide();
		};

}]);

app.filter('filterNumeric', function() {
	return function(value) {
 		if((isNaN(value) || value == undefined) && !((typeof(value) == 'string' || typeof(value) == 'number') && value.indexOf(",") + 1)) {
			return 0;
		}

		var value = value.toString();
		var separatorDecCurrent = ','; // приходящий в "value" разделить
		var switchZero = (value < 0); // если отрицательное число
		var separatorTh = ' '; // Разделитель разрядов на выходе
		var separatorDec = ','; // Десятичный разделитель на выходе

		// Определение длины форматируемой части
		var lengthValue = value.lastIndexOf(separatorDecCurrent); // До десятичной точки
		lengthValue = (lengthValue > -1) ? lengthValue : value.length;

		// Выделение временного буфера
		var tempResult = value.substring(lengthValue);
		if (tempResult.length > 3) {
			tempResult = tempResult.substr(0, 3);
		}

		var cnt = -1;
		for (var i = lengthValue; i > 0; i--) {
			cnt++;
			if (((cnt % 3) === 0) && (i !== lengthValue) && (!switchZero || (i > 1))) {
				tempResult = separatorTh + tempResult;
			}
			tempResult = value.charAt(i - 1) + tempResult;
		}

		return tempResult.replace(separatorDecCurrent, separatorDec);
	};
});

app.filter('filterPrice', function() {
	return function(value) {
		if(isNaN(value) || value == undefined) {
			return 0;
		}

		var sing = '';
		if(value < 0) {
			value = Math.abs(value);
			sing = '-';
		}

		var value = value.toString();
		var cellValue = value.substr(0, value.length - 2);
		var percentValue = value % 100;

		if(!cellValue.length) {
			cellValue = '0';
		}

		value = sing + cellValue;
		if(percentValue != 0) {
			value = value + ',' + percentValue;
		}

		return value;
	};
});

angular.module('ui.event',[]).directive('uiEvent', ['$parse',
	function ($parse) {
		return function ($scope, elm, attrs, $parse) {
			var events = $scope.$eval(attrs.uiEvent);
			angular.forEach(events, function (uiEvent, eventName) {
				var fn = $parse(uiEvent);
				elm.bind(eventName, function (evt) {
					var params = Array.prototype.slice.call(arguments);
					//Take out first paramater (event object);
					params = params.splice(1);
					fn($scope, {$event: evt, $params: params});
					if (!$scope.$$phase) {
						$scope.$apply();
					}
				});
			});
		};
	}]);













