var nav4 = window.Event ? true : false;

function confirmar( mensaje, destino) {
    if (confirm(mensaje)) {
        document.location = destino ;
        setTimeout("close();",1500);
        window.opener.history.go(0);
    }
}
function confirmar2( mensaje, destino) {
    if (confirm(mensaje)) {
        document.location = destino ;
    }
}

function acceptNum(evt){
     // NOTE: Backspace = 8, Enter = 13, '0' = 48, '9' = 57
     var key = nav4 ? evt.which : evt.keyCode;
     return (key <= 13 || (key >= 48 && key <= 57));
}

function formateo(fld, milSep, decSep, e) {
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (whichCode == 13) return true; // Enter
    key = String.fromCharCode(whichCode); // Get key value from key code
    if (strCheck.indexOf(key) == -1) return false; // Not a valid key
    len = fld.value.length;
    for(i = 0; i < len; i++)
     if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
    aux = '';
    for(; i < len; i++)
     if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) fld.value = '';
    if (len == 1) fld.value = '0'+ decSep + '0' + aux;
    if (len == 2) fld.value = '0'+ decSep + aux;
    if (len > 2) {
     aux2 = '';
     for (j = 0, i = len - 3; i >= 0; i--) {
      if (j == 3) {
       aux2 += milSep;
       j = 0;
      }
      aux2 += aux.charAt(i);
      j++;
     }
     fld.value = '';
     len2 = aux2.length;
     for (i = len2 - 1; i >= 0; i--)
      fld.value += aux2.charAt(i);
     fld.value += decSep + aux.substr(len - 2, len);
    }
    return false;
}

function checkDecimals(fieldName, fieldValue, nombre) {

     decallowed = 6;  // how many decimals are allowed?

     if (isNaN(fieldValue) || fieldValue == "") {
         alert("Campo "+ nombre +" está vacío o contiene una cifra NO válida\nIntroduzca las cifras sin separadores de miles\n");
         return (false);
     }
     else {
         if (fieldValue.indexOf('.') == -1) fieldValue += ".";
         dectext = fieldValue.substring(fieldValue.indexOf('.')+1, fieldValue.length);

         if (dectext.length > decallowed)
         {
             alert ("No se permiten cifras con más de " + decallowed + " números decimales.");
             return (false);
         }
         else {
             return (true);
         }
     }
}

function ventana (URL,ANCHO,ALTO){
     ventana1 = window.open(URL,"ventana1","width="+ANCHO+", height="+ALTO+", scrollbars=yes, menubar=no, location=no, resizable=no")
     ventana1.focus();
}
function devuelveMunicipio(cp,mun,pro){
         //Se encarga de escribir en el formulario adecuado los valores seleccionados
         //también debe cerrar la ventana del calendario
         var formulario_destino = 'act'

         //meto el municipio
         eval ("opener.document.inmu.cod.value='" + cp + "'")
         eval ("opener.document.inmu.mun.value='" + mun + "'")
         eval ("opener.document.inmu.pro.value='" + pro + "'")
         window.close()
}


//FUNCIONES DE VALIDACION
//Validacion de Codigo Postal
function vcp(form) {

        if (form.value.length != 5) {
                alert ("Código Postal incorrecto");
                return (false);
        } else
                return (true);

}

//Validacion de campo obligatorio
function vobligatorio(form,nombre) {

        if (form.value.length < 1) {
                alert("El campo " + nombre + " NO puede estar vacío");
                return (false);
        } else
                return (true);
}
//Validacion de campo obligatorio
function vobligatorio2(form,nombre) {

        if (form.value.length < 1) {
                return ("-> El campo " + nombre + " NO puede estar vacío\n");
                form.focus();
        } else
                return ("");
}
//Validacion de campo no obligatorio
function vvacio2(form,nombre) {

        if (form.value.length < 1) {
                return ("");
        } else {
                return ("-> El campo " + nombre + " DEBE estar vacío\n");
                form.focus();
        }

}
//FIN FUNCIONES


// Validacion y envio de formularioInmueble
function envia_inmueble(form){

        var alerta="";

        alerta+=vobligatorio2(form.ref,"Referencia");
        alerta+=vobligatorio2(form.pro,"Provincia");
        alerta+=vobligatorio2(form.mun,"Localidad");
        alerta+=vobligatorio2(form.cod,"Codigo Postal");
        alerta+=vobligatorio2(form.pre,"Precio");
        alerta+=vobligatorio2(form.tpi,"Tipo inmueble");
        alerta+=vobligatorio2(form.ges,"Gestión");

        if(alerta!=""){
           alert(alerta);
           return (false);
        }

        return (true);
}

//Validacion de Formulario Municipios
function runMunicipios (form)  {

        if (!vcp(form.codigop)){
             form.codigop.focus();
             return (false);
        }
        if (!vobligatorio(form.municipio,"Municipio")){
             form.municipio.focus();
             return (false);
        }
        if (!vobligatorio(form.provincia,"Provincia")){
             form.provincia.focus();
             return (false);
        }

        return (true);
}


function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function recarga(){
window.location = "<?php echo $_SERVER['PHP_SELF']; ?>?var="+document.form.select_1.value;
onChange="location.reload()";
}

function linkmunicipios(select){
    location.href='buscar.php?op=municipios&pro='+ select.value;
}

function sobre (src, color_sobre ) {
      if (!src.contains(event.fromElement)) {
        src.style.cursor = "default";
        src.bgColor = color_sobre ;
        src.FontColor=" ff0000 ";
      }
}
function fuera (src, color_fuera ) {
      if (!src.contains(event.toElement)) {
        src.style.cursor = "default";
        src.bgColor = color_fuera ;
      }
}

function CargarFoto(img, ancho, alto){
      derecha=(screen.width-ancho)/2;
      arriba=(screen.height-alto)/2;
      string="toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width="+ancho+",height="+alto+",left="+derecha+",top="+arriba+"";
      fin=window.open(img,"Foto",string);
}

function IsNumeric(valor)
{
   var log=valor.length; var sw="S";
   for (x=0; x<log; x++){
     v1=valor.substr(x,1);
     v2 = parseInt(v1);
     //Compruebo si es un valor numérico
     if (isNaN(v2)) { sw= "N";}
   }
   if (sw=="S") {return true;} else {return false; }
}

var primerslap=false;
var segundoslap=false;

function formateafecha(fecha)
{
  var long = fecha.length;
  var dia;
  var mes;
  var ano;

  if ((long>=2) && (primerslap==false)) {
     dia=fecha.substr(0,2);
     if ((IsNumeric(dia)==true) && (dia<=31) && (dia!="00")) {
        fecha=fecha.substr(0,2)+"/"+fecha.substr(3,7); primerslap=true;
     }
     else { fecha=""; primerslap=false;}
  }
  else{
     dia=fecha.substr(0,1);
     if (IsNumeric(dia)==false) {fecha="";}
     if ((long<=2) && (primerslap=true)) {fecha=fecha.substr(0,1); primerslap=false; }
  }
  if ((long>=5) && (segundoslap==false)){
     mes=fecha.substr(3,2);
     if ((IsNumeric(mes)==true) &&(mes<=12) && (mes!="00")) { fecha=fecha.substr(0,5)+"/"+fecha.substr(6,4); segundoslap=true; }
     else { fecha=fecha.substr(0,3);; segundoslap=false;}
  }
  else { if ((long<=5) && (segundoslap==true)) { fecha=fecha.substr(0,4); segundoslap=false; } }
  if (long>=7){
     ano=fecha.substr(6,4);
     if (IsNumeric(ano)==false) { fecha=fecha.substr(0,6); }
     else { if (long==10){ if ((ano==0) || (ano<1900) || (ano>2100)) { fecha=fecha.substr(0,6); } } }
  }

  if (long>=10){
     fecha=fecha.substr(0,10);
     dia=fecha.substr(0,2);
     mes=fecha.substr(3,2);
     ano=fecha.substr(6,4);
     // Año no viciesto y es febrero y el dia es mayor a 28
     if ( (ano%4 != 0) && (mes ==02) && (dia > 28) ) { fecha=fecha.substr(0,2)+"/"; }
  }
  return (fecha);
}

function copiar(form){
  form.obseng.value=form.obsesp.value;
  form.obsdeu.value=form.obsesp.value;
  form.descrip.value=form.obsesp.value;

  return;
}