var isNS4 = (navigator.appName=="Netscape")?1:0;

// Implementa startsWith en los objetos String
String.prototype.startsWith = function(s) { 
	return this.indexOf(s)==0; 
}

// Corrector de Bug PNG para Explorer. Opera y Mozilla funcionan correctamente sin este JS
function correctPNG() 
   {
   for(var i=0; i<document.images.length; i++)
      {
	  var img = document.images[i]
	  var imgName = img.src.toUpperCase()
	  if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
	     {
		 var imgID = (img.id) ? "id='" + img.id + "' " : ""
		 var imgClass = (img.className) ? "class='" + img.className + "' " : ""
		 var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
		 var imgStyle = "display:inline-block;" + img.style.cssText 
		 if (img.align == "left") imgStyle = "float:left;" + imgStyle
		 if (img.align == "right") imgStyle = "float:right;" + imgStyle
		 if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
		 var strNewHTML = "<span " + imgID + imgClass + imgTitle
		 + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
	     + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
		 + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
		 img.outerHTML = strNewHTML
		 i = i-1
	     }
      }

   }
var ua = navigator.userAgent.toLowerCase();
function detect(text) {
   stringposition = ua.indexOf(text) + 1;
   data = text;
   return stringposition;
}
if (detect('opera')) {
	 
 } else if (detect('firefox')){
	 
 } else if (detect('msie')){
	 window.attachEvent("onload", correctPNG);	
}	

function MM_findObj(n, d) { //v4.0
  var p,i,x;  
  if(!d) d=document; 
  if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
  }
  if(!(x=d[n])&&d.all) x=d.all[n]; 
  for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); 
  return x;
}

function validaInputFecha(diaFech,mesFech,anyoFech) {
   var bisiesto;
	var days = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
	var fecha = diaFech.value.toString();
	var dia = parseInt(diaFech.value,10);
	var mes = parseInt(mesFech.value,10);
	var ano = parseInt(anyoFech.value,10);
	var limite=0 ;
	var indice;
	var fecha1 = new Date();
	var actual = Date.parse(fecha1);
	if (mes>12 || mes<1) {
		mesFech.focus();
		return false;
	}
	indice = mes--;
	(ano % 4 == 0) ? ((ano %100 ==0)?((ano % 400 ==0)? bisiesto = true : bisiesto = false) : bisiesto = true) : bisiesto = false;
	if ((bisiesto== true) && indice ==2)
		limite = 29
	else
		limite = days[mes];
	if (dia<0 || dia>limite) {
		diaFech.focus();
		return false;
	}
    
	return true;
}    

function validaInputFechaHoy(diaFech,mesFech,anyoFech) {
	var dia = parseInt(diaFech.value,10);
	var mes = parseInt(mesFech.value,10);
	var ano = parseInt(anyoFech.value,10);
	var fecha1 = new Date();

    var diaHoy = parseInt(fecha1.getDate(),10);
    var mesHoy = parseInt(fecha1.getMonth()+1, 10);
    /*var anyoHoy = parseInt(fecha1.getYear()+1900, 10);*/
	var anyoHoy = 0;
        if (fecha1.getYear()<=999){
            anyoHoy=parseInt(fecha1.getYear()+1900, 10);
        }else{
            anyoHoy=parseInt(fecha1.getYear(), 10);
        }
    
    if ((ano > anyoHoy) || (ano < (anyoHoy-9))){
        anyoFech.focus();
        return false;
    }else if ((ano==anyoHoy) && (mes > mesHoy)){
        mesFech.focus();
        return false;
    }else if ((ano==anyoHoy) && (mes==mesHoy) && (dia>diaHoy)){
        diaFech.focus();
        return false;
    }
   
	return true;
}        

function autocompleta(obj,longitud,caracter,sentido)
{
	if (obj.value=="") return;
	if (isNaN(obj.value)) return;
	obj.value = Fill(obj.value,longitud,caracter,sentido);
}

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

function autoCompleta(campo){
	campoValue=campo.value;
	if(isNaN(campoValue)){
		return false;
	}else if(campoValue.length==1){
		campo.value="0"+campoValue;
	}
}

function autoCompletaYear(year){
	var yearValue=year.value;
	if(isNaN(yearValue))
		return false;
	if(yearValue.length==2){
		if(yearValue <=10){
			year.value="20"+yearValue;
		}else{
			year.value="19"+yearValue;
		}
	}else if(yearValue.length==1){
		year.value="200"+yearValue;
		}else if(yearValue.length==3){
			if(yearValue <=10){
				year.value="2"+yearValue;
			}else{
				year.value="1"+yearValue;
			}
		}
	}

function comprobarUnidades(unidades){
	if (unidades.value == '' || parseInt(unidades.value) ==0 || parseInt(unidades.value)<0 || unidades.length<=0){
		unidades.value = '1';
	}
	return;
}
// patron que se utiliza al validar el correo en los jsp

var patronCorreoElectronico=/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  // Algo seguido de @ seguido de algo


function validarPatron(s,patron){
	var s1;
	var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/;
	s1=s.match(patron);
	return(((s1 !=null)&(s==s1))& (!reg1.test(s)));
}

function validarFecha(obj,diasP,diasF)
{
	if (obj.value.length >0)
	{
		s = obj.value;
				
		if (!checkDate(s))
		{
			s = fillDate(s);
		
			if (!checkDate(s))
			{
				obj.value="";
				obj.focus();
				return;
			}
		}
		
		//No fechas pasadas n dias
		if ( (diasP!=null) && (diasP!='') )
		{
			var desde = new Date();
			desde.setDate(desde.getDate() - parseInt(diasP));
			desde.setHours(0);
			desde.setMinutes(0);
			desde.setSeconds(0);
			desde.setMilliseconds(0);
			
			var tmp= s.split("\/");
			var fechaObj = new Date(tmp[2].substring(0,4), tmp[1]-1, tmp[0]);
			
			if (fechaObj<desde)
			{
				obj.value="";
				obj.focus();
				return;
			}		
		}
		
		//No fechas futuras n dias
		if ( (diasF!=null) && (diasF!='') )
		{
			var hasta = new Date();
		     	hasta.setDate(hasta.getDate() + parseInt(diasF));
		
			var tmp= s.split("\/");
			var fechaFutura = new Date(tmp[2].substring(0,4), tmp[1]-1, tmp[0]);
			
			if (fechaFutura>hasta)
			{
				obj.value="";
				obj.focus();
				return;
			}
		}
		
		obj.value = s;		
	}
}

function checkDate(strDate)
{
    if(strDate.length>0)
	{
    var dateregex=/^[ ]*[0]?(\d{1,2})\/(\d{1,2})\/(\d{4,})[ ]*$/;
    var match=strDate.match(dateregex);
    if (match)
	{
		var tmpdate=new Date(match[3],parseInt(match[2],10)-1,match[1]);
        	if (tmpdate.getDate()==parseInt(match[1],10) && tmpdate.getFullYear()==parseInt(match[3],10) && tmpdate.getFullYear()>1999 && tmpdate.getFullYear() < 2100 &&  (tmpdate.getMonth()+1)==parseInt(match[2],10))
		{
        	return true;
		}
	 }
     return false;
    }
    else
	{
         return false;
    }
}

function fillDate(str)
{
	if (str==null)  return "";
	
	str=str.replace(/\//g,'');
	
	var now=new Date();
	
	var mes = ( now.getMonth() + 1 ) + "";
	if (mes.length==1) mes = "0" + mes;
	if (str.length==1) str="0" + str;
	if (str.length==2) str=str + mes + now.getFullYear();	
	
	if (str.length==4)str=str + now.getYear();
	
	if ( (str==null) || (str.length<6) ) return "";
	s=str.substring(0,2) + "/" + str.substring(2,4) + "/";

	if (str.substring(4,str.length).length==2)
		s = s + "20" + str.substring(4,str.length);
	else
		s = s + str.substring(4,str.length);
	
	return s;
}

function checkDisponible(img, tmn, link){	

	if (tmn==undefined || tmn=='' || (tmn!='1' && tmn!='2' && tmn!='3')) { tmn = '1'; }
	
	if (img.src.search(/\/noFoto/i) == -1){		
		img.src = "/images/noFoto"+tmn+".gif";
		img.alt = "";					
		
		if ( link!=undefined && link!='' && eval(document.getElementById(link)) ){
			document.getElementById(link).href=img.src;
		}			
	}else{		
		img.parentNode.removeChild(img);
		if (eval(document.getElementById(link))){
			document.getElementById(link).parentNode.removeChild(document.getElementById(link));
		}
	}
}

function checkDispFicha(img, link){	
	
	e = eval(document.getElementById(link));
	
	if (img.src.search(/\/noFoto/i) == -1){
		img.src = "/images/noFoto2.gif";
		img.alt = "";		
		
		if (e!=undefined) { e.href = "/images/noFoto3.gif"; }
		
	}else{
		if (e!=undefined){
			e.parentNode.removeChild(e);
		}
	}
}

var contadorCarrito = 0;
function comprobarSubmitCarrito(f){
	contadorCarrito++;
	if (contadorCarrito>1){		
		return false;
	}else{		
		f.submit();		
		return;		
	}
	return false;
}

function limpiaLista(id, tag){
	if (eval(document.getElementById(id))){
		var elements = document.getElementById(id).getElementsByTagName(tag);
		for (var i=0; i<elements.length; i++){
			if (elements[i].innerHTML.search(/\[/)!=-1 || elements[i].innerHTML.search(/---/)!=-1){
				elements[i].parentNode.removeChild(elements[i]);
				i--;
			}
		}
	}
}

function cortarDescripcion (descripcion)
{
	if (descripcion!=null && descripcion.length>100){
		var pos = descripcion.indexOf(' ',100);
		
		var descrip = descripcion.substring(0,pos);
		
		
	}	
}

  /*function comprobarFormato(formato, cadena){
        var cumple = true;
        for (i=0;i<formato.length;i++){
            var numeros = new RegExp('\\d');
            var caracteres = new RegExp('\\w');
            var guion = new RegExp('[-]');
            /*var barra1 = new RegExp('[/]');
            var barra2 = new RegExp('[\]');
            var punto = new RegExp('[.]');
            var parent1 = new RegExp('[(]');
            var parent2 = new RegExp('[)]');
            var corch1 = new RegExp('[[]');
            var corch2 = new RegExp('[]]');*/
           
            /*var cad = formato.substring(i,i+1);
            var cad2 = cadena.substring(i,i+1);
            
            // “-“ “/” “\” “.” “(“ “)” “[“ “]” 
            
            if (numeros.test(cad)){
                if (!numeros.test(cad2)){
                    cumple = false;
                }
            }else if (caracteres.test(cad)){
                if (!caracteres.test(cad2)){
                    cumple = false;
                }
            }else if (guion.test(cad)){
                if (!guion.test(cad2)){
                    cumple = false;
                }
            }/*else if (barra1.test(cad)){
                if (!barra1.test(cad2)){
                    cumple = false;
                }
            }else if (barra2.test(cad)){
                if (!barra2.test(cad2)){
                    cumple = false;
                }
            }else if (punto.test(cad)){
                if (!punto.test(cad2)){
                    cumple = false;
                }
            }else if (parent1.test(cad)){
                if (!parent1.test(cad2)){
                    cumple = false;
                }
            }else if (parent2.test(cad)){
                if (!parent2.test(cad2)){
                    cumple = false;
                }
            }else if (corch1.test(cad)){
                if (!corch1.test(cad2)){
                    cumple = false;
                }
            }else if (corch2.test(cad)){
                if (!corch2.test(cad2)){
                    cumple = false;
                }
            }else{
                cumple = false;
            }
        }
        return cumple;
    }*/
    function comprobarFormato(formato, cadena){
        var cumple = true;
        for (i=0;i<formato.length;i++){
            var reg = new RegExp('\\d');
            var reg2 = new RegExp('\\w');
            var cad = formato.substring(i,i+1);
            var cad2 = cadena.substring(i,i+1);
            
            if (reg.test(cad)){
                if (!reg.test(cad2)){
                    cumple = false;
                }
            }else if (reg2.test(cad)){
                if (!reg2.test(cad2)){
                    cumple = false;
                }
            }else{
                cumple = false;
            }
        }
        return cumple;
    }
	
	
function comparaFechaMayorActual(dia, mes, anio)
{
	var fecha = new Date(dia, mes, anio);

	var hoy = new Date();

    if (fecha==hoy) return 0;
    if (fecha<hoy) return 1;
    if (fecha>hoy) return 2;
}


