var _lang = $('html').attr('lang');
var _regexDigitOrComma = /(^\d+(\.|\,)?\d?\d?$)/;
var _label = 
{
    appareilElectromenagers : 
                            {
                                fr : 
                                    {
                                        util : "utilisations par année ",
							            jour : "jours d'utilisation par année "
                                    },
                                    
                                en :
                                    {
                                        util : "(days per year)",
							            jour : "(days per year)"
                                    }
                            },
                            
    autresAppareils : 
                            {
                                fr : 
                                    {
                                        heure : "heures/utilisation",
							            minute : "minutes/utilisation"
                                    },
                                    
                                en :
                                    {
                                        heure : "hours per use",
							            minute : "minutes per use"
                                    }
                            }
};
/***********************************************/
/* UTILITAIRES
/***********************************************/
function createDropDowm(id, key, value, options/*optional*/) {
    
    if(options === undefined) {
        options = {};
    }
    
    if(options.selectedIndex === undefined) {
        selectedIndex = 0;
    }
    
    if(options.fn === undefined) {
        fn = null;
    }
    
    
    if(options.data === undefined) options.data = null;
    
    var select = document.createElement('select');
    $(select).attr('id', id)
    
    //loop and populate the drop down
	for(var i=0; i < value.length; i++){
		
		//create a child 'option'
		var child = document.createElement('option');
		
		//add attributes
		child.innerHTML = value[i][key.text];
		child.value = value[i][key.value];
		
		if(options.data != null) {
		    
		    if(typeOf(options.data.key) === 'array') {
		        for(j=0; j < options.data.key.length; j++) {
		            
		            if(options.data.key[j] !== undefined) {
		                datakey = options.data.key[j];
    		            
		                $(child).data( datakey, value[i][datakey] );
		            }
		        }
		    }
		}
		
		//append the child to the parent 
		select.appendChild(child);
		
	}
	
	select.selectedIndex = options.selectedIndex;
	
    return select;
}

/*
id : id of the table
key : {text:'', value : ''}
value : 
*/

function createRadioButton(id, key, value, data/*optional*/) {
    
    if(data === undefined) {
        data = null;
    }
    
    var tab = document.createElement('table');
	tab.id = 'tab-' + id;
	var tbdy = document.createElement("tbody");
	
	for(var i=0; i < value.length; i++)
	{
		var lbl = i;
		
		try{
			rad = document.createElement('<input type="radio" name="grp' + id + '" />');
		}catch(err){
			rad = document.createElement('input');
		}
		
		$(rad).attr('type','radio');
		$(rad).attr('name','grp' + id);
		$(rad).attr('value',value[i][key.value]);
		$(rad).attr('id','rad' + id + '-' + i);
		$(rad).attr('class','no-border');
        
        if(data != null)  {
            $(rad).data(data.key,value[i][key[data.key]]);
        }
		
		var childTdRad = document.createElement('td');
		childTdRad.appendChild(rad);
		
		
		var childTdLbl = document.createElement('td');
		childTdLbl.innerHTML = value[i][key.text];
		
		var childTR = document.createElement('tr');
		
		childTR.appendChild(childTdRad);
		childTR.appendChild(childTdLbl);
		
		tbdy.appendChild(childTR);
	
	
		tab.appendChild(tbdy);
		
	}
	
	return tab;
}

jQuery.fn.validate = function() {
    
    function validateAllRequired(requiredLi){
        var result = true;
        
        for(i=0; i<requiredLi.length; i++)
        {   
            var requiredInput = $(requiredLi[i]).find(':input');
            var resultLi = true;
            
            if($(requiredInput[0]).attr("type") == "radio") { resultLi = false; result = false; }
            
            for(j=0; j<requiredInput.length; j++) {
                
                if(!$(requiredInput[j]).hasClass('optional')) {
                    var type = $(requiredInput[j]).attr('type');
                    var value = $(requiredInput[j]).val();
                     
                    switch(type) {
                        case 'checkbox':
                            if(!$(requiredInput[j]).attr('checked')) {result = false;resultLi = false;}
                        break;
                        
                        case 'radio':
                            if($(requiredInput[j]).attr('checked')) {result = true;resultLi = true;}
                            
                        break;
                        
                        case 'select-one':
                            if(value === "" || value === "-1") {result = false;resultLi = false;}
                        break;
                        
                        case 'text':
                            if(value == "") {result = false;resultLi = false;}
                        break;
                        
                        case 'textarea':
                            if(value == "") {result = false;resultLi = false;}
                        break;
                    }
                }
            }
            
            
            if(!resultLi) $(requiredLi[i]).addClass('error');
            else $(requiredLi[i]).removeClass('error');
        }
        
        return result;
    }
    
    
    var result = true;
    
    var requiredLi = $(this).find('li.required');
    
    result = validateAllRequired(requiredLi);
    
    return result;
}

/*au key press, vérifie si l'expression régulière est valide, 
si non return false*/
jQuery.fn.formatInput = function(regex) {
    
    $(this).keypress(function(e){
        var oldVal = $(this).val() != undefined ? $(this).val() : "";
        
        var code = e.which;
        
        if(code != '0' && code != '8'){
		    
		    var newVal = oldVal + String.fromCharCode(code);
    		
    		var isFormatOk = newVal.match(regex);
    		
		    if(!isFormatOk) {
    			e.preventDefault();
    			return false;
		    }
    		
	    }
    });
}

//ajout de l'espace pour le formattage des nombres français
//ex.: 56123.23 --> 56 123.23
function addSpace(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ' ' + '$2');
	}
	return x1 + x2;
}

function addVirgule(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}


//format du chiffre selon la langue
function formatNumber(val) {
    //val = parseFloat(val).toString();
    
    if(_lang == 'fr') {
        val = addSpace(val);
        val = val.replace('.', ',');
    }
	else if(_lang == 'en') {
        val = addVirgule(val);
    }
    
    return val;
}

function replaceCommaForDot(text) {
    text = text.replace(',', '.');
    return text;
}

function typeOf(value) {
    var s = typeof value;
    if (s === 'object') {
        if (value) {
            if (value instanceof Array) {
                s = 'array';
            }
        } else {
            s = 'null';
        }
    }
    return s;
}
/***********************************************/
/* CALCUL DE CONVERSION
/***********************************************/

/**
 * Calculate the conversion °F to °C and °C to °F
 * @method calculateTemperature
 */
function calculateTemperature()
{
	//get the user input
	var input = replaceCommaForDot($('#txtTemperature').val());
	
	//get the selected temperature
	var dd = $('#ddTemperature').val();
	var result;
	
	//calculate the conversion
	//celcius to fahrenheit
	if(dd == "c"){
		result = 9/5*(input*1)+32;
		$('#temperature').html("&deg;F");
	}
	//fahrenheit to celcius
	else{
		result = ( (input*1)-32 )*5/9;
		$('#temperature').html("&deg;C");
	}
	
	$('#txtTemperatureResultat').val( (formatNumber(result.toFixed(2))) );

}

/**
 * Calculate the conversion "meter to feet" and "feet to meter"
 * @method calculateLongueur
 */
function calculateLongueur()
{
	//get the user input
	var input = replaceCommaForDot($('#txtLongueur').val());
	
	//get the selected temperature
	var dd = $('#ddLongueur').val();
	
	var result;
	
	var constante = data.constanteConversion.longueur;
	//var constante = 1;
	//calculate the conversion
	//meter to foot
	if(dd == "m"){
		result = (input*1) * constante;
		if (_lang=="fr"){
		$('#longueur').html("pied");
		}
		else if (_lang=="en"){
		$('#longueur').html("ft.");
		}
	}
	//foot to meter
	else{
		result = (input*1) * 1/constante;
		
		
		if (_lang=="fr"){
		$('#longueur').html("m&egrave;tre");
		}
		else if (_lang=="en"){
		$('#longueur').html("m");
		}
	}
	
	if (_lang=="fr"){
	//ajoute un "s" au span si > 1
	if(result>1) $('#longueur').html( $('#longueur').html() + "s" );
	}
	
	$('#txtLongueurResultat').val( (formatNumber(result.toFixed(2))) );
}

/**
 * Calculate the conversion "m2 to p2" and "p2 to m2"
 * @method calculateSuperficie
 */
function calculateSuperficie()
{
	//get the user input
	var input = replaceCommaForDot($('#txtSuperficie').val());
	
	//get the selected temperature
	var dd = $('#ddSuperficie').val();
	
	var result;
	
	//=D7*IF(K7=1;1/K8;K8)
	var constante = data.constanteConversion.longueur;
	//var constante = 1;
	//calculate the conversion
	//meter to foot
	if(dd == "m"){
		result = (input*1) * (Math.pow(constante, 2));
		
		
		
		
		if (_lang=="fr"){
		$('#superficie').html("p&sup2;");
		}
		else if (_lang=="en"){
		$('#superficie').html("sq. ft.");
		}
	}
	//foot to meter
	else{
		result = (input*1) * 1/(Math.pow(constante, 2));
		
		
		$('#superficie').html("m&sup2;");
		
	}
	
	$('#txtSuperficieResultat').val( (formatNumber(result.toFixed(2))) );
}

/**
 * Calculate the conversion "litre to gallon IMP" and "gallon IMP to litre"
 * @method calculateVolume
 */
function calculateVolume()
{
	//get the user input
	var input = replaceCommaForDot($('#txtVolume').val());
	
	//get the selected temperature
	var dd = $('#ddVolume').val();
	
	var result;
	
	
	var constante = data.constanteConversion.volume;
	//var constante = 1;
	//calculate the conversion
	//meter to foot
	if(dd == "l"){
		result = (input*1) * 1/constante;
		
		if (_lang=="fr"){
		$('#volume').html("gallon IMP");
		}
		else if (_lang=="en"){
		$('#volume').html("Imp. gal.");
		}
		
		
		if (_lang=="fr"){
		//ajoute un "s" au span si > 1
		if(result>1) $('#volume').html("gallons IMP");
		}
	}
	//foot to meter
	else{
		result = (input*1) * constante;
		
		if (_lang=="fr"){
		$('#volume').html("litre");
		}
		else if (_lang=="en"){
		$('#volume').html("L");
		}
		
		if (_lang=="fr"){
		//ajoute un "s" au span si > 1
		if(result>1) $('#volume').html("litres");
		}
	}
	
	$('#txtVolumeResultat').val( (formatNumber(result.toFixed(2))) );
}

/**
 * Calculate the conversion "litre to gallon US" and "gallon US to litre"
 * @method calculateVolumeUS
 */
function calculateVolumeUS()
{
	//get the user input
	var input = replaceCommaForDot($('#txtVolumeUS').val());
	
	//get the selected temperature
	var dd = $('#ddVolumeUS').val();
	
	var result;
	
	
	var constante = data.constanteConversion.volumeUS;
	//var constante = 1;
	//calculate the conversion
	//meter to foot
	if(dd == "l"){
		result = (input*1) * 1/constante;
		
		if (_lang=="fr"){
		$('#volumeUS').html("gallon US");
		}
		else if (_lang=="en"){
		$('#volumeUS').html("U.S. gal.");	
		}
		
		if (_lang=="fr"){
		//ajoute un "s" au span si > 1
		if(result>1) $('#volumeUS').html("gallons US");
		}
	}
	//foot to meter
	else{
		result = (input*1) * constante;
		
		if (_lang=="fr"){
		$('#volumeUS').html("litre");
		}
		else if (_lang=="en"){
		$('#volumeUS').html("L");
		}
		
		if (_lang=="fr"){
		//ajoute un "s" au span si > 1
		if(result>1) $('#volumeUS').html("litres");
		}
	}
	
	$('#txtVolumeUSResultat').val( (formatNumber(result.toFixed(2))));
}

/**
 * Calculate the conversion "W to kW" and "kW to W"
 * @method calculatePuissance
 */
function calculatePuissance()
{
	//get the user input
	var input = replaceCommaForDot($('#txtPuissance').val());
	
	//get the selected temperature
	var dd = $('#ddPuissance').val();
	
	var result;
	
	
	var constante = data.constanteConversion.puissance;
	//var constante = 1;
	//calculate the conversion
	//meter to foot
	if(dd == "w"){
		result = (input*1) * 1/constante;
		$('#puissance').html("kW");
	}
	//foot to meter
	else{
		result = (input*1) * constante;
		$('#puissance').html("W");
	}
	
	$('#txtPuissanceResultat').val( (formatNumber(result.toFixed(2))) );
}

/**
 * Calculate the conversion "kW to Btu/hr" and "Btu/hr to kW"
 * @method calculatePuisThermiquekWBtu
 */
function calculatePuisThermiquekWBtu()
{
	//get the user input
	var input = replaceCommaForDot($('#txtPuisThermiquekWBtu').val());
	
	//get the selected temperature
	var dd = $('#ddPuisThermiquekWBtu').val();
	
	var result;
	
	
	var constante = 1/data.constanteConversion.puissanceThermiquekW;
	//var constante = 1;
	//calculate the conversion
	//meter to foot
	if(dd == "kw"){
		result = (input*1) * 1/constante;
		if (_lang=="fr"){
		$('#puisThermiquekWBtu').html("Btu/hr");
		}
		else if (_lang=="en"){
		$('#puisThermiquekWBtu').html("Btu/h");	
		}
	}
	//foot to meter
	else{
		result = (input*1) * constante;
		$('#puisThermiquekWBtu').html("kW");
	}
	
	$('#txtPuisThermiquekWBtuResultat').val( (formatNumber(result.toFixed(2))) );
}

/**
 * Calculate the conversion "kW to Tonne" and "Tonne to kW"
 * @method calculatePuisThermiquekWTonne
 */
function calculatePuisThermiquekWTonne()
{
	//get the user input
	var input = replaceCommaForDot($('#txtPuisThermiquekWTonne').val());
	
	//get the selected temperature
	var dd = $('#ddPuisThermiquekWTonne').val();
	
	var result;
	
	
	var constante = data.constanteConversion.puissanceThermiqueTonne/data.constanteConversion.puissanceThermiquekW;
	//var constante = 1;
	//calculate the conversion
	//meter to foot
	if(dd == "kw"){
		result = (input*1) * 1/constante;
		if (_lang=="fr"){
		$('#puisThermiquekWTonne').html("tonne");
		}
		else if (_lang=="en"){
		$('#puisThermiquekWTonne').html("ton");	
		}
		
		//ajoute un "s" au span si > 1
		if(result>1) $('#puisThermiquekWTonne').html( $('#puisThermiquekWTonne').html() + "s" );
		
	}
	//foot to meter
	else{
		result = (input*1) * constante;
		$('#puisThermiquekWTonne').html("kW");
		
	}
	
	$('#txtPuisThermiquekWTonneResultat').val( (formatNumber(result.toFixed(2))) );
}

/**
 * Calculate the conversion "Btu/hr to Tonne" and "Tonne to Btu/hr"
 * @method calculatePuisThermiqueBtuTonne
 */
function calculatePuisThermiqueBtuTonne()
{
	//get the user input
	var input = replaceCommaForDot( $('#txtPuisThermiqueBtuTonne').val());
	
	//get the selected temperature
	var dd = $('#ddPuisThermiqueBtuTonne').val();
	
	var result;
	
	
	var constante = data.constanteConversion.puissanceThermiqueTonne;
	//var constante = 1;
	//calculate the conversion
	//meter to foot
	if(dd == "b"){
		result = (input*1) * 1/constante;
		if (_lang=="fr"){
		$('#puisThermiqueBtuTonne').html("tonne");
		}
		else if (_lang=="en"){
			$('#puisThermiqueBtuTonne').html("ton");
		}
		
		//ajoute un "s" au span si > 1
		if(result>1) $('#puisThermiqueBtuTonne').html( $('#puisThermiqueBtuTonne').html() + "s" );
		
	}
	//foot to meter
	else{
		result = (input*1) * constante;
		if (_lang=="fr"){
		$('#puisThermiqueBtuTonne').html("Btu/hr");
		}
		else if (_lang=="en"){
		$('#puisThermiqueBtuTonne').html("Btu/h");
		}
		
	}
	
	$('#txtPuisThermiqueBtuTonneResultat').val( (formatNumber(result.toFixed(2))) );

}



function calculateMasseKgLb() {

    //get the user input

    var input = replaceCommaForDot($('#txtMasseKgLb').val());



    //get the selected masse

    var dd = $('#ddMasseKgLb').val();



    var result;





    var constante = data.constanteConversion.masseKgLb;

    //var constante = 1;

    //calculate the conversion

    //kg to lb

    if (dd == "kg") {



        result = input * constante; 

        

        $('#spanMasseKgLb').html("lb");

        

        //ajoute un "s" au span si > 1

        if (result > 1) $('#spanMasseKgLb').html($('#spanMasseKgLb').html() + "s");



    }

    //lb to kg

    else {

        result = input * (1 / constante); 



        $('#spanMasseKgLb').html("kg");

        

    }



    $('#txtMasseKgLbResultat').val((formatNumber(result.toFixed(2))));

}
/***************************************************/


/***********************************************/
/* INITIALISATION
/***********************************************/
function initChauffageEau() {
    initConsommationAnnuelle();
    initBainsDouche();
}

function initAppareil() {
    initElectromenager();
}

function initClimatisation() {
    initClimatisationIndividuelle();
    initClimatisationCentrale();
}

function initPiscine() {
    initPompePiscine();
    initChauffagePiscine();
}

function initAppareil() {
    initAutresAppareils();
}

function initAutresAppareils() {
    var id = 'ddPuissanceAppareil';
    var key = {text:'libelle_' + _lang, value:'puissanceMoyenne'};
	var value = data.appareil;
	
	var ddPuissanceAppareil = createDropDowm(id, key, value, {data:{key:['type', 'coutDT']}});
	
	$('#' + id).replaceWith(ddPuissanceAppareil);
	
	$('#' + id).change(function(e){
	    
	    var $option = $('#' + id + ' option:selected');
	    //affiche la zone "autres"
	    if($option.val() === "-900") {
	        var $li = $(this).parent();
	        var $subRow = $(this).parent().next();
	        
	        $li.removeClass('error');
	        
	        $subRow.addClass('required');
	        initRequired($subRow);
	        $subRow.show();
	        $('#l-note-appareil').hide();
	        $('#l-note-autre-appareil').show();
	        
	        
	    }
	    else {
	         var $subRow = $(this).parent().next();
	        $subRow.hide();
	        $subRow.removeClass('required error');
	        
	        $('#l-note-appareil').show();
	        $('#l-note-autre-appareil').hide();
	    }
	    
	    
	    //modifie le texte heures/utilisations pour minutes/utilisation lorsque nécessaire
	    if($option.data('type') == "0") {
	        $('#tempsUtilisation').html(_label.autresAppareils[_lang].heure);
	    }
	    else $('#tempsUtilisation').html(_label.autresAppareils[_lang].minute);
	    
	    //modifie le tarif DT selon les donnees
        var coutDT = $option.data('coutDT');
        
        if(coutDT != undefined) {
            
            if(coutDT === "haut") {
                tarif = data.tarif[1].cout_haut_tarif;
                $('#radTarifAppareil-1').data('moreInfo', data["appareil_tarif_dt_resultat_moreInfo_" + _lang]);
                
                if($('#radTarifAppareil-1').attr("checked")) {
                    $('.l-resultat-plus-information').html(data["appareil_tarif_dt_resultat_moreInfo_" + _lang]);
                }
            }
            else if(coutDT === "bas") {
                tarif = data.tarif[1].cout_bas_tarif;
            }
            
        }
        else {
            tarif = data.tarif[1].cout;
            $('#radTarifAppareil-1').data('moreInfo', data.tarif[1]["resultat_moreInfo_" + _lang]);
            
            if($('#radTarifAppareil-1').attr("checked")) {
                    $('.l-resultat-plus-information').html(data.tarif[1]["resultat_moreInfo_" + _lang]);
                }
        }
        
        $('#radTarifAppareil-1').val(tarif);
	});
	
	$('#btnCalculerAutresAppareils').click(function(e){
        
	    e.preventDefault();
	    
		//câble chauffant modification libelé cout total
		if ($('#ddPuissanceAppareil').val() == 7 || $('#ddPuissanceAppareil').val() == 5){
			$('#labelCoutEstimeAppareil span').show();
		}
		else{
			$('#labelCoutEstimeAppareil span').hide();
		}
		
	    //affiche le résultat du calcul
	    if($(this).parent().validate()) {
	        var puissance = parseFloat( $('#ddPuissanceAppareil').val() === "-900" ?  $('#txtAutres').val() : $('#ddPuissanceAppareil').val());
	        var type = parseFloat($('#ddPuissanceAppareil option:selected').data('type'));
	        
	       
	        
	        //type 1 = la valeur en minute
	        var heureUtilisation = ( type === 1 ? parseFloat($('#txtNbHeure').val()) / 60 : parseFloat($('#txtNbHeure').val()) );
	        
	        var utilisationAnnee = parseFloat($('#txtNbUtilisation').val());
	        
	        var tarif = parseFloat($('input[name=grpTarifAppareil]:checked').val());
	        var tarifAvecTaxes = tarif * (1 + (data.taxes.TVQ/100)) * (1 + (data.taxes.TPS/100));
	        
	        var consommationEstimee = heureUtilisation * utilisationAnnee / 1000 * puissance;
		    var coutEstimeTotal = consommationEstimee * tarifAvecTaxes / 100;
		    
		    $('#txtConsommationEstimeeAppareil').val(formatNumber(consommationEstimee.toFixed(1)));
		    $('#txtCoutEstimeAppareil').val(formatNumber(coutEstimeTotal.toFixed(2)));
		    
		    
		     //affiche les résultats
		    $(this).next().show();
		    //affiche le bandeau
		    $(this).parent().next().show();
	    }
	       
	    return false;
	});
}

function initChauffagePiscine() {
    
    //modifie le tarif DT pour utiliser seulement le bas tarif
    var tarif = data.tarif[1].cout_bas_tarif;
    $('#radTarifChauffage-1').val(tarif);
    
    //modifie le contenu de la section "Plus d'information" de la boite de résultat
    //Tarif DT seulement
    $('#radTarifChauffage-1').data('moreInfo', data.piscine['resultat_moreInfo_' + _lang]);
    
    var id = 'ddTypeDimension';
    var key = {text:'libelle_' + _lang, value:'consommation'};
	var value = data.piscine.type;
	
	var ddTypeDimension = createDropDowm(id, key, value);
	
	$('#' + id).replaceWith(ddTypeDimension);
	
	var id = 'ddAppareilChauffage';
    var key = {text:'libelle_' + _lang, value:'cop'};
	var value = data.piscine.appareil;
	
	var ddAppareilChauffage = createDropDowm(id, key, value);
	
	$('#' + id).replaceWith(ddAppareilChauffage);
	
	$('#btnCalculerChauffage').click(function(e){
        
	    e.preventDefault();
	    
	    //affiche le résultat du calcul
	    if($(this).parent().validate()) {
	        var typeDimension = parseFloat($('#ddTypeDimension').val());
	        var appareilChauffage = parseFloat($('#ddAppareilChauffage').val());
	        
	        var tarif = parseFloat($('input[name=grpTarifChauffage]:checked').val());
	        var tarifAvecTaxes = tarif * (1 + (data.taxes.TVQ/100)) * (1 + (data.taxes.TPS/100));
	        
	        var consommationEstimee = typeDimension * 3 / appareilChauffage;
		    var coutEstimeTotal = consommationEstimee * tarifAvecTaxes / 100;
		    
		    $('#txtConsommationEstimeeChauffage').val(formatNumber(consommationEstimee.toFixed(1)));
		    $('#txtCoutEstimeChauffage').val(formatNumber(coutEstimeTotal.toFixed(2)));
		    
		    //affiche les résultats
		    $(this).next().show();
		    //affiche le bandeau
		    $(this).parent().next().show();
	    }
	       
	    return false;
	});
}

function initPompePiscine() {
    
    //modifie le tarif DT pour utiliser seulement le bas tarif
    var tarif = data.tarif[1].cout_bas_tarif;
    $('#radTarifPompe-1').val(tarif);
    
    //modifie le contenu de la section "Plus d'information" de la boite de résultat
    //Tarif DT seulement
    $('#radTarifPompe-1').data('moreInfo', data['pompePuissance_resultat_moreInfo_' + _lang]);
    
    var id = 'ddPuissancePompe';
    var key = {text:'libelle_' + _lang, value:'consommation'};
	var value = data.pompePuissance;
	
	var ddPuissancePompe = createDropDowm(id, key, value);
	
	$('#' + id).replaceWith(ddPuissancePompe);
	
	$('#btnCalculerPompe').click(function(e){
        
	    e.preventDefault();
	    
	    //affiche le résultat du calcul
	    if($(this).parent().validate()) {
	        var puissance = parseFloat($('#ddPuissancePompe').val());
	        var heureUtilisation = parseFloat($('#txtNbHeure').val());
	        var jourUtilisation = parseFloat($('#txtNbJour').val());
	        
	        var tarif = parseFloat($('input[name=grpTarifPompe]:checked').val());
	        var tarifAvecTaxes = tarif * (1 + (data.taxes.TVQ/100)) * (1 + (data.taxes.TPS/100));
	        
	        var consommationEstimee = puissance * heureUtilisation * jourUtilisation / 1000;
		    var coutEstimeTotal = consommationEstimee * tarifAvecTaxes / 100;
	        
	        $('#txtConsommationEstimeePompe').val(formatNumber(consommationEstimee.toFixed(1)));
		    $('#txtCoutEstimePompe').val(formatNumber(coutEstimeTotal.toFixed(2)));
		    
	        //affiche les résultats
		    $(this).next().show();
		    //affiche le bandeau
		    $(this).parent().next().show();
	    }
	       
	    return false;
	});
}

function initClimatisationCentrale() {
    
    //modifie le tarif DT pour utiliser seulement le bas tarif
    var tarif = data.tarif[1].cout_bas_tarif;
    $('#radTarifCC-1').val(tarif);
    
    //modifie le contenu de la section "Plus d'information" de la boite de résultat
    //Tarif DT seulement
    $('#radTarifCC-1').data('moreInfo', data.climatisationCentrale['resultat_moreInfo_' + _lang]);
    
    var id = 'ddCapaciteCC';
    var key = {text:'libelle_' + _lang, value:'valeur'};
	var value = data.climatisationCentrale.capacite;
	
	var ddCapacite = createDropDowm(id, key, value, {selectedIndex:2});
	
	$('#' + id).replaceWith(ddCapacite);
	
	var id = 'ddRendementCC';
    var key = {text:'libelle_' + _lang, value:'valeur'};
	var value = data.climatisationCentrale.rendement;
	
	var ddRendement = createDropDowm(id, key, value, {selectedIndex:4});
	
	$('#' + id).replaceWith(ddRendement);
	
	var id = 'ddNbHeureCC';
    var key = {text:'libelle_' + _lang, value:'valeur'};
	var value = data.climatisationCentrale.heure;
	
	var ddNbHeureCC = createDropDowm(id, key, value);
	
	$('#' + id).replaceWith(ddNbHeureCC);
	
	$('#btnCalculerCC').click(function(e){
        
	    e.preventDefault();
	    
	     //affiche le résultat du calcul
	    if($(this).parent().validate()) {
	        
	        var capacite = parseFloat($('#ddCapaciteCC').val());
	        var rendement = parseFloat($('#ddRendementCC').val());
	        var heureUtilisation = parseFloat($('#ddNbHeureCC').val());
	        
	        var tarif = parseFloat($('input[name=grpTarifCC]:checked').val());
	        var tarifAvecTaxes = tarif * (1 + (data.taxes.TVQ/100)) * (1 + (data.taxes.TPS/100));
	        
	        var consommationEstimee = capacite / rendement / 1000 * heureUtilisation;
		    var coutEstimeTotal = consommationEstimee * tarifAvecTaxes / 100;
	        
	        $('#txtConsommationEstimeeCC').val(formatNumber(consommationEstimee.toFixed(1)));
		    $('#txtCoutEstimeCC').val(formatNumber(coutEstimeTotal.toFixed(2)));
	        
	        //affiche les résultats
		    $(this).next().show();
		    //affiche le bandeau
		    $(this).parent().next().show();
	    }
	    
	    return false;
	    
	});
}

function initClimatisationIndividuelle() {
    
    //modifie le tarif DT pour utiliser seulement le bas tarif
    var tarif = data.tarif[1].cout_bas_tarif;
    $('#radTarifElectro-1').val(tarif);
    
    //modifie le contenu de la section "Plus d'information" de la boite de résultat
    //Tarif DT seulement
    $('#radTarifElectro-1').data('moreInfo', data.climatisationIndividuelle['resultat_moreInfo_' + _lang]);
    
    var id = 'ddCapacite';
    var key = {text:'libelle_' + _lang, value:'valeur'};
	var value = data.climatisationIndividuelle.capacite;
	
	var ddCapacite = createDropDowm(id, key, value);
	
	$('#' + id).replaceWith(ddCapacite);
	
	var id = 'ddRendement';
    var key = {text:'libelle_' + _lang, value:'valeur'};
	var value = data.climatisationIndividuelle.rendement;
	
	var ddRendement = createDropDowm(id, key, value);
	
	$('#' + id).replaceWith(ddRendement);
	
	
	$('#btnCalculerCI').click(function(e){
        
	    e.preventDefault();
	    
	    //affiche le résultat du calcul
	    if($(this).parent().validate()) {
	        var capacite = parseFloat($('#ddCapacite').val());
	        var rendement = parseFloat($('#ddRendement').val());
	        var heureUtilisation = parseFloat($('#txtNbHeure').val());
	        var jourUtilisation = parseFloat($('#txtNbJour').val());
	        
	        var tarif = parseFloat($('input[name=grpTarifElectro]:checked').val());
	        var tarifAvecTaxes = tarif * (1 + (data.taxes.TVQ/100)) * (1 + (data.taxes.TPS/100));
	        
	        var consommationEstimee = capacite / rendement / 1000 * heureUtilisation * jourUtilisation;
		    var coutEstimeTotal = consommationEstimee * tarifAvecTaxes / 100;
	        
	        $('#txtConsommationEstimeeCI').val(formatNumber(consommationEstimee.toFixed(1)));
		    $('#txtCoutEstimeCI').val(formatNumber(coutEstimeTotal.toFixed(2)));
		    
	        //affiche les résultats
		    $(this).next().show();
		    //affiche le bandeau
		    $(this).parent().next().show();
	    }
	       
	    return false;
	});
}

function initElectromenager() {
    
    var id = 'ddAppareil';
    
    //get "Appareil" data
	var value = data.electromenager;
	
	//drop down key
	var key = {text:'libelle_' + _lang, value:'consommation'};
	
	var options = {};
	options.data = {key:['type']};
	
	var ddAppareil = createDropDowm(id, key, value, options);
	
	$('#' + id).replaceWith(ddAppareil);
	
	$('#' + id).change(function(e){
	    
	    var $option = $(this).find('option:selected');
	    
        if($option.data('type') == 0) {
            $('#lblPostType').html(_label.appareilElectromenagers[_lang].util);
        }
        else $('#lblPostType').html(_label.appareilElectromenagers[_lang].jour);
        
        
    });
	
	
	$('#btnCalculerElectro').click(function(e){
        
	    e.preventDefault();
	    
	    //affiche le résultat du calcul
	    if($(this).parent().validate()) {
	        
	        var appareil = parseFloat($('#ddAppareil').val());
	        var nbJour = parseFloat($('#txtNbJour').val());
	        
	        var consommation = appareil * nbJour;
	        var tarif = parseFloat($('input[name=grpTarifElectro]:checked').val());
	        
	        var tarifAvecTaxes = tarif * (1 + (data.taxes.TVQ/100)) * (1 + (data.taxes.TPS/100));
	        
	        var coutEstimeTotal = consommation * tarifAvecTaxes / 100;
	        
	        $('#txtConsommationEstimee').val(formatNumber(consommation.toFixed(1)));
		    $('#txtCoutEstime').val(formatNumber(coutEstimeTotal.toFixed(2)));
		    
	        //affiche les résultats
		    $(this).next().show();
		    //affiche le bandeau
		    $(this).parent().next().show();
	    }
	    
	    return false;
	    
    });
}

function initConsommationAnnuelle() {
    
    var id = 'ddNbPersonne';
    
    //drop down key
	var key = {text:'libelle_' + _lang, value:'kWh'};
	
    //get "consommation moyenne/personne eau chaude" data
	var value = data.eauChaudePersonne;
	
	var ddNbPersonne = createDropDowm(id, key, value);
	
	$('#' + id).replaceWith(ddNbPersonne);
	
	$('#btnCalculerConsommationAnnuelle').click(function(e){
	    e.preventDefault();
	    
	    //affiche le résultat du calcul
	    if($(this).parent().validate()) {
	        //get kWh for the number of person(s)
	        var kWh = parseFloat($('#' + id).val());
	        var tarif = parseFloat($('input[name=grpTarifConsommationAnnuelle]:checked').val());
	        
	        //calculate taxes
		    var tvq = tarif * data.taxes.TVQ / 100;
		    var tps = (tarif + tvq) * data.taxes.TPS / 100;
		    
		    //calculate the total
		    var coutEstimeTotal = (tarif + tvq + tps) * kWh / 100;
    		coutEstimeTotal = coutEstimeTotal.toFixed(2) != "NaN" ? coutEstimeTotal.toFixed(2) : "0.00";
		    
		    $('#txtConsommationEstimeeCA').val(formatNumber(kWh));
		    $('#txtCoutEstimeCA').val(formatNumber(coutEstimeTotal));
		    
		    //affiche les résultats
		    $(this).next().show();
		    //affiche le bandeau
		    $(this).parent().next().show();
	    }
	    
	    return false;
	});
}

function initBainsDouche() {
    
    var id = "Qty";
	var value = data.eauChaude;
	var key = {text:'libelle_' + _lang, value:'puissanceMoyenne'};
	
	var radios = createRadioButton(id, key, value);
	$('#' + id).replaceWith(radios);
	
	$('#txtQtyLitre').formatInput(_regexDigitOrComma);
	
	$('#txtQtyLitre').focus(function(e){
	    $('#radQty-3').attr('checked', true);
	});
	
	/*------------------------------------------*/
	
    $('#btnCalculerBainDouche').click(function(e){
        
	    e.preventDefault();
	    
	    //affiche le résultat du calcul
	    if($(this).parent().validate()) {
	        
	        //get kWh for the number of person(s)
	        //Autre est sélectionné, récupère la valeur du textbox
	        if($('input[name=grpQty]:checked').val() == '-1') kWh = parseFloat(replaceCommaForDot($('#txtQtyLitre').val()));
	        else kWh = parseFloat($('input[name=grpQty]:checked').val());
	        
	        var kWh = 4.18/3600 * (60-7) * kWh;
	        kWh = kWh.toString() != "NaN" ? kWh : 0.0;
	        
	        var tarif = parseFloat($('input[name=grpTarifBainDouche]:checked').val());
	        
	        //calculate taxes
		    var tvq = tarif * data.taxes.TVQ / 100;
		    var tps = (tarif + tvq) * data.taxes.TPS / 100;
		    
		    //calculate the total
		    var coutEstimeTotal = (tarif + tvq + tps) * kWh / 100;
    		coutEstimeTotal = coutEstimeTotal.toFixed(2) != "NaN" ? coutEstimeTotal.toFixed(2) : "0.00";
		    
		    $('#txtConsommationEstimeeBD').val(formatNumber(kWh.toFixed(1)));
		    $('#txtCoutEstimeBD').val(formatNumber(coutEstimeTotal));
		    
		    //affiche les résultats
		    $(this).next().show();
		    //affiche le bandeau
		    $(this).parent().next().show();
	    }
	    
	    return false;
	});
}

function initTab() {
    $('ul.tab-bg > li').click(function(e){
        $('ul.tab-bg > li').removeClass('active');
        $(this).addClass('active');
        
        var index = 0;
        for(i = 0; i < $('ul.tab-bg > li').length; i++) if( $($('ul.tab-bg > li')[i]).hasClass('active')) index = i;
        
        $('.l-box-wrap > div').hide().addClass('l-tab-hidden');
        $($('.l-box-wrap > div')[index]).show().removeClass('l-tab-hidden');
    });
}

function initPlusInformation() {
    $('li.l-plus-information > dl > dt > a, ul.l-form > li.l-plus-information > dl > dd > a.l-close').click(function(e){
        e.preventDefault();
        
        var $parentDl = $(this).parent().parent();
        
        if(!$parentDl.hasClass('l-active')){ 
		
		$parentDl.addClass('l-active');
		}
        else {
		$parentDl.removeClass('l-active');
		}
            
        return false;
    });
}

function initTarif() {
    
    //get "tarif" data
	var value = data.tarif;
	
	var key = {text:'nomTarif_' + _lang, value:'cout', moreInfo:'resultat_moreInfo_' + _lang};
	
	$('ul.l-tarif > li.required > div > div').each(function(obj){
	    
	    var id = $(this).attr('id');
	    
	    //texte pour climatisation individuelle et climatisation centrale
        /*if($(this).hasClass("climatisation")) {
            key = {text:'nomTarif_' + _lang, value:'cout', moreInfo:"resultat_moreInfo_climatisation_" + _lang};
        }
        else if($(this).hasClass("piscine-pompe")) {
            key = {text:'nomTarif_' + _lang, value:'cout', moreInfo:"resultat_moreInfo_piscine_pompe_" + _lang};
        }
        else if($(this).hasClass("piscine-chauffage")) {
            key = {text:'nomTarif_' + _lang, value:'cout', moreInfo:"resultat_moreInfo_piscine_chauffage_" + _lang};
        }
        else*/ 
	    
	    var radios = createRadioButton(id, key, value, {key:'moreInfo'});
	    
	    $(this).replaceWith(radios);
	    
	});
	
	$('.l-tarif :input[name^=grpTarif]').click(function(e){
        $(this).parents('.l-tab-content').find('.l-resultat-plus-information').html($(this).data('moreInfo'));
	});

    $('div.l-tarif-more-info').replaceWith(data["tarifMoreInfo_"+_lang]);
	
    
    
}

function initRequired(el/*optional*/) {   
    
    if(el === undefined) el =  $('li.required');
    if (_lang=="fr"){
    el.append('<label class="error">Ce champ est obligatoire</label>');
	}
	else{
		 el.append('<label class="error">This field is mandatory</label>');
	}
}

function initConverstisseur() {
    $('#txtTemperature').keyup(calculateTemperature);
    $('#ddTemperature').change(calculateTemperature);
    calculateTemperature();

    $('#txtLongueur').keyup(calculateLongueur);
    $('#ddLongueur').change(calculateLongueur);
    calculateLongueur();

    $('#txtSuperficie').keyup(calculateSuperficie);
    $('#ddSuperficie').change(calculateSuperficie);
    calculateSuperficie();

    $('#txtVolume').keyup(calculateVolume);
    $('#ddVolume').change(calculateVolume);
    calculateVolume();

    $('#txtVolumeUS').keyup(calculateVolumeUS);
    $('#ddVolumeUS').change(calculateVolumeUS);
    calculateVolumeUS();

    $('#txtPuissance').keyup(calculatePuissance);
    $('#ddPuissance').change(calculatePuissance);
    calculatePuissance();

    $('#txtPuisThermiquekWBtu').keyup(calculatePuisThermiquekWBtu);
    $('#ddPuisThermiquekWBtu').change(calculatePuisThermiquekWBtu);
    calculatePuisThermiquekWBtu();

    $('#txtPuisThermiquekWTonne').keyup(calculatePuisThermiquekWTonne);
    $('#ddPuisThermiquekWTonne').change(calculatePuisThermiquekWTonne);
    calculatePuisThermiquekWTonne();

    $('#txtPuisThermiqueBtuTonne').keyup(calculatePuisThermiqueBtuTonne);
    $('#ddPuisThermiqueBtuTonne').change(calculatePuisThermiqueBtuTonne);

    calculatePuisThermiqueBtuTonne();



    $('#txtMasseKgLb').keyup(calculateMasseKgLb);

    $('#ddMasseKgLb').change(calculateMasseKgLb);

    calculateMasseKgLb();
}

function loadTab() {
    var url = window.location.toString();
    
    var indexOfTab = url.indexOf('#tab');
    
    if(indexOfTab != -1) {
        var index = url.substring(indexOfTab + 4, indexOfTab + 4 + 1);
        
        $('a[href$=#tab'+index+']').click();
    }
}

//fonction appeler sur toutes les calculettes
function initCalculette() {
    
    initTab();
    initPlusInformation();
    loadTab();
    initTarif();
    initRequired();
    initConverstisseur();
    
    $(':input.digits-dot-or-comma-99').formatInput(_regexDigitOrComma);
}

initCalculette();
