(function(){
    'use strict';

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

        //get list book
        $scope.books = Book.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].id_article){
                    data[i].slides = Slide.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
                Book.save({idParent:idParent, title: title}, function(newBook){
                    $scope.books.push(newBook);
                });
            });
        };        
    })
    .controller('ModalAddMyvisitCtrl', function ($scope, $modalInstance) {

        $scope.add = function(){
            $modalInstance.close($scope.title);
        };
        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
        $scope.share = function () {
            $modalInstance($scope.book);
        };
    });
})();

