(function(){
    'use strict';

    angular.module('ammico', [ 'ngRoute','ammicoHome', 'ammicoMyvisit', 'ammicoBooks', 'ammicoVisites', 'ammicoSlides', 'ammicoSlideshow', 'ammicoSearch', 'ammicoAuth', 'templates' ])
    .config(function($routeProvider) {
        $routeProvider.
        when('/', {
            controller: 'homeCtrl',
            templateUrl: 'home/home.html',
            authRequired: false
        }).
        when('/my_visit', {
            controller: 'my_visitCtrl',
            templateUrl: 'my_visit/my_visit.html',
            authRequired: true
        }).
        when('/books', {
            controller: 'booksCtrl',
            templateUrl: 'books/books.html'
        }).
        when('/books/:idBook', {
            controller: 'bookCtrl',
            templateUrl: 'books/book.html',
            authRequired: true
        }).
        when('/visites', {
            controller: 'visitesCtrl',
            templateUrl: 'visites/visites.html',
            authRequired: true
        }).
        when('/visites/:idVisit', {
            controller: 'visiteCtrl',
            templateUrl: 'visites/visite.html',
            authRequired: true
        }).
        when('/slide/:idSlide', {
            controller: 'slidesCtrl',
            templateUrl: 'slides/slides.html',
            authRequired: true
        }).
        when('/slideshow/', {
            controller: 'slideshowCtrl',
            templateUrl: 'slideshow/slideshow.html',
            authRequired: true
        }).
        when('/slideshow/:iSlide', {
            controller: 'slideshowCtrl',
            templateUrl: 'slideshow/slideshow.html',
            authRequired: true
        }).
        when('/search/:q', {
            controller: 'searchCtrl',
            templateUrl: 'search/search.html',
            authRequired: true
        }).
        when('/auth/:action', {
            controller: 'authCtrl',
            templateUrl: 'home/home.html',
            authRequired: false
        }).
        otherwise({
            redirectTo: '/'
        });
    })
    .run( function($rootScope, $location, $window, $http) {
        $rootScope.globals = {};
        if ($window.sessionStorage.token) {
            $rootScope.globals.userLogged = true;
            $http.defaults.headers.common.Authorization = 'Token ' + $window.sessionStorage.token;
        }
        $rootScope.$on( '$routeChangeStart', function(event, next) {
            if (next.authRequired && !$rootScope.globals.userLogged) {
                $location.path( '/auth/login' );
            }
        });
    })
    .service('searchApi', function($resource, context) {
        this.searchResource = function(params){
            return $resource(context.urls.searchUrl,  
                    {
                callback: 'JSON_CALLBACK'
                    },
                    {
                        getJsonp: {
                            method: 'JSONP',
                            params: params,
                            isArray: false,
                            transformResponse: function(data){
                                // Transform meta list into meta dict
                                var nb = data.hits.length;
                                for(var i=0;i<nb;i++){
                                    var nb_metas = data.hits[i].metas.length;
                                    data.hits[i].metas_dict = {};
                                    for(var j=0;j<nb_metas;j++){
                                        if(typeof data.hits[i].metas[j].images==='undefined'){
                                            data.hits[i].metas_dict[data.hits[i].metas[j].name] = data.hits[i].metas[j].value;
                                        }
                                        else{
                                            data.hits[i].metas_dict.images = data.hits[i].metas[j].images[0].value;
                                        }
                                    }
                                }
                                return data;
                            }
                        }
                    });
        };
    })
    .service('ammicoApi', function($resource, context, $sce) {
        this.listBooks = $resource(context.urls.ammicoUrl+'/books');
        this.book = $resource(context.urls.ammicoUrl+'/books/:idBook', {idBook:'@id'});
        this.order = $resource(context.urls.ammicoUrl+'/books/:idBook/order', {idBook:'@id'});
        this.booksSlides = $resource(context.urls.ammicoUrl+'/books/:idBook/slides', {idBook:'@id'});
        this.listSlides= $resource(context.urls.ammicoUrl+'/slides');
        this.slide = $resource(context.urls.ammicoUrl+'/slides/:idSlide', {idSlide:'@id'});
        this.sanitizeUrls = function(data){
            data.details.audio = $sce.trustAsResourceUrl(data.details.audio);
            data.details.video = $sce.trustAsResourceUrl(data.details.video);
            data.audio = $sce.trustAsResourceUrl(data.audio);
            data.video = $sce.trustAsResourceUrl(data.video);
            return data;
        };
    })
    .service('authApi', function($resource, context) {
        this.login = $resource(context.urls.ammicoUrl+'/auth/api-token-auth');
        this.logout = $resource(context.urls.ammicoUrl+'/auth/logout');
        this.user = $resource(context.urls.ammicoUrl+'/auth/user');
        this.test = $resource(context.urls.ammicoUrl+'/auth/auth');
    });
})();

(function(){
  'use strict';

  angular.module('ammico')
  .controller('routeClassCtrl', function($scope, $location) {
    $scope.isActive = function(route) {
        return route === $location.path();
    };
  });

})();

(function(){
	'use strict';

	angular.module('ammicoAuth',['ngRoute'])
	.controller('authCtrl', function($location, $rootScope, $routeParams, $modal){
		$modal.open({
			templateUrl: 'auth/' + $routeParams.action + '_modal.html',
			controller: 'auth' + $routeParams.action + 'Ctrl'
		}).result.then(function (result) {
			$location.path(result);
		}, function () {
			$location.path('/');
		});
	})
	.controller('authloginCtrl', function($modalInstance, $scope, authApi, $window, $http, $rootScope){
		$scope.login = function(){
			authApi.login.save({username:$scope.username, password:$scope.password}, function(data){
				$rootScope.globals.userLogged = true;
				$window.sessionStorage.token = data.token;
				$http.defaults.headers.common.Authorization = 'Token ' + $window.sessionStorage.token;
				$modalInstance.close('/books');
			});
		};
		$scope.register = function () {
			$modalInstance.close('/auth/register');
		};
		$scope.cancel = function () {
			$modalInstance.close('/');
		};
	})
	.controller('authlogoutCtrl', function($modalInstance, $scope, $window, $http, $rootScope){
		delete $window.sessionStorage.token;
		$rootScope.globals.userLogged = false;
		delete $http.defaults.headers.common.Authorization;

		$scope.cancel = function () {
			$modalInstance.close('/');
		};
	})
	.controller('authregisterCtrl', function($scope, $modalInstance, authApi){
		$scope.register = function () {
			authApi.user.save({
				username: $scope.username,
				email: $scope.email,
				password: $scope.password,
			}, function(){
				$modalInstance.close('/auth/login');
			});
		};
		$scope.back = function () {
			$modalInstance.close('/auth/login');
		};
	});
})();

(function(){
	'use strict';

	angular.module('ammicoBooks',['ngRoute', 'ui.sortable'])
	.controller('booksCtrl', function($scope, $location, $modal, ammicoApi){
		$scope.books = ammicoApi.listBooks.query({format:'json'}, function(data){
			data.sort(function (a, b) {
				return a.date < b.date;
			});

			for (var i = 0; i < data.length; i++) {
		    	if (data[i].idArticle === null){
		    		data[i].slides = ammicoApi.booksSlides.query({idBook:data[i].id, format:'json'});
		    	}
			}	
		});

		$scope.toggleModal = function (index) {

			var modalInstance = $modal.open({
				templateUrl: 'books/add_book_modal.html',
				controller: 'ModalAddBookCtrl',
				size: 'sm'
			});

			modalInstance.result.then(function (idBook) {
				var newSlide = {
					book: idBook,
					idInventory: $scope.results.hits[index].metas_dict.inventorynumber
				};
				ammicoApi.listSlides.save(newSlide);
			});
		};
		
		$scope.searchSubmit = function(){
			$location.path('/search/' + $scope.q);
		};

		$scope.addBook = function (idParent) {
			$modal.open({
				templateUrl: 'books/add_modal.html',
				controller: 'ModalAddBookCtrl'
			}).result.then(function (title) {
				ammicoApi.listBooks.save({idParent:idParent, title: title}, function(newBook){
					$scope.books.push(newBook);
				});
			});
		};
		$scope.deleteItem = function(book){
			if(window.confirm('Êtes-vous sûr(e) de vouloir effacer cet élément ? Cette action est irrémédiable.')){
				ammicoApi.book.delete({idBook: book.id}, function(){
					$scope.books.splice($scope.books.indexOf(book), 1);
				},
				function(error) {
					if (error.status === 404){
						$scope.books.splice($scope.books.indexOf(book), 1);
					}
				});
			}
		};
	})

	.controller('bookCtrl', function($scope, $location, ammicoApi, $routeParams, $modal) {
		$scope.parentBook = ammicoApi.book.get({idBook:$routeParams.idBook, format:'json'}, function(data){
			data.slides = ammicoApi.booksSlides.query({idBook: data.id, format:'json'}, function(data){
				data.sort(function (a, b) {
					return a.orderIndex > b.orderIndex;
				});
			});
		});
		
		$scope.toggleFavorite = function (index) {

		    $scope.parentBook.slides[index].favorite = !$scope.parentBook.slides[index].favorite;
		    $scope.parentBook.slides[index].$save({format:'json'});
		    //$scope.slide.$save({idSlide:$scope.slide.id, format:'json'});
        };

		$scope.toggleModal = function (index) {

			var modalInstance = $modal.open({
				templateUrl: 'books/add_book_modal.html',
				controller: 'ModalAddBookCtrl',
				size: 'sm'
			});

			modalInstance.result.then(function (idBook) {
				var newSlide = {
					book: idBook,
					idInventory: $scope.results.hits[index].metas_dict.inventorynumber
				};
				ammicoApi.listSlides.save(newSlide);
			});
		};

		$scope.sortableOptions = {
				stop: function() {
					var order = $scope.parentBook.slides.map(function(i){
						return i.id;
					});
					ammicoApi.order.save({idBook:$routeParams.idBook}, {order: order});
				}
		};

		$scope.deleteItem = function(i){
		    if(window.confirm('Êtes-vous sûr(e) de vouloir effacer cet élément ? Cette action est irrémédiable.')){
		        $scope.parentBook.slides[i].$delete();
			//if(0<=i && i<$scope.slides.length){
//					ammicoApi.slide.delete({idSlide: $scope.slides[i].id}, function(){
//						$scope.slides.splice(i, 1);
//					},
//					function(error) {
//						if (error.status === 404){
//							$scope.slides.splice(i, 1);
//						}
//					});
//				}
			}
		};
	})
	.controller('ModalAddBookCtrl', function ($scope, ammicoApi, $modalInstance) {

		$scope.add = function(){
			$modalInstance.close($scope.title);
//			ammicoApi.listBooks.save({title: $scope.title}, function(newBook){
//			});
		};
		$scope.cancel = function () {
			$modalInstance.dismiss('cancel');
		}
		;
		$scope.books = ammicoApi.listBooks.query({format:'json'});
		
		$scope.addToBook = function(idBook){
			$modalInstance.close(idBook);
		};

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

'common service goes here';
(function(){
	'use strict';


	angular.module('ammicoHome',['ngRoute'])
	.config(function ($routeProvider) {
		$routeProvider
		.when('/', {
			templateUrl: 'home/home.html',
			controller: 'homeCtrl'
		});
	})
	.controller('homeCtrl', function($scope, $location){
		$scope.searchSubmit = function(){
			$location.path('/search/' + $scope.q);
		};
	})
	.filter('meta', function() {
		return function(input, metaName) {
			var nb = input.length, i = 0, found = false;
			while(found===false && i<nb){
				if(input[i].name===metaName){
					found = true;
					return input[i].value;
				}
				i++;
			}
			return '';
		};
	});

})();

(function(){
	'use strict';

	angular.module('ammicoMyvisit',['ngRoute', 'ui.sortable'])
	.controller('my_visitCtrl', function($scope, $location, $modal, ammicoApi){

		//get list book
		$scope.books = ammicoApi.listBooks.query({format:'json'}, function(data){
			data.sort(function (a, b) {
				return a.date < b.date;
			});

			for (var i = 0; i < data.length; i++) {
		    	if (data[i].idArticle){
		    		data[i].slides = ammicoApi.booksSlides.query({idBook:data[i].id, format:'json'});
		    	}
			}	
		});

		$scope.addBook = function (idParent) {
			$modal.open({
				templateUrl: 'my_visit/add_modal_my_visit.html',
				controller: 'ModalAddMyvisitCtrl'
			}).result.then(function (title) {
				//add book with the title written in the modal
				ammicoApi.listBooks.save({idParent:idParent, title: title}, function(newBook){
					$scope.books.push(newBook);
				});
			});
		};


		$scope.share = function (idParent) {
			$modal.open({
				templateUrl: 'my_visit/share_modal_my_visit.html',
				controller: 'ModalAddMyvisitCtrl'
			}).result.then(function (title) {
				//add book with the title written in the modal
				ammicoApi.slidesBook.query({idParent:idParent, title: title}, function(newBook){
					$scope.books(newBook);
				});
			});
		};

		
	})

	.controller('ModalAddMyvisitCtrl', function ($scope, ammicoApi, $modalInstance) {

		$scope.add = function(){
			$modalInstance.close($scope.title);
//			ammicoApi.listBooks.save({title: $scope.title}, function(newBook){
//			});
		};
		$scope.cancel = function () {
			$modalInstance.dismiss('cancel');
		};
		$scope.share = function () {
			$modalInstance($scope.book);
		};
	});

	


})();


(function(){
	'use strict';

	angular.module('ammicoSearch',['ngResource', 'ngRoute', 'ui.bootstrap'])
	.config(function ($routeProvider) {
		$routeProvider
		.when('/', {
			templateUrl: 'search/search.html',
			controller: 'searchCtrl'
		});
	})
	.controller('searchCtrl', function($scope, $location, $routeParams, searchApi, ammicoApi, $modal){
		$scope.q = $routeParams.q || '';
		$scope.results = searchApi.searchResource({q:$scope.q, of: 'json', synthesis: 'false', nresults:'10', callback: 'JSON_CALLBACK'}).getJsonp();
		
		$scope.toggleModal = function (index) {

			var modalInstance = $modal.open({
				templateUrl: 'search/modal.html',
				controller: 'ModalInstanceCtrl',
				size: 'sm'
			});

			modalInstance.result.then(function (idBook) {
				var newSlide = {
					book: idBook,
					idInventory: $scope.results.hits[index].metas_dict.inventorynumber
				};
				ammicoApi.listSlides.save(newSlide);
			});
		};
	})
	.controller('ModalInstanceCtrl', function ($scope, ammicoApi, $modalInstance) {
		$scope.books = ammicoApi.listBooks.query({format:'json'});
		
		$scope.addToBook = function(idBook){
			$modalInstance.close(idBook);
		};

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

(function(){
	'use strict';

	angular.module('ammicoSlides',['ngResource', 'ngRoute'])
	.controller('slidesCtrl', function($scope, $routeParams, ammicoApi){
		
		$scope.slide = ammicoApi.slide.get({idSlide:$routeParams.idSlide, format:'json'}, function(data){
			data = ammicoApi.sanitizeUrls(data);
		});

	})
	.directive('slideEditor', function() {
		return {
			restrict: 'AE',
			replace: true,
			scope: false,
			templateUrl: 'slides/data_editor.html',
			controller: function($scope){
				$scope.slidesave = function(){
					if(typeof $scope.slide.tags === 'string'){
						$scope.slide.tags = $scope.slide.tags.split(',');
						for (var i = $scope.slide.tags.length - 1; i >= 0; i--) {
							$scope.slide.tags[i] = $scope.slide.tags[i].trim();
						}
					}
					$scope.slide.editMode = false;
					$scope.slide.$save({idSlide:$scope.slide.id, format:'json'});
				};
				$scope.doubleClick = function(){
					$scope.slide.editMode = true;
				};
			}
		};
	});

})();

(function(){
	'use strict';

	angular.module('ammicoSlideshow',['ngResource', 'ngRoute', 'ui.bootstrap'])
	.controller('slideshowCtrl', function($scope, ammicoApi, $routeParams){
		$scope.slideshow = ammicoApi.booksSlides.query({idBook:$routeParams.iSlide, format:'json'}, function(data){
			data = ammicoApi.sanitizeUrls(data);
		});
		$scope.book = ammicoApi.book.get({idBook:$routeParams.iSlide, format:'json'});
	});
})();

(function(){
	'use strict';

	angular.module('ammicoVisites',['ngRoute', 'ui.sortable'])
	.controller('visitesCtrl', function($scope, $location, $modal, ammicoApi){

		//get list book
		$scope.books = ammicoApi.listBooks.query({format:'json'}, function(data){
			data.sort(function (a, b) {
				return a.date < b.date;
			});

			for (var i = 0; i < data.length; i++) {
		    	if (data[i].idArticle){
		    		data[i].slides = ammicoApi.booksSlides.query({idBook:data[i].id, format:'json'});
		    	}
			}	
		});

		$scope.toggleModal = function (index) {

			var modalInstance = $modal.open({
				templateUrl: 'visites/add_book_modal.html',
				controller: 'ModalAddVisitesCtrl',
				size: 'sm'
			});

			modalInstance.result.then(function (idBook) {
				var newSlide = {
					book: idBook,
					idInventory: $scope.results.hits[index].metas_dict.inventorynumber
				};
				ammicoApi.listSlides.save(newSlide);
			});
		};


		$scope.addBook = function (idParent) {
			$modal.open({
				templateUrl: 'visites/add_modal_visites.html',
				controller: 'ModalAddVisitesCtrl'
			}).result.then(function (title) {
				//add book with the title written in the modal
				ammicoApi.listBooks.save({idParent:idParent, title: title}, function(newBook){
					$scope.books.push(newBook);
				});
			});
		};
		
	})


  .controller('visiteCtrl', function($scope, ammicoApi, $routeParams, $modal) {
		//get the slides of a book
		$scope.slides = ammicoApi.booksSlides.query({idBook:$routeParams.idVisit, format:'json'}, function(data){
			data.sort(function (a, b) {
				return a.orderIndex > b.orderIndex;
			});
			
		});


		$scope.toggleModal = function (index) {

			var modalInstance = $modal.open({
				templateUrl: 'visites/add_book_modal.html',
				controller: 'ModalAddVisitesCtrl',
				size: 'sm'
			});

			modalInstance.result.then(function (idBook) {
				var newSlide = {
					book: idBook,
					idInventory: $scope.results.hits[index].metas_dict.inventorynumber
				};
				ammicoApi.listSlides.save(newSlide);
			});
		};

		$scope.addBook = function (idParent) {
			$modal.open({
				templateUrl: 'visites/add_modal_visites.html',
				controller: 'ModalAddVisitesCtrl'
			}).result.then(function (title) {
				//add book with the title written in the modal
				ammicoApi.listBooks.save({idParent:idParent, title: title}, function(newBook){
					$scope.books.push(newBook);
				});
			});
		};
		
		$scope.sortableOptions = {
				stop: function() {
					var order = $scope.slides.map(function(i){
						return i.id;
					});
					ammicoApi.order.save({idBook:$routeParams.idVisit}, {order: order});
				}
		};



		$scope.deleteItem = function(i){
			if(0<=i && i<$scope.slides.length){
				if(window.confirm('Êtes-vous sûr(e) de vouloir effacer cet élément ? Cette action est irrémédiable.')){
					//delete a slide
					ammicoApi.slide.delete({idSlide: $scope.slides[i].id}, function(){
						$scope.slides.splice(i, 1);
					},
					function(error) {
						if (error.status === 404){
							$scope.slides.splice(i, 1);
						}
					});
				}
			}
		};

	})


	.controller('ModalAddVisitesCtrl', function($scope, ammicoApi, $modalInstance) {

		$scope.add = function(){
			$modalInstance.close($scope.title);
//			ammicoApi.listBooks.save({title: $scope.title}, function(newBook){
//			});
		};
		$scope.cancel = function () {
			$modalInstance.dismiss('cancel');
		};

		$scope.books = ammicoApi.listBooks.query({format:'json'});
		
		$scope.addToBook = function(idBook){
			$modalInstance.close(idBook);
		};

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

	
	});

})();
