// JavaScript Document

/*intercambios*/

function valid_reparto() {
		//calcular el total de la fila
		total = 0;
		i=1;
		while(i<=15) {
			valor = document.getElementById('tdc_'+i).innerHTML;
			str = new String (valor);
			str = str.replace('</SPAN>',''); //ie
			str = str.replace('</span>',''); //ff
			str = str.replace('<SPAN id=c_'+i+'>',''); //ie
			str = str.replace('<span id="c_'+i+'">',''); //ff
			str = str.split('/');
			if (number(str[0])<number(str[1])) {
				alert ('No ha completado todos los repartos');
				return false;
			}
			i++;
		}
		return true;
}

function submit_int(step, id) {
	por = $('input:radio[name=por]:checked').val();
	
	//validar formulari inicial
	if(por=='porcentaje') {
		//energia max_e
		if (document.getElementById('max_e').value<=0) {
			alert("Debe introducir un valor válido en el campo Energía");
			document.getElementById('max_e').focus();
			return false;
		}
		//hc pc_h
		if (document.getElementById('pc_h').value<=0) {
			alert("Debe introducir un valor válido en el campo Hidratos de Carbono");
			document.getElementById('pc_h').focus();
			return false;
		}
		//proteines pc_p
		if (document.getElementById('pc_p').value<=0) {
			alert("Debe introducir un valor válido en el campo Proteínas");
			document.getElementById('pc_p').focus();
			return false;
		}
		//grasas pc_g
		if (document.getElementById('pc_g').value<=0) {
			alert("Debe introducir un valor válido en el campo Grasas");
			document.getElementById('pc_g').focus();
			return false;
		}
		//suma
		suma = 	number(document.getElementById('pc_h').value) + 
				number(document.getElementById('pc_p').value) + 
				number(document.getElementById('pc_g').value);
		if (suma!=100) {
			alert("Los porcentajes deben sumar 100");
			document.getElementById('pc_h').focus();
			return false;
		}
		document.getElementById('form_intercambios').action = '?p=dietas&sp=dintercambio&s='+step+'&d='+id+"#end";
	} 
	else {
		if(!$('#max_h').val()) {
			alert("Debe introducir un valor válido en el campo Hidratos de Carbono");
			document.getElementById('max_h').focus();
			return false;
		}
		if(!$('#max_p').val()) {
			alert("Debe introducir un valor válido en el campo Proteínas");
			document.getElementById('max_p').focus();
			return false;
		}
		document.getElementById('form_intercambios').action = '?p=dietas&sp=dintercambio&s='+step+'&d='+id+"#end";
	}
}

function valid_int(e, energia, col, id, lim) {

	//nomes deixa passar els números del 0 al 9 i .
	var unicode=e.charCode? e.charCode : e.keyCode;
	unicode = number(unicode);		
	if(!esnumopunt(unicode)) return 0;
	
	//cela clicada		
	clicked = 'r_'+id+'_'+col;
	valor = document.getElementById(clicked).value;
	
	//si no te .
	if (!introduint_decimal(valor)) {
	
	//mirar si cal arrodonir
	if (cal_arrodonir(valor, id)) clic = number_half(valor);
	else clic = number(valor);
			
	//calcular el total de la fila
	total = 0;
	i=1;
	while(i<=6) {
		if (i!=col)	total+=	number(document.getElementById('r_'+id+'_'+i).value);
		else total += clic;
		i++;
	}
	
	//comprovar que no supera el limit
	if (total>lim) {
		retorn = lim-(total-clic);
	} else retorn = clic;
	
	//actualitzar comptador
	document.getElementById('c_'+id).innerHTML = number(total-clic+retorn);
	
	//calcular kcal de la cela
	document.getElementById('td_'+id+'_'+col).innerHTML = retorn*energia;
	
	//actualitzar el sumatori energia de cada menjar
	totalc = 0;
	i=1;
	while(i<=15) {
		totalc += number(document.getElementById('td_'+i+'_'+col).innerHTML);
		i++;
	}
	document.getElementById('tot_'+col).innerHTML = totalc;

	//actualitzar percentatges energia
	totalisim = 0;
	i=1;
	while(i<=6) {
		totalisim += number(document.getElementById('tot_'+i).innerHTML);
		i++;
	}
	i=1;
	while(i<=6) {
		document.getElementById('pc_'+i).innerHTML = number(document.getElementById('tot_'+i).innerHTML*100/totalisim).toFixed(1);
		i++;
	}
	
	//actualitzar el sumatori de hc cada menjar
	totalhc = 0;
	i=1;
	while(i<=15) {
		ints = number(document.getElementById('r_'+i+'_'+col).value);
		hctoma = ints*factor(i);
		totalhc += hctoma;
		i++;
	}
	document.getElementById('hc_'+col).innerHTML = totalhc;

	//retornem
	return retorn;
	}
	return valor;
}

function valid_int2(energia, col, id, lim) {
	//cela clicada		
	clicked = 'r_'+id+'_'+col;
	valor = document.getElementById(clicked).value;
	
	//mirar si cal arrodonir
	clic = number(valor);
			
	//calcular el total de la fila
	total = 0;
	i=1;
	while(i<=6) {
		if (i!=col)	total+=	number(document.getElementById('r_'+id+'_'+i).value);
		else total += clic;
		i++;
	}
	
	//comprovar que no supera el limit
	if (total>lim) {
		retorn = lim-(total-clic);
	} else retorn = clic;
	//alert(retorn);
	
	//actualitzar comptador
	document.getElementById('c_'+id).innerHTML = number(total-clic+retorn);
	
	//calcular kcal de la cela
	document.getElementById('td_'+id+'_'+col).innerHTML = retorn*energia;
	
	//actualitzar el sumatori de cada menjar
	totalc = 0;
	i=1;
	while(i<=15) {
		totalc += number(document.getElementById('td_'+i+'_'+col).innerHTML);
		i++;
	}
	document.getElementById('tot_'+col).innerHTML = totalc;

	//actualitzar percentatges
	totalisim = 0;
	i=1;
	while(i<=6) {
		totalisim += number(document.getElementById('tot_'+i).innerHTML);
		i++;
	}
	i=1;
	while(i<=6) {
		document.getElementById('pc_'+i).innerHTML = number(document.getElementById('tot_'+i).innerHTML*100/totalisim).toFixed(1);
		i++;
	}
	
	//actualitzar el sumatori de hc cada menjar
	totalhc = 0;
	i=1;
	while(i<=15) {
		if (i!=id) ints = number(document.getElementById('r_'+i+'_'+col).value);
		else ints = retorn;
		hctoma = ints*factor(i);
		totalhc += hctoma;
		i++;
	}
	document.getElementById('hc_'+col).innerHTML = totalhc;

	//actualitzar percentatges
	totalshc = 0;
	i=1;
	while(i<=6) {
		totalshc += number(document.getElementById('hc_'+i).innerHTML);
		i++;
	}
	i=1;
	while(i<=6) {
		document.getElementById('hcpc_'+i).innerHTML = number(document.getElementById('hc_'+i).innerHTML*100/totalshc).toFixed(1);
		i++;
	}
	
	//retornem
	return retorn;
}

function factor(id) {
	switch(id)	{
		case 1: elfactor = 9; break;
		case 2: elfactor = 9; break;
		case 3: elfactor = 12; break;
		case 4: elfactor = 16; break;
		case 5: elfactor = 23; break;
		case 6: elfactor = 4; break;
		case 7: elfactor = 15; break;
		case 8: elfactor = 10; break;
		case 9: elfactor = 14; break;
		case 10: elfactor = 0; break;
		case 11: elfactor = 0; break;
		case 12: elfactor = 0; break;
		case 13: elfactor = 0; break;
		case 14: elfactor = 1; break;
		case 15: elfactor = 0; break;
		default: elfactor = 0;
	}
	return elfactor;
}

function esnumopunt(numopunt) {
	unicode = numopunt;
	if (unicode==190) return true; //punt
	if (unicode==110) return true; //punt
	if ((unicode>=48 && unicode<=57)) return true; //num
	if ((unicode>=96 && unicode<=105)) return true; //num
	if (unicode==46) return true; //punt
	return false;
}

function introduint_decimal(numero) {
	s = new String(numero);
	if ( (s.indexOf('.',0)>0) && 
		 (s.indexOf('.',0)==s.length-1)) {
		return true;
	}
	else return false;
}

function cal_arrodonir(numero,id) {
	cal = false;
	if (mitjos_permesos(id)) {
		s = new String(numero);
		if ( (s.indexOf('.',0)>0) && 
			!(s.indexOf('.',0)==s.length-1)) {
			cal = true;
		}
		else cal = false
	}
	return cal;
}

function mitjos_permesos(id) {
	return true;
}

function number_half(n) {
	s = new String(n);
	//si no te .
	
	part_int = number(s.substring(0,s.indexOf('.',0)));
	part_dec = number(s.substring(s.indexOf('.',0)+1,s.length));
	
	if (part_dec<3) {
		//<.3
		part_dec = 0;
	
	} else if (part_dec<7) {
		//.3 - .7
		part_dec = 5;
	} else {
		//>.7
		part_dec = 0;
		part_int += 1;
	}
	
	n = Number(part_int+'.'+part_dec);	

	return n;
}

function number(n) {
	n = Number(n);
	return n;
}

/**/

function check(element) {
	//marca un radio
	document.getElementById(element).checked = 'checked'
}

function valid_form_dietes () {
	
	if (!document.getElementById('nom_dieta').value) {
		alert ("Debe indicar un nombre de dieta");
		return false;
	}
	/*if (!(document.getElementById('pacients').value > 0)) {
		return confirm("¿Quiere crear la dieta sin asignarla a ningún paciente?");
	}*/
	
	return true;
	
}

function valid_form_platos () {

	if (!document.getElementById('nom_plat').value) {
		alert ("Debe indicar un nombre de plato");
		return false;
	}
	/*if (!(document.getElementById('grup').value > 0)) {
		//return confirm("¿Quiere crear el plato sin asignarlo a ningún grupo?");
		alert ("Debe asignar el plato a un grupo");
		return false;

	}*/
	
	return true;
	
}

function valid_form_platos2 () {

	if (!document.getElementById('new_nom_plat').value) {
		alert ("Debe indicar un nombre de plato");
		return false;
	}
	
	return true;
	
}

function numbersonly(e){
	//nomes deixa passar els números del 0 al 9
	var unicode=e.charCode? e.charCode : e.keyCode
	if (unicode!=8){ //if the key isn't the backspace key (which we should allow)
	if (unicode<48||unicode>57) //if not a number
		return false //disable key press
	}
}

function numbersandecimals(e){
	//nomes deixa passar els números del 0 al 9
	var unicode=e.charCode?  e.charCode : e.keyCode
	if (unicode!=8 && unicode!=46 && unicode!=110 && unicode!=190){ //if the key isn't the backspace key (which we should allow)
	if (unicode<48||unicode>57) //if not a number
		return false //disable key press
	}
}

aliment_seleccionat = 0;
function check_form_alimentos () {
	
	if (!aliment_seleccionat) {
		alert('Tiene que seleccionar un alimento');
		return false;
	}
	
	if(document.getElementById('radio1').checked && !(document.getElementById('grams').value))	{ 
		alert('Tiene que indicar una cantidad');
		document.getElementById('grams').focus();
		return false; 
	}	
	
	return true;
}

function ocultar_divs_valor_nutricional() {
	ocultar_div('ppaltot');	
	ocultar_div('restatot');	
	ocultar_div('ppal100');	
	ocultar_div('resta100');	
}

veient_div1 = 2;
veient_div2 = 2;
function mostra_div_comb(que) {
	switch(que) {
		
		case 1:	if (veient_div2==1) troggle_div('ppal100');
				if (veient_div2==2) { troggle_div('ppal100'); troggle_div('resta100');}
				veient_div1 = 1;
				break;
		case 2:	if (veient_div2==1) troggle_div('ppaltot');
				if (veient_div2==2) { troggle_div('ppaltot'); troggle_div('restatot');}
				veient_div1 = 2;
				break;
		case 3: if (veient_div1==1) troggle_div('ppal100');
				if (veient_div1==2) { troggle_div('ppaltot'); }
				veient_div2 = 1;
				break;
		case 4:	if (veient_div1==1) { troggle_div('ppal100'); troggle_div('resta100'); }
				if (veient_div1==2) { troggle_div('ppaltot'); troggle_div('restatot'); }
				veient_div2 = 2;
				break;
		
	}
}

elvisible = '00';
function troggle_vis(nomCapa) {
	try { ocultar_div(elvisible+'_DESAYUNO');} catch(e) {};
	try { ocultar_div(elvisible+'_ALMUERZO');} catch(e) {};
	try { ocultar_div(elvisible+'_COMIDA');} catch(e) {};
	try { ocultar_div(elvisible+'_MERIENDA');} catch(e) {};
	try { ocultar_div(elvisible+'_CENA');} catch(e) {};
	try { ocultar_div(elvisible+'_RECENA');} catch(e) {};
	try { ocultar_div(elvisible+'_TOTALES');} catch(e) {};
}

function troggle_div(nomCapa) {
if (document.getElementById(nomCapa).style.display!="") {
	document.getElementById(nomCapa).style.display="";
	document.getElementById(nomCapa).style.visibility="";
	}
	else ocultar_div(nomCapa);
}

function troggle_pestanya(arxiu) {
	troggle_div('div'+arxiu);
	troggle_div('pleg_'+arxiu);
	troggle_div('desp_'+arxiu);	
}

function ocultar_div(nomCapa){
	document.getElementById(nomCapa).style.visibility="hidden";
	document.getElementById(nomCapa).style.display="none";
}

function mostrar(nomCapa) {
	document.getElementById(nomCapa).style.display="";
	document.getElementById(nomCapa).style.visibility="";
}

function popup(direccion, pantallacompleta, herramientas, direcciones, estado, barramenu, barrascroll, cambiatamano, ancho, alto, izquierda, arriba, sustituir){
     var opciones = "fullscreen=" + pantallacompleta +
                 ",toolbar=" + herramientas +
                 ",location=" + direcciones +
                 ",status=" + estado +
                 ",menubar=" + barramenu +
                 ",scrollbars=" + barrascroll +
                 ",resizable=" + cambiatamano +
                 ",width=" + ancho +
                 ",height=" + alto +
                 ",left=" + izquierda +
                 ",top=" + arriba;
     var ventana = window.open(direccion,"venta",opciones,sustituir);

} 

function pop_up(url, w, h) {
	newWindow = window.open(url,'finestra','toolbar=no,location=no,scrollbars=yes,resizable=yes,width='+w+',height='+h+',left=0,top=0');
	newWindow.focus();
}

function full_popup(win){
	winWidth = 1000; // sets a default width for browsers who do not understand screen.width below
	winheight = 700; // ditto for height

	if (screen){ // weeds out older browsers who do not understand screen.width/screen.height
	   winWidth = screen.width;
	   winHeight = screen.height;
	}
	
	newWindow = window.open(win,'finestra','toolbar=no,location=no,scrollbars=yes,resizable=yes,width='+winWidth+',height='+winHeight+',left=0,top=0');
	newWindow.focus();
}
