// Documento JavaScript
// Esta función cargará las paginas
function llamarasincrono (url, id_contenedor)
{
    var pagina_requerida = false;
    if (window.XMLHttpRequest)
    {
        // Si es Mozilla, Safari etc
        pagina_requerida = new XMLHttpRequest ();
    } else if (window.ActiveXObject)
    {
        // pero si es IE
        try 
        {
            pagina_requerida = new ActiveXObject ("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            // en caso que sea una versión antigua
            try
            {
                pagina_requerida = new ActiveXObject ("Microsoft.XMLHTTP");
            }
            catch (e)
            {
            }
        }
    } 
    else
    return false;
    pagina_requerida.onreadystatechange = function ()
    {
        // función de respuesta
        cargarpagina (pagina_requerida, id_contenedor);
    }
    pagina_requerida.open ('GET', url, true); // asignamos los métodos open y send
    pagina_requerida.send (null);
}
// todo es correcto y ha llegado el momento de poner la información requerida
// en su sitio en la pagina xhtml
function cargarpagina (pagina_requerida, id_contenedor)
{
    if (pagina_requerida.readyState == 4 && (pagina_requerida.status == 200 || window.location.href.indexOf ("http") == - 1))
    document.getElementById (id_contenedor).innerHTML = pagina_requerida.responseText;
}

//Ocultar o veure continguts dels divs
function comentar(que){
	var tmp;
	
	var div = document.getElementById('div_'+que);
	var matchPos1 = div.innerHTML.search(/<!--/); //proba//-->

	if (matchPos1!=-1)		{
		tmp=div.innerHTML.replace("<!--", "");
		div.innerHTML=tmp.replace("-->", "");
	} else {
		div.innerHTML="<!--" + div.innerHTML + "-->";
	}
}

//Contar checkbox
function anyCheck() {
	var i;	
	i=0; 
	var total = 0;
	var totals = 0;
	var div = document.getElementById('label'+ i);
	while (div){
		total += 1;
		i++;
		if (Number(div.value) != 0) {
			totals += 1;
	   } 
		div = document.getElementById('label'+ i);
	}
	return totals;
}

// validarEnter( in valor ) return valor si es entero, si no ""
function validarEnter(valor){
	//intento convertir a enter.
    //si era un enter no li afecta, si no ho era lintenta convertir
	valor=parseInt(valor);
	//Comprova si es un valor numèrico
	if (isNaN(valor)) {
		//(no es numero) torno el valor cadena buida
		return "";
	}else{
		//En caso contrari (Si era un numero) torno el valor
		return valor;
	}
}
// validar ( in pes , in edat, in aliment ) return true/false si tots els camps es tan complerts.
//tambe compte que shagi seleccionat algun aliment
function validar(pes,edat) {
	if (!pes||!edat||!(document.form.homedona[0].checked||document.form.homedona[1].checked)){
		alert('-No pots deixar els camps PES i EDAT en blanc o no has selecionat HOME o DONA\n-No puedes dejar los campos PESO y EDAD en blanco o no has seleccionado HOMBRE o MUJER\n-You cannot leave the fields the WEIGH and the AGE emptinesses or you don\'t selected MAN or WOMAN');
		
		return false;
	} else {
		if (anyCheck()==0) {
			alert('-No te sentit no seleccionar cap aliment\n-No tiene sentido no seleccionar ningun alimento\n-It does not have felt not to select any food');
			return false;
		} else {
			if ((validarEnter(pes)=="")||(pes<1)||(pes>149)||(validarEnter(edat)=="")||(edat<1)||(edat>149)){
				alert('-PES i EDAT han de ser enters mes grans que 0 i mes petits que 150\n-PESO y EDAD tienen que ser enteros mas grandes que 0 y mas pequeños que 150\n-The WEIGH and the AGE they have to be integers biggers than 0 and smallers than 150');
				document.form.pes.value="";
				document.form.edat.value="";
				return false;
			}else {
				return true;          
			}
		}
	}
}

function canviar_radio(grupo){
	document.form.grupo[2].checked=false;
	return true;
}

//abrir popUP
function popupPage(w, h, page, s) {
	var hz=window.screen.height
	var wz=window.screen.width
	var horizontal=(wz/2)-(w/2);
	var vertical=(hz/2)-(h/2);
	var scrol;
	if (s=0){
		scrol='no';
	} else {
		scrol='yes';
	}		
	var windowprops = "location=no,scrollbars="+scrol+",menubars=no,toolbars=no,resizable=yes" + ",left=" + horizontal + ",top=" + vertical + ",width=" + w + ",height=" + h;
	popup = window.open(page,"Info",windowprops);
}

function browsertest(){
	document.write('<font class="Estilo10">El teu navegador soporta Javascript</font>')
}

/********************************************************************************
Copyright (C) 1999 Thomas Brattli
This script is made by and copyrighted to Thomas Brattli at www.bratta.com
Visit for more great scripts. This may be used freely as long as this msg is intact!
I will also appriciate any links you could give me.
********************************************************************************/
//Default browsercheck, added to all scripts!
function checkBrowser(){
	this.ver=navigator.appVersion
	this.dom=document.getElementById?1:0
	this.ie5=(this.ver.indexOf("MSIE 5")>-1 && this.dom)?1:0;
	this.ie4=(document.all && !this.dom)?1:0;
	this.ns5=(this.dom && parseInt(this.ver) >= 5) ?1:0;
	this.ns4=(document.layers && !this.dom)?1:0;
	this.bw=(this.ie5 || this.ie4 || this.ns4 || this.ns5)
	return this
}
bw=new checkBrowser()

//With nested layers for netscape, this function hides the layer if it's visible and visa versa
//function showHide(div,nest){
function showHide(div){
	obj=bw.dom?document.getElementById(div).style:bw.ie4?document.all[div].style:bw.ns4?document[div]:0; 
	if(obj.visibility=='visible' || obj.visibility=='show') obj.visibility='hidden'
	else obj.visibility='visible'
}

//Shows the div
function show(div,nest){
	obj=bw.dom?document.getElementById(div).style:bw.ie4?document.all[div].style:bw.ns4?nest?document[nest].document[div]:document[div]:0; 
	obj.visibility='visible'
}

//Hides the div
function hide(div,nest){
	obj=bw.dom?document.getElementById(div).style:bw.ie4?document.all[div].style:bw.ns4?nest?document[nest].document[div]:document[div]:0; 
	obj.visibility='hidden'
}

//Lo siguiente muestra un link “Ver más” que abre un div oculto:
// definiciones basicas

//conmutar entre dos divs i su titulo correspondiente q esta en otro div.
//Uno oculto i el otro no i viceversa
function mostrar(blo) {
  document.getElementById('div_'+blo).style.display="block";//VISIBLE
  document.getElementById(blo+'_off').style.display="block";//VISIBLE
  document.getElementById(blo+'_on').style.display="none";//OCULTO
}


function ocultar(blo) {
  document.getElementById('div_'+blo).style.display="none";//OCULTO
  document.getElementById(blo+'_off').style.display="none";//OCULTO
  document.getElementById(blo+'_on').style.display="block";//VISIBLE
}

//oculta un div i muestra otro
function sustituir(img,per) {
	document.getElementById(img).style.display="none";
	document.getElementById(per).style.display="block";
}


function sustituir_menu(activar,num) {
	var tmp;
	for (var i = 0; i < num; i++) {
		var elegido = 'menu_'+i;
		if (elegido == activar) {
			sustituir(elegido+'_disabled',elegido+'_enabled');
			tmp=i;
		} else {
			sustituir(elegido+'_enabled',elegido+'_disabled');
			document.getElementById('cos_'+i).style.display="none";
			document.getElementById('titol_'+i).style.display="none";
		}
	}
	document.getElementById('cos_'+tmp).style.display="block";
	document.getElementById('titol_'+tmp).style.display="block";
}


function sustituir_menu2(activar,tipus,num) {
	var tmp;
	for (var i = 0; i < num; i++) {
		var elegido = 'menu2'+tipus+'_'+i;
		if (elegido == activar) {
			sustituir(elegido+'_disabled',elegido+'_enabled');
			tmp=i;
		} else {
			sustituir(elegido+'_enabled',elegido+'_disabled');
			document.getElementById('subcos'+tipus+'_'+i).style.display="none";
		}
	}
	document.getElementById('subcos'+tipus+'_'+tmp).style.display="block";
}

//controla los checkbox i los resets de cada alimento
function habilitar(text) {
	var texto='text_'+text;
	if (document.form[texto].value==0){
		document.form[text].checked=false;
		alert('-Aquesta casella es nomes per desactivar un aliment\n-Esta casilla es solo para desactivar el alimento\n-This checkbox is only for deselect a food');
	} else {
		if (document.form[text].checked){
			document.form[texto].blur();
			document.form[texto].value=0;
		} else {
			document.form[texto].value=0;
			document.form['contador_'+text+'_petit'].value=0;
			document.form['contador_'+text+'_mig'].value=0;
			document.form['contador_'+text+'_gran'].value=0;
			
		}
		sustituir('res_'+text+'_petit','sum_'+text+'_petit');
		sustituir('res_'+text+'_mig','sum_'+text+'_mig');
		sustituir('res_'+text+'_gran','sum_'+text+'_gran');
	}
}

//incrementa en gramos i bloquea la racion
function sumar(val,text) {
	var texto='text_'+text;
	var valor=document.form[texto].value;
	document.form[text].checked=true;
	document.form[texto].value=Number(valor) + Number(val);
}

//decrementa los gramos i desbloqua la racion
function restar(val,text) {
	var texto='text_'+text;
	var valor=document.form[texto].value;
	document.form[texto].value=Number(valor) - Number(val);
	if (Number(document.form[texto].value)==0) {
		document.form[text].checked=false;
		document.form[texto].disabled=true;
	}
}


function operar_contador (campo,tamany,p,m,g) {
	var contador='contador_'+campo+'_'+tamany;
	var texto='text_'+campo;
	var contador_petit='contador_'+campo+'_petit';
	var contador_mig='contador_'+campo+'_mig';	
	var contador_gran='contador_'+campo+'_gran';	
	var texto='text_'+campo;
	if (Number(document.form[contador_petit].value)!=0 || Number(document.form[contador_mig].value)!=0 || Number(document.form[contador_gran].value)!=0) {
		document.form[campo].checked=true;
		document.form[texto].value=Number(document.form[contador_petit].value)*p+Number(document.form[contador_mig].value)*m+Number(document.form[contador_gran].value)*g;
	} else {
		document.form[campo].checked=false;
		document.form[texto].value=0;
		document.form[contador_petit].value=0;
		document.form[contador_mig].value=0;
		document.form[contador_gran].value=0;
	}
	if (Number(document.form[contador].value)==14) {
	} else { 
	}
}

//AUXILIAR: suma i sustituye
function operar_suma(campo,tamany,p,m,g) {
	var contador='contador_'+campo+'_'+tamany;
	if (Number(document.form[contador].value)<14) {
		document.form[contador].value=Number(document.form[contador].value)+1;
		operar_contador (campo,tamany,p,m,g);
		if (Number(document.form[contador].value)==14) {
		}
	} else {
	}
}

//AUXILIAR: resta i sustituye
function operar_resta(campo,tamany,val) {
	restar(val,campo); 
}

function cerrar(){
	window.close()
} 