var valprec = 0;

/**
 * @description This function fist verifies that the user has checked his
 *  gender and typed his wieght. In that case, compiles the BAC, adjusts the
 *  plot display parameters and draws it. It also displays information messages
 *  about the current BAC
 */
function compileBAC() {
    valprec = 0;
    var boolOk = true;

    // Checks the selected sex
    if(i_sexe) {
        var coefK = 0.7; // Coefficient for a man
    } else {
        var coefK = 0.6; // Coefficient for a woman
    }
    
    var intPoids = i_poids_kilo;
    if(intPoids == NaN) {
        boolOk = false;
    }

    //If weight and sex are set, compile the bac
    if(boolOk) {
        var glassAlcoholLevel = 14; //Approx content of alcohol in a glass
        var alcohol = new Array();

        for(var i=0; i != hours_values.length; i++) {
            var min	= minutes_values[i];
            var fl_min = parseFloat(min)/60;

            var hour = hours_values[i];

            var hourAsDecimal = (hour < 8 ? hour + 24 : hour) + fl_min;

            alcohol[i] = new Array(3);
            alcohol[i][0] = hourAsDecimal;
            if(hour < 10) {
                hour = '0' + hour;
            }
            if(min < 10) {
                min = '0' + min;
            }
            alcohol[i][1] = 0;
            alcohol[i][2] = hour+":"+min;
        }

        //Compile our scale
        var partyLength = alcohol[alcohol.length-1][0] - alcohol[0][0];

        //Defines scale on 1/4 hour
        intTabSize = partyLength*4;
        tabJalonGraph = new Array(intTabSize+3);
        for(i=0;i<intTabSize+3;i++) {
            tabJalonGraph[i]	= new Array(4);
            tabJalonGraph[i][0] = alcohol[0][0]+(i*0.25);
            tabJalonGraph[i][1] = 0;
            tabJalonGraph[i][2] = 0;
            tabJalonGraph[i][3] = '';
        }

        //Get amount of glasses
        for(var i=0; i != glass_amount_values.length; i++) {
            var nbVerre = glass_amount_values[i];
            alcohol[i][1] = glassAlcoholLevel * parseInt(nbVerre);
        }
        
        for(i=0; i < alcohol.length; i++) {
            for(j=0; j < tabJalonGraph.length; j++) {
                if(tabJalonGraph[j][0] == Math.round(tabJalonGraph[j][0])) {
                    var h = tabJalonGraph[j][0] > 23 ? tabJalonGraph[j][0] - 24 : tabJalonGraph[j][0];
                    if(h < 10)
                    	h = '0' + h;

                    tabJalonGraph[j][3] = h+':00';

                }

                if(tabJalonGraph[j][0]==alcohol[i][0]) {
                    tabJalonGraph[j][1] = alcohol[i][1];
                }
            }
        }
        
        var CoefPoids = intPoids*coefK;
        var txAlcool=0;
        
        for(var j = 0; j < tabJalonGraph.length; j++) {
            txAlcool = formuleCalcul(alcohol[0][0],tabJalonGraph[j][0],txAlcool,tabJalonGraph[j][1],CoefPoids);
            tabJalonGraph[j][2] = txAlcool;
        }

        var arrDataset = new Array();
        var arrParamX  = new Array();

        for(var i=0; i < tabJalonGraph.length; i++) {
            if(tabJalonGraph[i][3] != '') {
                arrParamX[i] = {v:i, label:tabJalonGraph[i][3]};
            } else {
                arrParamX[i] = {v:i, label:''};
            }
        }
        
        for(var i=0; i < tabJalonGraph.length; i++) {
            arrDataset[i] = [parseInt(i), parseFloat(tabJalonGraph[i][2])];
        }
        
        var res_alcool = Math.round(parseFloat(tabJalonGraph[tabJalonGraph.length-3][2])*1000);
		var strAlcool = res_alcool+'';
		while(strAlcool.length < 3) {
			strAlcool = '0'+strAlcool;
		}

        if(res_alcool < 40) {
            var phrase_res = "Está em condições legais para conduzir.";
        } else {
            if((res_alcool>=40) && (res_alcool<50)) {
                var phrase_res = "Legalmente pode conduzir, mas será preferível aguardar um pouco antes de o fazer!";
            } else {
                var phrase_res = "PERIGO! Você não está em condições de conduzir e fazê-lo seria crime. Use outro(s) meio(s) de transporte. Também pode considerar beber um pouco menos, ou utilizar um condutor 100% Cool.";
            }
        }

        
		var resposta = {taxa: strAlcool, mensagem: phrase_res};
		return resposta;
    }
    
	var resposta = {taxa: -1, mensagem: "Erro"};
	return resposta;
}

/**
 * @param {Number} t0 The BAC relative to the current point in the dataset
 * @param {Number} t1 The BAC relative to the previous point in the dataset
 * @param {Number} txAlcool The BAC of the user at the given point
 * @param {Number} conso The amount
 * @param {Float} CoefPoids The absobtion coefficient of the user
 * @description This functon is used to determine the list of points on the BAC
 *  plot. It returns the BAC compiled with the new drinks or the absorbition
 *  of alcohol by the user's body over time.
 * @return {Float} BAC
 */
function formuleCalcul(t0,t1,txAlcool,conso,CoefPoids) {
    if(t1>=t0) {
        diff = (t1-t0);
        if(diff<0) {
            diff=0;
        }
        
        res = (diff*0.015)-valprec;
        valprec += res;
        txAlcool = txAlcool-res;
        if(txAlcool<0) {
            txAlcool = 0;
        }
        //update bac
        txAlcool += parseFloat((parseInt(conso)/CoefPoids)/10);
    }
    
    return txAlcool;
}

var i_poids_kilo;
var i_sexe;

var hours_values = new Array();
var minutes_values = new Array();
var glass_amount_values = new Array();

function calcularFlash(p_poids_kilo, p_sexe,
	p_apero_nbverre, p_apero_verre, p_apero_heure, p_apero_min,
	p_entree_nbverre, p_entree_verre, p_entree_heure, p_entree_min,
	p_repas_nbverre, p_repas_verre, p_repas_heure, p_repas_min,
	p_digestif_nbverre, p_digestif_verre, p_digestif_heure, p_digestif_min,
	p_quitter_heure, p_quitter_min
) {
	i_poids_kilo = p_poids_kilo;

	i_sexe = p_sexe;
	
	glass_amount_values[0] = parseInt(p_apero_nbverre);
	hours_values[0] = parseInt(p_apero_heure);
	minutes_values[0] = parseInt(p_apero_min);
	
	glass_amount_values[1] = parseInt(p_entree_nbverre);
	hours_values[1] = parseInt(p_entree_heure);
	minutes_values[1] = parseInt(p_entree_min);
	
	glass_amount_values[2] = parseInt(p_repas_nbverre);
	hours_values[2] = parseInt(p_repas_heure);
	minutes_values[2] = parseInt(p_repas_min);
	
	glass_amount_values[3] = parseInt(p_digestif_nbverre);
	hours_values[3] = parseInt(p_digestif_heure);
	minutes_values[3] = parseInt(p_digestif_min);
	
	hours_values[4] = parseInt(p_quitter_heure);
	minutes_values[4] = parseInt(p_quitter_min);

	return compileBAC();
}
