// Global Killswitch
if (Drupal.jsEnabled) {
  (function ($, window, document) {
    // All available brushes for highlighting.
    var brushes = [
      "AppleScript",
      "AS3",
      "Bash",
      "ColdFusion",
      "Cpp",
      "CSharp",
      "Css",
      "Delphi",
      "Diff",
      "Erlang",
      "Groovy",
      "Java",
      "JavaFX",
      "JScript",
      "Perl",
      "Php",
      "Plain",
      "PowerShell",
      "Python",
      "Ruby",
      "Sass",
      "Scala",
      "Sql",
      "Vb",
      "Xml"
    ];

    $(function () {
      var settings = Drupal.settings.syntax_highlighter,
          bl = brushes.length,
          i = 0,
          codes = $(settings.selector),
          toLoad = {},
          cssAdded = false,
          filterCodes;

      if (codes.length) {
        // Create a RegExp for matching the class of the code with any brush.
        // The code should have a class of `brush-TYPE` ex. `brush-JScript`.
        // Matching is case sensitive.
        filterCodes = (function (classesRx) {
          return function () {
            var matches = this.className.match(classesRx),
                lineMatches,
                brush;
            // Check if there are any classes we have as a brush
            if (matches) {
              // Store the brush in the items to load, and as data in the element.
              brush = matches[1];
              toLoad[brush] = brush;
              $.data(this, 'brush', brush);

              lineMatches = this.className.match(/(?:^|\s)brushline-(\d+)(?:$|\s)/);
              if (lineMatches) {
                $.data(this, 'brushFirstLine', lineMatches[1]);
              }

              return true;
            }
            else {
              return false;
            }
          };
        }(new RegExp('(?:^|\\s)brush-(' + brushes.join('|') + ')(?:$|\\s)')));

        // Filter the codes if there are any of them, that should be syntax highlighted.
        codes = codes.filter(filterCodes);

        // Check if we still have elements...
        if (codes.length) {
          // Load CSS files dynamically. Hack needed to work in IE.
          (function () {
            var i, link, sa = 'setAttribute', head = $('head')[0];

            for (i = arguments.length - 1; i >= 0; i -= 1) {
              link = document.createElement('link');
              link[sa]('rel', 'stylesheet');
              link[sa]('type', 'text/css');
              link[sa]('href', arguments[i]);
              link[sa]('media', 'all');
              head.appendChild(link);
            }
          }(
            settings.path + '/styles/shThemeDefault.css',
            settings.path + '/styles/shCore.css'
          ));

          // Load the core for the highlighter.
          $.ajax({
            'url': settings.path + '/scripts/shCore.js',
            'cache': true,
            'dataType': 'script',
            'success': function () {
              var m,
                  itemsLeft,    // # of scripts that are left to be loaded
                  sl,           // # of scripts
                  scripts = [], // Array of script URLs.
                  i = 0,
                  complete = function () {
                    var strings, popup, writeWindow,
                        sh = window.SyntaxHighlighter,
                        sSh = 'SyntaxHighlighter';

                    itemsLeft -= 1;

                    // Check if all the scripts are loaded.
                    if (itemsLeft <= 0) {
                      /**
                       * Create a new window, write it's content in, and set focus on it.
                       *
                       * @param {String} body
                       *   The body of the document.
                       * @param {String} title
                       *   The title of the window.
                       *
                       * @returns {Window}
                       *   The new window object.
                       */
                      writeWindow = function (body, title) {
                        var wnd = popup('', '_blank', 640, 250, 'scrollbars=1'),
                            doc = wnd.document;

                        doc.write(
                          '<!DOCTYPE HTML><html><head><meta charset="UTF-8"><title>' +
                          (title ? title + ' | ' + sSh : sSh) +
                          '</title></head><body>' + body + '</body></html>'
                        );
                        doc.close();
                        wnd.focus();

                        return wnd;
                      };

                      /**
                       * Create a popup window.
                       *
                       * @param {String} url
                       *   URL of the window.
                       * @param {String} name
                       *   Name of the window so it can be referred to later.
                       * @param {Number} width
                       *   Width of the window.
                       * @param {Number} height
                       *   Height of the window.
                       * @param {String}
                       *   Window options as a comma separated string.
                       */
                      popup = function (url, name, width, height, options) {
                        var x = (screen.width - width) >> 1,
                            y = (screen.height - height) >> 1,
                            win;

                        options += [
                            '',
                            'left=' + x,
                            'top=' + y,
                            'width=' + width,
                            'height=' + height
                          ].join(', ');
                        options = options.replace(/^,\s*/, '');

                        win = window.open(url, name, options);
                        win.focus();
                        return win;
                      };

                      // SyntaxHighlighter will replace the <br> to \n for us.
                      sh.config.bloggerMode = true;

                      // Set the default string
                      strings = sh.config.strings;
                      strings.about = Drupal.t('about');
                      strings.viewPlain = Drupal.t('view plain');

                      // Generate a new toolbar
                      sh.toolbar.items = {
                        list : ['viewPlain', 'about'],
                        viewPlain : {
                          execute : function (highlighter) {
                            writeWindow(
                              '<pre>' + highlighter.code + '</pre>',
                              strings.viewPlain +
                                (highlighter.title ? ' | ' + highlighter.title : '')
                            );
                          }
                        },
                        about : {
                          execute : function (highlighter) {
                            writeWindow(
                              '<div style="text-align: center"><h1><a href="http://alexgorbatchev.com/SyntaxHighlighter" target="_blank">SyntaxHighlighter</a></h1><p>JavaScript code syntax highlighter. Copyright 2004-2010 Alex Gorbatchev.</p></div>'
                            );
                          }
                        }
                      };

                      // All loaded, so apply the highlighter.
                      codes.each(function () {
                        // Finally highlight with some defaults,
                        // using the brush stored in the elements' data.
                        sh.highlight({
                          'brush'      : $.data(this, 'brush').toLowerCase(),
                          'tab-size'   : 2,
                          'gutter'     : true,
                          'toolbar'    : true,
                          'quick-code' : true,
                          'first-line' : $.data(this, 'brushFirstLine') || 1
                        }, this);
                      });
                    }
                  };

              // List all script to load.
              for (m in toLoad) {
                if (toLoad.hasOwnProperty(m)) {
                  scripts.push(settings.path + '/scripts/shBrush' + m + '.js');
                }
              }

              sl = itemsLeft = scripts.length;
              // Load the scripts.
              for (; i < sl; i += 1) {
                $.ajax({
                  'url': scripts[i],
                  'cache': true,
                  'dataType': 'script',
                  'complete': complete
                });
              }
            }
          });
        }
      }
    });
  }($, this, document));
}

