/*

HTML Sweet Alert function
Use this for for passing html that will be compiled to Angular
You can pass an HTML string directly via 'html' option, or you can pass a link to template via 'templateHtml' option.

ex. Swangular.html({title: "Please fill in!",scope: $scope,templateHtml: '/templates/template.html'})
.then(function() { console.log("Done"); })
function swal_open(options) {
        var resolve = angular.extend({}, options.resolve);

        angular.forEach(resolve, function(value, key) {
          resolve[key] = angular.isString(value) ? $injector.get(value) : $injector.invoke(value, null, null, key);
        });

        return $q
          .all({
            html: _getHtml(options),
            locals: $q.all(resolve)
          })
          .then(function(setup) {
            var scope = options.scope,
              controller = options.controller,
              controllerAsOption = options.controllerAs,
              preConfirm = options.preConfirm;

            delete options.html;
            delete options.htmlTemplate;
            delete options.resolve;
            delete options.scope;
            delete options.controller;
            delete options.controllerAs;
            delete options.preConfirm;

            var locals = setup.locals;

            options.html = setup.html;

            scope = scope ? scope.$new() : $rootScope.$new();

            if (controller) {
              var controllerAs;

              if (controllerAsOption && angular.isString(controllerAsOption)) {
                controllerAs = controllerAsOption;
              }

              var controllerInstance = $controller(
                controller,
                angular.extend(locals, {
                  $scope: scope
                }),
                false,
                controllerAs
              );

              if (typeof preConfirm === 'string') {
                options.preConfirm = function() {
                  return $timeout(controllerInstance[preConfirm].bind(controllerInstance));
                };
              }
            }

            if (typeof preConfirm === 'function') {
              options.preConfirm = function() {
                return $timeout(preConfirm);
              };
            }

            var prom = $q.when(swal(options));
            var html = document.getElementsByClassName('swal2-modal')[0];

            // If there is a form, trigger the button on press of enter button
            var form = html.getElementsByTagName('form');
            if (form[0]) {
              form[0].onkeyup = function(event) {
                event.stopPropagation();
                if (event.keyCode === 13) {
                  html.querySelector('.swal2-confirm').click();
                }
              };
            }

            $compile(html)(scope);

            return prom;
          });
      }