(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, $modal, Slide){
        $scope.q = $routeParams.q || '';
        if ($scope.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 = $scope.results.collect[index];
              delete newSlide.date;
              newSlide.book = idBook;
              newSlide.research_id = (newSlide.inventorynumber || newSlide.id_stop);
              Slide.save(newSlide);
            });
        };
    })
    .controller('ModalInstanceCtrl', function ($scope, $modalInstance, Book) {
        $scope.books = Book.query({format:'json'});

        $scope.addToBook = function(idBook){
            $modalInstance.close(idBook);
        };

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