'use strict';
/*
 * Service to controll modal windows, based on angular (ui.bootstrap.modal)  http://angular-ui.github.io/bootstrap/
 */

dashboardApp.factory('modalWindowService', ['$rootScope', '$modal', function($rootScope, $modal) {
    var self = this;
    var $scope = {};
    var currentScope = {};

    var modalInstance = {};

      self.modal = {
          isOpen: false, // true if any modal window opened
          openedWindowName: '',
          //controller: ModalInstanceCtrl,
          open: function(windowName, callerScope) {
            var className;
              currentScope = callerScope;

              modalInstance = $modal.open({
                templateUrl: windowName +'.html', // 'saveQuery.html',
                scope: currentScope,
                controller: function($scope, $modalInstance) {
                    $scope.close = function() {
                    $modalInstance.close('cancel');
                };
                },
                resolve: {
                  items: function () {
                    return $scope.items;
                  }
                }
              });

              self.modal.isOpen = true;
              self.modal.openedWindowName = windowName;

              $rootScope.$broadcast('modalOpen', {'windowName': windowName} );

          },
          close: function(windowName, callerScope) {

              // TODO: find better fix for animate out
              $('.modal.fade.in').attr("class","modal fade out");

              setTimeout(function() {
                $('.modal-backdrop.fade.in').attr("class","modal-backdrop fade out");
                modalInstance.close('cancel');
                self.modal.isOpen = false;
                self.modal.openedWindowName = '';

                $rootScope.$broadcast('modalClose');
              },250);

          }
      };

    return self.modal;

}]);