escapeRegEx = /[.*+?^${}()|[\]\\]/g
pholderRegEx = pholderRegExSplit = null

setPholderRegEx = ()->
	start = settings.placeholder[0].replace(escapeRegEx, '\\$&')
	end = settings.placeholder[1].replace(escapeRegEx, '\\$&')
	middle = "[^#{end}]+"
	pholderRegEx = new RegExp("#{start}(#{middle})#{end}", 'g')
	pholderRegExSplit = new RegExp("#{start}#{middle}#{end}", 'g')
	return

setPholderRegEx() # Create the regEx on init



applyPlaceholders = (contexts, values, indexMap)->
	output = ''
	for contextPart,index in contexts
		output += contextPart
		output += values[indexMap[index]] if indexMap[index]
	
	return output


# simplyimport:if BUNDLE_TARGET = 'browser'
textContent = 'textContent'

addToNodeStore = (nodeStore, node, targetPlaceholder)->
	nodeStore[targetPlaceholder] ?= []
	nodeStore[targetPlaceholder].push(node)
	return


scanTextNodesPlaceholders = (element, nodeStore)->
	childNodes = Array::slice.call(element.childNodes)
	for node in childNodes
		if node.nodeType isnt 3 
			scanTextNodesPlaceholders(node, nodeStore)
		
		else if node[textContent].match(pholderRegExSplit)
			textPieces = node[textContent].split(pholderRegEx)

			if textPieces.length is 3 and textPieces[0]+textPieces[2] is '' # The entire textNode is just the placeholder
				addToNodeStore(nodeStore, node, textPieces[1])
			else
				newFragment = document.createDocumentFragment()

				for textPiece,index in textPieces
					newNode = newFragment.appendChild document.createTextNode(textPiece)
					if index % 2 # is an odd index, indicating that before this text piece should come a placeholder node
						addToNodeStore(nodeStore, newNode, textPiece)

				node.parentNode.replaceChild(newFragment, node)

	return
# simplyimport:end



