/**
 * Libreria: Validacion
 * Por     : Jose Antonio Rojas V.
 * e_mail  : jor@opensoft.cl
 * Fecha   : 01-12-1998
**/


// Constantes con tipos de campos (cada uno debe tener asociado una funcion de validacion)
var TYPE_STRING         = 0;
var TYPE_NUMBER         = 1;
var TYPE_NUMBERINT      = 2;
var TYPE_NUMBERFLOAT    = 3;
var TYPE_DATE           = 4;
var TYPE_EMAIL          = 5;
var TYPE_HTTP           = 6;
var TYPE_TIME           = 7;
var TYPE_NUMBERNATURAL  = 8;

// Constantes con separadores de cifras
var VAL_SEPARADOR_MILES     = ".";
var VAL_SEPARADOR_DECIMALES = ",";


// ======================================================================
// Funciones de validacion de tipos
// Obs: vacio, debe ser considerado como invalido, salvo en IsValid_Empty
// que precisamente retorna OK cuando el campo es vacio.
// ======================================================================
function LTrim(s){
  var s2    = "";
  var largo = s.length;

  for (var i = 0; (i<largo) && (s.substr(i,1)==" "); i++ )  ;
  for (         ;  i<largo                         ; i++ )  s2 = s2 + s.substr(i,1);
  return(s2);
}

function RTrim(s){
  var s2    = "";
  var largo = s.length;

  for (var i=largo-1; (i>=0) && (s.substr(i,1)==" "); i-- )  ;
  for (             ;  i>=0                         ; i-- )  s2 = s.substr(i,1) + s2;
  return(s2);
}


function IsValid_Empty( a_objeto ) {

  //"Combo"
  if (a_objeto.type == "select-one") {
    if (a_objeto.selectedIndex < 0)  return( true );
    return( ( RTrim( LTrim( a_objeto.options[a_objeto.selectedIndex].value ) ) == "" ) ? true : false );
  }

  //"Listbox"
  if (a_objeto.type == "select-multiple") {
    if (a_objeto.selectedIndex < 0)  return( true );
    return( ( RTrim( LTrim( a_objeto.options[a_objeto.selectedIndex].text ) ) == "" ) ? true : false );
  }

  //"Editbox"
  //return( ( RTrim( LTrim( a_objeto.value ) ) == "" ) ? true : false )
  return( ( a_objeto.value == "" ) ? true : false )
}


function IsValid_String( a_objeto ) {
  //cualquier cosa es un string, asi que no valida nada
  return( true );
  //return( !IsValid_Empty( a_objeto ) )
}


function IsValid_Number( a_objeto ) {
  //Vacio
  if( IsValid_Empty( a_objeto ) )  return( true );

  //Retorna
  return( IsValid_NumberInt( a_objeto ) || IsValid_NumberFloat( a_objeto ) );
}


function IsValid_NumberInt( a_objeto ) {
  //Vacio
  if( IsValid_Empty( a_objeto ) )  return( true );

  //Strings de expresiones regulares
  var ExpresionRegular_Str = "^(([0-9]+)|([0-9]{1,3}(\\" + VAL_SEPARADOR_MILES + "[0-9][0-9][0-9])*))$"

  //Objetos expresiones regulares
  var ExpresionRegular = new RegExp( ExpresionRegular_Str );

  //Retorna
  if (a_objeto.type == "select-one") {
    return( ExpresionRegular.test( a_objeto.options[a_objeto.selectedIndex].value ) );
  }
  else if (a_objeto.type == "select-multiple") {
    return( ExpresionRegular.test( a_objeto.options[a_objeto.selectedIndex].value ) );
  }
  else
    return( ExpresionRegular.test( a_objeto.value ) );
}


function IsValid_NumberFloat( a_objeto ) {
  //Vacio
  if( IsValid_Empty( a_objeto ) )  return( true );

  //Strings de expresiones regulares
  var ExpresionRegular_Str = "^(-)?(([0-9]+)|(([0-9]+)\\" + VAL_SEPARADOR_DECIMALES + "[0-9]+)|([0-9]{1,3}(\\" + VAL_SEPARADOR_MILES + "[0-9][0-9][0-9])*\\" + VAL_SEPARADOR_DECIMALES + "[0-9]+))$"

  //Objetos expresiones regulares
  var ExpresionRegular = new RegExp( ExpresionRegular_Str );

  //Retorna
  if (a_objeto.type == "select-one") {
    return( ExpresionRegular.test( a_objeto.options[a_objeto.selectedIndex].text ) );
  }
  else if (a_objeto.type == "select-multiple") {
    return( ExpresionRegular.test( a_objeto.options[a_objeto.selectedIndex].text ) );
  }
  else
    return( ExpresionRegular.test( a_objeto.value ) );
}


function IsValid_Date( a_objeto ) {
  //Vacio
  if( IsValid_Empty( a_objeto ) )  return( true );

  //Strings de expresiones regulares
  var meses                = "01|02|03|04|05|06|07|08|09|10|11|12";
  var dias                 = "01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31";
  var ExpresionRegular_Str = "^("+dias+")\\/("+meses+")\\/[0-9][0-9][0-9][0-9]$"

  //Objetos expresiones regulares
  var ExpresionRegular = new RegExp( ExpresionRegular_Str );

  //Evaluar expresiones
  var resultado;
  var valorObjeto;
  var largoObjeto;

  if (a_objeto.type == "select-one") {
    resultado = ExpresionRegular.test( a_objeto.options[a_objeto.selectedIndex].text );
    valorObjeto = a_objeto.options[a_objeto.selectedIndex].text;
    largoObjeto = valorObjeto.length;
  }
  else if (a_objeto.type == "select-multiple") {
    resultado = ExpresionRegular.test( a_objeto.options[a_objeto.selectedIndex].text );
    valorObjeto =a_objeto.options[a_objeto.selectedIndex].text;
    largoObjeto = valorObjeto.length;
  }
  else {
    resultado = ExpresionRegular.test( a_objeto.value );
    valorObjeto = a_objeto.value;
    largoObjeto = valorObjeto.length;
  }

  if ( resultado ){
    var largo= largoObjeto;
    var dia  = valorObjeto.substr(0,2);
    var mes  = valorObjeto.substr(3,2);
    var anno = valorObjeto.substr(largo-4,4);
    if (mes == "02") {
      //Si es divisible por 4 y no por 100 a no ser que
      //          sea div por 400 -> 29 2000 si 1900 no
      var bisiesto = (((anno%4 == 0) & (anno%100 != 0)) | (anno%400 == 0))?true:false;
      resultado = (bisiesto)?(eval(dia+"<30")):(eval(dia+"<29"))
    }
    //Revisa los dias 31 del mes
    else if (dia=="31" && ( (eval(mes+"<8")) && (mes%2==0) || (eval(mes+">7")) && (mes%2==1)))
      resultado = false;
  }

  if (Number(anno)<1900)
    resultado = false

  //Retorna
  return( resultado );
}


function IsValid_EMail( a_objeto ) {
  //Vacio
  if( IsValid_Empty( a_objeto ) )  return( true );

  //Strings de expresiones regulares: username y hostname
  var ExpresionRegular1_Str = "(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)";
  var ExpresionRegular2_Str = "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$";

  //Objetos expresiones regulares
  var ExpresionRegular1 = new RegExp( ExpresionRegular1_Str );
  var ExpresionRegular2 = new RegExp( ExpresionRegular2_Str );

  //Retorna
  if (a_objeto.type == "select-one") {
    return( !ExpresionRegular1.test( a_objeto.options[a_objeto.selectedIndex].text )  &&
             ExpresionRegular2.test( a_objeto.options[a_objeto.selectedIndex].text ) );
  }
  else if (a_objeto.type == "select-multiple") {
    return( !ExpresionRegular1.test( a_objeto.options[a_objeto.selectedIndex].text )  &&
             ExpresionRegular2.test( a_objeto.options[a_objeto.selectedIndex].text ) );
  }
  else
    return( !ExpresionRegular1.test( a_objeto.value )  &&
             ExpresionRegular2.test( a_objeto.value ) );
}


function IsValid_HTTP( a_objeto ) {
  //Vacio
  if( IsValid_Empty( a_objeto ) )  return( true );

  //Strings de expresiones regulares
  var alphadigit = "[A-Za-z0-9]";
  var safe       = "[\\$\\-\\_\\.\\+]";
  var hex        = "[0-9A-F-a-f]";
  var extra      = "[\\!\\*\\'\\(\\)\\,]";
  var reserved   = "[\\;\\/\\?\\:\\@\\&\\=]";
  var escape     = "\\%"+hex+hex;
  var unreserved = "([A-Za-z0-9]|"+safe+"|"+extra+")";
  var uchar      = "("+unreserved+"|"+escape+")";
  var xchar      = "("+unreserved+"|"+reserved+"|"+escape+")";

  var domainlabel = "("+alphadigit+"|("+alphadigit+"("+alphadigit+"|\\-)*"+alphadigit+"))";
  var toplabel    = "([A-Za-z]|([A-Za-z]("+alphadigit+"|\\-)*"+alphadigit+"))";
  var hostname    = "("+domainlabel+"\\.)*"+toplabel;
  var hostnumber  = "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+";
  var host        = "("+hostname+"|"+hostnumber+")";
  var port        = "[0-9]+";


  var search      = "("+uchar+"|[\\;\\:\\@\\&\\=])*";
  var hsegment    = "("+uchar+"|[\\;\\:\\@\\&\\=])*";
  var hpath       = "("+hsegment+"(\\/"+hsegment+")*)";
  var hostport    = "("+host+"(\\:"+port+")?)";
  var httpurl     = "(http\\:\\/\\/)?"+hostport+"(\\/"+hpath+"(\\?"+search+")?)?";

  var user        = "("+uchar+"|[\\;\\?\\&\\=])*";
  var password    = "("+uchar+"|[\\;\\?\\&\\=])*";
  var login       = "("+user+"(\\:"+password+")?\\@)?";
  var fsegment    = "("+uchar+"|[\\?\\:\\@\\&\\=])*";
  var fpath       = "("+fsegment+"(\\/"+fsegment+")*)";
  var ftptype     = "[AIDaid]";
  var ftpurl      = "ftp\\:\\/\\/"+login+"(\\/"+fpath+"(\\;type\\="+ftptype+")?)?";

  var fileurl     = "file\\:\\/\\/("+host+"|localhost)?\\/"+fpath;

  var url         = "^"+httpurl+"|"+ftpurl+"|"+fileurl+"$";

  var ExpresionRegular_Str = url;

  //Objetos expresiones regulares
  var ExpresionRegular = new RegExp( ExpresionRegular_Str );

  //Retorna
  if (a_objeto.type == "select-one") {
    return( ExpresionRegular.test( a_objeto.options[a_objeto.selectedIndex].text ) );
  }
  else if (a_objeto.type == "select-multiple") {
    return( ExpresionRegular.test( a_objeto.options[a_objeto.selectedIndex].text ) );
  }
  else
    return( ExpresionRegular.test( a_objeto.value ) );
}


function IsValid_Time( a_objeto ) {
  //Vacio
  if( IsValid_Empty( a_objeto ) )  return( true );

  //Strings de expresiones regulares
  var horas                = "(00|01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23)";
  var minutos              = "([0-5])[0-9]";
  var segundos             = "([0-5])[0-9]";
  //var ExpresionRegular_Str = "^"+horas+":"+minutos+":"+segundos+"$"
  var ExpresionRegular_Str = "^"+horas+":"+minutos+"$"

  //Objetos expresiones regulares
  var ExpresionRegular = new RegExp( ExpresionRegular_Str );

  //Evaluar expresiones
  var resultado;
  var valorObjeto;
  var largoObjeto;

  if (a_objeto.type == "select-one") {
    resultado = ExpresionRegular.test( a_objeto.options[a_objeto.selectedIndex].text );
    valorObjeto = a_objeto.options[a_objeto.selectedIndex].text;
    largoObjeto = valorObjeto.length;
  }
  else if (a_objeto.type == "select-multiple") {
    resultado = ExpresionRegular.test( a_objeto.options[a_objeto.selectedIndex].text );
    valorObjeto =a_objeto.options[a_objeto.selectedIndex].text;
    largoObjeto = valorObjeto.length;
  }
  else {
    resultado = ExpresionRegular.test( a_objeto.value );
    valorObjeto = a_objeto.value;
    largoObjeto = valorObjeto.length;
  }

  if ( resultado ){
    var largo= largoObjeto;
    var hora  = valorObjeto.substr(0,2);
    var min   = valorObjeto.substr(3,2);
    var seg   = valorObjeto.substr(largo-4,4);
    //resultado = false;
  }
  //Retorna

  return( resultado );

}

function IsValid_NumberNatural( a_objeto ){
  if( IsValid_Empty( a_objeto ) )   return( true );
  //si tiene espacios, es error
  if( a_objeto.value != "" && RTrim( LTrim( a_objeto.value ) ) == "")   return( false );
  if( isNaN(a_objeto.value) )       return( false );
  if( parseInt(a_objeto.value )< 1 )return( false );
  return( true );
}

function IsValid_DV( a_objetoRut, a_objetoDV ) {
  if( IsValid_Empty( a_objetoRut ) || IsValid_Empty( a_objetoDV ) )  return( true );
  l_DV = DigitoVerificadorRut( a_objetoRut );
  l_DVCampo = a_objetoDV.value;
  l_DVCampo = l_DVCampo.toUpperCase();

  if ( l_DVCampo != l_DV ) //Si el digito no corresponde retorno false
    return( false );
  //Retorna
  return( true )
}

function DigitoVerificadorRut( a_objeto ) {
  var rut = 0;
  var s = 0;
  var l_dv = "";

  rut = a_objeto.value;
  for (i=2; i< 8; i++){
    s = s + ( rut % 10 ) * i;
    rut = (rut - ( rut % 10 )) / 10;
  }
  s = s + ( rut % 10 ) * 2;
  rut = (rut - ( rut % 10 )) / 10;
  s = s + ( rut % 10 ) * 3;
  rut = (rut - ( rut % 10 )) / 10;
  s = 11 - ( s % 11 );
  if ( s == 10 )
     l_dv = "K";
  else
     if ( s == 11 )
        l_dv = "0"
     else
        l_dv = s + "";   // Se convierte el numero s a string
  return( l_dv );
}

//Construye arreglo con funciones de validacion
//Obs: deben estar en el mismo orden que el dado por las constantes de tipos!
var IsValid = new Array(
                         IsValid_String     , IsValid_Number, IsValid_NumberInt     ,
                         IsValid_NumberFloat, IsValid_Date  , IsValid_EMail         ,
                         IsValid_HTTP       , IsValid_Time  , IsValid_NumberNatural
                        );


// ================================
// Funciones generales
// ================================

function Campo( a_objeto, a_nombre, a_tipo, a_obligatorio ) {
  this.length        = 4;
  this.Objeto        = a_objeto;
  this.Nombre        = a_nombre;
  this.Tipo          = a_tipo;
  this.EsObligatorio = a_obligatorio;
}


//Arreglo con campos a validar
var g_CamposDeFormulario = new Array();


function ValidaCampos( a_Campos ) {

  //Variables que almacenan los nombres de campos con error y mensaje de error general
  var l_ErrorFaltan = "";
  var l_ErrorTipo   = "";
  var l_ErrorLogica = "";
  var l_Mensaje     = "";

  //Recorre campos del arreglo dado
  for( var i = 0; i < a_Campos.length; i++ ) {

    //Si campo no existe se lo salta
    if( !a_Campos[ i ].Objeto )  continue;

    //Si el campo es obligatorio y esta vacio, significa que hay error
    if ( a_Campos[ i ].EsObligatorio && IsValid_Empty( a_Campos[ i ].Objeto ) )  {

      if( l_ErrorFaltan != "" ) l_ErrorFaltan += ",";
      l_ErrorFaltan += "\n  - " + a_Campos[ i ].Nombre;

      //Continua con siguiente campo
      continue;
    }

    //Verifica error de tipo
    if( !IsValid[ a_Campos[ i ].Tipo ]( a_Campos[ i ].Objeto ) )  {
      if( l_ErrorTipo   != "" ) l_ErrorTipo   += ",";
      l_ErrorTipo   += "\n  - " + a_Campos[ i ].Nombre;
    }
  }

  //Mensaje de error: Faltantes
  if( l_ErrorFaltan != "" ) {
    if( l_Mensaje != "" ) l_Mensaje += "\n\n";
    l_Mensaje += THIS_VALIDACION_MENSAJE_ERROR_CAMPOS_FALTANTES + l_ErrorFaltan + "."
  }

  //Mensaje de error: Tipos
  if( l_ErrorTipo   != "" ) {
    if( l_Mensaje != "" ) l_Mensaje += "\n\n";
    l_Mensaje += THIS_VALIDACION_MENSAJE_ERROR_CAMPOS_TIPOS + l_ErrorTipo   + "."
  }

  //Mensaje de error: Logica
  if( window.ValidaLogica )  {
    l_ErrorLogica = ValidaLogica();
    if( l_ErrorLogica != "" ) {
      if( l_Mensaje != "" ) l_Mensaje += "\n\n";
      l_Mensaje += THIS_VALIDACION_MENSAJE_ERROR_LOGICA + l_ErrorLogica + "."
    }
  }

  //Retorna string con errores de validaciones
  return( l_Mensaje );
}


function ValidaFormulario() {

  //Valida los campos y guarda mensaje en variable
  var l_MensajeValidacion = ValidaCampos( g_CamposDeFormulario );

  //Si no hay error ejecuta submit antiguo y retorna
  if( l_MensajeValidacion == "" )  return( true );

  //Muestra mensaje
  alert( l_MensajeValidacion );

  //Retorna
  return( false );
}


//Cambia metodos de submit del formulario para anteponer la validacion
//document.forms[0].onsubmitOLD = document.forms[0].onsubmit;
//document.forms[0].onsubmit    = new Function( "if( !ValidaFormulario() ) return(false); return( this.onsubmitOLD() );" );


function InstalaValidacion( a_obj ) {

	a_obj.onclickOLD = a_obj.onclick;
  a_obj.onclick    = new Function( "if( !ValidaFormulario() ) return(false); return( this.onclickOLD() );" );
}

function DesinstalaValidacion( a_obj )  {
  if( a_obj.onclickOLD )  a_obj.onclick = a_obj.onclickOLD;
}

//Esta funcion permite instalar la validacion sobre un tag A basado en el id del link.
//parametros;
//  a_id  : id del link
//Ej:
//  tag                      : <A href="javascript:;" id="Buscar" onclick="...">
//  instalacion de validacion: InstalaValidacionEnLinkPorId( "Buscar" )
//
function InstalaValidacionEnLinkPorId( a_id ) {

  //Busca link donde href sea texto dado
  for( var i = document.links.length - 1; i >= 0; i-- )
    if( document.links[i].id == a_id )  break;

  //Si lo encuentra, instala la validacion
  if( i >= 0 )  InstalaValidacion( document.links[ i ] );
}



//Esta funcion permite instalar la validacion sobre un tag A. Se asume que
//el "nombre" del tag se indica en el atributo href. Esto se hace asi para
//tener una forma unica de recuperar el objeto tag A en Explorer y Netscape.
//Ej:
//  tag                      : <A href="Buscar" onclick="...">
//  instalacion de validacion: InstalaValidacionEnLinkPorHREF( "Buscar" )
//
function InstalaValidacionEnLinkPorHREF( a_txt ) {

  //Busca link donde href sea texto dado
  for( var i = document.links.length - 1; i >= 0; i-- )
    if( document.links[i].href.indexOf( a_txt ) == ( document.links[i].href.length - a_txt.length ) )
      break;

  //Si lo encuentra, instala la validacion
  if( i >= 0 )  InstalaValidacion( document.links[ i ] );
}


function validaCreaCampo( a_obj, a_label, a_type, a_flagObligatorio ) {
  g_CamposDeFormulario[ g_CamposDeFormulario.length ] = new Campo( a_obj, a_label, a_type, a_flagObligatorio );
}

function DestacaCamposObligatorios() {

  //Verifica browser
  if( !document.all )  return;

  //Recorre campos a validar
  for( var i = 0; i < g_CamposDeFormulario.length; i++ )  {

    //Si no es obligatorio se lo salta
    if( !g_CamposDeFormulario[ i ].EsObligatorio )  continue;

    //Si campo no existe se lo salta
    if( !g_CamposDeFormulario[ i ].Objeto        )  continue;

    //Lo destaca si es obligatorio
    g_CamposDeFormulario[ i ].Objeto.style.borderColor = "#EF7523";
  }
}


//------------------------------ mensajes ---------------------------------------------


//inicializa los mensajes que se mostraran al usuario en este js
//WOLF
//OBS: la funcion "validacionMesajes_load" carga los mensajes que se mostraran al usuario en este js
//     pero su funcion principal que quitar la dependencia de esta libreria con "idioma.js"
//      1ro- Se intentaran cargar los mensajes desde la libreria "idioma.js"
//      2do- Si ocurre una exception (como que la libreria idioma.js no este disponible) se cargaran los mensajes originales de este js

function validacionMesajes_load(){
  //mensajes multi-idioma...
  try{
    //IMPORTANTE: arrIdiomaMensaje ----> ver: "src/website/common/asp/idioma.js"
    idiomaId = getIdiomaId()

    THIS_VALIDACION_MENSAJE_ERROR_CAMPOS_FALTANTES = arrIdiomaMensaje[idiomaId][ VALIDACION_MENSAJE_ERROR_CAMPOS_FALTANTES ]
    THIS_VALIDACION_MENSAJE_ERROR_CAMPOS_TIPOS     = arrIdiomaMensaje[idiomaId][ VALIDACION_MENSAJE_ERROR_CAMPOS_TIPOS     ]
    THIS_VALIDACION_MENSAJE_ERROR_LOGICA           = arrIdiomaMensaje[idiomaId][ VALIDACION_MENSAJE_ERROR_LOGICA           ]
  }
  //mensajes "originales" libreria...
  catch(e){
    THIS_VALIDACION_MENSAJE_ERROR_CAMPOS_FALTANTES = "Los siguientes campos son obligatorios debe ingresarlos: "
    THIS_VALIDACION_MENSAJE_ERROR_CAMPOS_TIPOS     = "Los valores ingresados en los siguientes campos no son válidos: "
    THIS_VALIDACION_MENSAJE_ERROR_LOGICA           = "Se han detectado los siguientes errores de lógica: "
  }
}


//Inicializa libreria
window.onloadOld_Validacion = window.onload;
window.onload = function() {

  //Ejecuta evento onload original
  if( window.onloadOld_Validacion ) window.onloadOld_Validacion();

  //inicializa los mensajes que se mostraran al usuario en este js
  validacionMesajes_load()

  //Instala validacion en los botones que tengar alguno de los siguientes textos
  var textos = "Guardar~Grabar~Aceptar~Aplicar";
  for( var i = 0; i < document.forms[0].elements.length; i++ ) {
    if( document.forms[0].elements[i].type != "button" )  continue;
    if( textos.indexOf( LTrim( RTrim( document.forms[0].elements[i].value ) ), 0 ) == -1 )  continue;
    InstalaValidacion( document.forms[0].elements[i] );
  }

  //Inicializa valores del arreglo con campos a validar
  if( window.defineCamposValida )  window.defineCamposValida();

  //Marca campos obligatorios
  //Desde el 26/04/2001 esta funcion ya no se invoca automaticamente
  //DestacaCamposObligatorios();
}



//funcion:    radioSelectedIndex
//parametro:  obj_radioButton, objeto, input del tipo radiobutton
//Retorna:    entero, numero de opcion seleccionada, si no hay ninguna -1
//Descripcion:funcion desarrollada para validar que un radiobutton no esté vacio,
//            es equivalente a la propiedad selectedIndex de los select
//por:        joros
//fecha:      12/01/2004

function radioSelectedIndex(obj_radioButton){
  var optionSelected, idx
  optionSelected = - 1

  for (idx=0; idx<obj_radioButton.length; idx++)
    if (obj_radioButton[idx].checked) optionSelected = idx

  return optionSelected

}


//Descripcion: Formatea numeros con separador de miles con decimales de la forma:
//	       xxxxxxxx.xx ==> xx.xxx.xxx,xx
//Por	     : VSR
//Fecha      : 25/05/2005
function formatNumberSeparadorMiles(numero){
  var num = parseInt(Math.round(numero*100));
  num = num.toString()+"";
  var largo = num.length;
  var cad   = "";
  var signo = "";

  //Nos aseguramos que no existen caracteres no numéricos
  if (parseFloat(num)+"" != "NaN" && numero!=0){
    if (parseFloat(num)<0){
      num=num.substr(1,largo-1);
      signo="-";
    }
    largo = num.length;
    if (largo==1) cad=",0"+num;
    else //if (num.substr(largo-2,2)!='00')
    cad = ","+num.substr(largo-2,2)+cad;
    num= num.substr(0, largo-2);
    largo=num.length;
    if (largo<1) cad="0"+cad;
    while (largo>3){
       cad = "."+num.substr(largo-3, 3)+cad;
       num = num.substr(0, largo-3);
       largo=num.length;
    }
    cad = signo+num+cad;
    return cad;
  }
  else{
    return "0,00";
  }
}

//Descripcion: Desformatea numeros con separador de miles con decimales de la forma:
//	       xx.xxx.xxx,xx ==> xxxxxxxx.xx
//Por	     : VSR
//Fecha      : 25/05/2005
function unformatNumberSeparadorMiles(numero){
  if (numero=='0,00'||numero=='0,0'||numero=='0')
  return 0;
  if (numero.charAt(0)=="0") numero=numero.substr(1,numero.length-1);
  var cad="";
  var signo="";
  var largo=numero.length;
  var indice=numero.indexOf(",");
  var indice2=numero.indexOf(".");

  //nos aseguramos de que no es un numero ya
  if (indice==-1 && indice2==-1)
    return numero;
  else{
    if (numero.substr(0,1)=="-"){
      numero=numero.substr(1,largo-1);
      signo="-";
      largo=numero.length;
      indice=numero.indexOf(",");
      indice2=numero.indexOf(".");
    }
    if ((largo-indice2)>3){
      if (indice>=0){
        cad = "."+numero.substr(indice+1,largo-indice)+cad;
        numero=numero.substr(0,indice);
      }
      if (indice==0){
        cad = "0"+cad;
        numero="";
      }
      largo=numero.length;
      while (largo>3){
        cad =numero.substr(largo-3,3)+cad;
        indice2=numero.indexOf(".");
        if (indice2>=0){
          numero=numero.substr(0,largo-4);
        }
        else{
          numero=numero.substr(0,largo-3);
        }
        largo=numero.length;
      }
      cad=signo+numero+cad;
      return cad;
    }
    else return numero;
 }
}
