/**
 * Usage:
 *   In HTML. Add the following line towards the end of the document.
 *     <script type="text/javascript" src="se_hilite.js"></script>
 *   In CSS, define the following style:
 *     .hilite { background-color: #ff0; }
 * @author Scott Yang <http://scott.yang.id.au/>
 * @version 1.2
 * @customized by Pawel Dulak
 *
 * 08/11/08 Pawel: behavior changed (search engine rebuild) 
 */

// Configuration:
Hilite = {
	// Whether we are matching an exact word. For example, searching for
	// "highlight" will only match "highlight" but not "highlighting" if exact
	// is set to true.
	exact: true,
	// Name of the style to be used. Default to 'hilite'.
	style_name: 'hilite'
};

// Highlight a HTML string with a list of keywords.
Hilite.hiliteHTML = function(html, query) {
	var re = new Array();
	query = query.toLowerCase();
	if (Hilite.exact)
		re.push('\\b'+query+'\\b');
	else
		re.push(query);

	re = new RegExp('('+re.join("|")+')', "gi");

	var last = 0;
	var tag = '<';
	var skip = false;
	var skipre = new RegExp('^(script|style|textarea|tt)', 'gi');
	var part = null;
	var result = '';

	while (last >= 0) {
		var pos = html.indexOf(tag, last);
		if (pos < 0) {
			part = html.substring(last);
			last = -1;
		} else {
			part = html.substring(last, pos);
			last = pos+1;
		}

		if (tag == '<') {
			if (!skip) {
				oldpart = part;
				if (part.search(re) >= 0) {
					var pos = part.search(re);
					var posSlice = pos + query.length;
					partStart = part.substr(0,posSlice); 
					partEnd = part.substr(posSlice);
					var subs = '<span class="'+Hilite.style_name+'">$1</span>';
					part = partStart.replace(re, subs);
					part += Hilite.hiliteHTML(partEnd, query);
				}
			}
			else
				skip = false;
		} else if (part.match(skipre)) {
			skip = true;
		}

		result += part + (pos < 0 ? '' : tag);
		tag = tag == '<' ? '>' : '<';
	}

	return result;
};

/* Hilite.removeHTML = function(html) {
	var re = new Array();
	query = lastSearchQuery.toLowerCase();
	test = '<tt id="sea([0-9]+)" class="'+Hilite.style_name+'">('+query+')</tt>';
	reg = new RegExp(test, "gi");
	var subs = '$2';
	var result = html.replace(reg, subs);
	//for IE browsers
	test = '<tt class='+Hilite.style_name+' id=sea([0-9]+)>('+query+')</tt>';
	reg = new RegExp(test, "gi");
	var subs = '$2';
	var result = result.replace(reg, subs);
	//for IE browsers END 
	return result; 
}; */

// Highlight a DOM element with a list of keywords.
Hilite.hiliteElement = function(elm, query) {
	if (!query)
	return;

	var oldhtml = elm.innerHTML;
	var newhtml = Hilite.hiliteHTML(oldhtml, query);

	if (oldhtml != newhtml) {
		elm.innerHTML = newhtml;
		}
	/* else {
		alert("Search string not found");
	} */
};
