var esTarjeta= false;
var codPais='0';
var titular="";
var numeroTarjeta="";

var windowTitleGlobal;
var titleTextGlobal;
var errorTextGlobal;
var windowRedirectUrl;
var whitespace = " \t\n\r";
var defaultEmptyOK = false;

var cdlvisitor= getCookie("cdlvisitor");
var uNombre=  filterChars(getUNombre());
var uRapida= getURapida();
var uId= getUId();

var dolar=1.57;

function getUNombre() {
	uNombre='';
	if (cdlvisitor!=null) {
		var i1= cdlvisitor.indexOf("-");
		if (i1>0) {
			var resto= cdlvisitor.substring(i1+1);
			var i2= resto.indexOf("-");
			if (i2>0) {
				uNombre= resto.substring(i2+1);
			}
		}
	}
	return uNombre;
}

function getURapida() {
	var uRapida='';
	if (cdlvisitor!=null) {
		var i1= cdlvisitor.indexOf("-");
		if (i1>=0) {
			var resto= cdlvisitor.substring(i1+1);
			var i2= resto.indexOf("-");
			if (i2>=0) {
				uRapida= resto.substring(0,i2);
			} 
		} 
	}
	return uRapida;
}

function getUId() {
	var uId='0';
		if (cdlvisitor!=null) {
		var i1= cdlvisitor.indexOf("-");
		if (i1>=0) {
			uId= cdlvisitor.substring(0,i1);	
		} 
	}
	return uId;
}			

function open_error_window(errorText, titleText, urlRedirect, windowTitle, width, height, left, top)
{
//Use:
//open_error_window(errorText);
//open_error_window(errorText,'title');
//open_error_window(errorText,'title','http://www.casadellibro.com');
//...

var putItThere = null;

var chasm = screen.availWidth;
var mount = screen.availHeight;

if ((urlRedirect== null) || (urlRedirect=='undefined')) {
	windowRedirectUrl='';
} else {
	windowRedirectUrl=urlRedirect;
}

if ((windowTitle == null) || (windowTitle=='undefined')) {
	windowTitleGlobal ='::Casa Del Libro:: - Error';
} else {
	windowTitleGlobal=windowTitle;
}

if ((titleText == null)||(titleText=='undefined')) {
	titleTextGlobal='por favor,<br>compruebe los siguientes campos';
} else {
	titleTextGlobal=titleText;
}

if ((errorText == null)||(errorText=='undefined')) {
	errorText='';
} else {
	errorTextGlobal=errorText;
}

if ((width == null) || (width=='undefined'))
	width ='300';
if ((height == null) || (height=='undefined'))
	height ='300';
if ((left == null) || (left=='undefined'))
	left =((chasm - width - 10) * .5);
if ((top == null) || (top=='undefined'))
	top =((mount - height - 30) * .5);

new_window = open("/cdl/cda/javascript/windowPopUp2.html","displayWindow","width="+width+",height="+height+",left="+ left +",top="+ top);

}

function setCookie(name, value, expires, path, domain, secure) {
	var curCookie = name + "=" + escape(value) + ((expires) ? "; expires=" + expires.toGMTString() : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
	document.cookie = curCookie;
}
		
function getCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	} else
		begin += 2;
	var end = document.cookie.indexOf(";", begin);
	if (end == -1)
		end = dc.length;
	return unescape(dc.substring(begin + prefix.length, end));
}
		
function deleteCookie(name, path, domain) {
	if (getCookie(name)) {
		document.cookie = name + "=" + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}
		
/* Funciones comunes para comprar */
function isDigit (c){
	return ((c >= "0") && (c <= "9"));
}

function isInteger (s){
	var i;
	if (isEmpty(s))
		if (isInteger.arguments.length == 1) return defaultEmptyOK;
		else return (isInteger.arguments[1] == true);

	for (i = 0; i < s.length; i++){
        // Check that current character is number.
		var c = s.charAt(i);
		if (!isDigit(c)) return false;
	}

	// All characters are numbers.
	return true;
}

function esFechaValida() {
	var mesActual= document.myForm.mesActual.value * 1;
	var anoActual= document.myForm.anoActual.value *1;
	var mesTarjeta= document.myForm.mes[document.myForm.mes.selectedIndex].value * 1;
	var anoTarjeta= document.myForm.ano[document.myForm.ano.selectedIndex].value * 1;
	if (anoTarjeta>anoActual) {
		return true;
	} else {
		if (anoTarjeta==anoActual) {
			if (mesTarjeta>=mesActual) {
				return true;
			} else  {
				return false;
			}
		} else {
			return false;
		}
	}
}

function isEmail(StrObj) {
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(StrObj)) {
	return true;
} else {
	return false;
}
}

function isEmpty(s){
	return ((s == null) || (s.length == 0));
}

function isWhitespace (s){
	var i;

	if (isEmpty(s)) return true;
	for (i = 0; i < s.length; i++){
		var c = s.charAt(i);
		if (whitespace.indexOf(c) == -1) return false;
	}

	// All characters are whitespace.
	return true;
}

function boletinFormFactEnvio() {
	var tipo = "";
	if (document.myForm.tipogeneral.checked) {
		tipo = document.myForm.tipogeneral.value + "|";
	}
	if (document.myForm.tiponoticia.checked) {
		tipo = tipo + document.myForm.tiponoticia.value;
	}
	document.myForm.tipoboletin.value = tipo;
	return true;	
}

function borrarDatosFact() {
	document.myForm.fempresa.value="";
	document.myForm.fnombre.value="";
	document.myForm.fapellidos.value="";
	document.myForm.femail.value="";
	document.myForm.fnif.value="";
	document.myForm.fdireccion.value="";
	document.myForm.fpoblacion.value="";
	document.myForm.fprovincia.value="";
	document.myForm.fcp.value="";
	document.myForm.ftelefono.value="";
	document.myForm.fotroTelefono.value="";
}

function borrarDatosEnvio() {
	document.myForm.eempresa.value="";
	document.myForm.enombre.value="";
	document.myForm.eapellidos.value="";
	document.myForm.eemail.value="";
	document.myForm.edireccion.value="";
	document.myForm.epoblacion.value="";
	document.myForm.eprovincia.value="";
	document.myForm.ecp.value="";
	document.myForm.etelefono.value="";
	document.myForm.eotroTelefono.value="";		
}

function borrarDatos() {
	borrarDatosFact();
	if (document.myForm.datosEnvio.checked==true) { 
		borrarDatosEnvio();
	}
	document.myForm.instrucciones.value="";
}


//de formapago
var esTarjeta= false;
var checked= false;
var titular="";
var numeroTarjeta="";

function activaTarjeta() {
	esTarjeta=true;
}

function desactivaTarjeta() {
	esTarjeta=false;
}

function muestraDatos() {
	document.myForm.titular.value=titular;
	document.myForm.numeroTarjeta.value=numeroTarjeta;
}

function ocultaDatos() {
	desactivaTarjeta();
	titular= document.myForm.titular.value;
	numeroTarjeta= document.myForm.numeroTarjeta.value;

	document.myForm.titular.value="";
	document.myForm.numeroTarjeta.value="";
}

function validaTextArea(field,maxlimit){
	if(field.value.length > maxlimit){
		field.blur();
		//open_error_window('El área de texto no puede contener más de '+maxlimit+' caracteres.');
		message='El área de texto no puede contener más de '+maxlimit+' caracteres.';
		field.value=field.value.substring(0,maxlimit-1);
		document.myForm.error_msn.value=message; 
	}
}

function capaFactura(nombreCapa){
	if (document.myForm.factura) {
		if (document.myForm.factura.checked) {
			document.getElementById(nombreCapa).style.visibility="visible";
		} else {
			document.getElementById(nombreCapa).style.visibility="hidden";
		}
	}
}

function esTarjetaValidaOff() {
	var index= document.myForm.tarjeta.selectedIndex;
	//visa
	if (eval('document.myForm.tarjeta[index].value')=="3") {
		return isVisa(document.myForm.numeroTarjeta.value);
	//mastercard
	} else if (eval('document.myForm.tarjeta[index].value')=="2") {
		return isMasterCard(document.myForm.numeroTarjeta.value);
	//americanexpress
	} else if (eval('document.myForm.tarjeta[index].value')=="4") {
		return isAmericanExpress(document.myForm.numeroTarjeta.value);
	//dinnersclub
	} else if (eval('document.myForm.tarjeta[index].value')=="1") {
		return isDinersClub(document.myForm.numeroTarjeta.value);
	//cuenta libreria
	} else if (eval('document.myForm.tarjeta[index].value')=="6") {
		return isCuentaLibreria(document.myForm.numeroTarjeta.value);
	} else return false;
}	
	
function esES() {
	var idioma='';
	var isIE= (window.navigator.appName.indexOf('Explorer')>0);
	if (isIE) idioma= navigator.userLanguage.toLowerCase();
	else idioma= navigator.language;
	if ((idioma!='es') && (idioma!='es-es')) return false;
	else return true;
}

function showTiempo(tMin,tMax,k) {
	var inp;
	for (var i=0; i< document.myForm.numeroMetodos.value;i++) {
		inp=document.getElementById('tiempo'+i);
		if (inp!=null && typeof(inp)!='undefined' && inp.nodeType==1){
			if (k!=i) {
				inp.style.display="none";
			}else{
				inp.style.display="inline";
			}
		}
	}
	pagos(k);
}

function isVisa(cc){
	if (((cc.length == 16) || (cc.length == 13)) && (cc.substring(0,1) == 4))
		return isCreditCard(cc);
	return false;
}

function isMasterCard(cc){
	firstdig = cc.substring(0,1);
	seconddig = cc.substring(1,2);
	if ((cc.length == 16) && (firstdig == 5) && ((seconddig >= 1) && (seconddig <= 5)))
		return isCreditCard(cc);
	return false;
}

function isAmericanExpress(cc){
	firstdig = cc.substring(0,1);
	seconddig = cc.substring(1,2);
	if ((cc.length == 15) && (firstdig == 3) && ((seconddig == 4) || (seconddig == 7)))
		return isCreditCard(cc);
	return false;
}

function isDinersClub(cc){
	firstdig = cc.substring(0,1);
	seconddig = cc.substring(1,2);
	if ((cc.length == 14) && (firstdig == 3) && ((seconddig == 0) || (seconddig == 6) || (seconddig == 8)))
		return isCreditCard(cc);
	return false;
}

function isCuentaLibreria(cc){
	if ((cc.length == 6) || (cc.length == 7))
		return isInteger(cc);
	return false;
}

function isCreditCard(st) {
	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--;
	}
	if ((sum % 10) == 0)
		return (true);
	else
		return (false);
}

function LTrim(str) {
	for (var i=0; str.charAt(i)==" "; i++);
	return str.substring(i,str.length);
}
function RTrim(str) {
	for (var i=str.length-1; str.charAt(i)==" "; i--);
	return str.substring(0,i+1);
}
function Trim(str) {
	return LTrim(RTrim(str));
}	

function validarFormFactEnvio2(){
	var message="<ul>";
	var valida=true;

	if(isWhitespace(document.myForm.solicitud.value)) {
		message=message+"<li>Solicitud";
		valida=false;
	}
	
	if ((isWhitespace(document.myForm.fnombre.value)) || (isWhitespace(document.myForm.fapellidos.value)) || (isWhitespace(document.myForm.femail.value)) ||
		(isWhitespace(document.myForm.fdireccion.value)) || (isWhitespace(document.myForm.fpoblacion.value)) || (isWhitespace(document.myForm.fprovincia.value)) ||
		(isWhitespace(document.myForm.fcp.value)) || (isWhitespace(document.myForm.ftelefono.value))) {

			message=message+"<li>Campos obligatorios (*)";
			valida=false;
	} else {
		if (document.myForm.datosEnvio.checked) {
			if ((isWhitespace(document.myForm.enombre.value)) || (isWhitespace(document.myForm.eapellidos.value)) || (isWhitespace(document.myForm.eemail.value)) ||
				(isWhitespace(document.myForm.edireccion.value)) || (isWhitespace(document.myForm.epoblacion.value)) || (isWhitespace(document.myForm.eprovincia.value)) ||
				(isWhitespace(document.myForm.ecp.value)) || (isWhitespace(document.myForm.etelefono.value))) {
		
				message=message+"<li>Campos obligatorios (*)";
				valida=false;
			}
		}	
	}
	
	if (document.myForm.factura) {
		if (document.myForm.factura.checked) {
			if (isWhitespace(document.myForm.fnif.value)) {
				message=message+"<li>El NIF / CIF es obligatorio";
				valida=false;
			}
		}
	}
	
	// Para comprobar que el código postal se corresponde con el país/provincia 
	
	var fcpSub=(Trim(document.myForm.fcp.value)).substring(0,2)+"";
	
	if(document.myForm.fpais.value=='3'){
		if(!(fcpSub=="07")){
			message=message+"<li>Campos pais y codigo postal no coinciden (*)";
			valida=false;
		}
	}   
		
	if(document.myForm.fpais.value=='4'){ 
		if(!(fcpSub=="35" || fcpSub=="38" || fcpSub=="52" || fcpSub=="51")){
			message=message+"<li>Campos pais y codigo postal no coinciden (*)";
			valida=false;
		}
	}  	
  	  	
  	if ((document.myForm.fpais.value=='3') || (document.myForm.fpais.value=='4')) {
		if (fcpSub.indexOf("52") == 0 || fcpSub.indexOf("51") == 0 || 
			fcpSub.indexOf("35") == 0 || fcpSub.indexOf("38") == 0) {
			// melilla, ceuta, gran canaria, tenerife		
			document.myForm.factura.checked = true;
			document.getElementById("capaAsterisco").style.visibility="visible";
		}
	}	
	
	if ((document.myForm.fpais.value=='2') || (document.myForm.fpais.value=='3') || (document.myForm.fpais.value=='4')) {
		if ( (!isInteger(document.myForm.fcp.value)) || (document.myForm.fcp.value.length!=5)) {
			message=message+"<li>Codigo Postal de facturacion";
			valida=false;
		}
	}
		
	if (document.myForm.datosEnvio.checked) {	
		if ((document.myForm.epais.value=='2') || (document.myForm.epais.value=='3') || (document.myForm.epais.value=='4')) {
			if ( (!isInteger(document.myForm.ecp.value)) || (document.myForm.ecp.value.length!=5)) {
				message=message+"<li>Codigo Postal de envio";
				valida=false;
			}
		}
	}
	
	if ((!isWhitespace(document.myForm.femail.value)) && (!isEmail(document.myForm.femail.value))) {
		message=message+"<li>Email de Facturacion";
		valida=false;
	}
	if ((document.myForm.datosEnvio.checked) && (!isWhitespace(document.myForm.eemail.value)) && (!isEmail(document.myForm.eemail.value))) {
		message=message+"<li>Email de Envio";
		valida=false;
	}
	if (!valida) {
		message="<ul>"+message+"</ul>";
		document.myForm.error_msn.value=message; 
		return false;
	} else return true;
}

/* Función de alerta */
function alertaRoja(c){
	alert(c);
}

function formatFloat (s) {
	var maxFraction= 2;
	var dotSeen= false;
	var k=0;
	var result="";
	var str=new String(s);

	for (var i = 0; (i < str.length) && (k <= maxFraction); i++){   
		var c = str.charAt(i);
		if ((c == '.') || (dotSeen)) {
			dotSeen=true;
			k=k+1;
		}
		result=result+c;
	}
	return result;
}

function onClickTipo(k) {
	for (var i=0; i< document.myForm.numeroChkTipos.value;i++) {
		if (k!=i) {
			eval('document.myForm.tipoPago'+i+'.checked=false'); 
		} else {
			eval('document.myForm.tipoPago'+i+'.checked=true');
		}	
	}
}

function irFactEnvio(lang) {
	if (lang=="es_es") window.location="/compra/facturar";
	else window.location="/compra/facturar?lang="+lang;
}

function operaBolsa(operacion) {
	if (operacion=="continuar") {
		var continua= validarFormBolsa();
		if (continua){
			document.myForm.error_msn.value=null; 
			document.myForm.action="/compra/finalizarCompra2";
			document.myForm.submit();	
		} else {			
			document.myForm.action="/compra/bolsaCompra3";
			document.myForm.submit();		
		}
	} 
}
function operaFactEnvio(operacion,lang) {
	if (operacion=="anterior") {
		if (lang=="es_es") window.location="/compra/facturar";
		else window.location="/compra/facturar?lang="+lang;
	} else if (operacion=="continuar") {
		var continua= validarFormFactEnvio();
		if (continua) {
			boletinFormFactEnvio();
			if (document.myForm.factura) document.myForm.factura.disabled = false;
			document.myForm.error_msn.value=null;
			if (!esES()) {
				escapeFE();
			}
			var myConn = new XHConn(); 
			if (!myConn) alert("XMLHTTP no esta disponible. Inténtalo con un navegador más actual."); 
			var peticion = function (oXML) {
				if (oXML.status!=200){
					document.myForm.ofs.value='';
				}else{
					document.myForm.ofs.value=oXML.responseText;
				}
				document.myForm.action="/compra/bolsaCompra3";
				document.myForm.submit();
			} 
			myConn.connect("/cache/ofertas/ofertas.properties", "POST", "", peticion);
		} else {
			document.myForm.action="/compra/facturar";
			document.myForm.submit();
		}
	}
}

function validarFormBolsa() {
	var exist=0;
	var nan=0;
	var vacio=0;
	var index=0;
	var importePedido= eval(document.myForm.total.value) *1;
	var importeMaxPago=-1;
	var importeMaxTarjeta=-1;
	
	for (var i=0; i< document.myForm.metodoEnvioChk.length;i++) {
		if (document.myForm.metodoEnvioChk[i].checked){
			exist=1;
			break;
		}
	}
	
	if ( document.myForm.numeroLibros.value == "0"){ 
		vacio=1;
	}
	for (var i=0; i< document.myForm.numeroLibros.value;i++) {
		var p= eval('document.myForm.uds'+i+'.value');
		if (isNaN(eval(parseInt(p))) || (eval(parseInt(p)<=0))) nan=1;
	}	
	
	var message="";
	if (vacio==1) message="Bolsa Vacía.";	
	if (nan==1) message=message+"Unidades del pedido.";
	if (exist==0) message=message+"Método de Envío.";
	for (var i=0; i< document.myForm.numeroChkTipos.value;i++) {
		var p= eval('document.myForm.tipoPago'+i+'.checked');
		if (p==true) {
			exist=1; 
			index=i;
		}
	}
	
	if (exist==0) {
		message= message + 'Medio de pago.';
		document.myForm.error_msn.value=message; 
		return false;
	} else {
		importeMaxPago= eval('document.myForm.importeMaxPago'+index+'.value')*1;
	}
	index= document.myForm.tarjeta.selectedIndex;
	importeMaxTarjeta= eval('document.myForm.importeMaxTarjeta'+index+'.value')*1;

	if (esTarjeta) {
		if (document.myForm.titular.value=="") {
			message=message+"<li>Titular.";
		}
		
		if (document.myForm.numeroTarjeta.value=="") {
			message=message+"<li>Numero de Tarjeta.";
		}
		
		if ((document.myForm.titular.value=="")||(document.myForm.numeroTarjeta.value=="")) {
			document.myForm.error_msn.value=message+"</ul>"; 
			return false;
		} else {
			
			var valida= esTarjetaValidaOff();
			var numero= new String(document.myForm.numeroTarjeta.value);
			
			if (!valida) {
				message= message+ 'Numero de Tarjeta.';
				document.myForm.error_msn.value=message;
				return false;
			} else if (!esFechaValida()) {
				message= message+ 'Fecha de Caducidad.';
				document.myForm.error_msn.value=message;
				return false;
			} else if ( ( isVisa(numero) || isMasterCard(numero) || isAmericanExpress(numero)) && (importePedido>importeMaxTarjeta) ) {
				message="Se ha superado el importe maximo de compra. Por favor, póngase en contacto con nosotros llamando al teléfono 902151928 desde España o al +34914811371 desde fuera de España."; 
				document.myForm.error_msn.value=message;
				return false;
			} else if ( isCuentaLibreria(numero) && (importePedido>importeMaxTarjeta) ) {
				message="Se ha superado el importe maximo para la modalidad seleccionada. Por favor, elija otra forma de pago."; 
				document.myForm.error_msn.value=message;
				return false;
			}
		}
		
	} else if (importePedido > importeMaxPago) {
		
		message="Se ha superado el importe maximo para la modalidad seleccionada. Por favor, elija otra forma de pago."; 
		document.myForm.error_msn.value=message;
		return false;
	}	
	
	if ((nan==1) || (exist==0) || (vacio==1)){
		document.myForm.error_msn.value=message; 
		return false;
	}
	else {		
		return true;
	}
}

function recalcular(i,pvp){
	iTotal(i,pvp);
	subtotal();
	total();
}

function iTotal (i,pvp) {
	var uds='document.myForm.uds'+i+'.value';
	var itotal= pvp*eval(uds);
	itotal= formatFloat(itotal);
	itotald= formatFloat(itotal*dolar);
	eval('document.myForm.total'+i+'.value='+itotal);
	eval('document.myForm.totalD'+i+'.value='+itotald);
}

function subtotal() {
	var tot= 0;
	var subt= 0;
	var numeroLibros= document.myForm.numeroLibros.value;
	for (var i=0; i< numeroLibros; i++) {
		subt= (1.0*subt) + (1.0*eval('document.myForm.total'+i+'.value'));
	}
	subt= formatFloat(subt);
	subtD= formatFloat(subt*dolar);
	document.myForm.subtotal.value= subt;
	document.myForm.subtotalD.value= subtD;
}

function total() {
	var subtotal= document.myForm.subtotal.value;
	var costes= document.myForm.costes.value;
	var ofertas= document.myForm.ofertas;
	if (ofertas==null || typeof(ofertas)=='undefined' || ofertas.nodeType!=1) {
	    ofertas=0;
	}else{
	    ofertas=ofertas.value;
	}
	var total= (1.0*subtotal)+(1.0*costes)-(1.0*ofertas);
	var totalD= total * dolar;
	document.myForm.total.value= formatFloat(total);
	document.myForm.totalD.value= formatFloat(totalD);
}

function processClicks() {
	return false;
}

/* Facturacion Envio */
function cambiaIgualFE() {	
	if (document.myForm.datosEnvio.checked==false) { 
		document.myForm.igualfe.value='true'; 
	} else {
		document.myForm.igualfe.value='false'; 
	}
	 
	document.myForm.action="/compra/facturar"; 
	document.myForm.submit();
}
function cambiaPais(){
	if (document.myForm.factura) {
		if (document.myForm.fpais.options[document.myForm.fpais.selectedIndex].value == 4) {
			document.getElementById("capaAsterisco").style.visibility="visible";
			document.myForm.factura.checked = true;
			document.myForm.factura.disabled = true;
		}else{
			document.myForm.factura.disabled = false;
			document.getElementById("capaAsterisco").style.visibility="hidden";
			document.myForm.factura.checked = false;
		}
	}
}
function loginFacturacionEnvio() {
	document.myFormLogin.origen.value="/compra/facturar";
	document.myFormLogin.action="/compra/loginFactEnvioTrans2"; 
	document.myFormLogin.submit();
}  

function validarFormFactEnvio(){
	var message="<ul>";
	var valida=true;
	if ((isWhitespace(document.myForm.fnombre.value)) || (isWhitespace(document.myForm.fapellidos.value)) || (isWhitespace(document.myForm.femail.value)) || (isWhitespace(document.myForm.fdireccion.value)) ||
		(isWhitespace(document.myForm.fpoblacion.value)) || (isWhitespace(document.myForm.fprovincia.value)) ||(isWhitespace(document.myForm.fcp.value)) || (isWhitespace(document.myForm.ftelefono.value))) {

			message=message+"<li>Campos obligatorios (*)";
			valida=false;
	} else {
		if (document.myForm.datosEnvio.checked) {
			if ((isWhitespace(document.myForm.enombre.value)) || (isWhitespace(document.myForm.eapellidos.value)) || (isWhitespace(document.myForm.eemail.value)) ||
				(isWhitespace(document.myForm.edireccion.value)) || (isWhitespace(document.myForm.epoblacion.value)) || (isWhitespace(document.myForm.eprovincia.value)) ||
				(isWhitespace(document.myForm.ecp.value)) || (isWhitespace(document.myForm.etelefono.value))) {
		
				message=message+"<li>Campos obligatorios (*)";
				valida=false;
			}
		}	
	}
	var fcpSub=(Trim(document.myForm.fcp.value)).substring(0,2)+"";
	
	if(document.myForm.fpais.value=='3'){
		if(!(fcpSub=="07")){
			message=message+"<li>Campos pais y codigo postal no coinciden (*)";
			valida=false;
		}
	}   
	if(document.myForm.fpais.value=='4'){ 
		if(!(fcpSub=="35" || fcpSub=="38" || fcpSub=="52" || fcpSub=="51")){
			message=message+"<li>Campos pais y codigo postal no coinciden (*)";
			valida=false;
		}
	}
  	if ((document.myForm.fpais.value=='3') || (document.myForm.fpais.value=='4')) {
	if (fcpSub.indexOf("52") == 0 || fcpSub.indexOf("51") == 0 || 
		fcpSub.indexOf("35") == 0 || fcpSub.indexOf("38") == 0) {
		// melilla, ceuta, gran canaria, tenerife		
		document.myForm.factura.checked = true;
		document.getElementById("capaAsterisco").style.visibility="visible";
	}}
	if (document.myForm.factura) {
		if (document.myForm.factura.checked) {
			if (isWhitespace(document.myForm.fnif.value)) {
				message=message+"<li>El NIF / CIF es obligatorio";
				valida=false;
			}
		}
	}
	if ((document.myForm.fpais.value=='2') || (document.myForm.fpais.value=='3') || (document.myForm.fpais.value=='4')) {
		if ( (!isInteger(document.myForm.fcp.value)) || (document.myForm.fcp.value.length!=5)) {
			message=message+"<li>Codigo Postal de facturacion";
			valida=false;
		}
	}
	
	if (document.myForm.datosEnvio.checked) {	
		if ((document.myForm.epais.value=='2') || (document.myForm.epais.value=='3') || (document.myForm.epais.value=='4')) {
			if ( (!isInteger(document.myForm.ecp.value)) || (document.myForm.ecp.value.length!=5)) {
				message=message+"<li>Codigo Postal de envio";
				valida=false;
			} else {
				var ecpSub=(Trim(document.myForm.ecp.value)).substring(0,2)+"";
				if(document.myForm.epais.value=='3'){
			   		if(!(ecpSub=="07")){
			      			message=message+"<li>Campos pais y codigo postal no coinciden (*)";
				  		valida=false;
			   		}
				}   
				if(document.myForm.epais.value=='4'){ 
			   		if(!(ecpSub=="35" || ecpSub=="38" || ecpSub=="52" || ecpSub=="51")){
			     			message=message+"<li>Campos pais y codigo postal no coinciden (*)";
				 		valida=false;
			    		}
				}
		  		if ((document.myForm.epais.value=='3') || (document.myForm.epais.value=='4')) {
					if (ecpSub.indexOf("52") == 0 || ecpSub.indexOf("51") == 0 || ecpSub.indexOf("35") == 0 || ecpSub.indexOf("38") == 0) {
						// melilla, ceuta, gran canaria, tenerife		
						document.myForm.factura.checked = true;
						document.getElementById("capaAsterisco").style.visibility="visible";
					}
				}	
			}
		}
	}
	if ((!isWhitespace(document.myForm.femail.value)) && (!isEmail(document.myForm.femail.value))) {
		message=message+"<li>Email de Facturacion";
		valida=false;
	}
	if ((document.myForm.datosEnvio.checked) && (!isWhitespace(document.myForm.eemail.value)) && (!isEmail(document.myForm.eemail.value))) {
		message=message+"<li>Email de Envio";
		valida=false;
	}

	if (document.myForm.cambiarPais.value=="true") {
		message=message+"<li>Debera cambiar el pais destino en la primera pantalla del proceso de compra para que sea igual al pais de envio.";
		open_error_window(message,'por favor, compruebe los siguientes campos','/compra/bolsa2');
		return false;
	} 

	if (!valida) {
		message="<ul>"+message+"</ul>";
		document.myForm.error_msn.value=message; 
		return false;
	} else return true;
}

function escapeFE() {
	document.myForm.instrucciones.value=escape(document.myForm.instrucciones.value);

	document.myForm.fempresa.value=escape(document.myForm.fempresa.value);
	document.myForm.fnombre.value=escape(document.myForm.fnombre.value);
	document.myForm.fapellidos.value=escape(document.myForm.fapellidos.value);
	document.myForm.fdireccion.value=escape(document.myForm.fdireccion.value);
	document.myForm.fpoblacion.value=escape(document.myForm.fpoblacion.value);
	document.myForm.fprovincia.value=escape(document.myForm.fprovincia.value);
	if (document.myForm.datosEnvio.checked) {
		document.myForm.eempresa.value=escape(document.myForm.eempresa.value);
		document.myForm.enombre.value=escape(document.myForm.enombre.value);
		document.myForm.eapellidos.value=escape(document.myForm.eapellidos.value);
		document.myForm.edireccion.value=escape(document.myForm.edireccion.value);
		document.myForm.epoblacion.value=escape(document.myForm.epoblacion.value);
		document.myForm.eprovincia.value=escape(document.myForm.eprovincia.value);	
	}	
}


function hayTarjetaSeleccionada() {
	var index= document.myForm.tarjeta.selectedIndex;
	if (eval('document.myForm.nombreTarjeta'+index+'.value')=="") {
		return false;
	} else {
		return true;
	} 
}

function ReplaceChar(String, OldChar, NewChar){
	for(n=0; n< String.length; n++){
		if (String.charAt(n) == OldChar) String = String.substring(0,n) + NewChar + String.substring(n+1,String.length);
	}
	return String;
}

function filterChars(cadena) {
	var str= cadena;
	str=ReplaceChar(str,'Ñ','&Ntilde;');
	str=ReplaceChar(str,'ñ','&ntilde;');
	str=ReplaceChar(str,'Á','&Aacute;');
	str=ReplaceChar(str,'É','&Eacute;');
	str=ReplaceChar(str,'Í','&Iacute;');
	str=ReplaceChar(str,'Ó','&Oacute;');
	str=ReplaceChar(str,'Ú','&Uacute;');
	str=ReplaceChar(str,'á','&aacute;');
	str=ReplaceChar(str,'é','&eacute;');
	str=ReplaceChar(str,'í','&iacute;');
	str=ReplaceChar(str,'ó','&oacute;');
	str=ReplaceChar(str,'ú','&uacute;');	
	str=ReplaceChar(str,'¿','&iquest;');	
	str=ReplaceChar(str,'¡','&iexcl;');	
	str=ReplaceChar(str,'-','&macr;');	
	str=ReplaceChar(str,'Ç','&Ccedil;');	
	str=ReplaceChar(str,'ç','&ccedil;');	
	str=ReplaceChar(str,'Ü','&Uuml;');	
	str=ReplaceChar(str,'ü','&uuml;');	
	str=ReplaceChar(str,'À','&Agrave;');	
	str=ReplaceChar(str,'à','&agrave;');	
	return str;
}

function delLibro(aCodigo) {
	var newCart="";
	if (getCookie("cart")!=null) {
		var cart=getCookie("cart");
		var lineas= cart.split('|');	
		for (var i=0;i < lineas.length;i++) {
			var linea = lineas[i].split('_');
			var codigo=linea[0];
			if (codigo!=aCodigo && newCart!="") newCart=newCart+"|"+lineas[i];
			else if (codigo!=aCodigo && newCart=="") newCart=newCart+lineas[i];
		}
	}		
	setCookie("cart",newCart,"","/","","");
}	

function limpiar() {
	deleteCookie("cart","/","");
	deleteCookie("pack","/","");
}

function changeLibroUnid(aCodigo, unid) {
	var newCart="";
	if (getCookie("cart")!=null) {
		var cart=getCookie("cart");
		var lineas= cart.split('|');	
		for (var i=0;i < lineas.length;i++) {
			var linea = lineas[i].split('_');
			var codigo=linea[0];
			var titulo=linea[1];
			var precio=linea[2];
			var aut=linea[3];
			var img=linea[4];
			var cantidad=linea[5];
                        var origen=linea[6];
			if (codigo==aCodigo){ 
				cantidad = unid;
				if (isNaN(cantidad)) cantidad=1;
				if (newCart!=""){
					newCart=newCart+"|"+codigo+"_"+titulo+"_"+precio+"_"+aut+"_"+img+"_"+cantidad+"_"+origen;
				}else {
					newCart=newCart+codigo+"_"+titulo+"_"+precio+"_"+aut+"_"+img+"_"+cantidad+"_"+origen;
				}
			}else {
				if (newCart!=""){
					newCart=newCart+"|"+lineas[i];
				}else {
					newCart=newCart+lineas[i];
				}
			}
		}
	}		
	setCookie("cart",newCart,"","/","","");
}	

function XHConn(){
	var xmlhttp, bComplete = false;
	try {
		xmlhttp = new XMLHttpRequest();
	}catch (e){
		var XMLHTTP_IDS = new Array('MSXML2.XMLHTTP.5.0','MSXML2.XMLHTTP.4.0','MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP','Microsoft.XMLHTTP' );
		var success = false;
		for (var i=0;i < XMLHTTP_IDS.length && !success; i++) {
			try {
				xmlhttp = new ActiveXObject(XMLHTTP_IDS[i]);
				success = true;
			} catch (e) {}
		}
		if (!success) xmlhttp = false;
	}

	if (!xmlhttp) return null;
	this.connect = function(sURL, sMethod, sVars, fnDone){
		if (!xmlhttp) return false;
		bComplete = false;
		sMethod = sMethod.toUpperCase();

		try {
			if (sMethod == "GET"){
				xmlhttp.open(sMethod, sURL+"?"+sVars, true);
				sVars = "";
			}else{
				xmlhttp.open(sMethod, sURL, true);
				xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
				xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			}
			xmlhttp.onreadystatechange = function(){
				if (xmlhttp.readyState == 4 && !bComplete){
					bComplete = true;
					fnDone(xmlhttp);
				}
			};
			xmlhttp.send(sVars);
		}catch(z) { return false; }
		return true;
	};
	return this;
}
function envioChk(campo){
	var met;
	if (campo.length == undefined){
		met=campo.value;
	}else{
		for (var l=0;l<campo.length;l++){
			if (campo[l].checked){
			met=campo[l].value;
			break;
			}
		}
	}
	return met;
}
function cargarOfertas(cOferta,pais){
        var rText;
	var cuerpo = document.getElementsByTagName("body").item(0);
	var reali=document.getElementById("finCompra");
	var aplicar = document.getElementById("aplicarOferta");
	var proces=document.createElement("span");
	var textopro=document.createTextNode("COMPROBANDO OFERTA. Espere, por favor.");
	proces.appendChild(textopro);
	if (aplicar!=null && typeof(aplicar)!='undefined' && aplicar.nodeType==1){
		aplicar.style.visibility="hidden";
	}
	if (reali!=null && typeof(reali)!='undefined' && reali.nodeType==1){
		reali.style.visibility="hidden";
	}
    	var myConn = new XHConn(); 
	if (!myConn) alert("XMLHTTP no esta disponible. Inténtalo con un navegador más actual.");
	var peticion = function (oXML) {
                var padreList=document.getElementById("resumCoste");
                var tabLista = getFirstChild(padreList);
                var hayofer=document.getElementsByName("hayOferta")[0];
                try{
                        rText=oXML.responseText;
                        if (rText.indexOf("{")<0){
                                var inputOf=document.getElementById("ofertas");
                                hayofer.value="false";
                                var regaloId=document.getElementById("pregalo");
                                var inerror=document.getElementsByName("error_msn")[0];
                                if (inputOf!=null && typeof(inputOf)!='undefined'){
                                        var tbodyTab = getFirstChild(tabLista);
                                        if (tbodyTab.nodeName!='TBODY'){
                                                tbodyTab = getNextSibling(tbodyTab);
                                        }
                                        tbodyTab.removeChild((inputOf.parentNode).parentNode);
                                }
                                if (regaloId!=null && typeof(regaloId)!='undefined'){
                                        padreList.removeChild(regaloId);
                                }
                                if (inerror!=null && typeof(inerror)!='undefined' && inerror.nodeType==1){
                                        inerror.value="Oferta no existe.";
                                }
                                document.myForm.action="/compra/bolsaCompra3";
                                document.myForm.submit();
                        }else{
                                var respuesta=eval('('+rText+')');
                                if (respuesta){
                                        var total=document.getElementById("total");
                                        var totalD=document.getElementById("totalD");
                                        var inputOf=document.getElementById("ofertas");
                                        var inputOfD=document.getElementById("ofertasD");
                                        var inputGas=document.getElementById("costes");
                                        var inputGasD=document.getElementById("costesD");
                                        var inputDescG=document.myForm.desgast;
                                        var ofertas=respuesta.ofertas;
                                        var totalConOf=respuesta.total;
                                        var gastos=respuesta.gastos;
                                        var regalo=respuesta.regalo;
                                        var errorres=respuesta.error;
                                        var inMedios=respuesta.input;
                                        var descGast=respuesta.descgastos;
                                        if (ofertas!=null && typeof(ofertas)!='undefined' && ofertas!="" && ofertas!="null" && ofertas>0){
                                                hayofer.value="true";
                                                if (inputOfD==null || typeof(inputOfD)=='undefined'){
                                                        if (inputOf!=null && typeof(inputOf)=='undefined' && inputOf.nodeType==1) inputOf.parentNode.removeChild(inputOf);
                                                        var tbodyTab = getFirstChild(tabLista);
                                                        if (tbodyTab.nodeName!='TBODY'){
                                                                tbodyTab = getNextSibling(tbodyTab);
                                                        }
                                                        var filanueva = document.createElement("tr");
                                                        filanueva.className="descuento";
                                                        var moneda = document.createElement("span");
                                                        moneda.innerHTML="&nbsp;&euro;";
                                                        var celda1 = document.createElement("th");
                                                        celda1.setAttribute("scope","row");
                                                        var label = document.createTextNode("DESCUENTO");
                                                        celda1.appendChild(label);
                                                        filanueva.appendChild(celda1);
                                                        var celda2 = document.createElement("td");
                                                        celda2.className="columPrecio";
                                                        var input2 = document.createElement("input");
                                                        input2.type="text";
                                                        input2.name="ofertas";
                                                        input2.id="ofertas";
                                                        input2.value=ofertas;
                                                        input2.readOnly=true;
                                                        var moneda2 = document.createTextNode(" $");
                                                        celda2.appendChild(input2);
                                                        celda2.appendChild(moneda);
                                                        filanueva.appendChild(celda2);
                                                        var celda3 = document.createElement("td");
                                                        celda3.className="columPrecio";
                                                        var input3 = document.createElement("input");
                                                        input3.type="text";
                                                        input3.name="ofertasD";
                                                        input3.id="ofertasD";
                                                        input3.value=formatFloat(ofertas*dolar);
                                                        input3.readOnly=true;
                                                        celda3.appendChild(input3);
                                                        celda3.appendChild(moneda2);
                                                        filanueva.appendChild(celda3);
                                                        tbodyTab.insertBefore(filanueva,total.parentNode.parentNode);
                                                }else{
                                                        inputOf.value=ofertas;
                                                        inputOfD.value=formatFloat(ofertas*dolar);
                                                }
                                        }else{
                                                hayofer.value="false";
                                                if (inputOfD!=null && typeof(inputOfD)!='undefined'){
                                                        var tbodyTab = getFirstChild(tabLista);
                                                        if (tbodyTab.nodeName!='TBODY'){
                                                                tbodyTab = getNextSibling(tbodyTab);
                                                        }
                                                        tbodyTab.removeChild((inputOfD.parentNode).parentNode);
                                                }else{
                                                        if (inputOf!=null && typeof(inputOf)!='undefined') inputOf.value="0";
                                                }
                                        }
					if (descGast!=null && typeof(descGast)!='undefined' && descGast!="" && descGast!="null"){
						inputDescG.value=descGast;
					}else inputDescG.value=0;
                                        total.value=totalConOf;
                                        totalD.value=formatFloat(totalConOf*dolar);
                                        inputGas.value=gastos;
                                        inputGasD.value=formatFloat(gastos*dolar);
                                        if (regalo!=null && typeof(regalo)!='undefined' && regalo!="" && regalo!="null"){
                                                hayofer.value="true";
                                                var regaloId=document.getElementById("pregalo");
                                                if (regaloId!=null && typeof(regaloId)!='undefined' && regaloId.nodeType==1){
                                                        getFirstChild(regaloId).nodeValue="Regalo: "+regalo;
                                                }else{
                                                        var pieTabla = document.getElementById("resumCoste");
                                                        var myNewRegalo = document.createElement("p");
                                                        myNewRegalo.id="pregalo";
                                                        var myTexto = document.createTextNode("Regalo: "+regalo);
                                                        myNewRegalo.appendChild(myTexto);
                                                        padreList.insertBefore(myNewRegalo,pieTabla);
                                                }
                                        }else{
                                                var regaloId=document.getElementById("pregalo");
                                                if (regaloId!=null && typeof(regaloId)!='undefined'){
                                                        padreList.removeChild(regaloId);
                                                }
                                        }
                                        if (errorres!=null && typeof(errorres)!='undefined' && errorres!="" && errorres!="null"){
                                                var inerror=document.getElementsByName("error_msn")[0];
                                                if (inerror!=null && typeof(inerror)!='undefined' && inerror.nodeType==1){
                                                        inerror.value=errorres;
                                                }
                                                document.myForm.action="/compra/bolsaCompra3";
                                                document.myForm.submit();
                                        }else{
                                                var diverror=document.getElementById("mensajeError");
                                                if (diverror!=null && typeof(diverror)!='undefined' && diverror.nodeType==1){
                                                        var contenedor=document.getElementById("contenedorBolsa");
                                                        diverror.parentNode.removeChild(diverror);
                                                        if (contenedor!=null && typeof(contenedor)!='undefined' && contenedor.nodeType==1){
                                                                contenedor.id="contenedorBolsa2";
                                                        }
                                                }
                                                if (inMedios!=null && inMedios.length>0){
                                                        cambiarenvios(inMedios,"rapida");
                                                }
                                                if (aplicar!=null && typeof(aplicar)!='undefined' && aplicar.nodeType==1){
                                                        aplicar.style.visibility="visible";
                                                }
                                                if (reali!=null && typeof(reali)!='undefined' && reali.nodeType==1){
                                                        reali.style.visibility="visible";
                                                }
                                        }
                                }else{
                                        var inerror=document.getElementsByName("error_msn")[0];
                                        if (inerror!=null && typeof(inerror)!='undefined' && inerror.nodeType==1){
                                                inerror.value="Oferta no existe.";
                                        }
                                        document.myForm.action="/compra/bolsaCompra3";
                                        document.myForm.submit();
                                }
                        }
                }catch(ex){
                document.myForm.action="/compra/bolsaCompra3";
                document.myForm.submit();
                }
	}
        var metodo=envioChk(document.myForm.metodoEnvioChk);
        if (cOferta=="auto"){
                myConn.connect("/compra/evaluacionoferta", "POST", "codigoOferta=auto&ofs="+document.myForm.ofs.value+"&codigoPais="+pais+"&pesoBolsa="+document.myForm.pesoBolsa.value+"&metodoEnvioChk="+metodo+"&lang="+document.myForm.lang.value, peticion);
        }else{
                myConn.connect("/compra/evaluacionoferta", "POST", cOferta.name+"="+cOferta.value+"&ofs="+document.myForm.ofs.value+"&codigoPais="+pais+"&pesoBolsa="+document.myForm.pesoBolsa.value+"&metodoEnvioChk="+metodo+"&lang="+document.myForm.lang.value, peticion);
        }
}
function borrar2(cLibro,op,pos) { 
	var uds=eval('document.myForm2.uds'+pos+'.value');
	if (!isInteger(uds)) uds=1;
	var myConn = new XHConn(); 
	if (!myConn) alert("XMLHTTP no esta disponible. Inténtalo con un navegador más actual."); 
	var peticion = function (oXML) { 
		try{
			var rText=oXML.responseText;
			if (rText.indexOf("{")<0){
				document.myForm.action="/compra/facturar";
				document.myForm.submit();
			}else{
				var respuesta=eval('('+rText+')');
				if (respuesta){
					var libros=respuesta.libros;
					if (libros!=null && typeof(libros)!='undefined' && libros!="" && libros!="null"){
						var listaLib=document.getElementById("tabBolsa");
						if (listaLib!=null && typeof(listaLib)!='undefined' && listaLib.nodeType==1){
							listaLib.innerHTML='';
							listaLib.innerHTML=libros;
						}
					}
				}else{
					document.myForm.action="/compra/facturar";
					document.myForm.submit();
				}
			}
		}catch(ex){
		document.myForm.action="/compra/facturar";
		document.myForm.submit();
		}
	};
	if (op==1 || (op==0 && uds==0)){
		delLibro(cLibro);
                delPack(cLibro);
		myConn.connect("/compra/modificarCarrito2", "POST", "op=del&codLibro="+cLibro+"&lang="+document.myForm.lang.value, peticion);
	}else
		if (op==0 && uds!=0){
			changePackUnid(cLibro,uds);
			changeLibroUnid(cLibro, uds);
			myConn.connect("/compra/modificarCarrito2", "POST", "op=mod&uds="+uds+"&codLibro="+cLibro+"&lang="+document.myForm.lang.value, peticion);
		}
} 
function borrarAut(cLibro,op,pos) { 
	var uds=eval('document.myForm.uds'+pos+'.value');
	if (!isInteger(uds)) uds=1;
	var cuerpo = document.getElementsByTagName("body").item(0);
	var reali=document.getElementById("finCompra");
	var aplicar = document.getElementById("aplicarOferta");
	var proces=document.createElement("span");
	var textopro=document.createTextNode("MODIFICANDO BOLSA. Espere, por favor.");
	proces.appendChild(textopro);
	if (aplicar!=null && typeof(aplicar)!='undefined' && aplicar.nodeType==1){
		aplicar.style.visibility="hidden";
	}
	if (reali!=null && typeof(reali)!='undefined' && reali.nodeType==1){
		reali.style.visibility="hidden";
	}
	var myConn = new XHConn(); 
	if (!myConn) alert("XMLHTTP no esta disponible. Inténtalo con un navegador más actual."); 
	var peticion = function (oXML) { 
                var padreList=document.getElementById("resumCoste");
                var tabLista = getFirstChild(padreList);
		var hayofer=document.getElementsByName("hayOferta")[0];
		try{
			var rText=oXML.responseText;
			if (rText.indexOf("{")<0){
				var inputOf=document.getElementById("ofertas");
				hayofer.value="false";
				var regaloId=document.getElementById("pregalo");
				var inerror=document.getElementsByName("error_msn")[0];
				if (inputOf!=null && typeof(inputOf)!='undefined'){
					var tbodyTab = getFirstChild(tabLista);
					tbodyTab.removeChild((inputOf.parentNode).parentNode);
				}
				if (regaloId!=null && typeof(regaloId)!='undefined'){
					padreList.removeChild(regaloId);
				}
				if (inerror!=null && typeof(inerror)!='undefined' && inerror.nodeType==1){
					inerror.value="Oferta no existe.";
				}
				document.myForm.action="/compra/bolsaCompra3";
				document.myForm.submit();
			}else{
				var respuesta=eval('('+rText+')');
				if (respuesta){
					var subtotal=document.myForm.subtotal;
					var subtotalD=document.myForm.subtotalD;
					var total=document.getElementById("total");
					var totalD=document.getElementById("totalD");
					var inputOf=document.getElementById("ofertas");
					var inputOfD=document.getElementById("ofertasD");
					var inputGas=document.getElementById("costes");
					var inputGasD=document.getElementById("costesD");
					var inputDescG=document.myForm.desgast;
					var subtotRes=respuesta.subtotal;
					var ofertas=respuesta.ofertas;
					var totalConOf=respuesta.total;
					var gastos=respuesta.gastos;
					var regalo=respuesta.regalo;
					var errorres=respuesta.error;
					var inMedios=respuesta.input;
					var libros=respuesta.libros;
					var descGast=respuesta.descgastos;
					document.myForm.numeroLibros.value=respuesta.lineas;
					if (libros!=null && typeof(libros)!='undefined' && libros!="" && libros!="null"){
						var listaLib=document.getElementById("tabBolsa");
						if (listaLib!=null && typeof(listaLib)!='undefined' && listaLib.nodeType==1){
							listaLib.innerHTML='';
							listaLib.innerHTML=libros;
						}
					}
					if (ofertas!=null && typeof(ofertas)!='undefined' && ofertas!="" && ofertas!="null" && ofertas>0){
						hayofer.value="true";
						if (inputOfD==null || typeof(inputOfD)=='undefined'){
							if (inputOf!=null && typeof(inputOf)=='undefined' && inputOf.nodeType==1) inputOf.parentNode.removeChild(inputOf);
							var tbodyTab = getFirstChild(tabLista);
							if (tbodyTab.nodeName!='TBODY'){
								tbodyTab = getNextSibling(tbodyTab);
							}
							var filanueva = document.createElement("tr");
							filanueva.className="descuento";
							var moneda = document.createElement("span");
							moneda.innerHTML="&nbsp;&euro;";
							var celda1 = document.createElement("th");
							celda1.setAttribute("scope","row");
							var label = document.createTextNode("DESCUENTO");
							celda1.appendChild(label);
							filanueva.appendChild(celda1);
							var celda2 = document.createElement("td");
							celda2.className="columPrecio";
							var input2 = document.createElement("input");
							input2.type="text";
							input2.name="ofertas";
							input2.id="ofertas";
							input2.value=ofertas;
							input2.readOnly=true;
							var moneda2 = document.createTextNode("$");
							celda2.appendChild(input2);
							celda2.appendChild(moneda);
							filanueva.appendChild(celda2);
							var celda3 = document.createElement("td");
							celda3.className="columPrecio";
							var input3 = document.createElement("input");
							input3.type="text";
							input3.name="ofertasD";
							input3.id="ofertasD";
							input3.value=formatFloat(ofertas*dolar);
							input3.readOnly=true;
							celda3.appendChild(input3);
							celda3.appendChild(moneda2);
							filanueva.appendChild(celda3);
							tbodyTab.insertBefore(filanueva,total.parentNode.parentNode);
						}else{
							inputOf.value=ofertas;
							inputOfD.value=formatFloat(ofertas*dolar);
						}
					}else{
						hayofer.value="false";
						if (inputOfD!=null && typeof(inputOfD)!='undefined'){
							var tbodyTab = getFirstChild(tabLista);
							if (tbodyTab.nodeName!='TBODY'){
								tbodyTab = getNextSibling(tbodyTab);
							}
							tbodyTab.removeChild((inputOfD.parentNode).parentNode);
						}else{
							if (inputOf!=null && typeof(inputOf)!='undefined') inputOf.value="0";
						}
					}
					if (descGast!=null && typeof(descGast)!='undefined' && descGast!="" && descGast!="null"){
						inputDescG.value=descGast;
					}else inputDescG.value=0;
					subtotal.value=subtotRes;
					subtotalD.value=formatFloat(subtotRes*dolar);
					total.value=totalConOf;
					totalD.value=formatFloat(totalConOf*dolar);
					inputGas.value=gastos;
					inputGasD.value=formatFloat(gastos*dolar);
					if (regalo!=null && typeof(regalo)!='undefined' && regalo!="" && regalo!="null"){
						hayofer.value="true";
						var regaloId=document.getElementById("pregalo");
						if (regaloId!=null && typeof(regaloId)!='undefined' && regaloId.nodeType==1){
							getFirstChild(regaloId).nodeValue="Regalo: "+regalo;
						}else{
							var pieTabla = document.getElementById("resumCoste");
							var myNewRegalo = document.createElement("p");
							myNewRegalo.id="pregalo";
							var myTexto = document.createTextNode("Regalo: "+regalo);
							myNewRegalo.appendChild(myTexto);
							padreList.insertBefore(myNewRegalo,pieTabla);
						}
					}else{
						var regaloId=document.getElementById("pregalo");
						if (regaloId!=null && typeof(regaloId)!='undefined' && regaloId.nodeType==1){
							padreList.removeChild(regaloId);
						}
					}
					if (errorres!=null && typeof(errorres)!='undefined' && errorres!="" && errorres!="null"){
						var inerror=document.getElementsByName("error_msn")[0];
						if (inerror!=null && typeof(inerror)!='undefined' && inerror.nodeType==1){
							inerror.value=errorres;
						}
						document.myForm.action="/compra/bolsaCompra3";
						document.myForm.submit();
					}else{
						var diverror=document.getElementById("mensajeError");
						if (diverror!=null && typeof(diverror)!='undefined' && diverror.nodeType==1){
							var contenedor=document.getElementById("contenedorBolsa");
							if (contenedor!=null && typeof(contenedor)!='undefined' && contenedor.nodeType==1){
								contenedor.id="contenedorBolsa2";
							}
							diverror.parentNode.removeChild(diverror);
						}
						if (inMedios!=null && inMedios!='undefined' && inMedios.length>0){
							cambiarenvios(inMedios,"rapida");
						}
						//proces.parentNode.removeChild(proces);
						if (total.value>0){
							if (aplicar!=null && typeof(aplicar)!='undefined' && aplicar.nodeType==1){
								aplicar.style.visibility="visible";
							}
							if (reali!=null && typeof(reali)!='undefined' && reali.nodeType==1){
								reali.style.visibility="visible";
							}
						}
					}
				}else{
					var inerror=document.getElementsByName("error_msn")[0];
					if (inerror!=null && typeof(inerror)!='undefined' && inerror.nodeType==1){
						inerror.value="Oferta no existe.";
					}
					document.myForm.action="/compra/bolsaCompra3";
					document.myForm.submit();
				}
			}
		}catch(ex){
		document.myForm.action="/compra/bolsaCompra3";
		document.myForm.submit();
		}
	};
	var metodo=envioChk(document.myForm.metodoEnvioChk);
	if (op==1 || (op==0 && uds==0)){
		delLibro(cLibro);
                delPack(cLibro);
		myConn.connect("/compra/borrarLibro2", "POST", "op=del&codLibro="+cLibro+"&metodoEnvioChk="+metodo+"&ofs="+document.myForm.ofs.value+"&lang="+document.myForm.lang.value, peticion);
	}else
		if (op==0 && uds!=0){
			changePackUnid(cLibro,uds);
			changeLibroUnid(cLibro, uds);
			myConn.connect("/compra/borrarLibro2", "POST", "op=mod&uds="+uds+"&codLibro="+cLibro+"&metodoEnvioChk="+metodo+"&ofs="+document.myForm.ofs.value+"&lang="+document.myForm.lang.value, peticion);
		}
} 
function getNextSibling(startBrother){
	endBrother=startBrother.nextSibling;
	while(endBrother!=null && endBrother.nodeType!=1){
		endBrother = endBrother.nextSibling;
	}
	return endBrother;
}
function getFirstChild(startNode){
	var m=0;
	var hijo;
	if (startNode.hasChildNodes()){
		hijo=startNode.childNodes[0];
		while(m<(startNode.childNodes.length-1) && startNode.childNodes[m].nodeType!=1){
			m++;
			hijo=startNode.childNodes[m];
		}
	}
	return hijo;
}
function metodoEnvioG(importe,ofer,ofeG) {
	var subtotal= document.myForm.subtotal.value;
	var ofertas= document.myForm.ofertas;
	var ofertasG=document.myForm.desgast;
	var ofertaVal=0;
	var hayOferta= eval(document.myForm.hayOferta.value);	
	document.myForm.costes.value= importe;
	document.myForm.costesD.value= formatFloat(importe*dolar);
	if (ofer>0 || ofeG>0) {
		if (ofeG>0){
			ofertasG.value=formatFloat(ofeG);
		}
		if (ofertas==null || typeof(ofertas)=='undefined' || ofertas.nodeType!=1) {
			ofertaVal=0;
		}else{
			ofertas.value=ofer;
			document.myForm.ofertasD.value=formatFloat(ofer*dolar);
			ofertaVal=ofertas.value;
		}
	} else {
		ofertaVal=0;
		if (ofertas!=null && typeof(ofertas)!='undefined' && ofertas.nodeType==1) {
			ofertas.value=0;
			document.myForm.ofertasD.value=0;
		}
	}
	var total= (1.0*importe)+(1.0*subtotal)-(1.0*ofertaVal);
	total= formatFloat(total);
	document.myForm.total.value= total;
	document.myForm.totalD.value= formatFloat(total*dolar);
}
function cambiarenvios(inpMedios,tipo) { 
	if (tipo=='rapida'){
		var forma=document.getElementById("fSetEnvio");
		inputs="";
		for (k=0;k<inpMedios.length;k++)
			inputs=inputs+inpMedios[k];
		forma.innerHTML=inputs;
	}
} 
function ocultar(obj){
if (obj!=null && typeof(obj)!='undefined' && obj.nodeType==1)
	obj.style.visibility="hidden";
}
function LeeRecorte (objeto,borde){
    var vectorRecorte = objeto.clip.split("rect(")[1].split(")")[0].replace(/,/g, "").split("px");
    if (borde=="superior")
        return Number(vectorRecorte[0])
    if (borde=="derecho") 
        return Number(vectorRecorte[1])
    if (borde=="inferior") 
        return Number(vectorRecorte[2])
    if (borde=="izquierdo") 
        return Number(vectorRecorte[3])
}
var accion;
var limite;
var imagen1;
function RecorteRelativo (objeto,superior,derecho,inferior,izquierdo) {    
	objeto.clip = "rect("+(this.LeeRecorte(objeto,'superior')+superior)+"px "+(this.LeeRecorte(objeto,'derecho')+derecho)+"px "+Number(this.LeeRecorte(objeto,'inferior')+inferior)+"px "+Number(this.LeeRecorte(objeto,'izquierdo')+izquierdo)+"px)"
}

function RestaurarImagen(limite,derecho,izquierda,velocidad){
	if (LeeRecorte(imagen1,'derecho') < limite){
		RecorteRelativo (imagen1,0,derecho,izquierda,0);
		if(accion) clearTimeout(accion);
		accion = setTimeout ("RestaurarImagen("+limite+","+derecho+","+izquierda+","+velocidad+")",velocidad)
	}
}
function cargarTematicas(langParam){
	var capaTematicas=document.getElementById("capaTematicas");
        imagen1 =capaTematicas.style;
        capaTematicas.style.clip="rect(0px 0px 0px 0px)";
	var myConn = new XHConn(); 
	if (!myConn) alert("XMLHTTP no esta disponible. Inténtalo con un navegador más actual."); 
	var peticion = function (oXML) {
		capaTematicas.style.visibility="visible";
                RestaurarImagen(1010,27,7,35);
		capaTematicas.innerHTML=oXML.responseText;
                var orden=document.getElementById("orden");
                if (orden){
                orden.style.visibility="hidden";
                }
        	var filtro=document.getElementById("filtro");
                if (filtro){
                filtro.style.visibility="hidden";
        	}
        	var fidioma=document.getElementById("fidioma");
                if (fidioma){
                fidioma.style.visibility="hidden";
                }
	};
	myConn.connect("/modules/cargarTematicas", "POST", langParam,peticion); 
}
function ocultarTematicas(){
	var capa=document.getElementById("capaTematicas");
	capa.style.visibility="hidden";
        var orden=document.getElementById("orden");
        if (orden){
        orden.style.visibility="visible";
        }
}
function verTematicas(){
	var capa=document.getElementById("capaTematicas");
	capa.style.visibility="visible";
        var orden=document.getElementById("orden");
        if (orden){
        orden.style.visibility="hidden";
        }
}

function delPack(aCodigo) {
	var newPack="";
	if (getCookie("pack")!=null) {
		var pack=getCookie("pack");
		var lineas= pack.split('#');	
		for (var i=0;i < lineas.length;i++) {
			var linea = lineas[i].split('-');
			var cod1=linea[0];
                        var cod2=linea[1];
                        if (aCodigo!=cod1 && aCodigo!=cod2 && newPack!=""){
                            newPack=newPack+"#"+lineas[i];
                        }else if(aCodigo!=cod1 && aCodigo!=cod2 && newPack==""){
                            newPack=newPack+lineas[i];
                        }
		}
            setCookie("pack",newPack,"","/","","");
	}	
}


function changePackUnid(aCodigo, unid) {
	var newPack="";
	var lineasPack;
	var copiarPack=false;
	var iniPack=getCookie("pack");
	if (iniPack==null) iniPack="";
	if (iniPack!=''){
	if (getCookie("cart")!=null) {
		var cart=getCookie("cart");
		var lineas= cart.split('|');	
		for (var i=0;i < lineas.length;i++) {
			var linea = lineas[i].split('_');
			var codigo=linea[0];
			var titulo=linea[1];
			var precio=linea[2];
			var aut=linea[3];
			var img=linea[4];
			var cantidad=linea[5];
			if (codigo==aCodigo && cantidad > unid){//Solo tenemos que modificar la cookie de pack si restamos unidades
				var pack=getCookie("pack");
				lineasPack = pack.split('#');
				var contUnidPack=0;
				var contPack=0;
				var lineasConCodigo='';
				copiarPack=false;
				for(var j=0;j<lineasPack.length;j++){
					if(lineasPack[j].indexOf(aCodigo)>-1){
						var lineaPack=lineasPack[j].split('-');
						contUnidPack=contUnidPack+lineaPack[2];
						contPack++;
						if(lineasConCodigo=='') lineasConCodigo=''+j;
						else lineasConCodigo=lineasConCodigo+'-'+j;
					}else{
						if(newPack==''){
							newPack=lineasPack[j];
						}else {
							newPack=newPack+'#'+lineasPack[j];
						}
					}
				}
				if(contPack > 0){ //Hay pack con ese codigo
					if(contPack==1){
						var lineaPack = lineasPack[lineasConCodigo].split('-');
						var cod1=lineaPack[0];
						var cod2=lineaPack[1];
						var cant=lineaPack[2];
						var oft=lineaPack[3];
						var resta=cant-unid;
						if(contUnidPack>resta){
							cant=cant-resta;
							if(newPack==''){
								newPack=cod1+'-'+cod2+'-'+cant+'-'+oft;
							}else{
								newPack=newPack+'#'+cod1+'-'+cod2+'-'+cant+'-'+oft;
							}
						}
					}else{ //hay mas de un pack con ese libro
						var lineaConCodigo=lineasConCodigo.split('-');
						for (var k=0;k<lineaConCodigo.length;k++){
							var lineaPack = lineasPack[k].split('-');
							var cod1=lineaPack[0];
							var cod2=lineaPack[1];
							var cant=lineaPack[2];
							var oft=lineaPack[3];
							if(cant>=unid){
								cant=unid;
								if(newPack==''){
									newPack=cod1+'-'+cod2+'-'+cant+'-'+oft;
								}else{
									newPack=newPack+'#'+cod1+'-'+cod2+'-'+cant+'-'+oft;
								}
							}
						}
					}
				}
			}else{
				if (codigo==aCodigo){
					copiarPack=true;
				}
			}
		}
	}
	if (copiarPack){
		newPack=iniPack;
	}
	setCookie("pack",newPack,"","/","","");
	}
}
function pagos(k){
	var inp2=document.getElementById('metodoEnvioChk'+k);
	if (inp2!=null && typeof(inp2)!='undefined' && inp2.nodeType==1){
		fenvio=inp2.value;
		var rcontra=document.myForm.radioCon;
		var vcontra=document.myForm.contrarr;
		if (rcontra!=null && typeof(rcontra)!='undefined' && rcontra.nodeType==1){
			if (vcontra!=null && typeof(vcontra)!='undefined' && vcontra.nodeType==1){
				var opc=vcontra.value;
				var opc2=opc.split('-');
				var encon=false;
				var metod;
				for (var i=0;(i<opc2.length && !encon);i++){
					metod=opc2[i];
					if (metod==fenvio) encon=true;
				}
				var inputRa=eval('document.myForm.tipoPago'+rcontra.value);
				var etiq=getFirstChild(getNextSibling(inputRa));
				if (!encon && opc!=''){
					inputRa.disabled=true;
					inputRa.checked=false;
					inputRa.style.visibility="hidden";
					eval('document.myForm.tipoPago'+(rcontra.value-1)).checked=true;
					etiq.style.visibility="hidden";
				}else{
					if (encon){
						inputRa.disabled=false;
						inputRa.style.visibility="visible";
						etiq.style.visibility="visible";
					}
				}
			}
		}
	}
}