function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

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 MM_findObj(n, d) { //v4.01
  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 && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

$(document).ready(function(){
	/*$(document).pngFix();
	$('.png').pngFix();*/
})


function urlDecode(str){
  	str=str.replace(new RegExp('\\+','g'),' ');
    return unescape(str);
}

function cambiacategorias(inicio){
	$.ajax({
		url: "carga_categorias.asp",
		type: 'POST',
		dataType: 'text',
		data: "inicio="+inicio,
		timeout: '',
		error: function(){
			alert("Se ha producido un error");
		},
		success: function(data){
			$("#categorias").html(urlDecode(data));
		}
	});
}

function cambianovedades(inicio){
	$.ajax({
		url: "carga_novedades.asp",
		type: 'POST',
		dataType: 'text',
		data: "inicio="+inicio,
		timeout: '',
		error: function(){
			alert("Se ha producido un error");
		},
		success: function(data){
			$("#novedades").html(urlDecode(data));
		}
	});
}

function cambiaopinion(inicio,idarticulo){
	$.ajax({
		url: "carga_opiniones.asp",
		type: 'POST',
		dataType: 'text',
		data: "inicio="+inicio+"&idarticulo="+idarticulo,
		timeout: '',
		error: function(){
			alert("Se ha producido un error");
		},
		success: function(data){
			$("#opinion").html(urlDecode(data));
		}
	});
}


function ventana (url, width, height, name, parms)
{
	var left = Math.floor( (screen.width - width) / 2);
	var top = Math.floor( (screen.height - height) / 2);
	var winParms = "resize=true,scrollbars=yes,top=" + top + ",left=" + left + ",height=" + height + ",width=" + width;
	if (parms) { winParms += "," + parms; }
	var win = window.open(url, name, winParms);
	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
	return win;
}	



function abrirCarrito(){
	ventana("cesta.asp", 800, 450, "cesta", "");
	/*carrito=window.open("carrito.asp", "carrito", 'toolbar=0,scrollbars=yes, resizable=no, width=812, height=450, left=0, top=0');
	carrito.focus();*/
	return false;
}

function abreCarrito(){
	var fecha = new Date;
	var timestamp = fecha.getHours() + "_" + fecha.getMinutes() + "_" + fecha.getSeconds();
	if ($("#numLibros").html()!="0") {
		$("#iframe_cesta").attr("src","cesta.asp?kc=" + timestamp);
		$('#iframe_cesta').modal();
	} else {
		alert("No tiene ningún libro en su cesta.")	
	}
	
	return false;
}


function carrito_accion (accion,id_articulo,unidades,recarga) {
	if ((accion == "add") && (!recarga)) {
		$("#cargando").slideDown('slow');
	}
	$.ajax({
		url: "cesta_acciones.asp",
		type: 'POST',
		dataType: 'text',
		data: "accion=" + accion + "&id_articulo=" + id_articulo + "&uds=" + unidades,
		timeout: '',
		error: function(){
			alert("Se ha producido un error");
		},
		success: function(data){
			if ((accion == "add") && (!recarga)) {
				setTimeout("$('#cargando').slideUp('slow')",1500)
			}
			if (recarga) {
				top.window.document.getElementById("numLibros").innerHTML = data;
				if (data!="0") {
					document.facciones.submit();
				} else {
					document.facciones.submit();
					cerrar();
					
				}
			} else {
				document.getElementById("numLibros").innerHTML = data;	
			}
		}
	});
}

function cerrar() {
	$('#modalOverlay').fadeOut();
	$.modal.close(false);
}

//funciones de fecha
function esBisiesto(anyo)
{
        /**
        * si el año introducido es de dos cifras lo pasamos al periodo de 1900. Ejemplo: 25 > 1925
        */
        if (anyo < 100)
            var fin = anyo + 1900;
        else
            var fin = anyo ;

        /*
        * primera condicion: si el resto de dividir el año entre 4 no es cero > el año no es bisiesto
        * es decir, obtenemos año modulo 4, teniendo que cumplirse anyo mod(4)=0 para bisiesto
        */
        if (fin % 4 != 0)
            return false;
        else
        {
            if (fin % 100 == 0)
            {
                /**
                * si el año es divisible por 4 y por 100 y divisible por 400 > es bisiesto
                */
                if (fin % 400 == 0)
                {
                    return true;
                }
                /**
                * si es divisible por 4 y por 100 pero no lo es por 400 > no es bisiesto
                */
                else
                {
                    return false;
                }
            }
            /**
            * si es divisible por 4 y no es divisible por 100 > el año es bisiesto
            */
            else
            {
                return true;
            }
        }
}

function validarFecha(Cadena){

	var Fecha= new String(Cadena)	// Crea un string
	var RealFecha= new Date()	// Para sacar la fecha de hoy
	var Ano= new String(Fecha.substring(Fecha.lastIndexOf("/")+1,Fecha.length))
	var Mes= new String(Fecha.substring(Fecha.indexOf("/")+1,Fecha.lastIndexOf("/")))
	var Dia= new String(Fecha.substring(0,Fecha.indexOf("/")))
	
	if (isNaN(Ano) || Ano.length<4 || parseFloat(Ano)<1900 || Ano.length>4){
        	
		return false
	}
	//comprobamos q el año no sea inferior a 1900 ni tenga solo 3 cifras, ya q sino da problemas de formato.
	if(Ano.length==4){
		if (Ano<1900){
		return false
		}
	}
	if (Ano.length==3){
		return false
	}
	//fin comprobar año
	if (isNaN(Mes) || Mes.length>2 || Mes.length<1 || parseFloat(Mes)<1 || parseFloat(Mes)>12){
		
		return false
	}
	if (isNaN(Dia) || Dia.length<1 || Dia.length>2 || parseFloat(Dia)<1 || parseFloat(Dia)>31){
		
		return false
	}
	var bisiesto=esBisiesto(Ano)
	if (Mes==4 || Mes==6 || Mes==9 || Mes==11 || Mes==2) {
		if ( ((Mes==2) && (Dia > 28) && !(bisiesto) ) || (Dia>30) || ((bisiesto) && (Mes==2) && (Dia>29))) 																																	{    			
			return false
		}
	}
 	return true	
}

//funcioin de validacion de email
function validarEmail(email) {
	caracNoValidos = " /:,;";
	if(email == "") return false; 							// debe rellenarse
	for(i = 0; i < caracNoValidos.length; i++) {			// ¿hay algún carácter no válido?
		caracMal = caracNoValidos.charAt(i);
		if(email.indexOf(caracMal,0) > -1) return false;
	}
	posArroba = email.indexOf("@",1); 						// debe haber una @
	if(posArroba == -1) return false;
	if(email.indexOf("@",posArroba+1) != -1) return false;	// y sólo una
	posPunto = email.indexOf(".",posArroba);
	if(posPunto == -1) return false;  						// y al menos un . después de la @
	if(posPunto+3 > email.length) return false; 			// debe haber al menos 2 caracteres tras el .
	return true;
}

// Compara 2 fechas. 
// Si String1>String2 entonces devuelve false.
// Si tipoFecha es true las fechas vienen en formato americano.
function Comparar_Fecha(String1,String2,tipoFecha) {
	sFecha1 = new String(String1);
	sFecha2 = new String(String2);
	if (!tipoFecha) {
		ArrayFecha1=sFecha1.split("/");
		ArrayFecha2=sFecha2.split("/");
		sFecha1=ArrayFecha1[1]+"/"+ArrayFecha1[0]+"/"+ArrayFecha1[2];
		sFecha2=ArrayFecha2[1]+"/"+ArrayFecha2[0]+"/"+ArrayFecha2[2];
	} else {
		sFecha1 = String1;
		sFecha2 = String2;
	}
	//date.parse lo que hace es devolverte un numero entero, con lo cual la comparacion es asi de simple
	numFecha1=Date.parse(sFecha1);
	numFecha2=Date.parse(sFecha2);

	if (numFecha1>numFecha2) return false 
	return true;
}


//funcion q comprueba si el valor recibido es un numero y devuelve true i false
//tipo
	//"decimal"
	//"enteiro"
//signo
	//1 -> +
	//0 -> + e -
	//-1 -> -
//nulo -> si vale 1 quere decir non se permite o valor 0, se non se pasa pu pasaselle 0 quere decir q se permite o valor 0
function compruebaNumero(n,tipo,signo,nulo)
{
	var decimal=/^((\d+(\.\d*)?)|((\d*\.)?\d+)|(\d+(\,\d*)?)|((\d*\,)?\d+))$/

	if (n=="") return false;
	if (isNaN(n)) return false;
	if(tipo=="decimal") if(!decimal.test(n)) return false;
	if(tipo=="enteiro") if (n!=parseInt(n)) return false;
	if (isNaN(signo)) return false;
	if(nulo) if (isNaN(nulo)) return false;
	if(!nulo) nulo=0; else if(nulo!=1) nulo=0;
	switch(signo)
	{
		case 1://positivo
			if(nulo==0){ if(n<0) return false; }else{  if(n<=0) return false;}
			break;
		case 0://positivo negativo
			if(nulo==1){ if(n==0) return false; }
			break;
		case -1://negativo
			if(nulo==0){ if(n>0) return false; }else{  if(n>=0) return false;}
			break;
	}
	return true;
}