//
//  ENCPClean.js
//  CoverPage
//
//  Created by Zdzislaw Losvik on 09/04/2013.
//  Copyright (c) 2013 Evernote. All rights reserved.
//

//"use strict";


(function(jquery) {

  var $ = jquery;

  $.fn.extend({
    reverse: function() {
        return this.pushStack(this.get().reverse(), arguments);
    }
  });

  var ENCPClean = function() {
  }

  ENCPClean.prototype = {

    COLOR_DESATURATION_FACTOR: 0.6,
    fontsInfoCache: {},
    canvas: document.createElement("canvas"),
    callback: null,

    desaturateColor : function (color, amount) {
      var oldColor = this.convertColorToRGB(color);
      var intensity = 0.3 * oldColor.R + 0.59 * oldColor.G + 0.11 * oldColor.B;
      var newColor = {
        R : intensity * amount + oldColor.R * (1 - amount),
        G : intensity * amount + oldColor.G * (1 - amount),
        B : intensity * amount + oldColor.B * (1 - amount)
      };
      var colorValue = ((newColor.R << 16) | (newColor.G << 8) | newColor.B).toString(16);
      return "#" + ('000000' + colorValue).slice(-6);
    },

    convertColorToRGB: function(color) {
      var resultColor = "000000";
      if (color == 'black') {
        resultColor = "000000";
      }
      if (color[0] == "#") {
        resultColor = color.slice(1);
      }
      var rgbRegex = /\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/g;
      var rgbMatch = rgbRegex.exec(color);
      if (rgbMatch) {
        resultColor = {
          R : parseInt(rgbMatch[1]),
          G : parseInt(rgbMatch[2]),
          B : parseInt(rgbMatch[3])
        };
      } else {
        var colorInt = parseInt(resultColor, 16);
        resultColor = {
          R : (colorInt >> 16) & 0xFF,
          G : (colorInt >> 8) & 0xFF,
          B : colorInt & 0xFF
        };
      }
      return resultColor;
    },

    isBlackColor: function(colorString) {
      var color = this.convertColorToRGB(colorString);
      return color.R == 0 && color.G == 0 && color.B == 0;
    },

    fixImageLayout: function (rootElement) {

      function isSmallImage($image) {

        function isSmallSize(height, width) {
          if (!height || !width) {
            return false;
          }
          height = parseInt(height);
          width = parseInt(width);
          return height && width && height <= 64 && width <= 64;
        }

        if (isSmallSize($image.css("height"), $image.css("width"))) {
          return true;
        }

        if (isSmallSize($image.attr("height"), $image.attr("width"))) {
          return true;
        }
        var id = $image.attr("id");
        if (id) {
          // en-media:image/png:450d271a5b82fc52a3a50cc07cb1a874:23:23
          var matchObject = id.match(/^en-media:.*:(\d+):(\d+)$/i);
          if (matchObject) {
            var height = parseInt(matchObject[1]);
            var width = parseInt(matchObject[2]);
            if (isSmallSize(height, width)) {
              return true;
            }
          }
        }
        return false;
      }

      $(rootElement).find('img').filter(function () {
        return !$(this).closest("table, td, tr, .encp-media-container").length;
      }).each(function () {
        var $img = $(this);
        if (isSmallImage($img)) {
          $img.addClass("encp-small-image");
        } else {
          // TODO: Here replace img[src] with a link to a thumbnail obtained from the ENCPPlatform
          // TODO: Can encp-media-preview be moved from div to img nad div be removed? Here an everywhere else.
          var mime = $img.attr('x-evernote-mime');
          if (!mime && $img.attr('id')) {
            mime = $img.attr('id').split(":")[1];
          }
          $img.wrap('<div class="encp-media-container"/>').wrap('<div class="encp-media-preview"/>');
          $img.closest('.encp-media-container')
            .attr("data-media-url", $img.attr('src'))
            .attr("data-media-mime", mime)
            .addClass("encp-can-open-attachment");
        }
        $img.css("height", "");
        $img.css("width", "");
        $img.removeAttr("height");
        $img.removeAttr("width");
        $img.removeAttr("align");
      });
    },

    isMonospaceFont: function(fontName) {
      var self = this;
      if (self.fontsInfoCache[fontName] !== undefined) {
        return (self.fontsInfoCache[fontName] === 'fixed');
      }
      var isMono = false;
      if (fontName == 'Andale Mono' || fontName == 'Menlo' || fontName == 'Courier' || fontName == 'Courier New') {
        isMono = true;
      } else {
        var context = self.canvas.getContext("2d");
        context.font = '100px ' + fontName;
        isMono = (context.measureText('WWwwMMmm').width == context.measureText('..iijj--').width);
      }
      self.fontsInfoCache[fontName] = isMono ? 'fixed' : 'proportional';
      return isMono;
    },

    fixElementsStyle : function (rootElement) {
      var self = this;
      if ($(rootElement).attr('style')) {
        $(rootElement).attr('style','');
      }
      $(rootElement).find("[style]").each(function() {
        var element = $(this);
        if (this.getAttribute('style').indexOf('-evernote-highlight') > -1) {
          element.addClass('encp-note-highlight');
        }
        var fontFamily = element.css("font-family");
        if (fontFamily) {
          element.css("font-family", "");
          if (self.isMonospaceFont(fontFamily)) {
            element.addClass('encp-monospace-inline');
          }
        }
        // CP-227 - Use style attribute instead of Jquery css function, which converts the size to
        // pixels resulting in different results on different hardware (retina/non retina)
        var fontSize = this.style.fontSize;
        if (fontSize) {
          element.css("font-size", "");
          element.addClass(self.computeFontClassForSize(fontSize));
        }
        element.css("font-size", "");
        // CP-554 -  Text compressed in copy-paste content
        element.css("width", "");
        if (element.attr("width")) {
          element.attr("width", "");
        }
        var color = element.css("color");
        if (color) {
          // if (self.isBlackColor(color)) {
          //   element.css("color", "");
          // } else {
          //   element.css("color", self.desaturateColor(color, self.COLOR_DESATURATION_FACTOR));
          // }
        }
        if (element.css("background-color")) {
          element.css("background-color", "");
        }
        if (element.is("p, div, font, bold, i, span")) {
          this.style.margin = "";
          this.style.marginTop = "";
          this.style.marginBottom = "";
          this.style.marginLeft = "";
          this.style.marginRight = "";
          this.style.lineHeight = "";
        } else if (element.is("li")) {
          this.style.display = "";
        }
      });
    },

    computeFontClassForSize: function(sizeString) {
      var size = 0;
      if (sizeString.search(/px/gi) != -1) {
        size = Math.ceil(parseInt(sizeString.replace(/px/gi)) * 72 / 96);
      } else if (sizeString.search(/pt/gi) != -1) {
        size = parseInt(sizeString.replace(/pt/gi));
      } else if (sizeString.search(/em/gi) != -1) {
        size = Math.ceil(parseFloat(sizeString.replace(/em/gi)) * 12);
      } else if (sizeString.search(/xx-small/gi) != -1) {
        size = 8;
      } else if (sizeString.search(/x-small/gi) != -1) {
        size = 10;
      } else if (sizeString.search(/small/gi) != -1) {
        size = 12;
      } else if (sizeString.search(/medium/gi) != -1) {
        size = 14;
      } else if (sizeString.search(/large/gi) != -1) {
        size = 18;
      } else if (sizeString.search(/x-large/gi) != -1) {
        size = 24;
      } else if (sizeString.search(/xx-large/gi) != -1) {
        size = 36;
      } else {
        size = parseInt(sizeString);
        switch (size) {
          case 1: size = 10; break;
          case 2: size = 13; break;
          case 3: size = 16; break;
          case 4: size = 18; break;
          case 5: size = 24; break;
          case 6: size = 32; break;
          case 7: size = 48; break;
          default: size = 13; break;
        }
      }
      if (size <= 9) {
        return "small-font";
      } else if (size <= 17) {
        return "medium-font";
      } else {
        return "large-font";
      }
    },

    fixFontElements: function(rootElement) {
      var self = this;
      $(rootElement).find("font").each(function() {
        var element = $(this);
        var size = element.attr("size");
        if (size) {
          element.removeAttr("size");
          element.addClass(self.computeFontClassForSize(size));
        }
        if (element.attr("face")) {
          if (self.isMonospaceFont(element.attr('face'))) {
            if (element.parent().children().length == 1) {
              element.parent().addClass('encp-monospace-inline');
            } else {
              element.addClass('encp-monospace-inline');
            }
          }
          element.removeAttr("face");
        }
      });
    },

    fixElementsColor : function (rootElement) {
      var self = this;
      $(rootElement).find("[color]").each(function() {
        var element = $(this);
        var color = element.attr("color");
        if (self.isBlackColor(color)) {
          element.removeAttr("color");
        } else {
          element.attr("color", self.desaturateColor(color, self.COLOR_DESATURATION_FACTOR));
        }
      });
      $(rootElement).css("background-color", "");
    },

    fixLinks: function(rootElement) {
      $(rootElement).find("a").each(function() {
        var $this = $(this);
        if ($this.attr("href") && $this.attr("href").match(/evernote:/i)) {
          $this.addClass("encp-note-link");
        }
        if (!$this.find("img, embed").length) {
          $this.addClass("encp-text-link");
          $this.attr("tabindex", "0");
          $this.find("[style]").removeAttr("style");
          $this.find("[color]").removeAttr("color");
          $this.find("[background-color]").removeAttr("background-color");
          $this.find("font").each(function() {
            $(this).replaceWith("<span>" + this.innerHTML + "</span>");
          });
        }
      });
    },

    disableBrokenLinks: function() {
      $a = $('a.encp-broken-link');
      $a.removeAttr('href').attr('tabindex', '-1');
      $a.after('<img src="images/broken_notelink.svg" class="encp-broken-link-warning">');
    },

    replaceEncryptedText: function(rootElement) {
      $(rootElement).find("img[src^='en-resource://database/pprotect']").each(function() {
        $(this).attr({
          'src':'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKoAAAAoCAIAAADhbPYGAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAATFJREFUeNrsmkEOwUAUQBGL7rpjhxUu0c50IVxLJO5CHIBYdMolcAN23XXpS5NGBCE0Yea9pE3n93fzX/5Pp2k1juMKuEpdDq01hXAQY0yNKrgM+tEP6Af0A/oB/YB+QD/YS/2Th3f7w3K1TtO0iPi+PxoO+r0ulbW8+8X9bL64di/IUoJyi8pa3v3S93JuNhtahXm7i3WTbI7Hk9xiANjc/VmW5X1fuBfkQpb5DKCyTrz63XR5p92ipvYPf8/z3oq/SBRFd+OPfkog/3k+Gz9AP3xr+Jtkm2y2xXI8md5Ny+MqDLQKqLI93X/t/rvJwPAH9AP64Xf3/SXx7v6VfLof0A/oh9L1qzAoKRn+4NVPKz7kMfwB/YB+QD+gH9AP6Af0A/rhp7l89TPGUAg3OQswAElrbo/AAOZ/AAAAAElFTkSuQmCC',
          'class': 'encrypted-text no-doc-viewer'
        }).parent().parent().css('text-align','left');
      });
    },

    replaceBrokenImages: function(rootElement) {
      $(rootElement).find("img").each(function() {
        $(this).error(function(){
          $(this).attr({
            'src':'data:image/png;base64,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',
            'class': 'broken-image no-doc-viewer'
          });
        });
      });
    },

    removeFontClass: function(element) {
      $.each(['small-font','medium-font','large-font'], function() {
        var aClass = this.toString();
        element.removeClass(aClass);
        element.find('.' + aClass).removeClass(aClass);
      });
    },

    cleanSegmentedMonospaces: function(element) {
      var self = this;
      var monospaces = $();
      function wrapElement(kids) {
        var start = kids[0];
        var isBlockElement = $(start).is('p, div, blockquote, pre, ol, ul');
        if (kids.length > 1) {
          var end = kids[kids.length - 1];
          var $contents = element.contents();
          var tag = $(document.createElement(isBlockElement ? 'div' : 'span')).addClass('encp-note-monospace');
          $contents.slice($contents.index(start),$contents.index(end) + 1).removeClass('encp-monospace-inline').wrapAll(tag);
        } else if (kids.length && isBlockElement) {
          $(start).removeClass('encp-monospace-inline').addClass('encp-note-monospace');
        }
      }
      element.children().each(function() {
        var $child = $(this);
        if ($child.hasClass('encp-monospace-inline')) {
          monospaces.push($child);
          self.removeFontClass($child);
        } else {
          if (monospaces.length) {
            wrapElement(monospaces);
          }
          monospaces = [];
        }
      });
      if (monospaces.length) {
        wrapElement(monospaces);
      }
    },

    mergeMonospaceElements: function(rootElement) {
      var self = this;
      $(rootElement).find('*:has(.encp-monospace-inline)').each(function() {
        var $this = $(this);
        if ($this.children('.encp-monospace-inline').length == 0) {
          return;
        }
        if ($this.children('.encp-monospace-inline').length == $this.children().length) {
          $this.addClass('encp-note-monospace');
          $this.children().removeClass('encp-monospace-inline');
          self.removeFontClass($this);
        } else {
          self.cleanSegmentedMonospaces($this);
        }
      });
      self.cleanSegmentedMonospaces($(rootElement));
    },

    trimWhitespaceAtEndOfElement: function(element) {
      var self = this;
      var stop = false;
      var $element = $(element);

      stop = Array.prototype.some.call($element.children().reverse(), function (child) {
        return self.trimWhitespaceAtEndOfElement(child);
      });
      if (stop) return stop;

      Array.prototype.some.call($element.contents().reverse(), function (el) {
        var $el = $(el);
        var text;

        if (!$el.is('body, html, head')) {
          text = $el.text().replace(/[\n\s]+/g, '');
          if (text.length > 0 
              || $el.is('#en-editor-last-insertion-point, .encp-media-container, .encp-media-preview, .checkbox')
              || !$el.is('p, span, div, br')) {
            stop = true;
          } else {
            $el.remove();
          }
        }
        
        return stop;
      });

      return stop;
    },

    useUnsupportedFilePlaceholders: function (rootElement) {
      $(rootElement).find('span.attachment').each(function () {
        var $this = $(this);
        $this.find('span.icon').each(function() {
          $(this).replaceWith('<img src="images/file_attachment_icon.svg">');
        });
        $this.find('a.encp-text-link').removeClass('encp-text-link');
      });
    },

    postprocessWebContent: function (rootElement, noteTitle) {
      window.encpPlatform.markBrokenNoteLinks(rootElement);
      this.postprocessWebNoTitleContent(rootElement);
      this.insertNoteTitle(rootElement, noteTitle)
    },

    postprocessWebNoTitleContent: function (rootElement) {
      window.encpPlatform.markBrokenNoteLinks(rootElement);
      window.encpPlatform.fixEmbeddedMedia(rootElement);
      this.convertEmbeddedCheckboxesToHTML($(rootElement));
    },

    postprocessNoteContent: function (rootElement, noteTitle) {
      window.encpPlatform.markBrokenNoteLinks(rootElement);
      window.encpPlatform.fixEmbeddedMedia(rootElement);
      this.convertEmbeddedCheckboxesToHTML(rootElement);
      this.fixFontElements(rootElement);
      this.fixElementsStyle(rootElement);
      this.fixElementsColor(rootElement);
      this.fixImageLayout(rootElement);
      this.styleOrderedLists(rootElement);
      this.insertNoteTitle(rootElement, noteTitle);
      this.fixLinks(rootElement);
      this.disableBrokenLinks(rootElement);
      this.replaceEncryptedText(rootElement);
      this.replaceBrokenImages(rootElement);
      this.useUnsupportedFilePlaceholders(rootElement);
      this.mergeMonospaceElements(rootElement);
      this.trimWhitespaceAtEndOfElement(rootElement);
    },

    /**
     * @param rootElement the element and its children to be changed
     * @param noteAttributes - an object or JSON string containing info about the note: title, source, sourceURL, contentClass, and author
     */
    postprocess: function (rootElement, noteAttributes) {
      if (typeof noteAttributes == "string") {
        noteAttributes = JSON.parse(noteAttributes);
      }

      var typeInfo = this.checkPresentationType(rootElement, noteAttributes);

      this.postprocessWithTypeInfo(rootElement, noteAttributes.title, typeInfo);
      if (this.callback && typeof this.callback == 'function') {
        this.callback();
      }
    },

    postprocessWithTypeInfo: function(rootElement, noteTitle, typeInfo) {
      var $html = $("html");
      $html.attr("encp-source", typeInfo.source);
      $html.attr("encp-content-class", typeInfo.contentClass);
      $html.addClass('anysource');
      $html.addClass(typeInfo.cssClass);

      if (typeInfo.isNoteSource) {
        $html.addClass("encp-nocontents-in-title");
        this.postprocessNoteContent(rootElement, noteTitle);
      } else {
        if (typeInfo.needsTitle) {
          this.postprocessWebContent(rootElement, noteTitle);
        } else {
          $html.addClass("encp-no-title");
          this.postprocessWebNoTitleContent(rootElement);
        }
      }
    },

    checkPresentationType: function(rootElement, noteAttributes) {
      var needsTitle = true;
      var cssClass = null;
      var $rootElement = $(rootElement);
      var hasImages = $rootElement.find("img, embed, object.en-attachment").length > 0;
      var theText = rootElement.innerText;
      var hasText = (theText && theText.trim().length > 0);
      if (noteAttributes.source == "mobile.ios" && noteAttributes.contentClass == "evernote.penultimate.notebook") {
        cssClass = "notesource";
      } else if (noteAttributes.contentClass && noteAttributes.contentClass.indexOf("evernote.skitch") == 0) {
        cssClass = "notesource";
      } else if (!noteAttributes.source && !noteAttributes.author &&
          (noteAttributes.sourceURL == "http://evernote.com/" || noteAttributes.sourceURL == "http://yinxiang.com/")) {
        // Welcome note
        cssClass = "websource";
        needsTitle = false;
      } else if (noteAttributes.source == "mobile.android" && noteAttributes.sourceURL && noteAttributes.sourceURL.length > 0) {
        cssClass = "websource";
      } /*else if (noteAttributes.source == "web.clip" && !hasText) {
        cssClass = "notesource";
      }*/ else if (noteAttributes.source == 'Clearly' ||
          ((noteAttributes.contentClass && noteAttributes.contentClass.indexOf('evernote.food') === 0) ||
           (noteAttributes.contentClass && noteAttributes.contentClass.indexOf('evernote.hello') === 0))) {
        cssClass = "websource";
        needsTitle = false;
      } else if (noteAttributes.contentClass || noteAttributes.source == 'mail.smtp' || noteAttributes.source == 'web.clip') {
        cssClass = "websource";
        // Try being smart and do not add the title if it already exists at the beginning of a note
        var title = noteAttributes.title;
        if (title) {
          if (rootElement.textContent && rootElement.textContent.substr(0, title.length) == title) {
            needsTitle = false;
          }
        }
      } else {
        cssClass = "notesource";
      }
      return {
        source: noteAttributes.source,
        contentClass: noteAttributes.contentClass,
        cssClass: cssClass,
        needsTitle: needsTitle,
        isNoteSource: cssClass == "notesource",
        isEmpty: (!hasText && !hasImages)
      };
    },

    stylesheetName: function() {
      if ($("html").is(".notesource")) {
        return "presentation";
      } else {
        return "websource";
      }
    },

    convertEmbeddedCheckboxesToHTML : function(rootElement) {

      var checkInsideText = function(checkboxElement) {
        var prevSibling = checkboxElement.previousSibling;
        var $prevSibling = $(prevSibling);
        var text;
        if (prevSibling) {
          text = $prevSibling.text().replace(/[\n\s]+/g, '');
          return (prevSibling.nodeType == Node.TEXT_NODE && text.length > 0);
        }
        return false;
      }

      $(rootElement).find("img[src^='en-resource://database/check']").replaceWith(function() {
        var checkbox = $("<div class='checkbox'></div>");
        if (checkInsideText(this)) {
          checkbox.addClass("inside-text")
        };
        if ($(this).attr("src").match(/check1:/)) {
          checkbox.addClass("checked");
        }
        return checkbox;
      });
      $(rootElement).find("input[type='checkbox']").replaceWith(function() {
        var checkbox = $("<div class='checkbox'></div>");
        if (checkInsideText(this)) {
          checkbox.addClass("inside-text")
        };
        if ($(this).attr("checked") == 'checked') {
          checkbox.addClass("checked");
        }
        return checkbox;
      });
    },

    styleOrderedLists: function(rootElement) {
      $(rootElement).find("ol").each(function() {
        var ol = $(this);
        ol.children("li").each(function(index) {
          var liElement = $(this);
          liElement.wrapInner('<span class="content"></span>');
        });
      });
    },

    insertNoteTitle: function(rootElement, title) {
      if (!title || !title.length) {
        return;
      }
      title = title.split("&nbsp;").join(" ");
      var titleTemplate = $(
          "<div class='encp-note-title'>" +
            "<div class='encp-title-container'>" +
            "<h1 class='title'></h1>" +
          "</div>" +
      "</div>");
      $(titleTemplate).find("h1.title").text(title);
      $(rootElement).prepend(titleTemplate);
    },

    addStyle: function(path,title,rel) {
      var style = document.createElement('link');
      style.setAttribute('rel',(rel) ? rel : 'stylesheet');
      style.setAttribute('type','text/css');
      style.setAttribute('href',path);
      style.setAttribute('title',(title) ? title : '');
      document.getElementsByTagName('head')[0].appendChild(style);
    },

    addCommonStyle: function(title) {
      this.addStyle('css/' + title + '.css','','stylesheet');
    },

    addExtraStyle: function(title) {
      this.addStyle('css/' + title + '.css',title,'alternate stylesheet');
    },

    addThemeStyle: function(title) {
      var themeTitle = title;
      while (themeTitle.indexOf('-') > -1) {
        themeTitle = themeTitle.substr(themeTitle.indexOf('-') + 1);
      }
      this.addStyle('css/' + title + '.css',themeTitle,'alternate stylesheet');
    }
  };

  if (0) {
    window.addEventListener('load', function () {
      var cp = new ENCPClean();
      //noinspection XHTMLIncompatabilitiesJS
      cp.postprocess(document.body, {"contentClass":null,"author":"Kati Pesonen","title":"WC6: Simplified Article - Twitter “Related Headlines” Deliver News By Linking To Sites Where A Tweet Is Embedded | TechCrunch","source":"web.clip","sourceURL":"http://techcrunch.com/2013/08/19/twitter-related-headlines/"});
    }, false);
  }


  /**
   * Global exports below
   */
  window.ENCPClean = ENCPClean;

})(window.$encpJquery);


