/*-----------------------------------------------------------------
 * Fichero: /js/noms.js
 * Fecha: 25-03-2002
 * Autor: eli@efaber.net
 *
 * Descripción:
 *  A)Funciones que se utilizan para añadir nuevos elemenos a una 
 *    nomeclatura "on the fly". Como ejemplo se han utilizado los 
 *    scripts de www.quickbase.com
 *  B)Funciones que se utilizan para cambiar las opciones de los 
 *    selects dependiendo de la opciones elegidas en selects anteriores.
 *    (como ejemplo se utiliza el script auto-drop-down de 
 *    javascript.internet.com)
 *  C) Otras funciones simples que se usan en los formularios.
 *
 * $Id: noms.js,v 1.27 2005/06/28 23:10:42 eli Exp $
 *-----------------------------------------------------------------
 */


/*********************************************************************
*               CheckForAdd (original CheckForOther)
*
*         Handles the Add selection from a SELECT object
*
*  Argumentos:
*  <item> el nombre del select cuyas opciones se cambian
*  <label> y <tbl_id> son la etiqueta de la nomenclatura y el id de la
*	tabla con los items de la nomenclatura. Estos argumentos se pasan
*	a  /js/form_nom_input para "saber" qué valores del formulario 
*	hay que cambiar.
*  <is_mult> es 1 si cada vez que se elige la opción "Añadir" se añade
* 	una opción nueva al select. Por defecto, la nueva opción se añade
*	sólo la primera vez y después se cambia su valor.
*
*  La posición en el select de la opción que se va a añadir/modificar se pasa
*  como argumento <new_opt_index>.
*
*  NOTA: Por lo visto en Mozilla los cambios en el texto de la opción
*  que corresponde a item.selectedIndex no se aplican y aunque la nueva 
*  opción se añade a la lista, la opciçon que aparece sigue siendo la
*  "Añadir ...". Por esto antes de hacer cambis en el texto de la opción,
*  cambio el item.selectedIndex.
*
*  NOTA_2: Si el select es de tipo "multiple", el selectedIndex devuelve 
*  la poición del primer elemento elegido y el que corresponde a 
*  "Añadir nuevo" normalmente es el último. Por esto hay que comprobar 
*  no sólo que (<options[item.selectedIndex].value> == "other") sino también 
*  que ninguno de los demás elementos elegidos es "other".
***********************************************************************/
function CheckForAdd(item, label, tbl_id, is_mult)
  {
    var add_it = false;
    var new_opt_index = 0;
    var width=400;
    var height=10;

    if ((item.type == "select-multiple") || (is_mult==1)) { // ver NOTA_2
      if (!is_mult) { 
        is_mult=1
      }
      for(var i = 0; i < item.options.length; i++) {
            if ((item.options[i].selected) && (item.options[i].value == "other")) {
                new_opt_index = i;
                add_it = true;
                i = item.options.length;
            }
      } 
    } else {
      if (!is_mult) {
         is_mult=0
      }
      if (item.options[item.selectedIndex].value == "other") {
        add_it = true;
        new_opt_index = item.selectedIndex;
        item.selectedIndex = 0; // ver NOTA
      }
    }

    if (add_it) {
         var val = window.open('/js/form_nom_input?label='+label+'&tbl_id='+tbl_id+'&pos='+new_opt_index+'&is_mult='+is_mult,
                               'popuppage',
                               'width='+width+',height='+height+',top=100,left=100');
     }

  }


/**************************************************************************************
*                           sendValue()
*
*  Añade los nuevos datos como un elemento nuevo del select "item". Las notas
*  que corresponden al nuevo item se guardan en notes_val. 
*
*  Para poder distinguirlo de los demás elementos del select el nuevo tiene como
*  "value" el string "new". Los demás tienen com value el id del elemento en
*  la tabla correspondiente.
*
*  NOTA: La comparación (slen == origlen+1) no funciona porque "origlen" se 
*  considera como un string y, por lo tanto, si origlen==3 (origlen+1)=31. 
*  Por esto he creado la variable tmp. 
*
*  NOTA 2: Por lo visto en Mozilla, el "event" on Change no funciona para selects
*  donde hay sólo una opción y por ésto añado una opción más en estos casos 
*  (ver CheckForAdd). Cuando se introduce una opción nueva, hay que quitar la
*  opción "--" y sustituirla por la nueva. Sin embargo, si se sutituye el
*  item.options[0] por los nuevos valores, estos no aparecen en el select hasta
*  que se elija "Añadir ..." otra vez (?!). Por ésto intercambio 
*  la opción "Añadir ..." y la nueva.
*
*  CAMBIOS:
*  	(12-06-2002): Ya hay algunos casos en los que las nomenclaturas tienen 
*                     columnas adicionales al nombre. Para poder incluir elementos
*                     tmb en éstas, las variables del formulario que se rellena que
*                     corresponden a los valores nuevos se guardan en el array add_values
*                     y los correspondinents elementos del formulario que ha llamado
*                     a la función se gaurdan en el array add_vars. NOTA: Las variables
*                     del add_vars tienen que existir en el formulario inicial.
*
* eli@efaber.net (27-03-2003)
* NOTA sobre IE: En IE 5.x no se pueden crear opciones nuevas en otro window.
* Para que la función sendValue pueda crear nuevas opciones hay que llamarla
* como función del window al que pertence el select - window.opener.sendValue().
*
********************************************************************************************/

function sendValue(name, add_values, pos, is_mult, item, add_vars, origlen){
  if (name.value != "") 
  {
    /* Añadir una opción nueva */
    var txt = item.options[pos].text;
    var val = item.options[pos].value;
    var slen = item.length;
    var tmp = origlen; // ver NOTA
    tmp++;

    if (item.options.length <= 2) { // Si hay sólo dos opciones hay que tratarlas de una forma especial
      if ((item.options[0].value == 0) || (item.options[0].value == val)){ // ver NOTA 2
        if (item.type == "select-multiple") {
          item.options[0].text = name.value;
          item.options[0].value = 'new'+name.value;
          item.options[0].selected = true;
          item.options[1].text = txt;
          item.options[1].value = val;
          item.options[1].selected = false; // para el select-multiple
        } else {
          item.options[1].text = name.value;
          item.options[1].value = 'new'+name.value;
          item.options[1].selected = true;
          item.options[0].text = txt;
          item.options[0].value = val;
          item.options[0].selected = false; // para el select-multiple
          item.length=2;
        }
      }
    } else {
      if ((slen == tmp) || (is_mult==1)) {
        item.options[slen] = new Option(txt, val,false, false);
        change_pos = item.length-2;
        item.options[item.length-1].selected = false; // para el select-multiple
      } 
      else {
        change_pos = item.length-2;
        item.options[item.length-1].selected = false; // para el select-multiple
      }
      item.options[change_pos].text = name.value;
      item.options[change_pos].value = 'new'+'-'+item.options.length+'-'+name.value;
      item.options[change_pos].selected = true;
    }

    // Guardar las variables adicionales sobre esta nomenclatura.
    // El array add_vals contiene los valores y el add_vars las varaibles a las que hay que asignarlos.
    if (add_values != null) { 
      if (is_mult==1) {
        for (i = 0; i < add_values.length; i++) {
          fv = eval("document.popupform."+add_vars[i]);
          fv.value = fv.value+"-xxx-"+item.options.length+"-"+add_values[i];    
        }
      } else {
        for (i = 0; i < add_values.length; i++) {
          fv = eval("document.popupform."+add_vars[i]);
          fv.value = add_values[i];    
        }
      }
    }
  }
}


/*********************************************************************
 *                     getVar(), setVar() 
 * (from http://www.teaser.fr/~jcserre/js/vartk/)
 *
 * -If var name was defined, getVar will return its value/object
 * -If var name was not defined, the self. prefix prevent the
 * "undefined object" script error.
 * The returned value will then be the [undefined] value, but
 * on N2 this value behave in almost cases like an empty string.
 * So the isVar() function is provided to check the var before get
 *
 *********************************************************************/
function getVar(name) // return value of var "name"
{
	return eval( "self." + name ) // self. prefix required
}

function setVar(name, x) // define var "name" with value/object x
{
	eval( name + "= x" )
}

/*********************************************************************
 * prepare_new_vals
 *********************************************************************/


function prepareNewVals(newValNamesArray, valsArray) {
   var i;

   for (i = 0; i < newValNamesArray.length; i++) {
     valsArray[i] = getVar("document.selectform."+newValNamesArray[i]+".value");
   }
}


/*********************************************************************
 *                            saveNewValue
 * 
 * Guarda los valores introducidos en una ventana nueva a un select de 
 * la ventana principal. El formulario que se rellena para obtener
 * los nuevos valores es form_nom_input. El nombre del "form" con los
 * nuevos valores es "selectform" y el del "form" con el select que
 * se cambia es "popupform". El nombre del select dentro de este 
 * formulario es select_label+"_id".
 * (Como ejemplo ver bibliografy/edit-item)
 *********************************************************************/

function saveNewValue(select_label, new_val_names_array, new_vals_array, form_vars_array) {

  // Coger los valores de las variables adicionales (ver sendValue)
  prepareNewVals(new_val_names_array, new_vals_array);

  if (window.opener) {
  // Cambiar el select de la ventana principal.
  // En IE 5.x no se puede cambiar un select que no este en la misma ventana que
  // la función que intenta cambiarlo. Por esto es necesario llamar a una función
  // dentro de la ventana principal (donde esta el select que se intenta cambiar).
  // new_vals_array son los valores de las varables adicionales a name
  // form_vars_array son los nombres de las variables dentro del formualrio popupform
  // que reciben estos valores (ver sendValue).
  window.opener.sendValue(document.selectform.name,
                          new_vals_array,
                          document.selectform.opt_pos.value, document.selectform.is_mult.value,
                          eval("window.opener.document.popupform."+select_label+"_id"),
                          form_vars_array,
                          eval("window.opener.document.popupform."+select_label+"_num.value"));

  // Cerrar la ventana hijo. 
  window.close();
  }

}


/*********************************************************************
 *                    fillSelectFromArray
 *
 * Cambia las opciones de un select de acuerdo con la opción elegida 
 * en otro. 
 *
 * Original:  Jerome Caron (jerome.caron@globetrotter.net) 
 * form the JavaScript Source!! http://javascript.internet.com 
 *
 * Los ID-s de las opciones se guardan en itemArray[i][0],
 * el valor de la opción está en itemArray[i][1] y 
 * si el valor de selected (true o false) está en itemArray[i][2].
***********************************************************************/

function fillSelectFromArray(selectCtrl, itemArray, goodPrompt, badPrompt, defaultItem) {
  var i, j, k;
  var prompt;
  var select_one;
  var selected_value = 0;


  // empty existing items
  // i = selectCtrl.options.length;
  // selectCtrl.options[i] = null;
  for (i = selectCtrl.options.length-1; i >= 0; i--) {
    if (selectCtrl.options[i].selected && (selectCtrl.options[i].value > 0)) {
      selected_value = selectCtrl.options[i].value;
    }
    selectCtrl.options[i] = null;
  }

  prompt = (itemArray != null) ? goodPrompt : badPrompt;
  if (prompt == null) {
    j = 0;
  }
  else {
    selectCtrl.options[0] = new Option(prompt);
    j = 1;
  }

  select_one = 1;

  if (itemArray != null) {
   // add new items
   for (i = 0; i < itemArray.length; i++) {
     selectCtrl.options[j] = new Option(itemArray[i][0]);
     if (itemArray[i][1] != null) {
       selectCtrl.options[j].value = itemArray[i][1];
     }
     if (itemArray[i][2] != null) {
       select_one = 0;
       selectCtrl.options[j].selected = itemArray[i][2];
     }
     if ( selectCtrl.options[j].value == selected_value ) {
       selectCtrl.options[j].selected = true;
       select_one = 0;
     }
     j++;
   } 

   // select first item (prompt) for sub list
   if (select_one == 1) {
     selectCtrl.options[0].selected = true;
   }

 }
 else {
   selectCtrl.options[j] = new Option("--");
   selectCtrl.options[j].value = "0";
 }

}

/*********************************************************************
 *                    fillSelectFromArray2
 *
 * Lo mismo que fillSelectFromArray, sólo que añade al select sólo los
 * elementos del <itemArray> que cumplen (itemArray[i][2] == sel_id).
 * El valor de selected está en itemArray[i][3].
 *
 *********************************************************************/

function fillSelectFromArray2(selectCtrl, itemArray, sel_id, 
                             goodPrompt, badPrompt, defaultItem) {
  var i, j;
  var prompt;
  var select_first;

  select_first = 1;

  // empty existing items
  for (i = selectCtrl.options.length; i >= 0; i--) {
    selectCtrl.options[i] = null;
  }

  prompt = (itemArray != null) ? goodPrompt : badPrompt;
  if (prompt == null) {
    j = 0;
  }
  else {
    selectCtrl.options[0] = new Option(prompt);
    j = 1;
  }

  if (itemArray != null) {
   // add new items
   for (i = 0; i < itemArray.length; i++) {
     if (itemArray[i][2] == sel_id) {
       selectCtrl.options[j] = new Option(itemArray[i][0]);
       if (itemArray[i][1] != null) {
         selectCtrl.options[j].value = itemArray[i][1];
       }
       if (itemArray[i][3] != null) {
         selectCtrl.options[j].selected = itemArray[i][3];
         select_first = 0;
       }
       j++;
     }
   }

   // select first item (prompt) for sub list
   if (selectCtrl.length > 0 ) {
     if (select_first == 1) {
       selectCtrl.options[0].selected = true;
     }
   }
   else {
     selectCtrl.options[0] = new Option();
   }
 }

 return j // el número de opciones en el select
}


/*********************************************************************
 *                    fillSelectMultipleFromArray
 *
 * Cambia las opciones de un select de acuerdo con las opciones 
 * elegidas en otro teniendo en cuenta todas las opciones elegidas.
 *
 * Argumentos:
 * - arrayItems es el array que contiene todas las opciones para todas
 *	las posibles elecciones;
 * - selectParent es el "select multiple" cuyas opciones se utilizan 
 *	para obtener los elementos correspondientes del arrayItems
 * - selectCtrl es el select cuyas opciones se cambias por los 
 *	elementos de arrayItems que corresponden a las opcioenes 
 *	elegidas de selectParent.
 *
 * NOTA 1: Para que el Back muestre las opciones elegidas anteriormente, 
 * hay que guardar el selectCtrl.selectedIndex y despues de cambiar las
 * opciones de selectCtrl de acuerdo con las de selectParent, marcar como
 * selected la opción que corresponde al viejo selectCtrl.selectedIndex.
 *
 * NOTA 2: Para que la opción "niguno en concreto" siempre salga primera en
 * la lista con opciones, la cambio antes del sort y la vuelvo a recuperar
 * después.
 *
 * NOTA 3: Para marcar como selected los items correctos hay que usar 
 * el tercer elemento del array que corresponde a cara item.
 *********************************************************************/

function fillSelectMultipleFromArray(selectParent, selectCtrl, arrayItems) {
  var i, j, k;
  var prompt;
  var is_new = 1;
  var curr_sel_index = selectCtrl.selectedIndex; // NOTA 1
  var already_selected = 0;

  // empty existing items
  for (i = selectCtrl.options.length; i >= 0; i--) {
    selectCtrl.options[i] = null;
  }

  for(k = 0; k < selectParent.options.length; k++) {
    if (selectParent.options[k].selected) {
      if (is_new) {
        itemArray = new Array(arrayItems[k+1].length);
        itemArray = arrayItems[k+1];
        is_new = 0
      }
      else {
        itemArray = itemArray.concat(arrayItems[k+1]); 
      }
    }
  }

  // NOTA2 
  for (i = 0; i < itemArray.length; i++) {
    if (itemArray[i][0] == "ninguno en concreto" ) {
       itemArray[i][0] = 'AA'+itemArray[i][0];
    }
  } 

  itemArray = itemArray.sort()
 
  j = 0;
  for (i = 0; i < itemArray.length; i++) {
    if ((i == 0) || (itemArray[i][0] != itemArray[i-1][0])){
      if (itemArray[i][0] == "AAninguno en concreto") {
        selectCtrl.options[j] = new Option("ninguno en concreto");
      }
      else {
        selectCtrl.options[j] = new Option(itemArray[i][0]);
      }
      if (itemArray[i][1] != null) {
        selectCtrl.options[j].value = itemArray[i][1];
      }
      if (itemArray[i][2] == "true") {
        already_selected = 1;
        selectCtrl.options[j].selected = true; //NOTA 3
      }
      j++;
    }
  } 


  // select first item (prompt) for sub list
  if (selectCtrl.length > 0 ){
    //selectCtrl.options[0].selected = true;
    if ( already_selected == 0 && curr_sel_index >=0 && curr_sel_index < selectCtrl.options.length) {
      selectCtrl.options[curr_sel_index].selected = true; //NOTA 1
    }
  }
  else {
    selectCtrl.options[0] = new Option();
  }

  return j // el número de opciones en el select
}


/*********************************************************************
 *                   Check4AddFillSelect
 *
 * Comprueba si se ha elegido la opción "Añadir" y añade los datos nuevos 
 * en caso de que haya sido así.
 * Después cambia las opciones del select <selectCtrl> por los elementos
 * del array <itemArray>.
 *
***********************************************************************/

function Check4AddFillSelect(item, label, op_num, selectCtrl, itemArray, tbl_id, is_mult) { 

  CheckForAdd(item, label, tbl_id, is_mult); 

  fillSelectFromArray(selectCtrl, itemArray);   

  if (itemArray != null) {
    last = itemArray.length
  }
  else {
    last=0
  }

  if (last == 0) {
    selectCtrl.options[last] = new Option("--");
    selectCtrl.options[last].value = "0";
    last++;
  }
 
  /* Quitar la opción Añadir (por ahora)
   * op_num.value=last
   * selectCtrl.options[last] = new Option("< Añadir cliente >");
   * selectCtrl.options[last].value = "other";
   */

  /* selectCtrl.options[curr_sel_ind].selected = true; */

  /* OLD!
  op_num.value=last
  selectCtrl.options[last] = new Option("< Añadir cliente >");
  selectCtrl.options[last].value = "other";
  */

}

/*********************************************************************
 *                   Check4AddFillSelect2
 *
 * Lo mismo que Check4AddFillSelect, sólo que coge de <itemArray> solo 
 * los elemntos que tienen (itemArray[i][2] == sel_id)
 *
 * En el caso de que existe sólo la opciçon "Añadir", el onChange 
 * de donde se llama a esta función no se ejecuta porque como hay solo 
 * un elemento éste no cambia. Así que en estos caso añado una opción 
 * más "--" que se sustituirá por el elemento nuevo cuando se introduzca.
 ***********************************************************************/

function Check4AddFillSelect2(item, label, sel_id, op_num, selectCtrl, itemArray, tbl_id) { 
  var curr_sel_ind = selectCtrl.selectedIndex;

  CheckForAdd(item, label, tbl_id); 

  last = fillSelectFromArray2(selectCtrl, itemArray, sel_id);   

  if (last == 0) {
    selectCtrl.options[last] = new Option("--");
    selectCtrl.options[last].value = "0";
    last++;
  }
  /* Quito la opción Añadir, por ahora
   * op_num.value=last
   * selectCtrl.options[last] = new Option("< Añadir cliente >");
   * selectCtrl.options[last].value = "other";
   */

  //selectCtrl.options[curr_sel_ind].selected = true;
}


/*********************************************************************
 *                   AddLastSelOption
 *
 * Añade la opción "Añadir"+<what> al select <selectCtrl> y cambia el
 * valor de la variable que contiene el número de opciones.
 ***********************************************************************/

function AddLastSelOption(selectCtrl, opt_num, what) {
 
  last = opt_num.value;
  if (last == 0) {
    selectCtrl.options[last] = new Option("--");
    selectCtrl.options[last].value = "0";
    last++;
  } 

  selectCtrl.options[last] = new Option("< Añadir "+what+" >");
  selectCtrl.options[last].value = "other";

//  last++
//  opt_num.value = last;
}


/*********************************************************************
 *                   AddAllLastSelOptions
 *
 * Ejecuta AddLastSelOption para todas las nomenclaturas que tienen la
 * opción "Añadir".
 * Las nomenclaturas se dan como elementos del array <sel_list>. 
 * Cada elemento de <sel_list> es un array que contiene:
 *     - el nombre del select
 *     - el nombre de la variable que contiene el número de opciones
 *     - el texto que se añade despues de "Añadir"
 ***********************************************************************/

function AddAllLastSelOptions(form, sel_list) {
  var i;
  var sel_list;
  var sel_name, num_name;

  for (i = 0; i < sel_list.length; i++){ 
    sel_name = "form."+sel_list[i][0];
    num_name = "form."+sel_list[i][1];
    AddLastSelOption(eval(sel_name), eval(num_name), sel_list[i][2]);
  }

}


/*********************************************************************
 *                       visUpdateAllSelects
 *
 * Cambia el contenido de los selects que dependen de los valores de
 * otros selects y añade la opción "Añadir" a las nomenclaturas
 * de <sel_list>.
 * Esta función es específica para el módulo Visitas de Cardiva.
 *********************************************************************/
function visUpdateAllSelects(form, sel_list, clients, tbl_id, prod) {

  // Cambiar las opciones en clientes dependiendo de las opciones
  //  elegidas en hospitales y negocios.    

  Check4AddFillSelect2(form.h_id, "h", form.ng_id.selectedIndex, form.cl_num, form.cl_id, clients[form.h_id.selectedIndex], tbl_id);

  // Añadir la opción "Añadir" a las nomenclaturas de <sel_list>
  /* Desaactivo la opción Añadir 
   * AddAllLastSelOptions(form, sel_list);
   */

 if (form.rep_id.selectedIndex > 0) {
   fillSelectMultipleFromArray(form.rep_id, form.prod_id, prod);
 }
  
}


/*********************************************************************
 *                         CheckForAlert
 *
 *
 *********************************************************************/

function CheckForAlert(item, checkValue, alertText)
  {
    if (item.options[item.selectedIndex].text == checkValue) { 
      var val = window.alert(alertText)
     }

  }


/***********************************************************************
 *                           TwoListsUpdate
 *
 * Cambia las opciones en el select selectCtrl1 por los elementos del array arrayItems1[selectParentIndex]
 * y las opciones del select selectCtrl2 por las opciones de arrayItems2 que corresponden a las
 * opciones en arrayItems1[selectParentIndex].
 *
 * Por ejemplo, si selectParentIndex es el selectedIndex de un select que contiene lista de paises,
 * selectCtrl1 es el select con la lista de provincias, y selectCtrl2 es el select con la lista
 * de ciudades, la función two_lists_update va a rellenar selectCtrl1 con las provincias que
 * corresponden al país selectParentIndex, y el selectCtrl2 con la lista de las ciudades que
 * corresponden a todas las provincias del select selectCtrl1. 
 *
 * Así se podrá elegir directamente la ciudad sin tener que especifiar la provincia.
 *
 ***********************************************************************/

function TwoListsUpdate(selectCtrl1, selectCtrl2, selectParentIndex, arrayItems1, arrayItems2) {

  fillSelectFromArray(selectCtrl1, arrayItems1[selectParentIndex]);

  // empty existing items
  for (i = selectCtrl2.options.length; i >= 0; i--) {
    selectCtrl2.options[i] = null;
  }

  select_one = 1;
  k = 0;
  for (i = 0; i < arrayItems1[selectParentIndex].length; i++) { 
    finished = 0;
    // Si hay sólo una opción y ésta tiene id=0, el selectCtrl2 está vació.
    if (arrayItems1[selectParentIndex].length == 1) {
      if (arrayItems1[selectParentIndex][i][1] == 0) {
        selectCtrl2.options[0] = new Option(arrayItems1[selectParentIndex][i][0]);
        selectCtrl2.options[0].value = 0;
        finished = 1;
      }
    } 

    if (finished == 0) {
      for (j = 0; j < arrayItems2[i].length; j++) { 
       selectCtrl2.options[k] = new Option(arrayItems2[i][j][0]);
       if (arrayItems2[i][j][1] != null) {
         selectCtrl2.options[k].value = arrayItems2[i][j][1];
       }
       if (arrayItems2[i][j][2] != null) {
         select_one = 0;
         selectCtrl2.options[k].selected = arrayItems2[i][j][2];
       }
       k++;
      }
 
      // select first item (prompt) for sub list
      if (select_one == 1) {
        selectCtrl2.options[0].selected = true;
      }
    }
  }  

}

/***********************************************************************
 *                           calc_fld_sum
 *
 * Calcula la suma de varios valores.
 * Hay que tener en cuenta que los números en JavaScript se tratan de una 
 * forma especial, p.e. 0.05 + 0.01 = 0.060000000000000005
 * Por eso, hay que redondear la suma.
 * 
 * Para más información sobre el redondeo en JavaScript ver
 * Javascript Rounding, http://www.merlyn.demon.co.uk/js-round.htm
 ***********************************************************************/
function calc_fld_sum(fld_ar) {
  var i, val;
  var sum = 0;

  for (i = 0; i < fld_ar.length; i++) {
    val = parseFloat(fld_ar[i]);
    if (!isNaN(val)) {
      sum = sum + val; 
    }
  }

  sum = Math.round(sum*100000)/100000;
  return sum;
}

/*********************************************************************
*               AddNewItemOntheFly()
*
*  Shows the form to add a new nomenclature's item in a separate window.
*
*  Arguments:
*  <href> the URL of the script used to show the form.
*  <title> the window title
*
***********************************************************************/
function AddNewItemOntheFly(href, title)
{
   var window_name = title;
   var width=500;
   var height=550;

   try { 
     var an_window = window.open(href, window_name,'width='+width+',height='+height+',top=100 ,left=100,menubar=no,location=no,status=no,tollbar=no,scrollbars=yes');
     if (an_window.opener) {
       an_window.focus();
     }
   }
   catch (er) {
     window.location = href;
   } 
}

/*********************************************************************
*                            SaveNewItem()
*
*  Changes the focus to the parent window and calls the function to add
*  the new element to the select list.
*
*  Arguments:
*  <select_name> the name of the parent window's form select which have to be changed
*  <new_item_text> the text corresponding to the new select option.
*
*  NOTE: The child window MUST not be closed because the script that it calls
*  have to save the new item in the database. Afterwards the script redirects
*  to the script empty which closes the popup window
*  (see js/item-ae and js/empty).
*
***********************************************************************/
function SaveNewItem(select_name, new_item_text) {

  if (window.opener) { 
    window.blur();
    window.opener.focus();
    window.opener.ShowNewItem(eval("window.opener.document.popupform."+select_name), new_item_text);
  }

}

/*********************************************************************
*                         ShowNewItem()
*
*    Adds the new item to the list and marks it as selected.
*
* NOTE: This function must be called in the opener window as IE 5.x
* can only change select options that belong to the window that calls
* the Javascript function.
**********************************************************************/

function ShowNewItem(select_items, new_item_text)
{
   var last_item = select_items.length;
   var new_pos = last_item;

   select_items.options[new_pos] = new Option(new_item_text, "-1:"+new_item_text, true, true);

}

/*
* Compare two dates. Returns true if datefrom < dateto and shows an alert and returns false otherwise.
*/

function checkDates(datefrom_day, datefrom_month, datefrom_year, dateto_day, dateto_month, dateto_year)
{
  var is_ok = true;

  var dfrom = new Date(datefrom_day+"-"+datefrom_month+"-"+datefrom_year);
  alert("datefrom: "+dfrom);

  return is_ok;
}
