/* global HTMLElement */
/* eslint no-extend-native: ["error", { "exceptions": ["Array", "String", "HTMLElement"] }] */
;(function () {
  /* 常用资讯站点的文章正文区节点样式名 */
  var siteContentRe = {
    'hnedu.cn': {
      siteName: '湖南教育网',
      idRe: /^zdetail_zhengwena$/
    },
    'toutiao.com': {
      // 今日头条
      siteName: '今日头条',
      classNameRe: /article-content/
    },
    'sina.com.cn': {
      // 新浪新闻
      siteName: '新浪',
      classNameRe: /blkContainerSblkCon|article/,
      idRe: /^article$/
    },
    'ifeng.com': {
      // 凤凰资讯
      siteName: '凤凰网',
      classNameRe: /yc_con_txt/,
      idRe: /^(artical_real|yc_con_txt)$/
    },
    'qq.com': {
      // QQ新闻
      siteName: '腾讯',
      classNameRe: /Cnt-Main-Article-QQ/,
      idRe: /^Cnt-Main-Article-QQ$/
    },
    'xinhuanet.com': {
      // 新华网
      siteName: '新华网',
      classNameRe: /content/,
      idRe: /^(contentblock|p-detail)$/
    },
    'cntv.cn': {
      // CCTV新闻
      siteName: 'CCTV网',
      classNameRe: /cnt_bd/,
      idRe: /^content_body$/
    },
    'sohu.com': {
      // 搜狐新闻
      siteName: '搜狐',
      classNameRe: /article/,
      idRe: /^(contentText|mp-editor)$/
    },
    'huanqiu.com': {
      // 环球网
      siteName: '环球网',
      classNameRe: /la_con/
    },
    '163.com': {
      // 网易新闻
      siteName: '网易',
      classNameRe: /post_text/,
      idRe: /^endText$/
    },
    'cn.reuters.com': {
      // 路透中文网
      siteName: '路透中文网',
      classNameRe: /StandardArticleBody_body/,
      idRe: /^resizeableText$/
    },
    'zaobao.com': {
      // 联合早报
      siteName: '联合早报',
      classNameRe: /article-content-container/,
      idRe: /^FineDining$/
    },
    'people.com.cn': {
      // 人民网
      siteName: '人民网',
      classNameRe: /show_text|box_con/,
      idRe: /^(p_content|rwb_zw)$/
    },
    'cankaoxiaoxi.com': {
      // 参政消息
      siteName: '参政消息',
      classNameRe: /article-content/,
      idRe: /^ctrlfscont$/
    },
    'youku.com': {
      // 优酷
      siteName: '优酷',
      classNameRe: /(player|youku-player)/,
      idRe: /^(player|ykPlayer)$/
    },
    'wnzfw.gov.cn': {
      siteName: '渭南政法网',
      classNameRe: /news_page_content_text/
    }
  }

  var script = document.getElementById('_oneKeyReprintSheet')
  if (!script) {
    return
  }
  var jspath = script.hasAttribute ? script.src : script.getAttribute('src', 4)
  // ie下通过getAttribute('src', 4)才能获取全路径
  var baseUrl = jspath.substr(0, jspath.lastIndexOf('/') + 1)
  var savePostUrl = baseUrl + 'articleReprintEditor.html'
  var UID = new Date().getTime()
  var postFrameId = 'z-reprint-frame-' + UID // 唯一iframe id
  var postDialog
  var postFrame
  var articlePreviouslyValidated = false // 记录文章是否刚刚被转载过
  var pages$prepArticle$html = [] // 所有页面的正文HTML
  var isIE = !!window.ActiveXObject
  var isIE6 = isIE && !window.XMLHttpRequest
  var isQuirks =
    isIE6 || (document.compatMode === 'BackCompat' && typeof document.documentMode !== 'undefined' && document.documentMode < 7)

  if (!window.console) {
    window.console = {
      log: function () {}
    }
  }

  var getHost = function (url) {
    var dummyLink = document.createElement('a')
    dummyLink.href = url || document.URL
    return dummyLink.hostname
  }
  var theHost = getHost()
  var theHostName = theHost
  var theSiteInfo = {}

  /* 从常用站点的文章正文规则 , 取当前站点的正文元素id或class */
  for (var domain in siteContentRe) {
    if (theHost.indexOf(domain) > -1) {
      theSiteInfo = siteContentRe[domain]
      theHostName = theSiteInfo.siteName || theHost
      break
    }
  }

  function toArray (iterable, start, len) {
    //  把可枚举的集合转换为数组
    if (!iterable || !iterable.length) {
      return []
    }
    if (typeof iterable.length === 'number') {
      var results = []
      var i = 0
      var l = iterable.length
      for (; i < l; i++) {
        results.push(iterable[i])
      }
      return results.slice(start || 0, len || results.length)
    }
  }

  if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (obj) {
      var len = this.length
      var i = 0
      for (; i < len; i++) {
        if (this[i] === obj) {
          return i
        }
      }
      return -1
    }
  }
  if (String.prototype.indexOf) {
    String.prototype.trim = function () {
      return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '')
    }
  }
  if (!isIE && HTMLElement.prototype) {
    HTMLElement.prototype.__defineSetter__('innerText', function (txt) {
      this.textContent = txt
    })
    HTMLElement.prototype.__defineGetter__('innerText', function () {
      return this.textContent
    })
  }
  function getStyle (el) {
    if (!el.currentStyle) {
      el.currentStyle = (el.ownerDocument.defaultView || window).getComputedStyle(el, null)
    }
    return el.currentStyle
  }

  function getDimension (el) {
    // 获取元素尺寸
    if (!el._Dimension) {
      el._Dimension = {}
      var dimension = el.getBoundingClientRect()
      if (isIE) {
        // IE下不能对getBoundingClientRect方法返回的对象修改
        var prop = { bottom: 1, left: 1, right: 1, top: 1 }
        for (var key in prop) {
          el._Dimension[key] = dimension[key]
        }
        el._Dimension.width = el.offsetWidth
        el._Dimension.height = el.offsetHeight
      } else {
        el._Dimension = dimension
      }
      var doc = el.ownerDocument || document
      var scrollTop = Math.max(doc.documentElement.scrollTop, doc.body.scrollTop)
      var scrollLeft = Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft)
      el._Dimension.offsetLeft = el._Dimension.left + scrollLeft
      el._Dimension.offsetTop = el._Dimension.top + scrollTop
    }
    return el._Dimension
  }

  function isVisible (el) {
    var cs = getStyle(el)
    if (cs.display === 'none' || cs.visibility === 'hidden') {
      return false
    }
    if (cs.display !== 'inline' && el.offsetWidth === 0 && el.offsetHeight === 0) {
      return false
    }
    cs = getDimension(el)
    if (cs.width <= 0 && cs.height <= 0) {
      return false
    }
    return true
  }
  function getChildrenElements (el) {
    var tmp = []
    var i
    for (i = 0; i < el.childNodes.length; i++) {
      var n = el.childNodes[i]
      if (n.nodeType === 1) {
        tmp.push(n)
      }
    }
    return tmp
  }

  function getArticleTitle (doc) {
    doc = doc || document
    var curTitle = ''
    var origTitle = ''

    try {
      curTitle = origTitle = doc.title

      if (typeof curTitle !== 'string') {
        /* 如果有页面元素的id="title"，则document.title可能为此元素 */
        curTitle = origTitle = doc.getElementsByTagName('title')[0].innerText
      }
    } catch (e) {}

    if (curTitle.match(/ [|-] /)) {
      curTitle = origTitle.replace(/(.*)[|-] .*/gi, '$1')

      if (curTitle.split(' ').length < 3) {
        curTitle = origTitle.replace(/[^|-]*[|-](.*)/gi, '$1')
      }
    } else if (curTitle.indexOf(': ') !== -1) {
      curTitle = origTitle.replace(/.*:(.*)/gi, '$1')

      if (curTitle.split(' ').length < 3) {
        curTitle = origTitle.replace(/[^:]*[:](.*)/gi, '$1')
      }
    }
    var hs = []
    var h3s = toArray(doc.getElementsByTagName('h3'))
    var h2s = toArray(doc.getElementsByTagName('h2'))
    var h1s = toArray(doc.getElementsByTagName('h1'))

    hs = hs.concat(h3s, h2s, h1s) /* 查找页面内的 */
    if ((curTitle.length < 3 || curTitle.length > 150) && hs.length === 1) {
      curTitle = hs[0].innerText
    } else {
      for (var i = 0; i < hs.length; i++) {
        var h = hs[i].innerText
        if (h.length > 2 && origTitle.indexOf(h) > -1) {
          curTitle = h
        }
      }
    }

    curTitle = curTitle.trim()

    return curTitle
  }
  /**
   * 文章内容提取，参考了readability.js及浏览器插件IReader实现
   */
  var ArticleClipper = function (doc) {
    this.contentDocument = doc
    this.currentPageNumber = 1
    this.nextPageUrl = undefined
    this.parsedPages = {} // 缓存要查找的页面
    this.pageETags = {} // 解析过的其他页的ETag headers, 防止重复载入其他页面
    this.prepArticleHtml = []
    this.articleHtml = '' // 文章正文
    this.init()
  }
  ArticleClipper.prototype = {
    regexps: {
      commaRe: /[\uff0c,]/,
      periodRe: /[\u3002.]/, // 逗号
      unlikelyCandidatesRe: /oneKeyReprint|combx|comment|community|disqus|extra|foot|header|menu|remark|rss|shoutbox|sidebar|sponsor|ad-break|agegate|pagination|pager|popup|tweet|twitter/i,
      okMaybeItsACandidateRe: /and|article|body|column|main|shadow/i,
      positiveRe: /article|body|content|entry|hentry|main|page|pagination|post|text|blog|story|TRS_Editor/i,
      negativeRe: /^ad_|combx|comment|com-|contact|bottom|foot|footer|footnote|masthead|media|meta|outbrain|promo|related|scroll|shoutbox|sidebar|sponsor|shopping|tags|tool|widget/i,
      extraneousRe: /print|archive|comment|discuss|e[-]?mail|share|reply|all|login|sign|single/i,
      divToPElementsRe: /<(a|blockquote|dl|div|img|ol|p|pre|table|ul)/i,
      inlineElementsRe: /^(b|span|em|u|q|i|s|small|strong|font)$/i,
      hasBlockElementsRe: /<(dl|div|ol|p|pre|table|ul)/i,
      scriptTagRe: /<script[^>]*>[\S\s]*?<\/script[^>]*>/gi,
      styleTagRe: /<style[^>]*>[\S\s]*?<\/style[^>]*>/gi,
      replaceBrsRe: /(<br[^>]*>[ \n\r\t]*){2,}/gi,
      replaceFontsRe: /<(\/?)font[^>]*>/gi,
      // trimRe: /^\s+|\s+$/g,
      normalizeRe: /\s{2,}/g,
      killBreaksRe: /(<br\s*\/?>(\s|&nbsp;?)*){1,}/g,
      videoRe: /https?:\/\/(www\.)?(youtube|vimeo)\.com/i,
      nextLinkRe: /(下一页|next|weiter|continue|read\s+more|(>|&gt;|&#62;)([^|]|$)|(\u00bb|&raquo;|&#187;)([^|]|$))/i, // Match: next, continue, >, >>, » but not >|, »| as those usually mean last.
      prevLinkRe: /(上一页|prev|earl|old|new|<|&lt;|&#60;|\u00ab|&laquo;|&#171;)/i
    },

    init: function () {
      /* Make sure this document is added to the list of parsed pages first, so we don't double up on the first page */
      this.parsedPages[window.location.href.replace(/\/$/, '')] = true
      this.contentType = 'article'

      this.prepArticleHtml_video = this.grabVideo()
      this.prepArticleHtml = this.grabArticle()

      if (!this.prepArticleHtml.length || this.prepArticleHtml.join('').trim() === '') {
        this.articleHtml = this.prepArticleHtml_video || '<p>======== 文章正文区特征不明显，没有获取到文章内容 ========</p>'
      } else {
        if (this.topCandidate_video && this.topCandidate_video.clientHeight > this.topCandidate_article.clientHeight / 2) {
          this.articleHtml = this.prepArticleHtml_video
        } else {
          this.articleHtml = this.prepArticleHtml.join('')
        }
      }
      if (this.articleHtml !== this.prepArticleHtml_video) {
        this.nextPageUrl = this.findNextPageLink()
      }
    },
    grabVideo: function () {
      var objectNodes = this.contentDocument.getElementsByTagName('object')
      var embedNodes = this.contentDocument.getElementsByTagName('embed')
      var videoNodes = this.contentDocument.getElementsByTagName('video')
      var mediaElements = []
      for (var i = 0, l = objectNodes.length; i < l; i++) {
        mediaElements.push(objectNodes[i])
      }
      for (i = 0, l = embedNodes.length; i < l; i++) {
        mediaElements.push(embedNodes[i])
      }
      for (i = 0, l = videoNodes.length; i < l; i++) {
        mediaElements.push(videoNodes[i])
      }
      var candidates = []
      for (i = 0, l = mediaElements.length; i < l; i++) {
        var node = mediaElements[i]
        if (node.clientHeight > 300 && node.clientWidth > 400) {
          candidates.push([node, node.clientHeight * node.clientWidth])
        }
      }
      candidates.sort(function (a, b) {
        return b[1] - a[1]
      })
      var topCandidate = candidates[0]
      if (topCandidate) {
        this.topCandidate_video = topCandidate[0]
        return (
          '<div style="width:' +
          topCandidate[0].clientWidth +
          'px;height:' +
          topCandidate[0].clientHeight +
          'px;">' +
          topCandidate[0].outerHTML +
          '</div>'
        )
      }
      return ''
    },

    /**
     * 清除html中的iframes, forms, 剥除 <p> 标签外部多余的标签, etc.
     *
     * @param Element
     * @return void
     **/
    prepArticle: function (articleContent$htmlElem) {
      /* Clean out junk from the article content */
      this.clean(articleContent$htmlElem, 'h1')
      /**
       * If there is only one h2, they are probably using it
       * as a header and not a subheader, so remove it since we already have a header.
       ***/
      if (articleContent$htmlElem.getElementsByTagName('h2').length === 1) {
        this.clean(articleContent$htmlElem, 'h2')
      }
      this.clean(articleContent$htmlElem, 'textarea')
      this.clean(articleContent$htmlElem, 'iframe')
      this.clean(articleContent$htmlElem, 'script')

      /* 再次设置图片及链接的src，使不失效 */
      var links = articleContent$htmlElem.getElementsByTagName('a')
      var i, len
      for (i = 0, len = links.length; i < len; i++) {
        var a = links[i]
        var aHref = links[i].href
        if (aHref.indexOf('http') === 0 && a.hostname.indexOf(theHost) > -1) {
          // 如果链接不为外链，为了防止在ZCMS里发布的页面里的链接点击后
          // 跳回引用源页面，暴露引用来源，把这些链接取消掉
          var span = document.createElement('span')
          span.innerHTML = a.innerHTML
          a.innerHTML = ''
          a.parentNode.insertBefore(span, a)
        }
        a.setAttribute('href', aHref)
      }
      var images = articleContent$htmlElem.getElementsByTagName('img')
      for (i = 0, len = images.length; i < len; i++) {
        images[i].setAttribute('src', images[i].src)
      }

      hideLoading() // 当匹配到body时，“找到正文区”的提示也加进来了

      return articleContent$htmlElem
    },

    /**
     * 分析节点，估计节点为正文的可能性
     *
     * @param Element
     * @return void
     **/
    initializeNode: function (node) {
      node._contentScore = 0

      switch (node.tagName) {
        case 'DIV':
        case 'ARTICLE':
        case 'SECTION':
          node._contentScore += 5
          break

        case 'PRE':
        case 'TD':
        case 'BLOCKQUOTE':
          node._contentScore += 3
          break

        case 'ADDRESS':
        case 'OL':
        case 'UL':
        case 'DL':
        case 'DD':
        case 'DT':
        case 'LI':
        case 'FORM':
          node._contentScore -= 3
          break

        case 'H1':
        case 'H2':
        case 'H3':
        case 'H4':
        case 'H5':
        case 'H6':
        case 'TH':
          node._contentScore -= 5
          break
      }

      node._contentScore += this.getClassWeight(node)
    },

    /**
 只对大于一定尺寸的元素进行评分
*/
    getNodeToScoreBySize: function (node) {
      if (!isVisible(node)) {
        return false
      }
      if (node.offsetWidth < 300 || node.offsetHeight < 35) {
        /* 考虑子元素浮动时，页面元素高度为0 */
        var children = getChildrenElements(node)
        var cl = children.length
        if (cl) {
          if (
            (isVisible(children[0]) && children[0].offsetHeight > 35) ||
            (isVisible(children[cl - 1]) && children[cl - 1].offsetHeight > 35)
          ) {
            return true
          }
        }
        return false
      }
      return true
    },

    /**
     * 标记废弃的element
     */
    makeUnlikelyNode: function (node) {
      node._unlikely = true
      var nodes = node.getElementsByTagName('*')
      for (var i = 0, len = nodes.length; i < len; i++) {
        nodes[i]._unlikely = true
      }
    },
    /***
     * grabArticle - 使用各种指标（内容评分，类名，元素类型），找到是最有可能是正文的内容。然后把它包裹在一个div返回
     * @return Element
     **/
    grabArticle: function () {
      /**
       * 首先，准备节点。废弃看起来不cruddy的节点（如类名为“comment”的），并转换使用不当的div为P标签（如，不包含其他块级元素的p。）
       * TODO: Shouldn't this be a reverse traversal?
       **/
      var unlikelyTag = {
        HTML: 1,
        HEAD: 1,
        META: 1,
        TITLE: 1,
        SCRIPT: 1,
        STYLE: 1,
        LINK: 1,
        IMG: 1,
        FORM: 1,
        INPUT: 1,
        BUTTON: 1,
        TEXTAREA: 1,
        SELECT: 1,
        OPTION: 1,
        LABEL: 1,
        IFRAME: 1,
        UL: 1,
        OL: 1,
        LI: 1,
        DD: 1,
        DT: 1,
        A: 1,
        OBJECT: 1,
        PARAM: 1,
        EMBED: 1,
        NOSCRIPT: 1,
        EM: 1,
        B: 1,
        STRONG: 1,
        I: 1,
        INS: 1,
        BR: 1,
        HR: 1,
        PRE: 1,
        H1: 1,
        H2: 1,
        H3: 1,
        H4: 1,
        H5: 1,
        CITE: 1
      }
      var node
      var allElements = this.contentDocument.getElementsByTagName('*')
      var nodesToScore = [] // 要评分的节点
      var timeout = new Date().getTime() + 10000

      for (var nodeIndex = 0, len = allElements.length; nodeIndex < len; nodeIndex++) {
        node = allElements[nodeIndex]
        if (node._unlikely) {
          continue
        }
        /* 不可能是正文的节点  作 unlikely 标记
         */
        if (unlikelyTag[node.tagName]) {
          // 如果不为块元素
          node._unlikely = true
          continue
        }
        var unlikelyMatchString = node.className + node.id /* 如果id或class里有非正文特征 */
        if (
          unlikelyMatchString.search(this.regexps.unlikelyCandidatesRe) !== -1 &&
          unlikelyMatchString.search(this.regexps.okMaybeItsACandidateRe) === -1 &&
          node.tagName !== 'BODY'
        ) {
          this.makeUnlikelyNode(node)
          continue
        }
        if (!this.getNodeToScoreBySize(node) && node.tagName !== 'BODY') {
          // 如果尺寸小于300*75
          this.makeUnlikelyNode(node)
          continue
        }
        if (new Date().getTime() > timeout) {
          // 如果循环节点所花时间超过10秒则退出
          break
        }
        nodesToScore[nodesToScore.length] = node
      }
      // console.log(nodesToScore)
      /**
       * Loop through all paragraphs, and assign a score to them based on how content-y they look.
       * Then add their score to their parent node.
       *
       * A score is determined by things like number of commas, class names, etc. Maybe eventually link density.
       **/
      // var allParagraphs = this.contentDocument.getElementsByTagName("p");
      var candidates = []
      for (var j = 0; j < nodesToScore.length; j++) {
        var parentNode = nodesToScore[j].parentNode
        var grandParentNode = parentNode ? parentNode.parentNode : null
        var innerText = this.getInnerText(nodesToScore[j], true)

        if (!parentNode || typeof parentNode.tagName === 'undefined') {
          continue
        }

        /* If this paragraph is less than 25 characters, don't even count it. */
        if (innerText.length < 25 && nodesToScore[j].getElementsByTagName('IMG').length < 1) {
          continue
        }

        candidates.push(nodesToScore[j])
        if (typeof nodesToScore[j]._contentScore === 'undefined') {
          this.initializeNode(nodesToScore[j]) // 评分
        }
        /* Initialize ArticleClipper data for the parent. */
        if (typeof parentNode._contentScore === 'undefined') {
          this.initializeNode(parentNode) // 评分
          candidates.push(parentNode)
        }

        /* Initialize this data for the grandparent. */
        if (grandParentNode && grandParentNode.tagName && typeof grandParentNode._contentScore === 'undefined') {
          this.initializeNode(grandParentNode) // 评分
          candidates.push(grandParentNode)
        }

        var contentScore = 0

        /* 起始评分为1 */
        contentScore++

        /* 如果段落中有逗号则加分 */
        contentScore += innerText.split(this.regexps.commaRe).length * 2
        contentScore += innerText.split(this.regexps.periodRe).length

        /* For every 100 characters in this paragraph, add another point. Up to 3 points. */
        contentScore += Math.min(Math.floor(innerText.length / 100), 3)

        /* 如果文本节点多，是正文的可能性就大 */
        contentScore += this.getTextNodeCount(nodesToScore[j])

        /* 如果有大图片，是正文的可能性就大 */
        contentScore += this.getImgNodeCount(nodesToScore[j])

        nodesToScore[j]._contentScore += contentScore
        /* 添加评分到父节点和祖父节点 */
        if (this.regexps.inlineElementsRe.test(nodesToScore[j].tagName)) {
          parentNode._contentScore += contentScore
          if (grandParentNode) {
            grandParentNode._contentScore += contentScore / 2
          }
        } else {
          parentNode._contentScore += contentScore / 2
          if (grandParentNode) {
            grandParentNode._contentScore += contentScore / 4
          }
        }
      }
      /**
       * After we've calculated scores, loop through all of the possible candidate nodes we found
       * and find the one with the highest score.
       **/
      var topCandidate = null
      var i, il

      for (i = 0, il = candidates.length; i < il; i++) {
        /**
         * Scale the final candidates score based on link density. Good content should have a
         * relatively small link density (5% or less) and be mostly unaffected by this operation.
         **/

        candidates[i]._contentScore = candidates[i]._contentScore * (1 - this.getLinkDensity(candidates[i]))
        /* 2012年8月6日
  让末级节点的的评分更高，
  如果子级节点里有评分特别突出的，就降低节点的评分，使最高评分向这个突出的子节点倾斜
  *
  var children= getChildrenElements(candidates[i]);
  if(children.length){
    children.sort(function(a,b){
      return (b._contentScore||0) - (a._contentScore||0);
    });
    if(children[0]._contentScore>0){
      var child_candidate=1;
      var ni=1,  nl=children.length;
      for(;ni<nl;ni++){
        if(children[ni]._contentScore > children[0]._contentScore/3){
          child_candidate++;
        }else{
          break;
        }
      }
      console.log(candidates[i],children.length,child_candidate)
      candidates[i]._contentScore = candidates[i]._contentScore*child_candidate/nl;
    }
  }
  /* /2012年8月6日 让末级节点的的评分更高
  */

        // console.log('文章提取: ', 'Candidate: ' + candidates[i] + " (" + candidates[i].className + ":" + candidates[i].id + ") with score " + candidates[i]._contentScore);

        if (!topCandidate || candidates[i]._contentScore > topCandidate._contentScore) {
          topCandidate = candidates[i]
        }
      }
      if (!topCandidate || topCandidate._contentScore < 15) {
        return ''
      }
      this.topCandidate_article = topCandidate
      console.log('======== 最匹配正文区: ', topCandidate, ' 评分 ' + topCandidate._contentScore)
      showLoading('找到正文区')
      /**
       * 现在，我们有最佳候选了，看看它的兄弟节点的内容。如序言，被广告分隔开的内容等
       **/
      var prepArticleHtml = []
      this.articleLikely_NodeToScore = topCandidate
      var siblingScoreThreshold = Math.max(10, topCandidate._contentScore * 0.2) // 兄弟节点的评分如果为自己评分的1/5
      var siblingNodes = topCandidate.parentNode.childNodes
      for (i = 0, il = siblingNodes.length; i < il; i++) {
        var siblingNode = siblingNodes[i]
        var append = false

        if (siblingNode === topCandidate) {
          append = true
        } else {
          if (siblingNode.nodeType !== 1) {
            continue
          }
          if (unlikelyTag[siblingNode.tagName]) {
            continue
          }

          if (typeof siblingNode._contentScore === 'undefined') {
            this.initializeNode(siblingNode) // 评分
          }
          // console.log('文章提取: ', "Looking at sibling node: " + siblingNode + " (" + siblingNode.className + ":" + siblingNode.id + ")" + ((typeof siblingNode._contentScore !== 'undefined') ? (" with score " + siblingNode._contentScore) : ''));

          if (typeof siblingNode._contentScore !== 'undefined' && siblingNode._contentScore >= siblingScoreThreshold) {
            append = true
          }

          var contentBonus = 0 /* Give a bonus if sibling nodes and top candidates have the example same classname */
          if (siblingNode.className === topCandidate.className && topCandidate.className !== '') {
            contentBonus += topCandidate._contentScore * 0.2
          }
          if (typeof siblingNode._contentScore !== 'undefined' && siblingNode._contentScore + contentBonus >= siblingScoreThreshold) {
            append = true
          }

          /* 节点为p，或没有块元素内容 */
          if (siblingNode.nodeName === 'P' || siblingNode.innerHTML.search(this.regexps.hasBlockElementsRe) === -1) {
            var linkDensity = this.getLinkDensity(siblingNode)
            var nodeContent = this.getInnerText(siblingNode)
            var nodeLength = nodeContent.length

            if (nodeLength > 80 && linkDensity < 0.25) {
              append = true
            } else if (nodeLength < 80 && linkDensity === 0 && nodeContent.search(/[.\u3002]( |$)/) !== -1) {
              append = true
            }
          }
        }
        if (append) {
          this.articleLikely_NodeToScore = topCandidate.parentNode
          var nodeToAppend = siblingNode

          /* To ensure a node does not interfere with ArticleClipper styles, remove its classnames */
          // nodeToAppend.className = "";
          /* Append sibling and subtract from our list because it removes the node when you append to another node */
          var toAppendHtml = this.prepArticle(nodeToAppend).innerHTML // 注意这儿清掉了原域名的链接
          toAppendHtml = toAppendHtml.replace(this.regexps.styleTagRe, '')
          prepArticleHtml.push(toAppendHtml)
        }
      }
      return prepArticleHtml
    },

    /**
     * Removes script tags from the element.
     *
     * @param Element
     **/
    removeScripts: function (el) {
      var scripts = el.getElementsByTagName('script')
      // arrix
      scripts = [].slice.call(scripts)
      for (var i = scripts.length - 1; i >= 0; i--) {
        if (
          typeof scripts[i].src === 'undefined' ||
          (scripts[i].src.indexOf('onKeyReprint') === -1 && scripts[i].src.indexOf('typekit') === -1)
        ) {
          scripts[i].nodeValue = ''
          scripts[i].removeAttribute('src')
          if (scripts[i].parentNode) {
            scripts[i].parentNode.removeChild(scripts[i])
          }
        }
      }
    },

    getInnerText: function (e, mustHasTextNodeChild) {
      // 第二个参数为true时，如果没有直系的文本子节点则反回空
      var textContent = ''

      if (typeof e.textContent === 'undefined' && typeof e.innerText === 'undefined') {
        return ''
      }

      var hasTextNode = false
      for (var i = 0, il = e.childNodes.length; i < il; i++) {
        var childNode = e.childNodes[i]
        if (this.regexps.inlineElementsRe.test(childNode.tagName)) {
          childNode = childNode.childNodes[0]
        }
        if (childNode && childNode.nodeType === 3 && childNode.nodeValue.trim().length > 4) {
          // Node.TEXT_NODE 3
          hasTextNode = true
          break
        }
      }
      if (!hasTextNode && mustHasTextNodeChild) {
        return ''
      }

      if (navigator.appName === 'Microsoft Internet Explorer') {
        textContent = e.innerText.trim()
      } else {
        this.removeScripts(e)
        // 要去掉script标签，否则影响对链接密度的计算
        textContent = e.textContent.trim()
      }

      return textContent
    },

    getTextNodeCount: function (e) {
      var score = 0
      for (var i = 0, il = e.childNodes.length; i < il; i++) {
        var childNode = e.childNodes[i]
        if (childNode.nodeType === 3) {
          // Node.TEXT_NODE 3
          score++
        }
      }
      return score
    },

    getImgNodeCount: function (e) {
      var score = 0
      for (var i = 0, il = e.childNodes.length; i < il; i++) {
        var childNode = e.childNodes[i]
        if (childNode.nodeName === 'IMG') {
          // Node.TEXT_NODE 3
          score += Math.floor((childNode.clientHeight * childNode.clientHeight) / 10000)
        }
      }
      return score
    },

    /*
             获取链接密度
             */
    getLinkDensity: function (e) {
      var links = e.getElementsByTagName('a')
      var len = links.length

      var textLength = this.getInnerText(e).length
      var linkLength = 0
      for (var i = 0, il = len; i < il; i++) {
        linkLength += this.getInnerText(links[i]).length
      }
      if (linkLength === 0) {
        return 0
      }
      return linkLength / textLength
    },
    /*
            通过一个元素的id或class来估计其为正文的可能性
             */
    getClassWeight: function (e) {
      var weight = 0

      /* Look for a special classname */
      if (e.className !== '') {
        if (theSiteInfo.classNameRe && e.className.search(theSiteInfo.classNameRe) !== -1) {
          weight += 200
        }

        if (e.className.search(this.regexps.negativeReRe) !== -1) {
          weight -= 20
        }

        if (e.className.search(this.regexps.positiveReRe) !== -1) {
          weight += 20
        }
      }

      /* Look for a special ID */
      if (typeof e.id === 'string' && e.id !== '') {
        if (theSiteInfo.idRe && e.id.search(theSiteInfo.idRe) !== -1) {
          weight += 300
        }

        if (e.id.search(this.regexps.negativeReRe) !== -1) {
          weight -= 30
        }

        if (e.id.search(this.regexps.positiveReRe) !== -1) {
          weight += 30
        }
      }

      return weight
    },

    clean: function (e, tag) {
      var targetList = e.getElementsByTagName(tag)
      var isEmbed = tag === 'object' || tag === 'embed'

      for (var y = targetList.length - 1; y >= 0; y--) {
        /* Allow youtube and vimeo videos through as people usually want to see those. */
        if (isEmbed && targetList[y].innerHTML.search(this.regexps.videoRe) !== -1) {
          continue
        }

        targetList[y].parentNode.removeChild(targetList[y])
      }
    },
    // 找到当前页面的路径，用于和页面上的链接比较来找到“下一页”链接。
    findBaseUrl: function () {
      var noUrlParams = window.location.pathname.split('?')[0]

      var urlSlashes = noUrlParams.split('/').reverse()

      var cleanedSegments = []

      var possibleType = ''

      for (var i = 0, slashLen = urlSlashes.length; i < slashLen; i++) {
        var segment = urlSlashes[i]

        // Split off and save anything that looks like a file type.
        if (segment.indexOf('.') !== -1) {
          possibleType = segment.split('.')[1]

          /* If the type isn't alpha-only, it's probably not actually a file extension. */
          if (!possibleType.match(/[^a-zA-Z]/)) {
            segment = segment.split('.')[0]
          }
        }

        /**
         * EW-CMS specific segment replacement. Ugly.
         * Example: http://www.ew.com/ew/article/0,,20313460_20369436,00.html
         **/
        if (segment.indexOf(',00') !== -1) {
          segment = segment.replace(',00', '')
        }

        // If our first or second segment has anything looking like a page number, remove it.
        if (segment.match(/((_|-)?p[a-z]*|(_|-))[0-9]{1,2}$/i) && (i === 1 || i === 0)) {
          segment = segment.replace(/((_|-)?p[a-z]*|(_|-))[0-9]{1,2}$/i, '')
        }

        var del = false

        /* If this is purely a number, and it's the first or second segment, it's probably a page number. Remove it. */
        if (i < 2 && segment.match(/^\d{1,2}$/)) {
          del = true
        }

        /* If this is the first segment and it's just "index", remove it. */
        if (i === 0 && segment.toLowerCase() === 'index') {
          del = true
        }

        /* If our first or second segment is smaller than 3 characters, and the first segment was purely alphas, remove it. */
        if (i < 2 && segment.length < 3 && !urlSlashes[0].match(/[a-z]/i)) {
          del = true
        }

        /* If it's not marked for deletion, push it to cleanedSegments. */
        if (!del) {
          cleanedSegments.push(segment)
        }
      }

      // This is our final, cleaned, base article URL.
      return window.location.protocol + '//' + window.location.host + cleanedSegments.reverse().join('/')
    },
    // 在页面中查找可能的分页链接
    findNextPageLink: function (elem) {
      // 如果没有找到正文区，当然也不用找下一页了
      if (!this.articleLikely_NodeToScore) {
        return null
      }
      if (this.nextPageUrl !== undefined) {
        return this.nextPageUrl
      }
      if (!elem) {
        // 有时候下一页的链接不在正文区，所以要扩大查找下一页链接的范围
        elem = this.articleLikely_NodeToScore
        for (var pNode = elem, b = getDimension(elem).bottom + 250; pNode.nodeType === 1 && getDimension(pNode).bottom <= b;) {
          pNode = pNode.parentNode
        }
        if (pNode.nodeType === 1 && pNode !== elem) {
          elem = pNode
        }
      }
      var possiblePages = {}

      var allLinks = elem.getElementsByTagName('a')

      var articleBaseUrl = this.findBaseUrl()
      /**
  循环通过所有的链接，寻找可能是下一页链接的特征。
  如内容/className/id 中有“page”或“页”，或id或className为page-y的子节点。
  当然：“下一页”链接有时候只是评论的“下一页”

  然后对找到的链接评分并比较
**/
      var topCandidateDim = getDimension(this.articleLikely_NodeToScore)

      for (var i = 0, il = allLinks.length; i < il; i++) {
        var link = allLinks[i]

        var linkHref = allLinks[i].href.replace(/#.*$/, '').replace(/\/$/, '')

        /* If we've already seen this page, ignore it */
        if (linkHref === '' || linkHref === articleBaseUrl || linkHref === window.location.href || linkHref in this.parsedPages) {
          continue
        }

        /* If it's on a different domain, skip it. */
        if (window.location.host !== linkHref.split(/\/+/g)[1]) {
          continue
        }

        var linkText = this.getInnerText(link)

        /* If the linkText looks like it's not the next page, skip it. */
        if (linkText.match(this.regexps.extraneousRe) || linkText.length > 25) {
          continue
        }

        /* If the leftovers of the URL after removing the base URL don't contain any digits, it's certainly not a next page link. */
        var linkHrefLeftover = linkHref.replace(articleBaseUrl, '')
        if (!linkHrefLeftover.match(/\d/)) {
          continue
        }
        // 如果链接不可见
        if (!isVisible(link)) {
          continue
        }

        var linkDim = getDimension(link)
        // 如果小到不可点击或大到像一块内容
        if (linkDim.width < 8 || linkDim.height > 100) {
          continue
        }
        // 如果链接离正文区比较远
        if (topCandidateDim.top - linkDim.top + linkDim.height > 125 || linkDim.top - topCandidateDim.top - topCandidateDim.height > 125) {
          continue
        }
        if (topCandidateDim.left - linkDim.left + linkDim.width > 20 || linkDim.left - topCandidateDim.left - topCandidateDim.width > 20) {
          continue
        }

        if (!(linkHref in possiblePages)) {
          possiblePages[linkHref] = { score: 0, elem: link, linkText: linkText, href: linkHref }
        } else {
          possiblePages[linkHref].linkText += ' | ' + linkText
        }

        var linkObj = possiblePages[linkHref]

        /**
         * 如果当前页面文件夹路径不是链接url的一部分, 为“下一页”的可能性降低，降分
         * Example: http://www.actionscript.org/resources/articles/745/1/JavaScript-and-VBScript-Injection-in-ActionScript-3/Page1.html
         **/
        if (linkHref.indexOf(articleBaseUrl) !== 0) {
          linkObj.score -= 25
        }

        var linkData = linkText + ' ' + link.className + ' ' + link.id
        if (linkData.match(this.regexps.nextLinkRe)) {
          linkObj.score += 50
        }
        if (linkData.match(/pag(e|ing|inat)/i)) {
          linkObj.score += 25
        }
        if (linkData.match(/(首页|first|last|尾页|末页)/i)) {
          // -65 is enough to negate any bonuses gotten from a > or Â» in the text,
          /* If we already matched on "next", last is probably fine. If we didn't, then it's bad. Penalize. */
          if (!linkObj.linkText.match(this.regexps.nextLinkRe)) {
            linkObj.score -= 65
          }
        }
        if (linkData.match(this.regexps.negativeRe) || linkData.match(this.regexps.extraneousRe)) {
          linkObj.score -= 50
        }
        if (linkData.match(this.regexps.prevLinkRe)) {
          linkObj.score -= 200
        }

        /* If a parentNode contains page or paging or paginat */
        var parentNode = link.parentNode

        var positiveNodeMatch = false

        var negativeNodeMatch = false
        while (parentNode) {
          var parentNodeClassAndId = parentNode.className + ' ' + parentNode.id
          if (!positiveNodeMatch && parentNodeClassAndId && parentNodeClassAndId.match(/pag(e|ing|inat)/i)) {
            positiveNodeMatch = true
            linkObj.score += 25
          }
          if (!negativeNodeMatch && parentNodeClassAndId && parentNodeClassAndId.match(this.regexps.negativeRe)) {
            /* If this is just something like "footer", give it a negative. If it's something like "body-and-footer", leave it be. */
            if (!parentNodeClassAndId.match(this.regexps.positiveRe)) {
              linkObj.score -= 25
              negativeNodeMatch = true
            }
          }

          parentNode = parentNode.parentNode
        }

        /**
         * 如果网址路径有分页特征，加分
         * 如 /page/2/, /pagenum/2, ?p=3, ?page=11, ?pagination=34
         **/
        if (linkHref.match(/p(a|g|ag)?(e|ing|ination)?(=|\/)[0-9]{1,2}/i) || linkHref.match(/(page|paging)/i)) {
          linkObj.score += 25
        }

        /* If the URL contains negative values, give a slight decrease. */
        if (linkHref.match(this.regexps.extraneousRe)) {
          linkObj.score -= 15
        }

        /**
         * Minor punishment to anything that doesn't match our current URL.
         * NOTE: I'm finding this to cause more harm than good where something is exactly 50 points.
         *       Dan, can you show me a counterexample where this is necessary?
         * if (linkHref.indexOf(window.location.href) !== 0) {
         *    linkObj.score -= 1;
         * }
         **/

        /**
         * 如果页面没有“下一页”链接，只有页码编号，所以如果链接文本内容为数字，并且编号较低，也要加一点分，
         **/
        var linkTextAsNumber = parseInt(linkText, 10)
        if (linkTextAsNumber) {
          // Punish 1 since we're either already there, or it's probably before what we want anyways.
          if (linkTextAsNumber === 1) {
            linkObj.score -= 10
          } else {
            // Todo: Describe this better
            linkObj.score += Math.max(0, 10 - linkTextAsNumber)
          }
        }
      }

      /**
       * 对页面内所有链接打分后找到“下一页”链接，评分至少需要50分。
       **/
      var topPage = null
      for (var page in possiblePages) {
        if (possiblePages.hasOwnProperty(page)) {
          if (possiblePages[page].score >= 50 && (!topPage || topPage.score < possiblePages[page].score)) {
            topPage = possiblePages[page]
          }
        }
      }

      if (topPage) {
        var nextHref = topPage.href.replace(/\/$/, '')
        showLoading('发现分页链接')
        console.log('==== 最匹配下一页链接: ', topPage.elem, '评分: ' + topPage.score)
        this.parsedPages[nextHref] = true
        this.nextPageUrl = nextHref
        return nextHref
      } else {
        return null
      }
    }
  } // end ArticleClipper

  /** 界面实现 */

  var E = {
    on: function (el, eType, fn) {
      el.addEventListener
        ? el.addEventListener(eType, fn, false)
        : el.attachEvent
          ? el.attachEvent('on' + eType, fn)
          : (el['on' + eType] = fn)
    },
    off: function (el, eType, fn, useCapture) {
      if (useCapture === undefined) {
        useCapture = false
      }
      el.removeEventListener
        ? el.removeEventListener(eType, fn, useCapture)
        : el.detachEvent
          ? el.detachEvent('on' + eType, fn)
          : (el['on' + eType] = null)
    },
    evt: function (e) {
      return e || window.event
    }
  }

  var $id = function (id) {
    var el = typeof id === 'string' ? document.getElementById(id.replace(/^#/, '')) : id
    if (el && el.nodeName) {
      if (!(this instanceof $id)) {
        return new $id(el)
      }
      this.dom = el
    } else {
      return null
    }
  }
  $id.prototype.show = function () {
    this.dom.style.display = ''
  }
  $id.prototype.hide = function () {
    this.dom.style.display = 'none'
  }
  $id.prototype.remove = function () {
    this.dom.parentNode.removeChild(this.dom)
    this.dom = null
  }
  $id.prototype.on = function (evnt, func) {
    E.on(this.dom, evnt, func)
  }
  $id.prototype.off = function (evnt, func, useCapture) {
    E.off(this.dom, evnt, func, useCapture)
  }

  /**
   * 基本拖拽
   * new Dragdrop({
   *      target   拖拽元素 HTMLElemnt 必选
   *      handle   指定鼠标按下哪个元素时开始拖拽，实现模态对话框时用到
   *      dragable 是否可拖拽  (true)默认
   *      dragX    true/false false水平方向不可拖拽 (true)默认
   *      dragY    true/false false垂直方向不可拖拽 (true)默认
   *      area     [minX,maxX,minY,maxY] 指定拖拽范围 默认任意拖动
   *      onMove 移动过程中的回调函数
   * });
   */

  var dragConf = null

  var defaultDragConf
  var diffX
  var diffY

  function DragConfig (opt) {
    this.target = opt.target
    this.handle = opt.handle
    this.dragable = opt.dragable !== false
    this.dragX = opt.dragX !== false
    this.dragY = opt.dragY !== false
    this.area = opt.area
    this.onMove = opt.onMove
  }

  function Dragdrop (opt) {
    if (!opt) {
      return
    }
    dragConf = new DragConfig(opt)
    defaultDragConf = new DragConfig(opt)
    if (!dragConf.handle) {
      dragConf.handle = dragConf.target
    }
    E.on(dragConf.handle, 'mousedown', Dragdrop.mousedown)
  }
  Dragdrop.prototype = {
    dragX: function () {
      dragConf.dragX = true
      dragConf.dragY = false
    },
    dragY: function (b) {
      dragConf.dragY = true
      dragConf.dragX = false
    },
    dragAll: function () {
      dragConf.dragX = true
      dragConf.dragY = true
    },
    setArea: function (a) {
      dragConf.area = a
    },
    setBridge: function (b) {
      dragConf.handle = b
    },
    setDragable: function (b) {
      dragConf.dragable = b
    },
    reStore: function () {
      dragConf = new DragConfig(defaultDragConf)
      dragConf.target.style.top = '0px'
      dragConf.target.style.left = '0px'
    },
    getDragX: function () {
      return dragConf.dragX
    },
    getDragY: function () {
      return dragConf.dragY
    }
  }

  Dragdrop.mousedown = function (e) {
    e = E.evt(e)
    var el = dragConf.target
    var handleEl = dragConf.handle
    if (getStyle(el).position === 'static') {
      el.style.position = 'absolute'
    }
    el.style.cursor = 'move'
    diffX = e.clientX - el.offsetLeft
    diffY = e.clientY - el.offsetTop
    E.on(document, 'mousemove', Dragdrop.mousemove)
    E.on(document, 'mouseup', Dragdrop.mouseup)
    if (handleEl.setCapture) {
      // IE
      E.on(handleEl, 'losecapture', Dragdrop.mouseup)
      handleEl.setCapture()
      e.cancelBubble = true
    } else if (e.preventDefault) {
      // 标准DOM
      E.on(window, 'blur', Dragdrop.mouseup)
      e.preventDefault()
    }
    if (dragConf.onStart) {
      dragConf.onStart(e)
    }
  }

  Dragdrop.mousemove = function (e) {
    // 清除选择
    window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty()
    var el = dragConf.target

    e = E.evt(e)

    var moveX = e.clientX - diffX

    var moveY = e.clientY - diffY
    var minX, maxX, minY, maxY
    if (dragConf.area) {
      minX = dragConf.area[0]
      maxX = dragConf.area[1]
      minY = dragConf.area[2]
      maxY = dragConf.area[3]
      moveX < minX && (moveX = minX) // left 最小值
      moveX > maxX && (moveX = maxX) // left 最大值
      moveY < minY && (moveY = minY) // top 最小值
      moveY > maxY && (moveY = maxY) // top 最大值
    }
    if (dragConf.dragable) {
      dragConf.dragX && (el.style.left = moveX + 'px')
      dragConf.dragY && (el.style.top = moveY + 'px')
      if (dragConf.onMove) {
        var obj = {
          moveX: moveX,
          moveY: moveY
        }
        dragConf.onMove(e, obj)
      }
    }
  }

  Dragdrop.mouseup = function (e) {
    var el = dragConf.target
    var handleEl = dragConf.handle
    el.style.cursor = 'default'
    E.off(document, 'mousemove', Dragdrop.mousemove)
    E.off(document, 'mouseup', Dragdrop.mouseup)
    if (handleEl.releaseCapture) {
      // IE
      E.off(handleEl, 'losecapture', Dragdrop.mouseup)
      handleEl.releaseCapture()
    } else if (e.preventDefault) {
      // 标准DOM
      E.off(window, 'blur', Dragdrop.mouseup)
    }
    if (dragConf.onStop) {
      dragConf.onStop(e)
    }
  }

  var loadingBox = function () {
    if ($id('rdb-ext-LoadingBox')) {
      return $id('rdb-ext-LoadingBox')
    }
    var d = document.createElement('div')

    var cssPosition = isQuirks ? 'absolute' : 'fixed'
    d.id = 'rdb-ext-LoadingBox'
    d.style.cssText = [
      'display: block;',
      'left: 50%;',
      'top: 20%;',
      'height: 80px;',
      'min-width: 200px;',
      'max-width: 400px;',
      'margin-left: -100px;',
      'padding: 22px 0 0;',
      'position: ' + cssPosition + ';',
      'z-index: 10100;',
      'color: #FFFFFF;',
      'background-color: #444;',
      '-moz-border-radius: 10px;',
      '-webkit-border-radius: 10px;',
      'border-radius: 10px;',
      'border-width: 1px 0 0 1px;',
      'border-style: solid;',
      'border-color: #222;',
      'filter: alpha(opacity=85);',
      '-moz-opacity: .85;',
      'opacity: .85;',
      'text-align: center;'
    ].join('')
    d.innerHTML = [
      '<div id="rdb-ext-LoadingText" style="display:block; margin-left:0; padding-top: 10px; font: bold 18px Georgia; text-align: center;">',
      '<span id="rdb-ext-LoadingInnerText" style="color: #FFFFFF;">Saving</span>',
      '<span id="rdb-ext-ellipses-loader" style="color: #FFFFFF; display: inline-block; width: 22px; text-align: left;">.</span>',
      '</div>'
    ].join('')
    document.body.appendChild(d)
    return $id(d)
  }

  var showLoading = function (text, loading) {
    loadingBox()

    var loadDiv = $id('rdb-ext-LoadingInnerText')

    var ellipse = document.getElementById('rdb-ext-ellipses-loader')
    if (text) {
      loadDiv.dom.innerHTML = text
    }
    if (loading) {
      window.setInterval(function () {
        ellipse.innerHTML = ellipse.innerHTML.length < 3 ? ellipse.innerHTML + '.' : ''
      }, 500)
    } else {
      ellipse.innerHTML = '.'
    }
  }

  var hideLoading = function () {
    var loadBox = $id('rdb-ext-LoadingBox')
    if (loadBox) {
      loadBox.remove()
    }
  }

  var maxPages = 20 // 载入的最大分页数
  var pagesCounter = 1 // 当前页
  var hideFrame
  var otherPagesUrl$List = []
  var ka
  var getHideFrame = function () {
    if (!hideFrame) {
      hideFrame = document.createElement('iframe')
      hideFrame.style.cssText =
        'position:absolute;left:-100%;top:-100%;width:100%;height:100%;border:none;z-index:99;margin:0;padding:0;background-color:rgba(0, 0, 0, 0.0);opacity:0;-webkit-transition: opacity 0.4s'
      document.body.appendChild(hideFrame)
      if ('onreadystatechange' in document && 'onreadystatechange' in hideFrame) {
        hideFrame.attachEvent('onreadystatechange', function () {
          //  在ie下可以给iframe绑定onreadystatechange事件
          if (/loaded|complete/.test(hideFrame.readyState)) {
            clipper$getNextPageByFrame()
          }
        })
      } else {
        hideFrame.onload = function () {
          clipper$getNextPageByFrame()
        }
      }
    }
    return hideFrame
  }

  var getNextPage = function (url) {
    // 载入下一页
    if (!url || otherPagesUrl$List.indexOf(url) !== -1 || pagesCounter + 1 >= maxPages) {
      clearTimeout(ka)
      console.log('没有下一页的地址，开始提交表单')
      // submitForm(savePostUrl, true);
      submitByPostMessage()
      return false
    } else {
      otherPagesUrl$List.push(url)
      ka = setTimeout(function () {
        getHideFrame().src = url
        showLoading('载入分页中', true)
      }, 250)
    }
  }
  var submitByPostMessage = function () {
    if (!postDialog) {
      postDialog = new SimpleDialog(savePostUrl)
      postDialog.onLoad = function () {
        hideLoading()
        postData()
      }
      postDialog.show()
      postFrame = postDialog.innerFrame
    } else {
      // postFrame.src = savePostUrl;
      postDialog.show()
      postData()
    }
    window.addEventListener('message', function (ev) {
      if (savePostUrl.indexOf(ev.origin) !== -1) {
        var data = ev.data
        if (typeof data.action === 'string') {
          if (data.action === 'hideDialog') {
            postDialog.hide()
          } else if (data.action === 'removeDialog') {
            $id(postFrameId + '_wrap').remove()
            postDialog = null
          }
        }
      }
    })
    function postData () {
      var formInputs = {}
      formInputs.title = getArticleTitle()
      // formInputs.content = pages$prepArticle$html.join('<!--_ZVING_PAGE_BREAK_-->');
      formInputs.content = pages$prepArticle$html.join('<!--_PAGE_BREAK_-->')
      formInputs.url = theHostName
      postFrame.contentWindow.postMessage(formInputs, savePostUrl)
    }
  }

  var clipper$getNextPageByFrame = function () {
    var f = getHideFrame()
    ++pagesCounter
    if (f.src && f.contentDocument) {
      if (
        /404 Not Found|Apache .* - Error report|无法访问/.test(f.contentDocument.title) ||
        f.contentDocument.body.innerHTML.length < 200
      ) {
        //  当获取下一页内容失败时，不再继续
        getNextPage()
        return
      }
      var clipper = new ArticleClipper(f.contentDocument)
      clipper.currentPageNumber = pagesCounter
      if (clipper.articleLikely_NodeToScore) {
        var html = clipper.articleHtml
        pages$prepArticle$html.push(html)
        updateContent$byPrepArticle$HtmlElem()
      }
      // f.removeAttribute("src");
      getNextPage(clipper.nextPageUrl)
    } else if (otherPagesUrl$List.length) {
      // f.removeAttribute("src"); 移掉src在ie下会触发onreadystatechange
      var u = otherPagesUrl$List.pop()
      getNextPage(u)
    }
  }

  // 根据iframe里生成的其他页的正文HTMLElement更新当前页正文内容记录
  var updateContent$byPrepArticle$HtmlElem = function () {
    if (document.getElementById('content')) {
      document.getElementById('content').value = escape(pages$prepArticle$html.join('<!-- page split -->'))
    }
  }

  var loadOtherPages = function (articleClipper) {
    if (pagesCounter === 1) {
      otherPagesUrl$List = []
      getNextPage(articleClipper.nextPageUrl)
    } else {
      // 因为loadOtherPages只调用了一次，一般情况下不会走下面逻辑
      for (var b = 2; b <= pagesCounter; b++) {
        var article = pages$prepArticle$html[b]
        article && updateContent$byPrepArticle$HtmlElem()
      }
      if (otherPagesUrl$List.length - 1 > pagesCounter) {
        var url = otherPagesUrl$List.pop()
        getNextPage(url)
      } else {
        // submitForm(savePostUrl, true);// 分页都载入完成，则提交
        submitByPostMessage()
      }
    }
  }

  var readUrl = document.URL
  var init = function () {
    if (articlePreviouslyValidated && postDialog) {
      postDialog.show()
      return true
    }
    if (!/^https?:\/\/([^/]*)/.test(readUrl)) {
      return false
    }
    // console.log('readUrl',readUrl,'baseUrl',baseUrl)
    if (readUrl.indexOf(baseUrl) === 0 && readUrl.indexOf('http://develophost') !== 0) {
      return false // 不在应用域名下转载文章
    }

    if (!document.body) {
      return window.alert('页面还没有载入完成或页面结构不正常!')
    }
    showLoading('页面分析', true)
    var articleClipper = new ArticleClipper(document)
    pages$prepArticle$html.push(articleClipper.articleHtml)
    loadOtherPages(articleClipper)
  }

  var SimpleDialog = function (url) {
    this.width = 751
    this.height = 550
    this.url = url || 'about:blank'
    this.onLoad = function () {}
    var me = this
    this.show = function () {
      var boxdiv = document.getElementById(postFrameId + '_wrap')
      if (!boxdiv) {
        var arr = []
        arr.push(
          '<div id="_oneKeyReprintIframeDiv" style="background-color:#F6F6F6; border:1px solid #468; border-bottom-width:1px; padding:0; margin-top:0px;box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);">'
        )
        arr.push(
          '<div id="_oneKeyReprintIframeDiv_header" style="font-family:simsun;height:24px;background:#def;filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=\'#edf5f8\', endColorstr=\'#dae1e5\');background: -moz-linear-gradient(top, #edf5f8, #dae1e5);background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#edf5f8), to(#dae1e5));background:#def linear-gradient(top, #edf5f8, #dae1e5);">'
        )
        arr.push('<b style="float:left; line-height:20px;margin:3px 0 0 6px;">一键转载</b>')
        arr.push(
          '<a target="_self" style="font-size:18px; font-weight: bold; float:right; line-height:20px; text-decoration:none; margin:3px 3px 0 0; " href="javascript:void(0);" id="' +
            postFrameId +
            '_hideBtn">×</a>'
        )
        arr.push(
          '<a target="_self" style="font-size:18px; font-weight: bold; float:right; line-height:20px; text-decoration:none; margin:3px 3px 0 0; " href="javascript:void(0);" id="' +
            postFrameId +
            '_minBtn">-</a>'
        )
        arr.push('<span style="float:right" id="_oneKeyReprintIframeDiv_CloseTip"></span></div>')
        arr.push('<iframe src="' + me.url + '"')
        arr.push(
          ' id="' +
            postFrameId +
            '" name="' +
            postFrameId +
            '" allowTransparency="true"  width="' +
            (me.width - 2) +
            '" frameborder="0" style="height:' +
            (me.height - 25) +
            'px;background-color: #f7f7f7; border-top:1px solid #e0e9f1;border-color:#a8bdcf;">'
        )
        arr.push('</iframe>')
        arr.push('</div>')
        boxdiv = document.createElement('div')
        boxdiv.id = postFrameId + '_wrap'
        boxdiv.style.cssText =
          'position:' +
          (isQuirks ? 'absolute' : 'fixed') +
          '; left:50px; top:30px; width:' +
          me.width +
          'px; height:' +
          me.height +
          'px; margin:0; z-index:20100;'
        boxdiv.innerHTML = arr.join('\n')
        document.body.appendChild(boxdiv)
        $id(postFrameId + '_hideBtn').on('mousedown', function () {
          me.hide()
        })
        var minBtn = $id(postFrameId + '_minBtn')
        minBtn.on('click', function () {
          if (minBtn.dom.innerHTML === '-') {
            me.min()
          } else {
            me.normal()
          }
        })
        me.innerFrame = $id(postFrameId).dom
        $id(postFrameId).on('load', function () {
          me.onLoad()
        })
        /* me.innerFrame.onload = function() {
            me.onLoad();
          }; */

        boxdiv.style.left = (document.body.clientWidth - boxdiv.offsetWidth) / 2 + 'px'

        this.dragObj = new Dragdrop({
          target: boxdiv,
          handle: $id('_oneKeyReprintIframeDiv_header').dom
        })
      }
      boxdiv.style.display = 'block'
    }
    this.hide = function () {
      $id(postFrameId + '_wrap').hide()
    }
    this.min = function () {
      $id(postFrameId).hide()
      $id(postFrameId + '_minBtn').dom.innerHTML = '□'
    }
    this.normal = function () {
      $id(postFrameId).show()
      $id(postFrameId + '_minBtn').dom.innerHTML = '-'
    }
  }

  window.ArticleClipper = ArticleClipper
  window.oneKeyReprint = init
  if (document.body) {
    // 如果页面已经载入
    window.oneKeyReprint()
  }
})()
