/****************************************
 * FUNCIONES EN JAVASCRIPT DE NETQUEST  *
 * CopyRight    : Rankdom Systems, S.L. *
 * Última modif : 4.11.2003             *
 ****************************************/
 
/***************************************
 * Variables                           *
 ***************************************/

var whitespace       = " \t\n\r";
var Caracteres       = " 0123456789abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZáàäéèëíìïóòöúùü@.-_,¿?";
var letrasYNumeros   = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_";
var numerosNaturales = "0123456789";
// Variables necesarias para el control de Layers
var ie4              = (document.all) ? true : false;
var ns4              = (document.layers) ? true : false;
var ns6              = (document.getElementById && !document.all) ? true : false;

/***************************************
 * Métodos generales                   *
 ***************************************/

/**
 * detecta_browser()
 * Rellena algunas variables con los datos del Browser.
 */
function detecta_browser(){
 var navName = navigator.appName;
 var brVer   = navigator.userAgent;
 var brNum;
 var brVerId;
 var reg = new RegExp('/');
 if ( !(navigator.appName =='Microsoft Internet Explorer')){
   brVerId = brVer.indexOf('MSIE');
   brNum= brVer.substr(brVerId,8);
   }
 else{
   brVerId = brVerId.search(reg);
   brNum= brVer.substring(brVerId+1);
   }
}

/**
 * salir()
 * Método de confirmación de abandono de NETQUEST
 */
function salir() {
  confirma("¿Desea realmente abandonar Survey Manager?","../control/front.jsp?accion=ClienteSalir");
}

/**
 * isCaracter(s)
 * Devuelve true si 's' está formado por carácteres de  la variable 'Caracteres'.
 */
function isCaracter(s){
  var i;
  for(i=0; i < s.length; i++)
    {
	var c = s.charAt(i);
	if ( Caracteres.indexOf(c) == -1) return false;
	}
  return true;
}

/**
 * esSoloLetrasYNumeros(s)
 * Devuelve true si 's' está formado por carácteres de  la variable 'letrasYNumeros'.
 */
function esSoloLetrasYNumeros(s){
  var i;
  for(i=0; i < s.length; i++) {
	var c = s.charAt(i);
	if ( letrasYNumeros.indexOf(c) == -1) return false;
  }
  return true;
}

/**
 * contieneEspacios(s)
 * Devuelve true si encuentra un espacio en 's'.
 */

function contieneEspacios(s){
  var i;
  for(i=0; i < s.length; i++)
    {
    	var c= s.charAt(i);
    	if (c==" ") return true;
    }
   return false;
}

/**
 * esNoCadenaEspacios(s)
 * Devuelve 'true' si TODOS los carácteres de 's' son espacios.
 */
function esNoCadenaEspacios(s){
  var i;
  for(i=0; i < s.length; i++)
    {
      var c = s.charAt(i);
      if (c!=" ") return true;
    }
  return false;
}

/**
 * esCadenaVacia(s)
 * Devuelve 'true' si 's' es null, es un String vacío o son todos caracteres de espacio.
 */
function esCadenaVacia(s){
  
  var i;
  var c = '';
  
  if (s.lenght == 0 || s == null )return true;
  
  for (i = 0; i < s.length; i++){
    c = s.charAt(i);
    if (whitespace.indexOf(c) == -1) return false;
   }
  return true;
}

/**
 * contieneCadena(a,b)
 * Devuelve true si la cadena 'a' contiene a la cadena 'b'
 */
function contieneCadena(a,b){
  if (a.indexOf(b) == -1) return false;
  else return true;
}

/**
 * eslongitudcorrecta(s,longitud)
 * Devuelve true si el String es inferior o igual al número de carácteres
 */
function eslongitudcorrecta(s,longitud)
{
  var i;
  i=s.length;
  if (i <= longitud) {return true;}
  else{ return false;}
}

/**
 * isEmail(s)
 * Este método comprueba que s es una dirección de e-mail. 
 * La dirección de email ha de ser a@b.c -- osea:
 * Ha de haber como mínimo un carácter antes de la @
 * Ha de haber somo mínimo un carácter antes del .
 * Han de existir los carácteres @ y . a
 */
function isEmail(s){

  // Ha de haber un carácter antes de la @
  var i = 1;
  var sLength = s.length;
  // Buscamos la @
  while ((i < sLength) && (s.charAt(i) != "@"))
  { i++
  }
  if ((i >= sLength) || (s.charAt(i) != "@")) return false;
  else i += 2;
  // Buscamos el punto
  while ((i < sLength) && (s.charAt(i) != "."))
  { i++
  }
  // Ha de haber algún carácter después del punto
  if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
  else return true;
}

/**
 * esNatural(s)
 * Devuelve true si el String no contiene ni "-" ni ".".
 */
 
function esNatural(s){
  var i;
  for(i=0; i < s.length; i++)
    {
	var c = s.charAt(i);
	if (c=="-") return false;
	if (c==".") return false;
    }
  return true;
}


/**
 * esNumeroNatural (s)
 * Devuelve true String es un numeroNatural, osea son digitos sin el punto ni el '-'
 */
function esNumeroNatural(s){
  var i;
  if (s.length==0){
  	return false;
  }
  for(i=0; i < s.length; i++) {
	var c = s.charAt(i);
	if ( numerosNaturales.indexOf(c) == -1) return false;
  }
  return true;
}

/**
 * esNumeroDecimal(s)
 *  Devuelve "true" si la cadena es un número entero o decimal. O sea está formada
 * por digitos numéricos y si contiene un "." sólo puede contener uno.
 */
function esNumeroDecimal(sText){

   var ValidChars = "0123456789.";
   var ValidInitialChars = "-0123456789";
   var IsNumber   = true;
   var Char;
   var Contador   = 0;
   
   // Ticket #1451: Control de negativo
   Char = sText.charAt(0);
   if (ValidInitialChars.indexOf(Char) == -1) {
   	  IsNumber = false;
   }
   
   // Miro que sean caracteres válidos
   for (i = 1; i < sText.length && IsNumber == true; i++) { 
     Char = sText.charAt(i); 
     if (ValidChars.indexOf(Char) == -1) {
       IsNumber = false;
     }
   }
   
   // Miro que sólo contenga un punto
   for (i = 0; i < sText.length && IsNumber == true; i++) { 
     Char = sText.charAt(i);
     if (Char == '.') Contador++;
   }
   if (Contador>1) IsNumber = false;
   
   return IsNumber;
}


/**
 * Este método devuelve una cadena con las comillas simples
 * transformadas a &#39; y las dobles a  &quot;
 */
function parseComillas(parametro){
  longitud=parametro.length;
  cadena='';
  for (i=0;i<longitud;i++){
    if (parametro.charAt(i)=='"'){
      cadena=cadena + '&quot;';
    }
    else if (parametro.charAt(i)=="'"){
      cadena=cadena + '&#39;';
    }
    else {
      cadena=cadena + parametro.charAt(i);
    }
  }
  return cadena;
}

function trim(inputString) {
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") {
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") {
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   return retValue;
}

function parseComillasParaBD(parametro){
  longitud=parametro.length;
  cadena='';
  for (i=0;i<longitud;i++){
    if (parametro.charAt(i)=="'") cadena=cadena + "\'";
    else cadena=cadena + parametro.charAt(i);
  }
  return cadena;
}

function parseComillasParaBD2(str){
    var strParseado1="";
    var strParseado2="";
    var i=0;
    while(str.indexOf("&quot;")!=-1){
      strParseado1=strParseado1 + str.substring(i,str.indexOf("&quot;"));
      strParseado1=strParseado1 + '"';
      i=str.indexOf("&quot;")+6;
    }
    strParseado1=strParseado1 + str.substring(i,str.length);
    i=0;
    while(strParseado1.indexOf("&#39;")!=-1){
      strParseado2=strParseado2 + strParseado1.substring(i,strParseado1.indexOf("&#39"));
      strParseado2=strParseado2 + "\'";
      i=strParseado1.indexOf("&#39;")+5;
    }
    strParseado2=strParseado2 + strParseado1.substring(i,strParseado1.length);
    return strParseado2;
}

function confirma(mensaje,url){
  if (confirm(mensaje)) {
    document.location=url;
  }
}

/***************************************
 * Métodos de apertura de ventanas     *
 ***************************************/

/**
 * abrir_ventana(a,b,c)
 * Abre una ventana con:
 * a = url
 * b = nombre de la ventana
 * c = 'features'
 */
function abrir_ventana(a,b,c){
  window.open(a,b,c);
}

y='toolbar=yes,location=yes,resizable=yes,status=yes,scrollbars=yes,menubar=yes,width=';

/**
 *
 */
function n(url,features){

  // sd = fecha y hora actual
  var sd = new Date();
  
  // le quito la cadena "http://" a 'name'
  // wo = (url.substring(7,name.length));

  
  if (parseInt(navigator.appVersion)>=4){
    window.open(url, sd.getTime(), y+((screen.width/100)*80)+",height="+(((screen.height/100)*85)-200)+",left="+((screen.width/100)*9)+",top="+((screen.height/100)*14));
  }
  else {
    window.open(url,sd.getTime(),y+"600,height=280");
  }  
}

function abrir_img(im,ancho,alto){
  imagen   =im;
  anchoi   =ancho;
  altoi    =alto;
  masAlto  =alto+11;
  features = "width="+ancho+",height="+altoi+"screenX=0,screenY=0";
  newwin = window.open("ver_imagen.html",ancho+alto,features);
}

function abrir_img_num(im,num,ancho,alto){
  imagen   =im;
  anchoi   =ancho;
  altoi    =alto;
  masAlto  =alto+11;
  features = "width="+ancho+",height="+altoi+"screenX=0,screenY=0";
  newwin = window.open("ver_imagen.html",num,features);
}

/**
 * muestraVentanaColor(formulario, elemento, descripcion)
 * Método muestra la ventana de elección del color.
 */
function muestraVentanaColor(formulario, elemento, descripcion) {
  var color_chooser = window.open("../vistas/ColorChooser.jsp?e="+elemento.name+"&d="+descripcion+"&f="+formulario,"ColorChooser","width=400,height=450,menubar=0,scrollbars=1,toolbar=0,resizable=1");
  color_chooser.focus();
}

/**
 * GrabaCierra()
 * Método que envia el formulario y cierra la ventana.
 */
function GrabaCierra(){
 document.form1.submit();
 self.close();
 window.opener.location.reload();
}

/***************************************
 * Métodos de control de layers        *
 ***************************************/

function showlayer(lay) {
  if (ie4) {document.all[lay].style.visibility = "visible";}
  if (ns4) {document.layers[lay].visibility = "show";}
  if (ns6) {document.getElementById([lay]).style.display = "block";}
}

function hidelayer(lay) {
  if (ie4) {document.all[lay].style.visibility = "hidden";}
  if (ns4) {document.layers[lay].visibility = "hide";}
  if (ns6) {document.getElementById([lay]).style.display = "none";}
}

function anchoCorrecto(ancho) {
  if(esNumeroNatural(ancho)){
    if(ancho>0 && ancho<101){ return true; }
  }
  else return false;
}

function asistentePPI(destino,tipoParticipacion) {
  var url = '../vistas/ClienteEntregaPuntosPPI.jsp?tp='+tipoParticipacion+'&url='+escape(document.getElementById(destino).value);
  winRef = window.open(url,'EntregaPuntosPPI','width=720,height=240,scrollbars=yes');
  winRef.destino = destino;
}
// Extender DOM para tener forEach (JavaScript 1.5)
if (!Array.prototype.forEach) {
	Array.prototype.forEach = function(fun /*, thisp*/) {
	  var len = this.length;
	  if (typeof fun != "function")
	    throw new TypeError();
	
	  var thisp = arguments[1];
	  for (var i = 0; i < len; i++) {
	    if (i in this)
	      fun.call(thisp, this[i], i, this);
	  }
	};
}
