var selectedList;
var availableList;
var managedLists = new Array();
var g_optionGroupsAssigned = new Array();

function createListObjects(listNamePattern)
{
    var listCount = 0;
    var i=0;
    var tempListHolder;

    for(i=0; i <= listCount; i++)
    {
    	//Clear the temp list holder
    	tempListHolder = null;

    	tempListHolder = document.getElementById(listNamePattern+i);
    	//alert(tempListHolder);
    	if(tempListHolder != null)
    	{
    		//Add the select list to manage
    		managedLists[i] = tempListHolder;
    		//Unselect everything in the list
    		unSelectList(tempListHolder);
    		listCount++;
    	}
    	else
    	{
    		//No more select option lists to manage
    		break;
    	}
    }

    availableList = document.getElementById("availableOptions");
    //selectedList = document.getElementById("selectedOptions");
}

function delAttribute()
{
    var selIndex = selectedList.selectedIndex;
    if(selIndex < 0)
        return;
    availableList.appendChild(selectedList.options.item(selIndex))
    selectNone(selectedList,availableList);
    setSize(availableList,selectedList);
}



function addAttribute(listToAddTo)
{
    addAttributeAndResize(listToAddTo, false);
}

function addAttributeAndResize(listToAddTo, resizeList)
{
	var addIndex = -1; //= availableList.selectedIndex;
	var addIndexArray = new Array();
	var listNumber=9999;
	var maxTextWidthInList = 1;
	var currentTextWidthInList = 1;
	//alert('addAttribute managedLists.length:'+managedLists.length);

	//The list to add to does not exist
	if(listToAddTo >= managedLists.length)
	{
		alert('List:' + listToAddTo + ' that you are trying to add to does not exist!');
		return false;
	}

	for(var j=0; j < managedLists.length; j++)
	{
		//addIndex = managedLists[j].selectedIndex;

		//We have found our match
		//alert(managedLists[j]);

		for (var k = 0; k < managedLists[j].options.length; k++)
		{
		    if(managedLists[j].options[k].selected)
		    {
			//alert('adding to the addIndexArray item:' + k);
			//Add to the next available array position
			addIndexArray[addIndexArray.length] = k;
			listNumber = j;
		    }
		}

		//If we have found the list where options were selected
		// we do not move on to the next ones.
		if(listNumber <= j)
		{
			break;
		}
	}

	if(addIndexArray.length < 1)
	{
		alert('Please select something in the list to move.');
		return false;
	}
	else if(listToAddTo == listNumber)
	{
		//Trying to add to the same list
		alert('It is already in the list you are trying to move it to.');
		return false;
	}

	//Work out the largest width of anything in the list currently
	for(var n=0; n < managedLists[listToAddTo].length; n++)
	{
		currentTextWidthInList = managedLists[listToAddTo].options[n].text.length;
		if(currentTextWidthInList > maxTextWidthInList)
		{
			maxTextWidthInList = currentTextWidthInList;
		}
	}

	//alert('addAttribute maxTextWidthInList:'+maxTextWidthInList);


	//Move each selected item across to the new destination list
	//alert('addIndexArray.length:' + addIndexArray.length);
	var theOption;
	for(var m=0; m < addIndexArray.length; m++)
	{
		//alert('Adding item['+0+'] to list:'+addIndexArray[0]);
		///alert('managedLists[listNumber].options.item(addIndexArray[0]):'+managedLists[listNumber].options.item(addIndexArray[0]) );
		theOption = managedLists[listNumber].options.item(addIndexArray[0]);
		//alert('Adding theOption:'+theOption.value);

		//When we use the appendChild method, it takes it from the source
		// list and moves it to the target list.
		//This causes the addIndexArray to move all objects one array position
		// to the left, towards zero. Therefore, element [1] becomes element [0]
		// - This is why we always take array position zero, addIndexArray[0]
		// because it will be the next element in the list.
		managedLists[listToAddTo].appendChild(theOption);

		//alert("addAttribute theOption.text.length:"+theOption.text.length);
		//Re-size the width of the list to fit the maximum text width
		//alert('theOption.text.length:'+theOption.text.length + ' maxTextWidthInList:'+ maxTextWidthInList);
		if(theOption.text.length > maxTextWidthInList)
		{
			//alert('theOption.text.length > maxTextWidthInList');
			maxTextWidthInList = theOption.text.length;
			//alert('maxTextWidthInList:'+maxTextWidthInList);
		}

		//alert('addIndexArray.length:' + addIndexArray.length);
	}

	selectNone(managedLists[listToAddTo],managedLists[listNumber]);
	//alert('about to setSize for managedLists[listToAddTo].style.width:'+managedLists[listToAddTo].style.width);
	if(resizeList == true)
    {
        setSize(managedLists[listToAddTo],managedLists[listNumber]);
    }

    //alert('Setting managed List listToAddTo:'+listToAddTo+' with a width of:'+(maxTextWidthInList * 8) );
    //alert('Existing width of managedLists[listToAddTo].style.width:'+managedLists[listToAddTo].style.width);
    var pixelMultiplicationFactor = 8;
	if(maxTextWidthInList < 5)
	{
		pixelMultiplicationFactor = 18;
	}
	else if(maxTextWidthInList < 12)
	{
		pixelMultiplicationFactor = 11;
	}



	managedLists[listToAddTo].style.width = (maxTextWidthInList * pixelMultiplicationFactor) + "px";
	//alert('managedLists[listToAddTo].style.width:'+managedLists[listToAddTo].style.width);

    return true;
}

function delAll()
{
    var len = selectedList.length -1;
    for(i=len; i>=0; i--){
        availableList.appendChild(selectedList.item(i));
    }
    selectNone(selectedList,availableList);
    setSize(selectedList,availableList);

}

function addAll(){
    var len = availableList.length -1;
    for(i=len; i>=0; i--){
        selectedList.appendChild(availableList.item(i));
    }
    selectNone(selectedList,availableList);
    setSize(selectedList,availableList);

}
function selectNone(list1,list2){
    list1.selectedIndex = -1;
    list2.selectedIndex = -1;
    addIndex = -1;
    selIndex = -1;
}

function setSize(list1,list2)
{
    if(list1.size <= getSize(list1) )
    {
    	list1.size = getSize(list1);
    }

    if(list2.size <= getSize(list2) )
    {
    	list2.size = getSize(list2);
    }
}

function getSize(list){
    /* Mozilla ignores whitespace, IE doesn't - count the elements in the list */
    var len = list.childNodes.length;
    var nsLen = 0;
    //nodeType returns 1 for elements
    for(i=0; i<len; i++){
        if(list.childNodes.item(i).nodeType==1)
            nsLen++;
    }
    if(nsLen<2)
        return 2;
    else
        return nsLen;
}

function showSelected(){
    var optionList = document.getElementById("selectedOptions").options;
    var data = '';
    var len = optionList.length;
    for(i=0; i<len; i++){
        if(i>0)
            data += ',';
        data += optionList.item(i).value;
    }
    alert(data);
}

//
//This will unselect any options in any other lists
// Call this method from a select list onFocus event
//
function unSelectOtherLists(listNamePattern, thisSelectList)
{
    var listCount = 0;
    var i=0;
    var tempListHolder;

    for(i=0; i <= listCount; i++)
    {
    	//Clear the temp list holder
    	tempListHolder = null;

    	tempListHolder = document.getElementById(listNamePattern+i);
    	//alert(tempListHolder);
    	if(tempListHolder != null)
    	{
    		//Unselect the list if it is not the list being selected
    		if(thisSelectList != tempListHolder)
    		{
    			unSelectList(tempListHolder);
    		}

    		listCount++;
    	}
    	else
    	{
    		//No more select option lists to manage
    		break;
    	}
    }
}

function unSelectList(theSelectList)
{
	for (var i = 0; i < theSelectList.options.length; i++)
	{
		theSelectList.options[i].selected = false;
	}
}

function selectAllManagedLists()
{
    for (var i = 0; i < managedLists.length; i++)
	{
        selectAllInManagedList(i);
	}
}

function selectAllInManagedList(managedSelectListNumber)
{
	var theSelectList = managedLists[managedSelectListNumber];

	for (var i = 0; i < theSelectList.options.length; i++)
	{
		theSelectList.options[i].selected = true;
	}
}

function removeValueFromList(selectList, valueToRemove)
{
	for (var i = 0; i < selectList.options.length; i++)
	{
		if(selectList.options[i].value == valueToRemove)
		{
			selectList.options[i] = null;
		}
	}

	return selectList;
}

function addDistinctValueToList(selectList, valueKey, valueDescription)
{
	var foundAlready = false;
	//alert('addDistinctValueToList selectList:'+selectList+' valueKey:'+valueKey+' valueDescription:'+valueDescription);

	for (var i = 0; i < selectList.options.length; i++)
	{
		if(selectList.options[i].value == valueKey)
		{
			foundAlready = true;
		}
	}

	if(foundAlready == false)
	{
		var newOption = new Option(valueDescription, valueKey);
		//alert('addDistinctValueToList adding new option'+ newOption);
		selectList.options[selectList.length] = newOption;
	}

	return selectList;
}


function getSelectedOption(theSelectList)
{
	var selectedOption = null;

    for (var i = 0; i < theSelectList.options.length; i++)
	{
		if(theSelectList.options[i].selected == true)
		{
			selectedOption = theSelectList.options[i];
		}
	}

    return selectedOption;
}

function setSelectedOption(theSelectList, optionValueToSelect)
{
	var successfulAssignment = false;

    for (var i = 0; i < theSelectList.options.length; i++)
	{
        if(theSelectList.options[i].value == optionValueToSelect)
		{
            theSelectList.options[i].selected = true;
            successfulAssignment = true;
            break;
		}
	}

    return successfulAssignment;
}

//Uber Tab Horizontal List Change Selected Tab
function changeUberColourTab(selectedTabElement)
{
	//alert('changeUberColourTab called');
	var tabName;
	var tabAreaName;

	//Deselect all tabs
	for(var i=1;;i++)
	{
		tabName = 'ubercolortab'+i;
		tabAreaName = tabName + 'Area';

		var deSelectElement = document.getElementById(tabName);
		var hideArea = document.getElementById(tabAreaName);
		//alert('changeUberColourTab deSelectElement:'+deSelectElement+' hideArea:'+hideArea);

		if(deSelectElement == "undefined" || deSelectElement == null)
		{
			break;
		}
		else
		{
			deSelectElement.className="";

			//alert('changeUberColourTab Will attempt to hide tabAreaName:'+tabAreaName);

			if(hideArea != null && hideArea != 'undefined')
			{
				//alert('changeUberColourTab hiding tabAreaName:'+tabAreaName);
				hideArea.style.display = 'none';
			}
		}
	}

	//Select the tab which was clicked on
	var selectedTabElementParent = selectedTabElement.parentNode;
	var selectedTabElementParentID = selectedTabElementParent.id;
	tabAreaName = selectedTabElementParentID + 'Area';

	//alert('changeUberColourTab Will attempt to show tabAreaName:'+tabAreaName);
	//Show this tab as selected
	selectedTabElementParent.className = "selected";
	//Make the area attached to the tab visible
	var showArea = document.getElementById(tabAreaName);

	if(showArea != null && showArea != 'undefined')
	{
		//alert('changeUberColourTab showing tabAreaName:'+tabAreaName);
		showArea.style.display = 'block';
	}
}


function createOptionGroup(optGroupLabel){

	var optGroup = document.createElement('optgroup');

	var objOption=document.createElement("option");

	//objOption.innerHTML = optionText;
	//objOption.value = optionValue;

	optGroup.label = optGroupLabel;

	return optGroup;
}

function clearSelect(objSelect)
{
	//Clear down the local cache of option groups in the current select list
	g_optionGroupsAssigned = new Array();

	//Clear all options
	while(objSelect.options.length > 0){objSelect.remove(0);}

	//Clear any option groups
	while (objSelect.firstChild) {objSelect.removeChild(objSelect.firstChild);}

	return objSelect;
}

function createOption(objSelect, optionValue, optionText, optGroupLabel)
{

	var objOption = document.createElement("option");
	objOption.text = optionText;
	objOption.innerHTML = optionText;
	objOption.value = optionValue;


	if(optGroupLabel != null && optGroupLabel != '')
	{
		//Has this option group been added previously?
		var optGroup = g_optionGroupsAssigned[optGroupLabel];

		if(optGroup == null)
		{
			//alert('createOption found existing optGroup for optGroupLabel:'+optGroupLabel);
			//This option group does not exist so we create it.
			optGroup = createOptionGroup(optGroupLabel);
			//Add the group to the select list
			objSelect.appendChild(optGroup);

			//Store a reference to the option group to reuse for other options
			// that belong to the group.
			g_optionGroupsAssigned[optGroupLabel] = optGroup;
		}

		//Add the option to the group
		optGroup.appendChild(objOption);
	}
	else
	{
		//No group so just assign the option directly
		objSelect.appendChild(objOption);
	}

    return objOption;

/*
	if(document.all && !window.opera)
	  {objSelect.add(objOption);}
	 else
	  {objSelect.add(objOption, null);};
*/
}

function appendOptionToGroup(objOption, optGroup)
{
	if(optGroup != null)
	{
		optGroup.appendChild(objOption);
	}
}
            
function populateSelectList(objSelect, arrayOfValueGroupTextTuples, selectedOptionValue)
{
	//alert('populateSelectListRegions objSelect:'+objSelect+' arrayOfValueGroupTextTuples:'+arrayOfValueGroupTextTuples);
	clearSelect(objSelect);
    var objOption;

	var valueGroupTextTuples;
	for(var i=0; i < arrayOfValueGroupTextTuples.length; i++)
	{
		valueGroupTextTuples = arrayOfValueGroupTextTuples[i];
		//createOption(objSelect, optionValue, optionText, optGroupLabel)
		objOption = createOption(objSelect,valueGroupTextTuples[0],valueGroupTextTuples[2],valueGroupTextTuples[1]);

        if(selectedOptionValue != null && valueGroupTextTuples[0] == selectedOptionValue)
        {
            objOption.selected = true;    
        }
	}
}

/*
Code from:
http://www.delphifaq.com/faq/javascript/f1038.shtml
 */
function sortSelectList(selectBox)
{
    var strArray = new Array();
    var numArray = new Array();
    try
    {
        strIndex=0;
        numIndex=0;
        for (i = 0; i < selectBox.length; i++)
        {
            if (isNaN((selectBox.options[i].text*1)))
            {
                strArray[strIndex] = new Array();
                strArray[strIndex][0] = selectBox.options[i].text;
                strArray[strIndex++][1] = selectBox.options[i].value;
            }
            else
            {
                numArray[numIndex] = new Array();
                numArray[numIndex][0] = selectBox.options[i].text;
                numArray[numIndex++][1] = selectBox.options[i].value;
            }
        }
        for (i=0; i<numIndex-1; i++)
        {
            for (j=i; j<numIndex; j++)
            {
                if( (numArray[i][0]*1)>(numArray[j][0]*1))
                {
                    tNum=numArray[i][0];
                    tVal=numArray[i][1];
                    numArray[i][0]=numArray[j][0];
                    numArray[i][1]=numArray[j][1];
                    numArray[j][0]=tNum;
                    numArray[j][1]=tVal;
                }
            }
        }
        strArray.sort();
        listLength=0;
        for (j = 0; j < numIndex; j++)
        {
            selectBox.options[listLength].text = numArray[j][0];
            selectBox.options[listLength++].value = numArray[j][1];
        }
        for (j = 0; j < strIndex; j++)
        {
            selectBox.options[listLength].text = strArray[j][0];
            selectBox.options[listLength++].value = strArray[j][1];
        }
    }
    catch(e)
    {
        //In case of any error, dont do anything.
        alert('The following error occurred: ' + e.name + ' - ' + e.message);
    }
}
