
/****************************************************************************
 Carga la URL dada en la ventana del navegador
****************************************************************************/
function Recarga(sURL){
        //EncolaTarea(function(){window.location.href=sURL });
        EncolaTarea(new Function("window.location.href='"+sURL+"'" ));
        //window.location.href=sURL;
        //exit;
}

function RecargaInmediata(sURL){
        window.location.href=sURL;
        //exit;
}


/* Params=
top     integer     Specifies how far from the top of the screen to position the window, in pixels. Note that the browser will not let you position something entirely off the screen.
left    integer     Specifies how for from the left of the screen to position the window, in pixels. Note that the browser will not let you position something entirely off the screen.
height  integer     The external height of the window. Takes an integer that represents the size of the window in pixels. To avoid malicious code in hidden windows you cannt make the window any smaller than the height of the title bar plus the window frame. You also cannot create a window without a title bar.
width   integer     The external width of the window. Takes an integer that represents the size of the window in pixels. To avoid malicious code in hidden windows, you cannot set the width to below 100 pixels. You can, but the browser will ignore you.
dependent:  (Javascript 1.2) yes|no  Si es 'yes', crea una nueva ventana como un hijo de la ventana actual. Una ventana dependiente se cierra cuando su ventana madre se cierra. En la plataforma Windows, una ventana dependiente no se muestra en la barra de tareas.
copyHistory     yes|no  Copy the history object from the current window to the new window.
directories:    yes|no Si es 'yes', crea los botones de directorio comunes.
location    yes|no  Show the location bar.
menubar     yes|no  Show the menu bar.
status  yes|no  Show the status bar.
toolbar     yes|no  Show the toolbar.
resizable   yes|no  Is the user allowed to resize the window. Note that in some browsers, even if you select no, the user can still maximize the window, they just can't resize it by dragging on its frame.
scrollbars  yes|no  Is the window scrollable. If no, then they will not even be able to scroll down with the mouse, so make sure it all fits on the screen.
*/
function AbreVentana(sUrl, iAncho, iAlto, sNombre){
    var iLeft=Math.floor((screen.width - iAncho)/2);
    var iTop=Math.floor((screen.height - iAlto)/2);
    var sParams="top=" + iTop + ", left=" + iLeft + ", height=" + iAlto + ", width=" + iAncho;
    sParams=sParams+", status=yes, menubar=yes";
    //alert(sUrl +" "+ sNombre +" "+ sParams);
    window.open(sUrl, sNombre, sParams );
}

function CierraVentana(sNombre){
  //self.close();
  alert("Se cerrara");
  if ((typeof(sNombre) != "undefined")&&(!(sNombre.closed))){ 
      self.close();
  }
}

function ReloadParent(){
    window.opener.document.location.reload();
}



/******************************************************************
 Dado un ID de un elemento, se cambia su clase CSS. Esta funcion
 es principalmente para iluminar la pestaña activa del menu.
 Retorna true si se logro el cambio o false si no se pudo posiblemente
 porque no existe el ID
******************************************************************/
function CambiaClase(sId, sClase){

    oObj=document.getElementById(sId);
    if(oObj){
        oObj.className=sClase;
        sRet=true;
    }else
        sRet=false
    
    return (sRet);
    
} /* end CambiaClase */



/****************************************************************************
 Devuelve la fecha actual en el formato dado como argumento
****************************************************************************/
function FechaActual(sFormato){
    var now = new Date();
    var day = now.getDate();
    var month = now.getMonth()+1; // numbered from 0
    var year = now.getFullYear();
    var hora = "00"+now.getHours();
    var minuto= "00"+now.getMinutes();
    hora=hora.substr(hora.length-2,2);
    minuto=minuto.substr(minuto.length-2,2);
    if (year < 1900) year += 1900; // or use getFullYear() in v4 browsers
    //return(now.toLocaleDateString()+'<br>'+day+'/'+month+'/'+year+' '+hora+':'+minuto); 
    return(now.format(sFormato));
} /* end FechaActual() */

/*
 * DateFormat.js
 * Formats a Date object into a human-readable string
 *
 * Copyright (C) 2001 David A. Lindquist (http://www.gazingus.org)
 */

Date.MONTHS = [
  'January', 'February', 'March', 'April', 'May', 'June', 'July',
  'August', 'September', 'October', 'November', 'December'
];

Date.DAYS = [
  'Sunday', 'Monday', 'Tuesday', 'Wednesday',
  'Thursday', 'Friday', 'Saturday'
];

Date.SUFFIXES = [
  'st','nd','rd','th','th','th','th','th','th','th',
  'th','th','th','th','th','th','th','th','th','th',
  'st','nd','rd','th','th','th','th','th','th','th',
  'st'
];

Date.prototype.format = function( mask ) {
  var formatted     = ( mask != null ) ? mask : 'DD-MMM-YY';
  var letters       = 'DMYHdhmst'.split( '' );
  var temp          = new Array();
  var count         = 0;
  var regexA;
  var regexB        = /\[(\d+)\]/;

  var day           = this.getDay();
  var date          = this.getDate();
  var month         = this.getMonth();
  var year          = this.getFullYear().toString();
  var hours         = this.getHours();
  var minutes       = this.getMinutes();
  var seconds       = this.getSeconds();

  var formats       = new Object();
  formats[ 'D' ]    = date;
  formats[ 'd' ]    = date + Date.SUFFIXES[ date - 1 ];
  formats[ 'DD' ]   = ( date < 10 ) ? '0' + date : date;
  formats[ 'DDD' ]  = Date.DAYS[ day ].substring( 0, 3 );
  formats[ 'DDDD' ] = Date.DAYS[ day ];
  formats[ 'M' ]    = month + 1;
  formats[ 'MM' ]   = ( month + 1 < 10 ) ? '0' + ( month + 1 ) : month + 1;
  formats[ 'MMM' ]  = Date.MONTHS[ month ].substring( 0, 3 );
  formats[ 'MMMM' ] = Date.MONTHS[ month ];
  formats[ 'Y' ]    = ( year.charAt( 2 ) == '0' ) ? year.charAt( 3 ) : year.substring( 2, 4 );
  formats[ 'YY' ]   = year.substring( 2, 4 );
  formats[ 'YYYY' ] = year;
  formats[ 'H' ]    = hours;
  formats[ 'HH' ]   = ( hours < 10 ) ? '0' + hours : hours;  
  formats[ 'h' ]    = ( hours > 12 || hours == 0 ) ? Math.abs( hours - 12 ) : hours;
  formats[ 'hh' ]   = ( formats[ 'h' ] < 10 ) ? '0' + formats[ 'h' ] : formats[ 'h' ];
  formats[ 'm' ]    = minutes;
  formats[ 'mm' ]   = ( minutes < 10 ) ? '0' + minutes : minutes;
  formats[ 's' ]    = seconds;
  formats[ 'ss' ]   = ( seconds < 10 ) ? '0' + seconds : seconds;
  formats[ 't' ]    = ( hours < 12 ) ?  'A' : 'P';
  formats[ 'tt' ]   = ( hours < 12 ) ?  'AM' : 'PM';

  for ( var i = 0; i < letters.length; i++ ) {
    regexA = new RegExp( '(' + letters[ i ] + '+)' );
    while ( regexA.test( formatted ) ) {
      temp[ count ] = RegExp.$1;
      formatted = formatted.replace( RegExp.$1, '[' + count + ']' );
      count++;
    }
  }

  while ( regexB.test( formatted ) ) {
    formatted = formatted.replace( regexB, formats[ temp[ RegExp.$1 ] ] );
  }

  return formatted;
}



/**************************************************************************
 Como resultado de algunas operaciones hecha en la web, puede ser necesario
 que en la siguiente carga de la página se de algún mensaje de aviso o
 confirmacion. Para ello se crea una lista de funciones que se tiene que
 llamar una vez se ha cargado la página. Esta funcion las despacha.
 Esta lista tambien se usa para llamar a las funciones que se deben llamar
 una vez cargada la pagina, como los menus o la ventana de scroll.
 **************************************************************************/
var aTareas=new Array();
function DespachaTareas(){
    for(var a=0;a<aTareas.length;a++){
        //alert("Tarea:"+a+"/"+aTareas.length+" = "+aTareas[a]);
        eval(aTareas[a]);
    }
    //for(var a=aTareas.length-1;a>=0;a--){
    //    alert("Tarea:"+a+"/"+aTareas.length+" = "+aTareas[a]);
    //    eval(aTareas[a]);
    //}
}

/**************************************************************************
 Como resultado de algunas operaciones hecha en la web, puede ser necesario
 que en la siguiente carga de la página se de algún mensaje de aviso o
 confirmacion. Para ello se crea una lista de funciones que se tiene que
 llamar una vez se ha cargado la página. Esta funcion las encola.
 Esta lista tambien se usa para llamar a las funciones que se deben llamar
 una vez cargada la pagina, como los menus o la ventana de scroll.
 sTarea: tarea a realizar, puede ser una funcion o una orden javascript
**************************************************************************/
function EncolaTarea(sTarea){
    //aTareas[aTareas.length]=sTarea;
    //addEvent(window, "load", fprueba(), false);
    //addEvent(window, "load", function(){alert('seguda llamada') }, false);
    //addEvent(window, "load", new Function("alert('tercera llamada')"), false);
    //function fprueba(){
    //         alert("On load correcto");
    //}
    MyaddEvent(window, "load", sTarea, false);
    
}

// Cross-browser event handling
// by Scott Andrew LePera
// http://www.scottandrew.com/weblog/articles/cbs-events

// Modified 2004-08-10 by Andrew Grgeory to work around Konqueror bug
// Modified 2004-06-04 by Andrew Gregory to support legacy (NS3,4) browsers
// http://www.scss.com.au/family/andrew/

// eg. addEvent(imgObj, 'mousedown', processEvent, false);
function MyaddEvent(obj, evType, fn, useCapture) {
  // work around Konqueror bug #57913 which prevents
  // window.addEventListener('load',...) from working
  var ua = navigator.userAgent;
  var konq = ua.indexOf('KHTML') != -1 && ua.indexOf('Safari') == -1 && obj == window && evType == 'load';
  // don't use addEventListener for Konq, have Konq fall back to the old
  // obj.onload method
  if (obj.addEventListener && !konq) {
    obj.addEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.attachEvent) {
    return obj.attachEvent('on' + evType, fn);
  } else {
    if (!obj.cb_events) {
      obj.cb_events = new Object();
      obj.cb_ftemp = null;
    }
    var events = obj.cb_events[evType];
    if (!events) {
      events = new Array();
      obj.cb_events[evType] = events;
    }
    var i = 0;
    while ((i < events.length) && (events[i] != fn)) {
      i++;
    }
    if (i == events.length) {
      events[i] = fn;
      obj['on' + evType] = new Function("var ret=false,e=this.cb_events['"+evType+"'];if(e){for(var i=0;i<e.length;i++){this.cb_ftemp=e[i];ret=this.cb_ftemp()||ret;}return ret;}");
    }
    return true;
  }
}

// eg. removeEvent(imgObj, 'mousedown', processEvent, false);
function MyremoveEvent(obj, evType, fn, useCapture) {
  // work around Konqueror bug #57913 which prevents
  // window.addEventListener('load',...) from working
  var ua = navigator.userAgent;
  var konq = ua.indexOf('KHTML') != -1 && ua.indexOf('Safari') == -1 && obj == window && evType == 'load';
  // don't use addEventListener for Konq, have Konq fall back to the old
  // obj.onload method
  if (obj.removeEventListener && !konq) {
    obj.removeEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.detachEvent) {
    return obj.detachEvent('on' + evType, fn);
  } else {
    var ret = false;
    if (obj.cb_events) {
      var events = obj.cb_events[evType];
      if (events) {
        // remove any matching functions from the events array, shuffling items
        // down to fill in the space before truncating the array
        var dest = 0;
        for (var src = 0; src < events.length; src++) {
          if (dest != src) {
            events[dest] = events[src];
          }
          if (events[dest] == fn) {
            ret = true;
          } else {
            dest++;
          }
        }
        events.length = dest;
      }
    }
    return ret;
  }
}



/***************************************************************************
 Dado un campo de un formulario, comprueba si esta vacio. Si es asi
 retorna true, en caso de rellenado retorna false
***************************************************************************/
function CampoVacio(oCampo) {
    if(oCampo.value.length > 0) { return false; }
    return true;
}
/***************************************************************************
 Dado un array de campos de un formulario de tipo radio button, comprueba
 si estan todos desmarcados. Si es asi retorna true, en caso de rellenado
 retorna false
***************************************************************************/
function NingunCheck(oCampo) {
    for(var i = 0; i < oCampo.length; i++) {
	    if(oCampo[i].checked) { return false; }
	}
    return true;
}
/***************************************************************************
 Dado un campo de un formulario de tipo radio button, comprueba si esta
 marcado. Si es asi retorna true, en caso de rellenado retorna false
***************************************************************************/
function Chequeado(ss) {
    if(ss.checked) { return true; }
    return false;
}

/***************************************************************************
 Dado un campo de un formulario de tipo select, comprueba si hay algo
 seleccionado
 Si es asi retorna true, en caso de rellenado retorna false
***************************************************************************/
function Seleccionado(ss) {
    if(ss.selectedIndex==-1) { return false; }
    return true;
}


/***************************************************************************
 Algoritmo para calcular la letra del NIF. Dado el DNI retorna la letra
***************************************************************************/
function CalculaLetraNIF(sDNI){
  letras = new Array();
  letras[0]  = "T";
  letras[1]  = "R";
  letras[2]  = "W";
  letras[3]  = "A";
  letras[4]  = "G";
  letras[5]  = "M";
  letras[6]  = "Y";
  letras[7]  = "F";
  letras[8]  = "P";
  letras[9]  = "D";
  letras[10] = "X";
  letras[11] = "B";
  letras[12] = "N";
  letras[13] = "J";
  letras[14] = "Z";
  letras[15] = "S";
  letras[16] = "Q";
  letras[17] = "V";
  letras[18] = "H";
  letras[19] = "L";
  letras[20] = "C";
  letras[21] = "K";
  letras[22] = "E";
  
  sDNI = parseInt(sDNI);
  if (sDNI > 99999999){
    alert("Error. El DNI sólo tiene 8 dígitos")
  }else{
    letraDNI = letras[sDNI % 23];
    sDNI = sDNI.toString();
    sDNI = sDNI + letraDNI;
    //return sDNI
    return letraDNI;
  }

}

/***************************************************************************
 Algoritmo para comprobar si un NIF dado en el fomrmato 99999999Z es
 valido o no. Retorna true o false.
***************************************************************************/
function esNIFCorrecto(nif){
  txtError = "";
  ok = true;

  dni=nif.substring(0,nif.length-1);
  dni=parseInt(dni);
  letra=nif.charAt(nif.length-1);
  letraCorrecta = letras[ dni % 23];

  if (dni > 99999999){
    txtError += "El DNI tiene a lo sumo 8 cifras\n";
    ok = false;
  } else if(letra<"a" || letra>"Z"){
    txtError += "El último carácter debe ser una letra"
    ok = false;
  } else if(letra!=letraCorrecta) {
    txtError += "La letra correcta del NIF para "
    txtError += "ese DNI es " + letraCorrecta + "\n";
    ok = false;
  }

  if (ok) {
    return true;
  }else{
    alert(txtError);
    return false;
  }
}


// Credit Card Validation Javascript
// copyright 12th May 2003, by Stephen Chapman, Felgall Pty Ltd

// You have permission to copy and use this javascript provided that
// the content of the script is not changed in any way.

function validateCreditCard(s) {
var v = "0123456789";
var w = "";
for (var i=0; i < s.length; i++) {
x = s.charAt(i);
if (v.indexOf(x,0) != -1)
w += x;
}
var j = w.length / 2;
if (j < 6.5 || j > 8 || j == 7) return false;
var k = Math.floor(j);
var m = Math.ceil(j) - k;
var c = 0;
for (var i=0; i<k; i++) {
a = w.charAt(i*2+m) * 2;
c += a > 9 ? Math.floor(a/10 + a%10) : a;
}
for (var i=0; i<k+m; i++) c += w.charAt(i*2+1-m) * 1;
return (c%10 == 0);
}

/**************************************************************************
 Valida una entrada de una caja de texto para que solo permita numeros
 y como mucho el punto decimal.
 Se usa: onkeypress='return SoloNumeros(this, event, true)'
**************************************************************************/
function SoloNumeros(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;
}


/**************************************************************************
 Valida una entrada de una caja de texto para que solo permita letras
 Se usa: onkeypress='return SoloLetras(this, event, true)'
**************************************************************************/
function SoloLetras(myfield, e, dec){
var key;
var keychar;
var sLetras="abcdefghijklmnopqrstuvwxyz ";
    sLetras+="ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    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 ((sLetras.indexOf(keychar) > -1))
       return true;
    // decimal point jump
    else 
       return false;
}
