var text_old = '';
var current_id = 0;

// Прокрутка, если текущее вхождение не видно
function ScrollIntoView(){
	var elem_cr = idFound[current_id].getBoundingClientRect();
	var win_heigth = idTableScroll.clientHeight;
	if (elem_cr.bottom > win_heigth) {
		idFound[current_id].scrollIntoView(false);
	} else if (elem_cr.top < idHeaderRow.offsetHeight) {
		idTableScroll.scrollTop = idFound[current_id].offsetParent.offsetTop - idHeaderRow.offsetHeight;
	}
}

// Маркировка текущего вхождения
function MarkCurrentFound(i){
	if (idFound.length > 1) {
		idFound[current_id].className = '';
		current_id += i;
		switch(current_id){
			case idFound.length: current_id = 0; break;
			case -1:             current_id = idFound.length-1;
		}
		idFound[current_id].className = 'CurrentFound';
		ScrollIntoView();
	}
}

// Маркировка всех вхождений
function MarkText(text) {
	// Содержится ли элемент в idContents?
	function IsContain(el){
		if (el) {
			if ((el.id) && (el.id == 'idContents')) return true;
			return IsContain(el.parentElement);
		}
	}
	var found = 0;
	var TextRange = document.body.createTextRange();
	while (TextRange.findText(text)) {
		if (IsContain(TextRange.parentElement())) {
			TextRange.pasteHTML('<span id="idFound">' + TextRange.htmlText + '</span>');
			found++;
		}
		TextRange.collapse(false);
	}
	return found;
}

// Очистка маркировки всех вхождений
function ClearFounds() {
	idFoundCount.innerText = 0;
	idFindText.style.backgroundColor = "";
	text_old = '';
	current_id = 0;
	var parent;
	for (var found; found = document.getElementById('idFound');) {
		parent = found.parentNode;
		parent.insertBefore(found.firstChild, found);
		parent.removeChild(found);
	}
}

// Поиск текста
function FindStart() {
	if ((idFindText.value) && (idFindText.value != text_old)) {
		ClearFounds();
		var found_count = MarkText(idFindText.value);
		idFoundCount.innerText = found_count;
		if (found_count) {
			document.getElementById('idFound').className = 'CurrentFound';
			if (found_count > 1) {
				ScrollIntoView();
			} else {
				document.getElementById('idFound').scrollIntoView(false);
			}
		} else {
			idFindText.style.backgroundColor = "#FF9999";
		}
		text_old = idFindText.value;
	}
}

// Задержка запуска поиска
var timerFindID = null; // Идентификатор таймера
function Find() {
	if (timerFindID) {
		clearInterval(timerFindID);
		timerFindID = null;
	}
	if (idFindText.value) {
		timerFindID = setInterval(FindStart, 1000/idFindText.value.length);
	} else {
		ClearFounds();
	}
}
