/*
find_highlight.js
Funciones para resaltar o dejar de resaltar palabras de la busqueda
*/


/* Lee desde las cookies las keywords y llama a la funcion que resalta las keywords en el texto */

function TextHighlight(nodeId) {
	var sKeywords = getCookie("search_keywords");
	var sHigligthAction = getCookie("_search_highlight_action");

	/* Nada que resaltar */ 
	if(sHigligthAction != 'highlight' || sKeywords == null || sKeywords.length < 1) {
		return;
	}
	
	/* Obtener de las cookies palabras a resaltar */
	var arrWord = sKeywords.split(' ');
	var arrColor = new Array("#eBfF4F","#dBfF3F","#dAfE3E","#d5f939","#c5e929","#b5d919" );
  for (w=0;w<arrWord.length;w++) {
		var node = document.getElementById(nodeId);
		/* Ignoramos palabras muy cortas */
		if(node != null && arrWord[w].length > 2) {
	    highlightWord(node,arrWord[w], arrColor[w % arrColor.length]);
		}
  }
}

/* Toma un nodo DOM, una palabra y un código de color, para resaltar la palabra */
function highlightWord(node,word,color) {
  // Iterate into this nodes childNodes
  if (node.hasChildNodes) {
    var hi_cn;
    for (hi_cn=0;hi_cn<node.childNodes.length;hi_cn++) {
      highlightWord(node.childNodes[hi_cn],word,color);
    }
  }

  // And do this node itself
  if (node.nodeType == 3) { // text node
    tempNodeVal = node.nodeValue.toLowerCase();
    tempWordVal = word.toLowerCase();
    if (tempNodeVal.indexOf(tempWordVal) != -1) {
      pn = node.parentNode;
      if (! pn.style.backgroundColor) {
        // word has not already been highlighted!
        nv = node.nodeValue;
        ni = tempNodeVal.indexOf(tempWordVal);
        // Create a load of replacement nodes
        before = document.createTextNode(nv.substr(0,ni));
        docWordVal = nv.substr(ni,word.length);
        after = document.createTextNode(nv.substr(ni+word.length));
        hiwordtext = document.createTextNode(docWordVal);
        hiword = document.createElement("spanHighlight");
				hiword.style.backgroundColor = color;
        hiword.appendChild(hiwordtext);
        pn.insertBefore(before,node);
        pn.insertBefore(hiword,node);
        pn.insertBefore(after,node);
        pn.removeChild(node);
      }
    }
  }
}


/* Deja de resaltar todas las palabras del nodo de id nodeId */
function clearWord(nodeId) {
	var node = document.getElementById(nodeId);		
  // Iterar en los nodos hijos de este nodo
	if(node != null) {
		var elements = node.getElementsByTagName('spanHighlight');
		for (i=0; i< elements.length; i++) {
			elements[i].style.backgroundColor = 'FFFFFF';
			elements[i].style.backgroundColor = null;
		}
	}
}

