// función trim para javascript
String.prototype.trim = function()
{
    return this.replace(new RegExp("^\\s+|\\s+$", "gi"), "");
}

/*
function isCreditCard(st){
  // Encoding only works on cards with less than 19 digits
  if (st.length > 19)
    return (false);

  sum = 0; mul = 1; l = st.length;
  for (i = 0; i < l; i++) {
    digit = st.substring(l-i-1,l-i);
    tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }
}
*/

/***** 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];
  }
}

/**** Validación de Formularios Genérica ****/
// Generic Form Validation
// Jacob Hage (jacob@hage.dk)

var checkObjects	= new Array();
var errors		= "";
var returnVal		= false;
var language		= new Array();
language["header"]	= "Los siguientes datos son obligatorios:"
language["start"]	= "->";
language["field"]	= " Campo ";
language["require"]	= " requerido";
language["min"]		= " y debe contener al menos ";
language["max"]		= " y no debe contener más de ";
language["minmax"]	= " y no más de ";
language["chars"]	= " caracteres";
language["num"]		= " y debe contener un número";
language["email"]	= " debe contener un correo válido";
// -----------------------------------------------------------------------------
// define - Call this function in the beginning of the page. I.e. onLoad.
// n = name of the input field (Required)
// type= string, num, email (Required)
// min = the value must have at least [min] characters (Optional)
// max = the value must have maximum [max] characters (Optional)
// d = (Optional)
// -----------------------------------------------------------------------------
function define(n, type, HTMLname, min, max, d) {
var p;
var i;
var 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 = define(n, type, HTMLname, min, max, d.layers[i].document);
return x;       
}
eval("V_"+n+" = new formResult(x, type, HTMLname, min, max);");
checkObjects[eval(checkObjects.length)] = eval("V_"+n);
}
function formResult(form, type, HTMLname, min, max) {
this.form = form;
this.type = type;
this.HTMLname = HTMLname;
this.min  = min;
this.max  = max;
}
function validate() {
if (checkObjects.length > 0) {
errorObject = "";
for (i = 0; i < checkObjects.length; i++) {
validateObject = new Object();
validateObject.form = checkObjects[i].form;
validateObject.HTMLname = checkObjects[i].HTMLname;
validateObject.val = checkObjects[i].form.value;
validateObject.len = checkObjects[i].form.value.length;
validateObject.min = checkObjects[i].min;
validateObject.max = checkObjects[i].max;
validateObject.type = checkObjects[i].type;
if (validateObject.type == "num" || validateObject.type == "string") {
if ((validateObject.type == "num" && validateObject.len <= 0) || (validateObject.type == "num" && isNaN(validateObject.val))) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['num'] + "\n";
} else if (validateObject.min && validateObject.max && (validateObject.len < validateObject.min || validateObject.len > validateObject.max)) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['min'] + validateObject.min + language['minmax'] + validateObject.max+language['chars'] + "\n";
} else if (validateObject.min && !validateObject.max && (validateObject.len < validateObject.min)) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['min'] + validateObject.min + language['chars'] + "\n";
} else if (validateObject.max && !validateObject.min &&(validateObject.len > validateObject.max)) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['max'] + validateObject.max + language['chars'] + "\n";
} else if (!validateObject.min && !validateObject.max && validateObject.len <= 0) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + "\n";
   }
} else if(validateObject.type == "email") {
// Checking existense of "@" and ".". 
// Length of must >= 5 and the "." must 
// not directly precede or follow the "@"
if ((validateObject.val.indexOf("@") == -1) || (validateObject.val.charAt(0) == ".") || (validateObject.val.charAt(0) == "@") || (validateObject.len < 6) || (validateObject.val.indexOf(".") == -1) || (validateObject.val.charAt(validateObject.val.indexOf("@")+1) == ".") || (validateObject.val.charAt(validateObject.val.indexOf("@")-1) == ".")) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['email'] + "\n"; }
      }
   }
}
if (errors) {
alert(language["header"].concat("\n" + errors));
errors = "";
returnVal = false;
} else {
returnVal = true;
   }
}

// 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();
}

// funciones para mostrar/ocultar capas
function mostrar_capa(capa)
{
	document.getElementById(capa).style.visibility = "visible";
	document.getElementById(capa).style.position = "relative";
}
function ocultar_capa(capa)
{
	document.getElementById(capa).style.visibility = "hidden";
	document.getElementById(capa).style.position = "absolute";
}

/***** recargar la página pasando el idioma *****/
// recarga la página actual pasándole un idioma nuevo
function recargar_pagina(pagina)
{
	var id_idioma = document.getElementById('idioma').value;
	window.location.href = pagina + "&idioma=" + id_idioma;
}

/***** función de volver (a la página indicada) *****/
function volver(url_destino)
{
	window.location.href = url_destino;
}

/***** recargar la página para pasar la categoria *****/
function seleccionar_familia()
{
	document.getElementById('fFamilias').submit();
}

/***** recargar la página para filtrar pedidos *****/
function filtrar_pedidos()
{
	document.getElementById('fPedidos').submit();
}

/***** popup con la imagen del produto *****/
// se tienen unas dimensiones fijas, por lo que será sencillo establecer la imagen centrada.
function popup_imagen(ruta_imagen)
{
	var salida = "";
	salida += "<html>";
	salida += "<head><title>Detalle de la imagen</title></head>";
	salida += "<body bgcolor='white' leftmargin='0' topmargin='0' marginwidth='0' marginheight='0'>";
	salida += "<table border='0' width='100%' height='100%' cellspacing='0' cellpadding='0'>";
	salida += "<tr>";
	salida += "<td align='center' valign='middle'>";
	salida += "<a href='#' onclick='javascript:window.close();'><img border='0' src='" + ruta_imagen + "'></a>";
	salida += "</td>";
	salida += "</tr>";
	salida += "</table>";
	salida += "</body>";
	salida += "</html>";
	
	nueva = window.open("", "", "width=525, height=510, scrollbars");
	nueva.document.write(salida);
	nueva.document.close();
	nueva.focus();
}

/***** confirmar borrado de elemento *****/
function confirmar_borrado(tipo_elemento, id)
{
	switch( tipo_elemento )
	{
		case "familias":
			mensaje = "Está a punto de borrar una familia de productos. Se borrarán también sus descripciones.\n¿Está seguro?";
			url_destino = "borrar_familia.php?id=" + id;
			break;
		
		case "generos":
			mensaje = "Está a punto de borrar un género de productos. Se borrarán también sus descripciones.\n¿Está seguro?";
			url_destino = "borrar_genero.php?id=" + id;
			break;
		
		case "atributos":
			mensaje = "Está a punto de borrar un atributo. Se borrarán sus descripciones y los valores de los productos asociados a este atributo.\n¿Está seguro?";
			url_destino = "borrar_atributo.php?id=" + id;
			break;
		
		case "elementos":
			mensaje = "Está a punto de borrar un elemento de lista. Se borrarán los valores de los productos que estén asociados a este elemento.\n¿Está seguro?";
			url_destino = "borrar_elemento_lista.php?id=" + id;
			break;
		
		case "productos":
			mensaje = "Está a punto de borrar un producto.\n¿Está seguro?";
			url_destino = "borrar_producto.php?id=" + id;
			break;
		
		case "descargas":
			mensaje = "Está a punto de borrar una descarga.\n¿Está seguro?";
			url_destino = "borrar_descarga.php?id=" + id;
			break;
		
		case "usuarios":
			mensaje = "Está a punto de borrar un usuario.\n¿Está seguro?";
			url_destino = "borrar_usuario.php?id=" + id;
			break;
		
		case "autores":
			mensaje = "Está a punto de borrar un autor. Se borrarán también las asociaciones para los productos que tienen este autor.\n¿Está seguro?";
			url_destino = "borrar_autor.php?id=" + id;
			break;
		
		case "imagenes":
			mensaje = "Está a punto de borrar una imagen. Se borrarán también sus descripciones.\n¿Está seguro?";
			url_destino = "borrar_imagen.php?id=" + id;
			break;
		
		case "divisas":
			mensaje = "Está a punto de borrar una divisa.\n¿Está seguro?";
			url_destino = "borrar_divisa.php?id=" + id;
			break;
		
		case "gastos_envio":
			mensaje = "Está a punto de borrar un tipo de gasto de envío.\n¿Está seguro?";
			url_destino = "borrar_gasto.php?id=" + id;
			break;
		
		case "localizaciones":
			mensaje = "Está a punto de borrar una localización.\n¿Está seguro?";
			url_destino = "borrar_localizacion.php?id=" + id;
			break;
		
		case "pedidos":
			mensaje = "Está a punto de borrar un pedido. Este borrado es permanente.\n¿Está seguro?";
			url_destino = "borrar_pedido.php?id=" + id;
			break;
		
		case "banners":
			mensaje = "Está a punto de borrar un banner.\n¿Está seguro?";
			url_destino = "borrar_banner.php?id=" + id;
			break;
		
		case "contenidos":
			mensaje = "Está a punto de borrar un contenido. Se borrará también su referencia en el menú.\n¿Está seguro?";
			url_destino = "borrar_contenido.php?id=" + id;
			break;
		
		case "menus":
			mensaje = "Está a punto de borrar una opción del menú. El contenido permanecerá para que pueda vincularlo con otra opción si lo desea.\n¿Está seguro?";
			url_destino = "borrar_menu.php?id=" + id;
			break;
		
		case "idiomas":
			mensaje = "Está a punto de borrar un idioma. Todos los contenidos en ese idioma se perderán. Este borrado es permanente.\n¿Desea continuar?";
			url_destino = "borrar_idioma.php?id=" + id;
			break;
		
		case "formas_envio":
			mensaje = "Está a punto de borrar una forma de envío.\n¿Está seguro?";
			url_destino = "borrar_formas_envio.php?id=" + id;
			break;
		
		case "tarifas":
			mensaje = "Está a punto de borrar una tarifa.\n¿Está seguro?";
			url_destino = "borrar_tarifa.php?id=" + id;
			break;
	}
	
	a = confirm(mensaje)
	if( a )
		window.location.href = url_destino;
}

/***** métodos de asociación *****/
// crear asociación en generos
function crear_asociacion(idproducto, idcat)
{
	var cadena_generos = "";
	var lista_generos = document.getElementById('lista_no_asociados');
	// si selectedIndex = -1 es que no hay ningún elemento seleccionado
	if( lista_generos.selectedIndex != -1 )
	{
		for( var i =0; i <= lista_generos.options.length - 1 ; i++ )
		{
			if( lista_generos.options[i].selected )
				cadena_generos += lista_generos.options[i].value + ".";
		}
		cadena_generos = cadena_generos.substr(0, cadena_generos.length - 1);
		window.location.href = "agregar_asociaciones.php?claves="+cadena_generos+"&idproducto="+idproducto+"&idcat="+idcat;
	}
}

// borrar asociación en generos
function eliminar_asociacion(idproducto, idcat)
{
	var cadena_generos = "";
	var lista_generos = document.getElementById('lista_asociados');
	if( lista_generos.selectedIndex != -1 )
	{
		for( var i = 0; i <= lista_generos.options.length - 1; i++ )
		{
			if( lista_generos.options[i].selected )
				cadena_generos += lista_generos.options[i].value + ".";
		}
		cadena_generos = cadena_generos.substr(0, cadena_generos.length - 1);
		window.location.href = "eliminar_asociaciones.php?claves="+cadena_generos+"&idproducto="+idproducto+"&idcat="+idcat;
	}
}

// crear asociación en autores
function crear_asociacion_autores(idproducto, idcat)
{
	var cadena_generos = "";
	var lista_generos = document.getElementById('lista_no_asociados');
	// si selectedIndex = -1 es que no hay ningún elemento seleccionado
	if( lista_generos.selectedIndex != -1 )
	{
		for( var i =0; i <= lista_generos.options.length - 1 ; i++ )
		{
			if( lista_generos.options[i].selected )
				cadena_generos += lista_generos.options[i].value + ".";
		}
		cadena_generos = cadena_generos.substr(0, cadena_generos.length - 1);
		window.location.href = "agregar_asociaciones.php?claves="+cadena_generos+"&idproducto="+idproducto+"&idcat="+idcat;
	}
}

// borrar asociación en autores
function eliminar_asociacion_autores(idproducto, idcat)
{
	var cadena_generos = "";
	var lista_generos = document.getElementById('lista_asociados');
	if( lista_generos.selectedIndex != -1 )
	{
		for( var i = 0; i <= lista_generos.options.length - 1; i++ )
		{
			if( lista_generos.options[i].selected )
				cadena_generos += lista_generos.options[i].value + ".";
		}
		cadena_generos = cadena_generos.substr(0, cadena_generos.length - 1);
		window.location.href = "eliminar_asociaciones.php?claves="+cadena_generos+"&idproducto="+idproducto+"&idcat="+idcat;
	}
}



/***** funciones de ayuda en la paginacion *****/
function ir_a_pagina(destino, lista)
{
	var numero_pagina = document.getElementById(lista.id).value;
	
	//alert(destino.indexOf('?'));
	if( destino.indexOf('?') != -1 )
		window.location.href = destino + "&inicio=" + numero_pagina;
	else
		window.location.href = destino + "?inicio=" + numero_pagina;
}

/***** confirmación de borrado de un producto en el carrito *****/
function confirmar_borrado_producto(formulario, mensaje)
{
	var confirmar = confirm(mensaje);
	
	if( confirmar )
		//eval("document.forms." + formulario + ".submit();");
		eval("document.getElementById('" + formulario + "').submit();");
}

function vaciar_carrito(mensaje)
{
	var confirmar = confirm(mensaje);
	if( confirmar )
		document.getElementById('fVaciarCarrito').submit();
}

/***** función que lanza el formulario de compra final *****/
// tipo_pago
// 0 -> compra contra reembolso
// 1 -> compra con tarjeta
function lanzar_compra(tipo_pago, mensaje_error)
{
	// por defecto, pondremos la compra contrareembolso
	if( tipo_pago != 1 && tipo_pago != 0 && tipo_pago != 2  )
		tipo_pago = 0;
	
	var localidad = document.getElementById('localidad_entrega').value;
	var direccion = document.getElementById('direccion_entrega').value;
	var localizacion = document.getElementById('id_loc').value;
	var localizacion_hija = document.getElementById('id_loc_hija').value;
	// se incluye también el código postal...
	var codigo_postal = document.getElementById('codigo_postal').value;
	var pais = document.getElementById('pais_entrega').value;
	var ciudad = document.getElementById('ciudad_entrega').value;
	
	localidad = localidad.trim();
	direccion = direccion.trim();
	codigo_postal = codigo_postal.trim();
	pais = pais.trim();
	
	//alert("[" + localidad + "] --- [" + direccion + "]");
	
	if( direccion == '' || localidad == '' || localizacion == 0 ||codigo_postal == '' || pais == '' || ciudad == '' )
		alert(mensaje_error);
	else
	{
		document.getElementById('enviar_pedido').value = 1;
		document.getElementById('tipo_pago').value = tipo_pago;
		document.getElementById('fComprar').submit();
	}
}

function enviar_compra_tarjeta(ruta_base, codigo_idioma)
{
	var caducidad_formateada = document.getElementById('anno_caducidad').value + document.getElementById('mes_caducidad').value;
	document.getElementById('caducidad').value = caducidad_formateada;
	
	if( document.getElementById('PAN').value.trim() != '' )
	{
		ocultar_boton(ruta_base, codigo_idioma);
		document.getElementById('fComprarTarjeta').submit();
	}
	else
		alert("Debe introducir un número de tarjeta válido");
}

// la cosa esa de la ocultación del botón de los cojones
// para que ningún oligofrénico me haga doble clic
function ocultar_boton(ruta_base, codigo_idioma)
{
	var capa = document.getElementById('capa_boton');
	capa.innerHTML = "<img id='boton_comprar' border='0' src='" + ruta_base + "css/" + codigo_idioma + "/btn_esperar.gif' alt='espere...'>";
	document.getElementById('capa_informacion_espere').style.display = 'inline';
}

// función para que el pavo no tenga que escribir su dirección de nuevo.
// al añadir o quitar campos, esta función lo controla todo tanto en la parte pública como en el carrito privado.
function asociar_datos()
{
	var clave = document.getElementById('asociar');
	//alert(clave.checked);
	
	if( clave.checked )
	{
		document.getElementById('localidad_entrega').value = document.getElementById('localidad_oculta').value;
		document.getElementById('direccion_entrega').value = document.getElementById('direccion_oculta').value;
		document.getElementById('pais_entrega').value = document.getElementById('pais_oculto').value;
		document.getElementById('codigo_postal').value = document.getElementById('codigo_postal_oculto').value;
		document.getElementById('ciudad_entrega').value = document.getElementById('ciudad_oculta').value;
	}
	else
	{
		document.getElementById('localidad_entrega').value = '';
		document.getElementById('direccion_entrega').value = '';
		document.getElementById('pais_entrega').value = '';
		document.getElementById('codigo_postal').value = '';
		document.getElementById('ciudad_entrega').value = '';
	}
}

/***** cosas con las fechas *****/
function rellenaAnyos(numero_annos)
{
	cadena = "";

	var fecha		= new Date();
	var anno_actual	= fecha.getYear();

	if( anno_actual < 2000 )
		anno_actual += 1900;

	for( i = 0; i < numero_annos; i++ )
	{
		cadena += "<option value='" + (anno_actual + i) + "'>";
		cadena += (anno_actual + i);
		cadena += "</option>";
	}
	return cadena;
}

/***** cosas con los pedidos *****/
function cambiar_estado_pedido(idpedido)
{
	var nuevo_estado = document.getElementById('nuevo_estado_' + idpedido).value;
	//alert(nuevo_estado.value);
	window.location.href = "cambiar_estado.php?id=" + idpedido + "&codigo=" + nuevo_estado;
}

// confirmar borrado pedido en la zona privada
function confirmar_borrado_pedido(idpedido, mensaje)
{
	var a = confirm(mensaje);
	
	if( a )
		document.getElementById('fBorrarPedido_' + idpedido).submit();
}

// confirmación de deshacer el borrado del pedido
function confirmar_deshacer_borrado(ruta_base, idpedido)
{
	var a = confirm("¿Realmente desea devolver el pedido a su estado inicial?");
	
	if( a )
		window.location.href = ruta_base + "admin/pedidos/deshacer_borrado.php?idpedido=" + idpedido;
}

// confirmación del envío del pedido en el panel de control
function confirmar_envio_pedido(formulario)
{
	var c = confirm("¿Desea cursar este pedido?\n\nEsto hará que el carrito se vacíe y el pedido se guarde para ser procesado.\n\nNOTA: Asegúrese de que todos los datos son correctos.");
	if( c )
		lanzar_compra(0, 'Debe rellenar todos los campos');
		//document.getElementById('formulario').submit();
}

// activar o no los cuadros de datos del editor de menú...
function activar_datos(option_pulsado)
{
	//alert(option_pulsado);
	switch( option_pulsado )
	{
		case 'radio_url':
			// desactiva el campo url
			// desactiva el campo popup (además, este campo contendrá luego su valor por defecto)
			document.getElementById('lista_contenidos').disabled = true;
			document.getElementById('texto_url').disabled = false;
			document.getElementById('id_popup').disabled = true;
			break;
		
		case 'radio_contenido':
			document.getElementById('lista_contenidos').disabled = false;
			document.getElementById('texto_url').disabled = true;
			document.getElementById('id_popup').disabled = false;
			break;
	}
}

// lanzar el contenido en un popup
function popup_contenido(ruta_base, id, ididioma)
{
	var nueva = window.open(ruta_base + "publicos/contenidos/contenido_popup.php?id=" + id + "&ididioma=" + ididioma, "", "width=650, height=350, scrollbars");
	nueva.focus();
}

// cálculo del tamaño del textarea y fijación loreal para el número de caracteres
// el máximo es 200 porque yo lo valgo.
function calcular_longitud(objtxt)
{
	var maximo = 200;
	var contenido = objtxt.value;
	// número de caracteres del textarea
	var longitud = contenido.length;
	// se muestran cuántos caracteres quedan
	document.getElementById('maximo_caracteres').innerHTML = maximo - longitud;
	if( longitud > maximo - 1 )
		objtxt.value = contenido.substring(0, maximo);
}

// vista previa de un producto.
// Sí, lo sé...
function vista_previa(ruta_base)
{
	var nombre = document.getElementById('nombre');
	var entradilla = document.getElementById('entradilla');
	var descripcion = document.getElementById('descripcion');
	var precio = document.getElementById('precio');
	var precio_oferta = document.getElementById('precio_oferta');
	var stock = document.getElementById('stock');
	var referencia = document.getElementById('referencia');
	var iva = document.getElementById('iva');
	var novedad = document.getElementById('novedad');
	var agotado = document.getElementById('agotado');
	var oculto = document.getElementById('oculto');
	
	if( document.getElementById('imagen_producto') )
		var imagen_producto = document.getElementById('imagen_producto');
	
	var salida = "";
	salida += "<head><title>ecomm 0.1-villamusica - Vista previa</title>";
	salida += "<link href='" + ruta_base + "css/pcontrol.css' rel='stylesheet' type='text/css'>";
	salida += "</head>";
	salida += "<body>";
	salida += "<br><br><table class='tabla_datos' align='center' border='0' cellpadding='3' cellspacing='0' width='560'>";
	salida += "<tr class='rotulo_tabla'>";
    salida += "<td colspan='2' align='center'>";
    salida += "<b>" + nombre.value + "</b>";
    salida += "<br> Ref.: " + referencia.value + "</td>";
	salida += "</tr>";
 	salida += "<tr>";
    salida += "<td class='fila_tabla' align='center' valign='top' width='10'>";
    if( document.getElementById('imagen_producto') && imagen_producto.src != null )
    	salida += "<img border='0' src='" + imagen_producto.src.replace("thumb", "grande") + "' width='200'>";
    else
    	salida += "<div style='width: 200px; height: 200px; background-color: #F8F8F8; border: 1px solid black;'>Espacio para la imagen. Disponible solo en la modificación.</div>";
    salida += "</td>";
    salida += "<td class='fila_tabla' align='left' valign='top'>";
    if( entradilla.value != "" )
		salida += "<b>" + entradilla.value + "</b>";
	if( descripcion.value != "" )
		salida += "<br><br>" + descripcion.value + "<br>";
	if( novedad.checked == 1 )
		salida += "<img src='" + ruta_base + "imagenes/portada/icono_novedad.gif' align='middle' border='0' hspace='3' vspace='2'>";
	if( novedad.checked == 1 )
		salida += "<span class='info_icono_producto'> nuevo </span>";
	
    salida += "</td>";
    salida += "</tr>";
	salida += "<tr class='rotulo_tabla'>";
    salida += "<td class='fila_tabla' colspan='2'>";
	salida += "<b> Precios aplicados </b>";
    salida += "</td>";
    salida += "</tr>";
    salida += "<tr>";
    salida += "<td class='fila_tabla' colspan='2'>";
    salida += "<b> Precio: </b>";
    salida += precio.value + "&nbsp;-&nbsp;<img src='" + ruta_base + "imagenes/portada/icono_oferta.gif' align='middle' border='0' hspace='2'>";
    salida += "<b> Precio en oferta: </b>";

    salida += precio_oferta.value + "&nbsp;-&nbsp;";
	salida += "<b> I.V.A. para aplicar: </b>";
	salida += iva.value + "</td>";
	salida += "</tr>";
	salida += "</table>";

	/*
	salida += "Vista previa de valores\n";
	salida += "************************************\n";
	salida += "nombre: " + nombre.value + "\n";
	salida += "entradilla: " + entradilla.value + "\n";
	salida += "descripcion: " + descripcion.value + "\n";
	salida += "precio: " + precio.value + "\n";
	salida += "precio oferta: " + precio.value + "\n";
	salida += "stock: " + stock.value + "\n";
	salida += "referencia: " + referencia.value + "\n";
	salida += "iva: " + iva.value + "\n";
	salida += "novedad: " + novedad.value + "\n";
	salida += "agotado: " + agotado.value + "\n";
	salida += "oculto: " + oculto.value + "\n";
	
	alert(salida);
	*/
	
	var f = "width=600, height=500, scrollbars";
	var nueva = window.open("", "nueva_ventana", f);
	nueva.document.write(salida);
	nueva.document.close();
	nueva.focus();
}

// función para mostrar/ocultar las tarifas
function ver_tarifas(cual)
{
	var fila_tarifas = document.getElementById("capa_tarifas" + cual);
	
	if( fila_tarifas.style.display == 'none' )
		fila_tarifas.style.display = '';
	else
		fila_tarifas.style.display = 'none';
}

function colapsar_todo(cuantos)
{
	for( var i = 1; i <= cuantos; i++ )
		document.getElementById('capa_tarifas' + i).style.display = 'none';
}

function expandir_todo(cuantos)
{
	for( var i = 1; i <= cuantos; i++ )
		document.getElementById('capa_tarifas' + i).style.display = '';
}

// función para marcar/desmarcar los pedidos
function marcar_pedidos(modo)
{
	var total_pedidos = document.getElementById('total_pedidos_listado').value;
	var todos_marcados = document.getElementById('todos_marcados').value;
	switch( modo )
	{
		case 'todos':
			if( todos_marcados == 1 )
			{
				for( var i = 0; i < total_pedidos; i++ )
					document.getElementById('marca_pedido' + i).checked = false;
				
				document.getElementById('todos_marcados').value = 0;
				document.getElementById('marcar_todos').value = "Marcar todos los pedidos";
			}else{
				for( var i = 0; i < total_pedidos; i++ )
					document.getElementById('marca_pedido' + i).checked = true;
				
				document.getElementById('todos_marcados').value = 1;
				document.getElementById('marcar_todos').value = "Desmarcar todos los pedidos";
			}

			break;
		
		case 'alternar':
			for( var i = 0; i < total_pedidos; i++ )
			{
				elemento = document.getElementById('marca_pedido' + i);
				if( elemento.checked )
					elemento.checked = false;
				else
					elemento.checked = true;
			}
			break;
	}
}

// función para desmarcar estados
function desmarcar_estados(fila)
{
	for( var i = 1; i <= 13; i++ )
	{
		if( document.getElementById('estado_' + fila + "_" + i) )
			document.getElementById('estado_' + fila + "_" + i).checked = false;
	}
	return false;
}

// actualización de estados de los pedidos
function actualizar_estados()
{
	var total_pedidos = document.getElementById('total_pedidos_listado').value;
	var cadena_cambios = '';
	for( var i = 1; i <= total_pedidos; i++ )
	{
		for( var j = 1; j <= 13; j++ )
		{
			if( document.getElementById('estado_' + i + "_" + j) && document.getElementById('estado_' + i + "_" + j).checked == true )
			{
				//alert(document.getElementById('estado_' + i + "_" + j).value);
				cadena_cambios += document.getElementById('pedido_' + i).value + "-" + document.getElementById('estado_' + i + "_" + j).value + "::";
			}
		}
	}
	cadena_cambios = cadena_cambios.substr(0, cadena_cambios.length - 2);
	if( cadena_cambios != '' )
	{
		window.location.href = 'cambiar_estado.php?c=' + cadena_cambios;
		/*
		document.getElementById('cadena_cambios').value = cadena_cambios;
		document.getElementById('fCadenaCambios').submit();
		*/
	}
}

function imprimir_etiquetas(ruta_base, metodo)
{
	var total_pedidos = document.getElementById('total_pedidos_listado').value;
	var todos_marcados = document.getElementById('todos_marcados').value;
	var cadena_ids = "";
	
	for( var i = 1; i <= total_pedidos; i++ )
	{
		elemento = document.getElementById('marca_pedido' + (i - 1));
		
		if( elemento.checked == true )
			cadena_ids += document.getElementById('pedido_' + i).value + "::";
	}
	
	cadena_ids = cadena_ids.substr(0, cadena_ids.length - 2);
	//alert(cadena_ids);
	if( cadena_ids != '' )
	{
		switch( metodo )
		{
			case 'imprimir':
				url_final = ruta_base + "publicos/pedidos/imprimir_etiqueta_bloque.php?c=" + cadena_ids;
				break;
			
			case 'descargar':
				url_final = ruta_base + "publicos/pedidos/imprimir_etiqueta_csv.php?c=" + cadena_ids;
				break;
		}
		
		window.open(url_final, "", "");
	}
}

// imprimir los pedidos en bloque
function imprimir_pedido_bloque(ruta_base)
{
	var total_pedidos = document.getElementById('total_pedidos_listado').value;
	var todos_marcados = document.getElementById('todos_marcados').value;
	var cadena_ids = "";
	
	for( var i = 1; i <= total_pedidos; i++ )
	{
		elemento = document.getElementById('marca_pedido' + (i - 1));
		
		if( elemento.checked == true )
			cadena_ids += document.getElementById('pedido_' + i).value + "::";
	}
	
	cadena_ids = cadena_ids.substr(0, cadena_ids.length - 2);
	//alert(cadena_ids);
	if( cadena_ids != '' )
	{
		url_final = ruta_base + "publicos/pedidos/imprimir_pedido_bloque.php?c=" + cadena_ids;
		window.open(url_final, "", "");
	}
}

// imrpimir pedidos en una hojita html monísima
function imprimir_pedidos(ruta_base)
{
	var total_pedidos = document.getElementById('total_pedidos_listado').value;
	var todos_marcados = document.getElementById('todos_marcados').value;
	var cadena_ids = "";
	
	for( var i = 1; i <= total_pedidos; i++ )
	{
		elemento = document.getElementById('marca_pedido' + (i - 1));
		
		if( elemento.checked == true )
			cadena_ids += document.getElementById('pedido_' + i).value + "::";
	}
	
	cadena_ids = cadena_ids.substr(0, cadena_ids.length - 2);
	
	if( cadena_ids != '' )
	{
		url_final = ruta_base + "admin/pedidos/listado_pedidos_imprimir.php?c=" + cadena_ids;
		var f = "width=790, height=500, scrollbars";
		window.open(url_final, "", f);
	}
}

// imrpimir pedidos en una hojita html monísima (segunda parte
function imprimir_facturas(ruta_base)
{
	var total_pedidos = document.getElementById('total_pedidos_listado').value;
	var todos_marcados = document.getElementById('todos_marcados').value;
	var cadena_ids = "";
	
	for( var i = 1; i <= total_pedidos; i++ )
	{
		elemento = document.getElementById('marca_pedido' + (i - 1));
		
		if( elemento.checked == true )
			cadena_ids += document.getElementById('pedido_' + i).value + "::";
	}
	
	cadena_ids = cadena_ids.substr(0, cadena_ids.length - 2);
	
	if( cadena_ids != '' )
	{
		url_final = ruta_base + "admin/pedidos/listado_facturas_imprimir.php?c=" + cadena_ids;
		var f = "width=790, height=500, scrollbars";
		window.open(url_final, "", f);
	}
}

/***** eventos *****/

function comprobar_longitud()
{
	var obj = document.getElementById('entradilla');
	
	calcular_longitud(obj);
	
	obj.onkeyup = function(){
		calcular_longitud(obj);
	}
	obj.onblur = function (){
		calcular_longitud(obj);
	}
	obj.onfocus = function (){
		calcular_longitud(obj);
	}
}

/***** fin eventos *****/


// abrir el popup de tarifas para la modificación
function abrir_tarifas(ruta_base, idtarifa)
{
	var f = "width=900, height=200, scrollbars";
	var nueva = window.open(ruta_base + "admin/gastos_envio/modificar_tarifa.php?id=" + idtarifa, "", f);
	nueva.focus();
}

// comprobación del dni del usuario que compra por teléfono
function comprobar_dni(ruta_base)
{
	var dni = document.getElementById('dni').value;
	if( dni == '' || dni == null || dni == 'undefined' )
		alert('Para comprobar un DNI debe introducirlo primero');
	else{
		window.location.href = ruta_base + "admin/compra/comprobar_dni.php?dni=" + dni;
	}
}

function comprobar_email(ruta_base)
{
	var email = document.getElementById('email').value;
	if( email == '' || email == null || email == 'undefined' )
		alert('Para comprobar un EMAIL debe introducirlo primero');
	else{
		window.location.href = ruta_base + "admin/compra/comprobar_email.php?email=" + email;
	}
}

// preparar lista de localizaciones prohibidas
function preparar_prohibidas()
{
	var cadena_ids = ""
	var lista_ids = document.getElementById('loc_prohibidas');
	for( var i = 0; i < lista_ids.length; i++ ){
		if( lista_ids.options[i].selected ){
			//alert(lista_ids.options[i].value);
			cadena_ids += lista_ids.options[i].value + "::";
		}
	}
	cadena_ids = cadena_ids.substr(0, cadena_ids.length - 2);
	document.getElementById('cadena_ids').value = cadena_ids;
}

// función para abrir el listado de incidencias (y olé)
function abrir_incidencias(ruta_base, idpedido)
{
	var f = "width=650, height=500, scrollbars";
	url_final = ruta_base + "admin/incidencias/listado_incidencias.php?idpedido=" + idpedido;
	var ventana_incidencias = window.open(url_final, "ventana_incidencias", f);
	ventana_incidencias.focus();
}

// funcioncísima para resolver (es un decir) incidencias
function resolver_indicencias(ruta_base, idpedido, modo)
{
	window.location.href = ruta_base + "admin/incidencias/resolver_incidencia.php?idpedido=" + idpedido + "&modo=" + modo;
}

// función para borrar incidencias
function borrar_incidencias(ruta_base, idpedido)
{
	window.location.href = ruta_base + "admin/incidencias/borrar_incidencia.php?idpedido=" + idpedido;
}

function limpiar_busquedas()
{
	document.getElementById('genero').value=-1;
	document.getElementById('idcat').value=-1;
	document.getElementById('nombre_producto').value= "";
	document.getElementById('desc_producto').value="";
// 	document.getElementById('fFamilias').submit();
}