 function replaceChars(entry,out,add) {
	temp = "" + entry;
	while (temp.indexOf(out)>-1) {
		pos= temp.indexOf(out);
		temp = "" + (temp.substring(0, pos) + add + 
		temp.substring((pos + out.length), temp.length));
	}
	return temp;
 }
 
 function isAlfaNumerico(strString) {
   var strValidChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
   var strChar;
   var blnResult = true;
   
   for (i = 0; i < strString.length && blnResult == true; i++) {
	  strChar = strString.charAt(i);
	  if (strValidChars.indexOf(strChar) == -1)
		 blnResult = false;
   }

   if (typeof strString=="undefined") blnResult = false;

   return blnResult;
}

 function isDouble(strString) {
   var strValidChars = "0123456789.,";
   var strChar;
   var blnResult = true;
   var puntos = 0;
   
   for (i = 0; i < strString.length && blnResult == true; i++) {
	  strChar = strString.charAt(i);
	  if (strValidChars.indexOf(strChar) == -1)
		 blnResult = false;
	  if (strChar == ".")
	  	puntos++;
   }

   if (typeof strString=="undefined") blnResult = false;

   if (puntos>1) blnResult = false;

   return blnResult;
}

function isNumeric(strString) {
   var strValidChars = "0123456789.-";
   var strChar;
   var blnResult = true;

   for (i = 0; i < strString.length && blnResult == true; i++) {
	  strChar = strString.charAt(i);
	  if (strValidChars.indexOf(strChar) == -1)
		 blnResult = false;
   }
   return blnResult;
}

function isInteger(strString) {
   var strValidChars = "0123456789-";
   var strChar;
   var blnResult = true;

   for (i = 0; i < strString.length && blnResult == true; i++) {
	  strChar = strString.charAt(i);
	  if (strValidChars.indexOf(strChar) == -1)
		 blnResult = false;
   }
   return blnResult;
}

function isNatural(strString) {
   var strValidChars = "0123456789";
   var strChar;
   var blnResult = true;

   for (i = 0; i < strString.length && blnResult == true; i++) {
	  strChar = strString.charAt(i);
	  if (strValidChars.indexOf(strChar) == -1)
		 blnResult = false;
   }
   return blnResult;
}

// Lo contrario, quitar todos los caracteres que no estan en "bag" de "s"
function stripCharsNotInBag (s, bag)
{   var i;
    var returnString = "";
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }

    return returnString;
}

function dejaSoloNumeros (s){
	var valor = stripCharsNotInBag (s, '0123456789');
	return valor;
}

function isHex(strString) {
   var strValidChars = "0123456789ABCDEFabcdef";
   var strChar;
   var blnResult = true;

   for (i = 0; i < strString.length && blnResult == true; i++) {
	  strChar = strString.charAt(i);
	  if (strValidChars.indexOf(strChar) == -1)
		 blnResult = false;
   }
   return blnResult;
}


function checkDecimals(fieldName, fieldValue) {

	decallowed = 2;  // how many decimals are allowed?

	var blnResult = true;
	if (isNaN(fieldValue) || fieldValue == "") {
		alert("Oops!  That does not appear to be a valid number.  Please try again.");
		fieldName.select();
		fieldName.focus();
		blnResult = false;
	} else {
		if (fieldValue.indexOf('.') == -1) fieldValue += ".";
		dectext = fieldValue.substring(fieldValue.indexOf('.')+1, fieldValue.length);

		if (dectext.length > decallowed) {
			alert ("Oops!  Please enter a number with up to " + decallowed + " decimal places.  Please try again.");
			fieldName.select();
			fieldName.focus();
			blnResult = false;
		}
   }
   return blnResult;
}


function trim(s) {
	return s.replace( /\s*$/, "" ).replace( /^\s*/, "" );
}

function isEmail(email) {
	re = /[a-zA-Z0-9\.-_]*@[a-zA-Z0-9-_]{1,}\.[a-zA-Z0-9-_]{1,}[\.a-zA-Z0-9-_]{0,}[\w]$/;
    return ( re.test(email) && email.indexOf("..")==-1 ? true : false );
}

/********************************************************/
/* Formato para la fecha                                */
/********************************************************/
// Check browser version
var isNav4 = false, isNav5 = false, isIE4 = false
var strSeperator = "/";
// If you are using any Java validation on the back side you will want to use the / because
// Java date validations do not recognize the dash as a valid date separator.

var vDateType = 3; // Global value for type of date format
//                1 = mm/dd/yyyy
//                2 = yyyy/dd/mm  (Unable to do date check at this time)
//                3 = dd/mm/yyyy

var vYearType = 4; //Set to 2 or 4 for number of digits in the year for Netscape
var vYearLength = 2; // Set to 4 if you want to force the user to enter 4 digits for the year before validating.

var err = 0; // Set the error code to a default of zero

//alert(navigator.appName+"  /"+navigator.appVersion.substring(0,1)+"/");
if(navigator.appName == "Netscape")
{
   if ( eval(navigator.appVersion.substring(0,1)) < 5)
   {
      isNav4 = true;
      isNav5 = false;
	}
   else
   if ( eval(navigator.appVersion.substring(0,1)) > 4)
   {
      isNav4 = false;
      isNav5 = true;
	}
}
else
{
   isIE4 = true;
}

function DateFormat2(vDateName, vDateValue, e, dateCheck, dateType)  {

vDateType = dateType;

// vDateName = object name
// vDateValue = value in the field being checked
// e = event
// dateCheck
//       True  = Verify that the vDateValue is a valid date
//       False = Format values being entered into vDateValue only
// vDateType
//       1 = mm/dd/yyyy
//       2 = yyyy/mm/dd
//       3 = dd/mm/yyyy


   //Enter a tilde sign for the first number and you can check the variable information.
   if (vDateValue == "~")
   {
      alert("AppVersion = "+navigator.appVersion+" \nNav. 4 Version = "+isNav4+" \nNav. 5 Version = "+isNav5+" \nIE Version = "+isIE4+" \nYear Type = "+vYearType+" \nDate Type = "+vDateType+" \nSeparator = "+strSeperator);
      vDateName.value = "";
      vDateName.focus();
      return true;
   }
   var whichCode = (window.Event) ? e.which : e.keyCode;

   // Check to see if a seperator is already present.
   // bypass the date if a seperator is present and the length greater than 8
   if (vDateValue.length > 8 && (isNav4 || isNav5))
   {
      if ((vDateValue.indexOf("-") >= 1) || (vDateValue.indexOf("/") >= 1))
         return true;
   }

   //Eliminate all the ASCII codes that are not valid
   var alphaCheck = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/-";
   if (alphaCheck.indexOf(vDateValue) >= 1)
   {
      if (isNav4 || isNav5)
      {
         vDateName.value = "";
         vDateName.focus();
         vDateName.select();
         return false;
      }
      else
      {
         while ( vDateName.value!="" && "0123456789/".indexOf(vDateName.value.substr((vDateValue.length-1)))==-1){
           vDateName.value = vDateName.value.substr(0, (vDateValue.length-1));
         }
	 return false;
      }
   }
   if (whichCode == 8 || whichCode==13) //Ignore the Netscape value for backspace. IE has no value
      return false;
   else
   {
      //Create numeric string values for 0123456789/
      //The codes provided include both keyboard and keypad values
      //var strCheck = '47,48,49,50,51,52,53,54,55,56,57,58,59,95,96,97,98,99,100,101,102,103,104,105';
      var strCheck = ',47,48,49,50,51,52,53,54,55,56,57,58,59,95,96,97,98,99,100,101,102,103,104,105,';
      if (strCheck.indexOf(","+whichCode+",") != -1)
      {
         if (isNav4 || isNav5)
         {
            if (((vDateValue.length < 6 && dateCheck) || (vDateValue.length == 7 && dateCheck)) && (vDateValue.length >=1))
            {
               alert("Fecha no v�lida\nIntroduzcala de nuevo");
               vDateName.value = "";
               vDateName.focus();
               vDateName.select();
               return false;
            }
            if (vDateValue.length == 6 && dateCheck)
            {
               var mDay = vDateName.value.substr(2,2);
               var mMonth = vDateName.value.substr(0,2);
               var mYear = vDateName.value.substr(4,4)

               //Turn a two digit year into a 4 digit year
               if (mYear.length == 2 && vYearType == 4)
               {
                  var mToday = new Date();

                  //If the year is greater than 30 years from now use 19, otherwise use 20
                  var checkYear = mToday.getFullYear() + 30;
                  var mCheckYear = '20' + mYear;
                  if (mCheckYear >= checkYear)
                     mYear = '19' + mYear;
                  else
                     mYear = '20' + mYear;
               }
               var vDateValueCheck = mMonth+strSeperator+mDay+strSeperator+mYear;

               if (!dateValid(vDateValueCheck))
               {
                  alert("Fecha no v�lida\nIntroduzcala de nuevo");
                  vDateName.value = "";
                  vDateName.focus();
                  vDateName.select();
                  return false;
		         }
               return true;

            }
            else
            {
               // Reformat the date for validation and set date type to a 1


               if (vDateValue.length >= 8  && dateCheck)
               {
                  if (vDateType == 1) // mmddyyyy
                  {
                     var mDay = vDateName.value.substr(2,2);
                     var mMonth = vDateName.value.substr(0,2);
                     var mYear = vDateName.value.substr(4,4)
                     vDateName.value = mMonth+strSeperator+mDay+strSeperator+mYear;
                  }
                  if (vDateType == 2) // yyyymmdd
                  {
                     var mYear = vDateName.value.substr(0,4)
                     var mMonth = vDateName.value.substr(4,2);
                     var mDay = vDateName.value.substr(6,2);
                     vDateName.value = mYear+strSeperator+mMonth+strSeperator+mDay;
                  }
                  if (vDateType == 3) // ddmmyyyy
                  {
                     var mMonth = vDateName.value.substr(2,2);
                     var mDay = vDateName.value.substr(0,2);
                     var mYear = vDateName.value.substr(4,4)
                     vDateName.value = mDay+strSeperator+mMonth+strSeperator+mYear;
                  }

                  //Create a temporary variable for storing the DateType and change
                  //the DateType to a 1 for validation.

                  var vDateTypeTemp = vDateType;
                  vDateType = 1;
                  var vDateValueCheck = mMonth+strSeperator+mDay+strSeperator+mYear;

                  if (!dateValid(vDateValueCheck))
                  {
                     alert("Fecha no v�lida\nIntroduzcala de nuevo");
                     vDateType = vDateTypeTemp;
                     vDateName.value = "";
                     vDateName.focus();
                     vDateName.select();
                     return false;
		            }
                     vDateType = vDateTypeTemp;
                     return true;
	            }
               else
               {
                  if (((vDateValue.length < 8 && dateCheck) || (vDateValue.length == 9 && dateCheck)) && (vDateValue.length >=1))
                  {
                     alert("Fecha no v�lida\nIntroduzcala de nuevo");
                     vDateName.value = "";
                     vDateName.focus();
                     vDateName.select();
                     return false;
                  }
               }
            }
         }
         else
         {
         // Non isNav Check
            if (((vDateValue.length < 8 && dateCheck) || (vDateValue.length == 9 && dateCheck)) && (vDateValue.length >=1))
            {
               alert("Fecha no v�lida\nIntroduzcala de nuevo");
               vDateName.value = "";
               vDateName.focus();
               return true;
            }

            // Reformat date to format that can be validated. mm/dd/yyyy


            if (vDateValue.length >= 8 && dateCheck)
            {

               // Additional date formats can be entered here and parsed out to
               // a valid date format that the validation routine will recognize.

               if (vDateType == 1) // mm/dd/yyyy
               {
                  var mMonth = vDateName.value.substr(0,2);
                  var mDay = vDateName.value.substr(3,2);
                  var mYear = vDateName.value.substr(6,4)
               }
               if (vDateType == 2) // yyyy/mm/dd
               {
                  var mYear = vDateName.value.substr(0,4)
                  var mMonth = vDateName.value.substr(5,2);
                  var mDay = vDateName.value.substr(8,2);
               }
               if (vDateType == 3) // dd/mm/yyyy
               {
                  var mDay = vDateName.value.substr(0,2);
                  var mMonth = vDateName.value.substr(3,2);
                  var mYear = vDateName.value.substr(6,4)
               }
               if (vYearLength == 4)
               {
                  if (mYear.length < 4)
                  {
                     alert("Fecha no v�lida\nIntroduzcala de nuevo");
                     vDateName.value = "";
                     vDateName.focus();
                     return true;
                  }
               }

               // Create temp. variable for storing the current vDateType
               var vDateTypeTemp = vDateType;

               // Change vDateType to a 1 for standard date format for validation
               // Type will be changed back when validation is completed.
               vDateType = 1;

               // Store reformatted date to new variable for validation.
               var vDateValueCheck = mMonth+strSeperator+mDay+strSeperator+mYear;

               if (mYear.length == 2 && vYearType == 4 && dateCheck)
               {

                  //Turn a two digit year into a 4 digit year
                  var mToday = new Date();

                  //If the year is greater than 30 years from now use 19, otherwise use 20
                  var checkYear = mToday.getFullYear() + 30;
                  var mCheckYear = '20' + mYear;
                  if (mCheckYear >= checkYear)
                     mYear = '19' + mYear;
                  else
                     mYear = '20' + mYear;
                  vDateValueCheck = mMonth+strSeperator+mDay+strSeperator+mYear;

                  // Store the new value back to the field.  This function will
                  // not work with date type of 2 since the year is entered first.

                  if (vDateTypeTemp == 1) // mm/dd/yyyy
                     vDateName.value = mMonth+strSeperator+mDay+strSeperator+mYear;
                  if (vDateTypeTemp == 3) // dd/mm/yyyy
                     vDateName.value = mDay+strSeperator+mMonth+strSeperator+mYear;

               }


               if (!dateValid(vDateValueCheck))
               {
                  alert("Fecha no v�lida\nIntroduzcala de nuevo");
                  vDateType = vDateTypeTemp;
                  vDateName.value = "";
                  vDateName.focus();
                  return true;
		         }
               vDateType = vDateTypeTemp;
               return true;

            }
            else
            {

               if (vDateType == 1)
               {
                  if (vDateValue.length == 2)
                  {
                     vDateName.value = vDateValue+strSeperator;
                  }
                  if (vDateValue.length == 5)
                  {
                     vDateName.value = vDateValue+strSeperator;
                  }
               }
               if (vDateType == 2)
               {
                  if (vDateValue.length == 4)
                  {
                     vDateName.value = vDateValue+strSeperator;
                  }
                  if (vDateValue.length == 7)
                  {
                     vDateName.value = vDateValue+strSeperator;
                  }
               }
               if (vDateType == 3)
               {
                  if (vDateValue.length == 2)
                  {
                     vDateName.value = vDateValue+strSeperator;
                  }
                  if (vDateValue.length == 5)
                  {
                     vDateName.value = vDateValue+strSeperator;
                  }
               }
               return true;
            }
         }
         if (vDateValue.length == 10   && dateCheck)
         {
            if (!dateValid(vDateName))
            {
				// Un-comment the next line of code for debugging the dateValid() function error messages
				//               alert(err);
               alert("Fecha no v�lida\nIntroduzcala de nuevo");
               vDateName.focus();
               vDateName.select();
	         }
         }
         return false;
      }
      else
      {
         // If the value is not in the string return the string minus the last
         // key entered.
         if (isNav4 || isNav5)
         {
            vDateName.value = "";
            vDateName.focus();
            vDateName.select();
            return false;
         }
         else
         {
	      while ( vDateName.value!="" && "0123456789/".indexOf(vDateName.value.substr((vDateValue.length-1)))==-1){
                vDateName.value = vDateName.value.substr(0, (vDateValue.length-1));
	      }
              return false;
         }
      }
   }
}

function DateFormat(vDateName, vDateValue, e, dateCheck, dateType)  {   
    try {
    vDateType = dateType;
    while ( vDateName.value!="" && "0123456789/".indexOf(vDateName.value.substr((vDateValue.length-1)))==-1) {
        vDateName.value = vDateName.value.substr(0, (vDateValue.length-1));
    }
    if ( vDateName.value!="" && "0123456789/".indexOf(vDateName.value.substr((vDateValue.length-1)))==-1 ) {
	return false;
    }
    sep1="";
    sep2="";
    dd="";
    mm="";
    yy="";
    temp="";
    valor = vDateName.value;
    cont=0;
    isAno = 0;
    if ( valor.length>=5 ) {
	cad=valor.substring(valor.length-5);
    	isAno = ( cad.substring(0,1)=="/" ? 1 : 0);
    }
	//alert(isAno);
    while(valor!="" && valor.indexOf("/")!=-1) {
        valor = valor.replace("/","");
	cont++;
    }
    var key = (window.Event) ? e.which : e.keyCode;
    if ( ",8,36,37,39,46,".indexOf(","+key+",")==-1 && ( ((cont<2 && !isAno)||valor.length==8 ) || dateCheck) ) {
        for(var xx=0;  xx < valor.length; xx++) {
            letra=valor.charAt(xx);
            temp += letra + (xx==1 || xx==3 ?"/":"") ;
	    if ( xx==0 || xx==1 ) {
                dd+=letra;
	    } else if ( xx==2 || xx==3 ) {
                mm+=letra;
            } else {
                yy+=letra;
            }
        }
	if ( eval(yy) && yy!="" && eval(yy) < 1900 && yy.length<=3 && dateCheck) {
            n = eval(yy);
            if ( n >= 100 ) { 
		yy = n+1000;
            } else {
                yy = ( n <= 35 ? 2000+n : 1900+n);
            }
        temp = dd+"/"+mm+"/"+yy;
        }
        vDateName.value = temp;
    }
    if(dateCheck) {
      if (!dateValid(vDateName.value)) {
         //alert("Fecha no v�lida\nIntroduzcala de nuevo "+err);
         vDateName.value = "";
         alert("Fecha no v�lida\nIntroduzcala nuevamente ");
         vDateName.focus();
         vDateName.select();
         return false;
      }
      return true;
   }
   } catch(e) {
       alert("El formato de fecha es dd/mm/yyyy ejemplo: 01/02/2006");
       vDateName.value = "";
   }

}


function dateValid(objName) {
      var strDate;
      var strDateArray;
      var strDay;
      var strMonth;
      var strYear;
      var intday;
      var intMonth;
      var intYear;
      var booFound = false;
      var datefield = objName;
      var strSeparatorArray = new Array("-"," ","/",".");
      var intElementNr;
      // var err = 0;
      var strMonthArray = new Array(12);
      strMonthArray[0] = "Jan";
      strMonthArray[1] = "Feb";
      strMonthArray[2] = "Mar";
      strMonthArray[3] = "Apr";
      strMonthArray[4] = "May";
      strMonthArray[5] = "Jun";
      strMonthArray[6] = "Jul";
      strMonthArray[7] = "Aug";
      strMonthArray[8] = "Sep";
      strMonthArray[9] = "Oct";
      strMonthArray[10] = "Nov";
      strMonthArray[11] = "Dec";

      //strDate = datefield.value;
      strDate = objName;

      if (strDate.length < 1) {
         return true;
      }
      for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
         if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1)
         {
            strDateArray = strDate.split(strSeparatorArray[intElementNr]);
            if (strDateArray.length != 3)
            {
               err = 1;
               return false;
            }
            else
            {
               strDay = strDateArray[0];
               strMonth = strDateArray[1];
               strYear = strDateArray[2];
            }
            booFound = true;
         }
      }
      if (booFound == false) {
         if (strDate.length>5) {
            strDay = strDate.substr(0, 2);
            strMonth = strDate.substr(2, 2);
            strYear = strDate.substr(4);
         }
      }
      //Adjustment for short years entered
      if (strYear.length == 2) {
         strYear = '20' + strYear;
      }
      //strTemp = strDay;
      //strDay = strMonth;
      //strMonth = strTemp;
      intday = parseInt(strDay, 10);
      if (isNaN(intday)) {
         err = 2;
         return false;
      }

      intMonth = parseInt(strMonth, 10);
      if (isNaN(intMonth)) {
         for (i = 0;i<12;i++) {
            if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
               intMonth = i+1;
               strMonth = strMonthArray[i];
               i = 12;
            }
         }
         if (isNaN(intMonth)) {
            err = 3;
            return false;
         }
      }
      intYear = parseInt(strYear, 10);
      if (isNaN(intYear)) {
         err = 4;
         return false;
      }
      if (intMonth>12 || intMonth<1) {
         err = 5;
         return false;
      }
      if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
         err = 6;
         return false;
      }
      if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
         err = 7;
         return false;
      }
      if (intMonth == 2) {
         if (intday < 1) {
            err = 8;
            return false;
         }
         if (LeapYear(intYear) == true) {
            if (intday > 29) {
               err = 9;
               return false;
            }
         }
         else {
            if (intday > 28) {
               err = 10;
               return false;
            }
         }
      }
         return true;
}

function LeapYear(intYear) {
      if (intYear % 100 == 0) {
         if (intYear % 400 == 0) { return true; }
      }
      else {
         if ((intYear % 4) == 0) { return true; }
      }
         return false;
}



//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//calcular la edad de una persona
//recibe la fecha como un string en formato espa�ol
//devuelve un entero con la edad. Devuelve false en caso de que la fecha sea incorrecta o mayor que el dia actual
// el segundo parametro fechaHoy si no se pasa toma la fecha del dia
// author : Jairo R.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

function calcular_edad(fecha,fechaHoy){

    //calculo la fecha de hoy
    var hoy=new Date()

	if ( fechaHoy != null ) {
		hoy.setYear(fechaHoy.substring(6));
		hoy.setMonth(fechaHoy.substring(3,5)-1);
		hoy.setDate(fechaHoy.substring(0,2));
	}

    //calculo la fecha que recibo La descompongo en un array
    var array_fecha = fecha.split("/")
    //si el array no tiene tres partes, la fecha es incorrecta
    if (array_fecha.length!=3)
       return false

    //compruebo que los ano, mes, dia son correctos
    var ano = eval(array_fecha[2]);
    if (isNaN(ano))
       return false

    var mes = eval(array_fecha[1]);
    if (isNaN(mes))
       return false

    var dia = eval(array_fecha[0]);
    if (isNaN(dia))
       return false

    //si el a�o de la fecha que recibo solo tiene 2 cifras hay que cambiarlo a 4
    if (ano<=99)
       ano +=2000

    //resto los a�os de las dos fechas
    edad=hoy.getYear()- ano - 1; //-1 porque no se si ha cumplido a�os ya este a�o

    //si resto los meses y me da menor que 0 entonces no ha cumplido a�os. Si da mayor si ha cumplido
    if (hoy.getMonth() + 1 - mes < 0) //+ 1 porque los meses empiezan en 0
       return edad
    if (hoy.getMonth() + 1 - mes > 0)
       return edad+1

    //entonces es que eran iguales. miro los dias
    //si resto los dias y me da menor que 0 entonces no ha cumplido a�os. Si da mayor o igual si ha cumplido
    if (hoy.getUTCDate() - dia >= 0)
       return edad + 1

    return edad
}

// rellena con ceros por la izquierda una cadena
function zeros(valor,longitud) {
	var cad = "" + valor;
	longitud = longitud - (trim(cad).length);
	for ( k_i = 0; k_i < longitud ; k_i++ ) {
		cad = "0"+cad;
	}
	return cad;
}

// elimina los ceros que anteceden un valor. Ejm: 0058970, retorna: 58970
function eliminoCero(valor){
	var resultado = valor;
	for (i=0; i<valor.length; i++){
		if (valor.charAt(i)=="0"){
			if (resultado.length>1) resultado = resultado.substring(1,resultado.lenght);
			else	{
				resultado = "";
				break;
			}
		}
		else
			break;
	}
	return resultado;
}

// elimina las comas dentro de un valor. Ejm: 1,254,235.00 retorna: 1254235.00
function eliminarComas(valor){
	var resultado = "";
	for (i=0; i<valor.length; i++){
		if (valor.charAt(i)!=","){
			resultado = resultado + valor.charAt(i);
		}
	}
	return resultado;
}
  
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Nombre: convierte la fecha al formato plano AAAAMMDD
// author : Jairo R.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function toPlano(fecha,largo) {
	largo = ( largo == null || largo < 0 || largo > 8 ? 8 : largo );
	return (fecha.substring(fecha.length-4)+fecha.substring(fecha.length-7,fecha.length-5)+fecha.substring(0,2)).substring(0,largo);
}

//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Nombre: formatea una cadena con el punto decimal y separador de miles
// author : Jairo R.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function formatearValor(valor,n) {

	n = ( n == null ? 2 : n );
    var sep = ".";
    var sep2 = ","; //separador para quitar
	while (valor.indexOf(sep2) != -1 && sep2 != sep ) {
		valor = valor.substr(0,valor.indexOf(sep2)) + valor.substr(valor.indexOf(sep2)+1);
	}
	valor = (empty(valor) ? "0"+sep+"00" : valor);
	if ( valor.indexOf(sep) == -1 ) {
		valor = valor+sep+"00";
	}
    valor = valor.substr(0,valor.indexOf(sep)) + (valor+"0000000000000000000").substr(valor.indexOf(sep), n+1 );
    
    var cadena = valor.substr(0,valor.indexOf("."))
    var decimas = valor.substr(valor.indexOf("."));
    valor = cadena;
    var largo = valor.length
    var res = "";
    var cont = 0;
    var sep = "";
    for( var i = largo; i >= 0 ; i-- ) {
      res = valor.substr(i,1) + sep + res;
      if ( cont == 3 ) {
	      cont = 0;
	      sep = ","
      } else {
		  sep = "";
      }
      cont++; 
    }
    valor = res+decimas;
    return valor;
}

function formatearValorComa(valor,n) {

	n = ( n == null ? 2 : n );
    var sep = ",";
    var sep2 = "."; //separador para quitar
	while (valor.indexOf(sep2) != -1 && sep2 != sep ) {
		valor = valor.substr(0,valor.indexOf(sep2)) + valor.substr(valor.indexOf(sep2)+1);
	}
	valor = (empty(valor) ? "0"+sep+"00" : valor);
	if ( valor.indexOf(sep) == -1 ) {
		valor = valor+sep+"00";
	}
    valor = valor.substr(0,valor.indexOf(sep)) + (valor+"0000000000000000000").substr(valor.indexOf(sep), n+1 );
    
    var cadena = valor.substr(0,valor.indexOf(","))
    var decimas = valor.substr(valor.indexOf(","));
    valor = cadena;
    var largo = valor.length
    var res = "";
    var cont = 0;
    var sep = "";
    for( var i = largo; i >= 0 ; i-- ) {
      res = valor.substr(i,1) + sep + res;
      if ( cont == 3 ) {
	      cont = 0;
	      sep = "."
      } else {
		  sep = "";
      }
      cont++; 
    }
    valor = res+decimas;
    return valor;
}

//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Nombre: formatea un campo con el punto decimal y separador de miles
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	
function formatearCampo(campo) {

	campo.value = formatearValor(campo.value,2)
	campo.style.textAlign = "right";

}

function formatearCampoComa(campo) {

	campo.value = formatearValorComa(campo.value,2)
	campo.style.textAlign = "right";

}

// dejada por que es ustilizada en paginas anteriores
function separadorMiles(campo) {
	campo.value = formatearValor(campo.value,2)
}

function formatearCampoBlanco(campo) {
if(campo.value!=""){
formatearCampo(campo);
	}
}

function formatearCampoBlancoComa(campo) {
if(campo.value!=""){
formatearCampoComa(campo);
	}
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Nombre: Limita los puntos decimales de un campo segun el parametro especificado por "n"
// author : Jairo R.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	
function puntoDecimal(campo,n) {
    var valor = campo.value;
    var sep = ".";
    var sep2 = ","; //separador para quitar
	while (valor.indexOf(sep2) != -1 && sep2 != sep ) {
		valor = valor.substr(0,valor.indexOf(sep2)) + valor.substr(valor.indexOf(sep2)+1);
	}
	valor = (empty(valor) ? "0"+sep+"00" : valor);
	if ( valor.indexOf(sep) == -1 ) {
		valor = valor+sep+"00";
	}
    valor = valor.substr(0,valor.indexOf(sep)) + (valor+"0000000000000000000").substr(valor.indexOf(sep), n+1 );
	campo.value = valor;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Nombre: Limita los puntos decimales de un campo segun el parametro especificado por "n"
// author : Jairo R.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function puntoDecimalValor(valor,n) {
    var sep = ".";
    var sep2 = ","; //separador para quitar
	while (valor.indexOf(sep2) != -1 && sep2 != sep ) {
		valor = valor.substr(0,valor.indexOf(sep2)) + valor.substr(valor.indexOf(sep2)+1);
	}
	valor = (empty(valor) ? "0"+sep+"00" : valor);
	if ( valor.indexOf(sep) == -1 ) {
		valor = valor+sep+"00";
	}
    valor = valor.substr(0,valor.indexOf(sep)) + (valor+"0000000000000000000").substr(valor.indexOf(sep), n+1 );
	return (valor);
}

//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Nombre: Retorna true si el valor esta vacio en caso contrario false
// author : Jairo R.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function empty(valor) {
	var resultado = false;
	if ((valor == "") || ( trim(valor).length == 0) )
	{
			resultado = true;
	}
	return resultado;  
}

//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Nombre: visualiza o oculta un objeto determinando si es netscape o explorer
// author : Jairo R.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function visible(id,ver) {
	if ( ver ) {
		document.getElementById(id).style.position = "";
		document.getElementById(id).style.visibility = ( isNetscape() ? "" : "visible" );
	} else {
		document.getElementById(id).style.visibility = "hidden";
		document.getElementById(id).style.position = "absolute";
	}
}

//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Nombre: determina si es internet explorer
// author : Jairo R.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function isExplorer() {
    return ( (navigator.appName.toLowerCase()).indexOf("microsoft") != -1 );
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Nombre: determina si es netscape navigator
// author : Jairo R.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function isNetscape() {
    return ( (navigator.appName.toLowerCase()).indexOf("netscape") != -1 );
}


//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Nombre: valida la extension de un archivo
// author : Jairo R.
// parametros : fileName = Nombre del archivo, listaExt = lista de extensiones separadas por coma
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function validarExtension(fileName, listaExt) {
	try {
		if ( empty(listaExt) || empty(fileName) || fileName.length < 4 ) {
			return false; // estan vacias las extensiones
		}
		var ext = fileName;
		if (ext.indexOf(".")==-1) {
			return false;
		}
		while(ext.indexOf(".")!=-1) {
			ext = ext.substring(ext.indexOf(".")+1);
		}
		if ( listaExt.indexOf(ext)!=-1 ) {
			return true;
		}
	} catch(e) { }
	return false;
}


//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Descripci�n: Compara si la fecha pasada por par�metro es mayor o menos a la fecha actual
// parametros : fecha: string con formato dd/mm/aaaa
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function compararFechaConHoy(fecha){
	var mi_fecha=new Date();
	
	var diaHoy=mi_fecha.getDate();
	//alert (diaHoy);
	var mesHoy=mi_fecha.getMonth();
	mesHoy++;
	//alert (mesHoy);
	var anoHoy=mi_fecha.getFullYear();
	//alert (anoHoy);

	var diaInput=fecha.substr(0,2);
	var mesInput=fecha.substr(3,2);
	var anoInput=fecha.substr(6,4);

	if (anoInput>anoHoy){
		return "mayor";
	}
	else if (mesInput>mesHoy && anoHoy==anoInput){
		return "mayor";
	}
	else if (diaInput>diaHoy && mesHoy==mesInput){
		return "mayor";
	}
	return "menor";
}

//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Descripci�n: Compara dos fechas para saber si una es mayor que la otra (fecha1>fecha2)
// parametros : fecha1,fecha2= fechas con formato dd/mm/aaaa
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function compararFechas(fecha1,fecha2){
		var diaInput1=parseInt(fecha1.substr(0,2), 10);
		var mesInput1=parseInt(fecha1.substr(3,2), 10);
		var anoInput1=parseInt(fecha1.substr(6,4), 10);

		var diaInput2=parseInt(fecha2.substr(0,2), 10);
		var mesInput2=parseInt(fecha2.substr(3,2), 10);
		var anoInput2=parseInt(fecha2.substr(6,4), 10);

		if (anoInput1>anoInput2){
			return "mayor";
		}
		else if (mesInput1>mesInput2 && anoInput1==anoInput2){
			return "mayor";
		}
		else if (diaInput1>diaInput2 && mesInput1==mesInput2){
			return "mayor";
		}

		return "menor";
}
// validaciones de campos
function isEmpty(objeto,mensaje) {
	if ( trim(objeto.value)=="" ) {
		alert("Usted debe ingresar "+mensaje);
        objeto.focus();
		return true;
	}
	return false;
}

function isEmptyInt(objeto,mensaje) {
	try {
		if ( !parseInt(objeto.value) ) {
			alert("Usted debe ingresar un valor numerico en "+mensaje);
    	    objeto.focus();
			return true;
		} else {
			objeto.value=parseInt(objeto.value);
		}
	} catch (e) {
		alert("Usted debe ingresar un valor numerico en "+mensaje);
        objeto.focus();
		return true;
	}
	return false;
}
function isEmptyMail(objeto,mensaje) {
	if ( trim(objeto.value)=="" || !isEmail(objeto.value) ) {
		if ( !isEmail(objeto.value) ) {
			alert("Usted debe ingresar un correo valido para "+mensaje);
		} else {
			alert("Usted debe ingresar "+mensaje);
		}
        objeto.focus();
		return true;
	}
	return false;
}


function isInt(objeto,mensaje) {
	try {
		if (trim(objeto.value)!="") {
			if ( !parseInt(objeto.value) ) {
				alert("Usted debe ingresar un valor numerico en "+mensaje);
	    	    objeto.focus();
				return false;
			} else {
				objeto.value=parseInt(objeto.value);
			}
		}
	} catch (e) {
		alert("Usted debe ingresar un valor numerico en "+mensaje);
        objeto.focus();
		return false;
	}
	return true;
}

function isMail(objeto,mensaje) {
	if ( trim(objeto.value)!="" ) {
		if ( !isEmail(objeto.value) ) {
			if ( !isEmail(objeto.value) ) {
				alert("Usted debe ingresar un correo valido para "+mensaje);
			} else {
				alert("Usted debe ingresar "+mensaje);
			}
	        objeto.focus();
			return false;
		}
	}
	return true;
}

//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Descripci�n: Valida si todos los elementos de un formulario (de tipo text)
//              contienen valores num�ricos
// parametros : forma: document.nombre_formulario
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function validarCantidades(forma){
	var bien = true;
	var iTotalElementos = forma.elements.length;
	for (var i=0; i<iTotalElementos; i++){
		if (forma.elements[i].type == "text" && !isNatural(forma.elements[i].value)){
			alert("Las cantidades deben ser num�ricas");
			forma.elements[i].focus();
			bien = false;
			break;
		}
		if (forma.elements[i].value==""){
			forma.elements[i].value = "0";
		}
	}	

	if (bien==true){
		forma.submit();
	}
}


// copyright 1999 Idocs, Inc. http://www.idocs.com
// Distribute this script freely but keep this notice in place
function numbersonly(myfield, e, dec)
{
	var key;
	var keychar;
	
	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;
	keychar = String.fromCharCode(key);
	
	// control keys
	if ((key==null) || (key==0) || (key==8) || 
	    (key==9) || (key==13) || (key==27) )
	   return true;
	
	// numbers
	else if ((("0123456789").indexOf(keychar) > -1))
	   return true;
	
	// decimal point jump
	else if (dec && (keychar == "."))
	   {
	   myfield.form.elements[dec].focus();
	   return false;
	   }
	else
	   return false;
}

function dateonly(myfield, e, dec)
{
	var key;
	var keychar;
	
	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;
	keychar = String.fromCharCode(key);
	
	// control keys
	if ((key==null) || (key==0) || (key==8) || 
	    (key==9) || (key==13) || (key==27) )
	   return true;
	
	// numbers
	else if ((("0123456789/").indexOf(keychar) > -1))
	   return true;
	
	// decimal point jump
	else if (dec && (keychar == "."))
	   {
	   myfield.form.elements[dec].focus();
	   return false;
	   }
	else
	   return false;
}

function doubleonly(myfield, e, dec)
{
	var key;
	var keychar;
	
	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;
	keychar = String.fromCharCode(key);
	
	// control keys
	if ((key==null) || (key==0) || (key==8) || 
	    (key==9) || (key==13) || (key==27) )
	   return true;
	
	// numbers
	else if ((("0123456789.").indexOf(keychar) > -1))
	   return true;
	
	// decimal point jump
	else if (dec && (keychar == "."))
	   {
	   myfield.form.elements[dec].focus();
	   return false;
	   }
	else
	   return false;
}


//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// M�todo para validaci�n de fechas: esDigito(), valSep(), finMes(), valDia(), valMes(), valAno(), 
//									 valBisiesto(), valFecha()
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

function esDigito(sChr){
	var sCod = sChr.charCodeAt(0);
	return ((sCod > 47) && (sCod < 58));
}

function valSep(oTxt){
	var bOk = false;
	bOk = bOk || ((oTxt.value.charAt(2) == "-") && (oTxt.value.charAt(5) == "-"));
	bOk = bOk || ((oTxt.value.charAt(2) == "/") && (oTxt.value.charAt(5) == "/"));
	return bOk;
}

function finMes(oTxt){
	var nMes = parseInt(oTxt.value.substr(3, 2), 10);
	var nRes = 0;
	switch (nMes){
	case 1: nRes = 31; break;
	case 2: nRes = 29; break;
	case 3: nRes = 31; break;
	case 4: nRes = 30; break;
	case 5: nRes = 31; break;
	case 6: nRes = 30; break;
	case 7: nRes = 31; break;
	case 8: nRes = 31; break;
	case 9: nRes = 30; break;
	case 10: nRes = 31; break;
	case 11: nRes = 30; break;
	case 12: nRes = 31; break;
	}
	return nRes;
}

function valDia(oTxt){
	var bOk = false;
	var nDia = parseInt(oTxt.value.substr(0, 2), 10);
	bOk = bOk || ((nDia >= 1) && (nDia <= finMes(oTxt)));
	return bOk;
}

function valMes(oTxt){
	var bOk = false;
	var nMes = parseInt(oTxt.value.substr(3, 2), 10);
	bOk = bOk || ((nMes >= 1) && (nMes <= 12));
	return bOk;
}

function valAno(oTxt){
	var bOk = true;
	var nAno = oTxt.value.substr(6);
	bOk = bOk && (nAno.length == 4);
	if (bOk){
		for (var i = 0; i < nAno.length; i++){
			bOk = bOk && esDigito(nAno.charAt(i));
		}
	}
	return bOk;
}

function valBisiesto(oTxt){
	var bOk = true;
	var nDia = parseInt(oTxt.value.substr(0, 2), 10);
	var nMes = parseInt(oTxt.value.substr(3, 2), 10);
	var nAno = oTxt.value.substr(6);
	bOk = bOk && ((nAno%4 != 0) && (nMes == 2) && (nDia > 28));
	return bOk;
}

function valFecha(oTxt){
	var bOk = true;
	if (oTxt.value != ""){
		if (oTxt.value.length==10){
			bOk = bOk && (valAno(oTxt));
			bOk = bOk && (valMes(oTxt));
			bOk = bOk && (valDia(oTxt));
			bOk = bOk && (valSep(oTxt));
			//bOk = bOk && (valBisiesto(oTxt));
		}
		else bOk = false;
	}
	return bOk;
}

/*Selecciona todos los checkboxes del formulario pasado como par�metro*/
 function seleccionarTodos(laForma, campo){
	var iTotalElementos = laForma.elements.length;
	var seleccionar = false;
	if (campo.checked) seleccionar = true;
	for (i = 0; i<iTotalElementos;i++){
		if (laForma.elements[i].type == "checkbox"){
			if (seleccionar) laForma.elements[i].checked = true;
			else laForma.elements[i].checked = false;
		}
	}	
 }
 
 function goToURL(isbn,cod_libreria,cod_pais,b) {
			var url = window.location.href;			
			url = url.replace(/&/g,'*');			
			url = encodeURI(url);
			//url = url.replace(/ /g,'%20');				
			location.href = "/carrito_agregar.do?isbn="+isbn+"&cod_libreria="+cod_libreria+"&cod_pais="+cod_pais+"&b="+b+"&url="+url; 
 }

 function reemplazarAcentos(valor) {
	valor = valor.replace(/á/g,'&aacute;');
	valor = valor.replace(/é/g,'&eacute;');
	valor = valor.replace(/í/g,'&iacute;');
	valor = valor.replace(/ó/g,'&oacute;');
	valor = valor.replace(/ú/g,'&uacute;');
	valor = valor.replace(/ñ/g,'&ntilde;');
	valor = valor.replace(/Á/g,'&Aacute;');
	valor = valor.replace(/É/g,'&Eacute;');
	valor = valor.replace(/Í/g,'&Iacute;');
	valor = valor.replace(/Ó/g,'&Oacute;');
	valor = valor.replace(/Ú/g,'&Uacute;');
	valor = valor.replace(/Ñ/g,'&Ntilde;');
	return valor;
 }
 