// 1) enregistre les informations de fractionnement, formule et option/complements de garantie
// 2) appel CalculerComptant et RecalculerCotisation du MMI auto
// 3) alimente les données automates à partir du retour du métier pour générer le flux tarif

function creerListeOptionsGarantie(ListeOptions)
{
    var listeOptions = new Array();
    try			
    {
        // on récupère un tableau contenant les nom des options
        tabOption = ListeOptions.split("|");
		
        //Trouver la combinaison des options cliquées et la comparer avec les valeurs des données pour toutes les options 
        var indexQuestion = 0;

        // on traite toutes les options
        while (indexQuestion < tabOption.length)
        {
            var garantie = new Object;
            //récupération de la question correspondant à l'option
            var tabOptionsCheckBox = recupereToutesInputReponses(tabOption[indexQuestion]);
			
            // on regarde si la garantie a été checkée
            var isChecked = tabOptionsCheckBox[0].checked;
            // DA.WEB.PS.Automate.Auto.Interface.OptionGarantie
            garantie.Nom = tabOption[indexQuestion];
            if (isChecked)
            {
                garantie.Valeur = tabOptionsCheckBox[0].value;
            }
            else
            {
                garantie.Valeur = "";
            }
            
            listeOptions.push(garantie);
            indexQuestion++;
        }
        return listeOptions;
    }
    catch (Exception) 
    {
        //alert(Exception);
        return null;
    }    
}

function creerListeOptionsComplementGarantie(ListeIdOptions, ListeOptions)
{
    var listeOptions = new Array;
    try			
    {
        // on récupère un tableau contenant les nom des options
        tabOption = ListeOptions.split("|");
        // on récupère un tableau contenant les id des options
        tabIdOption = ListeIdOptions.split("|");
		
        //Trouver la combinaison des options cliquées et la comparer avec les valeurs des données pour toutes les options 
        var indexQuestion = 0;

        // on traite toutes les options
        while (indexQuestion < tabOption.length)
        {
            //récupération de la question correspondant à l'option
            var tabOptionsCheckBox = recupereToutesInputReponses(tabOption[indexQuestion]);
			
            // on regarde si la garantie a été checkée
            var isChecked = tabOptionsCheckBox[0].checked;
            // DA.WEB.PS.Automate.Auto.Interface.OptionGarantie
            var garantie = new Object;
            
            // de x_y on récupère x (id) et y (max niveau), toujours le même
	        var tabIdGarNiv = (tabIdOption[indexQuestion]).split("_");
	        // format 1_1 par exemple, condition fausse si aucune option complément garantie paramétrée
            if( tabIdGarNiv.length == 2 )
            {
		        // on veut savoir si le nombre de niveau est égal à 1 ou supérieur
		        if (tabIdGarNiv[1] == "1")
		        {
                    garantie.Nom = tabOption[indexQuestion];
                    // si l'option est coché, on prend la valeur
                    if (isChecked)
                    {
                        garantie.Valeur = tabOptionsCheckBox[0].value;
                    }
                    // sinon on retourne "" qui sera modifié par la valeur par défaut dans l'automate
                    else
                    {
                        garantie.Valeur = "";
                    }
		        }
		        else
		        {
			        // on a plusieurs niveau, on recherche un selected correspondant à la valeur du complément de garantie choisi
			    //    var libNiveauComplGarantie = tabOptionsCheckBox[1].options[tabOptionsCheckBox[1].selectedIndex].text;
			    //   afficheOption(isChecked, choixTarif, fluxTarif, tabIdGarNiv[0], tabOption[indexQuestion], tabOptionsCheckBox[1].value, libNiveauComplGarantie, isComplement);
			        
			        garantie.Nom = tabOption[indexQuestion];
			        garantie.Niveau = tabOptionsCheckBox[1].value;
			        garantie.Selectionnee = isChecked;
		        }
		        listeOptions.push(garantie);
	        }
            
            indexQuestion++;
        }
        return listeOptions;
    }
    catch (Exception) 
    {
        //alert(Exception);
        return null;
    }    
}

// on n'appelle l'Ajax que si on n'est pas déjà en train de faire un traitement
function RecalculerTarif(formule_fract, listeOptionsGarantie, listeOptionsComplementGarantie, listeOptionsIdComplementGarantie)
{
    
    // TODO : rendre disable les options, fractionnement, et formule
    if (!tarifEnCoursDeTraitement)
    {
        attente();
        tarifEnCoursDeTraitement = true;
        
        var idSession = document.forms["form1"].elements.idSession.value;
        var optionsGarantie = creerListeOptionsGarantie(listeOptionsGarantie);
        var optionsComplementGarantie = creerListeOptionsComplementGarantie(listeOptionsIdComplementGarantie, listeOptionsComplementGarantie);
            
        var formule = "";
        var fractionnement = "";
        // si on a cliqué sur une option
        // la formule, le fractionnement et le ChoixTarif n'ont pas changé
        if (formule_fract != '')
        {
            // si on a changé de fractionnement 
            // la formule n'a pas changée
            // SEUL le fractionnement a changé
            // ChoixTarif sera modifié par le WS
            if (formule_fract == '1' || formule_fract == '2' || formule_fract == '3')
            {
                fractionnement = formule_fract;
            }
            else
            {
            // si on a cliqué sur une formule
            // SEULE la formule est modifiée
            // le fractionnement n'a pas changé
            // ChoixTarif sera modifié par le WS
                var tab = formule_fract.split('_');
                formule = tab[0];
            }
        }
        DA.WEB.PS.MoteurRendu.Auto.Web.Tarif.RecalculerTarif(idSession, optionsGarantie, optionsComplementGarantie, formule, fractionnement, OnRecalculerTarifComplete, OnFailed);
    }
}

function OnRecalculerTarifComplete(resultats)
{
    choixTarif = resultats.ChoixTarif;
    var fluxTarif = CreerXmlDoc("<TARIF>" + resultats.FluxTarif + "</TARIF>");

    selectionnerTarifChoisiDA(choixTarif);
    afficheTarifFractionne();
    initTableauTarifTeamSite('', '', choixTarif,'');
	modififerFormuleChoisieResume(choixTarif);
	afficheOptions(choixTarif, fluxTarif, resultats.ListeOptionsGarantiesQuestion, resultats.ListeIdOptionsGarantiesQuestion, resultats.ListeOptionsComplementGarantieQuestion, resultats.ListeIdOptionsComplementGarantieQuestion);
	afficheCotisTotale(choixTarif,fluxTarif);
	afficheFractionnement(choixTarif, fluxTarif, resultats.MontantComptant30j, resultats.MontantComptant);
	verifierListeComplementOptions();
	if (resultats.ExamenVisuelNecessaire) {
	    viderTexte("apresQuestionChoixTarifExamenVisuelNecessaire");
	    ajouteTexte("Un examen visuel du véhicule vous sera demandé pour assurer définitivement votre véhicule. Vous serez contacté pour une prise de rendez-vous afin d'effectuer cette formalité entièrement gratuite.","apresQuestionChoixTarifExamenVisuelNecessaire", false);
	}
	else
	{
	    viderTexte("apresQuestionChoixTarifExamenVisuelNecessaire");
	}
	finAttente();
	tarifEnCoursDeTraitement = false;
}

function modififerFormuleChoisieResume(choixTarif)
{
    var formuleChoisie = document.getElementById('divFormuleChoisie');
    var sFormuleChoisie = ( choixTarif.indexOf('FTiers')> -1 ? "Au tiers" : "Tous risques" );
    if (formuleChoisie.innerText != sFormuleChoisie)
    {
        afficheFormuleChoisieResume(choixTarif);
    }
}