﻿function DropdownListUtility() {}

DropdownListUtility.GetValue = function(dropdownlist)
{
	if (dropdownlist.options.length == 0)
		return null;
	
	var ordinal = dropdownlist.selectedIndex;
	
	return dropdownlist.options[ordinal].value;
}

DropdownListUtility.GetText = function(dropdownlist, optionValue)
{
	if (dropdownlist.options.length == 0)
		return null;
		
	var ordinal = dropdownlist.selectedIndex;
	
	if (optionValue)
	{
		for (var i = 0; i < dropdownlist.options.length; i++)
		{
			if (dropdownlist.options[i].value == optionValue)
			{
				ordinal = i;
				break;
			}
		}
	}		

	return dropdownlist.options[ordinal].text;
}

DropdownListUtility.GetValueIndex = function(dropdownlist, value)
{
	var returnValue = -1;
	
	for (var i = 0; i < dropdownlist.options.length; i++)
	{
		if (dropdownlist.options[i].value == value)
		{
			returnValue = i;
			break;
		}
	}
	
	return returnValue;
}

DropdownListUtility.PromptAndAddItem = function(droplist, message)
{
	var custom = prompt(message, "");
	
	if (custom != null && custom.length != 0)
	{
		custom = ScrubValue(custom);
		DropDownList_addItem(droplist, custom, custom);
	}
	
	return custom;
}

DropdownListUtility.SelectValue = function(valueToSelect, dropdownlist, insertIfNotPresent)
{
	var found = false;
	
	for (var i = 0; i < dropdownlist.options.length; i++)
	{
		if (dropdownlist.options[i].value == valueToSelect)
		{
			dropdownlist.selectedIndex = i;
			found = true;
			break;
		}
	}
	
	if (insertIfNotPresent == true && found == false)
	{
		DropDownList_addItem(dropdownlist, valueToSelect, valueToSelect);
	}
}

DropdownListUtility.AddItem = function(droplist, customText, customValue)
{
	var len = droplist.length++;
	droplist.options[len].value = customText;
	droplist.options[len].text = customValue;
	droplist.selectedIndex = len;
}

DropdownListUtility.Reset = function(droplist)
{
	droplist.selectedIndex = 0;
}

DropdownListUtility.FilterOptions = function(droplist, predicate)
{
	var options = droplist.getElementsByTagName('OPTION');
	
	for (var i = 0; i < options.length; i++)
	{
		if (predicate(options[i]))
		{
			setStyle(options[i], 'display', '');
		}
		else
		{
			setStyle(options[i], 'display', 'none');
		}
	}
}

DropdownListUtility.AddOptions = function(droplist, optionstring)
{
	var arrKvp = optionstring.split(',');
	
	for (var i = 0; i < arrKvp.length; i++)
	{
		var kvp = arrKvp[i];
		var arrOption = kvp.split(':');
		
		var key = arrOption.length == 2 ? arrOption[1] : arrOption[0];
		var value = arrOption[0];
		
		DropDownList_addItem(droplist, value, key);
		
		droplist.selectedIndex = 0;
	}
}