/**
 * Binds a TinyMCE widget to <textarea> elements.
 */
angular.module('ui.tinymce', [])
  .value('uiTinymceConfig', {
      force_br_newlines: true,
      force_p_newlines: false,
      forced_root_block: '',
      statusbar: false,
      menubar: false,
      skin: "light",
      paste_as_text: true,
      relative_urls: false,
      convert_urls: false,
      remove_script_host: false,    
      plugins: "textcolor link paste code wizdomImagePicker",
      toolbar: "bold italic underline | forecolor | code | link wizdomImagePicker"
  })
  .directive('uiTinymce', ['uiTinymceConfig', 'contextInfo', 'notificationService', function (uiTinymceConfig, contextInfo, notificationService) {
      uiTinymceConfig = uiTinymceConfig || {};
      var generatedIds = 0;
      return {
          priority: 10,
          require: 'ngModel',
          link: function (scope, elm, attrs, ngModel) {

              if (attrs["uiTinymceDisable"] != null && $.parseJSON(attrs["uiTinymceDisable"])) {
                  return;
              }

              var expression, options, tinyInstance,
                updateView = function () {
                    ngModel.$setViewValue(elm.val());
                    if (!scope.$root.$$phase) {
                        scope.$apply();
                    }
                };

              // generate an ID if not present
              if (!attrs.id) {
                  attrs.$set('id', 'uiTinymce' + generatedIds++);
              }

              if (attrs.uiTinymce) {
                  expression = scope.$eval(attrs.uiTinymce);
              } else {
                  expression = {};
              }

              // make config'ed setup method available
              if (expression.setup) {
                  var configSetup = expression.setup;
                  delete expression.setup;
              }

              options = {
                  // Update model when calling setContent (such as from the source editor popup)
                  setup: function (ed) {
                      var args;
                      ed.on('init', function (args) {
                          ngModel.$render();
                          ngModel.$setPristine();
                      });
                      // Update model on button click
                      ed.on('ExecCommand', function (e) {
                          ed.save();
                          updateView();
                      });
                      // Update model on keypress
                      ed.on('KeyUp', function (e) {
                          ed.save();
                          updateView();
                      });
                      // Update model on change, i.e. copy/pasted text, plugins altering content
                      ed.on('SetContent', function (e) {
                          if (!e.initial && ngModel.$viewValue !== e.content) {
                              ed.save();
                              updateView();
                          }
                      });
                      ed.on('blur', function (e) {
                          elm.blur();
                      });
                      // Update model when an object has been resized (table, image)
                      ed.on('ObjectResized', function (e) {
                          ed.save();
                          updateView();
                      });
                      if (configSetup) {
                          configSetup(ed);
                      }
                  },
                  mode: 'exact',
                  elements: attrs.id
              };
              // extend options with initial uiTinymceConfig and options from directive attribute value
              angular.extend(options, uiTinymceConfig, expression, { language: contextInfo.language });
              setTimeout(function () {
                  if (window["Wizdom365BlobUrl"])
                      tinymce.baseURL = window["Wizdom365BlobUrl"] + "Base/Scripts/tinymce";
                  else if (window["Wizdom365AppUrl"])
                      tinymce.baseURL = window["Wizdom365AppUrl"] + "Base/Scripts/tinymce";
                  else
                      tinymce.baseURL = "/Base/Scripts/tinymce";
                  tinymce.init(options);
              });

              ngModel.$render = function () {
                  if (!tinyInstance) {
                      tinyInstance = tinymce.get(attrs.id);
                  }
                  if (tinyInstance) {
                      tinyInstance.setContent(ngModel.$viewValue || '');
                  }
              };

              scope.$on('$destroy', function () {
                  if (!tinyInstance) { tinyInstance = tinymce.get(attrs.id); }
                  if (tinyInstance) {
                      tinyInstance.remove();
                      tinyInstance = null;
                  }
              });

              function messageHandler(result) {
                  if (result.data.indexOf("imageUploadFailed:maxRequestLength") >= 0) {
                        notificationService.showErrorMessage("File size exceeds the limit allowed");
                  }
              }

              if (typeof window.addEventListener != 'undefined')
                  window.addEventListener('message', messageHandler, false);
              else if (typeof window["attachEvent"] != 'undefined')
                  window["attachEvent"]('onmessage', messageHandler);
          }
      };
  }]);