define([ 'toaster', 'services' ], function() {
	'use strict';
	var app = angular.module('myApp', [ 'toaster', 'common.services' ]);
	app.init = function() {
		angular.bootstrap(document, [ 'myApp' ]);
	};
	app.controller('AuthCtrl', function($scope, $window, $location, toaster, AuthenticationService, SessionService) {
		$scope.loading = false;
		$scope.user = {
			j_username : SessionService.getCookie('J_USERNAME'),
			j_password : "",
			remember_me : true
		};
		$scope.enterprise = {enName: '深圳市华商龙科技有限公司'};
		$scope.login = function(user, _url) {
			$scope.loading = true;
			AuthenticationService.login(user).success(function(responseText, status) {
				if (status == 200) {
					if(user.remember_me)
						SessionService.setCookie('J_USERNAME', user.j_username);
					else
						SessionService.removeCookie('J_USERNAME');
					var url = responseText;
					if(!url || url == '' || url.indexOf('/signin') > 0)
						url = './';
					$window.location.href = _url || url;
				}
			}).error(function(responseText) {
				$scope.loading = false;
				toaster.pop('error', '登录失败', responseText || '用户名或密码错误');
			});
		};
		var decodeUrl = function(url) {
			url = unescape(url.replace(/\$2F/g, '%2F').replace(/@/g, '#'));
			if(url.indexOf('http:') == -1 && url.indexOf('https:') == -1) {
				url = AuthenticationService.root() + '/' + url;
			}
			return url;
		};
		var loginAndRedirect = function() {
			var path = $location.path();
			if(path) {
				var params = path.split('/'), _params = [];
				angular.forEach(params, function(param){
					param && _params.push(param);
				});
				if(_params.length == 4 && _params[0] == 'redirect') {
					$scope.login({
						j_username: _params[1],
						j_password: _params[2]
					}, decodeUrl(_params[3]));
				}
			}
		};
		loginAndRedirect();
	});
	app.controller('NoticeCtrl', function($scope, SnapshotService){
		SnapshotService.getNotice(3, function(data){
			$scope.notices = data;
		});
	});
	return app;
});