/* global app, angular */

angular.module("robware", ['ngAnimate'], ["$httpProvider", function($httpProvider) {
	/*
	 * Stolen from: http://stackoverflow.com/questions/19254029/angularjs-http-post-does-not-send-data
	 * Reason: send payload as form data instead of JSON, bind to controller action parameters
	 */
	// Use x-www-form-urlencoded Content-Type
	$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
	/**
	 * The workhorse; converts an object to x-www-form-urlencoded serialization.
	 * @param {Object} obj
	 * @return {String}
	 */
	var param = function(obj) {
		var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
		for (name in obj) {
			value = obj[name];
			if (value instanceof Array) {
				for (i = 0; i < value.length; ++i) {
					subValue = value[i];
					fullSubName = name + '[' + i + ']';
					innerObj = {};
					innerObj[fullSubName] = subValue;
					query += param(innerObj) + '&';
				}
			}
			else if (value instanceof Object) {
				for (subName in value) {
					subValue = value[subName];
					fullSubName = name + '[' + subName + ']';
					innerObj = {};
					innerObj[fullSubName] = subValue;
					query += param(innerObj) + '&';
				}
			}
			else if (value !== undefined && value !== null)
				query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
		}

		return query.length ? query.substr(0, query.length - 1) : query;
	};
	// Override $http service's default transformRequest
	$httpProvider.defaults.transformRequest = [
		function(data) {
			return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
		}
	];

	$httpProvider.interceptors.push([
		'$rootScope',
		'$q',
		function($rootScope, $q) {
			return {
				request: function(config) {
					if (config.showSpinner)
						$rootScope.showSpinner();
					return config;
				},
				requestError: function(rejection) {
					$rootScope.hideSpinner();
					return $q.reject(rejection);
				},
				response: function(response) {
					$rootScope.hideSpinner();
					return response;
				},
				responseError: function(rejection) {
					$rootScope.hideSpinner();
					return $q.reject(rejection);
				}
			};
		}
	]);
}]);

angular.module("robware").controller("main", ['$scope', '$rootScope', function($scope, $rootScope) {
		var largeWindowBoundary = 1023;

		$scope.menuVisible = false;//window.innerWidth > largeWindowBoundary;

		$scope.shouldShowMenu = function() {
			return $scope.menuVisible || window.innerWidth > largeWindowBoundary;
		};

		$scope.spinnerVisible = false;

		$rootScope.showSpinner = function() {
			$scope.spinnerVisible = true;
		};

		$rootScope.hideSpinner = function() {
			$scope.spinnerVisible = false;
		};

		$(window).on("resize.doResize", function() {
			$scope.$apply(function() {
				//$scope.menuVisible = false;
			});
		});

		$scope.errors=[];
		$scope.showErrors=function(errors){
			$scope.errors=errors;
		}
	}]);