<commit_before>/**
 * selectToToggle - Show/hide an HTML block(s) according to value selected in a <select>, or <input type="radio"> element
 * Reserved JS class prefix: _stt
 * Reserved CSS class prefix: none
 * Note: Be careful if there are more than one selectToToggle elements on a page with one or more options having same values (use className on the option tags in those cases)
 **/
(function ($) {
  $.selectToToggle = function (el, toggleMap, wrapper) {

    var toggle = function() {
      for (var val in toggleMap) {
        if (val != this.value) {
          wrapper.find(toggleMap[val]).hide().removeAttr('selected checked').filter('option').each(function() { // if hiding an option element, also disable it to make it work in webkit
            var option = $(this);
            if (typeof option.data('_stt_disabled') === 'undefined') {
              option.data('_stt_disabled', !!this.disabled); // remember original disabled attribute
            }
          }).prop('disabled', true);
        }
      }

      wrapper.find(toggleMap[this.value]).show().filter('option').prop('disabled', function() {
        return $(this).data('_stt_disabled');
      }).filter('select option').parent().each(function() { //show the requried html block
        var dropdown = $(this);
        if (!dropdown.find('option:selected:enabled').length) { //in case any selected option gets hidden in this, select the first visible option
          dropdown.find('option:enabled').first().prop('selected', true);
        }
      });
    };

    el.on('change.selectToToggle', toggle);
    if (el[0].nodeName == 'SELECT' || el[0].checked) {
      toggle.apply(el[0]);
    }
  };

  $.fn.selectToToggle = function (
    toggleMap,  // map of select element's option value to corresponding jquery selectors strings (as accepted by find() method) (Optional - defaults to '._stt_[className]' if class name uses prefix _stt__, or '._stt_[value]' otherwise)
    wrapper     // wrapper element to call method 'find(selectors)' on - defaults to $(document.body)
  ) {

    return this.each(function () {
      var input = $(this);
      var tMap  = $.extend({}, toggleMap);
      wrapper   = wrapper || $(document.body);
      if ($.isEmptyObject(tMap)) {
        (this.nodeName == 'SELECT' ? input.find('option') : wrapper.find('input[name=' + this.name + ']')).each(function() {
          if (this.value) {
            tMap[this.value] = '._stt_' + ((this.className.match(/(?:\s+|^)_stt__([^\s]+)/) || []).pop() || this.value);
          }
        });
      }
      $.selectToToggle(input, tMap, wrapper);
    });
  };
})(jQuery);<commit_msg>selectToToggle can now be called as el.selectToToggle('trigger') to manually trigger the 'change' event in case change is triggered by somewhere else JavaScript instead of the user<commit_after>/**
 * selectToToggle - Show/hide an HTML block(s) according to value selected in a <select>, or <input type="radio"> element
 * Reserved JS class prefix: _stt
 * Reserved CSS class prefix: none
 * Note: Be careful if there are more than one selectToToggle elements on a page with one or more options having same values (use className on the option tags in those cases)
 **/
(function ($) {
  $.selectToToggle = function (el, options, wrapper) {

    var toggle = function() {
      for (var val in options) {
        if (val != this.value) {
          wrapper.find(options[val]).hide().removeAttr('selected checked').filter('option').each(function() { // if hiding an option element, also disable it to make it work in webkit
            var option = $(this);
            if (typeof option.data('_stt_disabled') === 'undefined') {
              option.data('_stt_disabled', !!this.disabled); // remember original disabled attribute
            }
          }).prop('disabled', true);
        }
      }

      wrapper.find(options[this.value]).show().filter('option').prop('disabled', function() {
        return $(this).data('_stt_disabled');
      }).filter('select option').parent().each(function() { //show the requried html block
        var dropdown = $(this);
        if (!dropdown.find('option:selected:enabled').length) { //in case any selected option gets hidden in this, select the first visible option
          dropdown.find('option:enabled').first().prop('selected', true);
        }
      });
    };

    if (options === 'trigger') {
      el.trigger('change.selectToToggle');
    } else {
      el.on('change.selectToToggle', toggle);
      if (el[0].nodeName == 'SELECT' || el[0].checked) {
        toggle.apply(el[0]);
      }
    }
  };

  $.fn.selectToToggle = function (
    options,    // string 'trigger' to trigger toggling for an existing element, or map of select element's option value to corresponding jquery selectors strings (as accepted by find() method) (Optional - defaults to '._stt_[className]' if class name uses prefix _stt__, or '._stt_[value]' otherwise)
    wrapper     // wrapper element to call method 'find(selectors)' on - defaults to $(document.body)
  ) {

    return this.each(function () {
      var input = $(this);
      if (options === 'trigger') {
        $.selectToToggle(input, 'trigger', wrapper);
      } else {
        var tMap  = $.extend({}, options);
        wrapper   = wrapper || $(document.body);
        if ($.isEmptyObject(tMap)) {
          (this.nodeName == 'SELECT' ? input.find('option') : wrapper.find('input[name=' + this.name + ']')).each(function() {
            if (this.value) {
              tMap[this.value] = '._stt_' + ((this.className.match(/(?:\s+|^)_stt__([^\s]+)/) || []).pop() || this.value);
            }
          });
        }
        $.selectToToggle(input, tMap, wrapper);
      }
    });
  };
})(jQuery);<|endoftext|>


<commit_before>CodeMirror.defineMode("clojure", function () {
  var BUILTIN = "builtin", COMMENT = "comment", COMMENTFORM = "comment comment-form"; STRING = "string", CHAR = "char",
      ATOM = "atom", NUMBER = "number", BRACKET = "bracket", KEYWORD = "keyword";
  var INDENT_WORD_SKIP = 2;

  function makeKeywords(str) {
    var obj = {}, words = str.split(" ");
    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
    return obj;
  }

  var atoms = makeKeywords("true false nil");

  var keywords = makeKeywords(
    "defn defn- def def- defonce defmulti defmethod defmacro defstruct deftype defprotocol defrecord defproject deftest slice defalias defhinted defmacro- defn-memo defnk defnk defonce- defunbound defunbound- defvar defvar- let letfn do case cond condp for loop recur when when-not when-let when-first if if-let if-not . .. -> ->> doto and or dosync doseq dotimes dorun doall load import unimport ns in-ns refer try catch finally throw with-open with-local-vars binding gen-class gen-and-load-class gen-and-save-class handler-case handle");

  var builtins = makeKeywords(
    "* *' *1 *2 *3 *agent* *allow-unresolved-vars* *assert* *clojure-version* *command-line-args* *compile-files* *compile-path* *compiler-options* *data-readers* *e *err* *file* *flush-on-newline* *fn-loader* *in* *math-context* *ns* *out* *print-dup* *print-length* *print-level* *print-meta* *print-readably* *read-eval* *source-path* *unchecked-math* *use-context-classloader* *verbose-defrecords* *warn-on-reflection* + +' - -' -> ->> ->ArrayChunk ->Vec ->VecNode ->VecSeq -cache-protocol-fn -reset-methods .. / < <= = == > >= EMPTY-NODE accessor aclone add-classpath add-watch agent agent-error agent-errors aget alength alias all-ns alter alter-meta! alter-var-root amap ancestors and apply areduce array-map aset aset-boolean aset-byte aset-char aset-double aset-float aset-int aset-long aset-short assert assoc assoc! assoc-in associative? atom await await-for await1 bases bean bigdec bigint biginteger binding bit-and bit-and-not bit-clear bit-flip bit-not bit-or bit-set bit-shift-left bit-shift-right bit-test bit-xor boolean boolean-array booleans bound-fn bound-fn* bound? butlast byte byte-array bytes case cast char char-array char-escape-string char-name-string char? chars chunk chunk-append chunk-buffer chunk-cons chunk-first chunk-next chunk-rest chunked-seq? class class? clear-agent-errors clojure-version coll? comment commute comp comparator compare compare-and-set! compile complement concat cond condp conj conj! cons constantly construct-proxy contains? count counted? create-ns create-struct cycle dec dec' decimal? declare default-data-readers definline definterface defmacro defmethod defmulti defn defn- defonce defprotocol defrecord defstruct deftype delay delay? deliver denominator deref derive descendants destructure disj disj! dissoc dissoc! distinct distinct? doall dorun doseq dosync dotimes doto double double-array doubles drop drop-last drop-while empty empty? ensure enumeration-seq error-handler error-mode eval even? every-pred every? ex-data ex-info extend extend-protocol extend-type extenders extends? false? ffirst file-seq filter filterv find find-keyword find-ns find-protocol-impl find-protocol-method find-var first flatten float float-array float? floats flush fn fn? fnext fnil for force format frequencies future future-call future-cancel future-cancelled? future-done? future? gen-class gen-interface gensym get get-in get-method get-proxy-class get-thread-bindings get-validator group-by hash hash-combine hash-map hash-set identical? identity if-let if-not ifn? import in-ns inc inc' init-proxy instance? int int-array integer? interleave intern interpose into into-array ints io! isa? iterate iterator-seq juxt keep keep-indexed key keys keyword keyword? last lazy-cat lazy-seq let letfn line-seq list list* list? load load-file load-reader load-string loaded-libs locking long long-array longs loop macroexpand macroexpand-1 make-array make-hierarchy map map-indexed map? mapcat mapv max max-key memfn memoize merge merge-with meta method-sig methods min min-key mod munge name namespace namespace-munge neg? newline next nfirst nil? nnext not not-any? not-empty not-every? not= ns ns-aliases ns-imports ns-interns ns-map ns-name ns-publics ns-refers ns-resolve ns-unalias ns-unmap nth nthnext nthrest num number? numerator object-array odd? or parents partial partition partition-all partition-by pcalls peek persistent! pmap pop pop! pop-thread-bindings pos? pr pr-str prefer-method prefers primitives-classnames print print-ctor print-dup print-method print-simple print-str printf println println-str prn prn-str promise proxy proxy-call-with-super proxy-mappings proxy-name proxy-super push-thread-bindings pvalues quot rand rand-int rand-nth range ratio? rational? rationalize re-find re-groups re-matcher re-matches re-pattern re-seq read read-line read-string realized? reduce reduce-kv reductions ref ref-history-count ref-max-history ref-min-history ref-set refer refer-clojure reify release-pending-sends rem remove remove-all-methods remove-method remove-ns remove-watch repeat repeatedly replace replicate require reset! reset-meta! resolve rest restart-agent resultset-seq reverse reversible? rseq rsubseq satisfies? second select-keys send send-off seq seq? seque sequence sequential? set set-error-handler! set-error-mode! set-validator! set? short short-array shorts shuffle shutdown-agents slurp some some-fn sort sort-by sorted-map sorted-map-by sorted-set sorted-set-by sorted? special-symbol? spit split-at split-with str string? struct struct-map subs subseq subvec supers swap! symbol symbol? sync take take-last take-nth take-while test the-ns thread-bound? time to-array to-array-2d trampoline transient tree-seq true? type unchecked-add unchecked-add-int unchecked-byte unchecked-char unchecked-dec unchecked-dec-int unchecked-divide-int unchecked-double unchecked-float unchecked-inc unchecked-inc-int unchecked-int unchecked-long unchecked-multiply unchecked-multiply-int unchecked-negate unchecked-negate-int unchecked-remainder-int unchecked-short unchecked-subtract unchecked-subtract-int underive unquote unquote-splicing update-in update-proxy use val vals var-get var-set var? vary-meta vec vector vector-of vector? when when-first when-let when-not while with-bindings with-bindings* with-in-str with-loading-context with-local-vars with-meta with-open with-out-str with-precision with-redefs with-redefs-fn xml-seq zero? zipmap *default-data-reader-fn* as-> cond-> cond->> reduced reduced? send-via set-agent-send-executor! set-agent-send-off-executor! some-> some->>");

  var indentKeys = makeKeywords(
    // Built-ins
    "ns fn def defn defmethod bound-fn if if-not case condp when while when-not when-first do future comment doto locking proxy with-open with-precision reify deftype defrecord defprotocol extend extend-protocol extend-type try catch " +

    // Binding forms
    "let letfn binding loop for doseq dotimes when-let if-let " +

    // Data structures
    "defstruct struct-map assoc " +

    // clojure.test
    "testing deftest " +

    // contrib
    "handler-case handle dotrace deftrace");

  var opposites = {")": "(",
                   "]": "[",
                   "}": "{"};

  var tests = {
    digit: /\d/,
    digit_or_colon: /[\d:]/,
    hex: /[0-9a-f]/i,
    sign: /[+-]/,
    exponent: /e/i,
    char: /[^\s\(\[\{\}\]\)]/,
    keyword_char: /[^\s\(\[\;\)\]]/,
    basic: /[\w\$_\-\.\*\+\/\?\><!]/,
    lang_keyword: /[\w\*\+!\-_?:\/\.#=]/,
  };

  function stateStack(indent, type, prev) { // represents a state stack object
    this.indent = indent;
    this.type = type;
    this.prev = prev;
  }

  function pushStack(state, indent, type) {
    state.indentStack = new stateStack(indent, type, state.indentStack);
  }

  function popStack(state) {
    state.indentStack = state.indentStack.prev;
  }

  function isNumber(ch, stream){
    // hex
    if ( ch === '0' && stream.eat(/x/i) ) {
      stream.eatWhile(tests.hex);
      return true;
    }

    // leading sign
    if ( ( ch == '+' || ch == '-' ) && ( tests.digit.test(stream.peek()) ) ) {
      stream.eat(tests.sign);
      ch = stream.next();
    }

    if ( tests.digit.test(ch) ) {
      stream.eat(ch);
      stream.eatWhile(tests.digit);

      if ( '.' == stream.peek() ) {
        stream.eat('.');
        stream.eatWhile(tests.digit);
      }

      if ( stream.eat(tests.exponent) ) {
        stream.eat(tests.sign);
        stream.eatWhile(tests.digit);
      }

      return true;
    }

    return false;
  }

  function eatString(stream) {
    var next, escaped = false;
    while ((next = stream.next()) != null) {
      if (next == "\"" && !escaped) {
        return false;
      }
      escaped = !escaped && next == "\\";
    }
    return "string";
  }

  function openForm(ch, stream, state, commentForms) {
    var keyWord = '', origpos = stream.pos, indentTemp = stream.column(), letter;
    if (ch == "(") while ((letter = stream.eat(tests.keyword_char)) != null) {
      keyWord += letter;
    }

    if (keyWord.length > 0 && keyWord == "comment" && commentForms) {
      state.mode = "comment";
      pushStack(state, indentTemp + INDENT_WORD_SKIP, "comment");
    } else if (keyWord.length > 0 && (indentKeys.propertyIsEnumerable(keyWord) ||
                               /^(?:def|with)/.test(keyWord))) { // indent-word
      pushStack(state, indentTemp + INDENT_WORD_SKIP, ch);
    } else { // non-indent word
      // we continue eating the spaces
      stream.eatSpace();
      if (stream.eol() || stream.peek() == ";") {
        // nothing significant after
        // we restart indentation 1 space after
        pushStack(state, indentTemp + 1, ch);
      } else {
        pushStack(state, indentTemp + stream.current().length, ch); // else we match
      }
    }
    stream.pos = origpos; // undo all the eating
  }

  function closeForm(ch, stream, state) {
    if (!state.indentStack) return;

    if (state.indentStack.type == opposites[ch]) {
      popStack(state);
    }
  }

  function commentForm(stream, state) {
    var next, escaped = false;
    while ((next = stream.next()) != null) {
      if (next == "\"") {
        return "comment-string";
      }
      if (next == "(" || next == "[" || next == "{") {
        openForm(next, stream, state);
      } else if (next == ")" && state.indentStack.type == "comment") {
        popStack(state);
        stream.backUp(1);
        return false;
      } else if(next == ")" || next == "]" || next == "}") {
        closeForm(next, stream, state);
      }

    }
    return "comment";
  }

  return {
    startState: function () {
      return {
        indentStack: null,
        indentation: 0,
        mode: false
      };
    },

    token: function (stream, state) {
      if (state.indentStack == null && stream.sol()) {
        // update indentation, but only if indentStack is empty
        state.indentation = stream.indentation();
      }

      // skip spaces
      if (stream.eatSpace()) {
        return null;
      }
      var returnType = null;

      switch(state.mode){
        case "string": // multi-line string parsing mode
          state.mode = eatString(stream);
          returnType = STRING; // continue on in string mode
          break;

        case "comment-string":
          var mode = eatString(stream);
          if(!mode) {
            state.mode = "comment";
          }
          returnType = COMMENTFORM;
          break;

        case "comment":
          state.mode = commentForm(stream, state);
          returnType = COMMENTFORM;
          break;

        default: // default parsing mode
          var ch = stream.next();

          if (ch == "\"") {
            state.mode = "string";
            returnType = STRING;
          } else if (ch == "\\") {
            stream.next();
            returnType = CHAR;
          } else if (ch == "'" && !( tests.digit_or_colon.test(stream.peek()) )) {
            returnType = ATOM;
          } else if (ch == ";") { // comment
            stream.skipToEnd(); // rest of the line is a comment
            returnType = COMMENT;
          } else if (isNumber(ch,stream)){
            returnType = NUMBER;
          } else if (ch == "(" || ch == "[" || ch == "{") {
            /**
                        Either
                        (indent-word ..
                        (non-indent-word ..
                        (;something else, bracket, etc.
                        */
            openForm(ch, stream, state, this.commentForms);
            returnType = BRACKET;
          } else if (ch == ")" || ch == "]" || ch == "}") {
            closeForm(ch, stream, state);
            returnType = BRACKET;
          } else if ( ch == ":" ) {
            stream.eatWhile(tests.lang_keyword);
            return ATOM;
          } else {
            stream.eatWhile(tests.basic);

            if (keywords && keywords.propertyIsEnumerable(stream.current())) {
              returnType = KEYWORD;
            } else if (builtins && builtins.propertyIsEnumerable(stream.current())) {
              returnType = BUILTIN;
            } else if (atoms && atoms.propertyIsEnumerable(stream.current())) {
              returnType = ATOM;
            } else returnType = null;
          }
            }

          return returnType;
        },

      indent: function (state) {
        if (state.indentStack == null) return state.indentation;
        return state.indentStack.indent;
      },

    commentForms: false,

      lineComment: ";;",
      disallowSingleQuoteStrings: true
    };
});

CodeMirror.defineMIME("text/x-clojure", "clojure");
CodeMirror.defineMIME("text/x-clojurescript", "clojure");
CodeMirror.defineMIME("clj", "clojure");
CodeMirror.defineMIME("cljs", "clojure");
<commit_msg>do not eat spaces when inside string<commit_after>CodeMirror.defineMode("clojure", function () {
  var BUILTIN = "builtin", COMMENT = "comment", COMMENTFORM = "comment comment-form"; STRING = "string", CHAR = "char",
      ATOM = "atom", NUMBER = "number", BRACKET = "bracket", KEYWORD = "keyword";
  var INDENT_WORD_SKIP = 2;

  function makeKeywords(str) {
    var obj = {}, words = str.split(" ");
    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
    return obj;
  }

  var atoms = makeKeywords("true false nil");

  var keywords = makeKeywords(
    "defn defn- def def- defonce defmulti defmethod defmacro defstruct deftype defprotocol defrecord defproject deftest slice defalias defhinted defmacro- defn-memo defnk defnk defonce- defunbound defunbound- defvar defvar- let letfn do case cond condp for loop recur when when-not when-let when-first if if-let if-not . .. -> ->> doto and or dosync doseq dotimes dorun doall load import unimport ns in-ns refer try catch finally throw with-open with-local-vars binding gen-class gen-and-load-class gen-and-save-class handler-case handle");

  var builtins = makeKeywords(
    "* *' *1 *2 *3 *agent* *allow-unresolved-vars* *assert* *clojure-version* *command-line-args* *compile-files* *compile-path* *compiler-options* *data-readers* *e *err* *file* *flush-on-newline* *fn-loader* *in* *math-context* *ns* *out* *print-dup* *print-length* *print-level* *print-meta* *print-readably* *read-eval* *source-path* *unchecked-math* *use-context-classloader* *verbose-defrecords* *warn-on-reflection* + +' - -' -> ->> ->ArrayChunk ->Vec ->VecNode ->VecSeq -cache-protocol-fn -reset-methods .. / < <= = == > >= EMPTY-NODE accessor aclone add-classpath add-watch agent agent-error agent-errors aget alength alias all-ns alter alter-meta! alter-var-root amap ancestors and apply areduce array-map aset aset-boolean aset-byte aset-char aset-double aset-float aset-int aset-long aset-short assert assoc assoc! assoc-in associative? atom await await-for await1 bases bean bigdec bigint biginteger binding bit-and bit-and-not bit-clear bit-flip bit-not bit-or bit-set bit-shift-left bit-shift-right bit-test bit-xor boolean boolean-array booleans bound-fn bound-fn* bound? butlast byte byte-array bytes case cast char char-array char-escape-string char-name-string char? chars chunk chunk-append chunk-buffer chunk-cons chunk-first chunk-next chunk-rest chunked-seq? class class? clear-agent-errors clojure-version coll? comment commute comp comparator compare compare-and-set! compile complement concat cond condp conj conj! cons constantly construct-proxy contains? count counted? create-ns create-struct cycle dec dec' decimal? declare default-data-readers definline definterface defmacro defmethod defmulti defn defn- defonce defprotocol defrecord defstruct deftype delay delay? deliver denominator deref derive descendants destructure disj disj! dissoc dissoc! distinct distinct? doall dorun doseq dosync dotimes doto double double-array doubles drop drop-last drop-while empty empty? ensure enumeration-seq error-handler error-mode eval even? every-pred every? ex-data ex-info extend extend-protocol extend-type extenders extends? false? ffirst file-seq filter filterv find find-keyword find-ns find-protocol-impl find-protocol-method find-var first flatten float float-array float? floats flush fn fn? fnext fnil for force format frequencies future future-call future-cancel future-cancelled? future-done? future? gen-class gen-interface gensym get get-in get-method get-proxy-class get-thread-bindings get-validator group-by hash hash-combine hash-map hash-set identical? identity if-let if-not ifn? import in-ns inc inc' init-proxy instance? int int-array integer? interleave intern interpose into into-array ints io! isa? iterate iterator-seq juxt keep keep-indexed key keys keyword keyword? last lazy-cat lazy-seq let letfn line-seq list list* list? load load-file load-reader load-string loaded-libs locking long long-array longs loop macroexpand macroexpand-1 make-array make-hierarchy map map-indexed map? mapcat mapv max max-key memfn memoize merge merge-with meta method-sig methods min min-key mod munge name namespace namespace-munge neg? newline next nfirst nil? nnext not not-any? not-empty not-every? not= ns ns-aliases ns-imports ns-interns ns-map ns-name ns-publics ns-refers ns-resolve ns-unalias ns-unmap nth nthnext nthrest num number? numerator object-array odd? or parents partial partition partition-all partition-by pcalls peek persistent! pmap pop pop! pop-thread-bindings pos? pr pr-str prefer-method prefers primitives-classnames print print-ctor print-dup print-method print-simple print-str printf println println-str prn prn-str promise proxy proxy-call-with-super proxy-mappings proxy-name proxy-super push-thread-bindings pvalues quot rand rand-int rand-nth range ratio? rational? rationalize re-find re-groups re-matcher re-matches re-pattern re-seq read read-line read-string realized? reduce reduce-kv reductions ref ref-history-count ref-max-history ref-min-history ref-set refer refer-clojure reify release-pending-sends rem remove remove-all-methods remove-method remove-ns remove-watch repeat repeatedly replace replicate require reset! reset-meta! resolve rest restart-agent resultset-seq reverse reversible? rseq rsubseq satisfies? second select-keys send send-off seq seq? seque sequence sequential? set set-error-handler! set-error-mode! set-validator! set? short short-array shorts shuffle shutdown-agents slurp some some-fn sort sort-by sorted-map sorted-map-by sorted-set sorted-set-by sorted? special-symbol? spit split-at split-with str string? struct struct-map subs subseq subvec supers swap! symbol symbol? sync take take-last take-nth take-while test the-ns thread-bound? time to-array to-array-2d trampoline transient tree-seq true? type unchecked-add unchecked-add-int unchecked-byte unchecked-char unchecked-dec unchecked-dec-int unchecked-divide-int unchecked-double unchecked-float unchecked-inc unchecked-inc-int unchecked-int unchecked-long unchecked-multiply unchecked-multiply-int unchecked-negate unchecked-negate-int unchecked-remainder-int unchecked-short unchecked-subtract unchecked-subtract-int underive unquote unquote-splicing update-in update-proxy use val vals var-get var-set var? vary-meta vec vector vector-of vector? when when-first when-let when-not while with-bindings with-bindings* with-in-str with-loading-context with-local-vars with-meta with-open with-out-str with-precision with-redefs with-redefs-fn xml-seq zero? zipmap *default-data-reader-fn* as-> cond-> cond->> reduced reduced? send-via set-agent-send-executor! set-agent-send-off-executor! some-> some->>");

  var indentKeys = makeKeywords(
    // Built-ins
    "ns fn def defn defmethod bound-fn if if-not case condp when while when-not when-first do future comment doto locking proxy with-open with-precision reify deftype defrecord defprotocol extend extend-protocol extend-type try catch " +

    // Binding forms
    "let letfn binding loop for doseq dotimes when-let if-let " +

    // Data structures
    "defstruct struct-map assoc " +

    // clojure.test
    "testing deftest " +

    // contrib
    "handler-case handle dotrace deftrace");

  var opposites = {")": "(",
                   "]": "[",
                   "}": "{"};

  var tests = {
    digit: /\d/,
    digit_or_colon: /[\d:]/,
    hex: /[0-9a-f]/i,
    sign: /[+-]/,
    exponent: /e/i,
    char: /[^\s\(\[\{\}\]\)]/,
    keyword_char: /[^\s\(\[\;\)\]]/,
    basic: /[\w\$_\-\.\*\+\/\?\><!]/,
    lang_keyword: /[\w\*\+!\-_?:\/\.#=]/,
  };

  function stateStack(indent, type, prev) { // represents a state stack object
    this.indent = indent;
    this.type = type;
    this.prev = prev;
  }

  function pushStack(state, indent, type) {
    state.indentStack = new stateStack(indent, type, state.indentStack);
  }

  function popStack(state) {
    state.indentStack = state.indentStack.prev;
  }

  function isNumber(ch, stream){
    // hex
    if ( ch === '0' && stream.eat(/x/i) ) {
      stream.eatWhile(tests.hex);
      return true;
    }

    // leading sign
    if ( ( ch == '+' || ch == '-' ) && ( tests.digit.test(stream.peek()) ) ) {
      stream.eat(tests.sign);
      ch = stream.next();
    }

    if ( tests.digit.test(ch) ) {
      stream.eat(ch);
      stream.eatWhile(tests.digit);

      if ( '.' == stream.peek() ) {
        stream.eat('.');
        stream.eatWhile(tests.digit);
      }

      if ( stream.eat(tests.exponent) ) {
        stream.eat(tests.sign);
        stream.eatWhile(tests.digit);
      }

      return true;
    }

    return false;
  }

  function eatString(stream) {
    var next, escaped = false;
    while ((next = stream.next()) != null) {
      if (next == "\"" && !escaped) {
        return false;
      }
      escaped = !escaped && next == "\\";
    }
    return "string";
  }

  function openForm(ch, stream, state, commentForms) {
    var keyWord = '', origpos = stream.pos, indentTemp = stream.column(), letter;
    if (ch == "(") while ((letter = stream.eat(tests.keyword_char)) != null) {
      keyWord += letter;
    }

    if (keyWord.length > 0 && keyWord == "comment" && commentForms) {
      state.mode = "comment";
      pushStack(state, indentTemp + INDENT_WORD_SKIP, "comment");
    } else if (keyWord.length > 0 && (indentKeys.propertyIsEnumerable(keyWord) ||
                               /^(?:def|with)/.test(keyWord))) { // indent-word
      pushStack(state, indentTemp + INDENT_WORD_SKIP, ch);
    } else { // non-indent word
      // we continue eating the spaces
      stream.eatSpace();
      if (stream.eol() || stream.peek() == ";") {
        // nothing significant after
        // we restart indentation 1 space after
        pushStack(state, indentTemp + 1, ch);
      } else {
        pushStack(state, indentTemp + stream.current().length, ch); // else we match
      }
    }
    stream.pos = origpos; // undo all the eating
  }

  function closeForm(ch, stream, state) {
    if (!state.indentStack) return;

    if (state.indentStack.type == opposites[ch]) {
      popStack(state);
    }
  }

  function commentForm(stream, state) {
    var next, escaped = false;
    while ((next = stream.next()) != null) {
      if (next == "\"") {
        return "comment-string";
      }
      if (next == "(" || next == "[" || next == "{") {
        openForm(next, stream, state);
      } else if (next == ")" && state.indentStack.type == "comment") {
        popStack(state);
        stream.backUp(1);
        return false;
      } else if(next == ")" || next == "]" || next == "}") {
        closeForm(next, stream, state);
      }

    }
    return "comment";
  }

  return {
    startState: function () {
      return {
        indentStack: null,
        indentation: 0,
        mode: false
      };
    },

    token: function (stream, state) {
      if (state.indentStack == null && stream.sol()) {
        // update indentation, but only if indentStack is empty
        state.indentation = stream.indentation();
      }

      // skip spaces
      if (state.mode != "string" && stream.eatSpace()) {
        return null;
      }
      var returnType = null;

      switch(state.mode){
        case "string": // multi-line string parsing mode
          state.mode = eatString(stream);
          returnType = STRING; // continue on in string mode
          break;

        case "comment-string":
          var mode = eatString(stream);
          if(!mode) {
            state.mode = "comment";
          }
          returnType = COMMENTFORM;
          break;

        case "comment":
          state.mode = commentForm(stream, state);
          returnType = COMMENTFORM;
          break;

        default: // default parsing mode
          var ch = stream.next();

          if (ch == "\"") {
            state.mode = "string";
            returnType = STRING;
          } else if (ch == "\\") {
            stream.next();
            returnType = CHAR;
          } else if (ch == "'" && !( tests.digit_or_colon.test(stream.peek()) )) {
            returnType = ATOM;
          } else if (ch == ";") { // comment
            stream.skipToEnd(); // rest of the line is a comment
            returnType = COMMENT;
          } else if (isNumber(ch,stream)){
            returnType = NUMBER;
          } else if (ch == "(" || ch == "[" || ch == "{") {
            /**
                        Either
                        (indent-word ..
                        (non-indent-word ..
                        (;something else, bracket, etc.
                        */
            openForm(ch, stream, state, this.commentForms);
            returnType = BRACKET;
          } else if (ch == ")" || ch == "]" || ch == "}") {
            closeForm(ch, stream, state);
            returnType = BRACKET;
          } else if ( ch == ":" ) {
            stream.eatWhile(tests.lang_keyword);
            return ATOM;
          } else {
            stream.eatWhile(tests.basic);

            if (keywords && keywords.propertyIsEnumerable(stream.current())) {
              returnType = KEYWORD;
            } else if (builtins && builtins.propertyIsEnumerable(stream.current())) {
              returnType = BUILTIN;
            } else if (atoms && atoms.propertyIsEnumerable(stream.current())) {
              returnType = ATOM;
            } else returnType = null;
          }
            }

          return returnType;
        },

      indent: function (state) {
        if (state.indentStack == null) return state.indentation;
        return state.indentStack.indent;
      },

    commentForms: false,

      lineComment: ";;",
      disallowSingleQuoteStrings: true
    };
});

CodeMirror.defineMIME("text/x-clojure", "clojure");
CodeMirror.defineMIME("text/x-clojurescript", "clojure");
CodeMirror.defineMIME("clj", "clojure");
CodeMirror.defineMIME("cljs", "clojure");
<|endoftext|>


<commit_before>/*global FBL */
FBL.ns(function () {
	with (FBL) {
		var panelName = "firerunner",
			regExpIsXPath = /^\//,
			regExpClass = /\s?firerunner\-match(\-hover)?/g,
			regExpHoverClass = /firerunner\-match\-hover/,
			regExpInitialViewClass = /initial\-view/,
			regExpRunner = /firerunner\-run\-element/,
			regExpSpaceFix = /^\s+|\s+$/g,
			regExpSlashEscape = /\//g,
			inputField = null,
			results = null,
			resultsHeader = null,
			statesFirerunner = {
			},
			strBundle = document.getElementById("firerunnerstrings"),
			translations = {
				firerunnerfindmatchingelements : strBundle.getString("firerunnerfindmatchingelements"),
				firerunnermatchingelements : strBundle.getString("firerunnermatchingelements"),
				firerunnernomatches : strBundle.getString("firerunnernomatches"),
				firerunnerfilter : strBundle.getString("firerunnerfilter"),
				firerunnerExecute: strBundle.getString("firerunnerexecute"),
			},
			getTabIndex = function () {
				var browsers = FBL.getTabBrowser().browsers,
					tabIndex;
				for (var i=0, il=browsers.length; i<il; i++) {
					if(FBL.getTabBrowser().getBrowserAtIndex(i).contentWindow == content) {
						tabIndex = i;
						break;
					}
				}
				return tabIndex;
			},
			getFirerunnerState = function () {
			    var tabIndex = getTabIndex(),
			        state = statesFirerunner[tabIndex],
			        matchingElementsExists = false;

			    try {
			        matchingElementsExists = state.matchingElements.length + "";
			    } catch(e) {}

			    if (!state || !matchingElementsExists) {
			        state = statesFirerunner[tabIndex] = {
			            matchingElements : []
			        };
			    }

			    return state;
			};

		Firebug.firerunnerModel = extend(Firebug.Module, {
			baseContentAdded : false,
			showPanel : function(browser, panel) {
				var isPanel = panel && panel.name === panelName,
					firerunnerButtons = Firebug.chrome.$("fbfirerunnerButtons"),
					state = getFirerunnerState();
			},

			addBaseContent : function (panelNode) {
				var baseContent = domplate({
						panelBase:
						DIV({
								id : "firerunner-container"
							},
							DIV({
									id: "firerunner-base-content"
								},
								H1(
									{},
									SPAN({
										},
										"Firerunner"
									),
									SPAN({
											id : "firerunner-help-text"
										},
										" - " + translations.firerunnerfindmatchingelements
									)
								),
								DIV(
									{
										id: "firerunner-search-box"
									},
									INPUT(
										{
											class : "firerunner-field",
											type : "text",
											value: Firebug.getPref(Firebug.prefDomain, "firerunner.filter"),
											onkeypress : function (evt) {
												if (evt.keyCode === 13) {
													Firebug.firerunnerModel.run(Firebug.currentContext);
												}
											}
										}
									),
									INPUT(
										{
											id : "firerunner-css-button",
											type : "button",
											value : translations.firerunnerfilter,
											onclick : function () {
												Firebug.firerunnerModel.run(Firebug.currentContext);
											}
										}
									)
								)
							),
							DIV(
								{
									class : "firerunner-results-container initial-view"
								},
								H2({
										class : "firerunner-results-header"
									},
									translations.firerunnermatchingelements
								),
								DIV(
									{
										class : "firerunner-results"
									},
									translations.nomatches
								)
							)
						)
					});
				baseContent.panelBase.replace({}, panelNode, baseContent);
			},

			addStyleSheet : function (doc) {
				var styleSheet = document.getElementById("firerunner-firebug-style");
				if (!styleSheet) {
					styleSheet = createStyleSheet(doc, "chrome://firerunner/skin/firebug.css");
					styleSheet.id = "firerunner-firebug-style";
					addStyleSheet(doc, styleSheet);
				}
			},

		   	run : function (context, element) {
				var panel = context.getPanel(panelName),
					panelNode = panel.panelNode,
					inputField = dLite.elmsByClass("firerunner-field", "input", panelNode)[0],
					resultsContainer = dLite.elmsByClass("firerunner-results-container", "div", panelNode)[0],
					results = dLite.elmsByClass("firerunner-results", "div", panelNode)[0],
					resultsHeader = dLite.elmsByClass("firerunner-results-header", "h2", panelNode)[0],
					execCmd = Firebug.getPref(Firebug.prefDomain, "firerunner.execCmd"),
					execParam = Firebug.getPref(Firebug.prefDomain, "firerunner.execParam"),
					paramRegExp = new RegExp(Firebug.getPref(Firebug.prefDomain, "firerunner.paramRegExp")),
					paramTagAttribute = Firebug.getPref(Firebug.prefDomain, "firerunner.paramTagAttribute"),

					// JavaScript and CSS to add to the web browser content
					currentDocument = Firebug.currentContext.window.document,
					cssApplied = currentDocument.getElementById("firerunner-css"),
					head,
					css,

					// Parse HTML elements
					parse = function () {
						// CSS/XPath to filter by
						var filterExpression = inputField.value,
							XPath = regExpIsXPath.test(filterExpression),
							resultItem = "",
							state = Firebug.firerunnerModel.clear(context),
							matchingElements,
							firerunnerResultItems;

						// Find matching elements
						if (typeof element !== "undefined") {
							matchingElements = [element];
						}
						else if (XPath) {
							matchingElements = [];
							var xPathNodes = currentDocument.evaluate(filterExpression, currentDocument, ((currentDocument.documentElement.namespaceURI === ns.xhtml)? "xhtml:" : null), 0, null), node;
							while ((node = xPathNodes.iterateNext())) {
								matchingElements.push(node);
							}
						}
						else {
							matchingElements = new XPCNativeWrapper(Firebug.currentContext.window).document.querySelectorAll(filterExpression.replace(regExpSlashEscape, "\\\/"));
						}

						// Clear results content
						results.innerHTML = "";

						// Add class to matching elements and clone them to the results container
						if (matchingElements.length > 0) {
							for (var j=0, jl=matchingElements.length, elm, nodeNameValue, nodeNameCode, k, kl, attr; j<jl; j++) {
								elm = matchingElements[j];
								nodeNameValue = elm.nodeName.toLowerCase();
								nodeNameCode = "" + nodeNameValue + "";

								// Each element match container
								var firerunnerElement = document.createElement("div");
								firerunnerElement.className = "firerunner-result-item" + ((j % 2 === 0)? " odd" : "");
								firerunnerElement.ref = j;

								// Run element link
								var firerunnerExecElement = document.createElement("div");
								firerunnerExecElement.className = "firerunner-run-element";
								var paramAttrValue = elm.getAttribute(paramTagAttribute);
								var paramCmdLabel = document.createTextNode(paramAttrValue);
								firerunnerExecElement.appendChild(paramCmdLabel);
								firerunnerElement.appendChild(firerunnerExecElement);

								results.appendChild(firerunnerElement);
								elm.className += ((elm.className.length > 0)? " " : "") + "firerunner-match";
							}
						}
						else {
							var noMatches = document.createTextNode(translations.firerunnernomatches);
							results.appendChild(noMatches);
						}

						state.matchingElements = matchingElements;

						firerunnerResultItems = dLite.elmsByClass("firerunner-result-item", "div", results);
						for (var l=0, ll=firerunnerResultItems.length, matchingElm; l<ll; l++) {
							elm = firerunnerResultItems[l];
							if (elm.getAttribute("ref")) {
								elm.addEventListener("mouseover", function (evt) {
									state.matchingElements[this.getAttribute("ref")].className += " firerunner-match-hover";
								}, false);

								elm.addEventListener("mouseout", function (evt) {
									matchingElm = state.matchingElements[this.getAttribute("ref")];
									matchingElm.className = matchingElm.className.replace(regExpHoverClass, "").replace(regExpSpaceFix, "");
								}, false);

								elm.addEventListener("click", function (evt) {
									var targetClassName = evt.target.className;
									if (regExpRunner.test(targetClassName)) {
										var paramTagAttrValue, execArg, match;
										matchingElm = state.matchingElements[this.getAttribute("ref")];
										paramTagAttrValue = matchingElm.getAttribute(paramTagAttribute);
										match = paramRegExp.exec(paramTagAttrValue);
										if (match != null) {
											execArg = match[1];
											if (execArg != null) {
												var parametrizedExecParamArg = execParam.replace("{0}", execArg);
												var execParamArray = parametrizedExecParamArg.split(" ");
												var apt_list = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
												apt_list.initWithPath(execCmd);
												var process = Components.classes["@mozilla.org/process/util;1"].
												createInstance(Components.interfaces.nsIProcess);
												process.init(apt_list);
												process.run(false, execParamArray, execParamArray.length);
											}
										}
									}
								}, false);
							}
						}
						// resultsHeader.innerHTML = translations.firerunnermatchingelements + ": " + matchingElements.length;
						var paramCmdLabel = document.createTextNode(translations.firerunnermatchingelements + ": " + matchingElements.length);
						resultsHeader.appendChild(paramCmdLabel);
						resultsContainer.className = resultsContainer.className.replace(regExpInitialViewClass, "").replace(regExpSpaceFix, "");
					};

					if (!cssApplied) {
						head = currentDocument.getElementsByTagName("head")[0];
						css = new XPCNativeWrapper(Firebug.currentContext.window).document.createElement("link");
						css.id = "firerunner-css";
						css.type = "text/css";
						css.rel = "stylesheet";
						css.href = "chrome://firerunner/content/browser.css";
						head.appendChild(css);
					}
					parse();
			},

			show : function (context) {
				// Forces Firebug to be shown, even if it's off
				Firebug.toggleBar(true);
				Firebug.toggleBar(true, panelName);
				if (Firebug.currentContext) {
					var panel = Firebug.currentContext.getPanel(panelName);
					var inputField = dLite.elmsByClass("firerunner-field", "input", panel.panelNode)[0];
					inputField.select();
					inputField.focus();
				}
			},

			hide : function (context) {
				Firebug.toggleBar(false, panelName);
			},

			selectCurrentElm : function (evt) {
				Firebug.firerunnerModel.run(Firebug.currentContext, evt.target);
				if (evt.type === "click") {
					evt.preventDefault();
				}
			},

			clear : function (context) {
				var panel = Firebug.currentContext.getPanel(panelName),
					panelNode = panel.panelNode,
					state = getFirerunnerState(),
					resultsContainer = dLite.elmsByClass("firerunner-results-container", "div", panelNode)[0],
					matchingElements;

				resultsContainer.className = "firerunner-results-container initial-view";
				matchingElements = state.matchingElements;

				// Clear previosuly matched elements' CSS classes
				for (var i=0, il=matchingElements.length, elm; i<il; i++) {
					elm = matchingElements[i];
					try {
						elm.className = elm.className.replace(regExpClass, "").replace(regExpSpaceFix, "");
						if (elm.className.length === 0) {
							elm.removeAttribute("class");
						}
					} catch(e) {}
				}
				return state;
			}
		});

		function firerunnerPanel () {
		}
		firerunnerPanel.prototype = extend(Firebug.Panel, {
			name : panelName,
			title : "Firerunner",
			initialize : function () {
				Firebug.Panel.initialize.apply(this, arguments);
				Firebug.firerunnerModel.addStyleSheet(this.document);
				Firebug.firerunnerModel.addBaseContent(this.panelNode);
			},

			getOptionsMenuItems : function () {
				return [];
			},

			optionsMenuItem : function  (text, option) {
				var pref = Firebug.getPref(Firebug.prefDomain, option);
				return {
					label : text,
					type : "checkbox",
					checked : pref,
					command : bindFixed(Firebug.setPref, this, Firebug.prefDomain, option, !pref)
				};
			}
		});

		Firebug.registerModule(Firebug.firerunnerModel);
		Firebug.registerPanel(firerunnerPanel);
	}
});
<commit_msg>Firefox 45.0 updates<commit_after>/*global FBL */
FBL.ns(function () {
	with (FBL) {
		var panelName = "firerunner",
			regExpIsXPath = /^\//,
			regExpClass = /\s?firerunner\-match(\-hover)?/g,
			regExpHoverClass = /firerunner\-match\-hover/,
			regExpInitialViewClass = /initial\-view/,
			regExpRunner = /firerunner\-run\-element/,
			regExpSpaceFix = /^\s+|\s+$/g,
			regExpSlashEscape = /\//g,
			inputField = null,
			results = null,
			resultsHeader = null,
			statesFirerunner = {
			},
			strBundle = document.getElementById("firerunnerstrings"),
			translations = {
				firerunnerfindmatchingelements : strBundle.getString("firerunnerfindmatchingelements"),
				firerunnermatchingelements : strBundle.getString("firerunnermatchingelements"),
				firerunnernomatches : strBundle.getString("firerunnernomatches"),
				firerunnerfilter : strBundle.getString("firerunnerfilter"),
				firerunnerExecute: strBundle.getString("firerunnerexecute"),
			},
			getTabIndex = function () {
				var browsers = FBL.getTabBrowser().browsers,
					tabIndex;
				for (var i=0, il=browsers.length; i<il; i++) {
					if(FBL.getTabBrowser().getBrowserAtIndex(i).contentWindow == content) {
						tabIndex = i;
						break;
					}
				}
				return tabIndex;
			},
			getFirerunnerState = function () {
			    var tabIndex = getTabIndex(),
			        state = statesFirerunner[tabIndex],
			        matchingElementsExists = false;

			    try {
			        matchingElementsExists = state.matchingElements.length + "";
			    } catch(e) {}

			    if (!state || !matchingElementsExists) {
			        state = statesFirerunner[tabIndex] = {
			            matchingElements : []
			        };
			    }

			    return state;
			};

		Firebug.firerunnerModel = extend(Firebug.Module, {
			baseContentAdded : false,
			showPanel : function(browser, panel) {
				var isPanel = panel && panel.name === panelName,
					firerunnerButtons = Firebug.chrome.$("fbfirerunnerButtons"),
					state = getFirerunnerState();
			},

			addBaseContent : function (panelNode) {
				var baseContent = domplate({
						panelBase:
						DIV({
								id : "firerunner-container"
							},
							DIV({
									id: "firerunner-base-content"
								},
								H1(
									{},
									SPAN({
										},
										"Firerunner"
									),
									SPAN({
											id : "firerunner-help-text"
										},
										" - " + translations.firerunnerfindmatchingelements
									)
								),
								DIV(
									{
										id: "firerunner-search-box"
									},
									INPUT(
										{
											class : "firerunner-field",
											type : "text",
											value: Firebug.getPref(Firebug.prefDomain, "firerunner.filter"),
											onkeypress : function (evt) {
												if (evt.keyCode === 13) {
													Firebug.firerunnerModel.run(Firebug.currentContext);
												}
											}
										}
									),
									INPUT(
										{
											id : "firerunner-css-button",
											type : "button",
											value : translations.firerunnerfilter,
											onclick : function () {
												Firebug.firerunnerModel.run(Firebug.currentContext);
											}
										}
									)
								)
							),
							DIV(
								{
									class : "firerunner-results-container initial-view"
								},
								H2({
										class : "firerunner-results-header"
									},
									translations.firerunnermatchingelements
								),
								DIV(
									{
										class : "firerunner-results"
									},
									translations.nomatches
								)
							)
						)
					});
				baseContent.panelBase.replace({}, panelNode, baseContent);
			},

			addStyleSheet : function (doc) {
				var styleSheet = document.getElementById("firerunner-firebug-style");
				if (!styleSheet) {
					styleSheet = createStyleSheet(doc, "chrome://firerunner/skin/firebug.css");
					styleSheet.id = "firerunner-firebug-style";
					addStyleSheet(doc, styleSheet);
				}
			},

		   	run : function (context, element) {
				var panel = context.getPanel(panelName),
					panelNode = panel.panelNode,
					inputField = dLite.elmsByClass("firerunner-field", "input", panelNode)[0],
					resultsContainer = dLite.elmsByClass("firerunner-results-container", "div", panelNode)[0],
					results = dLite.elmsByClass("firerunner-results", "div", panelNode)[0],
					resultsHeader = dLite.elmsByClass("firerunner-results-header", "h2", panelNode)[0],
					execCmd = Firebug.getPref(Firebug.prefDomain, "firerunner.execCmd"),
					execParam = Firebug.getPref(Firebug.prefDomain, "firerunner.execParam"),
					paramRegExp = new RegExp(Firebug.getPref(Firebug.prefDomain, "firerunner.paramRegExp")),
					paramTagAttribute = Firebug.getPref(Firebug.prefDomain, "firerunner.paramTagAttribute"),

					// JavaScript and CSS to add to the web browser content
					currentDocument = Firebug.currentContext.window.document,
					cssApplied = currentDocument.getElementById("firerunner-css"),
					head,
					css,

					// Parse HTML elements
					parse = function () {
						// CSS/XPath to filter by
						var filterExpression = inputField.value,
							XPath = regExpIsXPath.test(filterExpression),
							resultItem = "",
							state = Firebug.firerunnerModel.clear(context),
							matchingElements,
							firerunnerResultItems;

						// Find matching elements
						if (typeof element !== "undefined") {
							matchingElements = [element];
						}
						else if (XPath) {
							matchingElements = [];
							var xPathNodes = currentDocument.evaluate(filterExpression, currentDocument, ((currentDocument.documentElement.namespaceURI === ns.xhtml)? "xhtml:" : null), 0, null), node;
							while ((node = xPathNodes.iterateNext())) {
								matchingElements.push(node);
							}
						}
						else {
							matchingElements = new XPCNativeWrapper(Firebug.currentContext.window).document.querySelectorAll(filterExpression.replace(regExpSlashEscape, "\\\/"));
						}

						// Clear results content
						results.innerHTML = "";

						// Add class to matching elements and clone them to the results container
						if (matchingElements.length > 0) {
							for (var j=0, jl=matchingElements.length, elm, nodeNameValue, nodeNameCode, k, kl, attr; j<jl; j++) {
								elm = matchingElements[j];
								nodeNameValue = elm.nodeName.toLowerCase();
								nodeNameCode = "" + nodeNameValue + "";

								// Each element match container
								var firerunnerElement = document.createElement("div");
								firerunnerElement.className = "firerunner-result-item" + ((j % 2 === 0)? " odd" : "");
								firerunnerElement.ref = j;

								// Run element link
								var firerunnerExecElement = document.createElement("div");
								firerunnerExecElement.className = "firerunner-run-element";
                                                                firerunnerExecElement.ref = j;
								var paramAttrValue = elm.getAttribute(paramTagAttribute);
								var paramCmdLabel = document.createTextNode(paramAttrValue);
								firerunnerExecElement.appendChild(paramCmdLabel);
								firerunnerElement.appendChild(firerunnerExecElement);

								results.appendChild(firerunnerElement);
								elm.className += ((elm.className.length > 0)? " " : "") + "firerunner-match";
							}
						}
						else {
							var noMatches = document.createTextNode(translations.firerunnernomatches);
							results.appendChild(noMatches);
						}

						state.matchingElements = matchingElements;

						firerunnerResultItems = dLite.elmsByClass("firerunner-result-item", "div", results);
						for (var l=0, ll=firerunnerResultItems.length, matchingElm; l<ll; l++) {
							elm = firerunnerResultItems[l];
							if (elm.getAttribute("ref")) {
								elm.addEventListener("mouseover", function (evt) {
									state.matchingElements[this.getAttribute("ref")].className += " firerunner-match-hover";
								}, false);

								elm.addEventListener("mouseout", function (evt) {
									matchingElm = state.matchingElements[this.getAttribute("ref")];
									matchingElm.className = matchingElm.className.replace(regExpHoverClass, "").replace(regExpSpaceFix, "");
								}, false);

								elm.addEventListener("click", function (evt) {
									var targetClassName = evt.target.className;
									if (regExpRunner.test(targetClassName)) {
										var paramTagAttrValue, execArg, match;
										matchingElm = state.matchingElements[this.getAttribute("ref")];
										paramTagAttrValue = matchingElm.getAttribute(paramTagAttribute);
										match = paramRegExp.exec(paramTagAttrValue);
										if (match != null) {
											execArg = match[1];
											if (execArg != null) {
												var parametrizedExecParamArg = execParam.replace("{0}", execArg);
												var execParamArray = parametrizedExecParamArg.split(" ");
												var apt_list = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
												apt_list.initWithPath(execCmd);
												var process = Components.classes["@mozilla.org/process/util;1"].

												createInstance(Components.interfaces.nsIProcess);
												process.init(apt_list);
												process.run(false, execParamArray, execParamArray.length);
											}
										}
									}
								}, false);
							}
						}
						// resultsHeader.innerHTML = translations.firerunnermatchingelements + ": " + matchingElements.length;
						var paramCmdLabel = document.createTextNode(translations.firerunnermatchingelements + ": " + matchingElements.length);
						resultsHeader.appendChild(paramCmdLabel);
						resultsContainer.className = resultsContainer.className.replace(regExpInitialViewClass, "").replace(regExpSpaceFix, "");
					};

					if (!cssApplied) {
						head = currentDocument.getElementsByTagName("head")[0];
						css = new XPCNativeWrapper(Firebug.currentContext.window).document.createElement("link");
						css.id = "firerunner-css";
						css.type = "text/css";
						css.rel = "stylesheet";
						css.href = "chrome://firerunner/content/browser.css";
						head.appendChild(css);
					}
					parse();
			},

			show : function (context) {
				// Forces Firebug to be shown, even if it's off
				Firebug.toggleBar(true);
				Firebug.toggleBar(true, panelName);
				if (Firebug.currentContext) {
					var panel = Firebug.currentContext.getPanel(panelName);
					var inputField = dLite.elmsByClass("firerunner-field", "input", panel.panelNode)[0];
					inputField.select();
					inputField.focus();
				}
			},

			hide : function (context) {
				Firebug.toggleBar(false, panelName);
			},

			selectCurrentElm : function (evt) {
				Firebug.firerunnerModel.run(Firebug.currentContext, evt.target);
				if (evt.type === "click") {
					evt.preventDefault();
				}
			},

			clear : function (context) {
				var panel = Firebug.currentContext.getPanel(panelName),
					panelNode = panel.panelNode,
					state = getFirerunnerState(),
					resultsContainer = dLite.elmsByClass("firerunner-results-container", "div", panelNode)[0],
					matchingElements;

				resultsContainer.className = "firerunner-results-container initial-view";
				matchingElements = state.matchingElements;

				// Clear previosuly matched elements' CSS classes
				for (var i=0, il=matchingElements.length, elm; i<il; i++) {
					elm = matchingElements[i];
					try {
						elm.className = elm.className.replace(regExpClass, "").replace(regExpSpaceFix, "");
						if (elm.className.length === 0) {
							elm.removeAttribute("class");
						}
					} catch(e) {}
				}
				return state;
			}
		});

		function firerunnerPanel () {
		}
		firerunnerPanel.prototype = extend(Firebug.Panel, {
			name : panelName,
			title : "Firerunner",
			initialize : function () {
				Firebug.Panel.initialize.apply(this, arguments);
				Firebug.firerunnerModel.addStyleSheet(this.document);
				Firebug.firerunnerModel.addBaseContent(this.panelNode);
			},

			getOptionsMenuItems : function () {
				return [];
			},

			optionsMenuItem : function  (text, option) {
				var pref = Firebug.getPref(Firebug.prefDomain, option);
				return {
					label : text,
					type : "checkbox",
					checked : pref,
					command : bindFixed(Firebug.setPref, this, Firebug.prefDomain, option, !pref)
				};
			}
		});

		Firebug.registerModule(Firebug.firerunnerModel);
		Firebug.registerPanel(firerunnerPanel);
	}
});
<|endoftext|>


<commit_before>// Rebase require directory
requirejs.config({
	baseUrl: "lib",
	paths: {
		activity: "../js"
	}
});

// Vue main app
var app = new Vue({
	el: '#app',
	data: {
		grid: true,
		modeId: "grid-mode",
		images: [],
		activeImage: "",
		activeImageIndex: 0,
		previousBtnId: null,
		nextBtnId: null,
		recordIconId: null,
		imageCount: 9,	//update with Image slider
		imageLoaded: 0,
		intervalIds: [],
		colors: null,
		isLoaded: false,
		sizes: ['16px', '24px', '32px' ,'40px', '48px' , '56px', '64px' , '72px' , '80px' , '100px'],
		gridEditorContent: null,
		singleEditorsContent: [],
		editor: null,
		fontColor: null,
		backgroundColor: null,
		fontSelected: null,
		fontSize:null
	},
	methods: {
		initialized: function () {
			// Sugarizer initialized
			var environment = this.$refs.SugarActivity.getEnvironment();
			this.colors = [environment.user.colorvalue.fill, environment.user.colorvalue.stroke, '#FFFFFF'];
			if (this.activeImageIndex===0){
				this.previousBtnId = "previous-btn-inactive";
				this.nextBtnId = "next-btn";
			} else if (this.activeImageIndex===this.image.length - 1){
				this.previousBtnId = "previous-btn";
				this.nextBtnId = "next-btn-inactive";
			}
			this.recordIconId = "record";
			// document.getElementById('grid-mode').classList.add("active");
			for (var i=0; i<this.imageCount; i++){
				this.singleEditorsContent.push(null);
			}
			this.loadEditor();
		},
		imageLoaders: function(){
			function getRandomInt (min, max) {
				min = Math.ceil(min);
				max = Math.floor(max);
				return Math.floor(Math.random() * (max - min + 1)) + min;
			}
			const that = this;
			function getColor(){
				return that.colors[getRandomInt(0,2)];
			}
			var quesimgs = document.getElementsByClassName('questionmark');
			var len = quesimgs.length;
			if (!this.grid) len=1;
			for (var i=0; i<len; i++){
				quesimgs[i].style.background = getColor();
				(function (i){
					var intervalId = setInterval(function(){quesimgs[i].style.background = getColor()}, 900);
					that.intervalIds.push(intervalId);
				})(i);
			}
		},
		loadImages: function(){
			var xhr = new XMLHttpRequest();
			var imgs = [];
			var that = this;
			var source = document.location.href.substr(0, document.location.href.indexOf("/activities/"))+"/activities/Abecedarium.activity/database/db_meta.json";

			function checkFileExists (urlToFile) {
				try {
					var req = new XMLHttpRequest();
					req.open('HEAD', urlToFile, false);
					req.send();
					if(navigator.userAgent.indexOf("Safari") != -1){
						// Check sugarizer-server error here
						if (req.readyState === 4 && req.response != ""){
							return true;
						} else {
							return false;
						}
					} else {
						if (req.readyState === 4){
							return true;
						} else {
							return false;
						}
					}
				} catch (error) {
					return false;
				}
			}
			xhr.onload = function(){
					var data;
					data  = JSON.parse(xhr.response);
					for (var i=0; i<that.imageCount; i++){
						var img = data[Math.floor(Math.random() *  data.length)].code;
						var imgCheck = checkFileExists(document.location.href.substr(0, document.location.href.indexOf("/activities/"))+"/activities/Abecedarium.activity/images/database/"+img+".png");
						if (imgs.indexOf(img)===-1 && imgCheck==true){
							imgs.push(img);
						} else {
							i--;
						}
					}
					that.images = imgs;
					that.activeImage = that.images[that.activeImageIndex];
					if (!that.grid){
						that.isLoaded = true;
						for (var i=0; i<that.imageCount; i++){
							clearInterval(that.intervalIds[i]);
						}
					}
			};
			xhr.onerror = function(err){
				console.log("Error: ", xhr.statusText);
			};
			xhr.open("GET", source);
			xhr.send();
		},
		loadEditor: function(){
			var container = document.getElementById('editor-area');
			var editor = new Quill(container, {
				modules: {
				  toolbar: '.toolbar-container'
				},
			  });
			editor.format('size', '24px');
			this.editor = editor;
		},
		updateEditor: function(){
			this.fontColor != null && this.editor.format('color',this.fontColor);
			this.backgroundColor!=null && this.editor.format('background-color',this.backgroundColor);
			this.fontSelected !=null &&	this.editor.format('font', this.fontSelected);
			this.fontSize !=null ? this.editor.format('size', this.fontSize) : this.editor.format('size', '24px');
		},
		getUrlImg: function(img){
			return '../Abecedarium.activity/images/database/'+ img + '.png';
		},
		toggleMode: function(){
			if (this.grid){
				this.gridEditorContent = this.editor.getContents();
				this.editor.setContents(this.singleEditorsContent[this.activeImageIndex]);
				this.updateEditor();
				this.grid=false;
				this.modeId="single-mode";
			} else {
				this.activeImage = this.images[this.activeImageIndex];
				this.singleEditorsContent[this.activeImageIndex]= this.editor.getContents();
				this.editor.setContents(this.gridEditorContent);
				this.updateEditor();
				if (this.activeImageIndex === 0){
					this.previousBtnId = "previous-btn-inactive";
				}
				this.grid=true;
				this.modeId="grid-mode";
			}
		},
		previousImage: function () {
			if (this.activeImageIndex === 0){
				return;
			}
			this.nextBtnId = "next-btn";
			this.singleEditorsContent[this.activeImageIndex]= this.editor.getContents();
			this.activeImageIndex = this.activeImageIndex - 1;
			this.editor.setContents(this.singleEditorsContent[this.activeImageIndex]);
			this.updateEditor();
			this.activeImage = this.images[this.activeImageIndex];
			if (this.activeImageIndex === 0){
				this.previousBtnId = "previous-btn-inactive";
			}
		},
		nextImage: function () {
			if (this.activeImageIndex === this.images.length-1){
				return;
			}
			this.previousBtnId = "previous-btn"
			this.singleEditorsContent[this.activeImageIndex]= this.editor.getContents();
			this.activeImageIndex = this.activeImageIndex + 1;
			this.editor.setContents(this.singleEditorsContent[this.activeImageIndex]);
			this.updateEditor();
			this.activeImage = this.images[this.activeImageIndex];
			if (this.activeImageIndex === this.images.length-1){
				this.nextBtnId = "next-btn-inactive";
			}
		},
		loaded: function () {
			this.imageLoaded++;
			if (this.imageLoaded === this.imageCount ){
				this.isLoaded = true;
				this.activeImage = this.images[this.activeImageIndex];
				for (var i=0; i<this.imageCount; i++){
					clearInterval(this.intervalIds[i]);
				}
			}
		},
		increaseFont: function(){
			var currentSize = this.editor.getFormat();
			var that = this;
			if(currentSize.size==null){
				var index = that.sizes.indexOf('24px');
				that.editor.format('size',that.sizes[index+1]);
				that.fontSize = that.sizes[index+1];
			} else {
				var index = that.sizes.indexOf(currentSize.size);
				index++;
				if(index<that.sizes.length){
					that.editor.format('size',that.sizes[index]);
					that.fontSize = that.sizes[index];
				}
			}
		},
		decreaseFont: function(){
			var currentSize = this.editor.getFormat();
			var that = this;
			if(currentSize.size==null){
				var index = that.sizes.indexOf('24px');
				if(index>0)
				that.editor.format('size',that.sizes[index-1]);
				that.fontSize = that.sizes[index-1]
			}
			else {
				var index = that.sizes.indexOf(currentSize.size);
				index--;
				if(index>=0){
					that.editor.format('size',that.sizes[index]);
					that.fontSize = that.sizes[index];
				}
			}
		},
		onFormatText: function(e){
			this.editor.focus()
		},
		onFontChange: function(e){
			var newfont = e.font;
			if(newfont=="Arial") newfont="arial";
			if(newfont=="Comic Sans MS") newfont="comic";
			if(newfont=="Times New Roman")newfont="Times";
			if(newfont=="Courier New")newfont="Courier";
			if(newfont=="Lucida Console")newfont="Lucida";
			if(newfont=="Impact")newfont="Impact";
			if(newfont=="Georgia")newfont="Georgia";
			this.editor.format('font', newfont);
			this.fontSelected = newfont;
			this.editor.focus()
		},
		onForegroundColorChange: function(e){
			this.fontColor = e.detail.color;
			this.editor.format('color',this.fontColor);
		},
		onBackgroundColorChange: function(e){
			this.backgroundColor = e.detail.color;
			this.editor.format('background-color',this.backgroundColor);
		},

		onJournalNewInstance: function() {
			console.log("New instance");
			for (var i=0; i<this.imageCount; i++){
				this.singleEditorsContent.push(null);
			}
			this.imageLoaders();
			var that = this;
			window.setTimeout(function(){that.loadImages()},910);
		},
		onJournalDataLoaded: function (data, metadata) {
			console.log("Existing instance");

			this.grid = data.grid;
			this.imageLoaders();
			this.images = data.images;
			this.imageCount = data.imageCount;
			this.gridEditorContent = JSON.parse(data.gridEditorContent);
			this.singleEditorsContent = JSON.parse(data.singleEditorsContent);
			this.fontSelected = data.fontSelected;
			this.fontSize = data.fontSize;
			if(data.grid){
				this.grid=true;
				this.editor.setContents(this.gridEditorContent);
				this.updateEditor();
			} else {
				this.activeImage = this.images[this.activeImageIndex];
				this.grid = false;
				this.isLoaded = true;
				for (var i=0; i<this.imageCount; i++){
					clearInterval(this.intervalIds[i]);
				}
				this.editor.setContents(this.singleEditorsContent[0]);
				this.updateEditor();
				this.modeId="single-mode";
				if (this.activeImageIndex === 0){
					this.previousBtnId = "previous-btn-inactive";
				}
			}
		},
		onJournalLoadError: function(error) {
			console.log("Error loading from journal");
		},
		onStop: function() {
			if (this.grid){
				this.gridEditorContent = this.editor.getContents();
			} else {
				this.singleEditorsContent[this.activeImageIndex]= this.editor.getContents();
			}
			var context = {
				grid: this.grid,
				images: this.images,
				imageCount: this.imageCount,
				gridEditorContent: JSON.stringify(this.gridEditorContent),
				singleEditorsContent: JSON.stringify(this.singleEditorsContent),
				fontSelected: this.fontSelected,
				fontSize:this.fontSize,
			};
			this.$refs.SugarJournal.saveData(context);
		}
	}
});
<commit_msg>Updated loadImages to fix sugarizer-server<commit_after>// Rebase require directory
requirejs.config({
	baseUrl: "lib",
	paths: {
		activity: "../js"
	}
});

// Vue main app
var app = new Vue({
	el: '#app',
	data: {
		grid: true,
		modeId: "grid-mode",
		images: [],
		activeImage: "",
		activeImageIndex: 0,
		previousBtnId: null,
		nextBtnId: null,
		recordIconId: null,
		imageCount: 9,	//update with Image slider
		imageLoaded: 0,
		intervalIds: [],
		colors: null,
		isLoaded: false,
		sizes: ['16px', '24px', '32px' ,'40px', '48px' , '56px', '64px' , '72px' , '80px' , '100px'],
		gridEditorContent: null,
		singleEditorsContent: [],
		editor: null,
		fontColor: null,
		backgroundColor: null,
		fontSelected: null,
		fontSize:null
	},
	methods: {
		initialized: function () {
			// Sugarizer initialized
			var environment = this.$refs.SugarActivity.getEnvironment();
			this.colors = [environment.user.colorvalue.fill, environment.user.colorvalue.stroke, '#FFFFFF'];
			if (this.activeImageIndex===0){
				this.previousBtnId = "previous-btn-inactive";
				this.nextBtnId = "next-btn";
			} else if (this.activeImageIndex===this.image.length - 1){
				this.previousBtnId = "previous-btn";
				this.nextBtnId = "next-btn-inactive";
			}
			this.recordIconId = "record";
			// document.getElementById('grid-mode').classList.add("active");
			for (var i=0; i<this.imageCount; i++){
				this.singleEditorsContent.push(null);
			}
			this.loadEditor();
		},
		imageLoaders: function(){
			function getRandomInt (min, max) {
				min = Math.ceil(min);
				max = Math.floor(max);
				return Math.floor(Math.random() * (max - min + 1)) + min;
			}
			const that = this;
			function getColor(){
				return that.colors[getRandomInt(0,2)];
			}
			var quesimgs = document.getElementsByClassName('questionmark');
			var len = quesimgs.length;
			if (!this.grid) len=1;
			for (var i=0; i<len; i++){
				quesimgs[i].style.background = getColor();
				(function (i){
					var intervalId = setInterval(function(){quesimgs[i].style.background = getColor()}, 900);
					that.intervalIds.push(intervalId);
				})(i);
			}
		},
		loadImages: function(){
			var xhr = new XMLHttpRequest();
			var imgs = [];
			var that = this;
			var source = document.location.href.substr(0, document.location.href.indexOf("/activities/"))+"/activities/Abecedarium.activity/database/db_meta.json";

			function checkFileExists (urlToFile) {
				try {
					var req = new XMLHttpRequest();
					req.open('HEAD', urlToFile, false);
					req.send();
					if(navigator.userAgent.indexOf("Safari") != -1){
						// Check sugarizer-server error here req.response != ""
						if (req.readyState === 4){
							return true;
						} else {
							return false;
						}
					} else {
						if (req.readyState === 4){
							return true;
						} else {
							return false;
						}
					}
				} catch (error) {
					return false;
				}
			}
			xhr.onload = function(){
					var data;
					data  = JSON.parse(xhr.response);
					for (var i=0; i<that.imageCount; i++){
						var img = data[Math.floor(Math.random() *  data.length)].code;
						var imgCheck = checkFileExists(document.location.href.substr(0, document.location.href.indexOf("/activities/"))+"/activities/Abecedarium.activity/images/database/"+img+".png");
						if (imgs.indexOf(img)===-1 && imgCheck==true){
							imgs.push(img);
						} else {
							i--;
						}
					}
					that.images = imgs;
					that.activeImage = that.images[that.activeImageIndex];
					if (!that.grid){
						that.isLoaded = true;
						for (var i=0; i<that.imageCount; i++){
							clearInterval(that.intervalIds[i]);
						}
					}
			};
			xhr.onerror = function(err){
				console.log("Error: ", xhr.statusText);
			};
			xhr.open("GET", source);
			xhr.send();
		},
		loadEditor: function(){
			var container = document.getElementById('editor-area');
			var editor = new Quill(container, {
				modules: {
				  toolbar: '.toolbar-container'
				},
			  });
			editor.format('size', '24px');
			this.editor = editor;
		},
		updateEditor: function(){
			this.fontColor != null && this.editor.format('color',this.fontColor);
			this.backgroundColor!=null && this.editor.format('background-color',this.backgroundColor);
			this.fontSelected !=null &&	this.editor.format('font', this.fontSelected);
			this.fontSize !=null ? this.editor.format('size', this.fontSize) : this.editor.format('size', '24px');
		},
		getUrlImg: function(img){
			return '../Abecedarium.activity/images/database/'+ img + '.png';
		},
		toggleMode: function(){
			if (this.grid){
				this.gridEditorContent = this.editor.getContents();
				this.editor.setContents(this.singleEditorsContent[this.activeImageIndex]);
				this.updateEditor();
				this.grid=false;
				this.modeId="single-mode";
			} else {
				this.activeImage = this.images[this.activeImageIndex];
				this.singleEditorsContent[this.activeImageIndex]= this.editor.getContents();
				this.editor.setContents(this.gridEditorContent);
				this.updateEditor();
				if (this.activeImageIndex === 0){
					this.previousBtnId = "previous-btn-inactive";
				}
				this.grid=true;
				this.modeId="grid-mode";
			}
		},
		previousImage: function () {
			if (this.activeImageIndex === 0){
				return;
			}
			this.nextBtnId = "next-btn";
			this.singleEditorsContent[this.activeImageIndex]= this.editor.getContents();
			this.activeImageIndex = this.activeImageIndex - 1;
			this.editor.setContents(this.singleEditorsContent[this.activeImageIndex]);
			this.updateEditor();
			this.activeImage = this.images[this.activeImageIndex];
			if (this.activeImageIndex === 0){
				this.previousBtnId = "previous-btn-inactive";
			}
		},
		nextImage: function () {
			if (this.activeImageIndex === this.images.length-1){
				return;
			}
			this.previousBtnId = "previous-btn"
			this.singleEditorsContent[this.activeImageIndex]= this.editor.getContents();
			this.activeImageIndex = this.activeImageIndex + 1;
			this.editor.setContents(this.singleEditorsContent[this.activeImageIndex]);
			this.updateEditor();
			this.activeImage = this.images[this.activeImageIndex];
			if (this.activeImageIndex === this.images.length-1){
				this.nextBtnId = "next-btn-inactive";
			}
		},
		loaded: function () {
			this.imageLoaded++;
			if (this.imageLoaded === this.imageCount ){
				this.isLoaded = true;
				this.activeImage = this.images[this.activeImageIndex];
				for (var i=0; i<this.imageCount; i++){
					clearInterval(this.intervalIds[i]);
				}
			}
		},
		increaseFont: function(){
			var currentSize = this.editor.getFormat();
			var that = this;
			if(currentSize.size==null){
				var index = that.sizes.indexOf('24px');
				that.editor.format('size',that.sizes[index+1]);
				that.fontSize = that.sizes[index+1];
			} else {
				var index = that.sizes.indexOf(currentSize.size);
				index++;
				if(index<that.sizes.length){
					that.editor.format('size',that.sizes[index]);
					that.fontSize = that.sizes[index];
				}
			}
		},
		decreaseFont: function(){
			var currentSize = this.editor.getFormat();
			var that = this;
			if(currentSize.size==null){
				var index = that.sizes.indexOf('24px');
				if(index>0)
				that.editor.format('size',that.sizes[index-1]);
				that.fontSize = that.sizes[index-1]
			}
			else {
				var index = that.sizes.indexOf(currentSize.size);
				index--;
				if(index>=0){
					that.editor.format('size',that.sizes[index]);
					that.fontSize = that.sizes[index];
				}
			}
		},
		onFormatText: function(e){
			this.editor.focus()
		},
		onFontChange: function(e){
			var newfont = e.font;
			if(newfont=="Arial") newfont="arial";
			if(newfont=="Comic Sans MS") newfont="comic";
			if(newfont=="Times New Roman")newfont="Times";
			if(newfont=="Courier New")newfont="Courier";
			if(newfont=="Lucida Console")newfont="Lucida";
			if(newfont=="Impact")newfont="Impact";
			if(newfont=="Georgia")newfont="Georgia";
			this.editor.format('font', newfont);
			this.fontSelected = newfont;
			this.editor.focus()
		},
		onForegroundColorChange: function(e){
			this.fontColor = e.detail.color;
			this.editor.format('color',this.fontColor);
		},
		onBackgroundColorChange: function(e){
			this.backgroundColor = e.detail.color;
			this.editor.format('background-color',this.backgroundColor);
		},

		onJournalNewInstance: function() {
			console.log("New instance");
			for (var i=0; i<this.imageCount; i++){
				this.singleEditorsContent.push(null);
			}
			this.imageLoaders();
			var that = this;
			window.setTimeout(function(){that.loadImages()},910);
		},
		onJournalDataLoaded: function (data, metadata) {
			console.log("Existing instance");

			this.grid = data.grid;
			this.imageLoaders();
			this.images = data.images;
			this.imageCount = data.imageCount;
			this.gridEditorContent = JSON.parse(data.gridEditorContent);
			this.singleEditorsContent = JSON.parse(data.singleEditorsContent);
			this.fontSelected = data.fontSelected;
			this.fontSize = data.fontSize;
			if(data.grid){
				this.grid=true;
				this.editor.setContents(this.gridEditorContent);
				this.updateEditor();
			} else {
				this.activeImage = this.images[this.activeImageIndex];
				this.grid = false;
				this.isLoaded = true;
				for (var i=0; i<this.imageCount; i++){
					clearInterval(this.intervalIds[i]);
				}
				this.editor.setContents(this.singleEditorsContent[0]);
				this.updateEditor();
				this.modeId="single-mode";
				if (this.activeImageIndex === 0){
					this.previousBtnId = "previous-btn-inactive";
				}
			}
		},
		onJournalLoadError: function(error) {
			console.log("Error loading from journal");
		},
		onStop: function() {
			if (this.grid){
				this.gridEditorContent = this.editor.getContents();
			} else {
				this.singleEditorsContent[this.activeImageIndex]= this.editor.getContents();
			}
			var context = {
				grid: this.grid,
				images: this.images,
				imageCount: this.imageCount,
				gridEditorContent: JSON.stringify(this.gridEditorContent),
				singleEditorsContent: JSON.stringify(this.singleEditorsContent),
				fontSelected: this.fontSelected,
				fontSize:this.fontSize,
			};
			this.$refs.SugarJournal.saveData(context);
		}
	}
});
<|endoftext|>