/**	pc.pFunctionsDHTML */

/*	Alexander B. adaptat del codi del Gabi1.
	@description Fa visible o invisible un element HTML.
	@param element --- un element HTML, per exemple de document.getElementById("...").
	@param bVisible --- Ha de ser visible?
*/
function setVisible(element, bVisible) {
	if (bVisible) {
		if (element.tagName.toLowerCase() == 'tr') {
			//un TR visible hauria de tenir "table-row" ...
			try {
				element.style.display = "table-row";
			} catch (e) {
				//... pero IE no accepta "table-row" i funciona amb "inline".
				element.style.display = "inline";
			}
		} else if (element.tagName.toLowerCase() == 'table') {
			try {
				element.style.display = "table";
			} catch (e) {
				//... pero IE no accepta "table" i funciona amb "block".
				element.style.display = "block";
			}
		} else {
			element.style.display = "inline";
		}
	} else {
		element.style.display = "none";
	}
}//setVisible


/*	@description Comprova la visibilitat d'un cert element HTML.
	@param element --- un element HTML, per exemple de document.getElementById("...").
	@returns boolean --- true si l'element és visible, false altrament
*/
function isVisible(element) {
	return element.style.display != "none";
}

/*
	Gabriel Prat Blanes gabi @ infojobs . net 26/05/2003
	@description Donat un ID d'objecte d'HTML li canvia la propietat style.display de none a block o a l'inversa, 
	com a parametre opcional pot rebre un valor per style.disply forzat
	@param sId Com a parametre d'entrada rep un String que es l'ID d'un element de la pagina.
	@param [sDisplay] es pot enviar un segon parametre per forzar el valor d'style.display.
*/
function MostraAmaga(sId)
{
	if (document.getElementById(sId))
	{
		var sDisplay="";
		if (arguments.length > 1)
			sDisplay = arguments[1];

		if (sDisplay.length > 0)
			document.getElementById(sId).style.display=sDisplay;
		else
		{
			if(document.getElementById(sId).tagName.toLowerCase() == 'tr')
				sDisplay = "table-row";
			else
				sDisplay = "inline";
			if (document.getElementById(sId).style.display.toLowerCase() != "none") 
				document.getElementById(sId).style.display = "none";
			else
				try
				{
					document.getElementById(sId).style.display = sDisplay;
				}
				catch(e)
				{
					document.getElementById(sId).style.display = "inline";
				}
		}		
	}
	else
	{
		alert("Error, no hay ningun objeto con ID=\"" + sId + "\"");
	}
}
/*
	Gabriel Prat Blanes gabi @ infojobs . net 29/05/2003
	@description la funcio rep un objecte i un id de l'objecte pare on s'incloura l'objecte com a ultim fill.
	@param Objecte Objecte HTML que s'ensofronyara com a fill de l'objecte amb l'id proporcionat
	@param sIdPare id de l'objecte HTML que contindra l'objecte proporcionat.
*/
function AfegeixFill(Objecte, sIdPare)
{
	var oPare=document.getElementById(sIdPare);
	/* Comprovem que el pare existeix, en principi nomes a nivell de debug */
	if (!oPare)
	{
		alert("Error, el padre no se ha encontrado.");
		return(false);
	}
	else
		oPare.appendChild(Objecte);
	return(true);
}
/*
	Gabriel Prat Blanes gabi @ infojobs . net 29/05/2003
	@description Elimina la gerarquia especificada per la sequencia d'IDs rebuda. 
	Sempre que el nivell superior al eliminar el fill tingui un numero de fills = 0
	@param Rep N IDs d'elements de l'HTML en ordre gerarquic, de nivell mes alt a nivell mes petit.
*/
function EsborrarElement(sID)
{
	var Objecte=document.getElementById(sId);
	if (!Objecte)
	{
		alert("El objecto con ID " + sID + " no se ha encontrado.");
		return(false);
	}
	else
	{
		var oPare=Objecte.parentNode();
		oPare.removeChild(Objecte);
	}
	return(true);
}

/*
 * aunque por el nombre no queda claro, abre una nueva ventana pop-up
 * laURL        - url de la página a abrir
 * elNombre     - nombre interno de la ventana (no el titulo!)
 * ancho        - ancho en pixeles
 * alto         - alto en pixeles
 * tieneScrolls - "yes" o "no" (default: "no")
 * esResizable  - "yes o "no"  (default: "no")
 */
function entrar(laURL,elNombre,ancho,alto,tieneScrolls,esResizable) {
	if(typeof tieneScrolls == 'undefined')
		tieneScrolls="no";

	if(typeof esResizable == 'undefined')
		esResizable="no";

	window.open(laURL,
							elNombre,
							"width="+ancho+",height="+alto+
							",scrollbars="+tieneScrolls+",resizable="+esResizable+",alwaysRaised=yes,dependent=no,location=no,screenX=0,screenY=0");
}

/********************************/
// FUNCIONES DE PAGO 			//
/********************************/

// Valida si es 'valido' el contenido de la tecla pulsada
function checkFloatVal(value, e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);

    // control keys
    if ((key==null) || (key==0) || (key==8) || (key==9) || (key==27) )
        return true;
    // numbers
    else if ((('0123456789').indexOf(keychar) > -1))
        return true;
    // just one floating point
    else if ((('.').indexOf(keychar) > -1) && ((value).indexOf('.') == -1))
        return true;
    // decimal point jump
    else
        return false;
}

// Valida si es 'valido' el contenido de la tecla pulsada
function checkIntVal(e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);

    // control keys
    if ((key==null) || (key==0) || (key==8) || (key==9) || (key==27) )
        return true;
    // numbers
    else if ((("0123456789").indexOf(keychar) > -1))
        return true;    
    // decimal point jump
    else
        return false;
}

// Formatea el numero pasado a decimal con 2 digitos
function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) num = "0";
	var sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	var cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10) cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+
	num.substring(num.length-(4*i+3));
			
	return (((sign)?'':'-') + num + '.' + cents);
}

// Calcula el total del precio de una compra. USADO EN PAGO: pCompra.cfm
function calcularTotal(nombresDivs, iPorcentaje, divTotal, divImpuesto, divFinal){
	var diferentDivs=nombresDivs.split(",");
	// importe Total sin Impuestos
	var total = 0;
	// cantidad perteneciente a impuestos, un x por ciento del total
	var impuestos = 0;
	// importe total sumado al total de impuestos
	var total_final = 0;
    
    for (var i = 0; i<diferentDivs.length; i++) {
        var divElement = document.getElementById(diferentDivs[i]);
		if (divElement.innerHTML.length == 0)
			divElement.innerHTML = 0;
		total = parseFloat(total) + parseFloat(divElement.innerHTML);
	}
    
	// ponemos en el div del importe total la cantidad
	document.getElementById(divTotal).innerHTML = formatCurrency(total);
	document.getElementById('i' + divTotal).value = formatCurrency(total);
	// calculamos el valor de los impuestos
	impuestos = total * (iPorcentaje / 100);
	// ponemos en el div del impuesto total la cantidad
	document.getElementById(divImpuesto).innerHTML = formatCurrency(impuestos);
	document.getElementById('i' + divImpuesto).value = formatCurrency(impuestos);
	// calculamos el valor del total final
	total_final = total + impuestos;
	// ponemos en el div del importe final total la cantidad
	document.getElementById(divFinal).innerHTML = formatCurrency(total_final);
	document.getElementById('i' + divFinal).value = formatCurrency(total_final);
}

// Calcula el total del precio de un producto. USADO EN PAGO: pNuevaCompra.cfm
function calcular(idDiv, precio, cantidad) {
    var total = precio * cantidad;
    document.getElementById(idDiv).innerHTML = formatCurrency(total);
    var element = document.getElementById('I' + idDiv);
    if (element != null)
	    element.value = formatCurrency(total);
}
