﻿var comboBoxData = new Array();
var comboBoxCarrent = null;
var comboBoxTimeOutFunc = null;
var comboBoxDebug = false;
var comboBoxDebugWindow = null;

function comboBoxKeydown(evt, BoxID, bFillList)
{
	var currentBox = comboBoxCarrent; //comboBoxShow перебивает currentComboBox
	comboBoxShow(BoxID);
	if(currentBox != BoxID)
		comboBoxUpdate(BoxID);
	//Обрабатываем перемещение по списку и выбор из списка (нажатый символ ещё не записан в поле)
	//document.getElementById("divContent").innerHTML += "[KEYDOWN] keyCode: " + evt.keyCode + "; BoxID: " + BoxID + "<br/>";
	switch(evt.keyCode)
	{
		case 38:
			comboBoxUpSelection();
			break;
		case 40:
			comboBoxDownSelection();
			break;
		case 13:
			comboBoxListSelected();
			return false;
			break;
		case 9:
			comboBoxListSelected();
			//setTimeout("moveCaretToEnd(document.getElementById(comboBoxData['" + BoxID + "'].txtName));", 10);
			break;
		default:
	}
}

function comboBoxKeyup(evt, BoxID)
{
	//Обрабатываем работу с текстовым полем (нажатый символ записан в поле)
	//document.getElementById("divContent").innerHTML += "[KEYUP] keyCode: " + evt.keyCode + "; BoxID: " + BoxID + "<br/>";
	switch(evt.keyCode)
	{
		case 38:
			break;
		case 40:
			break;
		case 13:
			break;
		case 9:
			break;
		default:
			comboBoxUpdate(BoxID);
	}
}

function comboBoxUpdate(BoxID)
{
	var options = comboBoxList().options;
	options.length = 0;
	var boxData = comboBoxData[BoxID].Data;
	var cValue = document.getElementById(comboBoxData[BoxID].txtName).value.toLowerCase();
	var textValue = -1;
	var bPresent = false;
	var indPresent = -1;
	var searchType = comboBoxData[BoxID].searchType;
	var bHit = false
	var mode = comboBoxData[comboBoxCarrent].mode;
	
	if(comboBoxDebug && !comboBoxDebugWindow)
	{
		comboBoxDebugWindow = document.createElement("div");
		var parentElement = document.getElementById(comboBoxData[BoxID].txtName).parentNode;
		parentElement.insertBefore(comboBoxDebugWindow, document.getElementById(comboBoxData[BoxID].txtName));
	}
	//Если Email режим, то в поиске участвует часть значения после последней запятой.
	if(mode)
	{
		var lastComma = cValue.lastIndexOf(",");
		if(lastComma++ != -1)
		{
			cValue = cValue.substring(lastComma);
		}
	}
	
	cValue = trim(cValue);
	
	if(comboBoxDebug)
	{
		comboBoxDebugWindow.innerHTML += cValue + "<br/>";
	}
	
	for(var i in boxData)
	{
		bHit = false;
		if(searchType == 1)
			bHit = (boxData[i].toLowerCase().indexOf(cValue) != -1)
		else
			bHit = (boxData[i].toLowerCase().indexOf(cValue) == 0)
		if(bHit || cValue == "")
		{
			options[options.length] = new Option(boxData[i], i, false, false);
			if(!bPresent && boxData[i].toLowerCase().length == cValue.length)
			{
				//Найдено полное совпадение
				bPresent = true;
				textValue = i;
				indPresent = options.length - 1;
			}
		}
	}
	if(bPresent)
	{
		//Найдено полное совпадение
		setTimeout("comboBoxList().value = '" + textValue + "'", 10);
		comboBoxList().selectedIndex = indPresent;
		document.getElementById(comboBoxData[BoxID].txtValue).value = textValue;
	}
	else
	{
		//Полных совпадений не найдено. Выделяем первое в списке
		comboBoxList().selectedIndex = 0;
		if(options.length > 0) options[0].selected = true;
		if(!mode)
			document.getElementById(comboBoxData[BoxID].txtValue).value = "";
	}
	//Проверяем значение. Если токого нет, то value присваиваем пустую строку.
}

function comboBoxShowFullList(BoxID)
{
	comboBoxShow(BoxID);
	var options = comboBoxList().options;
	options.length = 0;
	var boxData = comboBoxData[BoxID].Data;
	for(var i in boxData)
	{
		options[options.length] = new Option(boxData[i], i, false, false);
	}
	if(options.length > 0) options[0].selected = true;
}

function comboBoxShowList(BoxID)
{
	comboBoxShow(BoxID);
	comboBoxUpdate(BoxID);
	comboBoxThrowEvent(BoxID, "focus")
}

function comboBoxListSelected()
{
	if(comboBoxList().selectedIndex != -1)
	{
		if(!comboBoxData[comboBoxCarrent].mode)
		{
			document.getElementById(comboBoxData[comboBoxCarrent].txtName).value = comboBoxList().options[comboBoxList().selectedIndex].text;
			document.getElementById(comboBoxData[comboBoxCarrent].txtValue).value = comboBoxList().options[comboBoxList().selectedIndex].value;
		}
		else
		{
			var selectedValue = comboBoxList().options[comboBoxList().selectedIndex].text;
			var fullValue = document.getElementById(comboBoxData[comboBoxCarrent].txtName).value;
			if(!this.tagName || this.tagName.toLowerCase() != "select")
			{
				var lastComma = fullValue.lastIndexOf(",");
				if(lastComma != -1)
				{
					fullValue = fullValue.substring(0, lastComma) + " ";
				}
				else
				{
					fullValue = "";
				}
			}
			var comma = (trim(fullValue) != "" && fullValue.charAt(fullValue.length - 1) != ",")? ", ": "";
		
			document.getElementById(comboBoxData[comboBoxCarrent].txtName).value = fullValue + comma + selectedValue;
			document.getElementById(comboBoxData[comboBoxCarrent].txtName).scrollTop = 10000;
			//document.getElementById(comboBoxData[comboBoxCarrent].txtValue).value = fullValue + comma + selectedValue;
		}
	}
	document.getElementById(comboBoxData[comboBoxCarrent].txtName).focus()
	comboBoxHideImmidiatly();
}

function comboBoxUpSelection()
{
	var boxList = comboBoxList()
	var sIndex = boxList.selectedIndex;
	comboBoxClearSelection();
	if(sIndex == -1) boxList.selectedIndex = boxList.options.length - 1; //Переходим на конец если -1 эелемент
	else boxList.selectedIndex = sIndex - 1;
}

function comboBoxDownSelection()
{
	var boxList = comboBoxList()
	var sIndex = boxList.selectedIndex;
	comboBoxClearSelection();
	if(sIndex == (boxList.options.length - 1)) boxList.selectedIndex = - 1; //Переходим на -1 эелемент если конец
	else boxList.selectedIndex = sIndex + 1;
}

function comboBoxClearSelection()
{
	var options = comboBoxList().options;
	for(var i = 0; i < options.length; i++)
		options[i].selected = false;
}

function comboBoxHide()
{
	comboBoxClearTimeoutFunc();
	comboBoxTimeOutFunc = setTimeout('comboBoxHideImmidiatly()', 100);
}

function comboBoxHideImmidiatly()
{
	//Валидация, если подключена.
	if(typeof validate == "function" && comboBoxCarrent)
	{
		if(validate(document.getElementById(comboBoxData[comboBoxCarrent].txtName)) == "")
			hideValidationMessage(document.getElementById(comboBoxData[comboBoxCarrent].txtName));
	}
	//Сбрасываем переменные.
	comboBoxClearTimeoutFunc();
	comboBoxCarrent = null;
	var boxList = comboBoxList();
	if(boxList) boxList.style.display = "none";
}

function comboBoxShow(BoxID)
{
	comboBoxClearTimeoutFunc();
	comboBoxCarrent = BoxID;
	//Проверяем присутсвует ли комбобокс. Если нет, то создаём его
	var boxList = comboBoxList();
	if(boxList == null)
	{
		boxList = document.createElement("select");
		boxList.id = "comboBoxList";
		boxList.style.position = "absolute";
		//boxList.style.left = 0;
		//boxList.style.top = 0;
		boxList.style.zIndex = 255;
		boxList.multiple = true;
		boxList.onfocus = comboBoxClearTimeoutFunc;
		boxList.onblur = comboBoxHide;
		boxList.ondblclick = comboBoxListSelected;
		document.getElementsByTagName("body")[0].appendChild(boxList);
	}
	
	var textEl = document.getElementById(comboBoxData[BoxID].txtName);
	
	if(typeof noDivScroll != "undefined" && noDivScroll)
	{
		var pageY = 0;
		var pageX = 0;
		par = textEl;
		while(par)
		{	
				pageY += par.offsetTop;
				pageX += par.offsetLeft;
				par=par.offsetParent;
		}
		pageY += document.getElementById(comboBoxData[BoxID].txtName).offsetHeight;
		boxList.style.left =pageX;
		boxList.style.top = pageY;
	}
	else
	{
		var parentEl = textEl.parentNode;
		parentEl.insertBefore(boxList, textEl);
		boxList.style.marginTop = textEl.offsetHeight;
	}

	boxList.style.width = document.getElementById(comboBoxData[BoxID].txtName).style.width;		
	boxList.style.height = "200px";

	comboBoxList().style.display = "";

	/*if(document.all)
	{
		var obj = boxList.getBoundingClientRect();
		var left = obj.left;
		var top = obj.top;

		
		//parentEl.removeChild(boxList);
		document.getElementsByTagName("body")[0].appendChild(boxList);
		boxList.style.left = left + "px";
		boxList.style.top = top + "px";
		//alert(left + " " + top);
	}*/

}

function comboBoxClearTimeoutFunc()
{
	if(comboBoxTimeOutFunc != null)
	{
		clearTimeout(comboBoxTimeOutFunc);
		comboBoxTimeOutFunc = null;
	}
}

function comboBoxCheckValue(BoxID, Name)
{
	if(trim(Name) == "") return true;
	for(var i in comboBoxData[BoxID].Data)
	{
		if(comboBoxData[BoxID].Data[i].toLowerCase() == Name.toLowerCase()) return true;
	}
	return false;
}

function comboBoxVisibility(BoxID)
{
	comboBoxClearTimeoutFunc();
	if(comboBoxCarrent == BoxID && comboBoxList())
	{
		//Комбобокс тотже.
		if(comboBoxList().style.display != "none")
		{
			comboBoxHideImmidiatly();
			//Стёрся comboBoxCarrent. Восстанавливаем 
			comboBoxCarrent = BoxID;
		}
		else
		{
			comboBoxShowFullList(BoxID);
		}
	}
	else
	{
		//Нажали на новый комбобокс
		comboBoxHideImmidiatly();
		comboBoxShowFullList(BoxID);
	}
	moveCaretToEnd(document.getElementById(comboBoxData[BoxID].txtName));
	comboBoxThrowEvent(BoxID, "focus")
}

function comboBoxValidate(BoxID)
{
	if(!document.getElementById(comboBoxData[BoxID].txtName).getAttribute("validation")) return "";
	if(document.getElementById(comboBoxData[BoxID].txtValue).value == "" || document.getElementById(comboBoxData[BoxID].txtValue).value == "0") return "Форма содержит некорректные значения. Пожалуйста, исправьте!";
	if(!comboBoxCheckValue(BoxID, document.getElementById(comboBoxData[BoxID].txtName).value)) return "Форма содержит некорректные значения. Пожалуйста, исправьте!";
	return "";
}

function comboBoxList()
{
	return document.getElementById("comboBoxList");
}

function moveCaretToEnd(inputObject)
{
	inputObject.focus();
	if (inputObject.createTextRange)
	{
		var r = inputObject.createTextRange();
		r.collapse(false);
		r.select();
	}
}

//Интерфейс для клиентских скриптов

function comboBoxGetValue(BoxID)
{
	return document.getElementById(comboBoxData[BoxID].txtValue).value;
}

function comboBoxSetValue(BoxID, Value)
{
	var boxData = comboBoxData[BoxID].Data;
	
	if(boxData[Value] != null)
	{
		document.getElementById(comboBoxData[BoxID].txtName).value = boxData[Value];
		document.getElementById(comboBoxData[BoxID].txtValue).value = Value;
	}
	//comboBoxHideImmidiatly();
}

function comboBoxSetEvent(BoxID, eName, eFunction, param)
{
	if(!comboBoxData[BoxID].events)
	{
		comboBoxData[BoxID].events = new Array();
		comboBoxData[BoxID].eventparams = new Array();
	}
	comboBoxData[BoxID].events[eName] = eFunction;
	comboBoxData[BoxID].eventparams[eName] = param;
}

function comboBoxThrowEvent(BoxID, eName)
{
	setTimeout("comboBoxThrowEventT('" + BoxID + "','" + eName + "')", 10)
}

function comboBoxThrowEventT(BoxID, eName)
{
	if(comboBoxData[BoxID].events && comboBoxData[BoxID].events[eName])
		comboBoxData[BoxID].events[eName](BoxID, comboBoxData[BoxID].eventparams[eName]);
}

function LTrim( value ) {
     var re = /\s*((\S+\s*)*)/;
     return value.replace(re, "$1");
}
function RTrim( value ) {
     var re = /((\s*\S+)*)\s*/;
     return value.replace(re, "$1");
}
function trim( value ) {
     return LTrim(RTrim(value));
}
