b2evolution PHP Cross Reference Blogging Systems

Source: /plugins/tinymce_plugin/tiny_mce/tiny_mce_src.js - 16802 lines - 433495 bytes - Summary - Text - Print

   1  (function(win) {
   2      var whiteSpaceRe = /^\s*|\s*$/g,
   3          undefined, isRegExpBroken = 'B'.replace(/A(.)|B/, '$1') === '$1';
   4  
   5      var tinymce = {
   6          majorVersion : '3',
   7  
   8          minorVersion : '4.8',
   9  
  10          releaseDate : '2012-02-02',
  11  
  12          _init : function() {
  13              var t = this, d = document, na = navigator, ua = na.userAgent, i, nl, n, base, p, v;
  14  
  15              t.isOpera = win.opera && opera.buildNumber;
  16  
  17              t.isWebKit = /WebKit/.test(ua);
  18  
  19              t.isIE = !t.isWebKit && !t.isOpera && (/MSIE/gi).test(ua) && (/Explorer/gi).test(na.appName);
  20  
  21              t.isIE6 = t.isIE && /MSIE [56]/.test(ua);
  22  
  23              t.isIE7 = t.isIE && /MSIE [7]/.test(ua);
  24  
  25              t.isIE8 = t.isIE && /MSIE [8]/.test(ua);
  26  
  27              t.isIE9 = t.isIE && /MSIE [9]/.test(ua);
  28  
  29              t.isGecko = !t.isWebKit && /Gecko/.test(ua);
  30  
  31              t.isMac = ua.indexOf('Mac') != -1;
  32  
  33              t.isAir = /adobeair/i.test(ua);
  34  
  35              t.isIDevice = /(iPad|iPhone)/.test(ua);
  36              
  37              t.isIOS5 = t.isIDevice && ua.match(/AppleWebKit\/(\d*)/)[1]>=534;
  38  
  39              // TinyMCE .NET webcontrol might be setting the values for TinyMCE
  40              if (win.tinyMCEPreInit) {
  41                  t.suffix = tinyMCEPreInit.suffix;
  42                  t.baseURL = tinyMCEPreInit.base;
  43                  t.query = tinyMCEPreInit.query;
  44                  return;
  45              }
  46  
  47              // Get suffix and base
  48              t.suffix = '';
  49  
  50              // If base element found, add that infront of baseURL
  51              nl = d.getElementsByTagName('base');
  52              for (i=0; i<nl.length; i++) {
  53                  if (v = nl[i].href) {
  54                      // Host only value like http://site.com or http://site.com:8008
  55                      if (/^https?:\/\/[^\/]+$/.test(v))
  56                          v += '/';
  57  
  58                      base = v ? v.match(/.*\//)[0] : ''; // Get only directory
  59                  }
  60              }
  61  
  62  			function getBase(n) {
  63                  if (n.src && /tiny_mce(|_gzip|_jquery|_prototype|_full)(_dev|_src)?.js/.test(n.src)) {
  64                      if (/_(src|dev)\.js/g.test(n.src))
  65                          t.suffix = '_src';
  66  
  67                      if ((p = n.src.indexOf('?')) != -1)
  68                          t.query = n.src.substring(p + 1);
  69  
  70                      t.baseURL = n.src.substring(0, n.src.lastIndexOf('/'));
  71  
  72                      // If path to script is relative and a base href was found add that one infront
  73                      // the src property will always be an absolute one on non IE browsers and IE 8
  74                      // so this logic will basically only be executed on older IE versions
  75                      if (base && t.baseURL.indexOf('://') == -1 && t.baseURL.indexOf('/') !== 0)
  76                          t.baseURL = base + t.baseURL;
  77  
  78                      return t.baseURL;
  79                  }
  80  
  81                  return null;
  82              };
  83  
  84              // Check document
  85              nl = d.getElementsByTagName('script');
  86              for (i=0; i<nl.length; i++) {
  87                  if (getBase(nl[i]))
  88                      return;
  89              }
  90  
  91              // Check head
  92              n = d.getElementsByTagName('head')[0];
  93              if (n) {
  94                  nl = n.getElementsByTagName('script');
  95                  for (i=0; i<nl.length; i++) {
  96                      if (getBase(nl[i]))
  97                          return;
  98                  }
  99              }
 100  
 101              return;
 102          },
 103  
 104          is : function(o, t) {
 105              if (!t)
 106                  return o !== undefined;
 107  
 108              if (t == 'array' && (o.hasOwnProperty && o instanceof Array))
 109                  return true;
 110  
 111              return typeof(o) == t;
 112          },
 113  
 114          makeMap : function(items, delim, map) {
 115              var i;
 116  
 117              items = items || [];
 118              delim = delim || ',';
 119  
 120              if (typeof(items) == "string")
 121                  items = items.split(delim);
 122  
 123              map = map || {};
 124  
 125              i = items.length;
 126              while (i--)
 127                  map[items[i]] = {};
 128  
 129              return map;
 130          },
 131  
 132          each : function(o, cb, s) {
 133              var n, l;
 134  
 135              if (!o)
 136                  return 0;
 137  
 138              s = s || o;
 139  
 140              if (o.length !== undefined) {
 141                  // Indexed arrays, needed for Safari
 142                  for (n=0, l = o.length; n < l; n++) {
 143                      if (cb.call(s, o[n], n, o) === false)
 144                          return 0;
 145                  }
 146              } else {
 147                  // Hashtables
 148                  for (n in o) {
 149                      if (o.hasOwnProperty(n)) {
 150                          if (cb.call(s, o[n], n, o) === false)
 151                              return 0;
 152                      }
 153                  }
 154              }
 155  
 156              return 1;
 157          },
 158  
 159  
 160          map : function(a, f) {
 161              var o = [];
 162  
 163              tinymce.each(a, function(v) {
 164                  o.push(f(v));
 165              });
 166  
 167              return o;
 168          },
 169  
 170          grep : function(a, f) {
 171              var o = [];
 172  
 173              tinymce.each(a, function(v) {
 174                  if (!f || f(v))
 175                      o.push(v);
 176              });
 177  
 178              return o;
 179          },
 180  
 181          inArray : function(a, v) {
 182              var i, l;
 183  
 184              if (a) {
 185                  for (i = 0, l = a.length; i < l; i++) {
 186                      if (a[i] === v)
 187                          return i;
 188                  }
 189              }
 190  
 191              return -1;
 192          },
 193  
 194          extend : function(o, e) {
 195              var i, l, a = arguments;
 196  
 197              for (i = 1, l = a.length; i < l; i++) {
 198                  e = a[i];
 199  
 200                  tinymce.each(e, function(v, n) {
 201                      if (v !== undefined)
 202                          o[n] = v;
 203                  });
 204              }
 205  
 206              return o;
 207          },
 208  
 209  
 210          trim : function(s) {
 211              return (s ? '' + s : '').replace(whiteSpaceRe, '');
 212          },
 213  
 214          create : function(s, p, root) {
 215              var t = this, sp, ns, cn, scn, c, de = 0;
 216  
 217              // Parse : <prefix> <class>:<super class>
 218              s = /^((static) )?([\w.]+)(:([\w.]+))?/.exec(s);
 219              cn = s[3].match(/(^|\.)(\w+)$/i)[2]; // Class name
 220  
 221              // Create namespace for new class
 222              ns = t.createNS(s[3].replace(/\.\w+$/, ''), root);
 223  
 224              // Class already exists
 225              if (ns[cn])
 226                  return;
 227  
 228              // Make pure static class
 229              if (s[2] == 'static') {
 230                  ns[cn] = p;
 231  
 232                  if (this.onCreate)
 233                      this.onCreate(s[2], s[3], ns[cn]);
 234  
 235                  return;
 236              }
 237  
 238              // Create default constructor
 239              if (!p[cn]) {
 240                  p[cn] = function() {};
 241                  de = 1;
 242              }
 243  
 244              // Add constructor and methods
 245              ns[cn] = p[cn];
 246              t.extend(ns[cn].prototype, p);
 247  
 248              // Extend
 249              if (s[5]) {
 250                  sp = t.resolve(s[5]).prototype;
 251                  scn = s[5].match(/\.(\w+)$/i)[1]; // Class name
 252  
 253                  // Extend constructor
 254                  c = ns[cn];
 255                  if (de) {
 256                      // Add passthrough constructor
 257                      ns[cn] = function() {
 258                          return sp[scn].apply(this, arguments);
 259                      };
 260                  } else {
 261                      // Add inherit constructor
 262                      ns[cn] = function() {
 263                          this.parent = sp[scn];
 264                          return c.apply(this, arguments);
 265                      };
 266                  }
 267                  ns[cn].prototype[cn] = ns[cn];
 268  
 269                  // Add super methods
 270                  t.each(sp, function(f, n) {
 271                      ns[cn].prototype[n] = sp[n];
 272                  });
 273  
 274                  // Add overridden methods
 275                  t.each(p, function(f, n) {
 276                      // Extend methods if needed
 277                      if (sp[n]) {
 278                          ns[cn].prototype[n] = function() {
 279                              this.parent = sp[n];
 280                              return f.apply(this, arguments);
 281                          };
 282                      } else {
 283                          if (n != cn)
 284                              ns[cn].prototype[n] = f;
 285                      }
 286                  });
 287              }
 288  
 289              // Add static methods
 290              t.each(p['static'], function(f, n) {
 291                  ns[cn][n] = f;
 292              });
 293  
 294              if (this.onCreate)
 295                  this.onCreate(s[2], s[3], ns[cn].prototype);
 296          },
 297  
 298          walk : function(o, f, n, s) {
 299              s = s || this;
 300  
 301              if (o) {
 302                  if (n)
 303                      o = o[n];
 304  
 305                  tinymce.each(o, function(o, i) {
 306                      if (f.call(s, o, i, n) === false)
 307                          return false;
 308  
 309                      tinymce.walk(o, f, n, s);
 310                  });
 311              }
 312          },
 313  
 314          createNS : function(n, o) {
 315              var i, v;
 316  
 317              o = o || win;
 318  
 319              n = n.split('.');
 320              for (i=0; i<n.length; i++) {
 321                  v = n[i];
 322  
 323                  if (!o[v])
 324                      o[v] = {};
 325  
 326                  o = o[v];
 327              }
 328  
 329              return o;
 330          },
 331  
 332          resolve : function(n, o) {
 333              var i, l;
 334  
 335              o = o || win;
 336  
 337              n = n.split('.');
 338              for (i = 0, l = n.length; i < l; i++) {
 339                  o = o[n[i]];
 340  
 341                  if (!o)
 342                      break;
 343              }
 344  
 345              return o;
 346          },
 347  
 348          addUnload : function(f, s) {
 349              var t = this;
 350  
 351              f = {func : f, scope : s || this};
 352  
 353              if (!t.unloads) {
 354  				function unload() {
 355                      var li = t.unloads, o, n;
 356  
 357                      if (li) {
 358                          // Call unload handlers
 359                          for (n in li) {
 360                              o = li[n];
 361  
 362                              if (o && o.func)
 363                                  o.func.call(o.scope, 1); // Send in one arg to distinct unload and user destroy
 364                          }
 365  
 366                          // Detach unload function
 367                          if (win.detachEvent) {
 368                              win.detachEvent('onbeforeunload', fakeUnload);
 369                              win.detachEvent('onunload', unload);
 370                          } else if (win.removeEventListener)
 371                              win.removeEventListener('unload', unload, false);
 372  
 373                          // Destroy references
 374                          t.unloads = o = li = w = unload = 0;
 375  
 376                          // Run garbarge collector on IE
 377                          if (win.CollectGarbage)
 378                              CollectGarbage();
 379                      }
 380                  };
 381  
 382  				function fakeUnload() {
 383                      var d = document;
 384  
 385                      // Is there things still loading, then do some magic
 386                      if (d.readyState == 'interactive') {
 387  						function stop() {
 388                              // Prevent memory leak
 389                              d.detachEvent('onstop', stop);
 390  
 391                              // Call unload handler
 392                              if (unload)
 393                                  unload();
 394  
 395                              d = 0;
 396                          };
 397  
 398                          // Fire unload when the currently loading page is stopped
 399                          if (d)
 400                              d.attachEvent('onstop', stop);
 401  
 402                          // Remove onstop listener after a while to prevent the unload function
 403                          // to execute if the user presses cancel in an onbeforeunload
 404                          // confirm dialog and then presses the browser stop button
 405                          win.setTimeout(function() {
 406                              if (d)
 407                                  d.detachEvent('onstop', stop);
 408                          }, 0);
 409                      }
 410                  };
 411  
 412                  // Attach unload handler
 413                  if (win.attachEvent) {
 414                      win.attachEvent('onunload', unload);
 415                      win.attachEvent('onbeforeunload', fakeUnload);
 416                  } else if (win.addEventListener)
 417                      win.addEventListener('unload', unload, false);
 418  
 419                  // Setup initial unload handler array
 420                  t.unloads = [f];
 421              } else
 422                  t.unloads.push(f);
 423  
 424              return f;
 425          },
 426  
 427          removeUnload : function(f) {
 428              var u = this.unloads, r = null;
 429  
 430              tinymce.each(u, function(o, i) {
 431                  if (o && o.func == f) {
 432                      u.splice(i, 1);
 433                      r = f;
 434                      return false;
 435                  }
 436              });
 437  
 438              return r;
 439          },
 440  
 441          explode : function(s, d) {
 442              return s ? tinymce.map(s.split(d || ','), tinymce.trim) : s;
 443          },
 444  
 445          _addVer : function(u) {
 446              var v;
 447  
 448              if (!this.query)
 449                  return u;
 450  
 451              v = (u.indexOf('?') == -1 ? '?' : '&') + this.query;
 452  
 453              if (u.indexOf('#') == -1)
 454                  return u + v;
 455  
 456              return u.replace('#', v + '#');
 457          },
 458  
 459          // Fix function for IE 9 where regexps isn't working correctly
 460          // Todo: remove me once MS fixes the bug
 461          _replace : function(find, replace, str) {
 462              // On IE9 we have to fake $x replacement
 463              if (isRegExpBroken) {
 464                  return str.replace(find, function() {
 465                      var val = replace, args = arguments, i;
 466  
 467                      for (i = 0; i < args.length - 2; i++) {
 468                          if (args[i] === undefined) {
 469                              val = val.replace(new RegExp('\\$' + i, 'g'), '');
 470                          } else {
 471                              val = val.replace(new RegExp('\\$' + i, 'g'), args[i]);
 472                          }
 473                      }
 474  
 475                      return val;
 476                  });
 477              }
 478  
 479              return str.replace(find, replace);
 480          }
 481  
 482          };
 483  
 484      // Initialize the API
 485      tinymce._init();
 486  
 487      // Expose tinymce namespace to the global namespace (window)
 488      win.tinymce = win.tinyMCE = tinymce;
 489  
 490      // Describe the different namespaces
 491  
 492      })(window);
 493  
 494  
 495  
 496  tinymce.create('tinymce.util.Dispatcher', {
 497      scope : null,
 498      listeners : null,
 499  
 500      Dispatcher : function(s) {
 501          this.scope = s || this;
 502          this.listeners = [];
 503      },
 504  
 505      add : function(cb, s) {
 506          this.listeners.push({cb : cb, scope : s || this.scope});
 507  
 508          return cb;
 509      },
 510  
 511      addToTop : function(cb, s) {
 512          this.listeners.unshift({cb : cb, scope : s || this.scope});
 513  
 514          return cb;
 515      },
 516  
 517      remove : function(cb) {
 518          var l = this.listeners, o = null;
 519  
 520          tinymce.each(l, function(c, i) {
 521              if (cb == c.cb) {
 522                  o = cb;
 523                  l.splice(i, 1);
 524                  return false;
 525              }
 526          });
 527  
 528          return o;
 529      },
 530  
 531      dispatch : function() {
 532          var s, a = arguments, i, li = this.listeners, c;
 533  
 534          // Needs to be a real loop since the listener count might change while looping
 535          // And this is also more efficient
 536          for (i = 0; i<li.length; i++) {
 537              c = li[i];
 538              s = c.cb.apply(c.scope, a.length > 0 ? a : [c.scope]);
 539  
 540              if (s === false)
 541                  break;
 542          }
 543  
 544          return s;
 545      }
 546  
 547      });
 548  
 549  (function() {
 550      var each = tinymce.each;
 551  
 552      tinymce.create('tinymce.util.URI', {
 553          URI : function(u, s) {
 554              var t = this, o, a, b, base_url;
 555  
 556              // Trim whitespace
 557              u = tinymce.trim(u);
 558  
 559              // Default settings
 560              s = t.settings = s || {};
 561  
 562              // Strange app protocol that isn't http/https or local anchor
 563              // For example: mailto,skype,tel etc.
 564              if (/^([\w\-]+):([^\/]{2})/i.test(u) || /^\s*#/.test(u)) {
 565                  t.source = u;
 566                  return;
 567              }
 568  
 569              // Absolute path with no host, fake host and protocol
 570              if (u.indexOf('/') === 0 && u.indexOf('//') !== 0)
 571                  u = (s.base_uri ? s.base_uri.protocol || 'http' : 'http') + '://mce_host' + u;
 572  
 573              // Relative path http:// or protocol relative //path
 574              if (!/^[\w-]*:?\/\//.test(u)) {
 575                  base_url = s.base_uri ? s.base_uri.path : new tinymce.util.URI(location.href).directory;
 576                  u = ((s.base_uri && s.base_uri.protocol) || 'http') + '://mce_host' + t.toAbsPath(base_url, u);
 577              }
 578  
 579              // Parse URL (Credits goes to Steave, http://blog.stevenlevithan.com/archives/parseuri)
 580              u = u.replace(/@@/g, '(mce_at)'); // Zope 3 workaround, they use @@something
 581              u = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(u);
 582              each(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], function(v, i) {
 583                  var s = u[i];
 584  
 585                  // Zope 3 workaround, they use @@something
 586                  if (s)
 587                      s = s.replace(/\(mce_at\)/g, '@@');
 588  
 589                  t[v] = s;
 590              });
 591  
 592              if (b = s.base_uri) {
 593                  if (!t.protocol)
 594                      t.protocol = b.protocol;
 595  
 596                  if (!t.userInfo)
 597                      t.userInfo = b.userInfo;
 598  
 599                  if (!t.port && t.host == 'mce_host')
 600                      t.port = b.port;
 601  
 602                  if (!t.host || t.host == 'mce_host')
 603                      t.host = b.host;
 604  
 605                  t.source = '';
 606              }
 607  
 608              //t.path = t.path || '/';
 609          },
 610  
 611          setPath : function(p) {
 612              var t = this;
 613  
 614              p = /^(.*?)\/?(\w+)?$/.exec(p);
 615  
 616              // Update path parts
 617              t.path = p[0];
 618              t.directory = p[1];
 619              t.file = p[2];
 620  
 621              // Rebuild source
 622              t.source = '';
 623              t.getURI();
 624          },
 625  
 626          toRelative : function(u) {
 627              var t = this, o;
 628  
 629              if (u === "./")
 630                  return u;
 631  
 632              u = new tinymce.util.URI(u, {base_uri : t});
 633  
 634              // Not on same domain/port or protocol
 635              if ((u.host != 'mce_host' && t.host != u.host && u.host) || t.port != u.port || t.protocol != u.protocol)
 636                  return u.getURI();
 637  
 638              o = t.toRelPath(t.path, u.path);
 639  
 640              // Add query
 641              if (u.query)
 642                  o += '?' + u.query;
 643  
 644              // Add anchor
 645              if (u.anchor)
 646                  o += '#' + u.anchor;
 647  
 648              return o;
 649          },
 650      
 651          toAbsolute : function(u, nh) {
 652              var u = new tinymce.util.URI(u, {base_uri : this});
 653  
 654              return u.getURI(this.host == u.host && this.protocol == u.protocol ? nh : 0);
 655          },
 656  
 657          toRelPath : function(base, path) {
 658              var items, bp = 0, out = '', i, l;
 659  
 660              // Split the paths
 661              base = base.substring(0, base.lastIndexOf('/'));
 662              base = base.split('/');
 663              items = path.split('/');
 664  
 665              if (base.length >= items.length) {
 666                  for (i = 0, l = base.length; i < l; i++) {
 667                      if (i >= items.length || base[i] != items[i]) {
 668                          bp = i + 1;
 669                          break;
 670                      }
 671                  }
 672              }
 673  
 674              if (base.length < items.length) {
 675                  for (i = 0, l = items.length; i < l; i++) {
 676                      if (i >= base.length || base[i] != items[i]) {
 677                          bp = i + 1;
 678                          break;
 679                      }
 680                  }
 681              }
 682  
 683              if (bp == 1)
 684                  return path;
 685  
 686              for (i = 0, l = base.length - (bp - 1); i < l; i++)
 687                  out += "../";
 688  
 689              for (i = bp - 1, l = items.length; i < l; i++) {
 690                  if (i != bp - 1)
 691                      out += "/" + items[i];
 692                  else
 693                      out += items[i];
 694              }
 695  
 696              return out;
 697          },
 698  
 699          toAbsPath : function(base, path) {
 700              var i, nb = 0, o = [], tr, outPath;
 701  
 702              // Split paths
 703              tr = /\/$/.test(path) ? '/' : '';
 704              base = base.split('/');
 705              path = path.split('/');
 706  
 707              // Remove empty chunks
 708              each(base, function(k) {
 709                  if (k)
 710                      o.push(k);
 711              });
 712  
 713              base = o;
 714  
 715              // Merge relURLParts chunks
 716              for (i = path.length - 1, o = []; i >= 0; i--) {
 717                  // Ignore empty or .
 718                  if (path[i].length == 0 || path[i] == ".")
 719                      continue;
 720  
 721                  // Is parent
 722                  if (path[i] == '..') {
 723                      nb++;
 724                      continue;
 725                  }
 726  
 727                  // Move up
 728                  if (nb > 0) {
 729                      nb--;
 730                      continue;
 731                  }
 732  
 733                  o.push(path[i]);
 734              }
 735  
 736              i = base.length - nb;
 737  
 738              // If /a/b/c or /
 739              if (i <= 0)
 740                  outPath = o.reverse().join('/');
 741              else
 742                  outPath = base.slice(0, i).join('/') + '/' + o.reverse().join('/');
 743  
 744              // Add front / if it's needed
 745              if (outPath.indexOf('/') !== 0)
 746                  outPath = '/' + outPath;
 747  
 748              // Add traling / if it's needed
 749              if (tr && outPath.lastIndexOf('/') !== outPath.length - 1)
 750                  outPath += tr;
 751  
 752              return outPath;
 753          },
 754  
 755          getURI : function(nh) {
 756              var s, t = this;
 757  
 758              // Rebuild source
 759              if (!t.source || nh) {
 760                  s = '';
 761  
 762                  if (!nh) {
 763                      if (t.protocol)
 764                          s += t.protocol + '://';
 765  
 766                      if (t.userInfo)
 767                          s += t.userInfo + '@';
 768  
 769                      if (t.host)
 770                          s += t.host;
 771  
 772                      if (t.port)
 773                          s += ':' + t.port;
 774                  }
 775  
 776                  if (t.path)
 777                      s += t.path;
 778  
 779                  if (t.query)
 780                      s += '?' + t.query;
 781  
 782                  if (t.anchor)
 783                      s += '#' + t.anchor;
 784  
 785                  t.source = s;
 786              }
 787  
 788              return t.source;
 789          }
 790      });
 791  })();
 792  
 793  (function() {
 794      var each = tinymce.each;
 795  
 796      tinymce.create('static tinymce.util.Cookie', {
 797          getHash : function(n) {
 798              var v = this.get(n), h;
 799  
 800              if (v) {
 801                  each(v.split('&'), function(v) {
 802                      v = v.split('=');
 803                      h = h || {};
 804                      h[unescape(v[0])] = unescape(v[1]);
 805                  });
 806              }
 807  
 808              return h;
 809          },
 810  
 811          setHash : function(n, v, e, p, d, s) {
 812              var o = '';
 813  
 814              each(v, function(v, k) {
 815                  o += (!o ? '' : '&') + escape(k) + '=' + escape(v);
 816              });
 817  
 818              this.set(n, o, e, p, d, s);
 819          },
 820  
 821          get : function(n) {
 822              var c = document.cookie, e, p = n + "=", b;
 823  
 824              // Strict mode
 825              if (!c)
 826                  return;
 827  
 828              b = c.indexOf("; " + p);
 829  
 830              if (b == -1) {
 831                  b = c.indexOf(p);
 832  
 833                  if (b != 0)
 834                      return null;
 835              } else
 836                  b += 2;
 837  
 838              e = c.indexOf(";", b);
 839  
 840              if (e == -1)
 841                  e = c.length;
 842  
 843              return unescape(c.substring(b + p.length, e));
 844          },
 845  
 846          set : function(n, v, e, p, d, s) {
 847              document.cookie = n + "=" + escape(v) +
 848                  ((e) ? "; expires=" + e.toGMTString() : "") +
 849                  ((p) ? "; path=" + escape(p) : "") +
 850                  ((d) ? "; domain=" + d : "") +
 851                  ((s) ? "; secure" : "");
 852          },
 853  
 854          remove : function(n, p) {
 855              var d = new Date();
 856  
 857              d.setTime(d.getTime() - 1000);
 858  
 859              this.set(n, '', d, p, d);
 860          }
 861      });
 862  })();
 863  
 864  (function() {
 865  	function serialize(o, quote) {
 866          var i, v, t;
 867  
 868          quote = quote || '"';
 869  
 870          if (o == null)
 871              return 'null';
 872  
 873          t = typeof o;
 874  
 875          if (t == 'string') {
 876              v = '\bb\tt\nn\ff\rr\""\'\'\\\\';
 877  
 878              return quote + o.replace(/([\u0080-\uFFFF\x00-\x1f\"\'\\])/g, function(a, b) {
 879                  // Make sure single quotes never get encoded inside double quotes for JSON compatibility
 880                  if (quote === '"' && a === "'")
 881                      return a;
 882  
 883                  i = v.indexOf(b);
 884  
 885                  if (i + 1)
 886                      return '\\' + v.charAt(i + 1);
 887  
 888                  a = b.charCodeAt().toString(16);
 889  
 890                  return '\\u' + '0000'.substring(a.length) + a;
 891              }) + quote;
 892          }
 893  
 894          if (t == 'object') {
 895              if (o.hasOwnProperty && o instanceof Array) {
 896                      for (i=0, v = '['; i<o.length; i++)
 897                          v += (i > 0 ? ',' : '') + serialize(o[i], quote);
 898  
 899                      return v + ']';
 900                  }
 901  
 902                  v = '{';
 903  
 904                  for (i in o) {
 905                      if (o.hasOwnProperty(i)) {
 906                          v += typeof o[i] != 'function' ? (v.length > 1 ? ',' + quote : quote) + i + quote +':' + serialize(o[i], quote) : '';
 907                      }
 908                  }
 909  
 910                  return v + '}';
 911          }
 912  
 913          return '' + o;
 914      };
 915  
 916      tinymce.util.JSON = {
 917          serialize: serialize,
 918  
 919          parse: function(s) {
 920              try {
 921                  return eval('(' + s + ')');
 922              } catch (ex) {
 923                  // Ignore
 924              }
 925          }
 926  
 927          };
 928  })();
 929  
 930  tinymce.create('static tinymce.util.XHR', {
 931      send : function(o) {
 932          var x, t, w = window, c = 0;
 933  
 934          // Default settings
 935          o.scope = o.scope || this;
 936          o.success_scope = o.success_scope || o.scope;
 937          o.error_scope = o.error_scope || o.scope;
 938          o.async = o.async === false ? false : true;
 939          o.data = o.data || '';
 940  
 941  		function get(s) {
 942              x = 0;
 943  
 944              try {
 945                  x = new ActiveXObject(s);
 946              } catch (ex) {
 947              }
 948  
 949              return x;
 950          };
 951  
 952          x = w.XMLHttpRequest ? new XMLHttpRequest() : get('Microsoft.XMLHTTP') || get('Msxml2.XMLHTTP');
 953  
 954          if (x) {
 955              if (x.overrideMimeType)
 956                  x.overrideMimeType(o.content_type);
 957  
 958              x.open(o.type || (o.data ? 'POST' : 'GET'), o.url, o.async);
 959  
 960              if (o.content_type)
 961                  x.setRequestHeader('Content-Type', o.content_type);
 962  
 963              x.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
 964  
 965              x.send(o.data);
 966  
 967  			function ready() {
 968                  if (!o.async || x.readyState == 4 || c++ > 10000) {
 969                      if (o.success && c < 10000 && x.status == 200)
 970                          o.success.call(o.success_scope, '' + x.responseText, x, o);
 971                      else if (o.error)
 972                          o.error.call(o.error_scope, c > 10000 ? 'TIMED_OUT' : 'GENERAL', x, o);
 973  
 974                      x = null;
 975                  } else
 976                      w.setTimeout(ready, 10);
 977              };
 978  
 979              // Syncronous request
 980              if (!o.async)
 981                  return ready();
 982  
 983              // Wait for response, onReadyStateChange can not be used since it leaks memory in IE
 984              t = w.setTimeout(ready, 10);
 985          }
 986      }
 987  });
 988  
 989  (function() {
 990      var extend = tinymce.extend, JSON = tinymce.util.JSON, XHR = tinymce.util.XHR;
 991  
 992      tinymce.create('tinymce.util.JSONRequest', {
 993          JSONRequest : function(s) {
 994              this.settings = extend({
 995              }, s);
 996              this.count = 0;
 997          },
 998  
 999          send : function(o) {
1000              var ecb = o.error, scb = o.success;
1001  
1002              o = extend(this.settings, o);
1003  
1004              o.success = function(c, x) {
1005                  c = JSON.parse(c);
1006  
1007                  if (typeof(c) == 'undefined') {
1008                      c = {
1009                          error : 'JSON Parse error.'
1010                      };
1011                  }
1012  
1013                  if (c.error)
1014                      ecb.call(o.error_scope || o.scope, c.error, x);
1015                  else
1016                      scb.call(o.success_scope || o.scope, c.result);
1017              };
1018  
1019              o.error = function(ty, x) {
1020                  if (ecb)
1021                      ecb.call(o.error_scope || o.scope, ty, x);
1022              };
1023  
1024              o.data = JSON.serialize({
1025                  id : o.id || 'c' + (this.count++),
1026                  method : o.method,
1027                  params : o.params
1028              });
1029  
1030              // JSON content type for Ruby on rails. Bug: #1883287
1031              o.content_type = 'application/json';
1032  
1033              XHR.send(o);
1034          },
1035  
1036          'static' : {
1037              sendRPC : function(o) {
1038                  return new tinymce.util.JSONRequest().send(o);
1039              }
1040          }
1041      });
1042  }());
1043  (function(tinymce){
1044      tinymce.VK = {
1045          DELETE: 46,
1046          BACKSPACE: 8,
1047          ENTER: 13,
1048          TAB: 9,
1049          SPACEBAR: 32,
1050          UP: 38,
1051          DOWN: 40,
1052          modifierPressed: function (e) {
1053              return e.shiftKey || e.ctrlKey || e.altKey;
1054          }
1055      }
1056  })(tinymce);
1057  
1058  (function(tinymce) {
1059      var VK = tinymce.VK, BACKSPACE = VK.BACKSPACE, DELETE = VK.DELETE;
1060  
1061  	function cleanupStylesWhenDeleting(ed) {
1062          var dom = ed.dom, selection = ed.selection;
1063  
1064          ed.onKeyDown.add(function(ed, e) {
1065              var rng, blockElm, node, clonedSpan, isDelete;
1066  
1067              isDelete = e.keyCode == DELETE;
1068              if ((isDelete || e.keyCode == BACKSPACE) && !VK.modifierPressed(e)) {
1069                  e.preventDefault();
1070                  rng = selection.getRng();
1071  
1072                  // Find root block
1073                  blockElm = dom.getParent(rng.startContainer, dom.isBlock);
1074  
1075                  // On delete clone the root span of the next block element
1076                  if (isDelete)
1077                      blockElm = dom.getNext(blockElm, dom.isBlock);
1078  
1079                  // Locate root span element and clone it since it would otherwise get merged by the "apple-style-span" on delete/backspace
1080                  if (blockElm) {
1081                      node = blockElm.firstChild;
1082  
1083                      // Ignore empty text nodes
1084                      while (node && node.nodeType == 3 && node.nodeValue.length == 0)
1085                          node = node.nextSibling;
1086  
1087                      if (node && node.nodeName === 'SPAN') {
1088                          clonedSpan = node.cloneNode(false);
1089                      }
1090                  }
1091  
1092                  // Do the backspace/delete actiopn
1093                  ed.getDoc().execCommand(isDelete ? 'ForwardDelete' : 'Delete', false, null);
1094  
1095                  // Find all odd apple-style-spans
1096                  blockElm = dom.getParent(rng.startContainer, dom.isBlock);
1097                  tinymce.each(dom.select('span.Apple-style-span,font.Apple-style-span', blockElm), function(span) {
1098                      var bm = selection.getBookmark();
1099  
1100                      if (clonedSpan) {
1101                          dom.replace(clonedSpan.cloneNode(false), span, true);
1102                      } else {
1103                          dom.remove(span, true);
1104                      }
1105  
1106                      // Restore the selection
1107                      selection.moveToBookmark(bm);
1108                  });
1109              }
1110          });
1111      };
1112  
1113  	function emptyEditorWhenDeleting(ed) {
1114          ed.onKeyUp.add(function(ed, e) {
1115              var keyCode = e.keyCode;
1116  
1117              if (keyCode == DELETE || keyCode == BACKSPACE) {
1118                  if (ed.dom.isEmpty(ed.getBody())) {
1119                      ed.setContent('', {format : 'raw'});
1120                      ed.nodeChanged();
1121                      return;
1122                  }
1123              }
1124          });
1125      };
1126  
1127  	function inputMethodFocus(ed) {
1128          ed.dom.bind(ed.getDoc(), 'focusin', function() {
1129              ed.selection.setRng(ed.selection.getRng());
1130          });
1131      };
1132  
1133  	function removeHrOnBackspace(ed) {
1134          ed.onKeyDown.add(function(ed, e) {
1135              if (e.keyCode === BACKSPACE) {
1136                  if (ed.selection.isCollapsed() && ed.selection.getRng(true).startOffset === 0) {
1137                      var node = ed.selection.getNode();
1138                      var previousSibling = node.previousSibling;
1139                      if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "hr") {
1140                          ed.dom.remove(previousSibling);
1141                          tinymce.dom.Event.cancel(e);
1142                      }
1143                  }
1144              }
1145          })
1146      }
1147  
1148  	function focusBody(ed) {
1149          // Fix for a focus bug in FF 3.x where the body element
1150          // wouldn't get proper focus if the user clicked on the HTML element
1151          if (!Range.prototype.getClientRects) { // Detect getClientRects got introduced in FF 4
1152              ed.onMouseDown.add(function(ed, e) {
1153                  if (e.target.nodeName === "HTML") {
1154                      var body = ed.getBody();
1155  
1156                      // Blur the body it's focused but not correctly focused
1157                      body.blur();
1158  
1159                      // Refocus the body after a little while
1160                      setTimeout(function() {
1161                          body.focus();
1162                      }, 0);
1163                  }
1164              });
1165          }
1166      };
1167  
1168  	function selectControlElements(ed) {
1169          ed.onClick.add(function(ed, e) {
1170              e = e.target;
1171  
1172              // Workaround for bug, http://bugs.webkit.org/show_bug.cgi?id=12250
1173              // WebKit can't even do simple things like selecting an image
1174              // Needs tobe the setBaseAndExtend or it will fail to select floated images
1175              if (/^(IMG|HR)$/.test(e.nodeName))
1176                  ed.selection.getSel().setBaseAndExtent(e, 0, e, 1);
1177  
1178              if (e.nodeName == 'A' && ed.dom.hasClass(e, 'mceItemAnchor'))
1179                  ed.selection.select(e);
1180  
1181              ed.nodeChanged();
1182          });
1183      };
1184  
1185  	function removeStylesOnPTagsInheritedFromHeadingTag(ed) {
1186          ed.onKeyDown.add(function(ed, event) {
1187  			function checkInHeadingTag(ed) {
1188                  var currentNode = ed.selection.getNode();
1189                  var headingTags = 'h1,h2,h3,h4,h5,h6';
1190                  return ed.dom.is(currentNode, headingTags) || ed.dom.getParent(currentNode, headingTags) !== null;
1191              }
1192  
1193              if (event.keyCode === VK.ENTER && !VK.modifierPressed(event) && checkInHeadingTag(ed)) {
1194                  setTimeout(function() {
1195                      var currentNode = ed.selection.getNode();
1196                      if (ed.dom.is(currentNode, 'p')) {
1197                          ed.dom.setAttrib(currentNode, 'style', null);
1198                          // While tiny's content is correct after this method call, the content shown is not representative of it and needs to be 'repainted'
1199                          ed.execCommand('mceCleanup');
1200                      }
1201                  }, 0);
1202              }
1203          });
1204      }
1205  	function selectionChangeNodeChanged(ed) {
1206          var lastRng, selectionTimer;
1207  
1208          ed.dom.bind(ed.getDoc(), 'selectionchange', function() {
1209              if (selectionTimer) {
1210                  clearTimeout(selectionTimer);
1211                  selectionTimer = 0;
1212              }
1213  
1214              selectionTimer = window.setTimeout(function() {
1215                  var rng = ed.selection.getRng();
1216  
1217                  // Compare the ranges to see if it was a real change or not
1218                  if (!lastRng || !tinymce.dom.RangeUtils.compareRanges(rng, lastRng)) {
1219                      ed.nodeChanged();
1220                      lastRng = rng;
1221                  }
1222              }, 50);
1223          });
1224      }
1225  
1226  	function ensureBodyHasRoleApplication(ed) {
1227          document.body.setAttribute("role", "application");
1228      }
1229      
1230      tinymce.create('tinymce.util.Quirks', {
1231          Quirks: function(ed) {
1232              // WebKit
1233              if (tinymce.isWebKit) {
1234                  cleanupStylesWhenDeleting(ed);
1235                  emptyEditorWhenDeleting(ed);
1236                  inputMethodFocus(ed);
1237                  selectControlElements(ed);
1238  
1239                  // iOS
1240                  if (tinymce.isIDevice) {
1241                      selectionChangeNodeChanged(ed);
1242                  }
1243              }
1244  
1245              // IE
1246              if (tinymce.isIE) {
1247                  removeHrOnBackspace(ed);
1248                  emptyEditorWhenDeleting(ed);
1249                  ensureBodyHasRoleApplication(ed);
1250                  removeStylesOnPTagsInheritedFromHeadingTag(ed)
1251              }
1252  
1253              // Gecko
1254              if (tinymce.isGecko) {
1255                  removeHrOnBackspace(ed);
1256                  focusBody(ed);
1257              }
1258          }
1259      });
1260  })(tinymce);
1261  
1262  (function(tinymce) {
1263      var namedEntities, baseEntities, reverseEntities,
1264          attrsCharsRegExp = /[&<>\"\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
1265          textCharsRegExp = /[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
1266          rawCharsRegExp = /[<>&\"\']/g,
1267          entityRegExp = /&(#x|#)?([\w]+);/g,
1268          asciiMap = {
1269                  128 : "\u20AC", 130 : "\u201A", 131 : "\u0192", 132 : "\u201E", 133 : "\u2026", 134 : "\u2020",
1270                  135 : "\u2021", 136 : "\u02C6", 137 : "\u2030", 138 : "\u0160", 139 : "\u2039", 140 : "\u0152",
1271                  142 : "\u017D", 145 : "\u2018", 146 : "\u2019", 147 : "\u201C", 148 : "\u201D", 149 : "\u2022",
1272                  150 : "\u2013", 151 : "\u2014", 152 : "\u02DC", 153 : "\u2122", 154 : "\u0161", 155 : "\u203A",
1273                  156 : "\u0153", 158 : "\u017E", 159 : "\u0178"
1274          };
1275  
1276      // Raw entities
1277      baseEntities = {
1278          '\"' : '&quot;', // Needs to be escaped since the YUI compressor would otherwise break the code
1279          "'" : '&#39;',
1280          '<' : '&lt;',
1281          '>' : '&gt;',
1282          '&' : '&amp;'
1283      };
1284  
1285      // Reverse lookup table for raw entities
1286      reverseEntities = {
1287          '&lt;' : '<',
1288          '&gt;' : '>',
1289          '&amp;' : '&',
1290          '&quot;' : '"',
1291          '&apos;' : "'"
1292      };
1293  
1294      // Decodes text by using the browser
1295  	function nativeDecode(text) {
1296          var elm;
1297  
1298          elm = document.createElement("div");
1299          elm.innerHTML = text;
1300  
1301          return elm.textContent || elm.innerText || text;
1302      };
1303  
1304      // Build a two way lookup table for the entities
1305  	function buildEntitiesLookup(items, radix) {
1306          var i, chr, entity, lookup = {};
1307  
1308          if (items) {
1309              items = items.split(',');
1310              radix = radix || 10;
1311  
1312              // Build entities lookup table
1313              for (i = 0; i < items.length; i += 2) {
1314                  chr = String.fromCharCode(parseInt(items[i], radix));
1315  
1316                  // Only add non base entities
1317                  if (!baseEntities[chr]) {
1318                      entity = '&' + items[i + 1] + ';';
1319                      lookup[chr] = entity;
1320                      lookup[entity] = chr;
1321                  }
1322              }
1323  
1324              return lookup;
1325          }
1326      };
1327  
1328      // Unpack entities lookup where the numbers are in radix 32 to reduce the size
1329      namedEntities = buildEntitiesLookup(
1330          '50,nbsp,51,iexcl,52,cent,53,pound,54,curren,55,yen,56,brvbar,57,sect,58,uml,59,copy,' +
1331          '5a,ordf,5b,laquo,5c,not,5d,shy,5e,reg,5f,macr,5g,deg,5h,plusmn,5i,sup2,5j,sup3,5k,acute,' +
1332          '5l,micro,5m,para,5n,middot,5o,cedil,5p,sup1,5q,ordm,5r,raquo,5s,frac14,5t,frac12,5u,frac34,' +
1333          '5v,iquest,60,Agrave,61,Aacute,62,Acirc,63,Atilde,64,Auml,65,Aring,66,AElig,67,Ccedil,' +
1334          '68,Egrave,69,Eacute,6a,Ecirc,6b,Euml,6c,Igrave,6d,Iacute,6e,Icirc,6f,Iuml,6g,ETH,6h,Ntilde,' +
1335          '6i,Ograve,6j,Oacute,6k,Ocirc,6l,Otilde,6m,Ouml,6n,times,6o,Oslash,6p,Ugrave,6q,Uacute,' +
1336          '6r,Ucirc,6s,Uuml,6t,Yacute,6u,THORN,6v,szlig,70,agrave,71,aacute,72,acirc,73,atilde,74,auml,' +
1337          '75,aring,76,aelig,77,ccedil,78,egrave,79,eacute,7a,ecirc,7b,euml,7c,igrave,7d,iacute,7e,icirc,' +
1338          '7f,iuml,7g,eth,7h,ntilde,7i,ograve,7j,oacute,7k,ocirc,7l,otilde,7m,ouml,7n,divide,7o,oslash,' +
1339          '7p,ugrave,7q,uacute,7r,ucirc,7s,uuml,7t,yacute,7u,thorn,7v,yuml,ci,fnof,sh,Alpha,si,Beta,' +
1340          'sj,Gamma,sk,Delta,sl,Epsilon,sm,Zeta,sn,Eta,so,Theta,sp,Iota,sq,Kappa,sr,Lambda,ss,Mu,' +
1341          'st,Nu,su,Xi,sv,Omicron,t0,Pi,t1,Rho,t3,Sigma,t4,Tau,t5,Upsilon,t6,Phi,t7,Chi,t8,Psi,' +
1342          't9,Omega,th,alpha,ti,beta,tj,gamma,tk,delta,tl,epsilon,tm,zeta,tn,eta,to,theta,tp,iota,' +
1343          'tq,kappa,tr,lambda,ts,mu,tt,nu,tu,xi,tv,omicron,u0,pi,u1,rho,u2,sigmaf,u3,sigma,u4,tau,' +
1344          'u5,upsilon,u6,phi,u7,chi,u8,psi,u9,omega,uh,thetasym,ui,upsih,um,piv,812,bull,816,hellip,' +
1345          '81i,prime,81j,Prime,81u,oline,824,frasl,88o,weierp,88h,image,88s,real,892,trade,89l,alefsym,' +
1346          '8cg,larr,8ch,uarr,8ci,rarr,8cj,darr,8ck,harr,8dl,crarr,8eg,lArr,8eh,uArr,8ei,rArr,8ej,dArr,' +
1347          '8ek,hArr,8g0,forall,8g2,part,8g3,exist,8g5,empty,8g7,nabla,8g8,isin,8g9,notin,8gb,ni,8gf,prod,' +
1348          '8gh,sum,8gi,minus,8gn,lowast,8gq,radic,8gt,prop,8gu,infin,8h0,ang,8h7,and,8h8,or,8h9,cap,8ha,cup,' +
1349          '8hb,int,8hk,there4,8hs,sim,8i5,cong,8i8,asymp,8j0,ne,8j1,equiv,8j4,le,8j5,ge,8k2,sub,8k3,sup,8k4,' +
1350          'nsub,8k6,sube,8k7,supe,8kl,oplus,8kn,otimes,8l5,perp,8m5,sdot,8o8,lceil,8o9,rceil,8oa,lfloor,8ob,' +
1351          'rfloor,8p9,lang,8pa,rang,9ea,loz,9j0,spades,9j3,clubs,9j5,hearts,9j6,diams,ai,OElig,aj,oelig,b0,' +
1352          'Scaron,b1,scaron,bo,Yuml,m6,circ,ms,tilde,802,ensp,803,emsp,809,thinsp,80c,zwnj,80d,zwj,80e,lrm,' +
1353          '80f,rlm,80j,ndash,80k,mdash,80o,lsquo,80p,rsquo,80q,sbquo,80s,ldquo,80t,rdquo,80u,bdquo,810,dagger,' +
1354          '811,Dagger,81g,permil,81p,lsaquo,81q,rsaquo,85c,euro'
1355      , 32);
1356  
1357      tinymce.html = tinymce.html || {};
1358  
1359      tinymce.html.Entities = {
1360          encodeRaw : function(text, attr) {
1361              return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
1362                  return baseEntities[chr] || chr;
1363              });
1364          },
1365  
1366          encodeAllRaw : function(text) {
1367              return ('' + text).replace(rawCharsRegExp, function(chr) {
1368                  return baseEntities[chr] || chr;
1369              });
1370          },
1371  
1372          encodeNumeric : function(text, attr) {
1373              return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
1374                  // Multi byte sequence convert it to a single entity
1375                  if (chr.length > 1)
1376                      return '&#' + (((chr.charCodeAt(0) - 0xD800) * 0x400) + (chr.charCodeAt(1) - 0xDC00) + 0x10000) + ';';
1377  
1378                  return baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';';
1379              });
1380          },
1381  
1382          encodeNamed : function(text, attr, entities) {
1383              entities = entities || namedEntities;
1384  
1385              return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
1386                  return baseEntities[chr] || entities[chr] || chr;
1387              });
1388          },
1389  
1390          getEncodeFunc : function(name, entities) {
1391              var Entities = tinymce.html.Entities;
1392  
1393              entities = buildEntitiesLookup(entities) || namedEntities;
1394  
1395  			function encodeNamedAndNumeric(text, attr) {
1396                  return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
1397                      return baseEntities[chr] || entities[chr] || '&#' + chr.charCodeAt(0) + ';' || chr;
1398                  });
1399              };
1400  
1401  			function encodeCustomNamed(text, attr) {
1402                  return Entities.encodeNamed(text, attr, entities);
1403              };
1404  
1405              // Replace + with , to be compatible with previous TinyMCE versions
1406              name = tinymce.makeMap(name.replace(/\+/g, ','));
1407  
1408              // Named and numeric encoder
1409              if (name.named && name.numeric)
1410                  return encodeNamedAndNumeric;
1411  
1412              // Named encoder
1413              if (name.named) {
1414                  // Custom names
1415                  if (entities)
1416                      return encodeCustomNamed;
1417  
1418                  return Entities.encodeNamed;
1419              }
1420  
1421              // Numeric
1422              if (name.numeric)
1423                  return Entities.encodeNumeric;
1424  
1425              // Raw encoder
1426              return Entities.encodeRaw;
1427          },
1428  
1429          decode : function(text) {
1430              return text.replace(entityRegExp, function(all, numeric, value) {
1431                  if (numeric) {
1432                      value = parseInt(value, numeric.length === 2 ? 16 : 10);
1433  
1434                      // Support upper UTF
1435                      if (value > 0xFFFF) {
1436                          value -= 0x10000;
1437  
1438                          return String.fromCharCode(0xD800 + (value >> 10), 0xDC00 + (value & 0x3FF));
1439                      } else
1440                          return asciiMap[value] || String.fromCharCode(value);
1441                  }
1442  
1443                  return reverseEntities[all] || namedEntities[all] || nativeDecode(all);
1444              });
1445          }
1446      };
1447  })(tinymce);
1448  
1449  tinymce.html.Styles = function(settings, schema) {
1450      var rgbRegExp = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi,
1451          urlOrStrRegExp = /(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi,
1452          styleRegExp = /\s*([^:]+):\s*([^;]+);?/g,
1453          trimRightRegExp = /\s+$/,
1454          urlColorRegExp = /rgb/,
1455          undef, i, encodingLookup = {}, encodingItems;
1456  
1457      settings = settings || {};
1458  
1459      encodingItems = '\\" \\\' \\; \\: ; : \uFEFF'.split(' ');
1460      for (i = 0; i < encodingItems.length; i++) {
1461          encodingLookup[encodingItems[i]] = '\uFEFF' + i;
1462          encodingLookup['\uFEFF' + i] = encodingItems[i];
1463      }
1464  
1465  	function toHex(match, r, g, b) {
1466  		function hex(val) {
1467              val = parseInt(val).toString(16);
1468  
1469              return val.length > 1 ? val : '0' + val; // 0 -> 00
1470          };
1471  
1472          return '#' + hex(r) + hex(g) + hex(b);
1473      };
1474  
1475      return {
1476          toHex : function(color) {
1477              return color.replace(rgbRegExp, toHex);
1478          },
1479  
1480          parse : function(css) {
1481              var styles = {}, matches, name, value, isEncoded, urlConverter = settings.url_converter, urlConverterScope = settings.url_converter_scope || this;
1482  
1483  			function compress(prefix, suffix) {
1484                  var top, right, bottom, left;
1485  
1486                  // Get values and check it it needs compressing
1487                  top = styles[prefix + '-top' + suffix];
1488                  if (!top)
1489                      return;
1490  
1491                  right = styles[prefix + '-right' + suffix];
1492                  if (top != right)
1493                      return;
1494  
1495                  bottom = styles[prefix + '-bottom' + suffix];
1496                  if (right != bottom)
1497                      return;
1498  
1499                  left = styles[prefix + '-left' + suffix];
1500                  if (bottom != left)
1501                      return;
1502  
1503                  // Compress
1504                  styles[prefix + suffix] = left;
1505                  delete styles[prefix + '-top' + suffix];
1506                  delete styles[prefix + '-right' + suffix];
1507                  delete styles[prefix + '-bottom' + suffix];
1508                  delete styles[prefix + '-left' + suffix];
1509              };
1510  
1511  			function canCompress(key) {
1512                  var value = styles[key], i;
1513  
1514                  if (!value || value.indexOf(' ') < 0)
1515                      return;
1516  
1517                  value = value.split(' ');
1518                  i = value.length;
1519                  while (i--) {
1520                      if (value[i] !== value[0])
1521                          return false;
1522                  }
1523  
1524                  styles[key] = value[0];
1525  
1526                  return true;
1527              };
1528  
1529  			function compress2(target, a, b, c) {
1530                  if (!canCompress(a))
1531                      return;
1532  
1533                  if (!canCompress(b))
1534                      return;
1535  
1536                  if (!canCompress(c))
1537                      return;
1538  
1539                  // Compress
1540                  styles[target] = styles[a] + ' ' + styles[b] + ' ' + styles[c];
1541                  delete styles[a];
1542                  delete styles[b];
1543                  delete styles[c];
1544              };
1545  
1546              // Encodes the specified string by replacing all \" \' ; : with _<num>
1547  			function encode(str) {
1548                  isEncoded = true;
1549  
1550                  return encodingLookup[str];
1551              };
1552  
1553              // Decodes the specified string by replacing all _<num> with it's original value \" \' etc
1554              // It will also decode the \" \' if keep_slashes is set to fale or omitted
1555  			function decode(str, keep_slashes) {
1556                  if (isEncoded) {
1557                      str = str.replace(/\uFEFF[0-9]/g, function(str) {
1558                          return encodingLookup[str];
1559                      });
1560                  }
1561  
1562                  if (!keep_slashes)
1563                      str = str.replace(/\\([\'\";:])/g, "$1");
1564  
1565                  return str;
1566              }
1567  
1568              if (css) {
1569                  // Encode \" \' % and ; and : inside strings so they don't interfere with the style parsing
1570                  css = css.replace(/\\[\"\';:\uFEFF]/g, encode).replace(/\"[^\"]+\"|\'[^\']+\'/g, function(str) {
1571                      return str.replace(/[;:]/g, encode);
1572                  });
1573  
1574                  // Parse styles
1575                  while (matches = styleRegExp.exec(css)) {
1576                      name = matches[1].replace(trimRightRegExp, '').toLowerCase();
1577                      value = matches[2].replace(trimRightRegExp, '');
1578  
1579                      if (name && value.length > 0) {
1580                          // Opera will produce 700 instead of bold in their style values
1581                          if (name === 'font-weight' && value === '700')
1582                              value = 'bold';
1583                          else if (name === 'color' || name === 'background-color') // Lowercase colors like RED
1584                              value = value.toLowerCase();        
1585  
1586                          // Convert RGB colors to HEX
1587                          value = value.replace(rgbRegExp, toHex);
1588  
1589                          // Convert URLs and force them into url('value') format
1590                          value = value.replace(urlOrStrRegExp, function(match, url, url2, url3, str, str2) {
1591                              str = str || str2;
1592  
1593                              if (str) {
1594                                  str = decode(str);
1595  
1596                                  // Force strings into single quote format
1597                                  return "'" + str.replace(/\'/g, "\\'") + "'";
1598                              }
1599  
1600                              url = decode(url || url2 || url3);
1601  
1602                              // Convert the URL to relative/absolute depending on config
1603                              if (urlConverter)
1604                                  url = urlConverter.call(urlConverterScope, url, 'style');
1605  
1606                              // Output new URL format
1607                              return "url('" + url.replace(/\'/g, "\\'") + "')";
1608                          });
1609  
1610                          styles[name] = isEncoded ? decode(value, true) : value;
1611                      }
1612  
1613                      styleRegExp.lastIndex = matches.index + matches[0].length;
1614                  }
1615  
1616                  // Compress the styles to reduce it's size for example IE will expand styles
1617                  compress("border", "");
1618                  compress("border", "-width");
1619                  compress("border", "-color");
1620                  compress("border", "-style");
1621                  compress("padding", "");
1622                  compress("margin", "");
1623                  compress2('border', 'border-width', 'border-style', 'border-color');
1624  
1625                  // Remove pointless border, IE produces these
1626                  if (styles.border === 'medium none')
1627                      delete styles.border;
1628              }
1629  
1630              return styles;
1631          },
1632  
1633          serialize : function(styles, element_name) {
1634              var css = '', name, value;
1635  
1636  			function serializeStyles(name) {
1637                  var styleList, i, l, value;
1638  
1639                  styleList = schema.styles[name];
1640                  if (styleList) {
1641                      for (i = 0, l = styleList.length; i < l; i++) {
1642                          name = styleList[i];
1643                          value = styles[name];
1644  
1645                          if (value !== undef && value.length > 0)
1646                              css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
1647                      }
1648                  }
1649              };
1650  
1651              // Serialize styles according to schema
1652              if (element_name && schema && schema.styles) {
1653                  // Serialize global styles and element specific styles
1654                  serializeStyles('*');
1655                  serializeStyles(element_name);
1656              } else {
1657                  // Output the styles in the order they are inside the object
1658                  for (name in styles) {
1659                      value = styles[name];
1660  
1661                      if (value !== undef && value.length > 0)
1662                          css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
1663                  }
1664              }
1665  
1666              return css;
1667          }
1668      };
1669  };
1670  
1671  (function(tinymce) {
1672      var transitional = {}, boolAttrMap, blockElementsMap, shortEndedElementsMap, nonEmptyElementsMap, customElementsMap = {},
1673          defaultWhiteSpaceElementsMap, selfClosingElementsMap, makeMap = tinymce.makeMap, each = tinymce.each;
1674  
1675  	function split(str, delim) {
1676          return str.split(delim || ',');
1677      };
1678  
1679  	function unpack(lookup, data) {
1680          var key, elements = {};
1681  
1682  		function replace(value) {
1683              return value.replace(/[A-Z]+/g, function(key) {
1684                  return replace(lookup[key]);
1685              });
1686          };
1687  
1688          // Unpack lookup
1689          for (key in lookup) {
1690              if (lookup.hasOwnProperty(key))
1691                  lookup[key] = replace(lookup[key]);
1692          }
1693  
1694          // Unpack and parse data into object map
1695          replace(data).replace(/#/g, '#text').replace(/(\w+)\[([^\]]+)\]\[([^\]]*)\]/g, function(str, name, attributes, children) {
1696              attributes = split(attributes, '|');
1697  
1698              elements[name] = {
1699                  attributes : makeMap(attributes),
1700                  attributesOrder : attributes,
1701                  children : makeMap(children, '|', {'#comment' : {}})
1702              }
1703          });
1704  
1705          return elements;
1706      };
1707  
1708      // Build a lookup table for block elements both lowercase and uppercase
1709      blockElementsMap = 'h1,h2,h3,h4,h5,h6,hr,p,div,address,pre,form,table,tbody,thead,tfoot,' + 
1710                          'th,tr,td,li,ol,ul,caption,blockquote,center,dl,dt,dd,dir,fieldset,' + 
1711                          'noscript,menu,isindex,samp,header,footer,article,section,hgroup';
1712      blockElementsMap = makeMap(blockElementsMap, ',', makeMap(blockElementsMap.toUpperCase()));
1713  
1714      // This is the XHTML 1.0 transitional elements with it's attributes and children packed to reduce it's size
1715      transitional = unpack({
1716          Z : 'H|K|N|O|P',
1717          Y : 'X|form|R|Q',
1718          ZG : 'E|span|width|align|char|charoff|valign',
1719          X : 'p|T|div|U|W|isindex|fieldset|table',
1720          ZF : 'E|align|char|charoff|valign',
1721          W : 'pre|hr|blockquote|address|center|noframes',
1722          ZE : 'abbr|axis|headers|scope|rowspan|colspan|align|char|charoff|valign|nowrap|bgcolor|width|height',
1723          ZD : '[E][S]',
1724          U : 'ul|ol|dl|menu|dir',
1725          ZC : 'p|Y|div|U|W|table|br|span|bdo|object|applet|img|map|K|N|Q',
1726          T : 'h1|h2|h3|h4|h5|h6',
1727          ZB : 'X|S|Q',
1728          S : 'R|P',
1729          ZA : 'a|G|J|M|O|P',
1730          R : 'a|H|K|N|O',
1731          Q : 'noscript|P',
1732          P : 'ins|del|script',
1733          O : 'input|select|textarea|label|button',
1734          N : 'M|L',
1735          M : 'em|strong|dfn|code|q|samp|kbd|var|cite|abbr|acronym',
1736          L : 'sub|sup',
1737          K : 'J|I',
1738          J : 'tt|i|b|u|s|strike',
1739          I : 'big|small|font|basefont',
1740          H : 'G|F',
1741          G : 'br|span|bdo',
1742          F : 'object|applet|img|map|iframe',
1743          E : 'A|B|C',
1744          D : 'accesskey|tabindex|onfocus|onblur',
1745          C : 'onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup',
1746          B : 'lang|xml:lang|dir',
1747          A : 'id|class|style|title'
1748      }, 'script[id|charset|type|language|src|defer|xml:space][]' + 
1749          'style[B|id|type|media|title|xml:space][]' + 
1750          'object[E|declare|classid|codebase|data|type|codetype|archive|standby|width|height|usemap|name|tabindex|align|border|hspace|vspace][#|param|Y]' + 
1751          'param[id|name|value|valuetype|type][]' + 
1752          'p[E|align][#|S]' + 
1753          'a[E|D|charset|type|name|href|hreflang|rel|rev|shape|coords|target][#|Z]' + 
1754          'br[A|clear][]' + 
1755          'span[E][#|S]' + 
1756          'bdo[A|C|B][#|S]' + 
1757          'applet[A|codebase|archive|code|object|alt|name|width|height|align|hspace|vspace][#|param|Y]' + 
1758          'h1[E|align][#|S]' + 
1759          'img[E|src|alt|name|longdesc|width|height|usemap|ismap|align|border|hspace|vspace][]' + 
1760          'map[B|C|A|name][X|form|Q|area]' + 
1761          'h2[E|align][#|S]' + 
1762          'iframe[A|longdesc|name|src|frameborder|marginwidth|marginheight|scrolling|align|width|height][#|Y]' + 
1763          'h3[E|align][#|S]' + 
1764          'tt[E][#|S]' + 
1765          'i[E][#|S]' + 
1766          'b[E][#|S]' + 
1767          'u[E][#|S]' + 
1768          's[E][#|S]' + 
1769          'strike[E][#|S]' + 
1770          'big[E][#|S]' + 
1771          'small[E][#|S]' + 
1772          'font[A|B|size|color|face][#|S]' + 
1773          'basefont[id|size|color|face][]' + 
1774          'em[E][#|S]' + 
1775          'strong[E][#|S]' + 
1776          'dfn[E][#|S]' + 
1777          'code[E][#|S]' + 
1778          'q[E|cite][#|S]' + 
1779          'samp[E][#|S]' + 
1780          'kbd[E][#|S]' + 
1781          'var[E][#|S]' + 
1782          'cite[E][#|S]' + 
1783          'abbr[E][#|S]' + 
1784          'acronym[E][#|S]' + 
1785          'sub[E][#|S]' + 
1786          'sup[E][#|S]' + 
1787          'input[E|D|type|name|value|checked|disabled|readonly|size|maxlength|src|alt|usemap|onselect|onchange|accept|align][]' + 
1788          'select[E|name|size|multiple|disabled|tabindex|onfocus|onblur|onchange][optgroup|option]' + 
1789          'optgroup[E|disabled|label][option]' + 
1790          'option[E|selected|disabled|label|value][]' + 
1791          'textarea[E|D|name|rows|cols|disabled|readonly|onselect|onchange][]' + 
1792          'label[E|for|accesskey|onfocus|onblur][#|S]' + 
1793          'button[E|D|name|value|type|disabled][#|p|T|div|U|W|table|G|object|applet|img|map|K|N|Q]' + 
1794          'h4[E|align][#|S]' + 
1795          'ins[E|cite|datetime][#|Y]' + 
1796          'h5[E|align][#|S]' + 
1797          'del[E|cite|datetime][#|Y]' + 
1798          'h6[E|align][#|S]' + 
1799          'div[E|align][#|Y]' + 
1800          'ul[E|type|compact][li]' + 
1801          'li[E|type|value][#|Y]' + 
1802          'ol[E|type|compact|start][li]' + 
1803          'dl[E|compact][dt|dd]' + 
1804          'dt[E][#|S]' + 
1805          'dd[E][#|Y]' + 
1806          'menu[E|compact][li]' + 
1807          'dir[E|compact][li]' + 
1808          'pre[E|width|xml:space][#|ZA]' + 
1809          'hr[E|align|noshade|size|width][]' + 
1810          'blockquote[E|cite][#|Y]' + 
1811          'address[E][#|S|p]' + 
1812          'center[E][#|Y]' + 
1813          'noframes[E][#|Y]' + 
1814          'isindex[A|B|prompt][]' + 
1815          'fieldset[E][#|legend|Y]' + 
1816          'legend[E|accesskey|align][#|S]' + 
1817          'table[E|summary|width|border|frame|rules|cellspacing|cellpadding|align|bgcolor][caption|col|colgroup|thead|tfoot|tbody|tr]' + 
1818          'caption[E|align][#|S]' + 
1819          'col[ZG][]' + 
1820          'colgroup[ZG][col]' + 
1821          'thead[ZF][tr]' + 
1822          'tr[ZF|bgcolor][th|td]' + 
1823          'th[E|ZE][#|Y]' + 
1824          'form[E|action|method|name|enctype|onsubmit|onreset|accept|accept-charset|target][#|X|R|Q]' + 
1825          'noscript[E][#|Y]' + 
1826          'td[E|ZE][#|Y]' + 
1827          'tfoot[ZF][tr]' + 
1828          'tbody[ZF][tr]' + 
1829          'area[E|D|shape|coords|href|nohref|alt|target][]' + 
1830          'base[id|href|target][]' + 
1831          'body[E|onload|onunload|background|bgcolor|text|link|vlink|alink][#|Y]'
1832      );
1833  
1834      boolAttrMap = makeMap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected,autoplay,loop,controls');
1835      shortEndedElementsMap = makeMap('area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed,source');
1836      nonEmptyElementsMap = tinymce.extend(makeMap('td,th,iframe,video,audio,object'), shortEndedElementsMap);
1837      defaultWhiteSpaceElementsMap = makeMap('pre,script,style,textarea');
1838      selfClosingElementsMap = makeMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr');
1839  
1840      tinymce.html.Schema = function(settings) {
1841          var self = this, elements = {}, children = {}, patternElements = [], validStyles, whiteSpaceElementsMap;
1842  
1843          settings = settings || {};
1844  
1845          // Allow all elements and attributes if verify_html is set to false
1846          if (settings.verify_html === false)
1847              settings.valid_elements = '*[*]';
1848  
1849          // Build styles list
1850          if (settings.valid_styles) {
1851              validStyles = {};
1852  
1853              // Convert styles into a rule list
1854              each(settings.valid_styles, function(value, key) {
1855                  validStyles[key] = tinymce.explode(value);
1856              });
1857          }
1858  
1859          whiteSpaceElementsMap = settings.whitespace_elements ? makeMap(settings.whitespace_elements) : defaultWhiteSpaceElementsMap;
1860  
1861          // Converts a wildcard expression string to a regexp for example *a will become /.*a/.
1862  		function patternToRegExp(str) {
1863              return new RegExp('^' + str.replace(/([?+*])/g, '.$1') + '$');
1864          };
1865  
1866          // Parses the specified valid_elements string and adds to the current rules
1867          // This function is a bit hard to read since it's heavily optimized for speed
1868  		function addValidElements(valid_elements) {
1869              var ei, el, ai, al, yl, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder,
1870                  prefix, outputName, globalAttributes, globalAttributesOrder, transElement, key, childKey, value,
1871                  elementRuleRegExp = /^([#+-])?([^\[\/]+)(?:\/([^\[]+))?(?:\[([^\]]+)\])?$/,
1872                  attrRuleRegExp = /^([!\-])?(\w+::\w+|[^=:<]+)?(?:([=:<])(.*))?$/,
1873                  hasPatternsRegExp = /[*?+]/;
1874  
1875              if (valid_elements) {
1876                  // Split valid elements into an array with rules
1877                  valid_elements = split(valid_elements);
1878  
1879                  if (elements['@']) {
1880                      globalAttributes = elements['@'].attributes;
1881                      globalAttributesOrder = elements['@'].attributesOrder;
1882                  }
1883  
1884                  // Loop all rules
1885                  for (ei = 0, el = valid_elements.length; ei < el; ei++) {
1886                      // Parse element rule
1887                      matches = elementRuleRegExp.exec(valid_elements[ei]);
1888                      if (matches) {
1889                          // Setup local names for matches
1890                          prefix = matches[1];
1891                          elementName = matches[2];
1892                          outputName = matches[3];
1893                          attrData = matches[4];
1894  
1895                          // Create new attributes and attributesOrder
1896                          attributes = {};
1897                          attributesOrder = [];
1898  
1899                          // Create the new element
1900                          element = {
1901                              attributes : attributes,
1902                              attributesOrder : attributesOrder
1903                          };
1904  
1905                          // Padd empty elements prefix
1906                          if (prefix === '#')
1907                              element.paddEmpty = true;
1908  
1909                          // Remove empty elements prefix
1910                          if (prefix === '-')
1911                              element.removeEmpty = true;
1912  
1913                          // Copy attributes from global rule into current rule
1914                          if (globalAttributes) {
1915                              for (key in globalAttributes)
1916                                  attributes[key] = globalAttributes[key];
1917  
1918                              attributesOrder.push.apply(attributesOrder, globalAttributesOrder);
1919                          }
1920  
1921                          // Attributes defined
1922                          if (attrData) {
1923                              attrData = split(attrData, '|');
1924                              for (ai = 0, al = attrData.length; ai < al; ai++) {
1925                                  matches = attrRuleRegExp.exec(attrData[ai]);
1926                                  if (matches) {
1927                                      attr = {};
1928                                      attrType = matches[1];
1929                                      attrName = matches[2].replace(/::/g, ':');
1930                                      prefix = matches[3];
1931                                      value = matches[4];
1932  
1933                                      // Required
1934                                      if (attrType === '!') {
1935                                          element.attributesRequired = element.attributesRequired || [];
1936                                          element.attributesRequired.push(attrName);
1937                                          attr.required = true;
1938                                      }
1939  
1940                                      // Denied from global
1941                                      if (attrType === '-') {
1942                                          delete attributes[attrName];
1943                                          attributesOrder.splice(tinymce.inArray(attributesOrder, attrName), 1);
1944                                          continue;
1945                                      }
1946  
1947                                      // Default value
1948                                      if (prefix) {
1949                                          // Default value
1950                                          if (prefix === '=') {
1951                                              element.attributesDefault = element.attributesDefault || [];
1952                                              element.attributesDefault.push({name: attrName, value: value});
1953                                              attr.defaultValue = value;
1954                                          }
1955  
1956                                          // Forced value
1957                                          if (prefix === ':') {
1958                                              element.attributesForced = element.attributesForced || [];
1959                                              element.attributesForced.push({name: attrName, value: value});
1960                                              attr.forcedValue = value;
1961                                          }
1962  
1963                                          // Required values
1964                                          if (prefix === '<')
1965                                              attr.validValues = makeMap(value, '?');
1966                                      }
1967  
1968                                      // Check for attribute patterns
1969                                      if (hasPatternsRegExp.test(attrName)) {
1970                                          element.attributePatterns = element.attributePatterns || [];
1971                                          attr.pattern = patternToRegExp(attrName);
1972                                          element.attributePatterns.push(attr);
1973                                      } else {
1974                                          // Add attribute to order list if it doesn't already exist
1975                                          if (!attributes[attrName])
1976                                              attributesOrder.push(attrName);
1977  
1978                                          attributes[attrName] = attr;
1979                                      }
1980                                  }
1981                              }
1982                          }
1983  
1984                          // Global rule, store away these for later usage
1985                          if (!globalAttributes && elementName == '@') {
1986                              globalAttributes = attributes;
1987                              globalAttributesOrder = attributesOrder;
1988                          }
1989  
1990                          // Handle substitute elements such as b/strong
1991                          if (outputName) {
1992                              element.outputName = elementName;
1993                              elements[outputName] = element;
1994                          }
1995  
1996                          // Add pattern or exact element
1997                          if (hasPatternsRegExp.test(elementName)) {
1998                              element.pattern = patternToRegExp(elementName);
1999                              patternElements.push(element);
2000                          } else
2001                              elements[elementName] = element;
2002                      }
2003                  }
2004              }
2005          };
2006  
2007  		function setValidElements(valid_elements) {
2008              elements = {};
2009              patternElements = [];
2010  
2011              addValidElements(valid_elements);
2012  
2013              each(transitional, function(element, name) {
2014                  children[name] = element.children;
2015              });
2016          };
2017  
2018          // Adds custom non HTML elements to the schema
2019  		function addCustomElements(custom_elements) {
2020              var customElementRegExp = /^(~)?(.+)$/;
2021  
2022              if (custom_elements) {
2023                  each(split(custom_elements), function(rule) {
2024                      var matches = customElementRegExp.exec(rule),
2025                          inline = matches[1] === '~',
2026                          cloneName = inline ? 'span' : 'div',
2027                          name = matches[2];
2028  
2029                      children[name] = children[cloneName];
2030                      customElementsMap[name] = cloneName;
2031  
2032                      // If it's not marked as inline then add it to valid block elements
2033                      if (!inline)
2034                          blockElementsMap[name] = {};
2035  
2036                      // Add custom elements at span/div positions
2037                      each(children, function(element, child) {
2038                          if (element[cloneName])
2039                              element[name] = element[cloneName];
2040                      });
2041                  });
2042              }
2043          };
2044  
2045          // Adds valid children to the schema object
2046  		function addValidChildren(valid_children) {
2047              var childRuleRegExp = /^([+\-]?)(\w+)\[([^\]]+)\]$/;
2048  
2049              if (valid_children) {
2050                  each(split(valid_children), function(rule) {
2051                      var matches = childRuleRegExp.exec(rule), parent, prefix;
2052  
2053                      if (matches) {
2054                          prefix = matches[1];
2055  
2056                          // Add/remove items from default
2057                          if (prefix)
2058                              parent = children[matches[2]];
2059                          else
2060                              parent = children[matches[2]] = {'#comment' : {}};
2061  
2062                          parent = children[matches[2]];
2063  
2064                          each(split(matches[3], '|'), function(child) {
2065                              if (prefix === '-')
2066                                  delete parent[child];
2067                              else
2068                                  parent[child] = {};
2069                          });
2070                      }
2071                  });
2072              }
2073          };
2074  
2075  		function getElementRule(name) {
2076              var element = elements[name], i;
2077  
2078              // Exact match found
2079              if (element)
2080                  return element;
2081  
2082              // No exact match then try the patterns
2083              i = patternElements.length;
2084              while (i--) {
2085                  element = patternElements[i];
2086  
2087                  if (element.pattern.test(name))
2088                      return element;
2089              }
2090          };
2091  
2092          if (!settings.valid_elements) {
2093              // No valid elements defined then clone the elements from the transitional spec
2094              each(transitional, function(element, name) {
2095                  elements[name] = {
2096                      attributes : element.attributes,
2097                      attributesOrder : element.attributesOrder
2098                  };
2099  
2100                  children[name] = element.children;
2101              });
2102  
2103              // Switch these
2104              each(split('strong/b,em/i'), function(item) {
2105                  item = split(item, '/');
2106                  elements[item[1]].outputName = item[0];
2107              });
2108  
2109              // Add default alt attribute for images
2110              elements.img.attributesDefault = [{name: 'alt', value: ''}];
2111  
2112              // Remove these if they are empty by default
2113              each(split('ol,ul,sub,sup,blockquote,span,font,a,table,tbody,tr'), function(name) {
2114                  elements[name].removeEmpty = true;
2115              });
2116  
2117              // Padd these by default
2118              each(split('p,h1,h2,h3,h4,h5,h6,th,td,pre,div,address,caption'), function(name) {
2119                  elements[name].paddEmpty = true;
2120              });
2121          } else
2122              setValidElements(settings.valid_elements);
2123  
2124          addCustomElements(settings.custom_elements);
2125          addValidChildren(settings.valid_children);
2126          addValidElements(settings.extended_valid_elements);
2127  
2128          // Todo: Remove this when we fix list handling to be valid
2129          addValidChildren('+ol[ul|ol],+ul[ul|ol]');
2130  
2131          // If the user didn't allow span only allow internal spans
2132          if (!getElementRule('span'))
2133              addValidElements('span[!data-mce-type|*]');
2134  
2135          // Delete invalid elements
2136          if (settings.invalid_elements) {
2137              tinymce.each(tinymce.explode(settings.invalid_elements), function(item) {
2138                  if (elements[item])
2139                      delete elements[item];
2140              });
2141          }
2142  
2143          self.children = children;
2144  
2145          self.styles = validStyles;
2146  
2147          self.getBoolAttrs = function() {
2148              return boolAttrMap;
2149          };
2150  
2151          self.getBlockElements = function() {
2152              return blockElementsMap;
2153          };
2154  
2155          self.getShortEndedElements = function() {
2156              return shortEndedElementsMap;
2157          };
2158  
2159          self.getSelfClosingElements = function() {
2160              return selfClosingElementsMap;
2161          };
2162  
2163          self.getNonEmptyElements = function() {
2164              return nonEmptyElementsMap;
2165          };
2166  
2167          self.getWhiteSpaceElements = function() {
2168              return whiteSpaceElementsMap;
2169          };
2170  
2171          self.isValidChild = function(name, child) {
2172              var parent = children[name];
2173  
2174              return !!(parent && parent[child]);
2175          };
2176  
2177          self.getElementRule = getElementRule;
2178  
2179          self.getCustomElements = function() {
2180              return customElementsMap;
2181          };
2182  
2183          self.addValidElements = addValidElements;
2184  
2185          self.setValidElements = setValidElements;
2186  
2187          self.addCustomElements = addCustomElements;
2188  
2189          self.addValidChildren = addValidChildren;
2190      };
2191  
2192      // Expose boolMap and blockElementMap as static properties for usage in DOMUtils
2193      tinymce.html.Schema.boolAttrMap = boolAttrMap;
2194      tinymce.html.Schema.blockElementsMap = blockElementsMap;
2195  })(tinymce);
2196  
2197  (function(tinymce) {
2198      tinymce.html.SaxParser = function(settings, schema) {
2199          var self = this, noop = function() {};
2200  
2201          settings = settings || {};
2202          self.schema = schema = schema || new tinymce.html.Schema();
2203  
2204          if (settings.fix_self_closing !== false)
2205              settings.fix_self_closing = true;
2206  
2207          // Add handler functions from settings and setup default handlers
2208          tinymce.each('comment cdata text start end pi doctype'.split(' '), function(name) {
2209              if (name)
2210                  self[name] = settings[name] || noop;
2211          });
2212  
2213          self.parse = function(html) {
2214              var self = this, matches, index = 0, value, endRegExp, stack = [], attrList, i, text, name, isInternalElement, removeInternalElements,
2215                  shortEndedElements, fillAttrsMap, isShortEnded, validate, elementRule, isValidElement, attr, attribsValue, invalidPrefixRegExp,
2216                  validAttributesMap, validAttributePatterns, attributesRequired, attributesDefault, attributesForced, selfClosing,
2217                  tokenRegExp, attrRegExp, specialElements, attrValue, idCount = 0, decode = tinymce.html.Entities.decode, fixSelfClosing, isIE;
2218  
2219  			function processEndTag(name) {
2220                  var pos, i;
2221  
2222                  // Find position of parent of the same type
2223                  pos = stack.length;
2224                  while (pos--) {
2225                      if (stack[pos].name === name)
2226                          break;                        
2227                  }
2228  
2229                  // Found parent
2230                  if (pos >= 0) {
2231                      // Close all the open elements
2232                      for (i = stack.length - 1; i >= pos; i--) {
2233                          name = stack[i];
2234  
2235                          if (name.valid)
2236                              self.end(name.name);
2237                      }
2238  
2239                      // Remove the open elements from the stack
2240                      stack.length = pos;
2241                  }
2242              };
2243  
2244              // Precompile RegExps and map objects
2245              tokenRegExp = new RegExp('<(?:' +
2246                  '(?:!--([\\w\\W]*?)-->)|' + // Comment
2247                  '(?:!\\[CDATA\\[([\\w\\W]*?)\\]\\]>)|' + // CDATA
2248                  '(?:!DOCTYPE([\\w\\W]*?)>)|' + // DOCTYPE
2249                  '(?:\\?([^\\s\\/<>]+) ?([\\w\\W]*?)[?/]>)|' + // PI
2250                  '(?:\\/([^>]+)>)|' + // End element
2251                  '(?:([^\\s\\/<>]+)((?:\\s+[^"\'>]+(?:(?:"[^"]*")|(?:\'[^\']*\')|[^>]*))*|\\/)>)' + // Start element
2252              ')', 'g');
2253  
2254              attrRegExp = /([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:\\.|[^\"])*)\")|(?:\'((?:\\.|[^\'])*)\')|([^>\s]+)))?/g;
2255              specialElements = {
2256                  'script' : /<\/script[^>]*>/gi,
2257                  'style' : /<\/style[^>]*>/gi,
2258                  'noscript' : /<\/noscript[^>]*>/gi
2259              };
2260  
2261              // Setup lookup tables for empty elements and boolean attributes
2262              shortEndedElements = schema.getShortEndedElements();
2263              selfClosing = schema.getSelfClosingElements();
2264              fillAttrsMap = schema.getBoolAttrs();
2265              validate = settings.validate;
2266              removeInternalElements = settings.remove_internals;
2267              fixSelfClosing = settings.fix_self_closing;
2268              isIE = tinymce.isIE;
2269              invalidPrefixRegExp = /^:/;
2270  
2271              while (matches = tokenRegExp.exec(html)) {
2272                  // Text
2273                  if (index < matches.index)
2274                      self.text(decode(html.substr(index, matches.index - index)));
2275  
2276                  if (value = matches[6]) { // End element
2277                      value = value.toLowerCase();
2278  
2279                      // IE will add a ":" in front of elements it doesn't understand like custom elements or HTML5 elements
2280                      if (isIE && invalidPrefixRegExp.test(value))
2281                          value = value.substr(1);
2282  
2283                      processEndTag(value);
2284                  } else if (value = matches[7]) { // Start element
2285                      value = value.toLowerCase();
2286  
2287                      // IE will add a ":" in front of elements it doesn't understand like custom elements or HTML5 elements
2288                      if (isIE && invalidPrefixRegExp.test(value))
2289                          value = value.substr(1);
2290  
2291                      isShortEnded = value in shortEndedElements;
2292  
2293                      // Is self closing tag for example an <li> after an open <li>
2294                      if (fixSelfClosing && selfClosing[value] && stack.length > 0 && stack[stack.length - 1].name === value)
2295                          processEndTag(value);
2296  
2297                      // Validate element
2298                      if (!validate || (elementRule = schema.getElementRule(value))) {
2299                          isValidElement = true;
2300  
2301                          // Grab attributes map and patters when validation is enabled
2302                          if (validate) {
2303                              validAttributesMap = elementRule.attributes;
2304                              validAttributePatterns = elementRule.attributePatterns;
2305                          }
2306  
2307                          // Parse attributes
2308                          if (attribsValue = matches[8]) {
2309                              isInternalElement = attribsValue.indexOf('data-mce-type') !== -1; // Check if the element is an internal element
2310  
2311                              // If the element has internal attributes then remove it if we are told to do so
2312                              if (isInternalElement && removeInternalElements)
2313                                  isValidElement = false;
2314  
2315                              attrList = [];
2316                              attrList.map = {};
2317  
2318                              attribsValue.replace(attrRegExp, function(match, name, value, val2, val3) {
2319                                  var attrRule, i;
2320  
2321                                  name = name.toLowerCase();
2322                                  value = name in fillAttrsMap ? name : decode(value || val2 || val3 || ''); // Handle boolean attribute than value attribute
2323  
2324                                  // Validate name and value
2325                                  if (validate && !isInternalElement && name.indexOf('data-') !== 0) {
2326                                      attrRule = validAttributesMap[name];
2327  
2328                                      // Find rule by pattern matching
2329                                      if (!attrRule && validAttributePatterns) {
2330                                          i = validAttributePatterns.length;
2331                                          while (i--) {
2332                                              attrRule = validAttributePatterns[i];
2333                                              if (attrRule.pattern.test(name))
2334                                                  break;
2335                                          }
2336  
2337                                          // No rule matched
2338                                          if (i === -1)
2339                                              attrRule = null;
2340                                      }
2341  
2342                                      // No attribute rule found
2343                                      if (!attrRule)
2344                                          return;
2345  
2346                                      // Validate value
2347                                      if (attrRule.validValues && !(value in attrRule.validValues))
2348                                          return;
2349                                  }
2350  
2351                                  // Add attribute to list and map
2352                                  attrList.map[name] = value;
2353                                  attrList.push({
2354                                      name: name,
2355                                      value: value
2356                                  });
2357                              });
2358                          } else {
2359                              attrList = [];
2360                              attrList.map = {};
2361                          }
2362  
2363                          // Process attributes if validation is enabled
2364                          if (validate && !isInternalElement) {
2365                              attributesRequired = elementRule.attributesRequired;
2366                              attributesDefault = elementRule.attributesDefault;
2367                              attributesForced = elementRule.attributesForced;
2368  
2369                              // Handle forced attributes
2370                              if (attributesForced) {
2371                                  i = attributesForced.length;
2372                                  while (i--) {
2373                                      attr = attributesForced[i];
2374                                      name = attr.name;
2375                                      attrValue = attr.value;
2376  
2377                                      if (attrValue === '{$uid}')
2378                                          attrValue = 'mce_' + idCount++;
2379  
2380                                      attrList.map[name] = attrValue;
2381                                      attrList.push({name: name, value: attrValue});
2382                                  }
2383                              }
2384  
2385                              // Handle default attributes
2386                              if (attributesDefault) {
2387                                  i = attributesDefault.length;
2388                                  while (i--) {
2389                                      attr = attributesDefault[i];
2390                                      name = attr.name;
2391  
2392                                      if (!(name in attrList.map)) {
2393                                          attrValue = attr.value;
2394  
2395                                          if (attrValue === '{$uid}')
2396                                              attrValue = 'mce_' + idCount++;
2397  
2398                                          attrList.map[name] = attrValue;
2399                                          attrList.push({name: name, value: attrValue});
2400                                      }
2401                                  }
2402                              }
2403  
2404                              // Handle required attributes
2405                              if (attributesRequired) {
2406                                  i = attributesRequired.length;
2407                                  while (i--) {
2408                                      if (attributesRequired[i] in attrList.map)
2409                                          break;
2410                                  }
2411  
2412                                  // None of the required attributes where found
2413                                  if (i === -1)
2414                                      isValidElement = false;
2415                              }
2416  
2417                              // Invalidate element if it's marked as bogus
2418                              if (attrList.map['data-mce-bogus'])
2419                                  isValidElement = false;
2420                          }
2421  
2422                          if (isValidElement)
2423                              self.start(value, attrList, isShortEnded);
2424                      } else
2425                          isValidElement = false;
2426  
2427                      // Treat script, noscript and style a bit different since they may include code that looks like elements
2428                      if (endRegExp = specialElements[value]) {
2429                          endRegExp.lastIndex = index = matches.index + matches[0].length;
2430  
2431                          if (matches = endRegExp.exec(html)) {
2432                              if (isValidElement)
2433                                  text = html.substr(index, matches.index - index);
2434  
2435                              index = matches.index + matches[0].length;
2436                          } else {
2437                              text = html.substr(index);
2438                              index = html.length;
2439                          }
2440  
2441                          if (isValidElement && text.length > 0)
2442                              self.text(text, true);
2443  
2444                          if (isValidElement)
2445                              self.end(value);
2446  
2447                          tokenRegExp.lastIndex = index;
2448                          continue;
2449                      }
2450  
2451                      // Push value on to stack
2452                      if (!isShortEnded) {
2453                          if (!attribsValue || attribsValue.indexOf('/') != attribsValue.length - 1)
2454                              stack.push({name: value, valid: isValidElement});
2455                          else if (isValidElement)
2456                              self.end(value);
2457                      }
2458                  } else if (value = matches[1]) { // Comment
2459                      self.comment(value);
2460                  } else if (value = matches[2]) { // CDATA
2461                      self.cdata(value);
2462                  } else if (value = matches[3]) { // DOCTYPE
2463                      self.doctype(value);
2464                  } else if (value = matches[4]) { // PI
2465                      self.pi(value, matches[5]);
2466                  }
2467  
2468                  index = matches.index + matches[0].length;
2469              }
2470  
2471              // Text
2472              if (index < html.length)
2473                  self.text(decode(html.substr(index)));
2474  
2475              // Close any open elements
2476              for (i = stack.length - 1; i >= 0; i--) {
2477                  value = stack[i];
2478  
2479                  if (value.valid)
2480                      self.end(value.name);
2481              }
2482          };
2483      }
2484  })(tinymce);
2485  
2486  (function(tinymce) {
2487      var whiteSpaceRegExp = /^[ \t\r\n]*$/, typeLookup = {
2488          '#text' : 3,
2489          '#comment' : 8,
2490          '#cdata' : 4,
2491          '#pi' : 7,
2492          '#doctype' : 10,
2493          '#document-fragment' : 11
2494      };
2495  
2496      // Walks the tree left/right
2497  	function walk(node, root_node, prev) {
2498          var sibling, parent, startName = prev ? 'lastChild' : 'firstChild', siblingName = prev ? 'prev' : 'next';
2499  
2500          // Walk into nodes if it has a start
2501          if (node[startName])
2502              return node[startName];
2503  
2504          // Return the sibling if it has one
2505          if (node !== root_node) {
2506              sibling = node[siblingName];
2507  
2508              if (sibling)
2509                  return sibling;
2510  
2511              // Walk up the parents to look for siblings
2512              for (parent = node.parent; parent && parent !== root_node; parent = parent.parent) {
2513                  sibling = parent[siblingName];
2514  
2515                  if (sibling)
2516                      return sibling;
2517              }
2518          }
2519      };
2520  
2521  	function Node(name, type) {
2522          this.name = name;
2523          this.type = type;
2524  
2525          if (type === 1) {
2526              this.attributes = [];
2527              this.attributes.map = {};
2528          }
2529      }
2530  
2531      tinymce.extend(Node.prototype, {
2532          replace : function(node) {
2533              var self = this;
2534  
2535              if (node.parent)
2536                  node.remove();
2537  
2538              self.insert(node, self);
2539              self.remove();
2540  
2541              return self;
2542          },
2543  
2544          attr : function(name, value) {
2545              var self = this, attrs, i, undef;
2546  
2547              if (typeof name !== "string") {
2548                  for (i in name)
2549                      self.attr(i, name[i]);
2550  
2551                  return self;
2552              }
2553  
2554              if (attrs = self.attributes) {
2555                  if (value !== undef) {
2556                      // Remove attribute
2557                      if (value === null) {
2558                          if (name in attrs.map) {
2559                              delete attrs.map[name];
2560  
2561                              i = attrs.length;
2562                              while (i--) {
2563                                  if (attrs[i].name === name) {
2564                                      attrs = attrs.splice(i, 1);
2565                                      return self;
2566                                  }
2567                              }
2568                          }
2569  
2570                          return self;
2571                      }
2572  
2573                      // Set attribute
2574                      if (name in attrs.map) {
2575                          // Set attribute
2576                          i = attrs.length;
2577                          while (i--) {
2578                              if (attrs[i].name === name) {
2579                                  attrs[i].value = value;
2580                                  break;
2581                              }
2582                          }
2583                      } else
2584                          attrs.push({name: name, value: value});
2585  
2586                      attrs.map[name] = value;
2587  
2588                      return self;
2589                  } else {
2590                      return attrs.map[name];
2591                  }
2592              }
2593          },
2594  
2595          clone : function() {
2596              var self = this, clone = new Node(self.name, self.type), i, l, selfAttrs, selfAttr, cloneAttrs;
2597  
2598              // Clone element attributes
2599              if (selfAttrs = self.attributes) {
2600                  cloneAttrs = [];
2601                  cloneAttrs.map = {};
2602  
2603                  for (i = 0, l = selfAttrs.length; i < l; i++) {
2604                      selfAttr = selfAttrs[i];
2605  
2606                      // Clone everything except id
2607                      if (selfAttr.name !== 'id') {
2608                          cloneAttrs[cloneAttrs.length] = {name: selfAttr.name, value: selfAttr.value};
2609                          cloneAttrs.map[selfAttr.name] = selfAttr.value;
2610                      }
2611                  }
2612  
2613                  clone.attributes = cloneAttrs;
2614              }
2615  
2616              clone.value = self.value;
2617              clone.shortEnded = self.shortEnded;
2618  
2619              return clone;
2620          },
2621  
2622          wrap : function(wrapper) {
2623              var self = this;
2624  
2625              self.parent.insert(wrapper, self);
2626              wrapper.append(self);
2627  
2628              return self;
2629          },
2630  
2631          unwrap : function() {
2632              var self = this, node, next;
2633  
2634              for (node = self.firstChild; node; ) {
2635                  next = node.next;
2636                  self.insert(node, self, true);
2637                  node = next;
2638              }
2639  
2640              self.remove();
2641          },
2642  
2643          remove : function() {
2644              var self = this, parent = self.parent, next = self.next, prev = self.prev;
2645  
2646              if (parent) {
2647                  if (parent.firstChild === self) {
2648                      parent.firstChild = next;
2649  
2650                      if (next)
2651                          next.prev = null;
2652                  } else {
2653                      prev.next = next;
2654                  }
2655  
2656                  if (parent.lastChild === self) {
2657                      parent.lastChild = prev;
2658  
2659                      if (prev)
2660                          prev.next = null;
2661                  } else {
2662                      next.prev = prev;
2663                  }
2664  
2665                  self.parent = self.next = self.prev = null;
2666              }
2667  
2668              return self;
2669          },
2670  
2671          append : function(node) {
2672              var self = this, last;
2673  
2674              if (node.parent)
2675                  node.remove();
2676  
2677              last = self.lastChild;
2678              if (last) {
2679                  last.next = node;
2680                  node.prev = last;
2681                  self.lastChild = node;
2682              } else
2683                  self.lastChild = self.firstChild = node;
2684  
2685              node.parent = self;
2686  
2687              return node;
2688          },
2689  
2690          insert : function(node, ref_node, before) {
2691              var parent;
2692  
2693              if (node.parent)
2694                  node.remove();
2695  
2696              parent = ref_node.parent || this;
2697  
2698              if (before) {
2699                  if (ref_node === parent.firstChild)
2700                      parent.firstChild = node;
2701                  else
2702                      ref_node.prev.next = node;
2703  
2704                  node.prev = ref_node.prev;
2705                  node.next = ref_node;
2706                  ref_node.prev = node;
2707              } else {
2708                  if (ref_node === parent.lastChild)
2709                      parent.lastChild = node;
2710                  else
2711                      ref_node.next.prev = node;
2712  
2713                  node.next = ref_node.next;
2714                  node.prev = ref_node;
2715                  ref_node.next = node;
2716              }
2717  
2718              node.parent = parent;
2719  
2720              return node;
2721          },
2722  
2723          getAll : function(name) {
2724              var self = this, node, collection = [];
2725  
2726              for (node = self.firstChild; node; node = walk(node, self)) {
2727                  if (node.name === name)
2728                      collection.push(node);
2729              }
2730  
2731              return collection;
2732          },
2733  
2734          empty : function() {
2735              var self = this, nodes, i, node;
2736  
2737              // Remove all children
2738              if (self.firstChild) {
2739                  nodes = [];
2740  
2741                  // Collect the children
2742                  for (node = self.firstChild; node; node = walk(node, self))
2743                      nodes.push(node);
2744  
2745                  // Remove the children
2746                  i = nodes.length;
2747                  while (i--) {
2748                      node = nodes[i];
2749                      node.parent = node.firstChild = node.lastChild = node.next = node.prev = null;
2750                  }
2751              }
2752  
2753              self.firstChild = self.lastChild = null;
2754  
2755              return self;
2756          },
2757  
2758          isEmpty : function(elements) {
2759              var self = this, node = self.firstChild, i, name;
2760  
2761              if (node) {
2762                  do {
2763                      if (node.type === 1) {
2764                          // Ignore bogus elements
2765                          if (node.attributes.map['data-mce-bogus'])
2766                              continue;
2767  
2768                          // Keep empty elements like <img />
2769                          if (elements[node.name])
2770                              return false;
2771  
2772                          // Keep elements with data attributes or name attribute like <a name="1"></a>
2773                          i = node.attributes.length;
2774                          while (i--) {
2775                              name = node.attributes[i].name;
2776                              if (name === "name" || name.indexOf('data-') === 0)
2777                                  return false;
2778                          }
2779                      }
2780  
2781                      // Keep non whitespace text nodes
2782                      if ((node.type === 3 && !whiteSpaceRegExp.test(node.value)))
2783                          return false;
2784                  } while (node = walk(node, self));
2785              }
2786  
2787              return true;
2788          },
2789  
2790          walk : function(prev) {
2791              return walk(this, null, prev);
2792          }
2793      });
2794  
2795      tinymce.extend(Node, {
2796          create : function(name, attrs) {
2797              var node, attrName;
2798  
2799              // Create node
2800              node = new Node(name, typeLookup[name] || 1);
2801  
2802              // Add attributes if needed
2803              if (attrs) {
2804                  for (attrName in attrs)
2805                      node.attr(attrName, attrs[attrName]);
2806              }
2807  
2808              return node;
2809          }
2810      });
2811  
2812      tinymce.html.Node = Node;
2813  })(tinymce);
2814  
2815  (function(tinymce) {
2816      var Node = tinymce.html.Node;
2817  
2818      tinymce.html.DomParser = function(settings, schema) {
2819          var self = this, nodeFilters = {}, attributeFilters = [], matchedNodes = {}, matchedAttributes = {};
2820  
2821          settings = settings || {};
2822          settings.validate = "validate" in settings ? settings.validate : true;
2823          settings.root_name = settings.root_name || 'body';
2824          self.schema = schema = schema || new tinymce.html.Schema();
2825  
2826  		function fixInvalidChildren(nodes) {
2827              var ni, node, parent, parents, newParent, currentNode, tempNode, childNode, i,
2828                  childClone, nonEmptyElements, nonSplitableElements, sibling, nextNode;
2829  
2830              nonSplitableElements = tinymce.makeMap('tr,td,th,tbody,thead,tfoot,table');
2831              nonEmptyElements = schema.getNonEmptyElements();
2832  
2833              for (ni = 0; ni < nodes.length; ni++) {
2834                  node = nodes[ni];
2835  
2836                  // Already removed
2837                  if (!node.parent)
2838                      continue;
2839  
2840                  // Get list of all parent nodes until we find a valid parent to stick the child into
2841                  parents = [node];
2842                  for (parent = node.parent; parent && !schema.isValidChild(parent.name, node.name) && !nonSplitableElements[parent.name]; parent = parent.parent)
2843                      parents.push(parent);
2844  
2845                  // Found a suitable parent
2846                  if (parent && parents.length > 1) {
2847                      // Reverse the array since it makes looping easier
2848                      parents.reverse();
2849  
2850                      // Clone the related parent and insert that after the moved node
2851                      newParent = currentNode = self.filterNode(parents[0].clone());
2852  
2853                      // Start cloning and moving children on the left side of the target node
2854                      for (i = 0; i < parents.length - 1; i++) {
2855                          if (schema.isValidChild(currentNode.name, parents[i].name)) {
2856                              tempNode = self.filterNode(parents[i].clone());
2857                              currentNode.append(tempNode);
2858                          } else
2859                              tempNode = currentNode;
2860  
2861                          for (childNode = parents[i].firstChild; childNode && childNode != parents[i + 1]; ) {
2862                              nextNode = childNode.next;
2863                              tempNode.append(childNode);
2864                              childNode = nextNode;
2865                          }
2866  
2867                          currentNode = tempNode;
2868                      }
2869  
2870                      if (!newParent.isEmpty(nonEmptyElements)) {
2871                          parent.insert(newParent, parents[0], true);
2872                          parent.insert(node, newParent);
2873                      } else {
2874                          parent.insert(node, parents[0], true);
2875                      }
2876  
2877                      // Check if the element is empty by looking through it's contents and special treatment for <p><br /></p>
2878                      parent = parents[0];
2879                      if (parent.isEmpty(nonEmptyElements) || parent.firstChild === parent.lastChild && parent.firstChild.name === 'br') {
2880                          parent.empty().remove();
2881                      }
2882                  } else if (node.parent) {
2883                      // If it's an LI try to find a UL/OL for it or wrap it
2884                      if (node.name === 'li') {
2885                          sibling = node.prev;
2886                          if (sibling && (sibling.name === 'ul' || sibling.name === 'ul')) {
2887                              sibling.append(node);
2888                              continue;
2889                          }
2890  
2891                          sibling = node.next;
2892                          if (sibling && (sibling.name === 'ul' || sibling.name === 'ul')) {
2893                              sibling.insert(node, sibling.firstChild, true);
2894                              continue;
2895                          }
2896  
2897                          node.wrap(self.filterNode(new Node('ul', 1)));
2898                          continue;
2899                      }
2900  
2901                      // Try wrapping the element in a DIV
2902                      if (schema.isValidChild(node.parent.name, 'div') && schema.isValidChild('div', node.name)) {
2903                          node.wrap(self.filterNode(new Node('div', 1)));
2904                      } else {
2905                          // We failed wrapping it, then remove or unwrap it
2906                          if (node.name === 'style' || node.name === 'script')
2907                              node.empty().remove();
2908                          else
2909                              node.unwrap();
2910                      }
2911                  }
2912              }
2913          };
2914  
2915          self.filterNode = function(node) {
2916              var i, name, list;
2917  
2918              // Run element filters
2919              if (name in nodeFilters) {
2920                  list = matchedNodes[name];
2921  
2922                  if (list)
2923                      list.push(node);
2924                  else
2925                      matchedNodes[name] = [node];
2926              }
2927  
2928              // Run attribute filters
2929              i = attributeFilters.length;
2930              while (i--) {
2931                  name = attributeFilters[i].name;
2932  
2933                  if (name in node.attributes.map) {
2934                      list = matchedAttributes[name];
2935  
2936                      if (list)
2937                          list.push(node);
2938                      else
2939                          matchedAttributes[name] = [node];
2940                  }
2941              }
2942  
2943              return node;
2944          };
2945  
2946          self.addNodeFilter = function(name, callback) {
2947              tinymce.each(tinymce.explode(name), function(name) {
2948                  var list = nodeFilters[name];
2949  
2950                  if (!list)
2951                      nodeFilters[name] = list = [];
2952  
2953                  list.push(callback);
2954              });
2955          };
2956  
2957          self.addAttributeFilter = function(name, callback) {
2958              tinymce.each(tinymce.explode(name), function(name) {
2959                  var i;
2960  
2961                  for (i = 0; i < attributeFilters.length; i++) {
2962                      if (attributeFilters[i].name === name) {
2963                          attributeFilters[i].callbacks.push(callback);
2964                          return;
2965                      }
2966                  }
2967  
2968                  attributeFilters.push({name: name, callbacks: [callback]});
2969              });
2970          };
2971  
2972          self.parse = function(html, args) {
2973              var parser, rootNode, node, nodes, i, l, fi, fl, list, name, validate,
2974                  blockElements, startWhiteSpaceRegExp, invalidChildren = [],
2975                  endWhiteSpaceRegExp, allWhiteSpaceRegExp, whiteSpaceElements, children, nonEmptyElements, rootBlockName;
2976  
2977              args = args || {};
2978              matchedNodes = {};
2979              matchedAttributes = {};
2980              blockElements = tinymce.extend(tinymce.makeMap('script,style,head,html,body,title,meta,param'), schema.getBlockElements());
2981              nonEmptyElements = schema.getNonEmptyElements();
2982              children = schema.children;
2983              validate = settings.validate;
2984              rootBlockName = "forced_root_block" in args ? args.forced_root_block : settings.forced_root_block;
2985  
2986              whiteSpaceElements = schema.getWhiteSpaceElements();
2987              startWhiteSpaceRegExp = /^[ \t\r\n]+/;
2988              endWhiteSpaceRegExp = /[ \t\r\n]+$/;
2989              allWhiteSpaceRegExp = /[ \t\r\n]+/g;
2990  
2991  			function addRootBlocks() {
2992                  var node = rootNode.firstChild, next, rootBlockNode;
2993  
2994                  while (node) {
2995                      next = node.next;
2996  
2997                      if (node.type == 3 || (node.type == 1 && node.name !== 'p' && !blockElements[node.name] && !node.attr('data-mce-type'))) {
2998                          if (!rootBlockNode) {
2999                              // Create a new root block element
3000                              rootBlockNode = createNode(rootBlockName, 1);
3001                              rootNode.insert(rootBlockNode, node);
3002                              rootBlockNode.append(node);
3003                          } else
3004                              rootBlockNode.append(node);
3005                      } else {
3006                          rootBlockNode = null;
3007                      }
3008  
3009                      node = next;
3010                  };
3011              };
3012  
3013  			function createNode(name, type) {
3014                  var node = new Node(name, type), list;
3015  
3016                  if (name in nodeFilters) {
3017                      list = matchedNodes[name];
3018  
3019                      if (list)
3020                          list.push(node);
3021                      else
3022                          matchedNodes[name] = [node];
3023                  }
3024  
3025                  return node;
3026              };
3027  
3028  			function removeWhitespaceBefore(node) {
3029                  var textNode, textVal, sibling;
3030  
3031                  for (textNode = node.prev; textNode && textNode.type === 3; ) {
3032                      textVal = textNode.value.replace(endWhiteSpaceRegExp, '');
3033  
3034                      if (textVal.length > 0) {
3035                          textNode.value = textVal;
3036                          textNode = textNode.prev;
3037                      } else {
3038                          sibling = textNode.prev;
3039                          textNode.remove();
3040                          textNode = sibling;
3041                      }
3042                  }
3043              };
3044  
3045              parser = new tinymce.html.SaxParser({
3046                  validate : validate,
3047                  fix_self_closing : !validate, // Let the DOM parser handle <li> in <li> or <p> in <p> for better results
3048  
3049                  cdata: function(text) {
3050                      node.append(createNode('#cdata', 4)).value = text;
3051                  },
3052  
3053                  text: function(text, raw) {
3054                      var textNode;
3055  
3056                      // Trim all redundant whitespace on non white space elements
3057                      if (!whiteSpaceElements[node.name]) {
3058                          text = text.replace(allWhiteSpaceRegExp, ' ');
3059  
3060                          if (node.lastChild && blockElements[node.lastChild.name])
3061                              text = text.replace(startWhiteSpaceRegExp, '');
3062                      }
3063  
3064                      // Do we need to create the node
3065                      if (text.length !== 0) {
3066                          textNode = createNode('#text', 3);
3067                          textNode.raw = !!raw;
3068                          node.append(textNode).value = text;
3069                      }
3070                  },
3071  
3072                  comment: function(text) {
3073                      node.append(createNode('#comment', 8)).value = text;
3074                  },
3075  
3076                  pi: function(name, text) {
3077                      node.append(createNode(name, 7)).value = text;
3078                      removeWhitespaceBefore(node);
3079                  },
3080  
3081                  doctype: function(text) {
3082                      var newNode;
3083          
3084                      newNode = node.append(createNode('#doctype', 10));
3085                      newNode.value = text;
3086                      removeWhitespaceBefore(node);
3087                  },
3088  
3089                  start: function(name, attrs, empty) {
3090                      var newNode, attrFiltersLen, elementRule, textNode, attrName, text, sibling, parent;
3091  
3092                      elementRule = validate ? schema.getElementRule(name) : {};
3093                      if (elementRule) {
3094                          newNode = createNode(elementRule.outputName || name, 1);
3095                          newNode.attributes = attrs;
3096                          newNode.shortEnded = empty;
3097  
3098                          node.append(newNode);
3099  
3100                          // Check if node is valid child of the parent node is the child is
3101                          // unknown we don't collect it since it's probably a custom element
3102                          parent = children[node.name];
3103                          if (parent && children[newNode.name] && !parent[newNode.name])
3104                              invalidChildren.push(newNode);
3105  
3106                          attrFiltersLen = attributeFilters.length;
3107                          while (attrFiltersLen--) {
3108                              attrName = attributeFilters[attrFiltersLen].name;
3109  
3110                              if (attrName in attrs.map) {
3111                                  list = matchedAttributes[attrName];
3112  
3113                                  if (list)
3114                                      list.push(newNode);
3115                                  else
3116                                      matchedAttributes[attrName] = [newNode];
3117                              }
3118                          }
3119  
3120                          // Trim whitespace before block
3121                          if (blockElements[name])
3122                              removeWhitespaceBefore(newNode);
3123  
3124                          // Change current node if the element wasn't empty i.e not <br /> or <img />
3125                          if (!empty)
3126                              node = newNode;
3127                      }
3128                  },
3129  
3130                  end: function(name) {
3131                      var textNode, elementRule, text, sibling, tempNode;
3132  
3133                      elementRule = validate ? schema.getElementRule(name) : {};
3134                      if (elementRule) {
3135                          if (blockElements[name]) {
3136                              if (!whiteSpaceElements[node.name]) {
3137                                  // Trim whitespace at beginning of block
3138                                  for (textNode = node.firstChild; textNode && textNode.type === 3; ) {
3139                                      text = textNode.value.replace(startWhiteSpaceRegExp, '');
3140  
3141                                      if (text.length > 0) {
3142                                          textNode.value = text;
3143                                          textNode = textNode.next;
3144                                      } else {
3145                                          sibling = textNode.next;
3146                                          textNode.remove();
3147                                          textNode = sibling;
3148                                      }
3149                                  }
3150  
3151                                  // Trim whitespace at end of block
3152                                  for (textNode = node.lastChild; textNode && textNode.type === 3; ) {
3153                                      text = textNode.value.replace(endWhiteSpaceRegExp, '');
3154  
3155                                      if (text.length > 0) {
3156                                          textNode.value = text;
3157                                          textNode = textNode.prev;
3158                                      } else {
3159                                          sibling = textNode.prev;
3160                                          textNode.remove();
3161                                          textNode = sibling;
3162                                      }
3163                                  }
3164                              }
3165  
3166                              // Trim start white space
3167                              textNode = node.prev;
3168                              if (textNode && textNode.type === 3) {
3169                                  text = textNode.value.replace(startWhiteSpaceRegExp, '');
3170  
3171                                  if (text.length > 0)
3172                                      textNode.value = text;
3173                                  else
3174                                      textNode.remove();
3175                              }
3176                          }
3177  
3178                          // Handle empty nodes
3179                          if (elementRule.removeEmpty || elementRule.paddEmpty) {
3180                              if (node.isEmpty(nonEmptyElements)) {
3181                                  if (elementRule.paddEmpty)
3182                                      node.empty().append(new Node('#text', '3')).value = '\u00a0';
3183                                  else {
3184                                      // Leave nodes that have a name like <a name="name">
3185                                      if (!node.attributes.map.name) {
3186                                          tempNode = node.parent;
3187                                          node.empty().remove();
3188                                          node = tempNode;
3189                                          return;
3190                                      }
3191                                  }
3192                              }
3193                          }
3194  
3195                          node = node.parent;
3196                      }
3197                  }
3198              }, schema);
3199  
3200              rootNode = node = new Node(args.context || settings.root_name, 11);
3201  
3202              parser.parse(html);
3203  
3204              // Fix invalid children or report invalid children in a contextual parsing
3205              if (validate && invalidChildren.length) {
3206                  if (!args.context)
3207                      fixInvalidChildren(invalidChildren);
3208                  else
3209                      args.invalid = true;
3210              }
3211  
3212              // Wrap nodes in the root into block elements if the root is body
3213              if (rootBlockName && rootNode.name == 'body')
3214                  addRootBlocks();
3215  
3216              // Run filters only when the contents is valid
3217              if (!args.invalid) {
3218                  // Run node filters
3219                  for (name in matchedNodes) {
3220                      list = nodeFilters[name];
3221                      nodes = matchedNodes[name];
3222  
3223                      // Remove already removed children
3224                      fi = nodes.length;
3225                      while (fi--) {
3226                          if (!nodes[fi].parent)
3227                              nodes.splice(fi, 1);
3228                      }
3229  
3230                      for (i = 0, l = list.length; i < l; i++)
3231                          list[i](nodes, name, args);
3232                  }
3233  
3234                  // Run attribute filters
3235                  for (i = 0, l = attributeFilters.length; i < l; i++) {
3236                      list = attributeFilters[i];
3237  
3238                      if (list.name in matchedAttributes) {
3239                          nodes = matchedAttributes[list.name];
3240  
3241                          // Remove already removed children
3242                          fi = nodes.length;
3243                          while (fi--) {
3244                              if (!nodes[fi].parent)
3245                                  nodes.splice(fi, 1);
3246                          }
3247  
3248                          for (fi = 0, fl = list.callbacks.length; fi < fl; fi++)
3249                              list.callbacks[fi](nodes, list.name, args);
3250                      }
3251                  }
3252              }
3253  
3254              return rootNode;
3255          };
3256  
3257          // Remove <br> at end of block elements Gecko and WebKit injects BR elements to
3258          // make it possible to place the caret inside empty blocks. This logic tries to remove
3259          // these elements and keep br elements that where intended to be there intact
3260          if (settings.remove_trailing_brs) {
3261              self.addNodeFilter('br', function(nodes, name) {
3262                  var i, l = nodes.length, node, blockElements = schema.getBlockElements(),
3263                      nonEmptyElements = schema.getNonEmptyElements(), parent, prev, prevName;
3264  
3265                  // Remove brs from body element as well
3266                  blockElements.body = 1;
3267  
3268                  // Must loop forwards since it will otherwise remove all brs in <p>a<br><br><br></p>
3269                  for (i = 0; i < l; i++) {
3270                      node = nodes[i];
3271                      parent = node.parent;
3272  
3273                      if (blockElements[node.parent.name] && node === parent.lastChild) {
3274                          // Loop all nodes to the right of the current node and check for other BR elements
3275                          // excluding bookmarks since they are invisible
3276                          prev = node.prev;
3277                          while (prev) {
3278                              prevName = prev.name;
3279  
3280                              // Ignore bookmarks
3281                              if (prevName !== "span" || prev.attr('data-mce-type') !== 'bookmark') {
3282                                  // Found a non BR element
3283                                  if (prevName !== "br")
3284                                      break;
3285      
3286                                  // Found another br it's a <br><br> structure then don't remove anything
3287                                  if (prevName === 'br') {
3288                                      node = null;
3289                                      break;
3290                                  }
3291                              }
3292  
3293                              prev = prev.prev;
3294                          }
3295  
3296                          if (node) {
3297                              node.remove();
3298  
3299                              // Is the parent to be considered empty after we removed the BR
3300                              if (parent.isEmpty(nonEmptyElements)) {
3301                                  elementRule = schema.getElementRule(parent.name);
3302  
3303                                  // Remove or padd the element depending on schema rule
3304                                  if (elementRule) {
3305                                    if (elementRule.removeEmpty)
3306                                        parent.remove();
3307                                    else if (elementRule.paddEmpty)
3308                                        parent.empty().append(new tinymce.html.Node('#text', 3)).value = '\u00a0';
3309                                }
3310                }
3311                          }
3312                      }
3313                  }
3314              });
3315          }
3316      }
3317  })(tinymce);
3318  
3319  tinymce.html.Writer = function(settings) {
3320      var html = [], indent, indentBefore, indentAfter, encode, htmlOutput;
3321  
3322      settings = settings || {};
3323      indent = settings.indent;
3324      indentBefore = tinymce.makeMap(settings.indent_before || '');
3325      indentAfter = tinymce.makeMap(settings.indent_after || '');
3326      encode = tinymce.html.Entities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);
3327      htmlOutput = settings.element_format == "html";
3328  
3329      return {
3330          start: function(name, attrs, empty) {
3331              var i, l, attr, value;
3332  
3333              if (indent && indentBefore[name] && html.length > 0) {
3334                  value = html[html.length - 1];
3335  
3336                  if (value.length > 0 && value !== '\n')
3337                      html.push('\n');
3338              }
3339  
3340              html.push('<', name);
3341  
3342              if (attrs) {
3343                  for (i = 0, l = attrs.length; i < l; i++) {
3344                      attr = attrs[i];
3345                      html.push(' ', attr.name, '="', encode(attr.value, true), '"');
3346                  }
3347              }
3348  
3349              if (!empty || htmlOutput)
3350                  html[html.length] = '>';
3351              else
3352                  html[html.length] = ' />';
3353  
3354              if (empty && indent && indentAfter[name] && html.length > 0) {
3355                  value = html[html.length - 1];
3356  
3357                  if (value.length > 0 && value !== '\n')
3358                      html.push('\n');
3359              }
3360          },
3361  
3362          end: function(name) {
3363              var value;
3364  
3365              /*if (indent && indentBefore[name] && html.length > 0) {
3366                  value = html[html.length - 1];
3367  
3368                  if (value.length > 0 && value !== '\n')
3369                      html.push('\n');
3370              }*/
3371  
3372              html.push('</', name, '>');
3373  
3374              if (indent && indentAfter[name] && html.length > 0) {
3375                  value = html[html.length - 1];
3376  
3377                  if (value.length > 0 && value !== '\n')
3378                      html.push('\n');
3379              }
3380          },
3381  
3382          text: function(text, raw) {
3383              if (text.length > 0)
3384                  html[html.length] = raw ? text : encode(text);
3385          },
3386  
3387          cdata: function(text) {
3388              html.push('<![CDATA[', text, ']]>');
3389          },
3390  
3391          comment: function(text) {
3392              html.push('<!--', text, '-->');
3393          },
3394  
3395          pi: function(name, text) {
3396              if (text)
3397                  html.push('<?', name, ' ', text, '?>');
3398              else
3399                  html.push('<?', name, '?>');
3400  
3401              if (indent)
3402                  html.push('\n');
3403          },
3404  
3405          doctype: function(text) {
3406              html.push('<!DOCTYPE', text, '>', indent ? '\n' : '');
3407          },
3408  
3409          reset: function() {
3410              html.length = 0;
3411          },
3412  
3413          getContent: function() {
3414              return html.join('').replace(/\n$/, '');
3415          }
3416      };
3417  };
3418  
3419  (function(tinymce) {
3420      tinymce.html.Serializer = function(settings, schema) {
3421          var self = this, writer = new tinymce.html.Writer(settings);
3422  
3423          settings = settings || {};
3424          settings.validate = "validate" in settings ? settings.validate : true;
3425  
3426          self.schema = schema = schema || new tinymce.html.Schema();
3427          self.writer = writer;
3428  
3429          self.serialize = function(node) {
3430              var handlers, validate;
3431  
3432              validate = settings.validate;
3433  
3434              handlers = {
3435                  // #text
3436                  3: function(node, raw) {
3437                      writer.text(node.value, node.raw);
3438                  },
3439  
3440                  // #comment
3441                  8: function(node) {
3442                      writer.comment(node.value);
3443                  },
3444  
3445                  // Processing instruction
3446                  7: function(node) {
3447                      writer.pi(node.name, node.value);
3448                  },
3449  
3450                  // Doctype
3451                  10: function(node) {
3452                      writer.doctype(node.value);
3453                  },
3454  
3455                  // CDATA
3456                  4: function(node) {
3457                      writer.cdata(node.value);
3458                  },
3459  
3460                   // Document fragment
3461                  11: function(node) {
3462                      if ((node = node.firstChild)) {
3463                          do {
3464                              walk(node);
3465                          } while (node = node.next);
3466                      }
3467                  }
3468              };
3469  
3470              writer.reset();
3471  
3472  			function walk(node) {
3473                  var handler = handlers[node.type], name, isEmpty, attrs, attrName, attrValue, sortedAttrs, i, l, elementRule;
3474  
3475                  if (!handler) {
3476                      name = node.name;
3477                      isEmpty = node.shortEnded;
3478                      attrs = node.attributes;
3479  
3480                      // Sort attributes
3481                      if (validate && attrs && attrs.length > 1) {
3482                          sortedAttrs = [];
3483                          sortedAttrs.map = {};
3484  
3485                          elementRule = schema.getElementRule(node.name);
3486                          for (i = 0, l = elementRule.attributesOrder.length; i < l; i++) {
3487                              attrName = elementRule.attributesOrder[i];
3488  
3489                              if (attrName in attrs.map) {
3490                                  attrValue = attrs.map[attrName];
3491                                  sortedAttrs.map[attrName] = attrValue;
3492                                  sortedAttrs.push({name: attrName, value: attrValue});
3493                              }
3494                          }
3495  
3496                          for (i = 0, l = attrs.length; i < l; i++) {
3497                              attrName = attrs[i].name;
3498  
3499                              if (!(attrName in sortedAttrs.map)) {
3500                                  attrValue = attrs.map[attrName];
3501                                  sortedAttrs.map[attrName] = attrValue;
3502                                  sortedAttrs.push({name: attrName, value: attrValue});
3503                              }
3504                          }
3505  
3506                          attrs = sortedAttrs;
3507                      }
3508  
3509                      writer.start(node.name, attrs, isEmpty);
3510  
3511                      if (!isEmpty) {
3512                          if ((node = node.firstChild)) {
3513                              do {
3514                                  walk(node);
3515                              } while (node = node.next);
3516                          }
3517  
3518                          writer.end(name);
3519                      }
3520                  } else
3521                      handler(node);
3522              }
3523  
3524              // Serialize element and treat all non elements as fragments
3525              if (node.type == 1 && !settings.inner)
3526                  walk(node);
3527              else
3528                  handlers[11](node);
3529  
3530              return writer.getContent();
3531          };
3532      }
3533  })(tinymce);
3534  
3535  (function(tinymce) {
3536      // Shorten names
3537      var each = tinymce.each,
3538          is = tinymce.is,
3539          isWebKit = tinymce.isWebKit,
3540          isIE = tinymce.isIE,
3541          Entities = tinymce.html.Entities,
3542          simpleSelectorRe = /^([a-z0-9],?)+$/i,
3543          blockElementsMap = tinymce.html.Schema.blockElementsMap,
3544          whiteSpaceRegExp = /^[ \t\r\n]*$/;
3545  
3546      tinymce.create('tinymce.dom.DOMUtils', {
3547          doc : null,
3548          root : null,
3549          files : null,
3550          pixelStyles : /^(top|left|bottom|right|width|height|borderWidth)$/,
3551          props : {
3552              "for" : "htmlFor",
3553              "class" : "className",
3554              className : "className",
3555              checked : "checked",
3556              disabled : "disabled",
3557              maxlength : "maxLength",
3558              readonly : "readOnly",
3559              selected : "selected",
3560              value : "value",
3561              id : "id",
3562              name : "name",
3563              type : "type"
3564          },
3565  
3566          DOMUtils : function(d, s) {
3567              var t = this, globalStyle, name;
3568  
3569              t.doc = d;
3570              t.win = window;
3571              t.files = {};
3572              t.cssFlicker = false;
3573              t.counter = 0;
3574              t.stdMode = !tinymce.isIE || d.documentMode >= 8;
3575              t.boxModel = !tinymce.isIE || d.compatMode == "CSS1Compat" || t.stdMode;
3576              t.hasOuterHTML = "outerHTML" in d.createElement("a");
3577  
3578              t.settings = s = tinymce.extend({
3579                  keep_values : false,
3580                  hex_colors : 1
3581              }, s);
3582              
3583              t.schema = s.schema;
3584              t.styles = new tinymce.html.Styles({
3585                  url_converter : s.url_converter,
3586                  url_converter_scope : s.url_converter_scope
3587              }, s.schema);
3588  
3589              // Fix IE6SP2 flicker and check it failed for pre SP2
3590              if (tinymce.isIE6) {
3591                  try {
3592                      d.execCommand('BackgroundImageCache', false, true);
3593                  } catch (e) {
3594                      t.cssFlicker = true;
3595                  }
3596              }
3597  
3598              if (isIE && s.schema) {
3599                  // Add missing HTML 4/5 elements to IE
3600                  ('abbr article aside audio canvas ' +
3601                  'details figcaption figure footer ' +
3602                  'header hgroup mark menu meter nav ' +
3603                  'output progress section summary ' +
3604                  'time video').replace(/\w+/g, function(name) {
3605                      d.createElement(name);
3606                  });
3607  
3608                  // Create all custom elements
3609                  for (name in s.schema.getCustomElements()) {
3610                      d.createElement(name);
3611                  }
3612              }
3613  
3614              tinymce.addUnload(t.destroy, t);
3615          },
3616  
3617          getRoot : function() {
3618              var t = this, s = t.settings;
3619  
3620              return (s && t.get(s.root_element)) || t.doc.body;
3621          },
3622  
3623          getViewPort : function(w) {
3624              var d, b;
3625  
3626              w = !w ? this.win : w;
3627              d = w.document;
3628              b = this.boxModel ? d.documentElement : d.body;
3629  
3630              // Returns viewport size excluding scrollbars
3631              return {
3632                  x : w.pageXOffset || b.scrollLeft,
3633                  y : w.pageYOffset || b.scrollTop,
3634                  w : w.innerWidth || b.clientWidth,
3635                  h : w.innerHeight || b.clientHeight
3636              };
3637          },
3638  
3639          getRect : function(e) {
3640              var p, t = this, sr;
3641  
3642              e = t.get(e);
3643              p = t.getPos(e);
3644              sr = t.getSize(e);
3645  
3646              return {
3647                  x : p.x,
3648                  y : p.y,
3649                  w : sr.w,
3650                  h : sr.h
3651              };
3652          },
3653  
3654          getSize : function(e) {
3655              var t = this, w, h;
3656  
3657              e = t.get(e);
3658              w = t.getStyle(e, 'width');
3659              h = t.getStyle(e, 'height');
3660  
3661              // Non pixel value, then force offset/clientWidth
3662              if (w.indexOf('px') === -1)
3663                  w = 0;
3664  
3665              // Non pixel value, then force offset/clientWidth
3666              if (h.indexOf('px') === -1)
3667                  h = 0;
3668  
3669              return {
3670                  w : parseInt(w) || e.offsetWidth || e.clientWidth,
3671                  h : parseInt(h) || e.offsetHeight || e.clientHeight
3672              };
3673          },
3674  
3675          getParent : function(n, f, r) {
3676              return this.getParents(n, f, r, false);
3677          },
3678  
3679          getParents : function(n, f, r, c) {
3680              var t = this, na, se = t.settings, o = [];
3681  
3682              n = t.get(n);
3683              c = c === undefined;
3684  
3685              if (se.strict_root)
3686                  r = r || t.getRoot();
3687  
3688              // Wrap node name as func
3689              if (is(f, 'string')) {
3690                  na = f;
3691  
3692                  if (f === '*') {
3693                      f = function(n) {return n.nodeType == 1;};
3694                  } else {
3695                      f = function(n) {
3696                          return t.is(n, na);
3697                      };
3698                  }
3699              }
3700  
3701              while (n) {
3702                  if (n == r || !n.nodeType || n.nodeType === 9)
3703                      break;
3704  
3705                  if (!f || f(n)) {
3706                      if (c)
3707                          o.push(n);
3708                      else
3709                          return n;
3710                  }
3711  
3712                  n = n.parentNode;
3713              }
3714  
3715              return c ? o : null;
3716          },
3717  
3718          get : function(e) {
3719              var n;
3720  
3721              if (e && this.doc && typeof(e) == 'string') {
3722                  n = e;
3723                  e = this.doc.getElementById(e);
3724  
3725                  // IE and Opera returns meta elements when they match the specified input ID, but getElementsByName seems to do the trick
3726                  if (e && e.id !== n)
3727                      return this.doc.getElementsByName(n)[1];
3728              }
3729  
3730              return e;
3731          },
3732  
3733          getNext : function(node, selector) {
3734              return this._findSib(node, selector, 'nextSibling');
3735          },
3736  
3737          getPrev : function(node, selector) {
3738              return this._findSib(node, selector, 'previousSibling');
3739          },
3740  
3741  
3742          select : function(pa, s) {
3743              var t = this;
3744  
3745              return tinymce.dom.Sizzle(pa, t.get(s) || t.get(t.settings.root_element) || t.doc, []);
3746          },
3747  
3748          is : function(n, selector) {
3749              var i;
3750  
3751              // If it isn't an array then try to do some simple selectors instead of Sizzle for to boost performance
3752              if (n.length === undefined) {
3753                  // Simple all selector
3754                  if (selector === '*')
3755                      return n.nodeType == 1;
3756  
3757                  // Simple selector just elements
3758                  if (simpleSelectorRe.test(selector)) {
3759                      selector = selector.toLowerCase().split(/,/);
3760                      n = n.nodeName.toLowerCase();
3761  
3762                      for (i = selector.length - 1; i >= 0; i--) {
3763                          if (selector[i] == n)
3764                              return true;
3765                      }
3766  
3767                      return false;
3768                  }
3769              }
3770  
3771              return tinymce.dom.Sizzle.matches(selector, n.nodeType ? [n] : n).length > 0;
3772          },
3773  
3774  
3775          add : function(p, n, a, h, c) {
3776              var t = this;
3777  
3778              return this.run(p, function(p) {
3779                  var e, k;
3780  
3781                  e = is(n, 'string') ? t.doc.createElement(n) : n;
3782                  t.setAttribs(e, a);
3783  
3784                  if (h) {
3785                      if (h.nodeType)
3786                          e.appendChild(h);
3787                      else
3788                          t.setHTML(e, h);
3789                  }
3790  
3791                  return !c ? p.appendChild(e) : e;
3792              });
3793          },
3794  
3795          create : function(n, a, h) {
3796              return this.add(this.doc.createElement(n), n, a, h, 1);
3797          },
3798  
3799          createHTML : function(n, a, h) {
3800              var o = '', t = this, k;
3801  
3802              o += '<' + n;
3803  
3804              for (k in a) {
3805                  if (a.hasOwnProperty(k))
3806                      o += ' ' + k + '="' + t.encode(a[k]) + '"';
3807              }
3808  
3809              // A call to tinymce.is doesn't work for some odd reason on IE9 possible bug inside their JS runtime
3810              if (typeof(h) != "undefined")
3811                  return o + '>' + h + '</' + n + '>';
3812  
3813              return o + ' />';
3814          },
3815  
3816          remove : function(node, keep_children) {
3817              return this.run(node, function(node) {
3818                  var child, parent = node.parentNode;
3819  
3820                  if (!parent)
3821                      return null;
3822  
3823                  if (keep_children) {
3824                      while (child = node.firstChild) {
3825                          // IE 8 will crash if you don't remove completely empty text nodes
3826                          if (!tinymce.isIE || child.nodeType !== 3 || child.nodeValue)
3827                              parent.insertBefore(child, node);
3828                          else
3829                              node.removeChild(child);
3830                      }
3831                  }
3832  
3833                  return parent.removeChild(node);
3834              });
3835          },
3836  
3837          setStyle : function(n, na, v) {
3838              var t = this;
3839  
3840              return t.run(n, function(e) {
3841                  var s, i;
3842  
3843                  s = e.style;
3844  
3845                  // Camelcase it, if needed
3846                  na = na.replace(/-(\D)/g, function(a, b){
3847                      return b.toUpperCase();
3848                  });
3849  
3850                  // Default px suffix on these
3851                  if (t.pixelStyles.test(na) && (tinymce.is(v, 'number') || /^[\-0-9\.]+$/.test(v)))
3852                      v += 'px';
3853  
3854                  switch (na) {
3855                      case 'opacity':
3856                          // IE specific opacity
3857                          if (isIE) {
3858                              s.filter = v === '' ? '' : "alpha(opacity=" + (v * 100) + ")";
3859  
3860                              if (!n.currentStyle || !n.currentStyle.hasLayout)
3861                                  s.display = 'inline-block';
3862                          }
3863  
3864                          // Fix for older browsers
3865                          s[na] = s['-moz-opacity'] = s['-khtml-opacity'] = v || '';
3866                          break;
3867  
3868                      case 'float':
3869                          isIE ? s.styleFloat = v : s.cssFloat = v;
3870                          break;
3871                      
3872                      default:
3873                          s[na] = v || '';
3874                  }
3875  
3876                  // Force update of the style data
3877                  if (t.settings.update_styles)
3878                      t.setAttrib(e, 'data-mce-style');
3879              });
3880          },
3881  
3882          getStyle : function(n, na, c) {
3883              n = this.get(n);
3884  
3885              if (!n)
3886                  return;
3887  
3888              // Gecko
3889              if (this.doc.defaultView && c) {
3890                  // Remove camelcase
3891                  na = na.replace(/[A-Z]/g, function(a){
3892                      return '-' + a;
3893                  });
3894  
3895                  try {
3896                      return this.doc.defaultView.getComputedStyle(n, null).getPropertyValue(na);
3897                  } catch (ex) {
3898                      // Old safari might fail
3899                      return null;
3900                  }
3901              }
3902  
3903              // Camelcase it, if needed
3904              na = na.replace(/-(\D)/g, function(a, b){
3905                  return b.toUpperCase();
3906              });
3907  
3908              if (na == 'float')
3909                  na = isIE ? 'styleFloat' : 'cssFloat';
3910  
3911              // IE & Opera
3912              if (n.currentStyle && c)
3913                  return n.currentStyle[na];
3914  
3915              return n.style ? n.style[na] : undefined;
3916          },
3917  
3918          setStyles : function(e, o) {
3919              var t = this, s = t.settings, ol;
3920  
3921              ol = s.update_styles;
3922              s.update_styles = 0;
3923  
3924              each(o, function(v, n) {
3925                  t.setStyle(e, n, v);
3926              });
3927  
3928              // Update style info
3929              s.update_styles = ol;
3930              if (s.update_styles)
3931                  t.setAttrib(e, s.cssText);
3932          },
3933  
3934          removeAllAttribs: function(e) {
3935              return this.run(e, function(e) {
3936                  var i, attrs = e.attributes;
3937                  for (i = attrs.length - 1; i >= 0; i--) {
3938                      e.removeAttributeNode(attrs.item(i));
3939                  }
3940              });
3941          },
3942  
3943          setAttrib : function(e, n, v) {
3944              var t = this;
3945  
3946              // Whats the point
3947              if (!e || !n)
3948                  return;
3949  
3950              // Strict XML mode
3951              if (t.settings.strict)
3952                  n = n.toLowerCase();
3953  
3954              return this.run(e, function(e) {
3955                  var s = t.settings;
3956                  var originalValue = e.getAttribute(n);
3957                  if (v !== null) {
3958                      switch (n) {
3959                          case "style":
3960                              if (!is(v, 'string')) {
3961                                  each(v, function(v, n) {
3962                                      t.setStyle(e, n, v);
3963                                  });
3964  
3965                                  return;
3966                              }
3967  
3968                              // No mce_style for elements with these since they might get resized by the user
3969                              if (s.keep_values) {
3970                                  if (v && !t._isRes(v))
3971                                      e.setAttribute('data-mce-style', v, 2);
3972                                  else
3973                                      e.removeAttribute('data-mce-style', 2);
3974                              }
3975  
3976                              e.style.cssText = v;
3977                              break;
3978  
3979                          case "class":
3980                              e.className = v || ''; // Fix IE null bug
3981                              break;
3982  
3983                          case "src":
3984                          case "href":
3985                              if (s.keep_values) {
3986                                  if (s.url_converter)
3987                                      v = s.url_converter.call(s.url_converter_scope || t, v, n, e);
3988  
3989                                  t.setAttrib(e, 'data-mce-' + n, v, 2);
3990                              }
3991  
3992                              break;
3993  
3994                          case "shape":
3995                              e.setAttribute('data-mce-style', v);
3996                              break;
3997                      }
3998                  }
3999                  if (is(v) && v !== null && v.length !== 0)
4000                      e.setAttribute(n, '' + v, 2);
4001                  else
4002                      e.removeAttribute(n, 2);
4003  
4004                  // fire onChangeAttrib event for attributes that have changed
4005                  if (tinyMCE.activeEditor && originalValue != v) {
4006                      var ed = tinyMCE.activeEditor;
4007                      ed.onSetAttrib.dispatch(ed, e, n, v);
4008                  }
4009              });
4010          },
4011  
4012          setAttribs : function(e, o) {
4013              var t = this;
4014  
4015              return this.run(e, function(e) {
4016                  each(o, function(v, n) {
4017                      t.setAttrib(e, n, v);
4018                  });
4019              });
4020          },
4021  
4022          getAttrib : function(e, n, dv) {
4023              var v, t = this, undef;
4024  
4025              e = t.get(e);
4026  
4027              if (!e || e.nodeType !== 1)
4028                  return dv === undef ? false : dv;
4029  
4030              if (!is(dv))
4031                  dv = '';
4032  
4033              // Try the mce variant for these
4034              if (/^(src|href|style|coords|shape)$/.test(n)) {
4035                  v = e.getAttribute("data-mce-" + n);
4036  
4037                  if (v)
4038                      return v;
4039              }
4040  
4041              if (isIE && t.props[n]) {
4042                  v = e[t.props[n]];
4043                  v = v && v.nodeValue ? v.nodeValue : v;
4044              }
4045  
4046              if (!v)
4047                  v = e.getAttribute(n, 2);
4048  
4049              // Check boolean attribs
4050              if (/^(checked|compact|declare|defer|disabled|ismap|multiple|nohref|noshade|nowrap|readonly|selected)$/.test(n)) {
4051                  if (e[t.props[n]] === true && v === '')
4052                      return n;
4053  
4054                  return v ? n : '';
4055              }
4056  
4057              // Inner input elements will override attributes on form elements
4058              if (e.nodeName === "FORM" && e.getAttributeNode(n))
4059                  return e.getAttributeNode(n).nodeValue;
4060  
4061              if (n === 'style') {
4062                  v = v || e.style.cssText;
4063  
4064                  if (v) {
4065                      v = t.serializeStyle(t.parseStyle(v), e.nodeName);
4066  
4067                      if (t.settings.keep_values && !t._isRes(v))
4068                          e.setAttribute('data-mce-style', v);
4069                  }
4070              }
4071  
4072              // Remove Apple and WebKit stuff
4073              if (isWebKit && n === "class" && v)
4074                  v = v.replace(/(apple|webkit)\-[a-z\-]+/gi, '');
4075  
4076              // Handle IE issues
4077              if (isIE) {
4078                  switch (n) {
4079                      case 'rowspan':
4080                      case 'colspan':
4081                          // IE returns 1 as default value
4082                          if (v === 1)
4083                              v = '';
4084  
4085                          break;
4086  
4087                      case 'size':
4088                          // IE returns +0 as default value for size
4089                          if (v === '+0' || v === 20 || v === 0)
4090                              v = '';
4091  
4092                          break;
4093  
4094                      case 'width':
4095                      case 'height':
4096                      case 'vspace':
4097                      case 'checked':
4098                      case 'disabled':
4099                      case 'readonly':
4100                          if (v === 0)
4101                              v = '';
4102  
4103                          break;
4104  
4105                      case 'hspace':
4106                          // IE returns -1 as default value
4107                          if (v === -1)
4108                              v = '';
4109  
4110                          break;
4111  
4112                      case 'maxlength':
4113                      case 'tabindex':
4114                          // IE returns default value
4115                          if (v === 32768 || v === 2147483647 || v === '32768')
4116                              v = '';
4117  
4118                          break;
4119  
4120                      case 'multiple':
4121                      case 'compact':
4122                      case 'noshade':
4123                      case 'nowrap':
4124                          if (v === 65535)
4125                              return n;
4126  
4127                          return dv;
4128  
4129                      case 'shape':
4130                          v = v.toLowerCase();
4131                          break;
4132  
4133                      default:
4134                          // IE has odd anonymous function for event attributes
4135                          if (n.indexOf('on') === 0 && v)
4136                              v = tinymce._replace(/^function\s+\w+\(\)\s+\{\s+(.*)\s+\}$/, '$1', '' + v);
4137                  }
4138              }
4139  
4140              return (v !== undef && v !== null && v !== '') ? '' + v : dv;
4141          },
4142  
4143          getPos : function(n, ro) {
4144              var t = this, x = 0, y = 0, e, d = t.doc, r;
4145  
4146              n = t.get(n);
4147              ro = ro || d.body;
4148  
4149              if (n) {
4150                  // Use getBoundingClientRect if it exists since it's faster than looping offset nodes
4151                  if (n.getBoundingClientRect) {
4152                      n = n.getBoundingClientRect();
4153                      e = t.boxModel ? d.documentElement : d.body;
4154  
4155                      // Add scroll offsets from documentElement or body since IE with the wrong box model will use d.body and so do WebKit
4156                      // Also remove the body/documentelement clientTop/clientLeft on IE 6, 7 since they offset the position
4157                      x = n.left + (d.documentElement.scrollLeft || d.body.scrollLeft) - e.clientTop;
4158                      y = n.top + (d.documentElement.scrollTop || d.body.scrollTop) - e.clientLeft;
4159  
4160                      return {x : x, y : y};
4161                  }
4162  
4163                  r = n;
4164                  while (r && r != ro && r.nodeType) {
4165                      x += r.offsetLeft || 0;
4166                      y += r.offsetTop || 0;
4167                      r = r.offsetParent;
4168                  }
4169  
4170                  r = n.parentNode;
4171                  while (r && r != ro && r.nodeType) {
4172                      x -= r.scrollLeft || 0;
4173                      y -= r.scrollTop || 0;
4174                      r = r.parentNode;
4175                  }
4176              }
4177  
4178              return {x : x, y : y};
4179          },
4180  
4181          parseStyle : function(st) {
4182              return this.styles.parse(st);
4183          },
4184  
4185          serializeStyle : function(o, name) {
4186              return this.styles.serialize(o, name);
4187          },
4188  
4189          loadCSS : function(u) {
4190              var t = this, d = t.doc, head;
4191  
4192              if (!u)
4193                  u = '';
4194  
4195              head = t.select('head')[0];
4196  
4197              each(u.split(','), function(u) {
4198                  var link;
4199  
4200                  if (t.files[u])
4201                      return;
4202  
4203                  t.files[u] = true;
4204                  link = t.create('link', {rel : 'stylesheet', href : tinymce._addVer(u)});
4205  
4206                  // IE 8 has a bug where dynamically loading stylesheets would produce a 1 item remaining bug
4207                  // This fix seems to resolve that issue by realcing the document ones a stylesheet finishes loading
4208                  // It's ugly but it seems to work fine.
4209                  if (isIE && d.documentMode && d.recalc) {
4210                      link.onload = function() {
4211                          if (d.recalc)
4212                              d.recalc();
4213  
4214                          link.onload = null;
4215                      };
4216                  }
4217  
4218                  head.appendChild(link);
4219              });
4220          },
4221  
4222          addClass : function(e, c) {
4223              return this.run(e, function(e) {
4224                  var o;
4225  
4226                  if (!c)
4227                      return 0;
4228  
4229                  if (this.hasClass(e, c))
4230                      return e.className;
4231  
4232                  o = this.removeClass(e, c);
4233  
4234                  return e.className = (o != '' ? (o + ' ') : '') + c;
4235              });
4236          },
4237  
4238          removeClass : function(e, c) {
4239              var t = this, re;
4240  
4241              return t.run(e, function(e) {
4242                  var v;
4243  
4244                  if (t.hasClass(e, c)) {
4245                      if (!re)
4246                          re = new RegExp("(^|\\s+)" + c + "(\\s+|$)", "g");
4247  
4248                      v = e.className.replace(re, ' ');
4249                      v = tinymce.trim(v != ' ' ? v : '');
4250  
4251                      e.className = v;
4252  
4253                      // Empty class attr
4254                      if (!v) {
4255                          e.removeAttribute('class');
4256                          e.removeAttribute('className');
4257                      }
4258  
4259                      return v;
4260                  }
4261  
4262                  return e.className;
4263              });
4264          },
4265  
4266          hasClass : function(n, c) {
4267              n = this.get(n);
4268  
4269              if (!n || !c)
4270                  return false;
4271  
4272              return (' ' + n.className + ' ').indexOf(' ' + c + ' ') !== -1;
4273          },
4274  
4275          show : function(e) {
4276              return this.setStyle(e, 'display', 'block');
4277          },
4278  
4279          hide : function(e) {
4280              return this.setStyle(e, 'display', 'none');
4281          },
4282  
4283          isHidden : function(e) {
4284              e = this.get(e);
4285  
4286              return !e || e.style.display == 'none' || this.getStyle(e, 'display') == 'none';
4287          },
4288  
4289          uniqueId : function(p) {
4290              return (!p ? 'mce_' : p) + (this.counter++);
4291          },
4292  
4293          setHTML : function(element, html) {
4294              var self = this;
4295  
4296              return self.run(element, function(element) {
4297                  if (isIE) {
4298                      // Remove all child nodes, IE keeps empty text nodes in DOM
4299                      while (element.firstChild)
4300                          element.removeChild(element.firstChild);
4301  
4302                      try {
4303                          // IE will remove comments from the beginning
4304                          // unless you padd the contents with something
4305                          element.innerHTML = '<br />' + html;
4306                          element.removeChild(element.firstChild);
4307                      } catch (ex) {
4308                          // IE sometimes produces an unknown runtime error on innerHTML if it's an block element within a block element for example a div inside a p
4309                          // This seems to fix this problem
4310  
4311                          // Create new div with HTML contents and a BR infront to keep comments
4312                          element = self.create('div');
4313                          element.innerHTML = '<br />' + html;
4314  
4315                          // Add all children from div to target
4316                          each (element.childNodes, function(node, i) {
4317                              // Skip br element
4318                              if (i)
4319                                  element.appendChild(node);
4320                          });
4321                      }
4322                  } else
4323                      element.innerHTML = html;
4324  
4325                  return html;
4326              });
4327          },
4328  
4329          getOuterHTML : function(elm) {
4330              var doc, self = this;
4331  
4332              elm = self.get(elm);
4333  
4334              if (!elm)
4335                  return null;
4336  
4337              if (elm.nodeType === 1 && self.hasOuterHTML)
4338                  return elm.outerHTML;
4339  
4340              doc = (elm.ownerDocument || self.doc).createElement("body");
4341              doc.appendChild(elm.cloneNode(true));
4342  
4343              return doc.innerHTML;
4344          },
4345  
4346          setOuterHTML : function(e, h, d) {
4347              var t = this;
4348  
4349  			function setHTML(e, h, d) {
4350                  var n, tp;
4351  
4352                  tp = d.createElement("body");
4353                  tp.innerHTML = h;
4354  
4355                  n = tp.lastChild;
4356                  while (n) {
4357                      t.insertAfter(n.cloneNode(true), e);
4358                      n = n.previousSibling;
4359                  }
4360  
4361                  t.remove(e);
4362              };
4363  
4364              return this.run(e, function(e) {
4365                  e = t.get(e);
4366  
4367                  // Only set HTML on elements
4368                  if (e.nodeType == 1) {
4369                      d = d || e.ownerDocument || t.doc;
4370  
4371                      if (isIE) {
4372                          try {
4373                              // Try outerHTML for IE it sometimes produces an unknown runtime error
4374                              if (isIE && e.nodeType == 1)
4375                                  e.outerHTML = h;
4376                              else
4377                                  setHTML(e, h, d);
4378                          } catch (ex) {
4379                              // Fix for unknown runtime error
4380                              setHTML(e, h, d);
4381                          }
4382                      } else
4383                          setHTML(e, h, d);
4384                  }
4385              });
4386          },
4387  
4388          decode : Entities.decode,
4389  
4390          encode : Entities.encodeAllRaw,
4391  
4392          insertAfter : function(node, reference_node) {
4393              reference_node = this.get(reference_node);
4394  
4395              return this.run(node, function(node) {
4396                  var parent, nextSibling;
4397  
4398                  parent = reference_node.parentNode;
4399                  nextSibling = reference_node.nextSibling;
4400  
4401                  if (nextSibling)
4402                      parent.insertBefore(node, nextSibling);
4403                  else
4404                      parent.appendChild(node);
4405  
4406                  return node;
4407              });
4408          },
4409  
4410          isBlock : function(node) {
4411              var type = node.nodeType;
4412  
4413              // If it's a node then check the type and use the nodeName
4414              if (type)
4415                  return !!(type === 1 && blockElementsMap[node.nodeName]);
4416  
4417              return !!blockElementsMap[node];
4418          },
4419  
4420          replace : function(n, o, k) {
4421              var t = this;
4422  
4423              if (is(o, 'array'))
4424                  n = n.cloneNode(true);
4425  
4426              return t.run(o, function(o) {
4427                  if (k) {
4428                      each(tinymce.grep(o.childNodes), function(c) {
4429                          n.appendChild(c);
4430                      });
4431                  }
4432  
4433                  return o.parentNode.replaceChild(n, o);
4434              });
4435          },
4436  
4437          rename : function(elm, name) {
4438              var t = this, newElm;
4439  
4440              if (elm.nodeName != name.toUpperCase()) {
4441                  // Rename block element
4442                  newElm = t.create(name);
4443  
4444                  // Copy attribs to new block
4445                  each(t.getAttribs(elm), function(attr_node) {
4446                      t.setAttrib(newElm, attr_node.nodeName, t.getAttrib(elm, attr_node.nodeName));
4447                  });
4448  
4449                  // Replace block
4450                  t.replace(newElm, elm, 1);
4451              }
4452  
4453              return newElm || elm;
4454          },
4455  
4456          findCommonAncestor : function(a, b) {
4457              var ps = a, pe;
4458  
4459              while (ps) {
4460                  pe = b;
4461  
4462                  while (pe && ps != pe)
4463                      pe = pe.parentNode;
4464  
4465                  if (ps == pe)
4466                      break;
4467  
4468                  ps = ps.parentNode;
4469              }
4470  
4471              if (!ps && a.ownerDocument)
4472                  return a.ownerDocument.documentElement;
4473  
4474              return ps;
4475          },
4476  
4477          toHex : function(s) {
4478              var c = /^\s*rgb\s*?\(\s*?([0-9]+)\s*?,\s*?([0-9]+)\s*?,\s*?([0-9]+)\s*?\)\s*$/i.exec(s);
4479  
4480  			function hex(s) {
4481                  s = parseInt(s).toString(16);
4482  
4483                  return s.length > 1 ? s : '0' + s; // 0 -> 00
4484              };
4485  
4486              if (c) {
4487                  s = '#' + hex(c[1]) + hex(c[2]) + hex(c[3]);
4488  
4489                  return s;
4490              }
4491  
4492              return s;
4493          },
4494  
4495          getClasses : function() {
4496              var t = this, cl = [], i, lo = {}, f = t.settings.class_filter, ov;
4497  
4498              if (t.classes)
4499                  return t.classes;
4500  
4501  			function addClasses(s) {
4502                  // IE style imports
4503                  each(s.imports, function(r) {
4504                      addClasses(r);
4505                  });
4506  
4507                  each(s.cssRules || s.rules, function(r) {
4508                      // Real type or fake it on IE
4509                      switch (r.type || 1) {
4510                          // Rule
4511                          case 1:
4512                              if (r.selectorText) {
4513                                  each(r.selectorText.split(','), function(v) {
4514                                      v = v.replace(/^\s*|\s*$|^\s\./g, "");
4515  
4516                                      // Is internal or it doesn't contain a class
4517                                      if (/\.mce/.test(v) || !/\.[\w\-]+$/.test(v))
4518                                          return;
4519  
4520                                      // Remove everything but class name
4521                                      ov = v;
4522                                      v = tinymce._replace(/.*\.([a-z0-9_\-]+).*/i, '$1', v);
4523  
4524                                      // Filter classes
4525                                      if (f && !(v = f(v, ov)))
4526                                          return;
4527  
4528                                      if (!lo[v]) {
4529                                          cl.push({'class' : v});
4530                                          lo[v] = 1;
4531                                      }
4532                                  });
4533                              }
4534                              break;
4535  
4536                          // Import
4537                          case 3:
4538                              addClasses(r.styleSheet);
4539                              break;
4540                      }
4541                  });
4542              };
4543  
4544              try {
4545                  each(t.doc.styleSheets, addClasses);
4546              } catch (ex) {
4547                  // Ignore
4548              }
4549  
4550              if (cl.length > 0)
4551                  t.classes = cl;
4552  
4553              return cl;
4554          },
4555  
4556          run : function(e, f, s) {
4557              var t = this, o;
4558  
4559              if (t.doc && typeof(e) === 'string')
4560                  e = t.get(e);
4561  
4562              if (!e)
4563                  return false;
4564  
4565              s = s || this;
4566              if (!e.nodeType && (e.length || e.length === 0)) {
4567                  o = [];
4568  
4569                  each(e, function(e, i) {
4570                      if (e) {
4571                          if (typeof(e) == 'string')
4572                              e = t.doc.getElementById(e);
4573  
4574                          o.push(f.call(s, e, i));
4575                      }
4576                  });
4577  
4578                  return o;
4579              }
4580  
4581              return f.call(s, e);
4582          },
4583  
4584          getAttribs : function(n) {
4585              var o;
4586  
4587              n = this.get(n);
4588  
4589              if (!n)
4590                  return [];
4591  
4592              if (isIE) {
4593                  o = [];
4594  
4595                  // Object will throw exception in IE
4596                  if (n.nodeName == 'OBJECT')
4597                      return n.attributes;
4598  
4599                  // IE doesn't keep the selected attribute if you clone option elements
4600                  if (n.nodeName === 'OPTION' && this.getAttrib(n, 'selected'))
4601                      o.push({specified : 1, nodeName : 'selected'});
4602  
4603                  // It's crazy that this is faster in IE but it's because it returns all attributes all the time
4604                  n.cloneNode(false).outerHTML.replace(/<\/?[\w:\-]+ ?|=[\"][^\"]+\"|=\'[^\']+\'|=[\w\-]+|>/gi, '').replace(/[\w:\-]+/gi, function(a) {
4605                      o.push({specified : 1, nodeName : a});
4606                  });
4607  
4608                  return o;
4609              }
4610  
4611              return n.attributes;
4612          },
4613  
4614          isEmpty : function(node, elements) {
4615              var self = this, i, attributes, type, walker, name, parentNode;
4616  
4617              node = node.firstChild;
4618              if (node) {
4619                  walker = new tinymce.dom.TreeWalker(node);
4620                  elements = elements || self.schema ? self.schema.getNonEmptyElements() : null;
4621  
4622                  do {
4623                      type = node.nodeType;
4624  
4625                      if (type === 1) {
4626                          // Ignore bogus elements
4627                          if (node.getAttribute('data-mce-bogus'))
4628                              continue;
4629  
4630                          // Keep empty elements like <img />
4631                          name = node.nodeName.toLowerCase();
4632                          if (elements && elements[name]) {
4633                              // Ignore single BR elements in blocks like <p><br /></p>
4634                              parentNode = node.parentNode;
4635                              if (name === 'br' && self.isBlock(parentNode) && parentNode.firstChild === node && parentNode.lastChild === node) {
4636                                  continue;
4637                              }
4638  
4639                              return false;
4640                          }
4641  
4642                          // Keep elements with data-bookmark attributes or name attribute like <a name="1"></a>
4643                          attributes = self.getAttribs(node);
4644                          i = node.attributes.length;
4645                          while (i--) {
4646                              name = node.attributes[i].nodeName;
4647                              if (name === "name" || name === 'data-mce-bookmark')
4648                                  return false;
4649                          }
4650                      }
4651  
4652                      // Keep non whitespace text nodes
4653                      if ((type === 3 && !whiteSpaceRegExp.test(node.nodeValue)))
4654                          return false;
4655                  } while (node = walker.next());
4656              }
4657  
4658              return true;
4659          },
4660  
4661          destroy : function(s) {
4662              var t = this;
4663  
4664              if (t.events)
4665                  t.events.destroy();
4666  
4667              t.win = t.doc = t.root = t.events = null;
4668  
4669              // Manual destroy then remove unload handler
4670              if (!s)
4671                  tinymce.removeUnload(t.destroy);
4672          },
4673  
4674          createRng : function() {
4675              var d = this.doc;
4676  
4677              return d.createRange ? d.createRange() : new tinymce.dom.Range(this);
4678          },
4679  
4680          nodeIndex : function(node, normalized) {
4681              var idx = 0, lastNodeType, lastNode, nodeType;
4682  
4683              if (node) {
4684                  for (lastNodeType = node.nodeType, node = node.previousSibling, lastNode = node; node; node = node.previousSibling) {
4685                      nodeType = node.nodeType;
4686  
4687                      // Normalize text nodes
4688                      if (normalized && nodeType == 3) {
4689                          if (nodeType == lastNodeType || !node.nodeValue.length)
4690                              continue;
4691                      }
4692                      idx++;
4693                      lastNodeType = nodeType;
4694                  }
4695              }
4696  
4697              return idx;
4698          },
4699  
4700          split : function(pe, e, re) {
4701              var t = this, r = t.createRng(), bef, aft, pa;
4702  
4703              // W3C valid browsers tend to leave empty nodes to the left/right side of the contents, this makes sense
4704              // but we don't want that in our code since it serves no purpose for the end user
4705              // For example if this is chopped:
4706              //   <p>text 1<span><b>CHOP</b></span>text 2</p>
4707              // would produce:
4708              //   <p>text 1<span></span></p><b>CHOP</b><p><span></span>text 2</p>
4709              // this function will then trim of empty edges and produce:
4710              //   <p>text 1</p><b>CHOP</b><p>text 2</p>
4711  			function trim(node) {
4712                  var i, children = node.childNodes, type = node.nodeType;
4713  
4714  				function surroundedBySpans(node) {
4715                      var previousIsSpan = node.previousSibling && node.previousSibling.nodeName == 'SPAN';
4716                      var nextIsSpan = node.nextSibling && node.nextSibling.nodeName == 'SPAN';
4717                      return previousIsSpan && nextIsSpan;
4718                  }
4719  
4720                  if (type == 1 && node.getAttribute('data-mce-type') == 'bookmark')
4721                      return;
4722  
4723                  for (i = children.length - 1; i >= 0; i--)
4724                      trim(children[i]);
4725  
4726                  if (type != 9) {
4727                      // Keep non whitespace text nodes
4728                      if (type == 3 && node.nodeValue.length > 0) {
4729                          // If parent element isn't a block or there isn't any useful contents for example "<p>   </p>"
4730                          // Also keep text nodes with only spaces if surrounded by spans.
4731                          // eg. "<p><span>a</span> <span>b</span></p>" should keep space between a and b
4732                          var trimmedLength = tinymce.trim(node.nodeValue).length;
4733                          if (!t.isBlock(node.parentNode) || trimmedLength > 0 || trimmedLength == 0 && surroundedBySpans(node))
4734                              return;
4735                      } else if (type == 1) {
4736                          // If the only child is a bookmark then move it up
4737                          children = node.childNodes;
4738                          if (children.length == 1 && children[0] && children[0].nodeType == 1 && children[0].getAttribute('data-mce-type') == 'bookmark')
4739                              node.parentNode.insertBefore(children[0], node);
4740  
4741                          // Keep non empty elements or img, hr etc
4742                          if (children.length || /^(br|hr|input|img)$/i.test(node.nodeName))
4743                              return;
4744                      }
4745  
4746                      t.remove(node);
4747                  }
4748  
4749                  return node;
4750              };
4751  
4752              if (pe && e) {
4753                  // Get before chunk
4754                  r.setStart(pe.parentNode, t.nodeIndex(pe));
4755                  r.setEnd(e.parentNode, t.nodeIndex(e));
4756                  bef = r.extractContents();
4757  
4758                  // Get after chunk
4759                  r = t.createRng();
4760                  r.setStart(e.parentNode, t.nodeIndex(e) + 1);
4761                  r.setEnd(pe.parentNode, t.nodeIndex(pe) + 1);
4762                  aft = r.extractContents();
4763  
4764                  // Insert before chunk
4765                  pa = pe.parentNode;
4766                  pa.insertBefore(trim(bef), pe);
4767  
4768                  // Insert middle chunk
4769                  if (re)
4770                  pa.replaceChild(re, e);
4771              else
4772                  pa.insertBefore(e, pe);
4773  
4774                  // Insert after chunk
4775                  pa.insertBefore(trim(aft), pe);
4776                  t.remove(pe);
4777  
4778                  return re || e;
4779              }
4780          },
4781  
4782          bind : function(target, name, func, scope) {
4783              var t = this;
4784  
4785              if (!t.events)
4786                  t.events = new tinymce.dom.EventUtils();
4787  
4788              return t.events.add(target, name, func, scope || this);
4789          },
4790  
4791          unbind : function(target, name, func) {
4792              var t = this;
4793  
4794              if (!t.events)
4795                  t.events = new tinymce.dom.EventUtils();
4796  
4797              return t.events.remove(target, name, func);
4798          },
4799  
4800  
4801          _findSib : function(node, selector, name) {
4802              var t = this, f = selector;
4803  
4804              if (node) {
4805                  // If expression make a function of it using is
4806                  if (is(f, 'string')) {
4807                      f = function(node) {
4808                          return t.is(node, selector);
4809                      };
4810                  }
4811  
4812                  // Loop all siblings
4813                  for (node = node[name]; node; node = node[name]) {
4814                      if (f(node))
4815                          return node;
4816                  }
4817              }
4818  
4819              return null;
4820          },
4821  
4822          _isRes : function(c) {
4823              // Is live resizble element
4824              return /^(top|left|bottom|right|width|height)/i.test(c) || /;\s*(top|left|bottom|right|width|height)/i.test(c);
4825          }
4826  
4827          /*
4828          walk : function(n, f, s) {
4829              var d = this.doc, w;
4830  
4831              if (d.createTreeWalker) {
4832                  w = d.createTreeWalker(n, NodeFilter.SHOW_TEXT, null, false);
4833  
4834                  while ((n = w.nextNode()) != null)
4835                      f.call(s || this, n);
4836              } else
4837                  tinymce.walk(n, f, 'childNodes', s);
4838          }
4839          */
4840  
4841          /*
4842          toRGB : function(s) {
4843              var c = /^\s*?#([0-9A-F]{2})([0-9A-F]{1,2})([0-9A-F]{2})?\s*?$/.exec(s);
4844  
4845              if (c) {
4846                  // #FFF -> #FFFFFF
4847                  if (!is(c[3]))
4848                      c[3] = c[2] = c[1];
4849  
4850                  return "rgb(" + parseInt(c[1], 16) + "," + parseInt(c[2], 16) + "," + parseInt(c[3], 16) + ")";
4851              }
4852  
4853              return s;
4854          }
4855          */
4856      });
4857  
4858      tinymce.DOM = new tinymce.dom.DOMUtils(document, {process_html : 0});
4859  })(tinymce);
4860  
4861  (function(ns) {
4862      // Range constructor
4863  	function Range(dom) {
4864          var t = this,
4865              doc = dom.doc,
4866              EXTRACT = 0,
4867              CLONE = 1,
4868              DELETE = 2,
4869              TRUE = true,
4870              FALSE = false,
4871              START_OFFSET = 'startOffset',
4872              START_CONTAINER = 'startContainer',
4873              END_CONTAINER = 'endContainer',
4874              END_OFFSET = 'endOffset',
4875              extend = tinymce.extend,
4876              nodeIndex = dom.nodeIndex;
4877  
4878          extend(t, {
4879              // Inital states
4880              startContainer : doc,
4881              startOffset : 0,
4882              endContainer : doc,
4883              endOffset : 0,
4884              collapsed : TRUE,
4885              commonAncestorContainer : doc,
4886  
4887              // Range constants
4888              START_TO_START : 0,
4889              START_TO_END : 1,
4890              END_TO_END : 2,
4891              END_TO_START : 3,
4892  
4893              // Public methods
4894              setStart : setStart,
4895              setEnd : setEnd,
4896              setStartBefore : setStartBefore,
4897              setStartAfter : setStartAfter,
4898              setEndBefore : setEndBefore,
4899              setEndAfter : setEndAfter,
4900              collapse : collapse,
4901              selectNode : selectNode,
4902              selectNodeContents : selectNodeContents,
4903              compareBoundaryPoints : compareBoundaryPoints,
4904              deleteContents : deleteContents,
4905              extractContents : extractContents,
4906              cloneContents : cloneContents,
4907              insertNode : insertNode,
4908              surroundContents : surroundContents,
4909              cloneRange : cloneRange
4910          });
4911  
4912  		function setStart(n, o) {
4913              _setEndPoint(TRUE, n, o);
4914          };
4915  
4916  		function setEnd(n, o) {
4917              _setEndPoint(FALSE, n, o);
4918          };
4919  
4920  		function setStartBefore(n) {
4921              setStart(n.parentNode, nodeIndex(n));
4922          };
4923  
4924  		function setStartAfter(n) {
4925              setStart(n.parentNode, nodeIndex(n) + 1);
4926          };
4927  
4928  		function setEndBefore(n) {
4929              setEnd(n.parentNode, nodeIndex(n));
4930          };
4931  
4932  		function setEndAfter(n) {
4933              setEnd(n.parentNode, nodeIndex(n) + 1);
4934          };
4935  
4936  		function collapse(ts) {
4937              if (ts) {
4938                  t[END_CONTAINER] = t[START_CONTAINER];
4939                  t[END_OFFSET] = t[START_OFFSET];
4940              } else {
4941                  t[START_CONTAINER] = t[END_CONTAINER];
4942                  t[START_OFFSET] = t[END_OFFSET];
4943              }
4944  
4945              t.collapsed = TRUE;
4946          };
4947  
4948  		function selectNode(n) {
4949              setStartBefore(n);
4950              setEndAfter(n);
4951          };
4952  
4953  		function selectNodeContents(n) {
4954              setStart(n, 0);
4955              setEnd(n, n.nodeType === 1 ? n.childNodes.length : n.nodeValue.length);
4956          };
4957  
4958  		function compareBoundaryPoints(h, r) {
4959              var sc = t[START_CONTAINER], so = t[START_OFFSET], ec = t[END_CONTAINER], eo = t[END_OFFSET],
4960              rsc = r.startContainer, rso = r.startOffset, rec = r.endContainer, reo = r.endOffset;
4961  
4962              // Check START_TO_START
4963              if (h === 0)
4964                  return _compareBoundaryPoints(sc, so, rsc, rso);
4965      
4966              // Check START_TO_END
4967              if (h === 1)
4968                  return _compareBoundaryPoints(ec, eo, rsc, rso);
4969      
4970              // Check END_TO_END
4971              if (h === 2)
4972                  return _compareBoundaryPoints(ec, eo, rec, reo);
4973      
4974              // Check END_TO_START
4975              if (h === 3) 
4976                  return _compareBoundaryPoints(sc, so, rec, reo);
4977          };
4978  
4979  		function deleteContents() {
4980              _traverse(DELETE);
4981          };
4982  
4983  		function extractContents() {
4984              return _traverse(EXTRACT);
4985          };
4986  
4987  		function cloneContents() {
4988              return _traverse(CLONE);
4989          };
4990  
4991  		function insertNode(n) {
4992              var startContainer = this[START_CONTAINER],
4993                  startOffset = this[START_OFFSET], nn, o;
4994  
4995              // Node is TEXT_NODE or CDATA
4996              if ((startContainer.nodeType === 3 || startContainer.nodeType === 4) && startContainer.nodeValue) {
4997                  if (!startOffset) {
4998                      // At the start of text
4999                      startContainer.parentNode.insertBefore(n, startContainer);
5000                  } else if (startOffset >= startContainer.nodeValue.length) {
5001                      // At the end of text
5002                      dom.insertAfter(n, startContainer);
5003                  } else {
5004                      // Middle, need to split
5005                      nn = startContainer.splitText(startOffset);
5006                      startContainer.parentNode.insertBefore(n, nn);
5007                  }
5008              } else {
5009                  // Insert element node
5010                  if (startContainer.childNodes.length > 0)
5011                      o = startContainer.childNodes[startOffset];
5012  
5013                  if (o)
5014                      startContainer.insertBefore(n, o);
5015                  else
5016                      startContainer.appendChild(n);
5017              }
5018          };
5019  
5020  		function surroundContents(n) {
5021              var f = t.extractContents();
5022  
5023              t.insertNode(n);
5024              n.appendChild(f);
5025              t.selectNode(n);
5026          };
5027  
5028  		function cloneRange() {
5029              return extend(new Range(dom), {
5030                  startContainer : t[START_CONTAINER],
5031                  startOffset : t[START_OFFSET],
5032                  endContainer : t[END_CONTAINER],
5033                  endOffset : t[END_OFFSET],
5034                  collapsed : t.collapsed,
5035                  commonAncestorContainer : t.commonAncestorContainer
5036              });
5037          };
5038  
5039          // Private methods
5040  
5041  		function _getSelectedNode(container, offset) {
5042              var child;
5043  
5044              if (container.nodeType == 3 /* TEXT_NODE */)
5045                  return container;
5046  
5047              if (offset < 0)
5048                  return container;
5049  
5050              child = container.firstChild;
5051              while (child && offset > 0) {
5052                  --offset;
5053                  child = child.nextSibling;
5054              }
5055  
5056              if (child)
5057                  return child;
5058  
5059              return container;
5060          };
5061  
5062  		function _isCollapsed() {
5063              return (t[START_CONTAINER] == t[END_CONTAINER] && t[START_OFFSET] == t[END_OFFSET]);
5064          };
5065  
5066  		function _compareBoundaryPoints(containerA, offsetA, containerB, offsetB) {
5067              var c, offsetC, n, cmnRoot, childA, childB;
5068              
5069              // In the first case the boundary-points have the same container. A is before B
5070              // if its offset is less than the offset of B, A is equal to B if its offset is
5071              // equal to the offset of B, and A is after B if its offset is greater than the
5072              // offset of B.
5073              if (containerA == containerB) {
5074                  if (offsetA == offsetB)
5075                      return 0; // equal
5076  
5077                  if (offsetA < offsetB)
5078                      return -1; // before
5079  
5080                  return 1; // after
5081              }
5082  
5083              // In the second case a child node C of the container of A is an ancestor
5084              // container of B. In this case, A is before B if the offset of A is less than or
5085              // equal to the index of the child node C and A is after B otherwise.
5086              c = containerB;
5087              while (c && c.parentNode != containerA)
5088                  c = c.parentNode;
5089  
5090              if (c) {
5091                  offsetC = 0;
5092                  n = containerA.firstChild;
5093  
5094                  while (n != c && offsetC < offsetA) {
5095                      offsetC++;
5096                      n = n.nextSibling;
5097                  }
5098  
5099                  if (offsetA <= offsetC)
5100                      return -1; // before
5101  
5102                  return 1; // after
5103              }
5104  
5105              // In the third case a child node C of the container of B is an ancestor container
5106              // of A. In this case, A is before B if the index of the child node C is less than
5107              // the offset of B and A is after B otherwise.
5108              c = containerA;
5109              while (c && c.parentNode != containerB) {
5110                  c = c.parentNode;
5111              }
5112  
5113              if (c) {
5114                  offsetC = 0;
5115                  n = containerB.firstChild;
5116  
5117                  while (n != c && offsetC < offsetB) {
5118                      offsetC++;
5119                      n = n.nextSibling;
5120                  }
5121  
5122                  if (offsetC < offsetB)
5123                      return -1; // before
5124  
5125                  return 1; // after
5126              }
5127  
5128              // In the fourth case, none of three other cases hold: the containers of A and B
5129              // are siblings or descendants of sibling nodes. In this case, A is before B if
5130              // the container of A is before the container of B in a pre-order traversal of the
5131              // Ranges' context tree and A is after B otherwise.
5132              cmnRoot = dom.findCommonAncestor(containerA, containerB);
5133              childA = containerA;
5134  
5135              while (childA && childA.parentNode != cmnRoot)
5136                  childA = childA.parentNode;
5137  
5138              if (!childA)
5139                  childA = cmnRoot;
5140  
5141              childB = containerB;
5142              while (childB && childB.parentNode != cmnRoot)
5143                  childB = childB.parentNode;
5144  
5145              if (!childB)
5146                  childB = cmnRoot;
5147  
5148              if (childA == childB)
5149                  return 0; // equal
5150  
5151              n = cmnRoot.firstChild;
5152              while (n) {
5153                  if (n == childA)
5154                      return -1; // before
5155  
5156                  if (n == childB)
5157                      return 1; // after
5158  
5159                  n = n.nextSibling;
5160              }
5161          };
5162  
5163  		function _setEndPoint(st, n, o) {
5164              var ec, sc;
5165  
5166              if (st) {
5167                  t[START_CONTAINER] = n;
5168                  t[START_OFFSET] = o;
5169              } else {
5170                  t[END_CONTAINER] = n;
5171                  t[END_OFFSET] = o;
5172              }
5173  
5174              // If one boundary-point of a Range is set to have a root container
5175              // other than the current one for the Range, the Range is collapsed to
5176              // the new position. This enforces the restriction that both boundary-
5177              // points of a Range must have the same root container.
5178              ec = t[END_CONTAINER];
5179              while (ec.parentNode)
5180                  ec = ec.parentNode;
5181  
5182              sc = t[START_CONTAINER];
5183              while (sc.parentNode)
5184                  sc = sc.parentNode;
5185  
5186              if (sc == ec) {
5187                  // The start position of a Range is guaranteed to never be after the
5188                  // end position. To enforce this restriction, if the start is set to
5189                  // be at a position after the end, the Range is collapsed to that
5190                  // position.
5191                  if (_compareBoundaryPoints(t[START_CONTAINER], t[START_OFFSET], t[END_CONTAINER], t[END_OFFSET]) > 0)
5192                      t.collapse(st);
5193              } else
5194                  t.collapse(st);
5195  
5196              t.collapsed = _isCollapsed();
5197              t.commonAncestorContainer = dom.findCommonAncestor(t[START_CONTAINER], t[END_CONTAINER]);
5198          };
5199  
5200  		function _traverse(how) {
5201              var c, endContainerDepth = 0, startContainerDepth = 0, p, depthDiff, startNode, endNode, sp, ep;
5202  
5203              if (t[START_CONTAINER] == t[END_CONTAINER])
5204                  return _traverseSameContainer(how);
5205  
5206              for (c = t[END_CONTAINER], p = c.parentNode; p; c = p, p = p.parentNode) {
5207                  if (p == t[START_CONTAINER])
5208                      return _traverseCommonStartContainer(c, how);
5209  
5210                  ++endContainerDepth;
5211              }
5212  
5213              for (c = t[START_CONTAINER], p = c.parentNode; p; c = p, p = p.parentNode) {
5214                  if (p == t[END_CONTAINER])
5215                      return _traverseCommonEndContainer(c, how);
5216  
5217                  ++startContainerDepth;
5218              }
5219  
5220              depthDiff = startContainerDepth - endContainerDepth;
5221  
5222              startNode = t[START_CONTAINER];
5223              while (depthDiff > 0) {
5224                  startNode = startNode.parentNode;
5225                  depthDiff--;
5226              }
5227  
5228              endNode = t[END_CONTAINER];
5229              while (depthDiff < 0) {
5230                  endNode = endNode.parentNode;
5231                  depthDiff++;
5232              }
5233  
5234              // ascend the ancestor hierarchy until we have a common parent.
5235              for (sp = startNode.parentNode, ep = endNode.parentNode; sp != ep; sp = sp.parentNode, ep = ep.parentNode) {
5236                  startNode = sp;
5237                  endNode = ep;
5238              }
5239  
5240              return _traverseCommonAncestors(startNode, endNode, how);
5241          };
5242  
5243  		 function _traverseSameContainer(how) {
5244              var frag, s, sub, n, cnt, sibling, xferNode;
5245  
5246              if (how != DELETE)
5247                  frag = doc.createDocumentFragment();
5248  
5249              // If selection is empty, just return the fragment
5250              if (t[START_OFFSET] == t[END_OFFSET])
5251                  return frag;
5252  
5253              // Text node needs special case handling
5254              if (t[START_CONTAINER].nodeType == 3 /* TEXT_NODE */) {
5255                  // get the substring
5256                  s = t[START_CONTAINER].nodeValue;
5257                  sub = s.substring(t[START_OFFSET], t[END_OFFSET]);
5258  
5259                  // set the original text node to its new value
5260                  if (how != CLONE) {
5261                      t[START_CONTAINER].deleteData(t[START_OFFSET], t[END_OFFSET] - t[START_OFFSET]);
5262  
5263                      // Nothing is partially selected, so collapse to start point
5264                      t.collapse(TRUE);
5265                  }
5266  
5267                  if (how == DELETE)
5268                      return;
5269  
5270                  frag.appendChild(doc.createTextNode(sub));
5271                  return frag;
5272              }
5273  
5274              // Copy nodes between the start/end offsets.
5275              n = _getSelectedNode(t[START_CONTAINER], t[START_OFFSET]);
5276              cnt = t[END_OFFSET] - t[START_OFFSET];
5277  
5278              while (cnt > 0) {
5279                  sibling = n.nextSibling;
5280                  xferNode = _traverseFullySelected(n, how);
5281  
5282                  if (frag)
5283                      frag.appendChild( xferNode );
5284  
5285                  --cnt;
5286                  n = sibling;
5287              }
5288  
5289              // Nothing is partially selected, so collapse to start point
5290              if (how != CLONE)
5291                  t.collapse(TRUE);
5292  
5293              return frag;
5294          };
5295  
5296  		function _traverseCommonStartContainer(endAncestor, how) {
5297              var frag, n, endIdx, cnt, sibling, xferNode;
5298  
5299              if (how != DELETE)
5300                  frag = doc.createDocumentFragment();
5301  
5302              n = _traverseRightBoundary(endAncestor, how);
5303  
5304              if (frag)
5305                  frag.appendChild(n);
5306  
5307              endIdx = nodeIndex(endAncestor);
5308              cnt = endIdx - t[START_OFFSET];
5309  
5310              if (cnt <= 0) {
5311                  // Collapse to just before the endAncestor, which
5312                  // is partially selected.
5313                  if (how != CLONE) {
5314                      t.setEndBefore(endAncestor);
5315                      t.collapse(FALSE);
5316                  }
5317  
5318                  return frag;
5319              }
5320  
5321              n = endAncestor.previousSibling;
5322              while (cnt > 0) {
5323                  sibling = n.previousSibling;
5324                  xferNode = _traverseFullySelected(n, how);
5325  
5326                  if (frag)
5327                      frag.insertBefore(xferNode, frag.firstChild);
5328  
5329                  --cnt;
5330                  n = sibling;
5331              }
5332  
5333              // Collapse to just before the endAncestor, which
5334              // is partially selected.
5335              if (how != CLONE) {
5336                  t.setEndBefore(endAncestor);
5337                  t.collapse(FALSE);
5338              }
5339  
5340              return frag;
5341          };
5342  
5343  		function _traverseCommonEndContainer(startAncestor, how) {
5344              var frag, startIdx, n, cnt, sibling, xferNode;
5345  
5346              if (how != DELETE)
5347                  frag = doc.createDocumentFragment();
5348  
5349              n = _traverseLeftBoundary(startAncestor, how);
5350              if (frag)
5351                  frag.appendChild(n);
5352  
5353              startIdx = nodeIndex(startAncestor);
5354              ++startIdx; // Because we already traversed it
5355  
5356              cnt = t[END_OFFSET] - startIdx;
5357              n = startAncestor.nextSibling;
5358              while (cnt > 0) {
5359                  sibling = n.nextSibling;
5360                  xferNode = _traverseFullySelected(n, how);
5361  
5362                  if (frag)
5363                      frag.appendChild(xferNode);
5364  
5365                  --cnt;
5366                  n = sibling;
5367              }
5368  
5369              if (how != CLONE) {
5370                  t.setStartAfter(startAncestor);
5371                  t.collapse(TRUE);
5372              }
5373  
5374              return frag;
5375          };
5376  
5377  		function _traverseCommonAncestors(startAncestor, endAncestor, how) {
5378              var n, frag, commonParent, startOffset, endOffset, cnt, sibling, nextSibling;
5379  
5380              if (how != DELETE)
5381                  frag = doc.createDocumentFragment();
5382  
5383              n = _traverseLeftBoundary(startAncestor, how);
5384              if (frag)
5385                  frag.appendChild(n);
5386  
5387              commonParent = startAncestor.parentNode;
5388              startOffset = nodeIndex(startAncestor);
5389              endOffset = nodeIndex(endAncestor);
5390              ++startOffset;
5391  
5392              cnt = endOffset - startOffset;
5393              sibling = startAncestor.nextSibling;
5394  
5395              while (cnt > 0) {
5396                  nextSibling = sibling.nextSibling;
5397                  n = _traverseFullySelected(sibling, how);
5398  
5399                  if (frag)
5400                      frag.appendChild(n);
5401  
5402                  sibling = nextSibling;
5403                  --cnt;
5404              }
5405  
5406              n = _traverseRightBoundary(endAncestor, how);
5407  
5408              if (frag)
5409                  frag.appendChild(n);
5410  
5411              if (how != CLONE) {
5412                  t.setStartAfter(startAncestor);
5413                  t.collapse(TRUE);
5414              }
5415  
5416              return frag;
5417          };
5418  
5419  		function _traverseRightBoundary(root, how) {
5420              var next = _getSelectedNode(t[END_CONTAINER], t[END_OFFSET] - 1), parent, clonedParent, prevSibling, clonedChild, clonedGrandParent, isFullySelected = next != t[END_CONTAINER];
5421  
5422              if (next == root)
5423                  return _traverseNode(next, isFullySelected, FALSE, how);
5424  
5425              parent = next.parentNode;
5426              clonedParent = _traverseNode(parent, FALSE, FALSE, how);
5427  
5428              while (parent) {
5429                  while (next) {
5430                      prevSibling = next.previousSibling;
5431                      clonedChild = _traverseNode(next, isFullySelected, FALSE, how);
5432  
5433                      if (how != DELETE)
5434                          clonedParent.insertBefore(clonedChild, clonedParent.firstChild);
5435  
5436                      isFullySelected = TRUE;
5437                      next = prevSibling;
5438                  }
5439  
5440                  if (parent == root)
5441                      return clonedParent;
5442  
5443                  next = parent.previousSibling;
5444                  parent = parent.parentNode;
5445  
5446                  clonedGrandParent = _traverseNode(parent, FALSE, FALSE, how);
5447  
5448                  if (how != DELETE)
5449                      clonedGrandParent.appendChild(clonedParent);
5450  
5451                  clonedParent = clonedGrandParent;
5452              }
5453          };
5454  
5455  		function _traverseLeftBoundary(root, how) {
5456              var next = _getSelectedNode(t[START_CONTAINER], t[START_OFFSET]), isFullySelected = next != t[START_CONTAINER], parent, clonedParent, nextSibling, clonedChild, clonedGrandParent;
5457  
5458              if (next == root)
5459                  return _traverseNode(next, isFullySelected, TRUE, how);
5460  
5461              parent = next.parentNode;
5462              clonedParent = _traverseNode(parent, FALSE, TRUE, how);
5463  
5464              while (parent) {
5465                  while (next) {
5466                      nextSibling = next.nextSibling;
5467                      clonedChild = _traverseNode(next, isFullySelected, TRUE, how);
5468  
5469                      if (how != DELETE)
5470                          clonedParent.appendChild(clonedChild);
5471  
5472                      isFullySelected = TRUE;
5473                      next = nextSibling;
5474                  }
5475  
5476                  if (parent == root)
5477                      return clonedParent;
5478  
5479                  next = parent.nextSibling;
5480                  parent = parent.parentNode;
5481  
5482                  clonedGrandParent = _traverseNode(parent, FALSE, TRUE, how);
5483  
5484                  if (how != DELETE)
5485                      clonedGrandParent.appendChild(clonedParent);
5486  
5487                  clonedParent = clonedGrandParent;
5488              }
5489          };
5490  
5491  		function _traverseNode(n, isFullySelected, isLeft, how) {
5492              var txtValue, newNodeValue, oldNodeValue, offset, newNode;
5493  
5494              if (isFullySelected)
5495                  return _traverseFullySelected(n, how);
5496  
5497              if (n.nodeType == 3 /* TEXT_NODE */) {
5498                  txtValue = n.nodeValue;
5499  
5500                  if (isLeft) {
5501                      offset = t[START_OFFSET];
5502                      newNodeValue = txtValue.substring(offset);
5503                      oldNodeValue = txtValue.substring(0, offset);
5504                  } else {
5505                      offset = t[END_OFFSET];
5506                      newNodeValue = txtValue.substring(0, offset);
5507                      oldNodeValue = txtValue.substring(offset);
5508                  }
5509  
5510                  if (how != CLONE)
5511                      n.nodeValue = oldNodeValue;
5512  
5513                  if (how == DELETE)
5514                      return;
5515  
5516                  newNode = n.cloneNode(FALSE);
5517                  newNode.nodeValue = newNodeValue;
5518  
5519                  return newNode;
5520              }
5521  
5522              if (how == DELETE)
5523                  return;
5524  
5525              return n.cloneNode(FALSE);
5526          };
5527  
5528  		function _traverseFullySelected(n, how) {
5529              if (how != DELETE)
5530                  return how == CLONE ? n.cloneNode(TRUE) : n;
5531  
5532              n.parentNode.removeChild(n);
5533          };
5534      };
5535  
5536      ns.Range = Range;
5537  })(tinymce.dom);
5538  
5539  (function() {
5540  	function Selection(selection) {
5541          var self = this, dom = selection.dom, TRUE = true, FALSE = false;
5542  
5543  		function getPosition(rng, start) {
5544              var checkRng, startIndex = 0, endIndex, inside,
5545                  children, child, offset, index, position = -1, parent;
5546  
5547              // Setup test range, collapse it and get the parent
5548              checkRng = rng.duplicate();
5549              checkRng.collapse(start);
5550              parent = checkRng.parentElement();
5551  
5552              // Check if the selection is within the right document
5553              if (parent.ownerDocument !== selection.dom.doc)
5554                  return;
5555  
5556              // IE will report non editable elements as it's parent so look for an editable one
5557              while (parent.contentEditable === "false") {
5558                  parent = parent.parentNode;
5559              }
5560  
5561              // If parent doesn't have any children then return that we are inside the element
5562              if (!parent.hasChildNodes()) {
5563                  return {node : parent, inside : 1};
5564              }
5565  
5566              // Setup node list and endIndex
5567              children = parent.children;
5568              endIndex = children.length - 1;
5569  
5570              // Perform a binary search for the position
5571              while (startIndex <= endIndex) {
5572                  index = Math.floor((startIndex + endIndex) / 2);
5573  
5574                  // Move selection to node and compare the ranges
5575                  child = children[index];
5576                  checkRng.moveToElementText(child);
5577                  position = checkRng.compareEndPoints(start ? 'StartToStart' : 'EndToEnd', rng);
5578  
5579                  // Before/after or an exact match
5580                  if (position > 0) {
5581                      endIndex = index - 1;
5582                  } else if (position < 0) {
5583                      startIndex = index + 1;
5584                  } else {
5585                      return {node : child};
5586                  }
5587              }
5588  
5589              // Check if child position is before or we didn't find a position
5590              if (position < 0) {
5591                  // No element child was found use the parent element and the offset inside that
5592                  if (!child) {
5593                      checkRng.moveToElementText(parent);
5594                      checkRng.collapse(true);
5595                      child = parent;
5596                      inside = true;
5597                  } else
5598                      checkRng.collapse(false);
5599  
5600                  checkRng.setEndPoint(start ? 'EndToStart' : 'EndToEnd', rng);
5601  
5602                  // Fix for edge case: <div style="width: 100px; height:100px;"><table>..</table>ab|c</div>
5603                  if (checkRng.compareEndPoints(start ? 'StartToStart' : 'StartToEnd', rng) > 0) {
5604                      checkRng = rng.duplicate();
5605                      checkRng.collapse(start);
5606  
5607                      offset = -1;
5608                      while (parent == checkRng.parentElement()) {
5609                          if (checkRng.move('character', -1) == 0)
5610                              break;
5611  
5612                          offset++;
5613                      }
5614                  }
5615  
5616                  offset = offset || checkRng.text.replace('\r\n', ' ').length;
5617              } else {
5618                  // Child position is after the selection endpoint
5619                  checkRng.collapse(true);
5620                  checkRng.setEndPoint(start ? 'StartToStart' : 'StartToEnd', rng);
5621  
5622                  // Get the length of the text to find where the endpoint is relative to it's container
5623                  offset = checkRng.text.replace('\r\n', ' ').length;
5624              }
5625  
5626              return {node : child, position : position, offset : offset, inside : inside};
5627          };
5628  
5629          // Returns a W3C DOM compatible range object by using the IE Range API
5630  		function getRange() {
5631              var ieRange = selection.getRng(), domRange = dom.createRng(), element, collapsed, tmpRange, element2, bookmark, fail;
5632  
5633              // If selection is outside the current document just return an empty range
5634              element = ieRange.item ? ieRange.item(0) : ieRange.parentElement();
5635              if (element.ownerDocument != dom.doc)
5636                  return domRange;
5637  
5638              collapsed = selection.isCollapsed();
5639  
5640              // Handle control selection
5641              if (ieRange.item) {
5642                  domRange.setStart(element.parentNode, dom.nodeIndex(element));
5643                  domRange.setEnd(domRange.startContainer, domRange.startOffset + 1);
5644  
5645                  return domRange;
5646              }
5647  
5648  			function findEndPoint(start) {
5649                  var endPoint = getPosition(ieRange, start), container, offset, textNodeOffset = 0, sibling, undef, nodeValue;
5650  
5651                  container = endPoint.node;
5652                  offset = endPoint.offset;
5653  
5654                  if (endPoint.inside && !container.hasChildNodes()) {
5655                      domRange[start ? 'setStart' : 'setEnd'](container, 0);
5656                      return;
5657                  }
5658  
5659                  if (offset === undef) {
5660                      domRange[start ? 'setStartBefore' : 'setEndAfter'](container);
5661                      return;
5662                  }
5663  
5664                  if (endPoint.position < 0) {
5665                      sibling = endPoint.inside ? container.firstChild : container.nextSibling;
5666  
5667                      if (!sibling) {
5668                          domRange[start ? 'setStartAfter' : 'setEndAfter'](container);
5669                          return;
5670                      }
5671  
5672                      if (!offset) {
5673                          if (sibling.nodeType == 3)
5674                              domRange[start ? 'setStart' : 'setEnd'](sibling, 0);
5675                          else
5676                              domRange[start ? 'setStartBefore' : 'setEndBefore'](sibling);
5677  
5678                          return;
5679                      }
5680  
5681                      // Find the text node and offset
5682                      while (sibling) {
5683                          nodeValue = sibling.nodeValue;
5684                          textNodeOffset += nodeValue.length;
5685  
5686                          // We are at or passed the position we where looking for
5687                          if (textNodeOffset >= offset) {
5688                              container = sibling;
5689                              textNodeOffset -= offset;
5690                              textNodeOffset = nodeValue.length - textNodeOffset;
5691                              break;
5692                          }
5693  
5694                          sibling = sibling.nextSibling;
5695                      }
5696                  } else {
5697                      // Find the text node and offset
5698                      sibling = container.previousSibling;
5699  
5700                      if (!sibling)
5701                          return domRange[start ? 'setStartBefore' : 'setEndBefore'](container);
5702  
5703                      // If there isn't any text to loop then use the first position
5704                      if (!offset) {
5705                          if (container.nodeType == 3)
5706                              domRange[start ? 'setStart' : 'setEnd'](sibling, container.nodeValue.length);
5707                          else
5708                              domRange[start ? 'setStartAfter' : 'setEndAfter'](sibling);
5709  
5710                          return;
5711                      }
5712  
5713                      while (sibling) {
5714                          textNodeOffset += sibling.nodeValue.length;
5715  
5716                          // We are at or passed the position we where looking for
5717                          if (textNodeOffset >= offset) {
5718                              container = sibling;
5719                              textNodeOffset -= offset;
5720                              break;
5721                          }
5722  
5723                          sibling = sibling.previousSibling;
5724                      }
5725                  }
5726  
5727                  domRange[start ? 'setStart' : 'setEnd'](container, textNodeOffset);
5728              };
5729  
5730              try {
5731                  // Find start point
5732                  findEndPoint(true);
5733  
5734                  // Find end point if needed
5735                  if (!collapsed)
5736                      findEndPoint();
5737              } catch (ex) {
5738                  // IE has a nasty bug where text nodes might throw "invalid argument" when you
5739                  // access the nodeValue or other properties of text nodes. This seems to happend when
5740                  // text nodes are split into two nodes by a delete/backspace call. So lets detect it and try to fix it.
5741                  if (ex.number == -2147024809) {
5742                      // Get the current selection
5743                      bookmark = self.getBookmark(2);
5744  
5745                      // Get start element
5746                      tmpRange = ieRange.duplicate();
5747                      tmpRange.collapse(true);
5748                      element = tmpRange.parentElement();
5749  
5750                      // Get end element
5751                      if (!collapsed) {
5752                          tmpRange = ieRange.duplicate();
5753                          tmpRange.collapse(false);
5754                          element2 = tmpRange.parentElement();
5755                          element2.innerHTML = element2.innerHTML;
5756                      }
5757  
5758                      // Remove the broken elements
5759                      element.innerHTML = element.innerHTML;
5760  
5761                      // Restore the selection
5762                      self.moveToBookmark(bookmark);
5763  
5764                      // Since the range has moved we need to re-get it
5765                      ieRange = selection.getRng();
5766  
5767                      // Find start point
5768                      findEndPoint(true);
5769  
5770                      // Find end point if needed
5771                      if (!collapsed)
5772                          findEndPoint();
5773                  } else
5774                      throw ex; // Throw other errors
5775              }
5776  
5777              return domRange;
5778          };
5779  
5780          this.getBookmark = function(type) {
5781              var rng = selection.getRng(), start, end, bookmark = {};
5782  
5783  			function getIndexes(node) {
5784                  var node, parent, root, children, i, indexes = [];
5785  
5786                  parent = node.parentNode;
5787                  root = dom.getRoot().parentNode;
5788  
5789                  while (parent != root && parent.nodeType !== 9) {
5790                      children = parent.children;
5791  
5792                      i = children.length;
5793                      while (i--) {
5794                          if (node === children[i]) {
5795                              indexes.push(i);
5796                              break;
5797                          }
5798                      }
5799  
5800                      node = parent;
5801                      parent = parent.parentNode;
5802                  }
5803  
5804                  return indexes;
5805              };
5806  
5807  			function getBookmarkEndPoint(start) {
5808                  var position;
5809  
5810                  position = getPosition(rng, start);
5811                  if (position) {
5812                      return {
5813                          position : position.position,
5814                          offset : position.offset,
5815                          indexes : getIndexes(position.node),
5816                          inside : position.inside
5817                      };
5818                  }
5819              };
5820  
5821              // Non ubstructive bookmark
5822              if (type === 2) {
5823                  // Handle text selection
5824                  if (!rng.item) {
5825                      bookmark.start = getBookmarkEndPoint(true);
5826  
5827                      if (!selection.isCollapsed())
5828                          bookmark.end = getBookmarkEndPoint();
5829                  } else
5830                      bookmark.start = {ctrl : true, indexes : getIndexes(rng.item(0))};
5831              }
5832  
5833              return bookmark;
5834          };
5835  
5836          this.moveToBookmark = function(bookmark) {
5837              var rng, body = dom.doc.body;
5838  
5839  			function resolveIndexes(indexes) {
5840                  var node, i, idx, children;
5841  
5842                  node = dom.getRoot();
5843                  for (i = indexes.length - 1; i >= 0; i--) {
5844                      children = node.children;
5845                      idx = indexes[i];
5846  
5847                      if (idx <= children.length - 1) {
5848                          node = children[idx];
5849                      }
5850                  }
5851  
5852                  return node;
5853              };
5854              
5855  			function setBookmarkEndPoint(start) {
5856                  var endPoint = bookmark[start ? 'start' : 'end'], moveLeft, moveRng, undef;
5857  
5858                  if (endPoint) {
5859                      moveLeft = endPoint.position > 0;
5860  
5861                      moveRng = body.createTextRange();
5862                      moveRng.moveToElementText(resolveIndexes(endPoint.indexes));
5863  
5864                      offset = endPoint.offset;
5865                      if (offset !== undef) {
5866                          moveRng.collapse(endPoint.inside || moveLeft);
5867                          moveRng.moveStart('character', moveLeft ? -offset : offset);
5868                      } else
5869                          moveRng.collapse(start);
5870  
5871                      rng.setEndPoint(start ? 'StartToStart' : 'EndToStart', moveRng);
5872  
5873                      if (start)
5874                          rng.collapse(true);
5875                  }
5876              };
5877  
5878              if (bookmark.start) {
5879                  if (bookmark.start.ctrl) {
5880                      rng = body.createControlRange();
5881                      rng.addElement(resolveIndexes(bookmark.start.indexes));
5882                      rng.select();
5883                  } else {
5884                      rng = body.createTextRange();
5885                      setBookmarkEndPoint(true);
5886                      setBookmarkEndPoint();
5887                      rng.select();
5888                  }
5889              }
5890          };
5891  
5892          this.addRange = function(rng) {
5893              var ieRng, ctrlRng, startContainer, startOffset, endContainer, endOffset, doc = selection.dom.doc, body = doc.body;
5894  
5895  			function setEndPoint(start) {
5896                  var container, offset, marker, tmpRng, nodes;
5897  
5898                  marker = dom.create('a');
5899                  container = start ? startContainer : endContainer;
5900                  offset = start ? startOffset : endOffset;
5901                  tmpRng = ieRng.duplicate();
5902  
5903                  if (container == doc || container == doc.documentElement) {
5904                      container = body;
5905                      offset = 0;
5906                  }
5907  
5908                  if (container.nodeType == 3) {
5909                      container.parentNode.insertBefore(marker, container);
5910                      tmpRng.moveToElementText(marker);
5911                      tmpRng.moveStart('character', offset);
5912                      dom.remove(marker);
5913                      ieRng.setEndPoint(start ? 'StartToStart' : 'EndToEnd', tmpRng);
5914                  } else {
5915                      nodes = container.childNodes;
5916  
5917                      if (nodes.length) {
5918                          if (offset >= nodes.length) {
5919                              dom.insertAfter(marker, nodes[nodes.length - 1]);
5920                          } else {
5921                              container.insertBefore(marker, nodes[offset]);
5922                          }
5923  
5924                          tmpRng.moveToElementText(marker);
5925                      } else {
5926                          // Empty node selection for example <div>|</div>
5927                          marker = doc.createTextNode('\uFEFF');
5928                          container.appendChild(marker);
5929                          tmpRng.moveToElementText(marker.parentNode);
5930                          tmpRng.collapse(TRUE);
5931                      }
5932  
5933                      ieRng.setEndPoint(start ? 'StartToStart' : 'EndToEnd', tmpRng);
5934                      dom.remove(marker);
5935                  }
5936              }
5937  
5938              // Setup some shorter versions
5939              startContainer = rng.startContainer;
5940              startOffset = rng.startOffset;
5941              endContainer = rng.endContainer;
5942              endOffset = rng.endOffset;
5943              ieRng = body.createTextRange();
5944  
5945              // If single element selection then try making a control selection out of it
5946              if (startContainer == endContainer && startContainer.nodeType == 1 && startOffset == endOffset - 1) {
5947                  if (startOffset == endOffset - 1) {
5948                      try {
5949                          ctrlRng = body.createControlRange();
5950                          ctrlRng.addElement(startContainer.childNodes[startOffset]);
5951                          ctrlRng.select();
5952                          return;
5953                      } catch (ex) {
5954                          // Ignore
5955                      }
5956                  }
5957              }
5958  
5959              // Set start/end point of selection
5960              setEndPoint(true);
5961              setEndPoint();
5962  
5963              // Select the new range and scroll it into view
5964              ieRng.select();
5965          };
5966  
5967          // Expose range method
5968          this.getRangeAt = getRange;
5969      };
5970  
5971      // Expose the selection object
5972      tinymce.dom.TridentSelection = Selection;
5973  })();
5974  
5975  
5976  /*
5977   * Sizzle CSS Selector Engine - v1.0
5978   *  Copyright 2009, The Dojo Foundation
5979   *  Released under the MIT, BSD, and GPL Licenses.
5980   *  More information: http://sizzlejs.com/
5981   */
5982  (function(){
5983  
5984  var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
5985      done = 0,
5986      toString = Object.prototype.toString,
5987      hasDuplicate = false,
5988      baseHasDuplicate = true;
5989  
5990  // Here we check if the JavaScript engine is using some sort of
5991  // optimization where it does not always call our comparision
5992  // function. If that is the case, discard the hasDuplicate value.
5993  //   Thus far that includes Google Chrome.
5994  [0, 0].sort(function(){
5995      baseHasDuplicate = false;
5996      return 0;
5997  });
5998  
5999  var Sizzle = function(selector, context, results, seed) {
6000      results = results || [];
6001      context = context || document;
6002  
6003      var origContext = context;
6004  
6005      if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
6006          return [];
6007      }
6008      
6009      if ( !selector || typeof selector !== "string" ) {
6010          return results;
6011      }
6012  
6013      var parts = [], m, set, checkSet, extra, prune = true, contextXML = Sizzle.isXML(context),
6014          soFar = selector, ret, cur, pop, i;
6015      
6016      // Reset the position of the chunker regexp (start from head)
6017      do {
6018          chunker.exec("");
6019          m = chunker.exec(soFar);
6020  
6021          if ( m ) {
6022              soFar = m[3];
6023          
6024              parts.push( m[1] );
6025          
6026              if ( m[2] ) {
6027                  extra = m[3];
6028                  break;
6029              }
6030          }
6031      } while ( m );
6032  
6033      if ( parts.length > 1 && origPOS.exec( selector ) ) {
6034          if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
6035              set = posProcess( parts[0] + parts[1], context );
6036          } else {
6037              set = Expr.relative[ parts[0] ] ?
6038                  [ context ] :
6039                  Sizzle( parts.shift(), context );
6040  
6041              while ( parts.length ) {
6042                  selector = parts.shift();
6043  
6044                  if ( Expr.relative[ selector ] ) {
6045                      selector += parts.shift();
6046                  }
6047                  
6048                  set = posProcess( selector, set );
6049              }
6050          }
6051      } else {
6052          // Take a shortcut and set the context if the root selector is an ID
6053          // (but not if it'll be faster if the inner selector is an ID)
6054          if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
6055                  Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
6056              ret = Sizzle.find( parts.shift(), context, contextXML );
6057              context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0];
6058          }
6059  
6060          if ( context ) {
6061              ret = seed ?
6062                  { expr: parts.pop(), set: makeArray(seed) } :
6063                  Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
6064              set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set;
6065  
6066              if ( parts.length > 0 ) {
6067                  checkSet = makeArray(set);
6068              } else {
6069                  prune = false;
6070              }
6071  
6072              while ( parts.length ) {
6073                  cur = parts.pop();
6074                  pop = cur;
6075  
6076                  if ( !Expr.relative[ cur ] ) {
6077                      cur = "";
6078                  } else {
6079                      pop = parts.pop();
6080                  }
6081  
6082                  if ( pop == null ) {
6083                      pop = context;
6084                  }
6085  
6086                  Expr.relative[ cur ]( checkSet, pop, contextXML );
6087              }
6088          } else {
6089              checkSet = parts = [];
6090          }
6091      }
6092  
6093      if ( !checkSet ) {
6094          checkSet = set;
6095      }
6096  
6097      if ( !checkSet ) {
6098          Sizzle.error( cur || selector );
6099      }
6100  
6101      if ( toString.call(checkSet) === "[object Array]" ) {
6102          if ( !prune ) {
6103              results.push.apply( results, checkSet );
6104          } else if ( context && context.nodeType === 1 ) {
6105              for ( i = 0; checkSet[i] != null; i++ ) {
6106                  if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
6107                      results.push( set[i] );
6108                  }
6109              }
6110          } else {
6111              for ( i = 0; checkSet[i] != null; i++ ) {
6112                  if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
6113                      results.push( set[i] );
6114                  }
6115              }
6116          }
6117      } else {
6118          makeArray( checkSet, results );
6119      }
6120  
6121      if ( extra ) {
6122          Sizzle( extra, origContext, results, seed );
6123          Sizzle.uniqueSort( results );
6124      }
6125  
6126      return results;
6127  };
6128  
6129  Sizzle.uniqueSort = function(results){
6130      if ( sortOrder ) {
6131          hasDuplicate = baseHasDuplicate;
6132          results.sort(sortOrder);
6133  
6134          if ( hasDuplicate ) {
6135              for ( var i = 1; i < results.length; i++ ) {
6136                  if ( results[i] === results[i-1] ) {
6137                      results.splice(i--, 1);
6138                  }
6139              }
6140          }
6141      }
6142  
6143      return results;
6144  };
6145  
6146  Sizzle.matches = function(expr, set){
6147      return Sizzle(expr, null, null, set);
6148  };
6149  
6150  Sizzle.find = function(expr, context, isXML){
6151      var set;
6152  
6153      if ( !expr ) {
6154          return [];
6155      }
6156  
6157      for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
6158          var type = Expr.order[i], match;
6159          
6160          if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
6161              var left = match[1];
6162              match.splice(1,1);
6163  
6164              if ( left.substr( left.length - 1 ) !== "\\" ) {
6165                  match[1] = (match[1] || "").replace(/\\/g, "");
6166                  set = Expr.find[ type ]( match, context, isXML );
6167                  if ( set != null ) {
6168                      expr = expr.replace( Expr.match[ type ], "" );
6169                      break;
6170                  }
6171              }
6172          }
6173      }
6174  
6175      if ( !set ) {
6176          set = context.getElementsByTagName("*");
6177      }
6178  
6179      return {set: set, expr: expr};
6180  };
6181  
6182  Sizzle.filter = function(expr, set, inplace, not){
6183      var old = expr, result = [], curLoop = set, match, anyFound,
6184          isXMLFilter = set && set[0] && Sizzle.isXML(set[0]);
6185  
6186      while ( expr && set.length ) {
6187          for ( var type in Expr.filter ) {
6188              if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
6189                  var filter = Expr.filter[ type ], found, item, left = match[1];
6190                  anyFound = false;
6191  
6192                  match.splice(1,1);
6193  
6194                  if ( left.substr( left.length - 1 ) === "\\" ) {
6195                      continue;
6196                  }
6197  
6198                  if ( curLoop === result ) {
6199                      result = [];
6200                  }
6201  
6202                  if ( Expr.preFilter[ type ] ) {
6203                      match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
6204  
6205                      if ( !match ) {
6206                          anyFound = found = true;
6207                      } else if ( match === true ) {
6208                          continue;
6209                      }
6210                  }
6211  
6212                  if ( match ) {
6213                      for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
6214                          if ( item ) {
6215                              found = filter( item, match, i, curLoop );
6216                              var pass = not ^ !!found;
6217  
6218                              if ( inplace && found != null ) {
6219                                  if ( pass ) {
6220                                      anyFound = true;
6221                                  } else {
6222                                      curLoop[i] = false;
6223                                  }
6224                              } else if ( pass ) {
6225                                  result.push( item );
6226                                  anyFound = true;
6227                              }
6228                          }
6229                      }
6230                  }
6231  
6232                  if ( found !== undefined ) {
6233                      if ( !inplace ) {
6234                          curLoop = result;
6235                      }
6236  
6237                      expr = expr.replace( Expr.match[ type ], "" );
6238  
6239                      if ( !anyFound ) {
6240                          return [];
6241                      }
6242  
6243                      break;
6244                  }
6245              }
6246          }
6247  
6248          // Improper expression
6249          if ( expr === old ) {
6250              if ( anyFound == null ) {
6251                  Sizzle.error( expr );
6252              } else {
6253                  break;
6254              }
6255          }
6256  
6257          old = expr;
6258      }
6259  
6260      return curLoop;
6261  };
6262  
6263  Sizzle.error = function( msg ) {
6264      throw "Syntax error, unrecognized expression: " + msg;
6265  };
6266  
6267  var Expr = Sizzle.selectors = {
6268      order: [ "ID", "NAME", "TAG" ],
6269      match: {
6270          ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
6271          CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
6272          NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
6273          ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
6274          TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
6275          CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/,
6276          POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
6277          PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
6278      },
6279      leftMatch: {},
6280      attrMap: {
6281          "class": "className",
6282          "for": "htmlFor"
6283      },
6284      attrHandle: {
6285          href: function(elem){
6286              return elem.getAttribute("href");
6287          }
6288      },
6289      relative: {
6290          "+": function(checkSet, part){
6291              var isPartStr = typeof part === "string",
6292                  isTag = isPartStr && !/\W/.test(part),
6293                  isPartStrNotTag = isPartStr && !isTag;
6294  
6295              if ( isTag ) {
6296                  part = part.toLowerCase();
6297              }
6298  
6299              for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
6300                  if ( (elem = checkSet[i]) ) {
6301                      while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
6302  
6303                      checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
6304                          elem || false :
6305                          elem === part;
6306                  }
6307              }
6308  
6309              if ( isPartStrNotTag ) {
6310                  Sizzle.filter( part, checkSet, true );
6311              }
6312          },
6313          ">": function(checkSet, part){
6314              var isPartStr = typeof part === "string",
6315                  elem, i = 0, l = checkSet.length;
6316  
6317              if ( isPartStr && !/\W/.test(part) ) {
6318                  part = part.toLowerCase();
6319  
6320                  for ( ; i < l; i++ ) {
6321                      elem = checkSet[i];
6322                      if ( elem ) {
6323                          var parent = elem.parentNode;
6324                          checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
6325                      }
6326                  }
6327              } else {
6328                  for ( ; i < l; i++ ) {
6329                      elem = checkSet[i];
6330                      if ( elem ) {
6331                          checkSet[i] = isPartStr ?
6332                              elem.parentNode :
6333                              elem.parentNode === part;
6334                      }
6335                  }
6336  
6337                  if ( isPartStr ) {
6338                      Sizzle.filter( part, checkSet, true );
6339                  }
6340              }
6341          },
6342          "": function(checkSet, part, isXML){
6343              var doneName = done++, checkFn = dirCheck, nodeCheck;
6344  
6345              if ( typeof part === "string" && !/\W/.test(part) ) {
6346                  part = part.toLowerCase();
6347                  nodeCheck = part;
6348                  checkFn = dirNodeCheck;
6349              }
6350  
6351              checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
6352          },
6353          "~": function(checkSet, part, isXML){
6354              var doneName = done++, checkFn = dirCheck, nodeCheck;
6355  
6356              if ( typeof part === "string" && !/\W/.test(part) ) {
6357                  part = part.toLowerCase();
6358                  nodeCheck = part;
6359                  checkFn = dirNodeCheck;
6360              }
6361  
6362              checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML);
6363          }
6364      },
6365      find: {
6366          ID: function(match, context, isXML){
6367              if ( typeof context.getElementById !== "undefined" && !isXML ) {
6368                  var m = context.getElementById(match[1]);
6369                  return m ? [m] : [];
6370              }
6371          },
6372          NAME: function(match, context){
6373              if ( typeof context.getElementsByName !== "undefined" ) {
6374                  var ret = [], results = context.getElementsByName(match[1]);
6375  
6376                  for ( var i = 0, l = results.length; i < l; i++ ) {
6377                      if ( results[i].getAttribute("name") === match[1] ) {
6378                          ret.push( results[i] );
6379                      }
6380                  }
6381  
6382                  return ret.length === 0 ? null : ret;
6383              }
6384          },
6385          TAG: function(match, context){
6386              return context.getElementsByTagName(match[1]);
6387          }
6388      },
6389      preFilter: {
6390          CLASS: function(match, curLoop, inplace, result, not, isXML){
6391              match = " " + match[1].replace(/\\/g, "") + " ";
6392  
6393              if ( isXML ) {
6394                  return match;
6395              }
6396  
6397              for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
6398                  if ( elem ) {
6399                      if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) {
6400                          if ( !inplace ) {
6401                              result.push( elem );
6402                          }
6403                      } else if ( inplace ) {
6404                          curLoop[i] = false;
6405                      }
6406                  }
6407              }
6408  
6409              return false;
6410          },
6411          ID: function(match){
6412              return match[1].replace(/\\/g, "");
6413          },
6414          TAG: function(match, curLoop){
6415              return match[1].toLowerCase();
6416          },
6417          CHILD: function(match){
6418              if ( match[1] === "nth" ) {
6419                  // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
6420                  var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
6421                      match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
6422                      !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
6423  
6424                  // calculate the numbers (first)n+(last) including if they are negative
6425                  match[2] = (test[1] + (test[2] || 1)) - 0;
6426                  match[3] = test[3] - 0;
6427              }
6428  
6429              // TODO: Move to normal caching system
6430              match[0] = done++;
6431  
6432              return match;
6433          },
6434          ATTR: function(match, curLoop, inplace, result, not, isXML){
6435              var name = match[1].replace(/\\/g, "");
6436              
6437              if ( !isXML && Expr.attrMap[name] ) {
6438                  match[1] = Expr.attrMap[name];
6439              }
6440  
6441              if ( match[2] === "~=" ) {
6442                  match[4] = " " + match[4] + " ";
6443              }
6444  
6445              return match;
6446          },
6447          PSEUDO: function(match, curLoop, inplace, result, not){
6448              if ( match[1] === "not" ) {
6449                  // If we're dealing with a complex expression, or a simple one
6450                  if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
6451                      match[3] = Sizzle(match[3], null, null, curLoop);
6452                  } else {
6453                      var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
6454                      if ( !inplace ) {
6455                          result.push.apply( result, ret );
6456                      }
6457                      return false;
6458                  }
6459              } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
6460                  return true;
6461              }
6462              
6463              return match;
6464          },
6465          POS: function(match){
6466              match.unshift( true );
6467              return match;
6468          }
6469      },
6470      filters: {
6471          enabled: function(elem){
6472              return elem.disabled === false && elem.type !== "hidden";
6473          },
6474          disabled: function(elem){
6475              return elem.disabled === true;
6476          },
6477          checked: function(elem){
6478              return elem.checked === true;
6479          },
6480          selected: function(elem){
6481              // Accessing this property makes selected-by-default
6482              // options in Safari work properly
6483              elem.parentNode.selectedIndex;
6484              return elem.selected === true;
6485          },
6486          parent: function(elem){
6487              return !!elem.firstChild;
6488          },
6489          empty: function(elem){
6490              return !elem.firstChild;
6491          },
6492          has: function(elem, i, match){
6493              return !!Sizzle( match[3], elem ).length;
6494          },
6495          header: function(elem){
6496              return (/h\d/i).test( elem.nodeName );
6497          },
6498          text: function(elem){
6499              return "text" === elem.type;
6500          },
6501          radio: function(elem){
6502              return "radio" === elem.type;
6503          },
6504          checkbox: function(elem){
6505              return "checkbox" === elem.type;
6506          },
6507          file: function(elem){
6508              return "file" === elem.type;
6509          },
6510          password: function(elem){
6511              return "password" === elem.type;
6512          },
6513          submit: function(elem){
6514              return "submit" === elem.type;
6515          },
6516          image: function(elem){
6517              return "image" === elem.type;
6518          },
6519          reset: function(elem){
6520              return "reset" === elem.type;
6521          },
6522          button: function(elem){
6523              return "button" === elem.type || elem.nodeName.toLowerCase() === "button";
6524          },
6525          input: function(elem){
6526              return (/input|select|textarea|button/i).test(elem.nodeName);
6527          }
6528      },
6529      setFilters: {
6530          first: function(elem, i){
6531              return i === 0;
6532          },
6533          last: function(elem, i, match, array){
6534              return i === array.length - 1;
6535          },
6536          even: function(elem, i){
6537              return i % 2 === 0;
6538          },
6539          odd: function(elem, i){
6540              return i % 2 === 1;
6541          },
6542          lt: function(elem, i, match){
6543              return i < match[3] - 0;
6544          },
6545          gt: function(elem, i, match){
6546              return i > match[3] - 0;
6547          },
6548          nth: function(elem, i, match){
6549              return match[3] - 0 === i;
6550          },
6551          eq: function(elem, i, match){
6552              return match[3] - 0 === i;
6553          }
6554      },
6555      filter: {
6556          PSEUDO: function(elem, match, i, array){
6557              var name = match[1], filter = Expr.filters[ name ];
6558  
6559              if ( filter ) {
6560                  return filter( elem, i, match, array );
6561              } else if ( name === "contains" ) {
6562                  return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0;
6563              } else if ( name === "not" ) {
6564                  var not = match[3];
6565  
6566                  for ( var j = 0, l = not.length; j < l; j++ ) {
6567                      if ( not[j] === elem ) {
6568                          return false;
6569                      }
6570                  }
6571  
6572                  return true;
6573              } else {
6574                  Sizzle.error( "Syntax error, unrecognized expression: " + name );
6575              }
6576          },
6577          CHILD: function(elem, match){
6578              var type = match[1], node = elem;
6579              switch (type) {
6580                  case 'only':
6581                  case 'first':
6582                      while ( (node = node.previousSibling) )     {
6583                          if ( node.nodeType === 1 ) { 
6584                              return false; 
6585                          }
6586                      }
6587                      if ( type === "first" ) { 
6588                          return true; 
6589                      }
6590                      node = elem;
6591                  case 'last':
6592                      while ( (node = node.nextSibling) )     {
6593                          if ( node.nodeType === 1 ) { 
6594                              return false; 
6595                          }
6596                      }
6597                      return true;
6598                  case 'nth':
6599                      var first = match[2], last = match[3];
6600  
6601                      if ( first === 1 && last === 0 ) {
6602                          return true;
6603                      }
6604                      
6605                      var doneName = match[0],
6606                          parent = elem.parentNode;
6607      
6608                      if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
6609                          var count = 0;
6610                          for ( node = parent.firstChild; node; node = node.nextSibling ) {
6611                              if ( node.nodeType === 1 ) {
6612                                  node.nodeIndex = ++count;
6613                              }
6614                          } 
6615                          parent.sizcache = doneName;
6616                      }
6617                      
6618                      var diff = elem.nodeIndex - last;
6619                      if ( first === 0 ) {
6620                          return diff === 0;
6621                      } else {
6622                          return ( diff % first === 0 && diff / first >= 0 );
6623                      }
6624              }
6625          },
6626          ID: function(elem, match){
6627              return elem.nodeType === 1 && elem.getAttribute("id") === match;
6628          },
6629          TAG: function(elem, match){
6630              return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;
6631          },
6632          CLASS: function(elem, match){
6633              return (" " + (elem.className || elem.getAttribute("class")) + " ")
6634                  .indexOf( match ) > -1;
6635          },
6636          ATTR: function(elem, match){
6637              var name = match[1],
6638                  result = Expr.attrHandle[ name ] ?
6639                      Expr.attrHandle[ name ]( elem ) :
6640                      elem[ name ] != null ?
6641                          elem[ name ] :
6642                          elem.getAttribute( name ),
6643                  value = result + "",
6644                  type = match[2],
6645                  check = match[4];
6646  
6647              return result == null ?
6648                  type === "!=" :
6649                  type === "=" ?
6650                  value === check :
6651                  type === "*=" ?
6652                  value.indexOf(check) >= 0 :
6653                  type === "~=" ?
6654                  (" " + value + " ").indexOf(check) >= 0 :
6655                  !check ?
6656                  value && result !== false :
6657                  type === "!=" ?
6658                  value !== check :
6659                  type === "^=" ?
6660                  value.indexOf(check) === 0 :
6661                  type === "$=" ?
6662                  value.substr(value.length - check.length) === check :
6663                  type === "|=" ?
6664                  value === check || value.substr(0, check.length + 1) === check + "-" :
6665                  false;
6666          },
6667          POS: function(elem, match, i, array){
6668              var name = match[2], filter = Expr.setFilters[ name ];
6669  
6670              if ( filter ) {
6671                  return filter( elem, i, match, array );
6672              }
6673          }
6674      }
6675  };
6676  
6677  var origPOS = Expr.match.POS,
6678      fescape = function(all, num){
6679          return "\\" + (num - 0 + 1);
6680      };
6681  
6682  for ( var type in Expr.match ) {
6683      Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
6684      Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
6685  }
6686  
6687  var makeArray = function(array, results) {
6688      array = Array.prototype.slice.call( array, 0 );
6689  
6690      if ( results ) {
6691          results.push.apply( results, array );
6692          return results;
6693      }
6694      
6695      return array;
6696  };
6697  
6698  // Perform a simple check to determine if the browser is capable of
6699  // converting a NodeList to an array using builtin methods.
6700  // Also verifies that the returned array holds DOM nodes
6701  // (which is not the case in the Blackberry browser)
6702  try {
6703      Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
6704  
6705  // Provide a fallback method if it does not work
6706  } catch(e){
6707      makeArray = function(array, results) {
6708          var ret = results || [], i = 0;
6709  
6710          if ( toString.call(array) === "[object Array]" ) {
6711              Array.prototype.push.apply( ret, array );
6712          } else {
6713              if ( typeof array.length === "number" ) {
6714                  for ( var l = array.length; i < l; i++ ) {
6715                      ret.push( array[i] );
6716                  }
6717              } else {
6718                  for ( ; array[i]; i++ ) {
6719                      ret.push( array[i] );
6720                  }
6721              }
6722          }
6723  
6724          return ret;
6725      };
6726  }
6727  
6728  var sortOrder;
6729  
6730  if ( document.documentElement.compareDocumentPosition ) {
6731      sortOrder = function( a, b ) {
6732          if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
6733              if ( a == b ) {
6734                  hasDuplicate = true;
6735              }
6736              return a.compareDocumentPosition ? -1 : 1;
6737          }
6738  
6739          var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;
6740          if ( ret === 0 ) {
6741              hasDuplicate = true;
6742          }
6743          return ret;
6744      };
6745  } else if ( "sourceIndex" in document.documentElement ) {
6746      sortOrder = function( a, b ) {
6747          if ( !a.sourceIndex || !b.sourceIndex ) {
6748              if ( a == b ) {
6749                  hasDuplicate = true;
6750              }
6751              return a.sourceIndex ? -1 : 1;
6752          }
6753  
6754          var ret = a.sourceIndex - b.sourceIndex;
6755          if ( ret === 0 ) {
6756              hasDuplicate = true;
6757          }
6758          return ret;
6759      };
6760  } else if ( document.createRange ) {
6761      sortOrder = function( a, b ) {
6762          if ( !a.ownerDocument || !b.ownerDocument ) {
6763              if ( a == b ) {
6764                  hasDuplicate = true;
6765              }
6766              return a.ownerDocument ? -1 : 1;
6767          }
6768  
6769          var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange();
6770          aRange.setStart(a, 0);
6771          aRange.setEnd(a, 0);
6772          bRange.setStart(b, 0);
6773          bRange.setEnd(b, 0);
6774          var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange);
6775          if ( ret === 0 ) {
6776              hasDuplicate = true;
6777          }
6778          return ret;
6779      };
6780  }
6781  
6782  // Utility function for retreiving the text value of an array of DOM nodes
6783  Sizzle.getText = function( elems ) {
6784      var ret = "", elem;
6785  
6786      for ( var i = 0; elems[i]; i++ ) {
6787          elem = elems[i];
6788  
6789          // Get the text from text nodes and CDATA nodes
6790          if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
6791              ret += elem.nodeValue;
6792  
6793          // Traverse everything else, except comment nodes
6794          } else if ( elem.nodeType !== 8 ) {
6795              ret += Sizzle.getText( elem.childNodes );
6796          }
6797      }
6798  
6799      return ret;
6800  };
6801  
6802  // Check to see if the browser returns elements by name when
6803  // querying by getElementById (and provide a workaround)
6804  (function(){
6805      // We're going to inject a fake input element with a specified name
6806      var form = document.createElement("div"),
6807          id = "script" + (new Date()).getTime();
6808      form.innerHTML = "<a name='" + id + "'/>";
6809  
6810      // Inject it into the root element, check its status, and remove it quickly
6811      var root = document.documentElement;
6812      root.insertBefore( form, root.firstChild );
6813  
6814      // The workaround has to do additional checks after a getElementById
6815      // Which slows things down for other browsers (hence the branching)
6816      if ( document.getElementById( id ) ) {
6817          Expr.find.ID = function(match, context, isXML){
6818              if ( typeof context.getElementById !== "undefined" && !isXML ) {
6819                  var m = context.getElementById(match[1]);
6820                  return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : [];
6821              }
6822          };
6823  
6824          Expr.filter.ID = function(elem, match){
6825              var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
6826              return elem.nodeType === 1 && node && node.nodeValue === match;
6827          };
6828      }
6829  
6830      root.removeChild( form );
6831      root = form = null; // release memory in IE
6832  })();
6833  
6834  (function(){
6835      // Check to see if the browser returns only elements
6836      // when doing getElementsByTagName("*")
6837  
6838      // Create a fake element
6839      var div = document.createElement("div");
6840      div.appendChild( document.createComment("") );
6841  
6842      // Make sure no comments are found
6843      if ( div.getElementsByTagName("*").length > 0 ) {
6844          Expr.find.TAG = function(match, context){
6845              var results = context.getElementsByTagName(match[1]);
6846  
6847              // Filter out possible comments
6848              if ( match[1] === "*" ) {
6849                  var tmp = [];
6850  
6851                  for ( var i = 0; results[i]; i++ ) {
6852                      if ( results[i].nodeType === 1 ) {
6853                          tmp.push( results[i] );
6854                      }
6855                  }
6856  
6857                  results = tmp;
6858              }
6859  
6860              return results;
6861          };
6862      }
6863  
6864      // Check to see if an attribute returns normalized href attributes
6865      div.innerHTML = "<a href='#'></a>";
6866      if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
6867              div.firstChild.getAttribute("href") !== "#" ) {
6868          Expr.attrHandle.href = function(elem){
6869              return elem.getAttribute("href", 2);
6870          };
6871      }
6872  
6873      div = null; // release memory in IE
6874  })();
6875  
6876  if ( document.querySelectorAll ) {
6877      (function(){
6878          var oldSizzle = Sizzle, div = document.createElement("div");
6879          div.innerHTML = "<p class='TEST'></p>";
6880  
6881          // Safari can't handle uppercase or unicode characters when
6882          // in quirks mode.
6883          if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
6884              return;
6885          }
6886      
6887          Sizzle = function(query, context, extra, seed){
6888              context = context || document;
6889  
6890              // Only use querySelectorAll on non-XML documents
6891              // (ID selectors don't work in non-HTML documents)
6892              if ( !seed && context.nodeType === 9 && !Sizzle.isXML(context) ) {
6893                  try {
6894                      return makeArray( context.querySelectorAll(query), extra );
6895                  } catch(e){}
6896              }
6897          
6898              return oldSizzle(query, context, extra, seed);
6899          };
6900  
6901          for ( var prop in oldSizzle ) {
6902              Sizzle[ prop ] = oldSizzle[ prop ];
6903          }
6904  
6905          div = null; // release memory in IE
6906      })();
6907  }
6908  
6909  (function(){
6910      var div = document.createElement("div");
6911  
6912      div.innerHTML = "<div class='test e'></div><div class='test'></div>";
6913  
6914      // Opera can't find a second classname (in 9.6)
6915      // Also, make sure that getElementsByClassName actually exists
6916      if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
6917          return;
6918      }
6919  
6920      // Safari caches class attributes, doesn't catch changes (in 3.2)
6921      div.lastChild.className = "e";
6922  
6923      if ( div.getElementsByClassName("e").length === 1 ) {
6924          return;
6925      }
6926      
6927      Expr.order.splice(1, 0, "CLASS");
6928      Expr.find.CLASS = function(match, context, isXML) {
6929          if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
6930              return context.getElementsByClassName(match[1]);
6931          }
6932      };
6933  
6934      div = null; // release memory in IE
6935  })();
6936  
6937  function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
6938      for ( var i = 0, l = checkSet.length; i < l; i++ ) {
6939          var elem = checkSet[i];
6940          if ( elem ) {
6941              elem = elem[dir];
6942              var match = false;
6943  
6944              while ( elem ) {
6945                  if ( elem.sizcache === doneName ) {
6946                      match = checkSet[elem.sizset];
6947                      break;
6948                  }
6949  
6950                  if ( elem.nodeType === 1 && !isXML ){
6951                      elem.sizcache = doneName;
6952                      elem.sizset = i;
6953                  }
6954  
6955                  if ( elem.nodeName.toLowerCase() === cur ) {
6956                      match = elem;
6957                      break;
6958                  }
6959  
6960                  elem = elem[dir];
6961              }
6962  
6963              checkSet[i] = match;
6964          }
6965      }
6966  }
6967  
6968  function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
6969      for ( var i = 0, l = checkSet.length; i < l; i++ ) {
6970          var elem = checkSet[i];
6971          if ( elem ) {
6972              elem = elem[dir];
6973              var match = false;
6974  
6975              while ( elem ) {
6976                  if ( elem.sizcache === doneName ) {
6977                      match = checkSet[elem.sizset];
6978                      break;
6979                  }
6980  
6981                  if ( elem.nodeType === 1 ) {
6982                      if ( !isXML ) {
6983                          elem.sizcache = doneName;
6984                          elem.sizset = i;
6985                      }
6986                      if ( typeof cur !== "string" ) {
6987                          if ( elem === cur ) {
6988                              match = true;
6989                              break;
6990                          }
6991  
6992                      } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
6993                          match = elem;
6994                          break;
6995                      }
6996                  }
6997  
6998                  elem = elem[dir];
6999              }
7000  
7001              checkSet[i] = match;
7002          }
7003      }
7004  }
7005  
7006  Sizzle.contains = document.compareDocumentPosition ? function(a, b){
7007      return !!(a.compareDocumentPosition(b) & 16);
7008  } : function(a, b){
7009      return a !== b && (a.contains ? a.contains(b) : true);
7010  };
7011  
7012  Sizzle.isXML = function(elem){
7013      // documentElement is verified for cases where it doesn't yet exist
7014      // (such as loading iframes in IE - #4833) 
7015      var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
7016      return documentElement ? documentElement.nodeName !== "HTML" : false;
7017  };
7018  
7019  var posProcess = function(selector, context){
7020      var tmpSet = [], later = "", match,
7021          root = context.nodeType ? [context] : context;
7022  
7023      // Position selectors must be done after the filter
7024      // And so must :not(positional) so we move all PSEUDOs to the end
7025      while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
7026          later += match[0];
7027          selector = selector.replace( Expr.match.PSEUDO, "" );
7028      }
7029  
7030      selector = Expr.relative[selector] ? selector + "*" : selector;
7031  
7032      for ( var i = 0, l = root.length; i < l; i++ ) {
7033          Sizzle( selector, root[i], tmpSet );
7034      }
7035  
7036      return Sizzle.filter( later, tmpSet );
7037  };
7038  
7039  // EXPOSE
7040  
7041  window.tinymce.dom.Sizzle = Sizzle;
7042  
7043  })();
7044  
7045  
7046  (function(tinymce) {
7047      // Shorten names
7048      var each = tinymce.each, DOM = tinymce.DOM, isIE = tinymce.isIE, isWebKit = tinymce.isWebKit, Event;
7049  
7050      tinymce.create('tinymce.dom.EventUtils', {
7051          EventUtils : function() {
7052              this.inits = [];
7053              this.events = [];
7054          },
7055  
7056          add : function(o, n, f, s) {
7057              var cb, t = this, el = t.events, r;
7058  
7059              if (n instanceof Array) {
7060                  r = [];
7061  
7062                  each(n, function(n) {
7063                      r.push(t.add(o, n, f, s));
7064                  });
7065  
7066                  return r;
7067              }
7068  
7069              // Handle array
7070              if (o && o.hasOwnProperty && o instanceof Array) {
7071                  r = [];
7072  
7073                  each(o, function(o) {
7074                      o = DOM.get(o);
7075                      r.push(t.add(o, n, f, s));
7076                  });
7077  
7078                  return r;
7079              }
7080  
7081              o = DOM.get(o);
7082  
7083              if (!o)
7084                  return;
7085  
7086              // Setup event callback
7087              cb = function(e) {
7088                  // Is all events disabled
7089                  if (t.disabled)
7090                      return;
7091  
7092                  e = e || window.event;
7093  
7094                  // Patch in target, preventDefault and stopPropagation in IE it's W3C valid
7095                  if (e && isIE) {
7096                      if (!e.target)
7097                          e.target = e.srcElement;
7098  
7099                      // Patch in preventDefault, stopPropagation methods for W3C compatibility
7100                      tinymce.extend(e, t._stoppers);
7101                  }
7102  
7103                  if (!s)
7104                      return f(e);
7105  
7106                  return f.call(s, e);
7107              };
7108  
7109              if (n == 'unload') {
7110                  tinymce.unloads.unshift({func : cb});
7111                  return cb;
7112              }
7113  
7114              if (n == 'init') {
7115                  if (t.domLoaded)
7116                      cb();
7117                  else
7118                      t.inits.push(cb);
7119  
7120                  return cb;
7121              }
7122  
7123              // Store away listener reference
7124              el.push({
7125                  obj : o,
7126                  name : n,
7127                  func : f,
7128                  cfunc : cb,
7129                  scope : s
7130              });
7131  
7132              t._add(o, n, cb);
7133  
7134              return f;
7135          },
7136  
7137          remove : function(o, n, f) {
7138              var t = this, a = t.events, s = false, r;
7139  
7140              // Handle array
7141              if (o && o.hasOwnProperty && o instanceof Array) {
7142                  r = [];
7143  
7144                  each(o, function(o) {
7145                      o = DOM.get(o);
7146                      r.push(t.remove(o, n, f));
7147                  });
7148  
7149                  return r;
7150              }
7151  
7152              o = DOM.get(o);
7153  
7154              each(a, function(e, i) {
7155                  if (e.obj == o && e.name == n && (!f || (e.func == f || e.cfunc == f))) {
7156                      a.splice(i, 1);
7157                      t._remove(o, n, e.cfunc);
7158                      s = true;
7159                      return false;
7160                  }
7161              });
7162  
7163              return s;
7164          },
7165  
7166          clear : function(o) {
7167              var t = this, a = t.events, i, e;
7168  
7169              if (o) {
7170                  o = DOM.get(o);
7171  
7172                  for (i = a.length - 1; i >= 0; i--) {
7173                      e = a[i];
7174  
7175                      if (e.obj === o) {
7176                          t._remove(e.obj, e.name, e.cfunc);
7177                          e.obj = e.cfunc = null;
7178                          a.splice(i, 1);
7179                      }
7180                  }
7181              }
7182          },
7183  
7184          cancel : function(e) {
7185              if (!e)
7186                  return false;
7187  
7188              this.stop(e);
7189  
7190              return this.prevent(e);
7191          },
7192  
7193          stop : function(e) {
7194              if (e.stopPropagation)
7195                  e.stopPropagation();
7196              else
7197                  e.cancelBubble = true;
7198  
7199              return false;
7200          },
7201  
7202          prevent : function(e) {
7203              if (e.preventDefault)
7204                  e.preventDefault();
7205              else
7206                  e.returnValue = false;
7207  
7208              return false;
7209          },
7210  
7211          destroy : function() {
7212              var t = this;
7213  
7214              each(t.events, function(e, i) {
7215                  t._remove(e.obj, e.name, e.cfunc);
7216                  e.obj = e.cfunc = null;
7217              });
7218  
7219              t.events = [];
7220              t = null;
7221          },
7222  
7223          _add : function(o, n, f) {
7224              if (o.attachEvent)
7225                  o.attachEvent('on' + n, f);
7226              else if (o.addEventListener)
7227                  o.addEventListener(n, f, false);
7228              else
7229                  o['on' + n] = f;
7230          },
7231  
7232          _remove : function(o, n, f) {
7233              if (o) {
7234                  try {
7235                      if (o.detachEvent)
7236                          o.detachEvent('on' + n, f);
7237                      else if (o.removeEventListener)
7238                          o.removeEventListener(n, f, false);
7239                      else
7240                          o['on' + n] = null;
7241                  } catch (ex) {
7242                      // Might fail with permission denined on IE so we just ignore that
7243                  }
7244              }
7245          },
7246  
7247          _pageInit : function(win) {
7248              var t = this;
7249  
7250              // Keep it from running more than once
7251              if (t.domLoaded)
7252                  return;
7253  
7254              t.domLoaded = true;
7255  
7256              each(t.inits, function(c) {
7257                  c();
7258              });
7259  
7260              t.inits = [];
7261          },
7262  
7263          _wait : function(win) {
7264              var t = this, doc = win.document;
7265  
7266              // No need since the document is already loaded
7267              if (win.tinyMCE_GZ && tinyMCE_GZ.loaded) {
7268                  t.domLoaded = 1;
7269                  return;
7270              }
7271  
7272              // Use IE method
7273              if (doc.attachEvent) {
7274                  doc.attachEvent("onreadystatechange", function() {
7275                      if (doc.readyState === "complete") {
7276                          doc.detachEvent("onreadystatechange", arguments.callee);
7277                          t._pageInit(win);
7278                      }
7279                  });
7280  
7281                  if (doc.documentElement.doScroll && win == win.top) {
7282                      (function() {
7283                          if (t.domLoaded)
7284                              return;
7285  
7286                          try {
7287                              // If IE is used, use the trick by Diego Perini licensed under MIT by request to the author.
7288                              // http://javascript.nwbox.com/IEContentLoaded/
7289                              doc.documentElement.doScroll("left");
7290                          } catch (ex) {
7291                              setTimeout(arguments.callee, 0);
7292                              return;
7293                          }
7294  
7295                          t._pageInit(win);
7296                      })();
7297                  }
7298              } else if (doc.addEventListener) {
7299                  t._add(win, 'DOMContentLoaded', function() {
7300                      t._pageInit(win);
7301                  });
7302              }
7303  
7304              t._add(win, 'load', function() {
7305                  t._pageInit(win);
7306              });
7307          },
7308  
7309          _stoppers : {
7310              preventDefault : function() {
7311                  this.returnValue = false;
7312              },
7313  
7314              stopPropagation : function() {
7315                  this.cancelBubble = true;
7316              }
7317          }
7318      });
7319  
7320      Event = tinymce.dom.Event = new tinymce.dom.EventUtils();
7321  
7322      // Dispatch DOM content loaded event for IE and Safari
7323      Event._wait(window);
7324  
7325      tinymce.addUnload(function() {
7326          Event.destroy();
7327      });
7328  })(tinymce);
7329  
7330  (function(tinymce) {
7331      tinymce.dom.Element = function(id, settings) {
7332          var t = this, dom, el;
7333  
7334          t.settings = settings = settings || {};
7335          t.id = id;
7336          t.dom = dom = settings.dom || tinymce.DOM;
7337  
7338          // Only IE leaks DOM references, this is a lot faster
7339          if (!tinymce.isIE)
7340              el = dom.get(t.id);
7341  
7342          tinymce.each(
7343                  ('getPos,getRect,getParent,add,setStyle,getStyle,setStyles,' + 
7344                  'setAttrib,setAttribs,getAttrib,addClass,removeClass,' + 
7345                  'hasClass,getOuterHTML,setOuterHTML,remove,show,hide,' + 
7346                  'isHidden,setHTML,get').split(/,/)
7347              , function(k) {
7348                  t[k] = function() {
7349                      var a = [id], i;
7350  
7351                      for (i = 0; i < arguments.length; i++)
7352                          a.push(arguments[i]);
7353  
7354                      a = dom[k].apply(dom, a);
7355                      t.update(k);
7356  
7357                      return a;
7358                  };
7359          });
7360  
7361          tinymce.extend(t, {
7362              on : function(n, f, s) {
7363                  return tinymce.dom.Event.add(t.id, n, f, s);
7364              },
7365  
7366              getXY : function() {
7367                  return {
7368                      x : parseInt(t.getStyle('left')),
7369                      y : parseInt(t.getStyle('top'))
7370                  };
7371              },
7372  
7373              getSize : function() {
7374                  var n = dom.get(t.id);
7375  
7376                  return {
7377                      w : parseInt(t.getStyle('width') || n.clientWidth),
7378                      h : parseInt(t.getStyle('height') || n.clientHeight)
7379                  };
7380              },
7381  
7382              moveTo : function(x, y) {
7383                  t.setStyles({left : x, top : y});
7384              },
7385  
7386              moveBy : function(x, y) {
7387                  var p = t.getXY();
7388  
7389                  t.moveTo(p.x + x, p.y + y);
7390              },
7391  
7392              resizeTo : function(w, h) {
7393                  t.setStyles({width : w, height : h});
7394              },
7395  
7396              resizeBy : function(w, h) {
7397                  var s = t.getSize();
7398  
7399                  t.resizeTo(s.w + w, s.h + h);
7400              },
7401  
7402              update : function(k) {
7403                  var b;
7404  
7405                  if (tinymce.isIE6 && settings.blocker) {
7406                      k = k || '';
7407  
7408                      // Ignore getters
7409                      if (k.indexOf('get') === 0 || k.indexOf('has') === 0 || k.indexOf('is') === 0)
7410                          return;
7411  
7412                      // Remove blocker on remove
7413                      if (k == 'remove') {
7414                          dom.remove(t.blocker);
7415                          return;
7416                      }
7417  
7418                      if (!t.blocker) {
7419                          t.blocker = dom.uniqueId();
7420                          b = dom.add(settings.container || dom.getRoot(), 'iframe', {id : t.blocker, style : 'position:absolute;', frameBorder : 0, src : 'javascript:""'});
7421                          dom.setStyle(b, 'opacity', 0);
7422                      } else
7423                          b = dom.get(t.blocker);
7424  
7425                      dom.setStyles(b, {
7426                          left : t.getStyle('left', 1),
7427                          top : t.getStyle('top', 1),
7428                          width : t.getStyle('width', 1),
7429                          height : t.getStyle('height', 1),
7430                          display : t.getStyle('display', 1),
7431                          zIndex : parseInt(t.getStyle('zIndex', 1) || 0) - 1
7432                      });
7433                  }
7434              }
7435          });
7436      };
7437  })(tinymce);
7438  
7439  (function(tinymce) {
7440  	function trimNl(s) {
7441          return s.replace(/[\n\r]+/g, '');
7442      };
7443  
7444      // Shorten names
7445      var is = tinymce.is, isIE = tinymce.isIE, each = tinymce.each;
7446  
7447      tinymce.create('tinymce.dom.Selection', {
7448          Selection : function(dom, win, serializer) {
7449              var t = this;
7450  
7451              t.dom = dom;
7452              t.win = win;
7453              t.serializer = serializer;
7454  
7455              // Add events
7456              each([
7457                  'onBeforeSetContent',
7458  
7459                  'onBeforeGetContent',
7460  
7461                  'onSetContent',
7462  
7463                  'onGetContent'
7464              ], function(e) {
7465                  t[e] = new tinymce.util.Dispatcher(t);
7466              });
7467  
7468              // No W3C Range support
7469              if (!t.win.getSelection)
7470                  t.tridentSel = new tinymce.dom.TridentSelection(t);
7471  
7472              if (tinymce.isIE && dom.boxModel)
7473                  this._fixIESelection();
7474  
7475              // Prevent leaks
7476              tinymce.addUnload(t.destroy, t);
7477          },
7478  
7479          setCursorLocation: function(node, offset) {
7480              var t = this; var r = t.dom.createRng();
7481              r.setStart(node, offset);
7482              r.setEnd(node, offset);
7483              t.setRng(r);
7484              t.collapse(false);
7485          },
7486          getContent : function(s) {
7487              var t = this, r = t.getRng(), e = t.dom.create("body"), se = t.getSel(), wb, wa, n;
7488  
7489              s = s || {};
7490              wb = wa = '';
7491              s.get = true;
7492              s.format = s.format || 'html';
7493              s.forced_root_block = '';
7494              t.onBeforeGetContent.dispatch(t, s);
7495  
7496              if (s.format == 'text')
7497                  return t.isCollapsed() ? '' : (r.text || (se.toString ? se.toString() : ''));
7498  
7499              if (r.cloneContents) {
7500                  n = r.cloneContents();
7501  
7502                  if (n)
7503                      e.appendChild(n);
7504              } else if (is(r.item) || is(r.htmlText)) {
7505                  // IE will produce invalid markup if elements are present that
7506                  // it doesn't understand like custom elements or HTML5 elements.
7507                  // Adding a BR in front of the contents and then remoiving it seems to fix it though.
7508                  e.innerHTML = '<br>' + (r.item ? r.item(0).outerHTML : r.htmlText);
7509                  e.removeChild(e.firstChild);
7510              } else
7511                  e.innerHTML = r.toString();
7512  
7513              // Keep whitespace before and after
7514              if (/^\s/.test(e.innerHTML))
7515                  wb = ' ';
7516  
7517              if (/\s+$/.test(e.innerHTML))
7518                  wa = ' ';
7519  
7520              s.getInner = true;
7521  
7522              s.content = t.isCollapsed() ? '' : wb + t.serializer.serialize(e, s) + wa;
7523              t.onGetContent.dispatch(t, s);
7524  
7525              return s.content;
7526          },
7527  
7528          setContent : function(content, args) {
7529              var self = this, rng = self.getRng(), caretNode, doc = self.win.document, frag, temp;
7530  
7531              args = args || {format : 'html'};
7532              args.set = true;
7533              content = args.content = content;
7534  
7535              // Dispatch before set content event
7536              if (!args.no_events)
7537                  self.onBeforeSetContent.dispatch(self, args);
7538  
7539              content = args.content;
7540  
7541              if (rng.insertNode) {
7542                  // Make caret marker since insertNode places the caret in the beginning of text after insert
7543                  content += '<span id="__caret">_</span>';
7544  
7545                  // Delete and insert new node
7546                  if (rng.startContainer == doc && rng.endContainer == doc) {
7547                      // WebKit will fail if the body is empty since the range is then invalid and it can't insert contents
7548                      doc.body.innerHTML = content;
7549                  } else {
7550                      rng.deleteContents();
7551  
7552                      if (doc.body.childNodes.length == 0) {
7553                          doc.body.innerHTML = content;
7554                      } else {
7555                          // createContextualFragment doesn't exists in IE 9 DOMRanges
7556                          if (rng.createContextualFragment) {
7557                              rng.insertNode(rng.createContextualFragment(content));
7558                          } else {
7559                              // Fake createContextualFragment call in IE 9
7560                              frag = doc.createDocumentFragment();
7561                              temp = doc.createElement('div');
7562  
7563                              frag.appendChild(temp);
7564                              temp.outerHTML = content;
7565  
7566                              rng.insertNode(frag);
7567                          }
7568                      }
7569                  }
7570  
7571                  // Move to caret marker
7572                  caretNode = self.dom.get('__caret');
7573  
7574                  // Make sure we wrap it compleatly, Opera fails with a simple select call
7575                  rng = doc.createRange();
7576                  rng.setStartBefore(caretNode);
7577                  rng.setEndBefore(caretNode);
7578                  self.setRng(rng);
7579  
7580                  // Remove the caret position
7581                  self.dom.remove('__caret');
7582  
7583                  try {
7584                      self.setRng(rng);
7585                  } catch (ex) {
7586                      // Might fail on Opera for some odd reason
7587                  }
7588              } else {
7589                  if (rng.item) {
7590                      // Delete content and get caret text selection
7591                      doc.execCommand('Delete', false, null);
7592                      rng = self.getRng();
7593                  }
7594  
7595                  // Explorer removes spaces from the beginning of pasted contents
7596                  if (/^\s+/.test(content)) {
7597                      rng.pasteHTML('<span id="__mce_tmp">_</span>' + content);
7598                      self.dom.remove('__mce_tmp');
7599                  } else
7600                      rng.pasteHTML(content);
7601              }
7602  
7603              // Dispatch set content event
7604              if (!args.no_events)
7605                  self.onSetContent.dispatch(self, args);
7606          },
7607  
7608          getStart : function() {
7609              var rng = this.getRng(), startElement, parentElement, checkRng, node;
7610  
7611              if (rng.duplicate || rng.item) {
7612                  // Control selection, return first item
7613                  if (rng.item)
7614                      return rng.item(0);
7615  
7616                  // Get start element
7617                  checkRng = rng.duplicate();
7618                  checkRng.collapse(1);
7619                  startElement = checkRng.parentElement();
7620  
7621                  // Check if range parent is inside the start element, then return the inner parent element
7622                  // This will fix issues when a single element is selected, IE would otherwise return the wrong start element
7623                  parentElement = node = rng.parentElement();
7624                  while (node = node.parentNode) {
7625                      if (node == startElement) {
7626                          startElement = parentElement;
7627                          break;
7628                      }
7629                  }
7630  
7631                  return startElement;
7632              } else {
7633                  startElement = rng.startContainer;
7634  
7635                  if (startElement.nodeType == 1 && startElement.hasChildNodes())
7636                      startElement = startElement.childNodes[Math.min(startElement.childNodes.length - 1, rng.startOffset)];
7637  
7638                  if (startElement && startElement.nodeType == 3)
7639                      return startElement.parentNode;
7640  
7641                  return startElement;
7642              }
7643          },
7644  
7645          getEnd : function() {
7646              var t = this, r = t.getRng(), e, eo;
7647  
7648              if (r.duplicate || r.item) {
7649                  if (r.item)
7650                      return r.item(0);
7651  
7652                  r = r.duplicate();
7653                  r.collapse(0);
7654                  e = r.parentElement();
7655  
7656                  if (e && e.nodeName == 'BODY')
7657                      return e.lastChild || e;
7658  
7659                  return e;
7660              } else {
7661                  e = r.endContainer;
7662                  eo = r.endOffset;
7663  
7664                  if (e.nodeType == 1 && e.hasChildNodes())
7665                      e = e.childNodes[eo > 0 ? eo - 1 : eo];
7666  
7667                  if (e && e.nodeType == 3)
7668                      return e.parentNode;
7669  
7670                  return e;
7671              }
7672          },
7673  
7674          getBookmark : function(type, normalized) {
7675              var t = this, dom = t.dom, rng, rng2, id, collapsed, name, element, index, chr = '\uFEFF', styles;
7676  
7677  			function findIndex(name, element) {
7678                  var index = 0;
7679  
7680                  each(dom.select(name), function(node, i) {
7681                      if (node == element)
7682                          index = i;
7683                  });
7684  
7685                  return index;
7686              };
7687  
7688              if (type == 2) {
7689  				function getLocation() {
7690                      var rng = t.getRng(true), root = dom.getRoot(), bookmark = {};
7691  
7692  					function getPoint(rng, start) {
7693                          var container = rng[start ? 'startContainer' : 'endContainer'],
7694                              offset = rng[start ? 'startOffset' : 'endOffset'], point = [], node, childNodes, after = 0;
7695  
7696                          if (container.nodeType == 3) {
7697                              if (normalized) {
7698                                  for (node = container.previousSibling; node && node.nodeType == 3; node = node.previousSibling)
7699                                      offset += node.nodeValue.length;
7700                              }
7701  
7702                              point.push(offset);
7703                          } else {
7704                              childNodes = container.childNodes;
7705  
7706                              if (offset >= childNodes.length && childNodes.length) {
7707                                  after = 1;
7708                                  offset = Math.max(0, childNodes.length - 1);
7709                              }
7710  
7711                              point.push(t.dom.nodeIndex(childNodes[offset], normalized) + after);
7712                          }
7713  
7714                          for (; container && container != root; container = container.parentNode)
7715                              point.push(t.dom.nodeIndex(container, normalized));
7716  
7717                          return point;
7718                      };
7719  
7720                      bookmark.start = getPoint(rng, true);
7721  
7722                      if (!t.isCollapsed())
7723                          bookmark.end = getPoint(rng);
7724  
7725                      return bookmark;
7726                  };
7727  
7728                  if (t.tridentSel)
7729                      return t.tridentSel.getBookmark(type);
7730  
7731                  return getLocation();
7732              }
7733  
7734              // Handle simple range
7735              if (type)
7736                  return {rng : t.getRng()};
7737  
7738              rng = t.getRng();
7739              id = dom.uniqueId();
7740              collapsed = tinyMCE.activeEditor.selection.isCollapsed();
7741              styles = 'overflow:hidden;line-height:0px';
7742  
7743              // Explorer method
7744              if (rng.duplicate || rng.item) {
7745                  // Text selection
7746                  if (!rng.item) {
7747                      rng2 = rng.duplicate();
7748  
7749                      try {
7750                          // Insert start marker
7751                          rng.collapse();
7752                          rng.pasteHTML('<span data-mce-type="bookmark" id="' + id + '_start" style="' + styles + '">' + chr + '</span>');
7753  
7754                          // Insert end marker
7755                          if (!collapsed) {
7756                              rng2.collapse(false);
7757  
7758                              // Detect the empty space after block elements in IE and move the end back one character <p></p>] becomes <p>]</p>
7759                              rng.moveToElementText(rng2.parentElement());
7760                              if (rng.compareEndPoints('StartToEnd', rng2) == 0)
7761                                  rng2.move('character', -1);
7762  
7763                              rng2.pasteHTML('<span data-mce-type="bookmark" id="' + id + '_end" style="' + styles + '">' + chr + '</span>');
7764                          }
7765                      } catch (ex) {
7766                          // IE might throw unspecified error so lets ignore it
7767                          return null;
7768                      }
7769                  } else {
7770                      // Control selection
7771                      element = rng.item(0);
7772                      name = element.nodeName;
7773  
7774                      return {name : name, index : findIndex(name, element)};
7775                  }
7776              } else {
7777                  element = t.getNode();
7778                  name = element.nodeName;
7779                  if (name == 'IMG')
7780                      return {name : name, index : findIndex(name, element)};
7781  
7782                  // W3C method
7783                  rng2 = rng.cloneRange();
7784  
7785                  // Insert end marker
7786                  if (!collapsed) {
7787                      rng2.collapse(false);
7788                      rng2.insertNode(dom.create('span', {'data-mce-type' : "bookmark", id : id + '_end', style : styles}, chr));
7789                  }
7790  
7791                  rng.collapse(true);
7792                  rng.insertNode(dom.create('span', {'data-mce-type' : "bookmark", id : id + '_start', style : styles}, chr));
7793              }
7794  
7795              t.moveToBookmark({id : id, keep : 1});
7796  
7797              return {id : id};
7798          },
7799  
7800          moveToBookmark : function(bookmark) {
7801              var t = this, dom = t.dom, marker1, marker2, rng, root, startContainer, endContainer, startOffset, endOffset;
7802  
7803              if (bookmark) {
7804                  if (bookmark.start) {
7805                      rng = dom.createRng();
7806                      root = dom.getRoot();
7807  
7808  					function setEndPoint(start) {
7809                          var point = bookmark[start ? 'start' : 'end'], i, node, offset, children;
7810  
7811                          if (point) {
7812                              offset = point[0];
7813  
7814                              // Find container node
7815                              for (node = root, i = point.length - 1; i >= 1; i--) {
7816                                  children = node.childNodes;
7817  
7818                                  if (point[i] > children.length - 1)
7819                                      return;
7820  
7821                                  node = children[point[i]];
7822                              }
7823  
7824                              // Move text offset to best suitable location
7825                              if (node.nodeType === 3)
7826                                  offset = Math.min(point[0], node.nodeValue.length);
7827  
7828                              // Move element offset to best suitable location
7829                              if (node.nodeType === 1)
7830                                  offset = Math.min(point[0], node.childNodes.length);
7831  
7832                              // Set offset within container node
7833                              if (start)
7834                                  rng.setStart(node, offset);
7835                              else
7836                                  rng.setEnd(node, offset);
7837                          }
7838  
7839                          return true;
7840                      };
7841  
7842                      if (t.tridentSel)
7843                          return t.tridentSel.moveToBookmark(bookmark);
7844  
7845                      if (setEndPoint(true) && setEndPoint()) {
7846                          t.setRng(rng);
7847                      }
7848                  } else if (bookmark.id) {
7849  					function restoreEndPoint(suffix) {
7850                          var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev, keep = bookmark.keep;
7851  
7852                          if (marker) {
7853                              node = marker.parentNode;
7854  
7855                              if (suffix == 'start') {
7856                                  if (!keep) {
7857                                      idx = dom.nodeIndex(marker);
7858                                  } else {
7859                                      node = marker.firstChild;
7860                                      idx = 1;
7861                                  }
7862  
7863                                  startContainer = endContainer = node;
7864                                  startOffset = endOffset = idx;
7865                              } else {
7866                                  if (!keep) {
7867                                      idx = dom.nodeIndex(marker);
7868                                  } else {
7869                                      node = marker.firstChild;
7870                                      idx = 1;
7871                                  }
7872  
7873                                  endContainer = node;
7874                                  endOffset = idx;
7875                              }
7876  
7877                              if (!keep) {
7878                                  prev = marker.previousSibling;
7879                                  next = marker.nextSibling;
7880  
7881                                  // Remove all marker text nodes
7882                                  each(tinymce.grep(marker.childNodes), function(node) {
7883                                      if (node.nodeType == 3)
7884                                          node.nodeValue = node.nodeValue.replace(/\uFEFF/g, '');
7885                                  });
7886  
7887                                  // Remove marker but keep children if for example contents where inserted into the marker
7888                                  // Also remove duplicated instances of the marker for example by a split operation or by WebKit auto split on paste feature
7889                                  while (marker = dom.get(bookmark.id + '_' + suffix))
7890                                      dom.remove(marker, 1);
7891  
7892                                  // If siblings are text nodes then merge them unless it's Opera since it some how removes the node
7893                                  // and we are sniffing since adding a lot of detection code for a browser with 3% of the market isn't worth the effort. Sorry, Opera but it's just a fact
7894                                  if (prev && next && prev.nodeType == next.nodeType && prev.nodeType == 3 && !tinymce.isOpera) {
7895                                      idx = prev.nodeValue.length;
7896                                      prev.appendData(next.nodeValue);
7897                                      dom.remove(next);
7898  
7899                                      if (suffix == 'start') {
7900                                          startContainer = endContainer = prev;
7901                                          startOffset = endOffset = idx;
7902                                      } else {
7903                                          endContainer = prev;
7904                                          endOffset = idx;
7905                                      }
7906                                  }
7907                              }
7908                          }
7909                      };
7910  
7911  					function addBogus(node) {
7912                          // Adds a bogus BR element for empty block elements or just a space on IE since it renders BR elements incorrectly
7913                          if (dom.isBlock(node) && !node.innerHTML)
7914                              node.innerHTML = !isIE ? '<br data-mce-bogus="1" />' : ' ';
7915  
7916                          return node;
7917                      };
7918  
7919                      // Restore start/end points
7920                      restoreEndPoint('start');
7921                      restoreEndPoint('end');
7922  
7923                      if (startContainer) {
7924                          rng = dom.createRng();
7925                          rng.setStart(addBogus(startContainer), startOffset);
7926                          rng.setEnd(addBogus(endContainer), endOffset);
7927                          t.setRng(rng);
7928                      }
7929                  } else if (bookmark.name) {
7930                      t.select(dom.select(bookmark.name)[bookmark.index]);
7931                  } else if (bookmark.rng)
7932                      t.setRng(bookmark.rng);
7933              }
7934          },
7935  
7936          select : function(node, content) {
7937              var t = this, dom = t.dom, rng = dom.createRng(), idx;
7938  
7939              if (node) {
7940                  idx = dom.nodeIndex(node);
7941                  rng.setStart(node.parentNode, idx);
7942                  rng.setEnd(node.parentNode, idx + 1);
7943  
7944                  // Find first/last text node or BR element
7945                  if (content) {
7946  					function setPoint(node, start) {
7947                          var walker = new tinymce.dom.TreeWalker(node, node);
7948  
7949                          do {
7950                              // Text node
7951                              if (node.nodeType == 3 && tinymce.trim(node.nodeValue).length != 0) {
7952                                  if (start)
7953                                      rng.setStart(node, 0);
7954                                  else
7955                                      rng.setEnd(node, node.nodeValue.length);
7956  
7957                                  return;
7958                              }
7959  
7960                              // BR element
7961                              if (node.nodeName == 'BR') {
7962                                  if (start)
7963                                      rng.setStartBefore(node);
7964                                  else
7965                                      rng.setEndBefore(node);
7966  
7967                                  return;
7968                              }
7969                          } while (node = (start ? walker.next() : walker.prev()));
7970                      };
7971  
7972                      setPoint(node, 1);
7973                      setPoint(node);
7974                  }
7975  
7976                  t.setRng(rng);
7977              }
7978  
7979              return node;
7980          },
7981  
7982          isCollapsed : function() {
7983              var t = this, r = t.getRng(), s = t.getSel();
7984  
7985              if (!r || r.item)
7986                  return false;
7987  
7988              if (r.compareEndPoints)
7989                  return r.compareEndPoints('StartToEnd', r) === 0;
7990  
7991              return !s || r.collapsed;
7992          },
7993  
7994          collapse : function(to_start) {
7995              var self = this, rng = self.getRng(), node;
7996  
7997              // Control range on IE
7998              if (rng.item) {
7999                  node = rng.item(0);
8000                  rng = self.win.document.body.createTextRange();
8001                  rng.moveToElementText(node);
8002              }
8003  
8004              rng.collapse(!!to_start);
8005              self.setRng(rng);
8006          },
8007  
8008          getSel : function() {
8009              var t = this, w = this.win;
8010  
8011              return w.getSelection ? w.getSelection() : w.document.selection;
8012          },
8013  
8014          getRng : function(w3c) {
8015              var t = this, s, r, elm, doc = t.win.document;
8016  
8017              // Found tridentSel object then we need to use that one
8018              if (w3c && t.tridentSel)
8019                  return t.tridentSel.getRangeAt(0);
8020  
8021              try {
8022                  if (s = t.getSel())
8023                      r = s.rangeCount > 0 ? s.getRangeAt(0) : (s.createRange ? s.createRange() : doc.createRange());
8024              } catch (ex) {
8025                  // IE throws unspecified error here if TinyMCE is placed in a frame/iframe
8026              }
8027  
8028              // We have W3C ranges and it's IE then fake control selection since IE9 doesn't handle that correctly yet
8029              if (tinymce.isIE && r && r.setStart && doc.selection.createRange().item) {
8030                  elm = doc.selection.createRange().item(0);
8031                  r = doc.createRange();
8032                  r.setStartBefore(elm);
8033                  r.setEndAfter(elm);
8034              }
8035  
8036              // No range found then create an empty one
8037              // This can occur when the editor is placed in a hidden container element on Gecko
8038              // Or on IE when there was an exception
8039              if (!r)
8040                  r = doc.createRange ? doc.createRange() : doc.body.createTextRange();
8041  
8042              if (t.selectedRange && t.explicitRange) {
8043                  if (r.compareBoundaryPoints(r.START_TO_START, t.selectedRange) === 0 && r.compareBoundaryPoints(r.END_TO_END, t.selectedRange) === 0) {
8044                      // Safari, Opera and Chrome only ever select text which causes the range to change.
8045                      // This lets us use the originally set range if the selection hasn't been changed by the user.
8046                      r = t.explicitRange;
8047                  } else {
8048                      t.selectedRange = null;
8049                      t.explicitRange = null;
8050                  }
8051              }
8052  
8053              return r;
8054          },
8055  
8056          setRng : function(r) {
8057              var s, t = this;
8058              
8059              if (!t.tridentSel) {
8060                  s = t.getSel();
8061  
8062                  if (s) {
8063                      t.explicitRange = r;
8064  
8065                      try {
8066                          s.removeAllRanges();
8067                      } catch (ex) {
8068                          // IE9 might throw errors here don't know why
8069                      }
8070  
8071                      s.addRange(r);
8072                      // adding range isn't always successful so we need to check range count otherwise an exception can occur
8073                      t.selectedRange = s.rangeCount > 0 ? s.getRangeAt(0) : null;
8074                  }
8075              } else {
8076                  // Is W3C Range
8077                  if (r.cloneRange) {
8078                      t.tridentSel.addRange(r);
8079                      return;
8080                  }
8081  
8082                  // Is IE specific range
8083                  try {
8084                      r.select();
8085                  } catch (ex) {
8086                      // Needed for some odd IE bug #1843306
8087                  }
8088              }
8089          },
8090  
8091          setNode : function(n) {
8092              var t = this;
8093  
8094              t.setContent(t.dom.getOuterHTML(n));
8095  
8096              return n;
8097          },
8098  
8099          getNode : function() {
8100              var t = this, rng = t.getRng(), sel = t.getSel(), elm, start = rng.startContainer, end = rng.endContainer;
8101  
8102              // Range maybe lost after the editor is made visible again
8103              if (!rng)
8104                  return t.dom.getRoot();
8105  
8106              if (rng.setStart) {
8107                  elm = rng.commonAncestorContainer;
8108  
8109                  // Handle selection a image or other control like element such as anchors
8110                  if (!rng.collapsed) {
8111                      if (rng.startContainer == rng.endContainer) {
8112                          if (rng.endOffset - rng.startOffset < 2) {
8113                              if (rng.startContainer.hasChildNodes())
8114                                  elm = rng.startContainer.childNodes[rng.startOffset];
8115                          }
8116                      }
8117  
8118                      // If the anchor node is a element instead of a text node then return this element
8119                      //if (tinymce.isWebKit && sel.anchorNode && sel.anchorNode.nodeType == 1) 
8120                      //    return sel.anchorNode.childNodes[sel.anchorOffset];
8121  
8122                      // Handle cases where the selection is immediately wrapped around a node and return that node instead of it's parent.
8123                      // This happens when you double click an underlined word in FireFox.
8124                      if (start.nodeType === 3 && end.nodeType === 3) {
8125  						function skipEmptyTextNodes(n, forwards) {
8126                              var orig = n;
8127                              while (n && n.nodeType === 3 && n.length === 0) {
8128                                  n = forwards ? n.nextSibling : n.previousSibling;
8129                              }
8130                              return n || orig;
8131                          }
8132                          if (start.length === rng.startOffset) {
8133                              start = skipEmptyTextNodes(start.nextSibling, true);
8134                          } else {
8135                              start = start.parentNode;
8136                          }
8137                          if (rng.endOffset === 0) {
8138                              end = skipEmptyTextNodes(end.previousSibling, false);
8139                          } else {
8140                              end = end.parentNode;
8141                          }
8142  
8143                          if (start && start === end)
8144                              return start;
8145                      }
8146                  }
8147  
8148                  if (elm && elm.nodeType == 3)
8149                      return elm.parentNode;
8150  
8151                  return elm;
8152              }
8153  
8154              return rng.item ? rng.item(0) : rng.parentElement();
8155          },
8156  
8157          getSelectedBlocks : function(st, en) {
8158              var t = this, dom = t.dom, sb, eb, n, bl = [];
8159  
8160              sb = dom.getParent(st || t.getStart(), dom.isBlock);
8161              eb = dom.getParent(en || t.getEnd(), dom.isBlock);
8162  
8163              if (sb)
8164                  bl.push(sb);
8165  
8166              if (sb && eb && sb != eb) {
8167                  n = sb;
8168  
8169                  var walker = new tinymce.dom.TreeWalker(sb, dom.getRoot());
8170                  while ((n = walker.next()) && n != eb) {
8171                      if (dom.isBlock(n))
8172                          bl.push(n);
8173                  }
8174              }
8175  
8176              if (eb && sb != eb)
8177                  bl.push(eb);
8178  
8179              return bl;
8180          },
8181  
8182          normalize : function() {
8183              var self = this, rng, normalized;
8184  
8185              // TODO:
8186              // Retain selection direction.
8187              // Lean left/right on Gecko for inline elements.
8188              // Run this on mouse up/key up when the user manually moves the selection
8189              
8190              // Normalize only on non IE browsers for now
8191              if (tinymce.isIE)
8192                  return;
8193  
8194  			function normalizeEndPoint(start) {
8195                  var container, offset, walker, dom = self.dom, body = dom.getRoot(), node;
8196  
8197                  container = rng[(start ? 'start' : 'end') + 'Container'];
8198                  offset = rng[(start ? 'start' : 'end') + 'Offset'];
8199  
8200                  // If the container is a document move it to the body element
8201                  if (container.nodeType === 9) {
8202                      container = container.body;
8203                      offset = 0;
8204                  }
8205  
8206                  // If the container is body try move it into the closest text node or position
8207                  // TODO: Add more logic here to handle element selection cases
8208                  if (container === body) {
8209                      // Resolve the index
8210                      if (container.hasChildNodes()) {
8211                          container = container.childNodes[Math.min(!start && offset > 0 ? offset - 1 : offset, container.childNodes.length - 1)];
8212                          offset = 0;
8213  
8214                          // Don't walk into elements that doesn't have any child nodes like a IMG
8215                          if (container.hasChildNodes()) {
8216                              // Walk the DOM to find a text node to place the caret at or a BR
8217                              node = container;
8218                              walker = new tinymce.dom.TreeWalker(container, body);
8219                              do {
8220                                  // Found a text node use that position
8221                                  if (node.nodeType === 3) {
8222                                      offset = start ? 0 : node.nodeValue.length - 1;
8223                                      container = node;
8224                                      normalized = true;
8225                                      break;
8226                                  }
8227  
8228                                  // Found a BR/IMG element that we can place the caret before
8229                                  if (/^(BR|IMG)$/.test(node.nodeName)) {
8230                                      offset = dom.nodeIndex(node);
8231                                      container = node.parentNode;
8232  
8233                                      // Put caret after image when moving the end point
8234                                      if (node.nodeName ==  "IMG" && !start) {
8235                                          offset++;
8236                                      }
8237  
8238                                      normalized = true;
8239                                      break;
8240                                  }
8241                              } while (node = (start ? walker.next() : walker.prev()));
8242                          }
8243                      }
8244                  }
8245  
8246                  // Set endpoint if it was normalized
8247                  if (normalized)
8248                      rng['set' + (start ? 'Start' : 'End')](container, offset);
8249              };
8250  
8251              rng = self.getRng();
8252  
8253              // Normalize the end points
8254              normalizeEndPoint(true);
8255              
8256              if (!rng.collapsed)
8257                  normalizeEndPoint();
8258  
8259              // Set the selection if it was normalized
8260              if (normalized) {
8261                  //console.log(self.dom.dumpRng(rng));
8262                  self.setRng(rng);
8263              }
8264          },
8265  
8266          destroy : function(s) {
8267              var t = this;
8268  
8269              t.win = null;
8270  
8271              // Manual destroy then remove unload handler
8272              if (!s)
8273                  tinymce.removeUnload(t.destroy);
8274          },
8275  
8276          // IE has an issue where you can't select/move the caret by clicking outside the body if the document is in standards mode
8277          _fixIESelection : function() {
8278              var dom = this.dom, doc = dom.doc, body = doc.body, started, startRng, htmlElm;
8279  
8280              // Make HTML element unselectable since we are going to handle selection by hand
8281              doc.documentElement.unselectable = true;
8282  
8283              // Return range from point or null if it failed
8284  			function rngFromPoint(x, y) {
8285                  var rng = body.createTextRange();
8286  
8287                  try {
8288                      rng.moveToPoint(x, y);
8289                  } catch (ex) {
8290                      // IE sometimes throws and exception, so lets just ignore it
8291                      rng = null;
8292                  }
8293  
8294                  return rng;
8295              };
8296  
8297              // Fires while the selection is changing
8298  			function selectionChange(e) {
8299                  var pointRng;
8300  
8301                  // Check if the button is down or not
8302                  if (e.button) {
8303                      // Create range from mouse position
8304                      pointRng = rngFromPoint(e.x, e.y);
8305  
8306                      if (pointRng) {
8307                          // Check if pointRange is before/after selection then change the endPoint
8308                          if (pointRng.compareEndPoints('StartToStart', startRng) > 0)
8309                              pointRng.setEndPoint('StartToStart', startRng);
8310                          else
8311                              pointRng.setEndPoint('EndToEnd', startRng);
8312  
8313                          pointRng.select();
8314                      }
8315                  } else
8316                      endSelection();
8317              }
8318  
8319              // Removes listeners
8320  			function endSelection() {
8321                  var rng = doc.selection.createRange();
8322  
8323                  // If the range is collapsed then use the last start range
8324                  if (startRng && !rng.item && rng.compareEndPoints('StartToEnd', rng) === 0)
8325                      startRng.select();
8326  
8327                  dom.unbind(doc, 'mouseup', endSelection);
8328                  dom.unbind(doc, 'mousemove', selectionChange);
8329                  startRng = started = 0;
8330              };
8331  
8332              // Detect when user selects outside BODY
8333              dom.bind(doc, ['mousedown', 'contextmenu'], function(e) {
8334                  if (e.target.nodeName === 'HTML') {
8335                      if (started)
8336                          endSelection();
8337  
8338                      // Detect vertical scrollbar, since IE will fire a mousedown on the scrollbar and have target set as HTML
8339                      htmlElm = doc.documentElement;
8340                      if (htmlElm.scrollHeight > htmlElm.clientHeight)
8341                          return;
8342  
8343                      started = 1;
8344                      // Setup start position
8345                      startRng = rngFromPoint(e.x, e.y);
8346                      if (startRng) {
8347                          // Listen for selection change events
8348                          dom.bind(doc, 'mouseup', endSelection);
8349                          dom.bind(doc, 'mousemove', selectionChange);
8350  
8351                          dom.win.focus();
8352                          startRng.select();
8353                      }
8354                  }
8355              });
8356          }
8357      });
8358  })(tinymce);
8359  
8360  (function(tinymce) {
8361      tinymce.dom.Serializer = function(settings, dom, schema) {
8362          var onPreProcess, onPostProcess, isIE = tinymce.isIE, each = tinymce.each, htmlParser;
8363  
8364          // Support the old apply_source_formatting option
8365          if (!settings.apply_source_formatting)
8366              settings.indent = false;
8367  
8368          // Default DOM and Schema if they are undefined
8369          dom = dom || tinymce.DOM;
8370          schema = schema || new tinymce.html.Schema(settings);
8371          settings.entity_encoding = settings.entity_encoding || 'named';
8372          settings.remove_trailing_brs = "remove_trailing_brs" in settings ? settings.remove_trailing_brs : true;
8373  
8374          onPreProcess = new tinymce.util.Dispatcher(self);
8375  
8376          onPostProcess = new tinymce.util.Dispatcher(self);
8377  
8378          htmlParser = new tinymce.html.DomParser(settings, schema);
8379  
8380          // Convert move data-mce-src, data-mce-href and data-mce-style into nodes or process them if needed
8381          htmlParser.addAttributeFilter('src,href,style', function(nodes, name) {
8382              var i = nodes.length, node, value, internalName = 'data-mce-' + name, urlConverter = settings.url_converter, urlConverterScope = settings.url_converter_scope, undef;
8383  
8384              while (i--) {
8385                  node = nodes[i];
8386  
8387                  value = node.attributes.map[internalName];
8388                  if (value !== undef) {
8389                      // Set external name to internal value and remove internal
8390                      node.attr(name, value.length > 0 ? value : null);
8391                      node.attr(internalName, null);
8392                  } else {
8393                      // No internal attribute found then convert the value we have in the DOM
8394                      value = node.attributes.map[name];
8395  
8396                      if (name === "style")
8397                          value = dom.serializeStyle(dom.parseStyle(value), node.name);
8398                      else if (urlConverter)
8399                          value = urlConverter.call(urlConverterScope, value, name, node.name);
8400  
8401                      node.attr(name, value.length > 0 ? value : null);
8402                  }
8403              }
8404          });
8405  
8406          // Remove internal classes mceItem<..>
8407          htmlParser.addAttributeFilter('class', function(nodes, name) {
8408              var i = nodes.length, node, value;
8409  
8410              while (i--) {
8411                  node = nodes[i];
8412                  value = node.attr('class').replace(/\s*mce(Item\w+|Selected)\s*/g, '');
8413                  node.attr('class', value.length > 0 ? value : null);
8414              }
8415          });
8416  
8417          // Remove bookmark elements
8418          htmlParser.addAttributeFilter('data-mce-type', function(nodes, name, args) {
8419              var i = nodes.length, node;
8420  
8421              while (i--) {
8422                  node = nodes[i];
8423  
8424                  if (node.attributes.map['data-mce-type'] === 'bookmark' && !args.cleanup)
8425                      node.remove();
8426              }
8427          });
8428  
8429          // Force script into CDATA sections and remove the mce- prefix also add comments around styles
8430          htmlParser.addNodeFilter('script,style', function(nodes, name) {
8431              var i = nodes.length, node, value;
8432  
8433  			function trim(value) {
8434                  return value.replace(/(<!--\[CDATA\[|\]\]-->)/g, '\n')
8435                          .replace(/^[\r\n]*|[\r\n]*$/g, '')
8436                          .replace(/^\s*((<!--)?(\s*\/\/)?\s*<!\[CDATA\[|(<!--\s*)?\/\*\s*<!\[CDATA\[\s*\*\/|(\/\/)?\s*<!--|\/\*\s*<!--\s*\*\/)\s*[\r\n]*/gi, '')
8437                          .replace(/\s*(\/\*\s*\]\]>\s*\*\/(-->)?|\s*\/\/\s*\]\]>(-->)?|\/\/\s*(-->)?|\]\]>|\/\*\s*-->\s*\*\/|\s*-->\s*)\s*$/g, '');
8438              };
8439  
8440              while (i--) {
8441                  node = nodes[i];
8442                  value = node.firstChild ? node.firstChild.value : '';
8443  
8444                  if (name === "script") {
8445                      // Remove mce- prefix from script elements
8446                      node.attr('type', (node.attr('type') || 'text/javascript').replace(/^mce\-/, ''));
8447  
8448                      if (value.length > 0)
8449                          node.firstChild.value = '// <![CDATA[\n' + trim(value) + '\n// ]]>';
8450                  } else {
8451                      if (value.length > 0)
8452                          node.firstChild.value = '<!--\n' + trim(value) + '\n-->';
8453                  }
8454              }
8455          });
8456  
8457          // Convert comments to cdata and handle protected comments
8458          htmlParser.addNodeFilter('#comment', function(nodes, name) {
8459              var i = nodes.length, node;
8460  
8461              while (i--) {
8462                  node = nodes[i];
8463  
8464                  if (node.value.indexOf('[CDATA[') === 0) {
8465                      node.name = '#cdata';
8466                      node.type = 4;
8467                      node.value = node.value.replace(/^\[CDATA\[|\]\]$/g, '');
8468                  } else if (node.value.indexOf('mce:protected ') === 0) {
8469                      node.name = "#text";
8470                      node.type = 3;
8471                      node.raw = true;
8472                      node.value = unescape(node.value).substr(14);
8473                  }
8474              }
8475          });
8476  
8477          htmlParser.addNodeFilter('xml:namespace,input', function(nodes, name) {
8478              var i = nodes.length, node;
8479  
8480              while (i--) {
8481                  node = nodes[i];
8482                  if (node.type === 7)
8483                      node.remove();
8484                  else if (node.type === 1) {
8485                      if (name === "input" && !("type" in node.attributes.map))
8486                          node.attr('type', 'text');
8487                  }
8488              }
8489          });
8490  
8491          // Fix list elements, TODO: Replace this later
8492          if (settings.fix_list_elements) {
8493              htmlParser.addNodeFilter('ul,ol', function(nodes, name) {
8494                  var i = nodes.length, node, parentNode;
8495  
8496                  while (i--) {
8497                      node = nodes[i];
8498                      parentNode = node.parent;
8499  
8500                      if (parentNode.name === 'ul' || parentNode.name === 'ol') {
8501                          if (node.prev && node.prev.name === 'li') {
8502                              node.prev.append(node);
8503                          }
8504                      }
8505                  }
8506              });
8507          }
8508  
8509          // Remove internal data attributes
8510          htmlParser.addAttributeFilter('data-mce-src,data-mce-href,data-mce-style', function(nodes, name) {
8511              var i = nodes.length;
8512  
8513              while (i--) {
8514                  nodes[i].attr(name, null);
8515              }
8516          });
8517  
8518          // Return public methods
8519          return {
8520              schema : schema,
8521  
8522              addNodeFilter : htmlParser.addNodeFilter,
8523  
8524              addAttributeFilter : htmlParser.addAttributeFilter,
8525  
8526              onPreProcess : onPreProcess,
8527  
8528              onPostProcess : onPostProcess,
8529  
8530              serialize : function(node, args) {
8531                  var impl, doc, oldDoc, htmlSerializer, content;
8532  
8533                  // Explorer won't clone contents of script and style and the
8534                  // selected index of select elements are cleared on a clone operation.
8535                  if (isIE && dom.select('script,style,select,map').length > 0) {
8536                      content = node.innerHTML;
8537                      node = node.cloneNode(false);
8538                      dom.setHTML(node, content);
8539                  } else
8540                      node = node.cloneNode(true);
8541  
8542                  // Nodes needs to be attached to something in WebKit/Opera
8543                  // Older builds of Opera crashes if you attach the node to an document created dynamically
8544                  // and since we can't feature detect a crash we need to sniff the acutal build number
8545                  // This fix will make DOM ranges and make Sizzle happy!
8546                  impl = node.ownerDocument.implementation;
8547                  if (impl.createHTMLDocument) {
8548                      // Create an empty HTML document
8549                      doc = impl.createHTMLDocument("");
8550  
8551                      // Add the element or it's children if it's a body element to the new document
8552                      each(node.nodeName == 'BODY' ? node.childNodes : [node], function(node) {
8553                          doc.body.appendChild(doc.importNode(node, true));
8554                      });
8555  
8556                      // Grab first child or body element for serialization
8557                      if (node.nodeName != 'BODY')
8558                          node = doc.body.firstChild;
8559                      else
8560                          node = doc.body;
8561  
8562                      // set the new document in DOMUtils so createElement etc works
8563                      oldDoc = dom.doc;
8564                      dom.doc = doc;
8565                  }
8566  
8567                  args = args || {};
8568                  args.format = args.format || 'html';
8569  
8570                  // Pre process
8571                  if (!args.no_events) {
8572                      args.node = node;
8573                      onPreProcess.dispatch(self, args);
8574                  }
8575  
8576                  // Setup serializer
8577                  htmlSerializer = new tinymce.html.Serializer(settings, schema);
8578  
8579                  // Parse and serialize HTML
8580                  args.content = htmlSerializer.serialize(
8581                      htmlParser.parse(args.getInner ? node.innerHTML : tinymce.trim(dom.getOuterHTML(node), args), args)
8582                  );
8583  
8584                  // Replace all BOM characters for now until we can find a better solution
8585                  if (!args.cleanup)
8586                      args.content = args.content.replace(/\uFEFF|\u200B/g, '');
8587  
8588                  // Post process
8589                  if (!args.no_events)
8590                      onPostProcess.dispatch(self, args);
8591  
8592                  // Restore the old document if it was changed
8593                  if (oldDoc)
8594                      dom.doc = oldDoc;
8595  
8596                  args.node = null;
8597  
8598                  return args.content;
8599              },
8600  
8601              addRules : function(rules) {
8602                  schema.addValidElements(rules);
8603              },
8604  
8605              setRules : function(rules) {
8606                  schema.setValidElements(rules);
8607              }
8608          };
8609      };
8610  })(tinymce);
8611  (function(tinymce) {
8612      tinymce.dom.ScriptLoader = function(settings) {
8613          var QUEUED = 0,
8614              LOADING = 1,
8615              LOADED = 2,
8616              states = {},
8617              queue = [],
8618              scriptLoadedCallbacks = {},
8619              queueLoadedCallbacks = [],
8620              loading = 0,
8621              undefined;
8622  
8623  		function loadScript(url, callback) {
8624              var t = this, dom = tinymce.DOM, elm, uri, loc, id;
8625  
8626              // Execute callback when script is loaded
8627  			function done() {
8628                  dom.remove(id);
8629  
8630                  if (elm)
8631                      elm.onreadystatechange = elm.onload = elm = null;
8632  
8633                  callback();
8634              };
8635              
8636  			function error() {
8637                  // Report the error so it's easier for people to spot loading errors
8638                  if (typeof(console) !== "undefined" && console.log)
8639                      console.log("Failed to load: " + url);
8640  
8641                  // We can't mark it as done if there is a load error since
8642                  // A) We don't want to produce 404 errors on the server and
8643                  // B) the onerror event won't fire on all browsers.
8644                  // done();
8645              };
8646  
8647              id = dom.uniqueId();
8648  
8649              if (tinymce.isIE6) {
8650                  uri = new tinymce.util.URI(url);
8651                  loc = location;
8652  
8653                  // If script is from same domain and we
8654                  // use IE 6 then use XHR since it's more reliable
8655                  if (uri.host == loc.hostname && uri.port == loc.port && (uri.protocol + ':') == loc.protocol && uri.protocol.toLowerCase() != 'file') {
8656                      tinymce.util.XHR.send({
8657                          url : tinymce._addVer(uri.getURI()),
8658                          success : function(content) {
8659                              // Create new temp script element
8660                              var script = dom.create('script', {
8661                                  type : 'text/javascript'
8662                              });
8663  
8664                              // Evaluate script in global scope
8665                              script.text = content;
8666                              document.getElementsByTagName('head')[0].appendChild(script);
8667                              dom.remove(script);
8668  
8669                              done();
8670                          },
8671                          
8672                          error : error
8673                      });
8674  
8675                      return;
8676                  }
8677              }
8678  
8679              // Create new script element
8680              elm = dom.create('script', {
8681                  id : id,
8682                  type : 'text/javascript',
8683                  src : tinymce._addVer(url)
8684              });
8685  
8686              // Add onload listener for non IE browsers since IE9
8687              // fires onload event before the script is parsed and executed
8688              if (!tinymce.isIE)
8689                  elm.onload = done;
8690  
8691              // Add onerror event will get fired on some browsers but not all of them
8692              elm.onerror = error;
8693  
8694              // Opera 9.60 doesn't seem to fire the onreadystate event at correctly
8695              if (!tinymce.isOpera) {
8696                  elm.onreadystatechange = function() {
8697                      var state = elm.readyState;
8698  
8699                      // Loaded state is passed on IE 6 however there
8700                      // are known issues with this method but we can't use
8701                      // XHR in a cross domain loading
8702                      if (state == 'complete' || state == 'loaded')
8703                          done();
8704                  };
8705              }
8706  
8707              // Most browsers support this feature so we report errors
8708              // for those at least to help users track their missing plugins etc
8709              // todo: Removed since it produced error if the document is unloaded by navigating away, re-add it as an option
8710              /*elm.onerror = function() {
8711                  alert('Failed to load: ' + url);
8712              };*/
8713  
8714              // Add script to document
8715              (document.getElementsByTagName('head')[0] || document.body).appendChild(elm);
8716          };
8717  
8718          this.isDone = function(url) {
8719              return states[url] == LOADED;
8720          };
8721  
8722          this.markDone = function(url) {
8723              states[url] = LOADED;
8724          };
8725  
8726          this.add = this.load = function(url, callback, scope) {
8727              var item, state = states[url];
8728  
8729              // Add url to load queue
8730              if (state == undefined) {
8731                  queue.push(url);
8732                  states[url] = QUEUED;
8733              }
8734  
8735              if (callback) {
8736                  // Store away callback for later execution
8737                  if (!scriptLoadedCallbacks[url])
8738                      scriptLoadedCallbacks[url] = [];
8739  
8740                  scriptLoadedCallbacks[url].push({
8741                      func : callback,
8742                      scope : scope || this
8743                  });
8744              }
8745          };
8746  
8747          this.loadQueue = function(callback, scope) {
8748              this.loadScripts(queue, callback, scope);
8749          };
8750  
8751          this.loadScripts = function(scripts, callback, scope) {
8752              var loadScripts;
8753  
8754  			function execScriptLoadedCallbacks(url) {
8755                  // Execute URL callback functions
8756                  tinymce.each(scriptLoadedCallbacks[url], function(callback) {
8757                      callback.func.call(callback.scope);
8758                  });
8759  
8760                  scriptLoadedCallbacks[url] = undefined;
8761              };
8762  
8763              queueLoadedCallbacks.push({
8764                  func : callback,
8765                  scope : scope || this
8766              });
8767  
8768              loadScripts = function() {
8769                  var loadingScripts = tinymce.grep(scripts);
8770  
8771                  // Current scripts has been handled
8772                  scripts.length = 0;
8773  
8774                  // Load scripts that needs to be loaded
8775                  tinymce.each(loadingScripts, function(url) {
8776                      // Script is already loaded then execute script callbacks directly
8777                      if (states[url] == LOADED) {
8778                          execScriptLoadedCallbacks(url);
8779                          return;
8780                      }
8781  
8782                      // Is script not loading then start loading it
8783                      if (states[url] != LOADING) {
8784                          states[url] = LOADING;
8785                          loading++;
8786  
8787                          loadScript(url, function() {
8788                              states[url] = LOADED;
8789                              loading--;
8790  
8791                              execScriptLoadedCallbacks(url);
8792  
8793                              // Load more scripts if they where added by the recently loaded script
8794                              loadScripts();
8795                          });
8796                      }
8797                  });
8798  
8799                  // No scripts are currently loading then execute all pending queue loaded callbacks
8800                  if (!loading) {
8801                      tinymce.each(queueLoadedCallbacks, function(callback) {
8802                          callback.func.call(callback.scope);
8803                      });
8804  
8805                      queueLoadedCallbacks.length = 0;
8806                  }
8807              };
8808  
8809              loadScripts();
8810          };
8811      };
8812  
8813      // Global script loader
8814      tinymce.ScriptLoader = new tinymce.dom.ScriptLoader();
8815  })(tinymce);
8816  
8817  tinymce.dom.TreeWalker = function(start_node, root_node) {
8818      var node = start_node;
8819  
8820  	function findSibling(node, start_name, sibling_name, shallow) {
8821          var sibling, parent;
8822  
8823          if (node) {
8824              // Walk into nodes if it has a start
8825              if (!shallow && node[start_name])
8826                  return node[start_name];
8827  
8828              // Return the sibling if it has one
8829              if (node != root_node) {
8830                  sibling = node[sibling_name];
8831                  if (sibling)
8832                      return sibling;
8833  
8834                  // Walk up the parents to look for siblings
8835                  for (parent = node.parentNode; parent && parent != root_node; parent = parent.parentNode) {
8836                      sibling = parent[sibling_name];
8837                      if (sibling)
8838                          return sibling;
8839                  }
8840              }
8841          }
8842      };
8843  
8844      this.current = function() {
8845          return node;
8846      };
8847  
8848      this.next = function(shallow) {
8849          return (node = findSibling(node, 'firstChild', 'nextSibling', shallow));
8850      };
8851  
8852      this.prev = function(shallow) {
8853          return (node = findSibling(node, 'lastChild', 'previousSibling', shallow));
8854      };
8855  };
8856  
8857  (function(tinymce) {
8858      tinymce.dom.RangeUtils = function(dom) {
8859          var INVISIBLE_CHAR = '\uFEFF';
8860  
8861          this.walk = function(rng, callback) {
8862              var startContainer = rng.startContainer,
8863                  startOffset = rng.startOffset,
8864                  endContainer = rng.endContainer,
8865                  endOffset = rng.endOffset,
8866                  ancestor, startPoint,
8867                  endPoint, node, parent, siblings, nodes;
8868  
8869              // Handle table cell selection the table plugin enables
8870              // you to fake select table cells and perform formatting actions on them
8871              nodes = dom.select('td.mceSelected,th.mceSelected');
8872              if (nodes.length > 0) {
8873                  tinymce.each(nodes, function(node) {
8874                      callback([node]);
8875                  });
8876  
8877                  return;
8878              }
8879  
8880  			function exclude(nodes) {
8881                  var node;
8882  
8883                  // First node is excluded
8884                  node = nodes[0];
8885                  if (node.nodeType === 3 && node === startContainer && startOffset >= node.nodeValue.length) {
8886                      nodes.splice(0, 1);
8887                  }
8888  
8889                  // Last node is excluded
8890                  node = nodes[nodes.length - 1];
8891                  if (endOffset === 0 && nodes.length > 0 && node === endContainer && node.nodeType === 3) {
8892                      nodes.splice(nodes.length - 1, 1);
8893                  }
8894  
8895                  return nodes;
8896              };
8897  
8898  			function collectSiblings(node, name, end_node) {
8899                  var siblings = [];
8900  
8901                  for (; node && node != end_node; node = node[name])
8902                      siblings.push(node);
8903  
8904                  return siblings;
8905              };
8906  
8907  			function findEndPoint(node, root) {
8908                  do {
8909                      if (node.parentNode == root)
8910                          return node;
8911  
8912                      node = node.parentNode;
8913                  } while(node);
8914              };
8915  
8916  			function walkBoundary(start_node, end_node, next) {
8917                  var siblingName = next ? 'nextSibling' : 'previousSibling';
8918  
8919                  for (node = start_node, parent = node.parentNode; node && node != end_node; node = parent) {
8920                      parent = node.parentNode;
8921                      siblings = collectSiblings(node == start_node ? node : node[siblingName], siblingName);
8922  
8923                      if (siblings.length) {
8924                          if (!next)
8925                              siblings.reverse();
8926  
8927                          callback(exclude(siblings));
8928                      }
8929                  }
8930              };
8931  
8932              // If index based start position then resolve it
8933              if (startContainer.nodeType == 1 && startContainer.hasChildNodes())
8934                  startContainer = startContainer.childNodes[startOffset];
8935  
8936              // If index based end position then resolve it
8937              if (endContainer.nodeType == 1 && endContainer.hasChildNodes())
8938                  endContainer = endContainer.childNodes[Math.min(endOffset - 1, endContainer.childNodes.length - 1)];
8939  
8940              // Same container
8941              if (startContainer == endContainer)
8942                  return callback(exclude([startContainer]));
8943  
8944              // Find common ancestor and end points
8945              ancestor = dom.findCommonAncestor(startContainer, endContainer);
8946                  
8947              // Process left side
8948              for (node = startContainer; node; node = node.parentNode) {
8949                  if (node === endContainer)
8950                      return walkBoundary(startContainer, ancestor, true);
8951  
8952                  if (node === ancestor)
8953                      break;
8954              }
8955  
8956              // Process right side
8957              for (node = endContainer; node; node = node.parentNode) {
8958                  if (node === startContainer)
8959                      return walkBoundary(endContainer, ancestor);
8960  
8961                  if (node === ancestor)
8962                      break;
8963              }
8964  
8965              // Find start/end point
8966              startPoint = findEndPoint(startContainer, ancestor) || startContainer;
8967              endPoint = findEndPoint(endContainer, ancestor) || endContainer;
8968  
8969              // Walk left leaf
8970              walkBoundary(startContainer, startPoint, true);
8971  
8972              // Walk the middle from start to end point
8973              siblings = collectSiblings(
8974                  startPoint == startContainer ? startPoint : startPoint.nextSibling,
8975                  'nextSibling',
8976                  endPoint == endContainer ? endPoint.nextSibling : endPoint
8977              );
8978  
8979              if (siblings.length)
8980                  callback(exclude(siblings));
8981  
8982              // Walk right leaf
8983              walkBoundary(endContainer, endPoint);
8984          };
8985  
8986          this.split = function(rng) {
8987              var startContainer = rng.startContainer,
8988                  startOffset = rng.startOffset,
8989                  endContainer = rng.endContainer,
8990                  endOffset = rng.endOffset;
8991  
8992  			function splitText(node, offset) {
8993                  return node.splitText(offset);
8994              };
8995  
8996              // Handle single text node
8997              if (startContainer == endContainer && startContainer.nodeType == 3) {
8998                  if (startOffset > 0 && startOffset < startContainer.nodeValue.length) {
8999                      endContainer = splitText(startContainer, startOffset);
9000                      startContainer = endContainer.previousSibling;
9001  
9002                      if (endOffset > startOffset) {
9003                          endOffset = endOffset - startOffset;
9004                          startContainer = endContainer = splitText(endContainer, endOffset).previousSibling;
9005                          endOffset = endContainer.nodeValue.length;
9006                          startOffset = 0;
9007                      } else {
9008                          endOffset = 0;
9009                      }
9010                  }
9011              } else {
9012                  // Split startContainer text node if needed
9013                  if (startContainer.nodeType == 3 && startOffset > 0 && startOffset < startContainer.nodeValue.length) {
9014                      startContainer = splitText(startContainer, startOffset);
9015                      startOffset = 0;
9016                  }
9017  
9018                  // Split endContainer text node if needed
9019                  if (endContainer.nodeType == 3 && endOffset > 0 && endOffset < endContainer.nodeValue.length) {
9020                      endContainer = splitText(endContainer, endOffset).previousSibling;
9021                      endOffset = endContainer.nodeValue.length;
9022                  }
9023              }
9024  
9025              return {
9026                  startContainer : startContainer,
9027                  startOffset : startOffset,
9028                  endContainer : endContainer,
9029                  endOffset : endOffset
9030              };
9031          };
9032  
9033      };
9034  
9035      tinymce.dom.RangeUtils.compareRanges = function(rng1, rng2) {
9036          if (rng1 && rng2) {
9037              // Compare native IE ranges
9038              if (rng1.item || rng1.duplicate) {
9039                  // Both are control ranges and the selected element matches
9040                  if (rng1.item && rng2.item && rng1.item(0) === rng2.item(0))
9041                      return true;
9042  
9043                  // Both are text ranges and the range matches
9044                  if (rng1.isEqual && rng2.isEqual && rng2.isEqual(rng1))
9045                      return true;
9046              } else {
9047                  // Compare w3c ranges
9048                  return rng1.startContainer == rng2.startContainer && rng1.startOffset == rng2.startOffset;
9049              }
9050          }
9051  
9052          return false;
9053      };
9054  })(tinymce);
9055  
9056  (function(tinymce) {
9057      var Event = tinymce.dom.Event, each = tinymce.each;
9058  
9059      tinymce.create('tinymce.ui.KeyboardNavigation', {
9060          KeyboardNavigation: function(settings, dom) {
9061              var t = this, root = settings.root, items = settings.items,
9062                      enableUpDown = settings.enableUpDown, enableLeftRight = settings.enableLeftRight || !settings.enableUpDown,
9063                      excludeFromTabOrder = settings.excludeFromTabOrder,
9064                      itemFocussed, itemBlurred, rootKeydown, rootFocussed, focussedId;
9065  
9066              dom = dom || tinymce.DOM;
9067  
9068              itemFocussed = function(evt) {
9069                  focussedId = evt.target.id;
9070              };
9071              
9072              itemBlurred = function(evt) {
9073                  dom.setAttrib(evt.target.id, 'tabindex', '-1');
9074              };
9075              
9076              rootFocussed = function(evt) {
9077                  var item = dom.get(focussedId);
9078                  dom.setAttrib(item, 'tabindex', '0');
9079                  item.focus();
9080              };
9081              
9082              t.focus = function() {
9083                  dom.get(focussedId).focus();
9084              };
9085  
9086              t.destroy = function() {
9087                  each(items, function(item) {
9088                      dom.unbind(dom.get(item.id), 'focus', itemFocussed);
9089                      dom.unbind(dom.get(item.id), 'blur', itemBlurred);
9090                  });
9091  
9092                  dom.unbind(dom.get(root), 'focus', rootFocussed);
9093                  dom.unbind(dom.get(root), 'keydown', rootKeydown);
9094  
9095                  items = dom = root = t.focus = itemFocussed = itemBlurred = rootKeydown = rootFocussed = null;
9096                  t.destroy = function() {};
9097              };
9098              
9099              t.moveFocus = function(dir, evt) {
9100                  var idx = -1, controls = t.controls, newFocus;
9101  
9102                  if (!focussedId)
9103                      return;
9104  
9105                  each(items, function(item, index) {
9106                      if (item.id === focussedId) {
9107                          idx = index;
9108                          return false;
9109                      }
9110                  });
9111  
9112                  idx += dir;
9113                  if (idx < 0) {
9114                      idx = items.length - 1;
9115                  } else if (idx >= items.length) {
9116                      idx = 0;
9117                  }
9118                  
9119                  newFocus = items[idx];
9120                  dom.setAttrib(focussedId, 'tabindex', '-1');
9121                  dom.setAttrib(newFocus.id, 'tabindex', '0');
9122                  dom.get(newFocus.id).focus();
9123  
9124                  if (settings.actOnFocus) {
9125                      settings.onAction(newFocus.id);
9126                  }
9127  
9128                  if (evt)
9129                      Event.cancel(evt);
9130              };
9131              
9132              rootKeydown = function(evt) {
9133                  var DOM_VK_LEFT = 37, DOM_VK_RIGHT = 39, DOM_VK_UP = 38, DOM_VK_DOWN = 40, DOM_VK_ESCAPE = 27, DOM_VK_ENTER = 14, DOM_VK_RETURN = 13, DOM_VK_SPACE = 32;
9134                  
9135                  switch (evt.keyCode) {
9136                      case DOM_VK_LEFT:
9137                          if (enableLeftRight) t.moveFocus(-1);
9138                          break;
9139      
9140                      case DOM_VK_RIGHT:
9141                          if (enableLeftRight) t.moveFocus(1);
9142                          break;
9143      
9144                      case DOM_VK_UP:
9145                          if (enableUpDown) t.moveFocus(-1);
9146                          break;
9147  
9148                      case DOM_VK_DOWN:
9149                          if (enableUpDown) t.moveFocus(1);
9150                          break;
9151  
9152                      case DOM_VK_ESCAPE:
9153                          if (settings.onCancel) {
9154                              settings.onCancel();
9155                              Event.cancel(evt);
9156                          }
9157                          break;
9158  
9159                      case DOM_VK_ENTER:
9160                      case DOM_VK_RETURN:
9161                      case DOM_VK_SPACE:
9162                          if (settings.onAction) {
9163                              settings.onAction(focussedId);
9164                              Event.cancel(evt);
9165                          }
9166                          break;
9167                  }
9168              };
9169  
9170              // Set up state and listeners for each item.
9171              each(items, function(item, idx) {
9172                  var tabindex;
9173  
9174                  if (!item.id) {
9175                      item.id = dom.uniqueId('_mce_item_');
9176                  }
9177  
9178                  if (excludeFromTabOrder) {
9179                      dom.bind(item.id, 'blur', itemBlurred);
9180                      tabindex = '-1';
9181                  } else {
9182                      tabindex = (idx === 0 ? '0' : '-1');
9183                  }
9184  
9185                  dom.setAttrib(item.id, 'tabindex', tabindex);
9186                  dom.bind(dom.get(item.id), 'focus', itemFocussed);
9187              });
9188              
9189              // Setup initial state for root element.
9190              if (items[0]){
9191                  focussedId = items[0].id;
9192              }
9193  
9194              dom.setAttrib(root, 'tabindex', '-1');
9195              
9196              // Setup listeners for root element.
9197              dom.bind(dom.get(root), 'focus', rootFocussed);
9198              dom.bind(dom.get(root), 'keydown', rootKeydown);
9199          }
9200      });
9201  })(tinymce);
9202  
9203  (function(tinymce) {
9204      // Shorten class names
9205      var DOM = tinymce.DOM, is = tinymce.is;
9206  
9207      tinymce.create('tinymce.ui.Control', {
9208          Control : function(id, s, editor) {
9209              this.id = id;
9210              this.settings = s = s || {};
9211              this.rendered = false;
9212              this.onRender = new tinymce.util.Dispatcher(this);
9213              this.classPrefix = '';
9214              this.scope = s.scope || this;
9215              this.disabled = 0;
9216              this.active = 0;
9217              this.editor = editor;
9218          },
9219          
9220          setAriaProperty : function(property, value) {
9221              var element = DOM.get(this.id + '_aria') || DOM.get(this.id);
9222              if (element) {
9223                  DOM.setAttrib(element, 'aria-' + property, !!value);
9224              }
9225          },
9226          
9227          focus : function() {
9228              DOM.get(this.id).focus();
9229          },
9230  
9231          setDisabled : function(s) {
9232              if (s != this.disabled) {
9233                  this.setAriaProperty('disabled', s);
9234  
9235                  this.setState('Disabled', s);
9236                  this.setState('Enabled', !s);
9237                  this.disabled = s;
9238              }
9239          },
9240  
9241          isDisabled : function() {
9242              return this.disabled;
9243          },
9244  
9245          setActive : function(s) {
9246              if (s != this.active) {
9247                  this.setState('Active', s);
9248                  this.active = s;
9249                  this.setAriaProperty('pressed', s);
9250              }
9251          },
9252  
9253          isActive : function() {
9254              return this.active;
9255          },
9256  
9257          setState : function(c, s) {
9258              var n = DOM.get(this.id);
9259  
9260              c = this.classPrefix + c;
9261  
9262              if (s)
9263                  DOM.addClass(n, c);
9264              else
9265                  DOM.removeClass(n, c);
9266          },
9267  
9268          isRendered : function() {
9269              return this.rendered;
9270          },
9271  
9272          renderHTML : function() {
9273          },
9274  
9275          renderTo : function(n) {
9276              DOM.setHTML(n, this.renderHTML());
9277          },
9278  
9279          postRender : function() {
9280              var t = this, b;
9281  
9282              // Set pending states
9283              if (is(t.disabled)) {
9284                  b = t.disabled;
9285                  t.disabled = -1;
9286                  t.setDisabled(b);
9287              }
9288  
9289              if (is(t.active)) {
9290                  b = t.active;
9291                  t.active = -1;
9292                  t.setActive(b);
9293              }
9294          },
9295  
9296          remove : function() {
9297              DOM.remove(this.id);
9298              this.destroy();
9299          },
9300  
9301          destroy : function() {
9302              tinymce.dom.Event.clear(this.id);
9303          }
9304      });
9305  })(tinymce);
9306  tinymce.create('tinymce.ui.Container:tinymce.ui.Control', {
9307      Container : function(id, s, editor) {
9308          this.parent(id, s, editor);
9309  
9310          this.controls = [];
9311  
9312          this.lookup = {};
9313      },
9314  
9315      add : function(c) {
9316          this.lookup[c.id] = c;
9317          this.controls.push(c);
9318  
9319          return c;
9320      },
9321  
9322      get : function(n) {
9323          return this.lookup[n];
9324      }
9325  });
9326  
9327  
9328  tinymce.create('tinymce.ui.Separator:tinymce.ui.Control', {
9329      Separator : function(id, s) {
9330          this.parent(id, s);
9331          this.classPrefix = 'mceSeparator';
9332          this.setDisabled(true);
9333      },
9334  
9335      renderHTML : function() {
9336          return tinymce.DOM.createHTML('span', {'class' : this.classPrefix, role : 'separator', 'aria-orientation' : 'vertical', tabindex : '-1'});
9337      }
9338  });
9339  
9340  (function(tinymce) {
9341      var is = tinymce.is, DOM = tinymce.DOM, each = tinymce.each, walk = tinymce.walk;
9342  
9343      tinymce.create('tinymce.ui.MenuItem:tinymce.ui.Control', {
9344          MenuItem : function(id, s) {
9345              this.parent(id, s);
9346              this.classPrefix = 'mceMenuItem';
9347          },
9348  
9349          setSelected : function(s) {
9350              this.setState('Selected', s);
9351              this.setAriaProperty('checked', !!s);
9352              this.selected = s;
9353          },
9354  
9355          isSelected : function() {
9356              return this.selected;
9357          },
9358  
9359          postRender : function() {
9360              var t = this;
9361              
9362              t.parent();
9363  
9364              // Set pending state
9365              if (is(t.selected))
9366                  t.setSelected(t.selected);
9367          }
9368      });
9369  })(tinymce);
9370  
9371  (function(tinymce) {
9372      var is = tinymce.is, DOM = tinymce.DOM, each = tinymce.each, walk = tinymce.walk;
9373  
9374      tinymce.create('tinymce.ui.Menu:tinymce.ui.MenuItem', {
9375          Menu : function(id, s) {
9376              var t = this;
9377  
9378              t.parent(id, s);
9379              t.items = {};
9380              t.collapsed = false;
9381              t.menuCount = 0;
9382              t.onAddItem = new tinymce.util.Dispatcher(this);
9383          },
9384  
9385          expand : function(d) {
9386              var t = this;
9387  
9388              if (d) {
9389                  walk(t, function(o) {
9390                      if (o.expand)
9391                          o.expand();
9392                  }, 'items', t);
9393              }
9394  
9395              t.collapsed = false;
9396          },
9397  
9398          collapse : function(d) {
9399              var t = this;
9400  
9401              if (d) {
9402                  walk(t, function(o) {
9403                      if (o.collapse)
9404                          o.collapse();
9405                  }, 'items', t);
9406              }
9407  
9408              t.collapsed = true;
9409          },
9410  
9411          isCollapsed : function() {
9412              return this.collapsed;
9413          },
9414  
9415          add : function(o) {
9416              if (!o.settings)
9417                  o = new tinymce.ui.MenuItem(o.id || DOM.uniqueId(), o);
9418  
9419              this.onAddItem.dispatch(this, o);
9420  
9421              return this.items[o.id] = o;
9422          },
9423  
9424          addSeparator : function() {
9425              return this.add({separator : true});
9426          },
9427  
9428          addMenu : function(o) {
9429              if (!o.collapse)
9430                  o = this.createMenu(o);
9431  
9432              this.menuCount++;
9433  
9434              return this.add(o);
9435          },
9436  
9437          hasMenus : function() {
9438              return this.menuCount !== 0;
9439          },
9440  
9441          remove : function(o) {
9442              delete this.items[o.id];
9443          },
9444  
9445          removeAll : function() {
9446              var t = this;
9447  
9448              walk(t, function(o) {
9449                  if (o.removeAll)
9450                      o.removeAll();
9451                  else
9452                      o.remove();
9453  
9454                  o.destroy();
9455              }, 'items', t);
9456  
9457              t.items = {};
9458          },
9459  
9460          createMenu : function(o) {
9461              var m = new tinymce.ui.Menu(o.id || DOM.uniqueId(), o);
9462  
9463              m.onAddItem.add(this.onAddItem.dispatch, this.onAddItem);
9464  
9465              return m;
9466          }
9467      });
9468  })(tinymce);
9469  (function(tinymce) {
9470      var is = tinymce.is, DOM = tinymce.DOM, each = tinymce.each, Event = tinymce.dom.Event, Element = tinymce.dom.Element;
9471  
9472      tinymce.create('tinymce.ui.DropMenu:tinymce.ui.Menu', {
9473          DropMenu : function(id, s) {
9474              s = s || {};
9475              s.container = s.container || DOM.doc.body;
9476              s.offset_x = s.offset_x || 0;
9477              s.offset_y = s.offset_y || 0;
9478              s.vp_offset_x = s.vp_offset_x || 0;
9479              s.vp_offset_y = s.vp_offset_y || 0;
9480  
9481              if (is(s.icons) && !s.icons)
9482                  s['class'] += ' mceNoIcons';
9483  
9484              this.parent(id, s);
9485              this.onShowMenu = new tinymce.util.Dispatcher(this);
9486              this.onHideMenu = new tinymce.util.Dispatcher(this);
9487              this.classPrefix = 'mceMenu';
9488          },
9489  
9490          createMenu : function(s) {
9491              var t = this, cs = t.settings, m;
9492  
9493              s.container = s.container || cs.container;
9494              s.parent = t;
9495              s.constrain = s.constrain || cs.constrain;
9496              s['class'] = s['class'] || cs['class'];
9497              s.vp_offset_x = s.vp_offset_x || cs.vp_offset_x;
9498              s.vp_offset_y = s.vp_offset_y || cs.vp_offset_y;
9499              s.keyboard_focus = cs.keyboard_focus;
9500              m = new tinymce.ui.DropMenu(s.id || DOM.uniqueId(), s);
9501  
9502              m.onAddItem.add(t.onAddItem.dispatch, t.onAddItem);
9503  
9504              return m;
9505          },
9506          
9507          focus : function() {
9508              var t = this;
9509              if (t.keyboardNav) {
9510                  t.keyboardNav.focus();
9511              }
9512          },
9513  
9514          update : function() {
9515              var t = this, s = t.settings, tb = DOM.get('menu_' + t.id + '_tbl'), co = DOM.get('menu_' + t.id + '_co'), tw, th;
9516  
9517              tw = s.max_width ? Math.min(tb.clientWidth, s.max_width) : tb.clientWidth;
9518              th = s.max_height ? Math.min(tb.clientHeight, s.max_height) : tb.clientHeight;
9519  
9520              if (!DOM.boxModel)
9521                  t.element.setStyles({width : tw + 2, height : th + 2});
9522              else
9523                  t.element.setStyles({width : tw, height : th});
9524  
9525              if (s.max_width)
9526                  DOM.setStyle(co, 'width', tw);
9527  
9528              if (s.max_height) {
9529                  DOM.setStyle(co, 'height', th);
9530  
9531                  if (tb.clientHeight < s.max_height)
9532                      DOM.setStyle(co, 'overflow', 'hidden');
9533              }
9534          },
9535  
9536          showMenu : function(x, y, px) {
9537              var t = this, s = t.settings, co, vp = DOM.getViewPort(), w, h, mx, my, ot = 2, dm, tb, cp = t.classPrefix;
9538  
9539              t.collapse(1);
9540  
9541              if (t.isMenuVisible)
9542                  return;
9543  
9544              if (!t.rendered) {
9545                  co = DOM.add(t.settings.container, t.renderNode());
9546  
9547                  each(t.items, function(o) {
9548                      o.postRender();
9549                  });
9550  
9551                  t.element = new Element('menu_' + t.id, {blocker : 1, container : s.container});
9552              } else
9553                  co = DOM.get('menu_' + t.id);
9554  
9555              // Move layer out of sight unless it's Opera since it scrolls to top of page due to an bug
9556              if (!tinymce.isOpera)
9557                  DOM.setStyles(co, {left : -0xFFFF , top : -0xFFFF});
9558  
9559              DOM.show(co);
9560              t.update();
9561  
9562              x += s.offset_x || 0;
9563              y += s.offset_y || 0;
9564              vp.w -= 4;
9565              vp.h -= 4;
9566  
9567              // Move inside viewport if not submenu
9568              if (s.constrain) {
9569                  w = co.clientWidth - ot;
9570                  h = co.clientHeight - ot;
9571                  mx = vp.x + vp.w;
9572                  my = vp.y + vp.h;
9573  
9574                  if ((x + s.vp_offset_x + w) > mx)
9575                      x = px ? px - w : Math.max(0, (mx - s.vp_offset_x) - w);
9576  
9577                  if ((y + s.vp_offset_y + h) > my)
9578                      y = Math.max(0, (my - s.vp_offset_y) - h);
9579              }
9580  
9581              DOM.setStyles(co, {left : x , top : y});
9582              t.element.update();
9583  
9584              t.isMenuVisible = 1;
9585              t.mouseClickFunc = Event.add(co, 'click', function(e) {
9586                  var m;
9587  
9588                  e = e.target;
9589  
9590                  if (e && (e = DOM.getParent(e, 'tr')) && !DOM.hasClass(e, cp + 'ItemSub')) {
9591                      m = t.items[e.id];
9592  
9593                      if (m.isDisabled())
9594                          return;
9595  
9596                      dm = t;
9597  
9598                      while (dm) {
9599                          if (dm.hideMenu)
9600                              dm.hideMenu();
9601  
9602                          dm = dm.settings.parent;
9603                      }
9604  
9605                      if (m.settings.onclick)
9606                          m.settings.onclick(e);
9607  
9608                      return Event.cancel(e); // Cancel to fix onbeforeunload problem
9609                  }
9610              });
9611  
9612              if (t.hasMenus()) {
9613                  t.mouseOverFunc = Event.add(co, 'mouseover', function(e) {
9614                      var m, r, mi;
9615  
9616                      e = e.target;
9617                      if (e && (e = DOM.getParent(e, 'tr'))) {
9618                          m = t.items[e.id];
9619  
9620                          if (t.lastMenu)
9621                              t.lastMenu.collapse(1);
9622  
9623                          if (m.isDisabled())
9624                              return;
9625  
9626                          if (e && DOM.hasClass(e, cp + 'ItemSub')) {
9627                              //p = DOM.getPos(s.container);
9628                              r = DOM.getRect(e);
9629                              m.showMenu((r.x + r.w - ot), r.y - ot, r.x);
9630                              t.lastMenu = m;
9631                              DOM.addClass(DOM.get(m.id).firstChild, cp + 'ItemActive');
9632                          }
9633                      }
9634                  });
9635              }
9636              
9637              Event.add(co, 'keydown', t._keyHandler, t);
9638  
9639              t.onShowMenu.dispatch(t);
9640  
9641              if (s.keyboard_focus) { 
9642                  t._setupKeyboardNav(); 
9643              }
9644          },
9645  
9646          hideMenu : function(c) {
9647              var t = this, co = DOM.get('menu_' + t.id), e;
9648  
9649              if (!t.isMenuVisible)
9650                  return;
9651  
9652              if (t.keyboardNav) t.keyboardNav.destroy();
9653              Event.remove(co, 'mouseover', t.mouseOverFunc);
9654              Event.remove(co, 'click', t.mouseClickFunc);
9655              Event.remove(co, 'keydown', t._keyHandler);
9656              DOM.hide(co);
9657              t.isMenuVisible = 0;
9658  
9659              if (!c)
9660                  t.collapse(1);
9661  
9662              if (t.element)
9663                  t.element.hide();
9664  
9665              if (e = DOM.get(t.id))
9666                  DOM.removeClass(e.firstChild, t.classPrefix + 'ItemActive');
9667  
9668              t.onHideMenu.dispatch(t);
9669          },
9670  
9671          add : function(o) {
9672              var t = this, co;
9673  
9674              o = t.parent(o);
9675  
9676              if (t.isRendered && (co = DOM.get('menu_' + t.id)))
9677                  t._add(DOM.select('tbody', co)[0], o);
9678  
9679              return o;
9680          },
9681  
9682          collapse : function(d) {
9683              this.parent(d);
9684              this.hideMenu(1);
9685          },
9686  
9687          remove : function(o) {
9688              DOM.remove(o.id);
9689              this.destroy();
9690  
9691              return this.parent(o);
9692          },
9693  
9694          destroy : function() {
9695              var t = this, co = DOM.get('menu_' + t.id);
9696  
9697              if (t.keyboardNav) t.keyboardNav.destroy();
9698              Event.remove(co, 'mouseover', t.mouseOverFunc);
9699              Event.remove(DOM.select('a', co), 'focus', t.mouseOverFunc);
9700              Event.remove(co, 'click', t.mouseClickFunc);
9701              Event.remove(co, 'keydown', t._keyHandler);
9702  
9703              if (t.element)
9704                  t.element.remove();
9705  
9706              DOM.remove(co);
9707          },
9708  
9709          renderNode : function() {
9710              var t = this, s = t.settings, n, tb, co, w;
9711  
9712              w = DOM.create('div', {role: 'listbox', id : 'menu_' + t.id, 'class' : s['class'], 'style' : 'position:absolute;left:0;top:0;z-index:200000;outline:0'});
9713              if (t.settings.parent) {
9714                  DOM.setAttrib(w, 'aria-parent', 'menu_' + t.settings.parent.id);
9715              }
9716              co = DOM.add(w, 'div', {role: 'presentation', id : 'menu_' + t.id + '_co', 'class' : t.classPrefix + (s['class'] ? ' ' + s['class'] : '')});
9717              t.element = new Element('menu_' + t.id, {blocker : 1, container : s.container});
9718  
9719              if (s.menu_line)
9720                  DOM.add(co, 'span', {'class' : t.classPrefix + 'Line'});
9721  
9722  //            n = DOM.add(co, 'div', {id : 'menu_' + t.id + '_co', 'class' : 'mceMenuContainer'});
9723              n = DOM.add(co, 'table', {role: 'presentation', id : 'menu_' + t.id + '_tbl', border : 0, cellPadding : 0, cellSpacing : 0});
9724              tb = DOM.add(n, 'tbody');
9725  
9726              each(t.items, function(o) {
9727                  t._add(tb, o);
9728              });
9729  
9730              t.rendered = true;
9731  
9732              return w;
9733          },
9734  
9735          // Internal functions
9736          _setupKeyboardNav : function(){
9737              var contextMenu, menuItems, t=this; 
9738              contextMenu = DOM.get('menu_' + t.id);
9739              menuItems = DOM.select('a[role=option]', 'menu_' + t.id);
9740              menuItems.splice(0,0,contextMenu);
9741              t.keyboardNav = new tinymce.ui.KeyboardNavigation({
9742                  root: 'menu_' + t.id,
9743                  items: menuItems,
9744                  onCancel: function() {
9745                      t.hideMenu();
9746                  },
9747                  enableUpDown: true
9748              });
9749              contextMenu.focus();
9750          },
9751  
9752          _keyHandler : function(evt) {
9753              var t = this, e;
9754              switch (evt.keyCode) {
9755                  case 37: // Left
9756                      if (t.settings.parent) {
9757                          t.hideMenu();
9758                          t.settings.parent.focus();
9759                          Event.cancel(evt);
9760                      }
9761                      break;
9762                  case 39: // Right
9763                      if (t.mouseOverFunc)
9764                          t.mouseOverFunc(evt);
9765                      break;
9766              }
9767          },
9768  
9769          _add : function(tb, o) {
9770              var n, s = o.settings, a, ro, it, cp = this.classPrefix, ic;
9771  
9772              if (s.separator) {
9773                  ro = DOM.add(tb, 'tr', {id : o.id, 'class' : cp + 'ItemSeparator'});
9774                  DOM.add(ro, 'td', {'class' : cp + 'ItemSeparator'});
9775  
9776                  if (n = ro.previousSibling)
9777                      DOM.addClass(n, 'mceLast');
9778  
9779                  return;
9780              }
9781  
9782              n = ro = DOM.add(tb, 'tr', {id : o.id, 'class' : cp + 'Item ' + cp + 'ItemEnabled'});
9783              n = it = DOM.add(n, s.titleItem ? 'th' : 'td');
9784              n = a = DOM.add(n, 'a', {id: o.id + '_aria',  role: s.titleItem ? 'presentation' : 'option', href : 'javascript:;', onclick : "return false;", onmousedown : 'return false;'});
9785  
9786              if (s.parent) {
9787                  DOM.setAttrib(a, 'aria-haspopup', 'true');
9788                  DOM.setAttrib(a, 'aria-owns', 'menu_' + o.id);
9789              }
9790  
9791              D