dojo.provide("parus.themeEditor");

dojo.require("parus.parus8");

if (!parus) parus = {};

if (!parus.parus8) dojo.mixin(parus, {
  parus8: {}
});

dojo.mixin(parus.parus8, {

  _nativeCSS: "",

  _themeCSSNode: null,

  _imageNames: null,

  _inspecting: false,

  _inspectingTimeout: null,

  toColor: function(idx) {
    var result = Number(idx).toString(16);
    while (result.length < 6)
    result = "0" + result;
    return "#" + result;
  },

  toColorIndex: function(str) {
    return eval(str.split("rgb").join("(function(r,g,b){return r*256*256+g*256+b;})"));
  },

  themeEditor: function() {
    this._themeEditorMode = true;
    dojo.cookie("bc", "", {
      expires: -1
    });

    parus.parus8._nativeCSS = dojo.cache("parus", "theme/custom/theme.css");
    parus.parus8._themeCSSNode = dojo.place("<style type=\"text/css\">" + "</style>", document.head, "last");
    parus.parus8._imageNames = eval(dojo.cache("parus", "theme/images.js"));
    parus.parus8._colorNames = eval(dojo.cache("parus", "theme/colors.js"));

    parus.parus8._indexedCSS = parus.parus8._nativeCSS;
    dojo.forEach(parus.parus8._colorNames, function(color, idx) {
      parus.parus8._indexedCSS = parus.parus8._indexedCSS.split("custom-" + color.name + "-custom").join(parus.parus8.toColor(idx));
    });

    parus.parus8.themeChanged();

  },

  blinkColor: function(name) {

    var variables = [{
      name: "custom-custom-custom",
      value: "custom"
    }];

    dojo.xhrGet({
      url: document.location.protocol + "//editor/theme.less",
      handleAs: "text",
      sync: true,
      load: function(response) {
        dojo.forEach(response.split(";"), function(v, idx) {
          if (idx >= 1) {
            v = v.split(":");
            if (v.length > 1) variables.push({
              name: "custom-" + dojo.trim(v[0] || "").split("@").join("") + "-custom",
              value: dojo.trim(v[1] || "")
            });
          }
        });
      }
    });

    var r = parus.parus8._nativeCSS;
    dojo.forEach(parus.parus8._imageNames, function(image, idx) {
      r = r.split("../images/" + image.name).join(document.location.protocol + "//editor/img?idx=" + idx);
      r = r.split("images/" + image.name).join(document.location.protocol + "//editor/img?idx=" + idx);
    });

    var blinkColors = ["white", "black", "green", "red", "blue", "fuchsia", "white", "black", "green", "red", "blue", "fuchsia", "white", "black", "green", "red", "blue", "fuchsia"];

    setTimeout(function() {
      var ir = r;
      if (blinkColors.length) {
        dojo.forEach(variables, function(v) {
          ir = ir.split(v.name).join((v.name == "custom-" + name + "-custom") ? blinkColors.shift() : v.value);
        });
        setTimeout(arguments.callee, 150);
      }
      else {
        dojo.forEach(variables, function(v) {
          ir = ir.split(v.name).join(v.value);
        });
      }
      parus.parus8._themeCSSNode.innerHTML = ir;
    }, 150);

  },


  themeChanged: function() {

    var variables = [{
      name: "custom-custom-custom",
      value: "custom"
    }];

    dojo.xhrGet({
      url: document.location.protocol + "//editor/theme.less",
      handleAs: "text",
      sync: true,
      load: function(response) {
        dojo.forEach(response.split(";"), function(v, idx) {
          if (idx >= 1) {
            v = v.split(":");
            if (v.length > 1) variables.push({
              name: "custom-" + dojo.trim(v[0] || "").split("@").join("") + "-custom",
              value: dojo.trim(v[1] || "")
            });
          }
        });
      }
    });

    var r = parus.parus8._nativeCSS;

    dojo.forEach(variables, function(v) {
      r = r.split(v.name).join(v.value);
    });


    var pc = (+(new Date));

    dojo.forEach(parus.parus8._imageNames, function(image, idx) {
      r = r.split("../images/" + image.name).join(document.location.protocol + "//editor/img?idx=" + idx + "&preventCache=" + pc);
      r = r.split("images/" + image.name).join(document.location.protocol + "//editor/img?idx=" + idx + "&preventCache=" + pc);
    });

    parus.parus8._themeCSSNode.innerHTML = r;

  },

  selectElementColors: function(node) {

    var backup = parus.parus8._themeCSSNode.innerHTML;
    parus.parus8._themeCSSNode.innerHTML = parus.parus8._indexedCSS;
    var cssColors = [];

    while (node /*&& !cssColors.length*/ ) {
      var styleSheets = document.styleSheets;
      for (var i = 0; i < styleSheets.length; i++) {
        if (!styleSheets[i].href) {
          var rules = styleSheets[i].rules;
          for (var j = 0; j < rules.length; j++) {
            var rule = rules[j];
            var nodes = document.querySelectorAll(rule.selectorText.split("custom-custom-custom").join("custom"));
            for (var k = 0; k < nodes.length; k++) {
              if (nodes[k] == node) {
                var matches = rule.cssText.match(/rgb\([0-9, ]*\)/g);
                if (matches) for (var l = 0; l < matches.length; l++) {
                  var color = parus.parus8.toColorIndex(matches[l]);
                  if (dojo.indexOf(cssColors, color) < 0) cssColors.push(color);
                }
              }
            }
          }
        }
      }
      node = node.parentNode;
    };

    parus.parus8._themeCSSNode.innerHTML = backup;

    if (cssColors.length) dojo.xhrGet({
      url: document.location.protocol + "//editor/selectColor?idx=" + cssColors.join(","),
      handleAs: "text",
      sync: true,
      loaded: function() {}
    })
    else alert("Не удалось получить цвета элемента.");
  },

  _inspectEvents: ["click", "auxclick", "contextmenu", "dblclick", "mousedown",
  //    "onblur",
  "onfocus", "onfocusin",
  //    "onfocusout",
  "dragstart", "pointerdown", "pointerup", "selectstart", "mouseup"],

  inspectElementClick: function(e) {
    if (parus.parus8._inspecting) {
      var node = e.target;
      e.stopPropagation();
      e.stopImmediatePropagation();
      e.preventDefault();
      e.cancelBubble = true;
      e.bubbles = false;
      e.returnValue = true;
      e.target = null;
      if (!parus.parus8._inspectingTimeout) parus.parus8._inspectingTimeout = setTimeout(dojo.hitch(function() {
        parus.parus8._inspectingTimeout = null;
        setTimeout(parus.parus8.unInspectElement, 500);
        parus.parus8.selectElementColors(node);
      }), 100);
    }
    return false;
  },

  inspectElement: function() {
    parus.parus8.unInspectElement();
    dojo.forEach(parus.parus8._inspectEvents, function(evt) {
      window.addEventListener(evt, parus.parus8.inspectElementClick, true);
    });
    parus.parus8._inspecting = true;
  },

  unInspectElement: function() {
    parus.parus8._inspecting = false;

    dojo.forEach(parus.parus8._inspectEvents, function(evt) {
      window.removeEventListener(evt, parus.parus8.inspectElementClick, true);
    });

    if (parus.parus8._inspectingTimeout) {
      clearTimeout(parus.parus8._inspectingTimeout);
      parus.parus8._inspectingTimeout = null;
    }
  }

});