//<script>
//funcion:confirmarDatos()
//descripcion: Función que comprueba que exista
function confirmarDatos(vEmpresa){

	obj1= eval("document.all.item(\"cliente\")")
	obj2 = eval("document.all.item(\"productoDAT\")")
	
	if (obj1 && obj2){
			IdCliente = obj1.value
			IdProducto = obj2.value
			
			if (IdCliente=="" || IdCliente==null || IdProducto=="" || IdProducto==null ){
				 
				 if (IdCliente=="" || IdCliente==null){ 
							alert(aTextos[192])
							obj1.focus()
				 }
				 if(IdProducto=="" || IdProducto==null){				 
							alert(aTextos[172])
							obj2.focus()
				 }
				 return false;
			}						
			else{
				TanqueValidar();
				//parametro que se pasa a todos los asp para que cargue la pagina del servidor.
				var d = new Date()
				var dFecha = d.getTime()				
				top.generador.location.href="comprobarDatos.asp?idcliente="+ IdCliente  + "&idempresa="+ vEmpresa +  "&fecha=" + dFecha+"&producto="+ IdProducto; 	
				return false;			
			}
	}
	else{		
		return false;
		
	}

}

//funcion : TruncDecimales
//descripcion : Función que deja el total con Session("numDecimales") decimales
//entrada : ftotal-> Valor a truncar 
function TruncDecimales(fTotal,iNumDec){
    var reComaPunt =/,/g;
    var sTotal = new String(fTotal)	   	    
    var sTotal = sTotal.replace(reComaPunt,'.') // PEP 26/04/2004 21:37
    var aTotal = sTotal.split(".");

    if (aTotal.length > 1) {
	   if (aTotal[1].length > iNumDec) {   		  
		  if (iNumDec>0){
				var sTruncado = aTotal[1].substring(0,iNumDec);
				if  (parseInt(aTotal[1].substring(iNumDec,iNumDec+1))>=5){
							//para incrementar el decimal convertimos sTruncado en decimal
							var decTrunc = "0."+sTruncado
							//Creamos el decimal que se ha de sumar 00...(tantos como decimales)1									 
							var decAdd = Math.pow(10,-iNumDec)									
							var decTotal = parseFloat(decTrunc) + parseFloat(decAdd)																											
									
							//Al sumar 2 reales hay casos en que se produce un error en la
							//suma este if controla el error, si se produce este error una vez sumado
							//  000001 al valor volvemos a llamar a la funcion truncar para que me
							//trunque este decimal
							var sDecTotal = new String(decTotal)
							var iVal =parseInt(parseInt(sDecTotal.substring(6,7)))
							if ((iVal>=0) && (iVal<=9)) {
								decTotal += 0.000001
								decTotal = TruncDecimales(decTotal,iNumDec);  
							}
							sTotal = decTotal																
							//incrementamos el valor real del total									
									
							if (parseInt(sTotal)==1){ 
										aTotal[0] = parseInt(aTotal[0])+1
										sTotal = aTotal[0] + ".0"
							}
							else{																
								//obtenemos la parte decimal
								sTruncado = new String(sTotal)
								aTruncado = sTruncado.split(".")
								sTruncado = aTruncado[1]
								sTotal = aTotal[0] + "." + sTruncado;
									
							}
									
					  }
					  else{
							sTotal = aTotal[0] + "." + sTruncado;
							
					  }
			}
			else{ 
						 sTotal = aTotal[0]
						if (parseInt(aTotal[1].substring(0,1))>=5)
								sTotal++;
						
			}
	   }
    }     
	return (sTotal)
}





//Funcion que comprueba si las tablas de los articulos estan generadas
function validarPropuesta(vEmpresa) {
  //Òscar 03/12/2003
  //Posem l'article "SEP" allà on no n'hi ha cap
  comprovaNoHiHaLiniaBuida();
  //Fi Òscar 03/12/2003
	var sTipoDoc = document.all.item("TipoDoc").value;
	if (sTipoDoc == "P") {
		var sTablas = document.all.item("Modelo");
		var sGenerica = document.all.item("ofertaGenerica").value;
		var sTipusOferta = document.all.item("TipoOferta").value;
			//sGenerica!='6+ofertaGenerica+ofertaGenerica+valor+Doc+SI'
		if (sTablas != '[object]' && sTipusOferta=="1"){
			alert(aTextos[188]);
			document.all.item("codigo1DAT").focus();
			return false;
		}
	}	
	//comprobacion de que existe el cliente y el producto
	obj1= eval("document.all.item(\"cliente\")")
	obj2 = eval("document.all.item(\"productoDAT\")")
	
	if (obj1 && obj2){
			IdCliente = obj1.value
			IdProducto = obj2.value
					
			if (IdCliente=="" || IdCliente==null || IdProducto=="" || IdProducto==null ){
						 
				 if (IdCliente=="" || IdCliente==null){ 
							alert(aTextos[192])
							obj1.focus()
				 }
				 if(IdProducto=="" || IdProducto==null){				 
							alert(aTextos[172])
							obj2.focus()
				 }
				 return false;
			}						
			else{
				TanqueValidar();

				//parametro que se pasa a todos los asp para que cargue la pagina del servidor.
				var d = new Date()
				var dFecha = d.getTime()				
				if (sTipoDoc == "P") {
						top.generador.location.href="comprobarDatos.asp?idcliente="+ IdCliente  + "&idempresa="+ vEmpresa +  "&modo=P&fecha=" + dFecha + "&producto="+ IdProducto;	
				}
				else top.generador.location.href="comprobarDatos.asp?idcliente="+ IdCliente + "&idempresa="+ vEmpresa +  "&modo=O&fecha=" + dFecha+"&producto="+ IdProducto;	
				return false;			
			}
	}
	else{		
		return false;
				
	}
}

function validarCliente(form) {
	var wCliente = form.Cliente.value;
	var wContacto = form.Contacto.value;
	var vfrase = /^\w+(.+)+$/;
	if (wCliente == ""){		
		alert(aTextos[189]);
		form.Cliente.focus();
		return false;	
	}	
	//if (!vfrase.test(wCliente))	{		
	//	alert(wCliente + " ¡ Cliente NO VALIDO !\nPor favor, introduzca Id. y nombre del cliente.");
	//	form.Cliente.select();		
	//	form.Cliente.focus();		
	//	return false;			
	//}	
			
	var bconfirm=confirm(aTextos[180]);
	if(bconfirm){
		return true;
	}
	else{
		 return false;
	}
}

//funcion que mira que esten los datos del cliente correctos y las tablas generadas.
function validarDatos(form,vEmpresa){
	var wCliente = form.Cliente.value;
	var wContacto = form.Contacto.value;
	var vfrase = /^\w+(.+)+$/;
	if (wCliente == ""){		
		alert(aTextos[170]);
		form.Cliente.focus();
		return false;	
	}	
	if (!vfrase.test(wCliente))	{		
		alert(wCliente + " " +aTextos[190]);
		form.Cliente.select();		
		form.Cliente.focus();		
		return false;			
	}	
				
	return validarPropuesta(vEmpresa);
}

//Funcion que comprueba que el identificador de cliente haya sido introducido
function ComprobarCliente() {
	if (document.all.item('Cliente').value == ""){
		alert(aTextos[192]);
		document.all.item('Cliente').focus();
		return false;
	}
}

//Funcion que carga los datos del articulo introducido cuando este se informa por teclado
function CargarLinea (empresa, numLinea, Cantidad) {
	var sTipoDoc = document.all.item("TipoDoc").value;
	var sDocId = document.all.item("Ref").value;
	var sCodArt = document.all.item('Codigo' + numLinea + 'DAT').value;
	var sInfoCliente = new String(document.all.item('Cliente').value);
	var aCliente = sInfoCliente.split("-");
	var sCliente = aCliente[0];
	var sEmpresa = eliminar_blancos(empresa);		
	//parametro que se pasa a todos los asp para que cargue la pagina del servidor.
	var d = new Date();
	var dFecha = d.getTime();
  
	//Òscar 24/02/2004
	//top.generador.location.href="generador.asp?accion=A&cliente=" + sCliente + "&codArticulo=" + sCodArt + "&tagPrecio=PrecioUn" + numLinea + "DAT&desc=Descripcion" + numLinea + "DAT&tagArticulo=Codigo" + numLinea + "DAT&cantidad="+ Cantidad + "&empCom=" + sEmpresa + "&tipo=" + sTipoDoc + "&fecha=" + dFecha;
	var esSubtTotal;
	esSubtTotal = sCodArt.toUpperCase()=="SUB";
	if (esSubtTotal)
	{
  	document.all.item('Codigo' + numLinea + 'DAT').value = document.all.item('Codigo' + numLinea + 'DAT').value.toUpperCase();
    calculaTotal("total"+numLinea+"DAT");
	}
	else
	{
	  top.generador.location.href="generador.asp?accion=A&cliente=" + sCliente + "&codArticulo=" + sCodArt + "&tagPrecio=PrecioUn" + numLinea + "DAT&desc=Descripcion" + numLinea + "DAT&tagArticulo=Codigo" + numLinea + "DAT&cantidad="+ Cantidad + "&empCom=" + sEmpresa + "&tipo=" + sTipoDoc + "&fecha=" + dFecha + "&docId=" + sDocId;
    }
	//Fi Òscar 24/02/2004
}

function RecargarTablas(sEmpCom){
	sTablas = document.all.item("Modelo");
	if (sTablas == '[object]'){
		construirCodigo (sEmpCom,'0','0');
	}
}

function mostrarClientes(tipo)
{
	mostrarClientes2(tipo,"","Cliente","");
}

function mostrarClientes2(tipo,URLPrefijo,varIDClienteName,emp) {
	var sCadena = new String(document.all.item(varIDClienteName).value);
	sTipo = sCadena.substr(0,2);
	//si sTipo contiene la cadena N# entonces es que se quiere dar de alta 
	//un nuevo cliente
	
	//parametro que se pasa a todos los asp para que cargue la pagina del servidor.
	var d = new Date();
	var dFecha = d.getTime();

	if (sTipo=="N#"){
		var sLlamada = URLPrefijo+"frm_cli_pot.htm";
		var wOpen = window.open(sLlamada,'new','toolbar=NO,scrollbars=YES,width=640,height=480');	
		
	}
	else {
		//if (!isNaN(sCadena)) sCadena="?"+sCadena;
		var sLlamada = URLPrefijo+"mostrarClientes.asp?cadena=" + sCadena + "&tipo=" + tipo + "&empresa=" + emp + "&fecha=" + dFecha;
		var wOpen = window.open(sLlamada,'new','toolbar=NO,scrollbars=YES,width=640,height=480');
	}

}

function mostrarClientes3(tipo,URLPrefijo,varIDClienteName,emp) {
	var sCadena = new String(document.all.item(varIDClienteName).value);
	sTipo = sCadena.substr(0,2);
	//si sTipo contiene la cadena N# entonces es que se quiere dar de alta 
	//un nuevo cliente
	
	//parametro que se pasa a todos los asp para que cargue la pagina del servidor.
	var d = new Date();
	var dFecha = d.getTime();

	if (sTipo=="N#"){
		var sLlamada = URLPrefijo+"frm_cli_pot.htm";
		var wOpen = window.open(sLlamada,'new','toolbar=NO,scrollbars=YES,width=640,height=480');	
		
	}
	else {
		//if (!isNaN(sCadena)) sCadena="?"+sCadena;
		var sLlamada = URLPrefijo+"mostrarClientesV2.asp?cadena=" + sCadena + "&tipo=" + tipo + "&empresa=" + emp + "&fecha=" + dFecha;
		var wOpen = window.open(sLlamada,'new','toolbar=NO,scrollbars=YES,width=640,height=480');
	}

}


function obtenerCliente (tipo, sEmpCom)
{
	obtenerCliente2(tipo, sEmpCom, "","Cliente");
}

function obtenerCliente2 (tipo, sEmpCom, URLPrefijo,varIDClienteName) {
	var sCliente = document.all.item(varIDClienteName).value;
	
	//parametro que se pasa a todos los asp para que cargue la pagina del servidor.

	var d = new Date();
	var	dFecha = d.getTime();

	if (isNaN(sCliente)) sCliente = -1;
	
	if (tipo == "S")
		window.top.generador.location.href=URLPrefijo+"generador.asp?accion=B&cliente=" + sCliente + "&empCom=" + sEmpCom + "&fecha=" + dFecha;
	if (tipo =="O")
		window.top.generador.location.href=URLPrefijo+"generador.asp?accion=BO&cliente=" + sCliente + "&empCom=" + sEmpCom + "&fecha=" + dFecha;
	if (tipo =="P")
		window.top.generador.location.href=URLPrefijo+"generador.asp?accion=BO&cliente=" + sCliente + "&empCom=" + sEmpCom + "&fecha=" + dFecha;
}

function mostrarProductos(tipo)
{
	mostrarProductos2(tipo,"");
}

function mostrarProductos2(tipo,URLPrefijo) {
	var sCadena = document.all.item("ProductoDAT").value;
	//parametro que se pasa a todos los asp para que cargue la pagina del servidor.
	var d = new Date();
	var	dFecha = d.getTime();

	var sLlamada = URLPrefijo+"mostrarProductos.asp?cadena=" + sCadena + "&fecha=" + dFecha;	
	window.open(sLlamada,'new','toolbar=NO,scrollbars=YES,width=640,height=480');
}

function mostrarArticulos(tipo, cliente, tagCodigo, tagDescripcion, tagPrecio, empComercial, cantidad) {
	var sCadena = eval("document.all.item(\"" + tagCodigo + "\").value");
	//parametro que se pasa a todos los asp para que cargue la pagina del servidor.
	var d = new Date();
	var	dFecha = d.getTime();
	var sDocId = document.all.item("Ref").value;

	sCadena = eliminar_blancos(sCadena);
	var sLlamada = "mostrarArticulos.asp?cadena=" + sCadena + "&cliente=" + cliente + "&tagDescripcion=" + tagDescripcion + "&tagPrecio=" + tagPrecio + "&tagArticulo=" + tagCodigo +"&cantidad=" + cantidad + "&empComercial=" + empComercial + "&tipo=" + tipo + "&fecha=" + dFecha + "&docId=" + sDocId;
	
	window.open(sLlamada,'new','toolbar=NO,scrollbars=YES,width=640,height=480');
}

function mostrarEstoc(tipo, cliente, tagCodigo, tagDescripcion, tagPrecio, empComercial, cantidad) {
	var sCadena = eval("document.all.item(\"" + tagCodigo + "\").value");
	//parametro que se pasa a todos los asp para que cargue la pagina del servidor.
	var d = new Date();
	var	dFecha = d.getTime();

	sCadena = eliminar_blancos(sCadena);
	var sLlamada = "mostrarEstoc.asp?cadena=" + sCadena + "&cliente=" + cliente + "&tagDescripcion=" + tagDescripcion + "&tagPrecio=" + tagPrecio + "&tagArticulo=" + tagCodigo +"&cantidad=" + cantidad + "&empComercial=" + empComercial + "&tipo=" + tipo + "&fecha=" + dFecha;
	
	window.open(sLlamada,'new','toolbar=NO,scrollbars=YES,width=640,height=480');
}

function WizardArticulos(tipo,  tagCodigo, tagDescripcion, tagPrecio, empComercial, cantidad, modelBombaOLD) {
	var sCadena = ''; //eval("document.all.item(\"" + tagCodigo + "\").value");
	var sCliente = eval("document.all.item('Cliente').value");
	var sBombaKit = eval("document.all.item('TipusBombaKit').value");
	var sBombaRecobert = eval("document.all.item('TipusBombaRecobert').value");
	var modelBomba = eval("document.all.item('TipusBomba').value");
	//alert(eliminar_espais(modelBomba));
	//parametro que se pasa a todos los asp para que cargue la pagina del servidor.
	var d = new Date();
	var	dFecha = d.getTime();
	var sDocId = document.all.item("Ref").value;


	sCadena = eliminar_blancos(sCadena);
	var sLlamada = "WizardArticulos.asp?cadena=" + sCadena + "&bomba="+ eliminar_espais(modelBomba) + "&bombaKit="+ sBombaKit + "&bombaRecobert="+ sBombaRecobert + "&cliente=" + sCliente + "&tagDescripcion=" + tagDescripcion + "&tagPrecio=" + tagPrecio + "&tagArticulo=" + tagCodigo +"&cantidad=" + cantidad + "&empComercial=" + empComercial + "&tipo=" + tipo + "&fecha=" + dFecha + "&docId=" + sDocId;
	
	window.open(sLlamada,'new','toolbar=NO,scrollbars=YES,width=640,height=480');
}

function PrecioTotal(id_linea){
/*	var precio=0;	
	precio= document.all.item(id_linea).value;
	fPrTotal += parseFloat(precio);
	document.all.item('Total').value = fPrTotal;
	document.all.item('Euros').value = fPrTotal/166.386;
	return(true);	
*/
}

function calcularTotales (iNumDec) {
	var fPrTotal = 0;
	var fPaquete = 0;
	var fPortes = 0;
	var fPeso = 0.00;
	var i;
	var sPeso = "";

	for (var i=1; i<=iNumLineas; i++) {
  	//Òscar 24/02/2002
		//if (document.all.item('total' + i + "DAT").value != "") 	
		if ((document.all.item('total' + i + "DAT").value != "") && (document.all.item('codigo' + i + "DAT").value.toUpperCase() != "SUB"))
		{
  		fPrTotal += parseFloat(document.all.item('total' + i + "DAT").value);	
		}
		//Fi Òscar 24/02/2002
	
		if (document.all.item('peso' + i + "UN").value != "") 
			fPeso += parseFloat(document.all.item('peso' + i + "UN").value)*parseFloat(document.all.item('cantidad' + i +'DAT').value);	
	}
	
	var sPaquete = document.all.item('PaqueteDAT').value;
	var	sPortes = document.all.item('PortesDAT').value;

	if (sPaquete != "") fPaquete = parseFloat(sPaquete);
	if (sPortes != "") fPortes = parseFloat(sPortes);

	fPrTotal += fPaquete + fPortes;

	//dejamos el total con Session("numDecimales") decimales
	sTotal = TruncDecimales(fPrTotal,iNumDecimales);  
	 
	if (isNaN(fPrTotal))
		sTotal = 0;
	
	//dejamos el total en euros con Session("numDecimales") decimales  
	if (parseFloat(fCambio)!=0)		 
		var fEuros = fPrTotal/fCambio;    
	else
		var fEuros = 0;
  	var sTotalEuros = new String(fEuros);
    
  	//dejamos el total con Session("numDecimales") decimales
	sTotalEuros = TruncDecimales(sTotalEuros,2);  // 2 perque son EUROS !! PEP
	
	
	sPeso = TruncDecimales(fPeso,2);
	
	document.all.item('totalPesoTXT').value = sPeso;
	document.all.item('totalPtsDAT').value = sTotal;
	document.all.item('totalEurosDAT').value = sTotalEuros;      

}

function PrecioLinea(id_cantidad,id_precio,id_descuento,id_precio_total,numDecimales,id_peso,id_pesoTXT){
  var sCantidad=eliminar_blancos(document.all.item(id_cantidad).value);
  var sPrecio = eliminar_blancos(document.all.item(id_precio).value);
  var sPeso = eliminar_blancos(document.all.item(id_peso).value);
  var sDescuento = new String(eliminar_blancos(document.all.item(id_descuento).value));
  sDescuento = sDescuento.replace(",",".");
  var iNumDec = numDecimales; //iNumDecimales;
  var fTotal;  
  var fPesTotal;

  //Òscar 23/02/2004
  var esSubTotal;
  var esSeparador;
  esSubTotal = (esLiniaSubtotal(id_cantidad));
  esSeparador = (esLiniaSeparador(id_cantidad));
  //Fi Òscar 23/02/2004
  
  //Òscar 23/02/2004
	//if (sPrecio=="" || isNaN(sPrecio))
	if (sPrecio=="" || isNaN(sPrecio) || esSubTotal || esSeparador)
	{
  	if (esSubTotal || esSeparador)
  	{
    	document.all.item(id_precio).value = "";
  	}
  	else
  	{
		  document.all.item(id_precio).value = 0;
	  }
		sPrecio=0;
	}
	
	//Òscar 23/02/2004
	//if (sCantidad=="" || isNaN(sCantidad))
	if (sCantidad=="" || isNaN(sCantidad) || esSubTotal || esSeparador)
	{
  	if (esSubTotal || esSeparador)
  	{
    	document.all.item(id_cantidad).value="";
    	sCantidad=0;	

  	}
  	else
  	{
		 document.all.item(id_cantidad).value=1;
		 sCantidad=1;	
	  }
		 
	}

	//Òscar 23/02/2004
	//if (isNaN(sPeso) || (sPeso==-1) || sPeso=="") 
	if (isNaN(sPeso) || (sPeso==-1) || sPeso=="" || esSubTotal || esSeparador) 
	{ 
		document.all.item(id_peso).value = '';
		document.all.item(id_pesoTXT).value = '';
		
		sPeso=0;
	}
	else 
	{
		fPesTotal=parseFloat(sPeso);
		fPesTotal=fPesTotal*parseFloat(sCantidad);
		document.all.item(id_peso).value = sPeso;
		
		sPeso=TruncDecimales(fPesTotal,2);
		document.all.item(id_pesoTXT).value = sPeso;
	}
	
	
	//Òscar 23/02/2004
	if (sDescuento=="" || isNaN(sDescuento) || esSubTotal || esSeparador)
	{
	   if (esSubTotal || esSeparador)
	   {
  	  document.all.item(id_descuento).value= "";
	   }
	   else
	   {
  	  document.all.item(id_descuento).value=0;
	   }
		 sDescuento=0;	
	}	
	
	fPrecioUn = parseFloat(sPrecio);
	fPrecioUn = TruncDecimales(fPrecioUn,iNumDec);
	fDescuento = fPrecioUn*parseFloat(sDescuento);
	fDescuento = fDescuento / 100; 
	fPrecioNeto = fPrecioUn - fDescuento;
//alert(fPrecioNeto + "-" + fDescuento + "-" + fPrecioUn)
	fPrecioNeto = TruncDecimales(fPrecioNeto,iNumDec);
	fTotal = fPrecioNeto*parseFloat(sCantidad);	
	//dejamos el total con Session("numDecimales") decimales
	sTotal = TruncDecimales(fTotal,iNumDec);
  
	//Òscar 23/02/2004
	if (!esSubTotal && !esSeparador)
	{
  //Fi Òscar 23/02/2004
    //precio total linea
    if (!isNaN(fTotal))
  	document.all.item(id_precio_total).value= sTotal;
    else 
  	document.all.item(id_precio_total).value= 0;
    //precio total acumulado de la propuesta  
    calcularTotales (iNumDec);
    
    if ((document.all.item(id_cantidad).value == "") ||
  	  (document.all.item(id_precio).value == "")) {
  		document.all.item(id_precio_total).value= "";
    }      
  //Òscar 23/02/2004
  }
  //Fi Òscar 23/02/2004
  
  //Òscar 23/02/2004	  
  if (esSubTotal)
  {
    calculaTotal(id_precio_total);
  }
  //Fi Òscar 23/02/2004
}

function PrecioDescuento(id_cantidad, id_precio, id_descuento, id_precio_total, numDecimales){
  var sCantidad=document.all.item(id_cantidad).value;
  var sPrecio = document.all.item(id_precio).value;
  var sDescuento = new String(eliminar_blancos(document.all.item(id_descuento).value));
  sDescuento = sDescuento.replace(",",".");
  var iNumDec = numDecimales; //iNumDecimales;
  var fTotal;
  var fDescuento;

  //Òscar 23/02/2004
  var esSubTotal = esLiniaSubtotal(id_cantidad);
  var esSeparador = esLiniaSeparador(id_cantidad);
  //Fi ÒScar 23/02/2004
  
  if (parseFloat(sDescuento) > 100) 
		alert(aTextos[193]);
  else {
	if (sDescuento=="" || isNaN(sDescuento)){
  	  //Òscar 23/02/2004
		  //document.all.item(id_descuento).value=0;
		  if (esSubTotal || esSeparador)
		  {
  		  document.all.item(id_descuento).value="";
		  }
		  else
		  {
		    document.all.item(id_descuento).value=0;
	    }
	    //Fi Òscar 23/02/2004
		 sDescuento=0;	
	}
	  	fTotal = parseFloat(sPrecio)*parseFloat(sCantidad);
	fDescuento = fTotal*parseFloat(sDescuento);
	fDescuento = fDescuento / 100; 
	fTotal = fTotal - fDescuento;
	
	//dejamos el total con Session("numDecimales") decimales
	sTotal = TruncDecimales(fTotal,iNumDec);
   
	//precio total linea
	if (!isNaN(fTotal))
		document.all.item(id_precio_total).value= sTotal;
    else 
		document.all.item(id_precio_total).value= 0;

	//precio total acumulado de la propuesta  
	calcularTotales (iNumDec);
  
	if ((document.all.item(id_cantidad).value == "") ||
		  (document.all.item(id_precio).value == "")) {
			document.all.item(id_precio_total).value= "";
	}      
  }
  //Òscar 23/02/2004	  
  if (esSubTotal)
  {
    calculaTotal(id_precio_total);
  }
  //Fi Òscar 23/02/2004

}

//Nombre: construirCodigo.
//Entradas: identificador de la entrada correspondiente al input del form referente al
//			codigo del articulo que informa el usuario.
//Descripcion: Generacion del codigo de las tablas especificas de la bomba con el codigo
//			   que nos pasan como entrada.
function construirCodigo(empCom, docId, docCnum) {
	//parametro que se pasa a todos los asp para que cargue la pagina del servidor.
	var d = new Date();
	var	dFecha = d.getTime();

	var sTipoOferta = eval("document.all.item('TipoOferta').value");
	if (sTipoOferta != "1") { // Si no es tipus bomba cal sortir
		alert("¡ Esta no es una oferta de bombas ! \n\n This is not a pump offer !"  );
		return 1;
	}
	var sTipoDoc = eval("document.all.item('TipoDoc').value");
	var sCodArt = eval("document.all.item('Codigo1DAT').value");
	var obj1 = eval("document.all.item('Codigo2DAT')");
	var sCodMotor="";
	if (obj1){
		sCodMotor = obj1.value;
	}
	var obj2 = eval("document.all.item('Codigo3DAT')");
	var sCodAccesorio="";
	if (obj2){
		sCodAccesorio = obj2.value;
	}
	
	//var sLlamada = "generador.asp?accion=G&codArticulo=" + sCodArt + "&codMotor=" + sCodMotor + "&docId=" + docId + "&docCnum=" + docCnum;
	//window.open(sLlamada,'new','toolbar=NO,scrollbars=YES,width=640,height=480');
	top.generador.location.href="generador.asp?accion=G&codArticulo=" + sCodArt + "&codMotor=" + sCodMotor + "&codAccesorio=" + sCodAccesorio + "&docId=" + docId + "&docCnum=" + docCnum + "&tipo=" + sTipoDoc + "&empCom=" + empCom + "&fecha=" + dFecha;
}

//Òscar 01/12/2003
function comprovaNoHiHaLiniaBuida()
{
  for (i=1;i<=iNumLineas;i++)
  {
    if (document.all.item("codigo"+ i +"DAT")!=null)
    {
      if (document.all.item("codigo"+ i +"DAT").value=="")
      {
        document.all.item("codigo"+ i +"DAT").value = "SEP";
      } else {
	      if (document.all.item("codigo"+ i +"DAT").value=="SUB")
	      {
		//alert("Poso checked=Fals");
	        document.all.item("agrupado"+ i +"").checked = false;
	      }
      }
    }
  }
}
//Òscar 01/12/2003

function NuevaLinea(vNumDecimales, empresa, empCom, cantidad,doc_id,doc_cnum) {
  //Òscar 01/12/2003
  comprovaNoHiHaLiniaBuida();
  //Fi Òscar 01/12/2003
	if (document.all.item('Cliente').value == ""){
		alert(aTextos[192]);
		document.all.item('Cliente').focus();
		return false;
	}
	sEmpresa = eliminar_blancos(empresa);
	GestionTablaPedidos(vNumDecimales, sEmpresa, -1, empCom, cantidad,doc_id,doc_cnum);
	document.all.item("codigo"+ iNumLineas +"DAT").focus();
}

function BorrarLinea(vNumDecimales, empresa, vLinea, empCom, cantidad,doc_id,doc_cnum) {
	if (document.all.item('Cliente').value == ""){
		alert(aTextos[192]);
		document.all.item('Cliente').focus();
		return false;
	}
	sEmpresa = eliminar_blancos(empresa);	
	GestionTablaPedidos(vNumDecimales, sEmpresa, vLinea, empCom,cantidad,doc_id,doc_cnum);
	
	calcularTotales(vNumDecimales);
}

function busquedaArticulos(tipo,tagCodigo,tagDescripcion,tagPrecio,empComercial,cantidad) {
	if (document.all.item('Cliente').value == ""){
		alert(aTextos[192]);
		document.all.item('Cliente').focus();
		return false;
	}
	//var sCodigo = eval("document.all.item('" + tagCodigo + "').value");
	mostrarArticulos(tipo,document.all.item('Cliente').value,tagCodigo,tagDescripcion,tagPrecio,empComercial,cantidad);
}

function busquedaEstoc(tipo,tagCodigo,tagDescripcion,tagPrecio,empComercial,cantidad) {
	if (document.all.item('Cliente').value == ""){
		alert(aTextos[192]);
		document.all.item('Cliente').focus();
		return false;
	}
	
	//var sCodigo = eval("document.all.item('" + tagCodigo + "').value");
	mostrarEstoc(tipo,document.all.item('Cliente').value,tagCodigo,tagDescripcion,tagPrecio,empComercial,cantidad);
}

function eliminar_blancos(sString) {
	var sTexto = new String("");
	var sResultat = "";	
	var sCar = "";
		
	sTexto = sString;
	if (!(sTexto == null)){ 
		var iLongitud = sTexto.length;
		sCar = sTexto.substring (iLongitud-1, iLongitud);
		while (sCar == " ") {
			iLongitud -= 1;
			sCar = sTexto.substring(iLongitud-1, iLongitud);
		}
			
		sResultat = sTexto.substring (0,iLongitud);
	}

	return sResultat;
}
function eliminar_espais(sString) {
	var sTexto = new String("");
	var sResultat = "";	
	var sCar = "";
		
	sTexto = sString;
	if (!(sTexto == null)){ 
		var iLongitud = sTexto.length;
		while (iLongitud>0) {
			sCar=sTexto.substring(iLongitud-1, iLongitud);
			if (sCar!= " ") {
				sResultat=sCar+sResultat;
			}
			iLongitud -= 1;
		}
	}

	return sResultat.toUpperCase();
}

function Canviar_Linies(sString, iInici, iFinal) {
	var sText = new String("");
		
	sText = sString;
	if (!(sText == null) && (iInici!=iFinal)){ 
		  sText = sText.replace("Linea"+iInici, "Linea"+iFinal);
		  sText = sText.replace("NumLinea"+iInici, "NumLinea"+iFinal);
		  sText = sText.replace("codigo"+iInici, "codigo"+iFinal);
		  sText = sText.replace("cantidad"+iInici, "cantidad"+iFinal);
		  sText = sText.replace("descripcion"+iInici, "descripcion"+iFinal);
		  sText = sText.replace("precioUn"+iInici, "precioUn"+iFinal);
		  sText = sText.replace("descuento"+iInici, "descuento"+iFinal);
		  sText = sText.replace("total"+iInici, "total"+iFinal);
		  sText = sText.replace("mostrarDesc"+iInici, "mostrarDesc"+iFinal);
		  sText = sText.replace("agrupado"+iInici, "agrupado"+iFinal);
	 	  //alert("Linea"+iInici + "   ->   Linea"+iFinal + " : " + sString + " -> " + sText);
	}

	return sText;
}

//funcion:GestionTablaPedidos()
//descripcion:Funcion que gestiona los pedidos para que el numero de lineas del
//	pedido pueda crecer  dinamicamente. Para ello se utiliza un array donde se guardaran las 
//	lineas ya creadas, este array se utilizará para crear otra vez estas lineas y insertar una
//	nueva linea,tambien permiter poder eliminar una linea,
// para esto se utilizará la propiedad inner HTML
function GestionTablaPedidos(vNumDecimales, sEmpresa, vLinea, sEmpCom, iCantidad,doc_id,doc_cnum){	

	
	var sTablaPedidos="";	
	var sValLinea,sValNumLinea,sHiddenCodigo,sValCodigo,sCantidad,sCantidadDat,sPeso,sPesoU;
	//Òscar 23/02/2003
	var sumaTotal = 0;
	var esSubTotal = false;
	var esSeparador = false;
	//Fi Òscar 23/02/2004
	
	sTablaPedidos+="<TABLE BORDER=\"0\">";
	sTablaPedidos+="<TR>";
	sTablaPedidos+="<TD><B><SPAN class=\"texto1\">"+ aTextos[77] + "</SPAN></B></TD>";
	sTablaPedidos+="<TD><B><SPAN class=\"texto1\">"+ aTextos[78] + "</SPAN></B></TD>";
	sTablaPedidos+="<TD><B><SPAN class=\"texto1\">"+ aTextos[79] + "</SPAN></B></TD>";
	sTablaPedidos+="<TD><B><SPAN class=\"texto1\">"+ aTextos[81] + "</SPAN></B></TD>";
	sTablaPedidos+="<TD><B><SPAN class=\"texto1\">"+ aTextos[82] + "<br>(%).</SPAN></B></TD>";
	sTablaPedidos+="<TD><B><SPAN class=\"texto1\">"+ aTextos[83] + "</SPAN></B></TD>";
	sTablaPedidos+="<TD><B><SPAN class=\"texto1\">"+ aTextos[87] + "</SPAN></B></TD>";
	sTablaPedidos+="<TD><B><SPAN class=\"texto1\">"+ aTextos[88] + "</SPAN></B></TD>";
	sTablaPedidos+="<TD><B><SPAN class=\"texto1\">"+ aTextos[394] + "</SPAN></B></TD>";
	sTablaPedidos+="</TR>";
	var EliminarLinia=0;
	//sAgrupado = document.all.item("agrupado1").value;
	sAgrupado="1+1";
	var i=1;
	//obtenemos el tipo del documento
	sTipoDoc = document.all.item("TipoDoc").value;
	for(var j=1;j<=iNumLineas;j++){
  	
  	//Òscar 23/02/2004
  	esSubTotal = document.all.item("codigo"+ j +"DAT").value.toUpperCase()=="SUB";
  	esSeparador = document.all.item("codigo"+ j +"DAT").value.toUpperCase()=="SEP";
  	//Fi Òscar 23/02/2004
  	
		if (j != vLinea){
			
			//CODIGO
			//obtenemos los valores para la celdad de codigo
			sValLinea= Canviar_Linies(document.all.item("Linea"+ j).value,j,i);
			sValNumLinea= Canviar_Linies(document.all.item("NumLinea"+ j).value,j,i);
			sHiddenCodigo= Canviar_Linies(document.all.item("codigo"+ j).value,j,i); 
			// nomes permetem afegir una linia si aquesta no es blanca i l'anterior tampoc
			//if ((j<=1)||
			//	((j>1) && ((document.all.item("codigo"+ (j-1) +"DAT").value!='') || (document.all.item("codigo"+ j +"DAT").value!='')))) {
			//	EliminarLinia=0;
			//} else {
			//	EliminarLinia=1;
			//}
			sValCodigo= document.all.item("codigo"+ j +"DAT").value;
			
			//linea para la celda del codigo
			sTablaPedidos+="<TR><TD>";
			sTablaPedidos+="<INPUT TYPE=HIDDEN NAME=\"Linea"+ i +"\" VALUE=\""+ sValLinea+"\">";

			aValores=sValNumLinea.split("+");
			iorden=parseInt(aValores[0]);
			//sTablaPedidos+="<INPUT TYPE=HIDDEN NAME=\"NumLinea"+ i +"\" VALUE=\""+ sValNumLinea +"\">"; 			
			sTablaPedidos+="<INPUT TYPE=HIDDEN NAME=\"NumLinea"+ i +"\" VALUE=\""+iorden+"+NumLinea"+ i +"+NumLinea+atributo+Linea+"+ i +"\">";

	
			sTablaPedidos+="<INPUT TYPE=HIDDEN NAME=\"codigo"+ i +"\" VALUE=\""+ sHiddenCodigo +"\">";

			sTablaPedidos+="<img border=\"0\" src=\"images/wizard.gif\" WIDTH=\"20\" HEIGHT=\"18\" onClick=\"WizardArticulos(sTipoDoc,'codigo"+ i +"DAT','descripcion"+ i +"DAT','precioUn"+ i +"DAT','" + sEmpCom + "','" + iCantidad + "',form1.TipusBomba.value);\">";

			sTablaPedidos+="<img border=0 src=\"images/consulta.gif\" onClick=\"busquedaArticulos(sTipoDoc,'codigo"+ i +"DAT','descripcion"+ i +"DAT','precioUn"+ i +"DAT','" + sEmpCom + "','" + iCantidad + "');\" WIDTH=22 HEIGHT=18>";
			sTablaPedidos+="<INPUT TYPE=TEXT MAXLENGTH=\"100\" CLASS=\"inputform\" NAME=\"codigo"+ i +"DAT\" SIZE=\"10\" VALUE=\""+ sValCodigo +"\" onFocus=\"ComprobarCliente();\" onblur=\"CargarLinea('" + sEmpCom + "', " + i + ",'" + iCantidad + "');\">";
			sTablaPedidos+="</TD>";
			
			//CANTIDAD
			//obtenemos los valores para la celdad de cantidad			 
			sCantidad= Canviar_Linies(document.all.item("cantidad"+ j).value,j,i);
			//Òscar 23/02/2004
			//sCantidadDat= document.all.item("cantidad"+ j +"DAT").value;
			if (esSubTotal)
			{
  			sCantidadDat = "";
			}
			else
			{
  			sCantidadDat= document.all.item("cantidad"+ j +"DAT").value;
			}
			//Fi Òscar 23/02/2004
			 		
			//linea para la celda de cantidad
			sTablaPedidos+="<TD>";
			sTablaPedidos+="<INPUT TYPE=HIDDEN NAME=\"cantidad"+ i +"\" VALUE=\""+ sCantidad +"\">";
			sTablaPedidos+="<INPUT TYPE=TEXT MAXLENGTH=\"100\" CLASS=\"inputform\" onblur=\"PrecioLinea('cantidad"+ i +"DAT','precioUn"+ i +"DAT','descuento"+ i +"DAT','total"+ i +"DAT','"+vNumDecimales+"','peso"+ i +"UN','peso"+ i +"TXT');\" NAME=\"cantidad"+ i +"DAT\" SIZE=\"3\" VALUE=\""+ sCantidadDat +"\">";
			sTablaPedidos+="</TD>";
			
			//DESCRIPCION
			//obtenemos los valores para la celdad de descripcion			 
			sDescripcion= Canviar_Linies(document.all.item("descripcion"+ j).value,j,i);
			sDescripcionDat= document.all.item("descripcion"+ j +"DAT").value;		
			 		
			//linea para la celda de descripcion
			sTablaPedidos+="<TD>";
			sTablaPedidos+="<INPUT TYPE=HIDDEN NAME=\"descripcion"+ i +"\" VALUE=\""+ sDescripcion +"\">";
			sTablaPedidos+="<INPUT TYPE=TEXT MAXLENGTH=\"100\" CLASS=\"inputform\" NAME=\"descripcion"+ i +"DAT\" SIZE=\"15\" VALUE=\""+ sDescripcionDat +"\">";									
			sTablaPedidos+="</TD>";
			
			//PRECIO UNIDAD
			//obtenemos los valores para la celdad de precio unidad			 
			sPrecioUn = Canviar_Linies(document.all.item("precioUn"+ j).value,j,i);

			//Òscar 23/02/2004
			// PEP 08/04/2004 21:03 HO comento per poder tenir preu unitari = total /quantitat inicial
			//if (esSubTotal)
			//{
  			//	sPrecioUnDat = "";
			//}
			//else
			//{
			  sPrecioUnDat = document.all.item("precioUn"+ j +"DAT").value;
		  	//}
			//Fi Òscar 23/02/2004
			 		
			//linea para la celda de precio unidad
			sTablaPedidos+="<TD>";
			sTablaPedidos+="<INPUT TYPE=HIDDEN NAME=\"precioUn"+ i +"\" VALUE=\""+ sPrecioUn +"\">";
			sTablaPedidos+="<INPUT TYPE=TEXT MAXLENGTH=\"100\" CLASS=\"inputform\" onblur=\"PrecioLinea('cantidad"+ i +"DAT','precioUn"+ i +"DAT','descuento"+ i +"DAT','total"+ i +"DAT','"+vNumDecimales+"','peso"+ i +"UN','peso"+ i +"TXT');\" NAME=\"precioUn"+ i +"DAT\" SIZE=\"7\" VALUE=\""+ sPrecioUnDat +"\">";
			sTablaPedidos+="</TD>";
			
			//DESCUENTO
			//obtenemos los valores para la celdad de descuento			 
			sDescuento = Canviar_Linies(document.all.item("descuento"+ j).value,j,i);
			
			//Òscar 23/02/2004
			if (esSubTotal)
			{
  			sDescuentoDat = "";
			}
			else
			{
			  sDescuentoDat = document.all.item("descuento"+ j +"DAT").value;
		  }
			//Fi Òscar 23/02/2004
			 		
			//linea para la celda de descuento
			sTablaPedidos+="<TD>";
			sTablaPedidos+="<INPUT TYPE=HIDDEN NAME=\"descuento"+ i +"\" VALUE=\""+ sDescuento +"\">";
			sTablaPedidos+="<INPUT TYPE=TEXT MAXLENGTH=\"100\" CLASS=\"inputform\" onblur=\"PrecioDescuento('cantidad"+ i +"DAT','precioUn"+ i +"DAT','descuento"+ i +"DAT','total"+ i +"DAT','"+vNumDecimales+"');\" NAME=\"descuento"+ i +"DAT\" SIZE=\"3\" VALUE=\""+ sDescuentoDat +"\">";
			sTablaPedidos+="</TD>";
			
			//PRECIO TOTAL
			//obtenemos los valores para la celdad de precio total			 
			sTotal = Canviar_Linies(document.all.item("total"+ j).value,j,i);
			sTotalDat = document.all.item("total"+ j +"DAT").value;
			
			//Òscar 23/02/2004
      if (esSubTotal)
      {
        sTotal=sumaTotal;
        sTotalDat = sumaTotal;
        sumaTotal = 0;
      }			
      //Fi Òscar 23/02/2004
			 		
			//linea para la celda de precio total
			sTablaPedidos+="<TD>";
			sTablaPedidos+="<INPUT TYPE=HIDDEN NAME=\"total"+ i +"\" VALUE=\""+ sTotal +"\">";
			sTablaPedidos+="<INPUT TYPE=TEXT READONLY=\"YES\" MAXLENGTH=\"100\" CLASS=\"inputform\" NAME=\"total"+ i +"DAT\" SIZE=\"8\" onblur=\"PrecioTotal('total"+ i +"DAT');\" VALUE=\""+ sTotalDat +"\">";
		}
		//si es la ultima linea hay que mostrar el link para que se pueda añadir una linea
		//este caso se aplica cuando estamos eliminando una linea
		if( (vLinea!=-1 && j==iNumLineas && vLinea!=iNumLineas)|| (vLinea==iNumLineas && (j==(iNumLineas-1))) ){
				sTablaPedidos+="<img border=\"0\" src=\"images/+1.gif\" onClick=\"NuevaLinea('"+vNumDecimales+"','"+sEmpresa+"','" + sEmpCom + "','" + iCantidad + "','"+doc_id+"','"+doc_cnum+"');\" WIDTH=\"22\" HEIGHT=\"18\" >";
				if (i!=1){
						sTablaPedidos+="<img border=\"0\" src=\"images/DeleteLine.gif\" onClick=\"BorrarLinea('"+ vNumDecimales + "', '"+sEmpresa+"',"+i+",'" + sEmpCom + "','" + iCantidad + "','"+doc_id+"','"+doc_cnum+"');\" WIDTH=\"22\" HEIGHT=\"18\">";
				}
		}else{
			if ((vLinea==-1)||(j!=vLinea)) {
				 sTablaPedidos+="<img border=\"0\" src=\"images/DeleteLine.gif\" onClick=\"BorrarLinea('"+ vNumDecimales + "', '"+sEmpresa+"',"+i+",'" + sEmpCom + "','" + iCantidad + "','"+doc_id+"','"+doc_cnum+"');\" WIDTH=\"22\" HEIGHT=\"18\">";
			}
		}
		
		if ((j != vLinea )){ 
			//acabamos de construir la linea de pedido
			
			//MOSTRAR DESCUENTOS (SI/NO)
			sMostrarDesc = Canviar_Linies(document.all.item("mostrarDesc"+ j).value,j,i);
			sTablaPedidos+="</TD><TD>";
			if (document.all.item("mostrarDesc"+ j).checked == true)
				sTablaPedidos+="<INPUT TYPE=\"CHECKBOX\" NAME=\"mostrarDesc" + i + "\" VALUE=\"" + sMostrarDesc + "\" CHECKED=\"TRUE\">";
			else
				sTablaPedidos+="<INPUT TYPE=\"CHECKBOX\" NAME=\"mostrarDesc" + i + "\" VALUE=\"" + sMostrarDesc + "\">";
			sTablaPedidos+="</TD>";
			
			//AGRUPADO (SI/NO)
			sAgrupado = Canviar_Linies(document.all.item("agrupado"+ j).value,j,i);
			sTablaPedidos+="<TD>";
			if (document.all.item("agrupado"+ j).checked == true)
				sTablaPedidos+="<INPUT TYPE=\"CHECKBOX\" NAME=\"agrupado" + i + "\" VALUE=\"" + sAgrupado + "\" CHECKED=\"TRUE\">";
			else
				sTablaPedidos+="<INPUT TYPE=\"CHECKBOX\" NAME=\"agrupado" + i + "\" VALUE=\"" + sAgrupado + "\">";

			sTablaPedidos+="<img border=\"0\" src=\"images/estoc.jpg\" onClick=\"busquedaEstoc('O','codigo"+ i +"DAT','descripcion"+ i +"DAT','precioUn"+ i +"DAT','');\" WIDTH=\"16\" HEIGHT=\"16\">";

			sTablaPedidos+="</TD>";
					
			//PESO
			//obtenemos el valor del PESO
			sPesoU = document.all.item("peso"+ j +"UN").value;
			sPeso = document.all.item("peso"+ j +"TXT").value;
			 		
			//linea para la celda de PESO
			sTablaPedidos+="<TD>";
			sTablaPedidos+="<INPUT TYPE=HIDDEN NAME=\"peso"+ i +"UN\" VALUE=\""+ sPesoU +"\">";
			sTablaPedidos+="<INPUT TYPE=TEXT READONLY=\"YES\" MAXLENGTH=\"100\" CLASS=\"inputform\" NAME=\"peso"+ i +"TXT\" SIZE=\"8\"  VALUE=\""+ sPeso +"\">";
			sTablaPedidos+="</TD>";

			//KK sTablaPedidos+="<img border=\"0\" src=\"images/DeleteLine.gif\" onClick=\"BorrarLinea(vNumDecimales, '"+sEmpresa+"',"+i+");\" WIDTH=\"22\" HEIGHT=\"18\">";
			sTablaPedidos+="</TR>";			
			i++;
		}
		//Òscar 23/02/2004
		if (j!=vLinea)
		{
  		if (!esSubTotal)
  		{
    		if ((sTotalDat)!="")
    		{
          sumaTotal = parseFloat(sumaTotal) + parseFloat(sTotalDat);
        }
      }
      if (esSeparador)
      {
        sumaTotal = 0;
      }
    }
    //Fi Òscar 23/02/2004
	}	
	
	
	//obtenemos el último número de orden introducido para dar el valor correcto de orden
	//dentro del documento a los distintos input de una linea, para obtener el orden se 
	//utiliza la variable sTotal que contiene el último orden utilizado
	
	aValores = sAgrupado.split("+");
	iorden = parseInt(aValores[0]);	

	if(vLinea==-1){
		
		//añadimos una nueva linea de pedidos
		iNumLineas++;
		iorden++;
		sTablaPedidos+="<TR><TD>";
		sTablaPedidos+="<INPUT TYPE=HIDDEN NAME=\"Linea"+ iNumLineas +"\" VALUE=\""+iorden+"+Linea"+ iNumLineas +"+Linea+relacion+LineasPropuesta+vacio\">";
		iorden++;
		sTablaPedidos+="<INPUT TYPE=HIDDEN NAME=\"NumLinea"+ iNumLineas +"\" VALUE=\""+iorden+"+NumLinea"+ iNumLineas +"+NumLinea+atributo+Linea+"+ iNumLineas +"\">";
		iorden++;
		sTablaPedidos+="<INPUT TYPE=HIDDEN NAME=\"codigo"+ iNumLineas +"\" VALUE=\""+iorden+"+codigo"+ iNumLineas +"+Codigo+valor+Linea+adjunto\">";
		iorden++;
		
		sTablaPedidos+="<img border=\"0\" src=\"images/wizard.gif\" WIDTH=\"20\" HEIGHT=\"18\" onClick=\"WizardArticulos(sTipoDoc,'codigo"+ iNumLineas +"DAT','descripcion"+ iNumLineas +"DAT','precioUn"+ iNumLineas +"DAT','" + sEmpCom + "','" + iCantidad + "',form1.TipusBomba.value);\">";
		
		sTablaPedidos+="<img border=0 src=\"images/consulta.gif\" onClick=\"busquedaArticulos(sTipoDoc,'codigo"+ iNumLineas +"DAT','descripcion"+ iNumLineas +"DAT','precioUn"+ iNumLineas +"DAT','" + sEmpCom + "','" + iCantidad + "');\" WIDTH=22 HEIGHT=18>";
		sTablaPedidos+="<INPUT TYPE=TEXT MAXLENGTH=\"100\" CLASS=\"inputform\" NAME=\"codigo"+ iNumLineas +"DAT\" SIZE=\"10\" onFocus=\"ComprobarCliente();\" onblur=\"CargarLinea('" + sEmpCom + "', " + i + ",'" + iCantidad+ "');\">";
		sTablaPedidos+="</TD>";
				
		sTablaPedidos+="<TD>";
		sTablaPedidos+="<INPUT TYPE=HIDDEN NAME=\"cantidad"+ iNumLineas +"\" VALUE=\""+iorden+"+cantidad"+ iNumLineas +"+Cantidad+valor+Linea+adjunto\">";
		iorden++;
		sTablaPedidos+="<INPUT TYPE=TEXT MAXLENGTH=\"100\" CLASS=\"inputform\" onblur=\"PrecioLinea('cantidad"+ iNumLineas +"DAT','precioUn"+ iNumLineas +"DAT','descuento"+ iNumLineas +"DAT','total"+ iNumLineas +"DAT','"+vNumDecimales+"','peso"+ iNumLineas +"UN','peso"+ iNumLineas +"TXT');\" NAME=\"cantidad"+ iNumLineas +"DAT\" SIZE=\"3\">";
		sTablaPedidos+="</TD>";
				
		sTablaPedidos+="<TD>";
		sTablaPedidos+="<INPUT TYPE=HIDDEN NAME=\"descripcion"+ iNumLineas +"\" VALUE=\""+iorden+"+descripcion"+ iNumLineas +"+Descripcion+valor+Linea+adjunto\">";
		iorden++;
		sTablaPedidos+="<INPUT TYPE=TEXT MAXLENGTH=\"100\" CLASS=\"inputform\" NAME=\"descripcion"+ iNumLineas +"DAT\" SIZE=\"15\">";									
		sTablaPedidos+="</TD>";
				
		sTablaPedidos+="<TD>";
		sTablaPedidos+="<INPUT TYPE=HIDDEN NAME=\"precioUn"+ iNumLineas +"\" VALUE=\""+iorden+"+precioUn"+ iNumLineas +"+PrecioUnidad+valor+Linea+adjunto\">";
		iorden++;
		sTablaPedidos+="<INPUT TYPE=TEXT MAXLENGTH=\"100\" CLASS=\"inputform\" onblur=\"PrecioLinea('cantidad"+ iNumLineas +"DAT','precioUn"+ iNumLineas +"DAT','descuento"+ iNumLineas +"DAT','total"+ iNumLineas +"DAT','"+vNumDecimales+"','peso"+ iNumLineas +"UN','peso"+ iNumLineas +"TXT');\" NAME=\"precioUn"+ iNumLineas +"DAT\" SIZE=\"7\">";
		sTablaPedidos+="</TD>";
				
		sTablaPedidos+="<TD>";
		sTablaPedidos+="<INPUT TYPE=HIDDEN NAME=\"descuento"+ iNumLineas +"\" VALUE=\""+iorden+"+descuento"+ iNumLineas +"+Descuento+valor+Linea+adjunto\">";
		iorden++;
		sTablaPedidos+="<INPUT TYPE=TEXT MAXLENGTH=\"100\" CLASS=\"inputform\" onblur=\"PrecioDescuento('cantidad"+ iNumLineas +"DAT','precioUn"+ iNumLineas +"DAT','descuento"+ iNumLineas +"DAT','total"+ iNumLineas +"DAT','"+vNumDecimales+"');\" NAME=\"descuento"+ iNumLineas +"DAT\" SIZE=\"3\">";
		sTablaPedidos+="</TD>";
				
		sTablaPedidos+="<TD>";
		sTablaPedidos+="<INPUT TYPE=HIDDEN NAME=\"total"+ iNumLineas +"\" VALUE=\""+iorden+"+total"+ iNumLineas +"+Total+valor+Linea+adjunto\">";
		iorden++;
		sTablaPedidos+="<INPUT TYPE=TEXT MAXLENGTH=\"100\" READONLY=\"YES\" CLASS=\"inputform\" NAME=\"total"+ iNumLineas +"DAT\" SIZE=\"8\" onblur=\"PrecioTotal('total"+ iNumLineas +"DAT');\">";
		sTablaPedidos+="<img border=\"0\" src=\"images/+1.gif\" onClick=\"NuevaLinea('"+vNumDecimales+"','"+sEmpresa+"','" + sEmpCom + "','" + iCantidad + "','"+doc_id+"','"+doc_cnum+"');\" WIDTH=\"22\" HEIGHT=\"18\" >";
		sTablaPedidos+="<img border=\"0\" src=\"images/DeleteLine.gif\" onClick=\"BorrarLinea('"+ vNumDecimales + "', '"+sEmpresa+"',iNumLineas, '" + sEmpCom + "','" + iCantidad + "','"+doc_id+"','"+doc_cnum+"');\" WIDTH=\"22\" HEIGHT=\"18\">";
		sTablaPedidos+="</TD>";
		
		sTablaPedidos+="<TD>";
		sTablaPedidos+="<INPUT TYPE=\"CHECKBOX\" NAME=\"mostrarDesc" + iNumLineas + "\" VALUE=\"" + iorden + "+mostrarDesc" + iNumLineas + "+MostrarDesc+valor+Linea+Si\" checked>";
		iorden++;
		sTablaPedidos+="</TD>";
			
		sTablaPedidos+="<TD>";
		sTablaPedidos+="<INPUT TYPE=\"CHECKBOX\" NAME=\"agrupado" + iNumLineas + "\" VALUE=\"" + iorden + "+agrupado" + iNumLineas + "+Agrupado+valor+Linea+Si\">";
		sTablaPedidos+="<img border=\"0\" src=\"images/estoc.jpg\" onClick=\"busquedaEstoc('O','codigo"+ iNumLineas +"DAT','descripcion"+ iNumLineas +"DAT','precioUn"+ iNumLineas +"DAT','');\" WIDTH=\"16\" HEIGHT=\"16\">";
		iorden++;
		sTablaPedidos+="<TD>";
		sTablaPedidos+="<INPUT TYPE=HIDDEN NAME=\"peso"+ iNumLineas +"UN\" VALUE=\"\">";
		sTablaPedidos+="<INPUT TYPE=TEXT MAXLENGTH=\"100\" READONLY=\"YES\" CLASS=\"inputform\" NAME=\"peso"+ iNumLineas +"TXT\" SIZE=\"8\" >";
		sTablaPedidos+="</TD></TR>";
			
	}
	else{
		iNumLineas--;
	}	
	
	//EMBALAJE
	//obtenemos el valor para la celdad del valor del paquete
	sPaqueteDat = document.all.item("PaqueteDAT").value;
			
			 		
	//linea para el valor del paquete
	sTablaPedidos+="<TR><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD>";
	sTablaPedidos+="<TD colspan=\"2\"><B><SPAN class=\"texto1\">"+ aTextos[89] + ":</SPAN></B></TD>";
	sTablaPedidos+="<TD colspan=\"2\">";
	sTablaPedidos+="<INPUT TYPE=\"HIDDEN\" NAME=\"Paquete\" VALUE=\"131+Paquete+Paquete+valor+LineasPropuesta+adjunto\">";
	sTablaPedidos+="<INPUT TYPE=\"TEXT\" MAXLENGTH=\"100\" class=\"inputform\" NAME=\"PaqueteDAT\" SIZE=\"10\" onblur=\"calcularTotales ('"+vNumDecimales+"');\" VALUE=\""+ sPaqueteDat +"\">";
	sTablaPedidos+="</TD></TR>";
	
	//PORTES
	//obtenemos el valor para la celdad del valor de portes
	sPortesDat = document.all.item("PortesDAT").value;
			
	var stotalPesoTXT = document.all.item("totalPesoTXT").value;
			 		
	//linea para el valor de portes
	sTablaPedidos+="<TR><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD>";
	sTablaPedidos+="<TD colspan=\"2\"><B><SPAN class=\"texto1\">"+ aTextos[90] + ":</SPAN></B>	</TD>";
	sTablaPedidos+="<TD colspan=\"2\">";
	sTablaPedidos+="<INPUT TYPE=\"HIDDEN\" NAME=\"Portes\" VALUE=\"132+Portes+Portes+valor+LineasPropuesta+adjunto\">";
	sTablaPedidos+="<INPUT TYPE=\"TEXT\" MAXLENGTH=\"100\" class=\"inputform\" NAME=\"PortesDAT\" SIZE=\"10\" onblur=\"calcularTotales ('"+vNumDecimales+"');\" VALUE=\""+ sPortesDat +"\">";
	sTablaPedidos+="</TD><TD>";
	sTablaPedidos+="<INPUT TYPE=\"TEXT\" MAXLENGTH=\"100\" class=\"inputform\" NAME=\"totalPesoTXT\" READONLY=\"YES\" SIZE=\"8\" VALUE=\""+ stotalPesoTXT +"\">";
	sTablaPedidos+="</TD></TR>";
	//IMPORTE TOTAL
	//obtenemos el valor para la celda de la cantidad total
	stotalPtsDAT = document.all.item("totalPtsDAT").value;
			
			 		
	//linea para  la cantidad total
	sTablaPedidos+="<TR><!--Cantidad Total-->";
	sTablaPedidos+="<TD colspan=\"3\"><input type=\"button\" class=\"submit\" id=\"boton\" name=\"boton\" value=\""+ aTextos[134] + "\" onClick=\"construirCodigo('" + sEmpCom + "','"+doc_id+"','"+doc_cnum+"');\"></TD>";
	sTablaPedidos+="<TD>&nbsp;</TD>";
	sTablaPedidos+="<TD colspan=\"2\"><SPAN class=\"texto1\"><b><div id=\"cantTotal\">"+ aTextos[379] + "("+ sSimbolo + "):</div></b></SPAN></TD>";
	sTablaPedidos+="<TD COLSPAN=\"2\">";
	sTablaPedidos+="<INPUT TYPE=\"HIDDEN\" NAME=\"totalPts\" VALUE=\"133+totalPts+TotalPts+valor+LineasPropuesta+adjunto\">";
	sTablaPedidos+="<INPUT TYPE=\"TEXT\" MAXLENGTH=\"100\" class=\"inputform\" NAME=\"totalPtsDAT\" READONLY=\"YES\" SIZE=\"10\" VALUE=\""+ stotalPtsDAT +"\">";
	sTablaPedidos+="</TD></TR></table>";
	
	//EUROS	
	//obtenemos el valor para la celda de la cantidad en euros
	stotalEurosDAT = document.all.item("totalEurosDAT").value;
			
			 		
	//linea para  la cantidad en euros
	//sTablaPedidos+="<div id=\"DivEuro\" Name=\"DivEuro\" >";
	//sTablaPedidos+="<TABLE border=\"0\"><TR><!--Euros-->";
	//sTablaPedidos+="<TD><SPAN class=\"texto1\">&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD>";
	//sTablaPedidos+="<TD colspan=\"2\"><SPAN class=\"texto1\"><b>"+ aTextos[85] + ":</b></SPAN>	</TD>";
	//sTablaPedidos+="<TD COLSPAN=\"2\">";
	sTablaPedidos+="<INPUT TYPE=\"HIDDEN\" NAME=\"totalEuros\" VALUE=\"134+totalEuros+TotalEuros+valor+LineasPropuesta+adjunto\">";
	sTablaPedidos+="<INPUT TYPE=\"HIDDEN\" MAXLENGTH=\"100\" class=\"inputform\" NAME=\"totalEurosDAT\" READONLY=\"YES\" SIZE=\"10\" VALUE=\""+ stotalEurosDAT +"\">";
	//sTablaPedidos+="</TD></TR></table></div>";

 Lineas.innerHTML=sTablaPedidos; 

 //si hemos añadido una nueva línea situamos el cursor en el campo
 //código de la nueva línea.
 if(vLinea==-1){
	document.all.item("codigo"+ iNumLineas +"DAT").focus();
 }
/* if(vLinea!=-1){
	construirCodigo(sEmpCom,'0','0');
 }*/
}

//funcion:ObtenerProvinciasPais
//descripcion:Obtener las provincias de un pais
//entrada: vProvSel: Id de  la provincia seleccionada, este parámetro sólo
//	se utiliza cuando se llama a esta función desde el generador.asp-> que hemos
//	cambiado de cliente.
function ObtenerProvinciasPais(vProvSel){
	var selected=document.all.item("pais").selectedIndex;
	
	var pais_id = document.all.item("pais").options[selected].value;

	if (!isNaN(vProvSel)){
		top.generador.location.href="ObtenerProvincias.asp?id_pais=" + pais_id + "&tipo=Emp&provsel=" + vProvSel
	}
	else{	
		top.generador.location.href="ObtenerProvincias.asp?id_pais=" + pais_id + "&tipo=Emp&provsel=-1"
	}
}


//funcion:PutDecimales
//descripcion:Funcion que se utiliza en el generador.asp para tener acceso
//	a la variable iNumdecimales y poder asignar el numero de decimales a
// tener en cuenta en el documento
function PutDecimales(vNumDecimales){
	iNumDecimales=vNumDecimales
}

function getDecimales(){

	return(iNumDecimales)
}

//funcion:PutSimbolo
//descripcion:Funcion que se utiliza en el generador.asp para guardar
//	el simbolo de la divisa y poder utilizar está variable en las funciones
//	javascript de formulario.js
function PutSimbolo(vSimbolo){
	sSimbolo=vSimbolo
}

function getSimbolo(){

	return(sSimbolo)
}

//funcion:PutCambio
//descripcion:Funcion que se utiliza en el generador.asp para guardar
//	el cambio  de la divisa del cliente a euro y poder utilizar 
//	está variable en las funciones javascript de formulario.js
function PutCambio(vCambio){
	fCambio=vCambio
}

function getCambio(){
	return(fCambio)
}
//variable utilizada para saber el numero de linias que se llevan introducidas
var iNumLineas=1;
var iNumDecimales;
//variable que contiene el simbolo de la divisa.Ej.:PTS.
var sSimbolo="";
var fCambio=1 

// Numero de documents adjunts
var iNumDocuments=0;

function NouDoc(pEmpresa) {
	//parametro que se pasa a todos los asp para que cargue la pagina del servidor.
	var d = new Date();
	var	dFecha = d.getTime();


	if (iNumDocuments==0) {
		if (iNumDocumentM!=0) {
			iNumDocuments=iNumDocumentM;
			iNumDocumentM=0;
		}
	}
	iNumDocuments=iNumDocuments+1;
	var sLlamada = "UpDocument.asp?cadena=" + pEmpresa + "&NumDocuments=" + iNumDocuments + "&fecha=" + dFecha;	
	window.open(sLlamada,'new','toolbar=NO,scrollbars=YES,width=500,height=200');
}


function BorrarDocWindow(pDocument) {
	//parametro que se pasa a todos los asp para que cargue la pagina del servidor.
	var d = new Date();
	var	dFecha = d.getTime();

	var sLlamada = "DeleteDoc.asp?document=" + pDocument + "&cami=" + aTextos[401] + "&fecha=" + dFecha;	
	window.open(sLlamada,'new','toolbar=NO,scrollbars=YES,width=1,height=1');
}

function obtenirPathDoc(fitxer) {
			cami = aTextos[401];
			//fitxer = node.selectSingleNode("@NomDocument").text;
			tmpPath = fitxer.substr(0,4) + "/" + fitxer.substr(4,2);
			return cami + "/" + tmpPath + "/" + fitxer;
}

function BorrarDoc(pNumDocument) {
	var sCadena = '';
	var j=0;
	for (i=1;i<=iNumDocuments+1;i=i+1) {
		var obj = eval("document.all.item(\"document" + i + "\")");
		if (obj) {
			sDocument = document.all.item("document"+ i).value;
			snomFitxer = document.all.item("NomDocument"+ i +"DAT").value;
			if (i!=pNumDocument) {
				j=j+1;
				var iNumOrdre = 9001+10*j ;
				sNouDocument ="<TR><TD WIDTH=\"10%\"><A TARGET=\"_blank\" HREF=\"" + obtenirPathDoc(snomFitxer) + "\"><B><SPAN class=\"texto1\">" + aTextos[397] + ":</SPAN></B></A></TD>";
				sNouDocument +="<TD WIDTH=\"90%\">&nbsp;";
 			    sNouDocument +="<INPUT TYPE=\"HIDDEN\" NAME=\"document"+j+"\" VALUE=\""+iNumOrdre+"+Document"+j+"+Document+relacion+DocumentsAdjunts+vacio\">"
 			    sNouDocument +="<input type=\"HIDDEN\" name=\"NumDocument"+j+"\" value=\""+(iNumOrdre+1)+"+NumDocument"+j+"+NumDocument+atributo+Document+"+j+"\">"
			    sNouDocument +="<input type=\"HIDDEN\" name=\"NomDocument"+j+"\" value=\""+(iNumOrdre+2)+"+NomDocument"+j+"+NomDocument+atributo+Document+adjunto\">"
			    sNouDocument +="<INPUT TYPE=\"TEXT\" NAME=\"NomDocument"+j+"DAT\" VALUE=\"" + snomFitxer + "\" SIZE=\"30\" READONLY=\"YES\"></TD>";
				sNouDocument +="<TD WIDTH=\"22\"><img border=\"0\" src=\"images/DeleteLine.gif\"  WIDTH=\"22\" HEIGHT=\"18\" onClick=\"BorrarDoc(" + j + ");\" ALT=\"["+j+"]\">";
				sNouDocument +="<SCRIPT DEFER='true' lang='javascript'>iNumDocuments="+j+";</SCRIPT>";
				sNouDocument +="</TD></TR>";
				sCadena=sCadena + sNouDocument;
			}else{
				BorrarDocWindow(snomFitxer);
			}
		}
	}
	var obj2 = eval("top.cuerpo.document.all.item(\"Documents\")")
	//if (sCadena=='') {
	//	sCadena='<TR><TD>&nbsp;</TD></TR>';
	//}
	if (obj2) {
		if (sCadena=='') {
			obj2.innerHTML ='';
		} else {
			obj2.innerHTML = '<TABLE BORDER="0" >' + sCadena + '</TABLE>';
		}
	} else {
		alert('objecte Documents no trobat !');
	}

	iNumDocuments=j;

}

function fAmagatSN() {
	if (document.all.item('TipoDoc').value=='P') { // Quan es proposta cal veure el boto
		return "visible";
	}
	if (document.all.item('TipoDoc').value=='O' && document.all.item('modo').value=='N') {
		return "visible"; // Quan es oferta directa cal veure el boto
	}
	if (document.all.item('TipoDoc').value=='O' && document.all.item('modo').value=='R') {
		return "visible"; // Quan ramifiquem cal veure el boto
	}
	return "hidden";
}

function amagarCondicionesTO(camp) {
	var AmagatSN = fAmagatSN();

	if (top.cuerpo.document.all.item("TipoOferta").value=="1") { // Només quan siguin bombes
		top.cuerpo.document.all["boton"].style.visibility=AmagatSN;		
		top.cuerpo.document.all["condicionsServei2"].style.visibility="visible";	
	}else{
		top.cuerpo.document.all["condicionsServei2"].style.visibility="hidden";	
		top.cuerpo.document.all["boton"].style.visibility="hidden";	
	}
}

function amagarCondiciones(camp) {
	var AmagatSN = fAmagatSN();

	top.cuerpo.document.all["boton"].style.visibility="hidden";	
	if (top.cuerpo.document.all.item("TipoOferta").value=="1") { // Només quan siguin bombes
		top.cuerpo.document.all["boton"].style.visibility=AmagatSN;		
	}
	if (camp.checked) {	
		top.cuerpo.document.all["condicionsServei"].style.visibility="hidden";	
		top.cuerpo.document.all["boton"].style.visibility="hidden";	
		if (top.cuerpo.document.all.item("productoDAT").value=='') {
					top.cuerpo.document.all.item("productoDAT").value=aTextos[412];
		}
		top.cuerpo.document.all.item("TipoOferta").value=7; // otro
		top.cuerpo.document.all.item("ofertaGenerica").value='6+ofertaGenerica+ofertaGenerica+valor+Doc+SI';
	}else{
		top.cuerpo.document.all["condicionsServei"].style.visibility="visible";	
		top.cuerpo.document.all["boton"].style.visibility=AmagatSN;	
		top.cuerpo.document.all.item("ofertaGenerica").value='6+ofertaGenerica+ofertaGenerica+valor+Doc+NO';
	}
}


//Òscar 23/02/2004:
//                  Aquesta funció retorna TRUE si a la línia del control
//                  passat hi ha un subtotal
function esLiniaSubtotal(idCantidad)
{
  var inici;
  var quants;
  var quin;
  inici = 8;
  quants = idCantidad.indexOf("DAT")-8;
  quin = idCantidad.substr(inici,quants);
  return(document.all["codigo"+quin+"DAT"].value.toUpperCase()=="SUB");
}

function esLiniaSeparador(idCantidad)
{
  var inici;
  var quants;
  var quin;
  inici = 8;
  quants = idCantidad.indexOf("DAT")-8;
  quin = idCantidad.substr(inici,quants);
  return(document.all["codigo"+quin+"DAT"].value.toUpperCase()=="SEP");
}
//Fi Òscar 23/02/2004

//Òscar 23/02/2004:
//                  Aquesta funció posa al control de total indicat el subtotal
//                  dels seus anteriors fins al separador anterior o
//                  la primera línia
function calculaTotal(idTotal)
{
  var inici;
  var quants;
  var quin;
  var i;
  var suma = 0;
  var cal = true;
  var controlCodi;
  var quantitat = 0;
  inici = 5;
  
  quants = idTotal.indexOf("DAT")-5;
  quin = parseInt(idTotal.substr(inici,quants));
  i = quin-1;
  while ((i>=1) && (cal))
  {
    controlCodi = document.all["codigo"+i+"DAT"].value.toUpperCase();
    if ((controlCodi!="SEP") && (document.all["total"+i+"DAT"].value!="") && (controlCodi!="SUB"))
    {
    	quantitat = parseFloat(document.all["cantidad"+i+"DAT"].value);
        suma += parseFloat(document.all["total"+i+"DAT"].value);
    }
    else
    {
      cal = false;
    }
    i--;
  }
  if (quantitat!=0) document.all["precioUn"+quin+"DAT"].value=suma/quantitat;
  document.all["total"+quin+"DAT"].value=suma;
}
//Fi Òscar 23/02/2004
