// JavaScript Document

function Abrir_Ventana(theURL,winName,features) { 
  window.open(theURL,winName,features);
}


/***********************************************
* Contractible Headers script- © Dynamic Drive (www.dynamicdrive.com)
* This notice must stay intact for legal use. Last updated Oct 21st, 2003.
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/

var enablepersist="off" //Enable saving state of content structure using session cookies? (on/off)
var collapseprevious="yes" //Collapse previously open content when opening present? (yes/no)

if (document.getElementById){
document.write('<style type="text/css">')
document.write('.switchcontent{display:none;}')
document.write('</style>')
}

function getElementbyClass(classname){
ccollect=new Array()
var inc=0
var alltags=document.all? document.all : document.getElementsByTagName("*")
for (i=0; i<alltags.length; i++){
if (alltags[i].className==classname)
ccollect[inc++]=alltags[i]
}
}

function contractcontent(omit){
var inc=0
while (ccollect[inc]){
if (ccollect[inc].id!=omit)
ccollect[inc].style.display="none"
inc++
}
}

function expandcontent(cid){
if (typeof ccollect!="undefined"){
if (collapseprevious=="yes")
contractcontent(cid)
document.getElementById(cid).style.display=(document.getElementById(cid).style.display!="block")? "block" : "none"
}
}

function revivecontent(){
contractcontent("omitnothing")
selectedItem=getselectedItem()
selectedComponents=selectedItem.split("|")
for (i=0; i<selectedComponents.length-1; i++)
document.getElementById(selectedComponents[i]).style.display="block"
}

function get_cookie(Name) { 
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) { 
offset += search.length
end = document.cookie.indexOf(";", offset);
if (end == -1) end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}

function getselectedItem(){
if (get_cookie(window.location.pathname) != ""){
selectedItem=get_cookie(window.location.pathname)
return selectedItem
}
else
return ""
}

function saveswitchstate(){
var inc=0, selectedItem=""
while (ccollect[inc]){
if (ccollect[inc].style.display=="block")
selectedItem+=ccollect[inc].id+"|"
inc++
}

document.cookie=window.location.pathname+"="+selectedItem
}

function do_onload(){
getElementbyClass("switchcontent")
if (enablepersist=="on" && typeof ccollect!="undefined")
revivecontent()
}


if (window.addEventListener)
window.addEventListener("load", do_onload, false)
else if (window.attachEvent)
window.attachEvent("onload", do_onload)
else if (document.getElementById)
window.onload=do_onload

if (enablepersist=="on" && document.getElementById)
window.onunload=saveswitchstate

/***********************************************
* Contractible Headers script- © Dynamic Drive (www.dynamicdrive.com)
* This notice must stay intact for legal use. Last updated Oct 21st, 2003.
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/

/*Funciones de calculadoras*/
var tnumero = /^\d+$/
var resultados = new Array();

function Common_IsVacio(valor)
{
	return valor==null || !valor || valor=="";
}

function Common_GetObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=Common_GetObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function checkDigit(e)
{
	var key = window.event ? e.keyCode : e.which;
	if (key)
	{
		var keychar = String.fromCharCode(key);
		return tnumero.test(keychar);
	}
	return false;
}

function isNumber(valor)
{
	return !Common_IsVacio(valor) && tnumero.test(valor);
}

function GetNumberValue(controlId, message, showMessage)
{
	var obj = Common_GetObj(controlId);
	if ((!obj || !isNumber(obj.value)) && showMessage)
	{
		alert(message);
		obj.select(); obj.focus();
		return null;
	}
	return obj.value * 1;
}

function formatear(valor, numeroDecimales)
{
	aux = valor + "";
	posPunto = aux.indexOf(".");
	if (posPunto && posPunto>=0)
	{
		fin =  aux.length;
		if ((posPunto+numeroDecimales)<fin)
		{
			fin = posPunto + numeroDecimales + 1;
		}
		valor = aux.substring(0,fin);										
	}
	return valor;
}

function GetRango(valor, listaValores)
{
	valoracion = null;
	
	//Ponemos un numero alto para tratar el caso de que sea mayor que el ultimo elemento
	listaValores[listaValores.length] = 2000;
	
	for (i=0;i<=listaValores.length && valoracion==null;i++)
	{
		var estaRango = valor < listaValores[i];
		if (i>0 && i<listaValores.length-1 && estaRango)
		{
			estaRango = valor >= listaValores[i-1];
		}
		else if (i==listaValores.length-1)
		{
			estaRango = valor >= listaValores[i-1];
		}
		if (estaRango)
		{
			valoracion = i + 1;
		}
	}
	return valoracion;
}

function DeseleccionarResultado()
{
	obj = Common_GetObj("trResultado1");
	for (i=2;obj!=null;i++)
	{
		obj.className = "";
		obj = Common_GetObj("trResultado" + i);
	}
}


function SeleccionarResultado(valor)
{
	obj = Common_GetObj("trResultado"+valor);
	if (obj)
	{
	 obj.className = "trSeleccion";	
	}
}

function SetResultado(valor, listaValores, divValoracionId ,divResultadoId)
{
	valoracion = GetRango(valor, listaValores);
	Common_GetObj(divValoracionId).innerHTML = Common_GetObj(divResultadoId+valoracion).innerHTML;
	SeleccionarResultado(valoracion);
}

//Funcion que devuelve el la suma de los value de los radios que se llaman preguntaName
function GetTotalRadios(preguntaName)
{
	var suma = 0;
	for(i=1;(obj = Common_GetObj(preguntaName+i))!=null;i++)
	{
		valor = -1;
		if (obj.length)
		{
			for (v = 0; v<obj.length && valor==-1; v++)
			{
				if (obj[v].checked==true)
				{
					valor = obj[v].value;
				}
			}
		}
		else if (obj) // es mozilla
		{
			var inputs = obj.getElementsByTagName ("input");
			if (inputs && inputs.length>0) 
			{
				for (v = 0; v < inputs.length && valor==-1; v++) 
				{
					if (inputs[v].checked)
					{
						valor = inputs[v].value;
					}
				}
			}
		}
		if (valor==-1)
		{
			alert("Debe responder a todas las preguntas");
			return -1;
		}
		suma += valor * 1;
	}	
	return suma;
}

function IndiceMasaCorporal(alturaId, pesoId, resultadoId, divValoracionId, divResultadoId)
{
	DeseleccionarResultado();
	Common_GetObj(resultadoId).innerHTML = "---";
	Common_GetObj(divValoracionId).innerHTML = "---";
	h = GetNumberValue(alturaId, "El valor de la altura no es válido", true);
	w = GetNumberValue(pesoId, "El valor del peso no es válido",h!=null);

	if (h==null || w==null)
	{
		return;
	}
	h = h / 100;
	imc = w / (h * h);
	
	Common_GetObj(resultadoId).innerHTML = formatear(imc, 1);
	SetResultado(imc, new Array ( 18.5, 25 , 30, 35, 40 ), divValoracionId ,divResultadoId);
}

function Fagestrom(preguntaName, divValoracionId, resultadoId, divPuntosId)
{
	DeseleccionarResultado();
	Common_GetObj(divPuntosId).innerHTML = "";
	Common_GetObj(divValoracionId).innerHTML = "---";
	
	indice = GetTotalRadios(preguntaName);
	if (indice>-1)
	{
		Common_GetObj(divPuntosId).innerHTML = " (" + indice + " puntos" + ")";
		SetResultado(indice, new Array ( 2, 4, 6, 8 ), divValoracionId, resultadoId);
	}
}

function Audit(preguntaName, resultadoId)
{
	Common_GetObj(resultadoId).innerHTML = "---";
	indice = GetTotalRadios(preguntaName);
	if (indice>-1)
	{
		Common_GetObj(resultadoId).innerHTML = indice + " puntos";
	}
}

function Colesterol(aId, bId, cId, resultadoLDLId, resultadoVLDLId)
{
	Common_GetObj(resultadoLDLId).innerHTML = "---";
	Common_GetObj(resultadoVLDLId).innerHTML = "---";
	a = GetNumberValue(aId, "El valor del colesterol total no es válido", true);
	b = GetNumberValue(bId, "El valor del colesterol HDL no es válido",a!=null);
	c = GetNumberValue(cId, "El valor de los trigliceridos no es válido",a!=null && b!=null);
	if (a==null || b==null || c==null)
	{
		return;
	}
	Common_GetObj(resultadoLDLId).innerHTML = Math.round(a -((c/5)+ b));
	Common_GetObj(resultadoVLDLId).innerHTML = Math.round(c / 5);
}

function TensionArterial(sistolica, diastolica, divValoracionId, divResultadoId)
{
	DeseleccionarResultado();
	Common_GetObj(divResultadoId).innerHTML = "---";		
	s = GetNumberValue(sistolica, "El valor de la presión sistólica no es válido", true);
	d = GetNumberValue(diastolica, "El valor la presión diastólica no es válido",s!=null);
	if (s==null || d==null)
	{
		return;
	}
	rangoS = GetRango(s, new Array(120, 130, 140, 160, 180));
	rangoD = GetRango(d, new Array(80, 85, 90, 100, 110));
	max = rangoD>rangoS?rangoD:rangoS;
	Common_GetObj(divResultadoId).innerHTML = Common_GetObj(divValoracionId+max).innerHTML;
	SeleccionarResultado(max);	
}

function RiesgoCardioVascular(object, fila, hombre, mujer)
{
	ActivateTD(object, fila, new Array(hombre, mujer));
}

function ActivateTD(object, fila, valor)
{
	if (resultados[fila]!=null)
	{
		resultados[fila][0].className = "tdDisabled";
	}
	object.className = "tdEnabled";
	if (resultados[0] || fila==0)
	{
		resultados[fila] = new Array(object, valor);
		var total = 0;
		for (i=1;i<resultados.length;i++)
		{
			if (resultados[i])
			{
				total += resultados[i][1][resultados[0][1]==true?0:1];
				//alert("sumando " + resultados[i][1][resultados[0][1]==true?0:1]);
			}
		}
		idx = total;
		if (total>17) { idx = 19; }
		else if (total <= -2) { idx = 0; }
		else if (total == -1) { idx = 1; }
		else { idx += 2; }

		isHombre = resultados[0][1];

		totalPercentage = isHombre?60:30;
		Common_GetObj("divMaximo").innerHTML = totalPercentage;
		
		arrayHombre = new Array (2,2,3,3,4,5,7,8,10,13,16,20,25,31,37,45,53,53,53,57);
		arrayMujer = new Array  (1,2,2,2,3,3,4,4,5,6,7,8,10,11,13,15,18,20,24,27);
		resultado = isHombre?arrayHombre[idx]:arrayMujer[idx];
		
		pct = (100 / totalPercentage) * resultado + "%";
		Common_GetObj("divResultBar").innerHTML = (idx==arrayHombre.length-1?">=":"") + resultado + "%";
		Common_GetObj("divResultBar").style.width= pct;
	}
	else
	{
		alert("Para ver el resultado, debe seleccionar primero el sexo");
	}
}

function SetSexo(object, value)
{
	ActivateTD(object, 0, value);
	object.className = "tdEnabled";	
}

function ClassOver(object)
{
	object.className = "tdOver";
}

function ClassOut(object)
{
	for (i=0;i<resultados.length;i++)
	{
		if (resultados[i]!=null && object==resultados[i][0])
		{
			object.className = "tdEnabled";
			return;
		}
	}
	object.className = "tdDisabled";
}

function CambiaImagenHome()
{
	// Para añadir más imágenes solo hay que introducir más elementos en el array imagen con
	// el número de índice correlativo.
	var imagen = new Array ( "homeIMG01.jpg", "homeIMG02.jpg", "homeIMG03.jpg", 
			"homeIMG04.jpg", "homeIMG05.jpg", "homeIMG06.jpg", "homeIMG07.jpg",
			"homeIMG08.jpg","homeIMG09.jpg" );
			
	num = Math.random() * imagen.length;
	Common_GetObj('imgHomeIzquierda').style.backgroundImage = 'url(images/'+ imagen[Math.floor(num)] + ')';
}

function Nothing()
{
}
