function sortCompare(a, b)
{
     // Sortiere auch deutsche Umlaute
     var c = a.replace(/ä/,"ae");
     c = c.replace(/Ä/,"Ae");
     c = c.replace(/Ö/,"Oe");
     c = c.replace(/ö/,"oe");
     c = c.replace(/Ü/,"Ue");
     c = c.replace(/ü/,"ue");
     c = c.replace(/ß/,"ß");


     var d = b.replace(/ä/,"ae");
     d = d.replace(/Ä/,"Ae");
     d = d.replace(/ö/,"oe");
     d = d.replace(/Ö/,"Oe");
     d = d.replace(/Ü/,"Ue");
     d = d.replace(/ü/,"ue");
     d = d.replace(/ß/,"ß");

     if(c < d)
         return -1;
     else if(a == b)
         return 0;
     else
         return 1;
}

function updateSelect(sourceListIdStr, targetListIdStr, ajaxListIdStr, mode, mode2){
 
	// first we need to read the length of the list
	sourceList = document.getElementById(sourceListIdStr);
	targetList = document.getElementById(targetListIdStr);
	ajaxListId = document.getElementById(ajaxListIdStr);
	sourceText = false;
	sourceValue = sourceList.value;
		// get selected text
		for (i=0; i<sourceList.length; i++){
			if(sourceList.options[i].selected == true){
				sourceText = sourceList.options[i].text;
			}
		}
     
    if (!sourceText){
        alert('Bitte wählen Sie zunächst eine Option aus');
    }
    else if(sourceValue == '')
    {
        //alert(sourceText);
        removeFreeTextFromSelect(ajaxListIdStr, mode2);
    }   
    else
    {
       
	// if we have the sourde data, then we can proceed and append it to the destination
	removeSelected(sourceList);
	addOption();

	if ((sourceValue) && (sourceText)){
  		 	
			//add the new value to the param list, but don't add it to the select options now.
			var vals = new Array();
			
			if (targetListIdStr == ajaxListIdStr){
			
				 for (i=0; i<ajaxListId.length; i++){
						val = ajaxListId.options[i].value;
						vals.push(val);
				}
				vals.push(sourceValue);
				
			}else if(sourceListIdStr == ajaxListIdStr){
			 	
				 for (i=0; i<ajaxListId.length; i++){
					val = ajaxListId.options[i].value;
					if (val != sourceValue){
						vals.push(val);
					}
				}
			}
			optionValues = vals;
			switch (mode){
				case 'UpdateZielgruppen2':
				
					DivID = 'UpdateZielgruppen2_preload';
					p = '?cl=ajaxlist&amp;fnc=UpdateZielgruppen&'+serial('select', vals);
				
				break;
				case 'UpdateAnwenderKreis2':
					DivID = 'UpdateAnwenderKreis2_preload';
					p = '?cl=ajaxlist&amp;fnc=UpdateAnwenderKreis&'+serial('anwenderkreisselect', vals);
				
				break;
				case 'UpdateSpezialitaet2':
					DivID = 'UpdateSpezialitaet2_preload';
					p = '?cl=ajaxlist&amp;fnc=UpdateSpezialitaet&'+serial('spezialitaetselect', vals);
				
				break;
				case 'UpdateWerbemittel2':
					DivID = 'UpdateWebemittel2_preload';
					p = '?cl=ajaxlist&amp;fnc=UpdateWebemittel&'+serial('werbemittelselected', vals);
				break;
				
				case 'UpdateWerbeZielgruppen2':
					DivID = 'UpdateWerbeZielgruppen2_preload';
					p = '?cl=ajaxlist&amp;fnc=UpdateWerbeZielgruppen&'+serial('werbezielgruppenselect', vals);		
				break;
				default:
					alert('undefined_mode: ' + mode);
				break;
			}
			
			
			if (DivID){
			 
				 new Ajax.Request(baseLink,{
					method:'get',
					parameters: p,
					onLoading: function(wait4a){
						$(DivID).innerHTML='<div align="center" valign="middle" style="height:50px;padding-top:19px"><img src='+ imageDir +'ajax_spinner.gif"  align="absmiddle"><div>';
					},
					onSuccess: function(transport){
						var response = transport.responseText;
							$(DivID).innerHTML = '';
					},
					onFailure: function(){ 
						alert('Something went wrong...');
					    }
				    });
			    }
           }
	}
};


function removeFreeTextFromSelect(id, fnc){

     select = document.getElementById(id);
     textArr = Array();
     
     if (select){
         for (i=0; i<ajaxListId.length; i++){
                if ((!select.options[i].selected) && (select.options[i].value == '')){
                        textArr.push(select.options[i].text);
                        }     
                }
         }
         
     str  = textArr.join('\n');         
     switch (fnc){
                case 'SaveZielgruppeFreitextInSession':      
                  DivID = 'UpdateZielgruppen2_preload';
                break;
                 case 'SaveAnwenderkreisFreitextInSession':      
                  DivID = 'UpdateAnwenderKreis2_preload';
                break;
                 case 'SaveSpezialitaetFreitextInSession':      
                  DivID = 'UpdateSpezialitaet2_preload';
                break;
                 case 'SaveWerbemittelFreitextInSession':      
                  DivID = 'UpdateWebemittel2_preload';
                break;
                 case 'SaveWerbeZielgruppeFreitextInSession':      
                  DivID = 'UpdateWerbeZielgruppen2_preload';                  
                break; 
                
                default:
                  alert('undefined_mode: ' + mode);
                break;
            }
            
    if (DivID){
                 new Ajax.Request(baseLink,{
                    method:'get',
                    parameters:'?cl=ajaxlist&amp;fnc='+fnc+'&s='+str,
                    onLoading: function(wait4a){   
                        $(DivID).innerHTML='<div align="center" valign="middle" style="height:50px;padding-top:19px"><img src='+ imageDir +'ajax_spinner.gif"  align="absmiddle"><div>';
                    },
                    onSuccess: function(transport){
                        removeSelected(select);
                        var response = transport.responseText;
                            $(DivID).innerHTML = '';
                    },
                    onFailure: function(){ 
                        alert('Something went wrong...');
                    }
                });
                }
}


function insertInSelect(sourceFieldIdStr, targetListIdStr, ajaxListIdStr, fnc){

    // first we need to read the length of the list
    sourceField = document.getElementById(sourceFieldIdStr);
    targetList = document.getElementById(targetListIdStr);
    ajaxListId = document.getElementById(ajaxListIdStr);
    
    param = 's'; 
    sourceText =  sourceField.value;
    sourceField.value = '';
    sourceValue = '';
    //alert(sourceText);
    if (sourceText != ''){
  
        labels = Array();
        for (i=0; i<ajaxListId.length; i++){
            if(ajaxListId.options[i].value == ''){
                            lab = ajaxListId.options[i].text;
                            labels.push(lab);
                    }
        }
        
        labels.push(sourceText); 
        str  = labels.join('\n');

        switch (fnc){
                    case 'SaveZielgruppeFreitextInSession':      
                      DivID = 'UpdateZielgruppen2_preload';
                    break;
                    case 'SaveAnwenderkreisFreitextInSession':      
                      DivID = 'UpdateAnwenderKreis2_preload';
                    break;                   
                    case 'SaveSpezialitaetFreitextInSession':      
                      DivID = 'UpdateSpezialitaet2_preload';
                    break;                    
                    case 'SaveWerbemittelFreitextInSession':      
                      DivID = 'UpdateWebemittel2_preload';
                    break;
                     case 'SaveWerbeZielgruppeFreitextInSession':      
                     DivID = 'UpdateWerbeZielgruppen2_preload';              
                    break;                     
                    default:
                      alert('undefined_mode: ' + mode);
                    break;
                }
                
        if (DivID){
                     new Ajax.Request(baseLink,{
                        method:'get',
                        parameters:'?cl=ajaxlist&amp;fnc='+fnc+'&s='+str,
                        onLoading: function(wait4a){   
                            $(DivID).innerHTML='<div align="center" valign="middle" style="height:50px;padding-top:19px"><img src='+ imageDir +'ajax_spinner.gif"  align="absmiddle"><div>';
                        },
                        onSuccess: function(transport){
                            var response = transport.responseText;
                                $(DivID).innerHTML = '';
                                addOption();
                        },
                        onFailure: function(){ 
                            alert('Something went wrong...');
                        }
                    });
           }
    }
}
 

//remove the option from the source list
function removeSelected(selectElem){
	 var i;
	 for (i = selectElem.length - 1; i>=0; i--) {
		if (selectElem.options[i].selected) {
			selectElem.remove(i);
			return true;
		}
	}
}
		
// add the option to the destination list
function addOption(){
	 
	   // we have to insert the new option in the correct position to keep altpabetical order
	   // we fist read the current options
	   // var arr = Array();
	    textArr = Array();
	    valsArr = Array();
	    for (i=0; i<targetList.length; i++){
						v = targetList.options[i].text;
						valsArr[v] = targetList.options[i].value;
					    textArr.push(v);
					}
		 
		textArr.push(sourceText);
		valsArr[sourceText] = sourceValue;
		 
		//sort the labels
		var sortedTextArr = textArr.sort(sortCompare);
	    
		//now that we have all the labels, we clear all the options from the select box
		while (targetList.length > 0){
				targetList.remove(0);
		}		
		//redraw the options in sorted order
		for (i=0; i<sortedTextArr.length; i++){
				  newEl = document.createElement('option');
				  newEl.text = sortedTextArr[i];
				  newEl.value = valsArr[sortedTextArr[i]];
					 try {
		    		targetList.add(newEl, null); // standards compliant; doesn't work in IE
		  		}
			  		catch(ex) {
		    		targetList.add(newEl); // IE only
		  		}		
		}
}
	
function serial(varName, arr){

 		var str = '';
		for(i=0; i<arr.length; i++){
		 	if (str == ''){
				str += varName+'[]='+arr[i];
			}else{
				str += '&'+varName+'[]='+arr[i];
			}
		}			
	return str;
} 


function sortSelect(id){

    elem = document.getElementById(id);
    textArr = Array();
    valsArr = Array();
    
     for (i=0; i<elem.length; i++){
        v = elem.options[i].text;
        valsArr[v] = elem.options[i].value;
        textArr.push(v);
     }
         //sort the labels
         var sortedTextArr = textArr.sort(sortCompare);
        
        //now that we have all the labels, we clear all the options from the select box
        while (elem.length > 0){
                elem.remove(0);
        }
        
        //redraw the options in sorted order
        for (i=0; i<sortedTextArr.length; i++){

                  newEl = document.createElement('option');
                  newEl.text = sortedTextArr[i];
                  newEl.value = valsArr[sortedTextArr[i]];
                     try {
                    elem.add(newEl, null); // standards compliant; doesn't work in IE
                  }
                      catch(ex) {
                    elem.add(newEl); // IE only
                  }          
        }
}