
/***** ROLLOVER SENCILLO QE TE CAGAS *****/
//en la imagen --> onmouseover="this.src=Imagenes[0].src;" onmouseout="this.src=Imagenes[1].src;"
//en onLoad de <body> -->onLoad="Precargar('rutarelativa/imagen-ON', 'rutarelativa/imagen-OFF')"
Imagenes = new Array();
function Precargar() {
	
  for (var i=0; i<Precargar.arguments.length; i++) {    
    Imagenes[i]=new Image; 
    Imagenes[i].src=Precargar.arguments[i];
  }
}



/***** Captura de la posición del ratón *****/
function Browser() {
this.isIE = false; // Internet Explorer
this.isNS = false; // Netscape
this.isOpera = false; // Opera
if (navigator.userAgent.indexOf("Netscape6/") >= 0) {
this.isNS = true;
return;
}
if (navigator.userAgent.indexOf("Gecko") >= 0) {
this.isNS = true;
return;
}
if (navigator.userAgent.indexOf("MSIE") >=0 && navigator.userAgent.indexOf("Opera") <0) {
this.isIE = true;
return;
}
if (navigator.userAgent.indexOf("Opera") >=0) {
this.isOpera = true;
return;
}
}

var browser = new Browser();

function initMovimiento(event){
cancelar();
if (browser.isIE || browser.isOpera) {
document.attachEvent("onmousemove", getposicion);
window.event.cancelBubble = true;
window.event.returnValue = false;
}
if (browser.isNS) {
document.addEventListener("mousemove", getposicion, true);
event.preventDefault();
}
}
function initPulsar(event){
cancelar();
if (browser.isIE || browser.isOpera) {
document.attachEvent("onclick", getposicion);
window.event.cancelBubble = true;
window.event.returnValue = false;
}
if (browser.isNS) {
document.addEventListener("click", getposicion, true);
event.preventDefault();
}
}
function getposicion(event){
if (browser.isIE) {
x = window.event.clientX + document.documentElement.scrollLeft
+ document.body.scrollLeft;
y = window.event.clientY + document.documentElement.scrollTop
+ document.body.scrollTop;
}
if (browser.isNS) {
x = event.clientX + window.scrollX;
y = event.clientY + window.scrollY;
}
if (browser.isOpera) {
x = window.event.clientX + document.documentElement.scrollLeft;
y = window.event.clientY + document.documentElement.scrollTop;
}
document.getElementById("posicion").style.visibility = "visible";
document.getElementById("posicion").style.left= (x - 55) +"px";
document.getElementById("posicion").style.top = y + 20 +"px";
document.getElementById("posicion").innerHTML = "Coordenada x: " + x + "<br>Coordenada y: " + y;
}

function cancelar() {
if (browser.isIE || browser.isOpera) {
document.detachEvent("onmousemove", getposicion);
document.detachEvent("onclick", getposicion);
}
if (browser.isNS ) {
document.removeEventListener("mousemove", getposicion, true);
document.removeEventListener("click", getposicion, true);
}
document.getElementById("posicion").style.visibility= "hidden";
}

//-----------------------------------------

// popups de imágenes de la galería
function popup(ruta_base, ancho, id_imagen)
{
	var features = "width=" + ancho + ", height=600";
	
	nueva = window.open(ruta_base + "admin/galeria/ver_imagen.php?id=" + id_imagen, "imagen", features);
	nueva.focus();
}
function popup_imagen(ruta_base, ancho, alto)
{
	var features = "width=" + ancho + ", height=" + alto;
	
	nueva = window.open(ruta_base, 'Imagen', features);
	nueva.focus();
}
// popups del detalle de un pedido
function detalle_pedido(ruta_base, ref)
{
	nueva = window.open(ruta_base + "admin/pedidos/ver_pedido.php?ref=" + ref, "Detalle de pedido", "width=500, height=500, scrollbars=1");
	nueva.focus();
}


// funciones para mostrar/ocultar capas
function mostrar_capa(event, capa)
{
	var flagstyle = document.getElementById('flagstyle');
	if (flagstyle.style.display == 'none') {
		document.getElementById(capa).style.display = "block";
		document.getElementById(capa).style.position = "absolute";

		if (browser.isIE) {
			x = window.event.clientX + document.documentElement.scrollLeft
			+ document.body.scrollLeft;
			y = window.event.clientY + document.documentElement.scrollTop
			+ document.body.scrollTop;
		}
		if (browser.isNS) {
			x = event.clientX + window.scrollX;
			y = event.clientY + window.scrollY;
		}
		if (browser.isOpera) {
			x = window.event.clientX + document.documentElement.scrollLeft;
			y = window.event.clientY + document.documentElement.scrollTop;
		}

		document.getElementById(capa).style.left= (x - (document.getElementById(capa).offsetWidth/2)) +"px";
		document.getElementById(capa).style.top = (y + 20) +"px";
	}
}
function ocultar_capa(capa)
{
	var flagstyle = document.getElementById('flagstyle');
	if (flagstyle.style.display == 'none') {
		document.getElementById(capa).style.display = "none";
		document.getElementById(capa).style.position = "absolute";

		if (browser.isIE || browser.isOpera) {
			document.detachEvent("onmousemove", getposicion);
			document.detachEvent("onclick", getposicion);
		}
		
		if (browser.isNS ) {
			document.removeEventListener("mousemove", getposicion, true);
			document.removeEventListener("click", getposicion, true);
		}
	}
}

function habilitar_campos(fPedido1)
{
	document.fPedido1.nombre.readOnly    = true;
	document.fPedido1.apellidos.readOnly = true;
	
	document.fPedido1.direccion.readOnly = false;
	document.fPedido1.direccion.style.backgroundColor = '#FFFFFF';
	document.fPedido1.direccion.focus();
	
	document.fPedido1.cp.readOnly        = false;
	document.fPedido1.cp.style.backgroundColor = '#FFFFFF';
	
	document.fPedido1.poblacion.readOnly = false;
	document.fPedido1.poblacion.style.backgroundColor = '#FFFFFF';
	
	document.fPedido1.provincia.readOnly = false;
	document.fPedido1.provincia.style.backgroundColor = '#FFFFFF';
	/*
	document.fPedido1.pais.readOnly      = false;
	document.fPedido1.pais.style.backgroundColor = '#FFFFFF';
	*/
	return false;
}

function validar_formulario(fRestablecer)
{
	var datos = "";
			
	if (document.fRestablecer.nombre_user.value == "")
		var datos = datos + "\n>> Nombre incompleto";
	
	if (document.forms.fRestablecer.dni_user.value.length == 0)
		var datos = datos + "\n>> DNI incorrecto (ej: 12345678X)";
	else
	{
		if (!nif(document.forms.fRestablecer.dni_user.value) || document.forms.fRestablecer.dni_user.value.length > 9)
			var datos = datos + "\n>> DNI incorrecto (ej: 12345678X)";				
	}
	
	if (document.fRestablecer.email_user.value == "")
		var datos=datos + "\n>> Email incompleto";
	else
	{
			if (!isValidEmail(document.fRestablecer.email_user.value))
				var datos = datos + "\n>> Email incorrecto";
	}
	
	if (datos != "")
	{
		alert(datos);
		return (false);
	}
	else
	{
		return (true);
	}
}

function validar_registro(fRegistro)
{
	
	var datos = "";
	
	if (document.fRegistro.nombre_usuario.value == "")
		var datos = datos + "\n>> Campo Nombre de Usuario incompleto";
	
	if (document.fRegistro.password1.value == "" || document.fRegistro.password2.value == "")
		var datos = datos + "\n>> Campo Contraseña o confirmación de contraseña incompleto";
	else if (document.fRegistro.password1.value != "" && document.fRegistro.password2.value != "")
	{
		if (document.fRegistro.password1.value != document.fRegistro.password2.value != "")
			var datos = datos + "\n>> Las contraseñas especificadas deben ser iguales";
		else
			if (document.fRegistro.password1.value.length < 5)
				var datos = datos + "\n>> La Contraseña especificada es demasiado corta. Debe ser mayor de 4 caracteres.";
	}
	
	if (document.fRegistro.nombre_real.value == "")
		var datos = datos + "\n>> Campo Nombre incompleto";
	
	if (document.fRegistro.apellidos.value == "")
		var datos = datos + "\n>> Campo Apellidos incompleto";
	
	if (document.forms.fRegistro.dni.value.length == 0)
		var datos = datos + "\n>> Campo NIF/CIF/NIE incompleto (ej: 12345678X / A12345678 / X1234567Q)";
	else
	{
		if ((!nif(document.forms.fRegistro.dni.value) && !cif(document.forms.fRegistro.dni.value) && !nie(document.forms.fRegistro.dni.value)) || document.forms.fRegistro.dni.value.length > 9)
			var datos = datos + "\n>> NIF/CIF/NIE) incorrecto (ej: 12345678X / A12345678 / X1234567Q)";				
	}
	
	if (document.fRegistro.direccion.value == "")
		var datos = datos + "\n>> Campo Dirección incompleto";
	
	if (document.fRegistro.codigopostal.value == "")
		var datos = datos + "\n>> Codigo Postal incompleto";
	else
	{
		cp = parseInt(document.fRegistro.codigopostal.value);
	  	if (isNaN(cp))
      	var datos = datos + "\n>> El Codigo postal es incorrecto. Campo numérico.";
      else if (document.fRegistro.codigopostal.value.length > 5 || document.fRegistro.codigopostal.value.length < 5)
       		var datos = datos + "\n>> El Código Postal debe tener 5 cifras";      
	}

	if (document.fRegistro.localidad.value == "" || document.fRegistro.localidad.value == "Seleccione antes una provincia")
		var datos = datos + "\n>> Campo Localidad incompleto";
	
	if (document.fRegistro.provincia.value == "" || document.fRegistro.provincia.value == "Seleccione su provincia...")
		var datos = datos + "\n>> Campo Provincia incompleto";
		

	if (document.fRegistro.telefono.value == "")
		var datos = datos + "\n>> Campo Teléfono incompleto";
	else
	{
		telefono = parseInt(document.fRegistro.telefono.value);
   	if (isNaN(telefono))
    	var datos = datos + "\n>> Teléfono incorrecto. Campo numérico.";
    else if (document.fRegistro.telefono.value.length > 9 || document.fRegistro.telefono.value.length < 9)
   		var datos = datos + "\n>> El campo Teléfono debe tener nueve cifras";      	
	}

	if (document.fRegistro.email_usuario.value == "")
		var datos=datos + "\n>> Email incompleto";
	else
	{
			if (!isValidEmail(document.fRegistro.email_usuario.value))
				var datos = datos + "\n>> Email incorrecto";
	}
	
	if (datos != "")
	{
		alert(datos);
		return (false);
	}
	else
	{
		return (true);
	}
}


//Funcion para validar un email
function isValidEmail(email, required) {
    if (required==undefined) {   // if not specified, assume it's required
        required=true;
    }
    
    email = trim(email);
    
    if (email==null) {
        if (required) {
            return false;
        }
        return true;
    }
    if (email.length==0) {  
        if (required) {
            return false;
        }
        return true;
    }
    if (! allValidChars(email)) {  // check to make sure all characters are valid
        return false;
    }
    if (email.indexOf("@") < 1) { //  must contain @, and it must not be the first character
        return false;
    } else if (email.lastIndexOf(".") <= email.indexOf("@")) {  // last dot must be after the @
        return false;
    } else if (email.indexOf("@") == email.length) {  // @ must not be the last character
        return false;
    } else if (email.indexOf("..") >=0) { // two periods in a row is not valid
	return false;
    } else if (email.indexOf(".") == email.length) {  // . must not be the last character
	return false;
    }
    return true;
}

function allValidChars(email) {
  var parsed = true;
  var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-_";
  for (var i=0; i < email.length; i++) {
    var letter = email.charAt(i).toLowerCase();
    if (validchars.indexOf(letter) != -1)
      continue;
    parsed = false;
    break;
  }
  return parsed;
}

function ltrim(cadena) { 
    return cadena.replace(/^\s+/, ""); 
} 
 
function rtrim(cadena) { 
    return cadena.replace(/\s+$/, ""); 
} 
 
function trim(cadena) { 
    return rtrim(ltrim(cadena)); 
}
// Comprueba la entrada de DNI
function nif(dni) 
{
  numero = dni.substr(0,dni.length-1);
  let = dni.substr(dni.length-1,1);
  let = let.toUpperCase();
  numero = numero % 23;
  letra='TRWAGMYFPDXBNJZSQVHLCKET';
  letra=letra.substring(numero,numero+1);
  
  if (letra!=let) 
    return false;
   else
   	return true;
}
// Comprueba la entrada de un NIE
function nie(nie) 
{
	var temp=nie.toUpperCase();
	var cadenadni="TRWAGMYFPDXBNJZSQVHLCKE";

  //comprobacion de NIEs
  //T
  if (/^[T]{1}/.test(temp))
	{
		if (nie[8] == /^[T]{1}[A-Z0-9]{8}$/.test(temp))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
 
	//XYZ
	if (/^[XYZ]{1}/.test(temp))
	{
		pos = str_replace(['X', 'Y', 'Z'], ['0','1','2'], temp).substring(0, 8) % 23;
		if (nie[8] == cadenadni.substring(pos, pos + 1))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
   	
}
function str_replace(search, replace, subject) {
   
    var f = search, r = replace, s = subject;
    var ra = r instanceof Array, sa = s instanceof Array, f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;
 
    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
        }
    };
 
    return sa ? s : s[0];
}
// Comprueba la entrada de CIF
function cif(elCIF) 
{
  var resul = false;
  var cif = elCIF.toUpperCase(); 

  if ((!/^[A-Za-z0-9]{9}$/.test(cif)) || (!/^[ABCDEFGHJKLMNPQRSUV]/.test(cif)))
		resul = false;
  else
    resul = true;
   
   return resul;
}
function vaciar_carrito()
{
	if (confirm('¿Estás seguro de desea eliminar definitivamente los artículos del carrito?'))
		return true;
	else
		return false;
}
function borrar_articulo()
{
	if (confirm('¿Estás seguro de desea eliminar definitivamente este artículo?'))
		return true;
	else
		return false;
}

function modificar_estado()
{
	if (confirm('¿Estás seguro de desea modificar el estado de este pedido?'))
		return true;
	else
		return false;
}

function validar_contactar(fContacto)
{
	var datos = "";
			
	if (document.fContacto.telefono.value == "")
		var datos = datos + "\n>> Teléfono incompleto";
	
	if (document.fContacto.comentarios.value == "")
		var datos = datos + "\n>> Consulta incompleta";
	
	if (document.fContacto.email.value == "")
		var datos=datos + "\n>> Email incompleto";
	else
	{
			if (!isValidEmail(document.fContacto.email.value))
				var datos = datos + "\n>> Email incorrecto";
	}
	
	if (datos != "")
	{
		alert(datos);
		return (false);
	}
	else
	{
		return (true);
	}
}

/********************** popup para ampliar imagen *************************/
var _img_grande;

function mostrar() 
{
	var ops = "top=" + ((screen.height - _img_grande.height) / 2);
	ops += ",left=" + ((screen.width - _img_grande.width) / 2);
	ops += ",width=" + _img_grande.width + ",height=" + _img_grande.height;
	var contenido = "<html><body style='background-image: url(" + _img_grande.src + ");background-repeat: no-repeat;'></body></html>";
	var ventana = window.open("", "", ops);
	ventana.document.write(contenido);
	ventana.document.close();
}

function cargando() 
{
	if (_img_grande.complete) 
		mostrar();
	else 
		setTimeout("cargando()", 100);
}

function abrir(imagen) 
{
	_img_grande = new Image();
	_img_grande.src = imagen;
	cargando();
}
function mostrar_capa_boton(capa)
{
	
	var flagstyle = document.getElementById(capa);
	if (flagstyle.style.display == 'none') 
	{
		document.getElementById(capa).style.display = "block";
	}
	else if (flagstyle.style.display == 'block') 
	{
		document.getElementById(capa).style.display = "none";
	}
}
