// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function inList(toList, element) {
    list = $(toList);
    if(list.options.length==0) {
        return false;
    }

    for(var i=0; i<list.options.length;i++) {
        if(list.options[i].value==element) {
            return true;
        }
    }
    return false;
}

function copyListItem(from,to) {
    var fromList = $(from);
    var toList = $(to);

    for (var i=0;i<fromList.options.length;i++)
    {
        var current = fromList.options[i];

        if (current.selected)
        {
            if(!inList(to, current.value)) {
                txt = current.text;
                val = current.value;
                toList.options[toList.length] = new Option(txt,val);
                sortOptions(toList);
            }
        }
    }
}



function compareOptionText(a,b) {
    /*
        * return >0 if a>b
        * 0 if a=b
        * <0 if a<b
        */
    // textual comparison
    return a.text!=b.text ? a.text<b.text ? -1 : 1 : 0;
// numerical comparison
// return a.text - b.text;
}



function sortOptions(list) {
    var items = list.options.length;
    // create array and make copies of options in list
    var tmpArray = new Array(items);
    for ( i=0; i<items; i++ )
        tmpArray[i] = new
        Option(list.options[i].text,list.options[i].value);
    // sort options using given function
    tmpArray.sort(compareOptionText);
    // make copies of sorted options back to list
    for ( i=0; i<items; i++ ) {
        list.options[i] = new Option(tmpArray[i].text,tmpArray[i].value);
    }
}




function deleteListItem(from) {
    var fromList = $(from);

    for(i=0;i<fromList.options.length;i++)
    {
        var current = fromList.options[i];
        if(current.selected)
        {
            fromList.options[i] = null;
            i--;
        }
    }
}

function allSelect(elementName)
{
    var list = $(elementName);
    if (list.length==0) return;
    for (i=0;i<list.length;i++)
    {
        list.options[i].selected = true;
    }
}