﻿/**************************/
/** VALIDATION_FUNCTIONS **/
/**************************/

//Con esta línea, estamos declarando una función llamada trim() en la clase String
//Es decir, que en cualquier cadena de texto podemos llamar al método trim() para que nos devuelva el contenido sin espacios por delante ni por detrás
//Ejemplo en funcion verificarParametros(theForm, titulo_exacto)
String.prototype.trim = function() { 
	return this.replace(/^\s+|\s+$/g, ""); 
}

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;
 }
 /**************************/
 /** VALIDATION_FUNCTIONS **/
 /**************************/
 
 
 
 /***********/
 /** POPUP **/
 /***********/
 function popUpSeguridad(){
 	window.open("/views/pages/frontend/seguridad.html","Seguridad","width=750,height=700,top=(screen.availWidth - 380)/2, left=(screen.availHeight - 390)/2, location=no,menubar=no,personalbar=no,resizable=no,status=yes,toolbar=no,scrollbars=no");
 }
 function recomendarLibro(isbn){
 	window.open("/recomendarLibro.do?isbn="+isbn,"Libro","width=435,height=380,location=no,menubar=no,personalbar=no,resizable=no,status=yes,toolbar=no,scrollbars=no");
 }
 function popUpListaTemas(){
 	window.open("/views/pages/common/listaTemas.jsp","Temas","width=730,height=500,location=no,menubar=no,personalbar=no,resizable=no,status=yes,toolbar=no,scrollbars=no");
 }
 function popUpPoliticasDevoluciones(){
 	window.open("/politicaDevoluciones.do","Devoluciones","width=725,height=550,top=(screen.availWidth - 725)/2, left=(screen.availHeight - 550)/2, location=no,menubar=no,personalbar=no,resizable=no,status=yes,toolbar=no,scrollbars=yes");
 }
 function agregarComentario(isbn){
 	window.open("/agregarComentario.do?isbn="+isbn,"Comentario","width=560,height=560,location=no,menubar=no,personalbar=no,resizable=no,status=yes,toolbar=no,scrollbars=yes");
 }
 function agregarCita(isbn){
 	window.open("/agregarCita.do?isbn="+isbn,"Cita","width=460,height=500,location=no,menubar=no,personalbar=no,resizable=no,status=yes,toolbar=no,scrollbars=no");
 }
 function boVerDetalle(isbn, codPais, porcentajeMax){
 	window.open("/BO_detalle_precios.do?isbn="+isbn+"&pais="+codPais+"&porcentaje="+porcentajeMax,"Precios","width=600,height=485,location=no,menubar=no,personalbar=no,resizable=no,status=yes,toolbar=no,scrollbars=yes");
 }
 function boMostrarSubtema(pagina, tipo, cod_padre, cod_genero){
 	window.open("/BO_modificarTema.do?pagina="+pagina+"&tipo="+tipo+"&cod_padre="+cod_padre+"&cod_genero="+cod_genero,"Subtema","width=500,height=250,location=no,menubar=no,personalbar=no,resizable=no,status=yes,toolbar=no,scrollbars=no");
 }
 function popUpCondicionesUso(){
 	window.open("/condicionesUso.do","Condiciones","width=725,height=550,top=(screen.availWidth - 725)/2, left=(screen.availHeight - 550)/2, location=no,menubar=no,personalbar=no,resizable=no,status=yes,toolbar=no,scrollbars=yes");
 }
 function popUpCondicionesUsoEnvio(){
 	window.open("/condicionesUso.do#envio","Condiciones","width=725,height=550,top=(screen.availWidth - 725)/2, left=(screen.availHeight - 550)/2, location=no,menubar=no,personalbar=no,resizable=no,status=yes,toolbar=no,scrollbars=yes");
 }
 function popUpPreguntasFrecuentes(){
 	window.open("/views/pages/frontend/preguntas_frecuentes.html","PreguntasFrecuentes","width=550,height=550,location=no,menubar=no,personalbar=no,resizable=no,status=yes,toolbar=no,scrollbars=yes");
 }
 function popUpComoComprar(){
 	window.open("/views/pages/frontend/como_comprar.html","Compra","width=735,height=550,top=(screen.availWidth - 735)/2, left=(screen.availHeight - 550)/2, location=no,menubar=no,personalbar=no,resizable=no,status=yes,toolbar=no,scrollbars=yes");
 }
 function popUpCostosEnvio(){
 	window.open("/costosEnvio.do","Costos","width=735,height=400,top=(screen.availWidth - 735)/2, left=(screen.availHeight - 550)/2, location=no,menubar=no,personalbar=no,resizable=no,status=yes,toolbar=no,scrollbars=yes");
 }
 function popUpBusqueda(){
 	window.open("/popUpBusqueda.do","Busqueda","width=490,height=300,top=(screen.availWidth - 490)/2, left=(screen.availHeight - 300)/2, location=no,menubar=no,personalbar=no,resizable=no,status=yes,toolbar=no,scrollbars=yes");
 }
 function popUpVentajas(){
 	window.open("/views/pages/frontend/ventajas.html","Ventajas","width=600,height=450,top=(screen.availWidth - 490)/2, left=(screen.availHeight - 300)/2, location=no,menubar=no,personalbar=no,resizable=no,status=yes,toolbar=no,scrollbars=yes");
 }
 function popUpBiografia(cod_autor){
 	window.open("/popUpBiografia.do?cod_autor="+cod_autor,"Biografia","width=590,height=400,top=(screen.availWidth - 490)/2, left=(screen.availHeight - 300)/2, location=no,menubar=no,personalbar=no,resizable=no,status=yes,toolbar=no,scrollbars=yes");
 }
 function popUpRequisitos(){
	 window.open("/views/pages/frontend/requisito_descarga_ebook.html","Ventajas","width=780,height=470,top=(screen.availWidth - 490)/2, left=(screen.availHeight - 300)/2, location=no,menubar=no,personalbar=no,resizable=no,status=yes,toolbar=no,scrollbars=yes");
 }
 function popUpCapituloLibro(isbn){
	 window.open("/pdfs/"+isbn+".pdf","Capítulo","width=780,height=700,top=(screen.availWidth - 490)/2, left=(screen.availHeight - 300)/2, location=no,menubar=no,personalbar=no,resizable=no,status=yes,toolbar=no,scrollbars=yes");
 }
 /***********/
 /** POPUP **/
 /***********/
 
 
 
 /*****************************************/
 /** /scripts/scripts_paginaprincipal.js **/
 /*****************************************/
	function llenarComboPaisInicio() {
		if (document.getElementById("comboPaisesHeader").length>1) {
			return ;
		}
		primer_tope();
	}
	
    function obtenerUrl(url,cod_pais){
        if(url.indexOf('todosPaises=')>0)
        	url_aux =  url.substring(0,url.indexOf('todosPaises=') - 1);
        else
        	url_aux =  url;
        if(url.indexOf('cod_pais_header=') >= 0){
            url_aux = url_aux.substring(0,url.indexOf('cod_pais_header=') - 1);
           }	
		
        if(url_aux.indexOf("?") >= 0) url_aux = url_aux + "&cod_pais_header=" + cod_pais;
        else url_aux = url_aux + "?cod_pais_header=" + cod_pais;

        //Nuevo c?digo 2007-04-13
        var buscarPor = document.busqueda_sencilla.buscarPor.value;
        var txtBuscar = document.busqueda_sencilla.txtBusqueda.value;
 
        if(txtBuscar==null || txtBuscar==""){
        	indexBuscar = url.indexOf('buscarPor=');
        	indexTxt= url.indexOf('&txtBusqueda=');
	        if(indexBuscar>0){
	        	if(indexTxt>0){
			        buscarPor = url.substring(indexBuscar+10,indexTxt);
			        if(url.indexOf('todosPaises=')>0)
			        	txtBuscar = url.substring(indexTxt+13,url.indexOf('todosPaises=')-1);
			        else
			        	txtBuscar = url.substring(indexTxt+13,url.length);
			    }else{
			        buscarPor = url.substring(indexBuscar+10,url.length);
			    }
	        }
		}else{
	        buscarPor = document.busqueda_sencilla.buscarPor.value;
	        txtBuscar = document.busqueda_sencilla.txtBusqueda.value;
		}

        if(txtBuscar!=null && txtBuscar!=""){
	        url_aux = url_aux + "&buscarPor="+buscarPor+"&txtBusqueda="+txtBuscar;
	    }
	    //Fin nuevo c?digo
	    if(url_aux.indexOf('cod_pais_header_ip=') <= 0)
	    	url_aux = url_aux + "&cod_pais_header_ip=<%=cod_pais_ip%>";
	    url_aux=url_aux+"&todosPaises=false";
        return url_aux;
    }
    
    function obtenerUrlIP(url,cod_pais)
    {
        url_aux = url;
        if(url.indexOf('cod_pais_header_ip=') >= 0)
        {
            url_aux = url_aux.substring(0,url.indexOf('cod_pais_header_ip=') - 1);
        }
        if(url_aux.indexOf("?") >= 0) url_aux = url_aux + "&cod_pais_header_ip=" + cod_pais;
        else url_aux = url_aux + "?cod_pais_header_ip=" + cod_pais;

	    if(url_aux.indexOf('cod_pais_header=') <= 0)
	    	url_aux = url_aux + "&cod_pais_header=<%=cod_pais_header%>";

        return url_aux;
    }
    
    function obtenerUrlUbicacion(url,cod_pais) {
	    	//closebar();
	    	document.location = obtenerUrlIP(url,cod_pais);
	    }
	    
    // Detect if the browser is IE or not.
    // If it is not IE, we assume that the browser is NS.
/*    var IE = document.all?true:false

    // If NS -- that is, !IE -- then set up for mouse capture
    if (!IE) document.captureEvents(Event.MOUSEMOVE)

    // Set-up to use getMouseXY function onMouseMove
    document.onmousemove = getMouseXY;
*/
    // Temporary variables to hold mouse x-y pos.s
    var tempX = 0;
    var tempY = 0;

    // Main function to retrieve mouse x-y pos.s

    function getMouseXY(e) {
      if (IE) { // grab the x-y pos.s if browser is IE
        tempX = event.clientX + document.body.scrollLeft
        tempY = event.clientY + document.body.scrollTop
      } else {  // grab the x-y pos.s if browser is NS
        tempX = e.pageX
        tempY = e.pageY
      }
      // catch possible negative values in NS4
      if (tempX < 0){tempX = 0}
      if (tempY < 0){tempY = 0}
      return true;
    }

    function findObj(theObj, theDoc) {
      var p, i, foundObj;

      if(!theDoc) theDoc = document;
      if( (p = theObj.indexOf("?")) > 0 && parent.frames.length)
      {
        theDoc = parent.frames[theObj.substring(p+1)].document;
        theObj = theObj.substring(0,p);
      }
      if(!(foundObj = theDoc[theObj]) && theDoc.all) foundObj = theDoc.all[theObj];
      for (i=0; !foundObj && i < theDoc.forms.length; i++)
        foundObj = theDoc.forms[i][theObj];
      for(i=0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++)
        foundObj = findObj(theObj,theDoc.layers[i].document);
      if(!foundObj && document.getElementById) foundObj = document.getElementById(theObj);

      return foundObj;
    }

    function showToolTip(mensaje,width,orientacion) {
        eldiv = findObj('tooltip');
        x = tempX;
        y = tempY;
        //alert("(X,Y) = (" + x + ", " + y + ")");
        if (orientacion = 'derecha') {
            eldiv.style.left = (x - width) + "px";
        } else {
            eldiv.style.left = (x + 10) + "px";
        }

        eldiv.style.top = (y -10) + "px";
        eldiv.style.width= width + "px";
        eldiv.innerHTML = "<FONT class='toolTipClass'>" + mensaje + "</FONT>";
        eldiv.style.display="";
    }

    function hideToolTip() {
        eldiv = findObj('tooltip');
        eldiv.style.display="none";
    }

	function llenarComboPaisInicio() {
		if (document.getElementById("comboPaisesHeader").length>1) {
			return ;
		}
		primer_tope();
	}

	var actual = "";
    function llenarComboPais(valor) {
		var paises = valor;
		paises = paises.split("\n");
		var ele = document.getElementById("comboPaisesHeader");
		var myEle;
		var x ;

		actual = (ele.value!=""?ele.value:actual);

		if (ele.length>1) {
			return ;
		}
		for (var q=ele.length;q>=0;q--) {
			//ele.options[q]=null;
		}

		var datos = new Array();
		var arr;
		var cont = 0;
		for(var i = 0; i < paises.length; i++) {
alert(paises[i]);
			arr = paises[i].split(":");
			if (arr[1]!=null) {
				datos[cont++] = arr;
			}
		}
		var nuevo_Control = 0;
		for ( x = 0 ; x < datos.length  ; x++ ){
			myEle = document.createElement("option");
			myEle.value = datos[x][0];
			myEle.text = trim(datos[x][1]);
			//if (myEle.value == actual) {
			//	myEle.selected = true;
			//}
			ele.length = (nuevo_Control);
			ele[nuevo_Control] = myEle;
			nuevo_Control++
		}
		ele.value = actual;


	}



		 var _objetus = null;
		 //funcion encargada de crear el objeto
	 function objetus() {
		 try {
		 	 objetus = new ActiveXObject("Msxml2.XMLHTTP");         }
		 catch (e) {
		 	 try {
		 		objetus= new ActiveXObject("Microsoft.XMLHTTP");                 }
		 	 catch (E) {
		 		objetus= false;
		 	 }
		 }
		 if (!objetus && typeof XMLHttpRequest!='undefined') {
		 	objetus = new XMLHttpRequest();
		 }
		 return objetus
	}

	function primer_tope() {
		if (_objetus==null) {
			_objetus=objetus()
		}
		_values_send="funcion=pt"
		_URL_="/views/common/frontend/paises.html?"
		_objetus.open("GET",_URL_+"&"+_values_send,true);
		_objetus.onreadystatechange=function() {
			if (_objetus.readyState==4) {
				llenarComboPais(_objetus.responseText);
			}
		}
		_objetus.send(null);
	}

    function verificarParametros(theForm, titulo_exacto)
    {
    	theForm.cant_pagina.value=0;
    	theForm.num_pagina.value=1;
    	theForm.orden.value="libro";
        if(theForm.txtBuscarLibro.value == '')
        {
            if(theForm.buscarLibroPor.value == 'titulo') alert('Debe escribir el titulo del libro que desea buscar');
            if(theForm.buscarLibroPor.value == 'autor') alert('Debe escribir el autor del libro que desea buscar');
            if(theForm.buscarLibroPor.value == 'isbn') alert('Debe escribir el ISBN del libro que desea buscar');            
            //return false;
        }else{
	        var s =theForm.txtBuscarLibro.value;
	    	s=eliminarAcentos(s);
	    	if(theForm.buscarLibroPor.value == 'titulo'){
	    		s=s.replace(/_-_/gi,"-");
	    		s=s.replace(/-/gi,"_-_");	    	
	    	}
	    	theForm.txtBuscarLibro.value=s;
        	if(theForm.buscarLibroPor.value != 'isbn' && theForm.txtBuscarLibro.value.trim().length<4){
				alert("El texto debe contener por lo menos 4 caracteres");
	        	//return false;
        	}else{
        		//document.frmSeccionBuscarLibro.cod_pais_header.value="";
        		theForm.todosPaises.value="true";
        		theForm.titulo_exacto.value=titulo_exacto;
				theForm.submit();
				//return true;
			}
        }
    }
    
    function submitenter(myfield,e){
		var keycode;
		if (window.event) keycode = window.event.keyCode;
		else if (e) keycode = e.which;
		else return true;
		
		if (keycode == 13){
		   verificarParametros(document.busqueda_sencilla, false);
		   return false;
		}
		else
		   return true;
	}
    
    function resetPagina(theForm){
    	theForm.cant_pagina.value=0;
    	theForm.num_pagina.value=1;
    }    
    
    function eliminarAcentos(Text){
		var cadena="";
		for (var j = 0; j < Text.length; j++){
			var Char=Text.charCodeAt(j);
			switch(Char){
				case 225:
				cadena+="a";
				break;
				case 233:
				cadena+="e";
				break;
				case 237:
				cadena+="i";
				break;
				case 243:
				cadena+="o";
				break;
				case 250:
				cadena+="u";
				case 224:
				cadena+="a";
				break;
				case 232:
				cadena+="e";
				break;
				case 236:
				cadena+="i";
				break;
				case 242:
				cadena+="o";
				break;
				case 249:
				cadena+="u";
				break;
				case 193:
				cadena+="A";
				break;
				case 201:
				cadena+="E";
				break;
				case 205:
				cadena+="I";
				break;
				case 211:
				cadena+="O";
				break;
				case 218:
				cadena+="U";
				break;
				case 192:
				cadena+="A";
				break;
				case 200:
				cadena+="E";
				break;
				case 204:
				cadena+="I";
				break;
				case 210:
				cadena+="O";
				break;
				case 217:
				cadena+="U";
				break;
				case 241:
				cadena+="n";
				break;
				case 209:
				cadena+="n";
				break;
				default:
				cadena+=Text.charAt(j);
				break;
			}			
		}
		return cadena;
	}
    
function mouseLeaves (element, evt) {
if (typeof evt.toElement != 'undefined' && typeof element.contains !=
'undefined') {
return !element.contains(evt.toElement);
}
else if (typeof evt.relatedTarget != 'undefined' && evt.relatedTarget) {
return !contains(element, evt.relatedTarget);
}
}

function contains (container, containee) {
while (containee) {
if (container == containee) {
return true;
}
containee = containee.parentNode;
}
return false;
}

function hideElement (element) {
//if (element.style) {
//element.style.visibility = 'hidden';
//}


var IfrRef = document.getElementById('iframedeatras');
IfrRef.style.display = "none";     
element.style.display="none";

}

function showElement (element) {
if (element.style) {
element.style.visibility = 'visible';
}
}

/***********************************************
* Drop Down/ Overlapping Content- ? Dynamic Drive (www.dynamicdrive.com)
* This notice must stay intact for legal use.
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/



function getposOffset(overlay, offsettype){

var totaloffset=(offsettype=="left")? overlay.offsetLeft : overlay.offsetTop;
var parentEl=overlay.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
}

var ie=document.all;
var ns6=document.getElementById && !document.all;

function overlay(curobj, subobjstr, opt_position){

if (document.getElementById){

var subobj=document.getElementById(subobjstr)
var IfrRef=document.getElementById('iframedeatras')


//oculto los otros divs que puedan estar abiertos
var item1=document.getElementById('subcontent2');
var item2=document.getElementById('subcontent3');
var item3=document.getElementById('subcontent4');
var item4=document.getElementById('subcontent5');
var item5=document.getElementById('subcontent6');

if(item1==subobj) {
	item2.style.display="none";
	item3.style.display="none";
	item4.style.display="none";
	item5.style.display="none";
	}
else if(item2==subobj) {
	item1.style.display="none";
	item3.style.display="none";
	item4.style.display="none";
	item5.style.display="none";
	}
else if(item3==subobj) {
	item1.style.display="none";
	item2.style.display="none";
	item4.style.display="none";
	item5.style.display="none";
	}
else if(item4==subobj) {
	item1.style.display="none";
	item2.style.display="none";
	item3.style.display="none";
	item5.style.display="none";
	}
else {
	item1.style.display="none";
	item2.style.display="none";
	item3.style.display="none";
	item4.style.display="none";
}


 
//************************************************


var xpos=getposOffset(curobj, "left")+((typeof opt_position!="undefined" && opt_position.indexOf("right")!=-1)? -(subobj.offsetWidth-curobj.offsetWidth) : 0) 
var ypos=getposOffset(curobj, "top")+((typeof opt_position!="undefined" && opt_position.indexOf("bottom")!=-1)? curobj.offsetHeight : 0)

if(item5==subobj) {
	xpos=xpos-400;
}
if(item4==subobj) {
	xpos=xpos-300;
}

subobj.style.left=xpos+"px"
subobj.style.top=ypos+"px"
subobj.style.zIndex = 1;

IfrRef.style.display = "block";
subobj.style.display=(subobj.style.display!="block")? "block" : "none"


//para el iframe que aparece justo detras del div. 
//Esto es para evitar el problema de IE de los div sobre las listas desplegables

IfrRef.style.width = subobj.offsetWidth;
IfrRef.style.height = subobj.offsetHeight;
IfrRef.style.top = subobj.style.top;
IfrRef.style.left = subobj.style.left;
IfrRef.style.zIndex = 0; //subobj.style.zIndex - 1;



return false
}
else
return true
}

//****************************************
function overlaymini(num_cat,cat,curobj, subobjstr, opt_position){

if (document.getElementById){

var subobj=document.getElementById(subobjstr)
var IfrRef=document.getElementById('iframedeatras')

var subnombre="";
//oculto los otros div que puedan estar abiertos
for(i=0;i<num_cat;i++)
{
	subnombre = "sub_"+cat+i ;
	var actual=document.getElementById(subnombre);
	if(actual != subobj )
		actual.style.display="none";
}


var xpos=getposOffset(curobj, "left")+((typeof opt_position!="undefined" && opt_position.indexOf("right")!=-1)? -(subobj.offsetWidth-curobj.offsetWidth) : 0) 
var ypos=getposOffset(curobj, "top")+((typeof opt_position!="undefined" && opt_position.indexOf("bottom")!=-1)? curobj.offsetHeight : 0)

xpos=xpos-200;
ypos=ypos-280;

subobj.style.left=xpos+"px"
subobj.style.top=ypos+"px"
subobj.style.zIndex = 1;

IfrRef.style.display = "block";
subobj.style.display=(subobj.style.display!="block")? "block" : "none"


//para el iframe que aparece justo detras del div. 
//Esto es para evitar el problema de IE de los div sobre las listas desplegables

/*
IfrRef.style.width = subobj.offsetWidth;
IfrRef.style.height = subobj.offsetHeight;
IfrRef.style.top = subobj.style.top;
IfrRef.style.left = subobj.style.left;
IfrRef.style.zIndex = 0; //subobj.style.zIndex - 1;
*/

return false
}
else
return true
}



function overlayclose(subobj){

var IfrRef = document.getElementById('iframedeatras');
IfrRef.style.display = "none";
     
document.getElementById(subobj).style.display="none";
   


}
/*****************************************/
/** /scripts/scripts_paginaprincipal.js **/
/*****************************************/


/* FUNCION QUE GENERA EL SLIDE DE LIBROS DE LA SECCION QUE LA LLAME */
function printSlideSeccion(seccion,cantLibros,cantRotaciones,linkLibro,librosFadeImage,librosEstrellas,descLibroFadeImage,altPortadas,screenWidth){
	var k=0, i, j;
	/*alert(seccion);*/
	var anchoGaleria=screenWidth-290;
	var anchoLibro=Math.round(((cantRotaciones*anchoGaleria)-(cantLibros+cantRotaciones)*10)/(cantLibros)); // el factor de 10 viene del margen de los objetos tipo panel, seteado en el css
	
	// configuracion del carrousell
	stepcarousel.setup({
		galleryid: seccion, //id of carousel DIV
		beltclass: 'belt', //class of inner "belt" DIV containing all the panel DIVs
		panelclass: 'panel', //class of panel DIVs each holding content
		autostep: {enable:false, moveby:0, pause:3000},
		panelbehavior: {speed:1500, wraparound:false, persist:false},
		defaultbuttons: {enable: false, moveby: 3, leftnav: ['http://i34.tinypic.com/317e0s5.gif', -5, 80], rightnav: ['http://i38.tinypic.com/33o7di8.gif', -20, 80]},
		statusvars: ['statusA', 'statusB', 'statusC'], //register 3 variables that contain current panel (start), current panel (last), and total panels
		contenttype: ['inline'] //content setting ['inline'] or ['external', 'path_to_external_file']
	})
	
	
	document.write('<table border="0"><tr>');
	document.write('<td><a href="javascript:moverSeccion(\''+seccion+'\', '+(-cantLibros/cantRotaciones)+');"><img src="/images/imgPaginaPrincipalNueva/flechaIzquierda.gif" width="20px" height="20px" border="0" /></a></td>');
	document.write('<td align="center">');
	document.write('<div id="'+seccion+'" class="stepcarousel" style="background-color:#ffffff;width:'+anchoGaleria+'px;"><div class="belt">');
	for(i=0;i<cantLibros;i++){
		if(i<cantLibros/2){
			document.write('<div id="'+seccion+i+'" class="panel" style="width:'+anchoLibro+'px;"><a href="'+linkLibro[i]+'"><img class="portadaLibro" src="'+librosFadeImage[i]+'" alt="'+altPortadas[i]+'" /></a>'+librosEstrellas[i]+descLibroFadeImage[i]+'</div>');
		}else{
			document.write('<div id="'+seccion+i+'" class="panel" style="width:'+anchoLibro+'px;">Cargando libro...</div>');
		}
	}
	document.write('</div></div>');
	document.write('</td>');
	document.write('<td><a href="javascript:moverSeccion(\''+seccion+'\', '+(cantLibros/cantRotaciones)+');addSegundaRondaSlide(\''+seccion+'\','+i+',cantLibros,'+anchoLibro+',linkLibro'+seccion+',librosFadeImage'+seccion+',librosEstrellas'+seccion+',descLibroFadeImage'+seccion+');"><img src="/images/imgPaginaPrincipalNueva/flechaDerecha.gif" width="20px" height="20px" border="0" /></a></td>');
	document.write('</tr></table>');
}

/* FUNCION QUE AJUSTA EL ALTO DEL SLIDE DE LA SECCION QUE LO LLAME */
function setAltoSlide(seccion){
	var i;
	var altoLibro=0; // almacena el alto del tag de libro mas alto
	if(document.getElementById(seccion)){
		i=0;
		altoLibro=0; // almacena el alto del tag de libro mas alto
		while(document.getElementById(seccion+i)){
			if(altoLibro<document.getElementById(seccion+i).offsetHeight){
				altoLibro=document.getElementById(seccion+i).offsetHeight;
			}
			i++;
		}
		if(altoLibro>0){
			document.getElementById(seccion).style.height=altoLibro-5+'px';
		}
	}
}

function limpiarBusquedaSencillaForm(formatoParam,formatoSess){
	if(formatoParam==null){
		document.busqueda_sencilla.formato.value=formatoSess;
		document.busqueda_sencilla.buscarLibroPor.value="titulo";
		document.busqueda_sencilla.txtBuscarLibro.value="";
	}
}

/* FUNCION PARA ALTERNAR VISIBILIDAD DE OBJETO */
function toggleDisplay(id){
	//alert(id);
	document.getElementById(id).style.display=document.getElementById(id).style.display=='block'?'none':'block';
}
