     length = 0
     for childNode in node.childNodes
       length += lengthOfNode(childNode)
+    return length
+
+lengthOfNodeToOffset = (node, offset) ->
+  if node.nodeType == Node.TEXT_NODE
+    return offset
+  else if node.tagName == "BR"
+    # Hope this never happens
+    console.log("Is this correct behavior?")
+    return offset
+  else if (node.tagName == "SPAN") || (node.tagName == "DIV")
+    length = 0
+    for i in [0...offset] by 1
+      length += lengthOfNode(node.childNodes[i])
     return length
 
 nodeAndOffsetFromCursorLocation = (location, node) ->

        newNode = createNode(remainder, @htmlfier, @descriptor.slice(0), null)
        @subnodes.push(newNode)
    node.processed = true

  return node

htmlfy = (dataText) ->

  formattedText = formattedText.replace(/&nbsp;/g, ' ')           # &nbsp; -> ' '
  return formattedText

# Common ancestor of two nodes, algorithm from
# http://stackoverflow.com/questions/3960843/how-to-find-the-nearest-common-ancestors-of-two-or-more-nodes
parentsOfNode = (node) ->
  nodes = [node]
  while node = node.parentNode
    nodes.unshift(node)
  return nodes

commonAncestorOfTwoNodes = (node1, node2) ->
  parents1 = parentsOfNode(node1)
  parents2 = parentsOfNode(node2)
  return null if parents1[0] != parents2[0]
  for i in [0...parents1.length] by 1
    if parents1[i] != parents2[i]
      return parents1[i - 1]

cursorLocationForRootNodeFromAnchorNodeAndOffset = (rootNode, anchorNode, anchorOffset, currentNode) ->
  if !currentNode
    currentNode = rootNode
  if currentNode == anchorNode
    return lengthOfNodeToOffset(anchorNode, anchorOffset)
  else if !currentNode.contains(anchorNode) && rootNode.contains(commonAncestorOfTwoNodes(currentNode, anchorNode)) && (currentNode.compareDocumentPosition(anchorNode) == Node.DOCUMENT_POSITION_FOLLOWING) # if currentNode is before anchorNode
    return lengthOfNode(currentNode)
  else if !currentNode.contains(anchorNode) && rootNode.contains(commonAncestorOfTwoNodes(currentNode, anchorNode)) && (currentNode.compareDocumentPosition(anchorNode) == Node.DOCUMENT_POSITION_PRECEDING) # If rootNode is after anchor node, not make sence
    return 0
  else if currentNode.contains(anchorNode)
    location = 0
    for childNode in currentNode.childNodes
      location += cursorLocationForRootNodeFromAnchorNodeAndOffset(rootNode, anchorNode, anchorOffset, childNode)
    return location

lengthOfNode = (node) ->
  if node.nodeType == Node.TEXT_NODE
