// Compare two options within a list by VALUES
function compareOptionValues(a, b) 
{ 
  // Radix 10: for numeric values
  // Radix 36: for alphanumeric values
  var sA = parseInt( a.value, 36 );  
  var sB = parseInt( b.value, 36 );  
  return sA - sB;
}

// Compare two options within a list by TEXT
function compareOptionText(a, b) 
{ 
  // Radix 10: for numeric values
  // Radix 36: for alphanumeric values
  var sA = parseInt( a.text, 36 );  
  var sB = parseInt( b.text, 36 );  
  return sA - sB;
}

// Función que mueve un item desde la lista origen a la lista destino
// Argumentos: lista Origen, lista Destino, mover todos, 
//				elementos ordenados, criterio de orden (TEXT o VALUES)
function moveDualList( listaOrigen, listaDestino, moveAll, ordered, ordCriteria, str2Check, PositiveCheck, addFirst ) 
{
  // Si no seleccioné ningún elemento o la opción moverlos todos salgo
  if( (listaOrigen.selectedIndex == -1) && (moveAll == false) ) {
    return; 
  }

//alert("listaOrigen:"+listaOrigen.options.length);
//alert("listaDestino:"+listaDestino.options.length);

  newlistaDestino = new Array( listaDestino.options.length );
  
  if( addFirst )
  {
	  var len = 0;
	  for (var i=0; i<listaOrigen.options.length; i++) 
	  { 
	    if (listaOrigen.options[i] != null && ( listaOrigen.options[i].selected == true || moveAll ) && ( !str2Check || ( listaOrigen.options[i].value.indexOf(str2Check)>-1 && PositiveCheck ) || ( listaOrigen.options[i].value.indexOf(str2Check)==-1 && !PositiveCheck ) ) )
	    {
	       // Si fue seleccionado o eligió la opción de mover todos, lo agrego a la lista
	       newlistaDestino[ len ] = new Option( listaOrigen.options[i].text, listaOrigen.options[i].value, listaOrigen.options[i].defaultSelected, listaOrigen.options[i].selected );
	       len++;
	    }
	  }

	  for (i=0; i<listaDestino.options.length; i++) 
	  {
	    if( listaDestino.options[i] != null)
	    {
	      newlistaDestino[ len ] = new Option( listaDestino.options[ i ].text, listaDestino.options[ i ].value, listaDestino.options[ i ].defaultSelected, listaDestino.options[ i ].selected );
          len++;
	    }
	  }
  }
  else
  {
	  var len = 0;
	  for (len=0; len<listaDestino.options.length; len++) 
	  {
	    if( listaDestino.options[len] != null)
	    {
	      newlistaDestino[ len ] = new Option( listaDestino.options[ len ].text, listaDestino.options[ len ].value, listaDestino.options[ len ].defaultSelected, listaDestino.options[ len ].selected );
	    }
	  }
	
	  for (var i=0; i<listaOrigen.options.length; i++) 
	  { 
	    if (listaOrigen.options[i] != null && ( listaOrigen.options[i].selected == true || moveAll ) && ( !str2Check || ( listaOrigen.options[i].value.indexOf(str2Check)>-1 && PositiveCheck ) || ( listaOrigen.options[i].value.indexOf(str2Check)==-1 && !PositiveCheck ) ) )
	    {
	       // Si fue seleccionado o eligió la opción de mover todos, lo agrego a la lista
	       newlistaDestino[ len ] = new Option( listaOrigen.options[i].text, listaOrigen.options[i].value, listaOrigen.options[i].defaultSelected, listaOrigen.options[i].selected );
	       len++;
	    }
	  }
  }

  // Si la lista debe ser ordenada, la ordeno con la función que corresponda
  if( ordered )
  {
  	if( ordCriteria=="VALUES" )
  		newlistaDestino.sort( compareOptionValues );
  	else
  		newlistaDestino.sort( compareOptionText );
  }

  // Agrego la nueva lista destino al campo del formulario
  for (var j=0; j<newlistaDestino.length; j++ )
  {
    if ( newlistaDestino[ j ] != null )
    {
      listaDestino.options[ j ] = newlistaDestino[ j ];
    }
  }

  // Elimino de la lista origen los elementos que fueron movidos
  for( var i=listaOrigen.options.length-1; i>=0; i-- )
  { 
    if ( listaOrigen.options[i]!=null && ( listaOrigen.options[i].selected == true || moveAll ) && ( !str2Check || ( listaOrigen.options[i].value.indexOf(str2Check)>-1 && PositiveCheck ) || ( listaOrigen.options[i].value.indexOf(str2Check)==-1 && !PositiveCheck ) ) )
    {
       listaOrigen.options[i]       = null;
    }
  }
  return true;
}

var Combo2Process = new Array();

function SetMultiComboStr( comboStringField )
{
	if( Combo2Process.length>0 )
	{
		var retStr='';
		for( var i=0; i<Combo2Process.length; i++ )
		{
			if( retStr>'' ) retStr+= "\\";
			retStr+=Combo2Process[i]+"=";
			var cmbStr='';
			for( var k=0; k<document.getElementById( Combo2Process[i] ).options.length; k++ ) 
			{
				if( cmbStr>'' ) cmbStr+="/";
				cmbStr+=document.getElementById( Combo2Process[i] ).options[k].value;
			}
			retStr+=cmbStr;
		}
		comboStringField.value=retStr;
	}
}

// Arma una string con las opciones del combo para procesarlas en el script
// Recibe el objeto de tipo combo y un campo String (hidden)
function SetComboStr(ComboElements,ComboString)
{
	var retStr='';
	for( i=0;i<ComboElements.options.length; i++){
		if(retStr>'') retStr+="/";
		retStr+=ComboElements.options[i].value+"/";
	}
	ComboString.value=retStr;
}

// Función que mueve un Email y un Nombre de 2 campos a un Lista de direcciones
// Argumentos: Campo de Nombre, Campo de Email, lista Destino
function moveEmailDualList( nameField, emailField, listaDestino, eraseFields, ordered, ordCriteria ) 
{
  // Si no cargué el Email no hago nada (el Nombre puede venir vacío)
  if( !emailField.value || !nameField.value ) 
    return;

  newlistaDestino = new Array( listaDestino.options.length );

  var len = 0;
  for (len=0; len<listaDestino.options.length; len++) 
  {
    if( listaDestino.options[len] != null)
    {
      newlistaDestino[ len ] = new Option( listaDestino.options[ len ].text, listaDestino.options[ len ].value, listaDestino.options[ len ].defaultSelected, listaDestino.options[ len ].selected );
    }
  }
  
  newlistaDestino[ len ] = new Option( nameField.value, nameField.value+" <"+emailField.value+">" );
  if( eraseFields )
  {
	nameField.value = '';
	emailField.value = '';
  }

  // Si la lista debe ser ordenada, la ordeno con la función que corresponda
  if( ordered )
  {
  	if( ordCriteria=="VALUES" )
  		newlistaDestino.sort( compareOptionValues );
  	else
  		newlistaDestino.sort( compareOptionText );
  }
  
  // Agrego la nueva lista destino al campo del formulario
  for (var j=0; j<newlistaDestino.length; j++ )
  {
    if ( newlistaDestino[ j ] != null )
    {
      listaDestino.options[ j ] = newlistaDestino[ j ];
    }
  }
}

// Arma una string con las opciones del combo para procesarlas en el script
// Recibe el objeto de tipo combo y un campo String (hidden)
function SetComboEmailStr(ComboElements,ComboString)
{
	var retStr='';
	for( i=0;i<ComboElements.options.length; i++)
	{
		if(retStr>'') retStr+=",";
		retStr+=ComboElements.options[i].value;
	}
	ComboString.value=retStr;
}

// Aca agrego las funciones para manejo de múltiples listas, pero que no son necesariamente
// entre 2 listas propiamentedicho. 

// Esto sería conveniente separarlo y llevarlo a el multilist.js, hay que ver como se hace
// para inlucír un .js desde otro.

// Carga una lista múltiple a partir del contenido de 2 campos de un formulario
function moveTwoFields2MultList( valueField, descriptionField, listaDestino, eraseFields, noRepeated, ordered, ordCriteria )
{
	// Si no cargué el Email no hago nada (el Nombre puede venir vacío)
	if( !valueField.value || !descriptionField.value ) 
		return;
	
	newlistaDestino = new Array( listaDestino.options.length );
	
	var len = 0;
	for (len=0; len<listaDestino.options.length; len++) 
	{
		if( listaDestino.options[len] != null)
		{
		  if( noRepeated && listaDestino.options[ len ].value==valueField.value )
		  	return;

		  newlistaDestino[ len ] = new Option( listaDestino.options[ len ].text, listaDestino.options[ len ].value, listaDestino.options[ len ].defaultSelected, listaDestino.options[ len ].selected );
		}
		 
		
	}
	
	newlistaDestino[ len ] = new Option( descriptionField.value, valueField.value );
	if( eraseFields )
	{
		descriptionField.value = '';
		valueField.value = '';
	}
	
	// Si la lista debe ser ordenada, la ordeno con la función que corresponda
	if( ordered )
	{
		if( ordCriteria=="VALUES" )
			newlistaDestino.sort( compareOptionValues );
		else
			newlistaDestino.sort( compareOptionText );
	}
	
	// Agrego la nueva lista destino al campo del formulario
	for (var j=0; j<newlistaDestino.length; j++ )
	{
		if ( newlistaDestino[ j ] != null )
		  listaDestino.options[ j ] = newlistaDestino[ j ];
	}
}

// Función que agrega el valor cargado en un Campo del formulario a un Lista de múltiple selección
// Argumentos: Nombre del Campo, lista Destino, Eliminar el valor del campo
function addField2MultiList( field, targetList, eraseField, ordered, ordCriteria )
{
  // Si el campo no tiene valor no hago nada
  if( !field.value ) 
    return false;

  newlistaDestino = new Array( targetList.options.length );

  var len = 0;
  for (len=0; len<targetList.options.length; len++) 
  {
    if( targetList.options[len] != null)
    {
      newlistaDestino[ len ] = new Option( targetList.options[ len ].text, targetList.options[ len ].value, targetList.options[ len ].defaultSelected, targetList.options[ len ].selected );
    }
  }
  
  newlistaDestino[ len ] = new Option( field.value, field.value );

  if( eraseField )
	field.value = '';

  // Si la lista debe ser ordenada, la ordeno con la función que corresponda
  if( ordered )
  {
  	if( ordCriteria=="VALUES" )
  		newlistaDestino.sort( compareOptionValues );
  	else
  		newlistaDestino.sort( compareOptionText );
  }
  
  // Agrego la nueva lista destino al campo del formulario
  for (var j=0; j<newlistaDestino.length; j++ )
  {
    if ( newlistaDestino[ j ] != null )
    {
      targetList.options[ j ] = newlistaDestino[ j ];
    }
  }
  return true;
}

function deleteFromMultiList( list, deleteAll )
{
  if( (list.selectedIndex == -1) && (deleteAll == false) ) 
    return false;
	
  // Elimino de la lista los elementos que fueron seleccionados o todos
  for( var i=list.options.length-1; i>=0; i-- )
  {
    if ( list.options[i]!=null && ( list.options[i].selected == true || deleteAll ) )
    {
       list.options[i] = null;
    }
  }
  
  return true;
}

function searchInMultiList( SearchStr, list, exactMatch )
{
	if( !SearchStr )
		return false;

	var Qty=0;		
	var lastFound = '';
	for( var i=list.options.length-1; i>=0; i-- )
	{
		if( (exactMatch && list.options[i].text==SearchStr ) || (!exactMatch && getMatchStrQty(list.options[i].text,SearchStr) ) )
		{
			list.options[i].selected=1;
			Qty++;
			lastFound = list.options[i].text;
		}
	}
	if( Qty==1 ) return lastFound;
	else return Qty;
}


// Función que mueve un Email y un Nombre de 2 campos a un Lista de direcciones
// Argumentos: Campo de Nombre, Campo de Email, lista Destino
//function moveEmailDualList( nameField, emailField, listaDestino, eraseFields ) 
//{
//	alert(nameField);
//alert(document.getElementById(nameField).value);  
//
//  var nameFieldValue = document.getElementById(nameField).value;
//  var emailFieldValue = document.getElementById(emailField).value;
//  // Si no cargué el Email no hago nada (el Nombre puede venir vacío)
//  if( !emailFieldValue || !nameFieldValue ) 
//    return;
//
//  var listaDestinoObj = document.getElementById(listaDestino);
//
//  newlistaDestino = new Array( listaDestinoObj.options.length );
//
//  var len = 0;
//  for (len=0; len<listaDestinoObj.options.length; len++) 
//  {
//    if( listaDestinoObj.options[len] != null)
//    {
//      newlistaDestino[ len ] = new Option( listaDestinoObj.options[ len ].text, listaDestinoObj.options[ len ].value, listaDestinoObj.options[ len ].defaultSelected, listaDestinoObj.options[ len ].selected );
//    }
//  }
//  
//  newlistaDestino[ len ] = new Option( nameFieldValue, nameFieldValue+" <"+emailFieldValue+">" );
//  if( eraseFields )
//  {
//	document.getElementById(nameField).value = '';
//	document.getElementById(emailField).value = '';
//  }
//  
//  // Agrego la nueva lista destino al campo del formulario
//  for (var j=0; j<newlistaDestino.length; j++ )
//  {
//    if ( newlistaDestino[ j ] != null )
//    {
//      listaDestinoObj.options[ j ] = newlistaDestino[ j ];
//    }
//  }
//}
//
//// Arma una string con las opciones del combo para procesarlas en el script
//// Recibe el objeto de tipo combo y un campo String (hidden)
//function SetComboEmailStr(ComboElements,ComboString)
//{
//	var retStr='';
//	var ComboElementsObj = document.getElementById(ComboElements);
//	for( i=0;i<ComboElementsObj.options.length; i++)
//	{
//		if(retStr>'') retStr+=",";
//		retStr+=ComboElementsObj.options[i].value;
//	}
//	document.getElementById(ComboString).value=retStr;
//}
//

