<!--
// init()
// -----------------------------------------------------------------------------------------------------------------------------
function init() {
	var n;
	for ( n = 1; n < 6; n++ ) {
		calculoImporte( n );
	}
	recalcularTotal();
}

// calculoImporte( campo, valor, pos )
// -----------------------------------------------------------------------------------------------------------------------------
function calculoImporte( pos ) {
	var cantidad = 1;
	var IVA = 16;
	var total = 0;
	var objPre = document.getElementById("p"+pos+"_pre");
	var objUni = document.getElementById("p"+pos+"_uds");
	var objDes = document.getElementById("p"+pos+"_des");
	var objTotal = document.getElementById("p"+pos+"_tot");
	var cantidad = clearCharsNoNumeric( objUni.value );
	objUni.value = clearCharsNoNumeric( cantidad );

	var precio = objPre.value;
	if ( precio != "" ) {
		precio = comaAPunto( clearCharsNoNumericComa( objPre.value ) ); // Limpiamos caracteres que no sean numericos, o la coma
		objPre.value = puntoAComa( precio ); // Actualizamos el campo del precio
	} else {
		precio = 0;
		objPre.value = "";
	}
	
	//precio = comaAPunto( precio ); // Sustituimos la coma por el punto
	var descuento = objDes.value;
	objDes.value = clearCharsNoNumeric( descuento );
	descuento = clearCharsNoNumeric( descuento );
	
	objTotal.innerHTML = 0;
	
	if ( isNaN( cantidad ) ) { cantidad = 1; }
	if ( isNaN( precio ) ) { precio = 0; }
	if ( descuento != "" ) {
		if ( isNaN( descuento ) ) { descuento = 0; objDes.value = ""; } 
		else { descuento =  parseInt( descuento); objDes.value = descuento; }
	}
	//if ( descuento > 100 ) { descuento = 0; }
	
	total = precio * cantidad - ( precio * cantidad * descuento / 100 );
	objTotal.innerHTML = invertirComasYPuntos( FormatNumber( total,2, false, false, true) ); 
	
	recalcularTotal();
}

// recalcularTotal
// ----------------------------------------------------------------------------------------------------------------------------
function recalcularTotal() {
	var arrTotBase = new Array( 0, 0, 0, 0, 0 );
	var totalBase = totalConIva = totalIRPF = totalIva = 0;
	var totalBaseConFormato;
	var porIRPF = 0;
	var iva = 16;
	for ( n = 0; n < arrTotBase.length; n++ ) {
		objTotal = makeJavaScriptNumberFromFormat( document.getElementById("p"+(n+1)+"_tot").innerHTML );
		if ( ! isNaN( objTotal ) ) { 
			arrTotBase[n] = parseFloat( objTotal );  
			
		}
	}
	for ( n = 0; n < arrTotBase.length; n++ ) {
		totalBase += arrTotBase[n];
	}
	
	var objTotalBase = document.getElementById("totalbaseimponible");
	// IVA
	totalIva = totalBase * iva / 100;
	totalBaseConFormato = invertirComasYPuntos( FormatNumber( totalBase , 2, false, false, true ) );
	
	objTotalBase.innerHTML = invertirComasYPuntos( FormatNumber( totalBase , 2, false, false, true ) );
	document.getElementById("copiaTotalBaseImponible").innerHTML = totalBaseConFormato;
	document.getElementById("copiaTotalBaseImponibleIRPF").innerHTML = totalBaseConFormato;
	document.getElementById("totalIva1").innerHTML = invertirComasYPuntos( FormatNumber( totalIva, 2, false, false, true ) );
	
	// IRPF
	porIRPF = document.getElementById("val_irpf").value;
	if ( porIRPF > 0 ) {
		totalIRPF = totalBase * porIRPF / 100;
		//alert( totalIRPF );
		document.getElementById("totalIrpf1").innerHTML = "-" + invertirComasYPuntos( FormatNumber( totalIRPF, 2, false, false, true ) );
	}
	
	document.getElementById("totalFactura").innerHTML = invertirComasYPuntos( FormatNumber( totalBase + totalIva - totalIRPF, 2, false, false, true ) );
}

// limpiarTotales()
// ----------------------------------------------------------------------------------------------------------------------------
function limpiarTotales() {
	for ( n = 0; n < 5; n++ ) {
		document.getElementById("p"+(n+1)+"_tot").innerHTML = 0;
	}

	document.getElementById("copiaTotalBaseImponible").innerHTML = "";
	document.getElementById("copiaTotalBaseImponibleIRPF").innerHTML = "";
	document.getElementById("totalIva1").innerHTML = "";
	document.getElementById("totalIrpf1").innerHTML = "";
	document.getElementById("totalFactura").innerHTML = "";
}


function FormatNumber( num,decimalNum,bolLeadingZero,bolParens,bolCommas )
/**********************************************************************
	IN:
		NUM - the number to format
		decimalNum - the number of decimal places to format the number to
		bolLeadingZero - true / false - display a leading zero for
										numbers between -1 and 1
		bolParens - true / false - use parenthesis around negative numbers
		bolCommas - put commas as number separators.
 
	RETVAL:
		The formatted number!
 **********************************************************************/
{ 
  if (isNaN(parseInt(num))) return "NaN";

	var tmpNum = num;
	var iSign = num < 0 ? -1 : 1;		// Get sign of number
	
	// Adjust number so only the specified number of numbers after
	// the decimal point are shown.
	// Ajustamos el numero 
	tmpNum *= Math.pow(10,decimalNum);
	tmpNum = Math.round(Math.abs(tmpNum))
	tmpNum /= Math.pow(10,decimalNum);
	tmpNum *= iSign;					// Readjust for sign
	
	
	// Create a string object to do our formatting on
	var tmpNumStr = new String(tmpNum);

	// See if we need to strip out the leading zero or not.
	if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
		if (num > 0)
			tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
		else
			tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);
		
	// See if we need to put in the commas
	if (bolCommas && (num >= 1000 || num <= -1000)) {
		var iStart = tmpNumStr.indexOf(".");
		if (iStart < 0)
			iStart = tmpNumStr.length;

		iStart -= 3;
		while (iStart >= 1) {
			tmpNumStr = tmpNumStr.substring(0,iStart) + "," + tmpNumStr.substring(iStart,tmpNumStr.length)
			iStart -= 3;
		}		
	}

	// Miramos si es necesario usar parentesis (numeros negativos)
	if (bolParens && num < 0)
		tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";

	//tmpNumStr = replaceCommasForDots( tmpNumStr );

	return tmpNumStr;		// Devolvemos la cadena formateada Return our formatted string!
}

// NOTA: formatNumber con MINUSCULA
// ---------------------------------------------------------------------------------------------------
function formatNumber( num, prefix ){
   prefix = prefix || '';
   num += '';
   var splitStr = num.split(',');
   var splitLeft = splitStr[0];
   var splitRight = splitStr.length > 1 ? ',' + splitStr[1] : '';
   var regx = /(\d+)(\d{3})/;
   while ( regx.test( splitLeft ) ) {
      splitLeft = splitLeft.replace(regx, '$1' + ',' + '$2');
   }
   return prefix + splitLeft + splitRight;
}

// unformatNumber(num)
// ----------------------------------------------------------------------------------------------------
function unformatNumber( num ) {
  return num.replace(/([^0-9\.\-])/g,'')*1;
}

// replaceCommasForDots( tmpNumStr )
// ----------------------------------------------------------------------------------------------------
function replaceCommasForDots( valor ) {
	var str = new String( valor );
	str = str.replace( ",","#" );
	str = str.replace( ".","," );
	str = str.replace( "#","." );
	//alert( str );
	return str;
}

// clearCharsNoNumeric( valor )
// ------------------------------------------------------------------------------------------------------------------------------------
function clearCharsNoNumericComa( valor ) {
	var str = new String( valor );
	var res = "";
	var bComa = false;
	for ( n = 0; n < str.length; n++ ) {
		if ( ( str.charCodeAt( n ) > 47 && str.charCodeAt( n ) < 58 ) || str.charCodeAt( n ) == 44 ) {
			res += str.charAt( n );
		}
	}
	str = new String( res );
	res = "";
	for ( n = 0; n < str.length; n++ ) {
		if ( bComa == false && str.charCodeAt( n ) == 44 ) {
			bComa = true; // Primera coma
			res += str.charAt( n );
		}
		else  // Numeros
		{
			if ( str.charCodeAt( n ) != 44 ) { res += str.charAt( n ); }
		}
	}
	
	return res;
}

// clearCharsNoNumeric( valor )
// ------------------------------------------------------------------------------------------------------------------------------------
function clearCharsNoNumeric( valor ) {
	var str = new String( valor );
	var res = "";
	for ( n = 0; n < str.length; n++ ) {
		if ( str.charCodeAt( n ) > 47 && str.charCodeAt( n ) < 58 ) {
			res += str.charAt( n );
		}
	}
	return res;
}


// comaAPunto( valor )
// ---------------------------------------------------------------------------------------------------------------------
function comaAPunto( valor )
{
	var por = new String( valor ); // Obtenemos el valor del porcentaje como una cadena
	por = por.replace( ",","." ); // Reemplazamos la coma por el punto, eso permite al javascript interpretar el valor como numero
	if ( isNaN (  por  ) ) { 
		return -1;
	} else {
		return por;
	}
}

// puntoAComa( valor )
// ---------------------------------------------------------------------------------------------------------------------
function puntoAComa( valor )
{
	var por = new String( valor ); // Obtenemos el valor del porcentaje como una cadena
	por = por.replace( ".","," ); // Reemplazamos la coma por el punto, eso permite al javascript interpretar el valor como numero
	return por;
}

// invertirComasYPuntos( valor )
// ---------------------------------------------------------------------------------------------------------------------
function invertirComasYPuntos( valor ) {
	var por = new String( valor ); // Obtenemos el valor del porcentaje como una cadena
	por = por.replace( ".","#" ); // Reemplazamos la coma por el punto, eso permite al javascript interpretar el valor como numero
	por = por.replace( ",","." );
	por = por.replace( "#","," );
	return por;
}

// makeJavaScriptNumberFromFormat( valor ) 
// ---------------------------------------------------------------------------------------------------------------------
function makeJavaScriptNumberFromFormat( valor ) 
{
	var str = new String( valor );
	str = str.replace(".","" );
	str = str.replace(",","." );
	return str;
}
// -->