'use strict';
(function(ereeder) {
  ereeder.render = function(contentFiles) {
    var htmlsToVisit = [];
    for (var i = contentFiles.length - 1; i > -1; --i) {
      htmlsToVisit.push(contentFiles[i]);
    }
    var container = document.getElementById('container');
    var textLengthCounter = 0;

    function onHtmlRenderCompleted() {
      if (htmlsToVisit.length) {
        renderHtml(htmlsToVisit.pop());
      } else {
        ereeder.onRenderCompleted();
      }
    }

    onHtmlRenderCompleted();

    function renderHtml(contentFile) {
      function initContainer() {
        container.innerHTML = '';
        var headChildNodes = contentFile.head.childNodes;
        for (var i = 0; i < headChildNodes.length; ++i) {
          container.appendChild(headChildNodes[i].cloneNode(true));
        }
      }

      function insertNode() {
        previousNode = currentNode;
        currentNode = nodeToVisit.pop();
        container.appendChild(currentNode.cloneNode(true));
      }

      function save() {
        ereeder.pages.push({
          content: container.cloneNode(true),
          position: textLengthCounter
        });
        textLengthCounter += container.innerText.length;
        initContainer();
        if (nodeToVisit.length) {
          insertNode();
          setTimeout(testPage, 16);
        } else {
          onHtmlRenderCompleted();
        }
      }

      var currentNode = contentFile.body;
      var previousNode;
      var nodeToVisit = [];
      initContainer();
      container.appendChild(currentNode.cloneNode(true));
      setTimeout(testPage, 16);

      function testPage() {
        if (window.parent.document.getElementById('container').clientHeight > container.clientHeight + 16) {
          if (currentNode.nextSibling === nodeToVisit[nodeToVisit.length - 1]) {
            insertNode();
            testPage();
          } else {
            save();
          }
        } else {
          container.removeChild(container.lastChild);
          if (previousNode === currentNode.previousSibling) {
            nodeToVisit.push(currentNode);
            save();
          } else {
            var children = currentNode.childNodes;
            if (children) {
              for (var i = children.length - 1; i > -1; --i) {
                nodeToVisit.push(children[i]);
              }
              insertNode();
              testPage();
            } else {
              container.appendChild(currentNode.cloneNode(true));
              save();
            }
          }
        }
      }
    }
  };
  window.parent.ereeder.onContainerReady();
}(window.ereeder = window.ereeder || {}));
