// Gestion centralisé du javascript du dossier PASS-TRAVAUX
// 

Event.observe(window,'load', gestionPassTravaux);

var toUrls23p08='../s23_renovation/s23p08_personnalisation.php';
var toUrls23p09='../s23_renovation/s23p09_saisie_dossier.php';

function gestionPassTravaux()
{
   // PASS-TRAVAUX
   if($('s23p06Form')) {
      var zeForm = new Validation('s23p06Form', {
         useTitles:true,
         stopOnFirst:false,
         onFormValidate: function() {

            $('todo').value = "testEligibilite";

            $('s23p06Form').action = '../s23_renovation/s23p06_eligibilite.php';
         }
      });
      
      

      Event.observe('ouiTravPro', 'click', function() {$('tip_castors').hide();});
      Event.observe('nonTravPro', 'click', function() {$('tip_castors').show();});

      // s23p06 . Tooltip
      if($('tip_castors')) {
         new Tip('tip_castors', 'Si vous êtes membre des castors, veuillez prendre contact avec le COVECOL au 02.51.05.98.47');
      }

   }

   // Eligible
   if($('s23p06FormE')) {
      Event.observe('lienEligible', 'click', function() {$('todo').value='begin';$('s23p06FormE').action = toUrls23p08; $('s23p06FormE').submit();});
   }
   
   // creation PASS-TRAVAUX
   // saisie du mail 
   if($('s23p08Form')) {
      var zeForm = new Validation('s23p08Form', {
         useTitles:true,
         stopOnFirst:false,
         onFormValidate: function() {
            $('todo').value = "create";
            $('s23p08Form').action = toUrls23p08;
         }
      });

      Validation.addAllThese([
         ['validate-conf-email', 'Confirmation incorrecte.',
         function(v,elt) {
            var ret = (v == $F('data_email_'));
            return (ret);
         }]
      ]);
      // blocage de copier coller
      Event.observe('confEmail','keypress',function(event){
            if(event.charCode==118 && event.ctrlKey) Event.stop(event);         
      });
      Event.observe('confEmail','change', function(event){
         if(event.charCode==118 && event.ctrlKey) Event.stop(event);
      });
   }// fin de la saisie du mail ! rediriger vers s20p08_perso
   

      //Verification des formulaires, à partir de là on redirige toujours sur s20p09 !!!!
     if($('caseFileForm')) {
         var zeForm = new Validation('caseFileForm', {
         useTitles:true,
         stopOnFirst:false,
         onFormValidate: function() {
                                       $('todo').value = "next";
                                       $('caseFileForm').action = toUrls23p09;
                                    }
         });
         
      //Si le bouton annuler existe
         if($('btnAnnuler')) {
            Event.observe('btnAnnuler', 'click', function() {
               if(confirm('Si vous annulez la saisie de votre dossier, celui-ci sera définitivement perdu.\n\nSouhaitez-vous abandonner la saisie votre dossier ?'))
               {
                  $('todo').value = "cancel";
                  $('caseFileForm').action = toUrls23p09;
                  $('caseFileForm').submit();
               }
            });
         }
         // si on clique sur btnEnregistrer ON enregistre
         if($('btnEnregistrer')) {
            Event.observe('btnEnregistrer', 'click', function() {
               if(confirm('Votre dossier restera accessible 2 mois à compter de la date de création de votre dossier.\n\n- Cliquez sur OK pour enregistrer votre dossier.\n- Cliquez sur Annuler pour continuer à saisir votre dossier.')) {
                  $('todo').value = "save";
                  $('caseFileForm').action = toUrls23p09;
                  $('caseFileForm').submit();
               } else {return false;}
            });
         }
               
         if($('btnEnregistrerComplet')) {
            Event.observe('btnEnregistrerComplet', 'click', function() {
               $('todo').value = "save";
               $('caseFileForm').action = toUrls23p09;
               $('caseFileForm').submit();
            });
         }      
         // si on appuye sur le bouton suivant ... on va à l'étape suivante!
         if($('btnEtapeSuivante')) {
            Event.observe('btnEtapeSuivante', 'click', function() {
               $('todo').value = "next";
               $('caseFileForm').action = toUrls23p09;
            });
            Event.observe('btnEtapeSuivante', 'click', zeForm.validate.bindAsEventListener(zeForm));
         }
         // si on appuye sur le bouton finaliser      
         if($('btnFinaliser')) {
            Event.observe('btnFinaliser', 'click', function() {
               $('todo').value = "next";
               $('caseFileForm').action = toUrls23p09;
               $('caseFileForm').submit();
            });
         }
         if($('btnCommencerSaisie')) {
            Event.observe('btnCommencerSaisie', 'click', function() {
               $('todo').value='next';
               $('caseFileForm').action = toUrls23p09;
               $('caseFileForm').submit();
            });
         }
         if($('errMsg')) {
            if($('errMsg').innerHTML  != '') {
               Element.show('errMsg'); Effect.BlindUp('errMsg', {delay:3});
            }
         }

   /** 3_1 . */
   function calcTotRevenus() {
      // init values
      var smn = $F('data_salaire_mensuel_net_');
      var bs = $F('data_base_salaire_');
      var ar = $F('data_autres_revenus_');
      // replace , by .
      var smn=smn.replace(',','.');
      var ar = ar.replace(',','.');
      // check if is number;
      smn = (isNaN(smn) || smn.length==0) ? '' : parseInt(smn, 10);
      bs = (isNaN(bs) || bs.length==0) ? 12 : parseInt(bs,10);
      ar = (isNaN(ar) || ar.length==0) ? '' : parseInt(ar,10);
      // calc total revenus
      if(smn.length!=0 && bs.length!=0 && ar.length!=0) {
            $('data_total_revenus_').value = (parseInt(smn,10) * parseInt(bs,10)) + parseInt(ar,10);}
      // set values
      $('data_salaire_mensuel_net_').value = smn;
      $('data_base_salaire_').value = bs;
      $('data_autres_revenus_').value = ar;
   }


   function calcCoTotRevenus() {
      // init values
      var smn = $F('data_co_salaire_mensuel_net_');
      var bs = $F('data_co_base_salaire_');
      var ar = $F('data_co_autres_revenus_');
      // replace , by .
      var smn=smn.replace(',','.');
      var ar = ar.replace(',','.');
      // check if is number;
      smn = (isNaN(smn) || smn.length==0) ? '' : parseInt(smn, 10);
      bs = (isNaN(bs) || bs.length==0) ? 12 : parseInt(bs,10);
      ar = (isNaN(ar) || ar.length==0) ? '' : parseInt(ar,10);
      // calc total revenus
      if(smn.length!=0 && bs.length!=0 && ar.length!=0) {
            $('data_co_total_revenus_').value = (parseInt(smn,10) * parseInt(bs,10)) + parseInt(ar,10);}
      // set values
      $('data_co_salaire_mensuel_net_').value = smn;
      $('data_co_base_salaire_').value = bs;
      $('data_co_autres_revenus_').value = ar;
   }
   

   if($('data_total_revenus_')) {
      calcTotRevenus();
      Event.observe('data_salaire_mensuel_net_', 'change', calcTotRevenus);
      Event.observe('data_base_salaire_', 'change', calcTotRevenus);
      Event.observe('data_autres_revenus_', 'change', calcTotRevenus);
      Event.observe('data_total_revenus_', 'change', calcTotRevenus);
   }

   if($('data_co_total_revenus_')) {
      calcCoTotRevenus();
      Event.observe('data_co_salaire_mensuel_net_', 'change', calcCoTotRevenus);
      Event.observe('data_co_base_salaire_', 'change', calcCoTotRevenus);
      Event.observe('data_co_autres_revenus_', 'change', calcCoTotRevenus);
      Event.observe('data_co_total_revenus_', 'change', calcCoTotRevenus);
   }
      
   if($('data_sante_q8_date_')) {
      var calDateCoNaissance =  Calendar.setup({inputField:"data_sante_q8_date_", displayArea : "data_sante_q8_date_trigger", button:"data_sante_q8_date_trigger", ifFormat:"dd/mm/y", mondayFirst:true, onSelect:setDate});}
      if($('data_sante_co_q8_date_')) {
         var calDateCoNaissance =  Calendar.setup({inputField:"data_sante_co_q8_date_", displayArea : "data_sante_co_q8_date_trigger", button:"data_sante_co_q8_date_trigger", ifFormat:"dd/mm/y", mondayFirst:true, onSelect:setDate});}
   }

      
   // gestion de la pré-personnalisation !
   if($('data_GRL_')) {
      Event.observe('data_GRL_', 'click', function() {
         if($('data_GRL_').checked == true)
            Field.enable('AGDG');
         else
         { 
            Field.disable('AGDG');
            // si le champ AGDG est disable on coche la case Loca Pass
            $('AGDG').checked=true;
            $('data_AGDG_').value=1;
            // et on affiche les frais d'agence
            $('fraisDagence').show(); 
         }
      });

      if($('AGDG'))
      {
         if($('AGDG').checked==false)
         {
               $('fraisDagence').hide();
               $('data_mt_frais_agence_').value = '';
               $('data_AGDG_').value=0;
         }
         Event.observe('AGDG', 'click', function() {
            if($('AGDG').checked == true) 
            {
               $('fraisDagence').show();
               $('data_AGDG_').value=1;
            } 
            else 
            {
               $('fraisDagence').hide();
               $('data_mt_frais_agence_').value = '';
               $('data_AGDG_').value=0;
            }
         });
      }
   }
   
   
   if($('data_PCFA_') && $('montantPCFA')) {
      // si ce champ existe et qu'on recharge la page en le cochant il faut que le montant soit toujours afficher
      if($('data_PCFA_').checked==false)
      {
         $('montantPCFA').hide();
         $('data_mt_frais_agence_').value = '';
      }   
      else
      {
         $('montantPCFA').show();         
      }    
      // si on coche la case l'input
      Event.observe('data_PCFA_', 'click', function() {
         if($('data_PCFA_').checked==false)
         {  // si c'est decoché on vire la valeur !
            $('montantPCFA').hide();
            $('data_mt_frais_agence_').value = '';
         }   
         else
            $('montantPCFA').show();         
         
      });
   }
   

   if($('s20p07Form')) {
      var zeForm = new Validation('s20p07Form', {
         useTitles:true,
         stopOnFirst:false,
         onFormValidate: function() {
            $('todo').value = "begin";
            $('s20p07Form').action = '../s20_location/s20p08_personnalisation.php';
         }
      });
      
      Validation.addAllThese([
         ['validate-PFCA', 'Le montant est plafonné à 150€ maxi',
         function(v,elt) {
            return ($('data_PCFA_').checked == false) || ( $('data_PCFA_').checked == true && !Validation.get('IsEmpty').test(v) && Validation.get('validate-int').test(v) && v<=150 );
         }]
      ]);
      
   }
   
   
   // 1_2 . Tooltip
   if($('tip_nb_pers_a_charge_')) {
      new Tip('tip_nb_pers_a_charge_', 'Toute personne rattachée au foyer fiscal.');
   }

   // 1_3 . Tooltip
   if($('tip_phone_')) {
      new Tip('tip_phone_', 'Vous devez renseigner au moins un n° de téléphone, <strong>fixe</strong> ou <strong>mobile</strong>.');
   }
   if($('tip_co_phone_')) {
      new Tip('tip_co_phone_', 'Vous devez renseigner au moins un n° de téléphone, <strong>fixe</strong> ou <strong>mobile</strong>.');
   }

   // 1_3 . Pre-remplissage des champs
   if($('data_phone_') && $('data_co_phone_')) {
      Event.observe('data_phone_','change', function(){
         if($F('data_co_phone_') == '') $('data_co_phone_').value=$F('data_phone_');
      });
   }
   
   if($('data_address_') && $('data_co_address_')) {
      Event.observe('data_address_','change', function(){
         if($F('data_co_address_') == '') $('data_co_address_').value=$F('data_address_');
      });
   }

   if($('data_comp_address_') && $('data_co_comp_address_')) {
      Event.observe('data_comp_address_','change', function(){
         if($F('data_co_comp_address_') == '') $('data_co_comp_address_').value=$F('data_comp_address_');
      });
   }

   if($('data_zipcode_') && $('data_co_zipcode_')) {
      Event.observe('data_zipcode_','change', function(){
         if($F('data_co_zipcode_') == '') $('data_co_zipcode_').value=$F('data_zipcode_');
      });
   }

   if($('data_city_') && $('data_co_city_')) {
      Event.observe('dataCity_','change', function(){
         if($F('dataCoCity_') == '') $('dataCoCity_').value = $('data_co_city_').value = $F('data_city_');
      });
   }

   /** 1_4. ctrl emploi en f° de la situat° pro si pas salarie on cache, sinon on montre */
   function toogleEmploi(situation_pro) {

      if($(situation_pro).value=='' || $(situation_pro).value>2) $$('.corequis').each(function(obj){obj.hide();});
      else $$('.corequis').each(function(obj){obj.show();});
   }

   function enableDisableEmploi(situation_pro) {
         if($(situation_pro).value=='' || $(situation_pro).value>2) {
            $$('.requis').each(function(obj){obj.disable();}); //si pas salarie on cache
            }
         else
            $$('.requis').each(function(obj){obj.enable();}); // sinon on montre
   }

   if($('data_situation_pro_')) {
      toogleEmploi('data_situation_pro_');
      Event.observe('data_situation_pro_','change', function(){enableDisableEmploi('data_situation_pro_');});
   }

   if($('data_co_situation_pro_')) {
      toogleEmploi('data_co_situation_pro_');
      Event.observe('data_co_situation_pro_','change', function(){toogleEmploi('data_co_situation_pro_');});
   }



   

   // 4_1 . Tooltip
   if($('data_PC_montant_')) {
      new Tip('tip_PC_montant_', 'Le montant du prêt COVECOL qui vous est attribué est calculé en fonction de votre revenu imposable de l\'année n-2 et du nombre de personnes composant le ménage.');
   }

   if($('data_PC_duree_')) {
      new Tip('tip_PC_duree_', 'Le durée maximale est de 120 mois.');
   }

   // 2_1 . On gere ici le montant du depot de garantie par défaut le montant du loyer hors charge
   if($('data_L_mt_hors_charges_')) {
      Event.observe('data_L_mt_hors_charges_','blur', function(){
         if($F('data_L_mt_depot_garantie_') == '') {
            $('data_L_mt_depot_garantie_').value = $('data_L_mt_hors_charges_').value;
         }
      });
   }

   if($('data_T_date_demarrage_')) {
      var calDateDemarrage =  Calendar.setup({inputField:"data_T_date_demarrage_", displayArea : "data_T_date_demarrage_trigger", button:"data_T_date_demarrage_trigger", ifFormat:"dd/mm/y", mondayFirst:true, onSelect:setDate});}


   // 3_1 . Tooltip
   if($('tip_rib_titulaire_')) {
      new Tip('tip_rib_titulaire_', 'Préciser le nom et le prénom.');
   }


   // 4_1 . calcul de la mensualité du pret COVECOL
   if($('data_PC_montant_')) {

      var ret = getMensualite($F('data_PC_montant_'), 1.5, $F('data_PC_duree_'));
      if(ret == $F('data_PC_montant_')) $('data_PC_duree_').value = 1;
      $('data_PC_mensualite_').value = roundDec(ret,2);

      ['data_PC_montant_','data_PC_duree_'].each(function(e){
         Event.observe(e, 'change', function(){
            var ret = getMensualite($F('data_PC_montant_'), 1.5, $F('data_PC_duree_'));
            if(ret == $F('data_PC_montant_')) $('data_PC_duree_').value = 1;
            $('data_PC_mensualite_').value = roundDec(ret,2);
         });
      });
   }


   // 4_1 . calcul du total financement
   function calcTotalFinancement() {
         $('data_total_financement_').value = roundDec($F('data_apport_personnel_'), 0) + roundDec($F('data_PC_montant_'), 0) + roundDec($F('data_PB_montant_'), 0);
   }

   if($('data_PB_montant_')) {
      ['data_PB_montant_','data_apport_personnel_'].each(function(e){
         Event.observe(e,'change', calcTotalFinancement);
      });
   }
   

   // Proposition automatique de la liste déroulante, en fonction du montant du depot de garantie
   if($('data_L_mt_depot_garantie_')) {

      Event.observe('data_L_mt_depot_garantie_','change', function(){

         if( $F('data_L_mt_depot_garantie_') != '') {

            var calc = $F('data_L_mt_depot_garantie_')/15;

            $('L_duree_rbt_').selectedIndex = 0;

            if(calc > 36) {
               $('L_duree_rbt_12').show();$('L_duree_rbt_18').hide();
               $('L_duree_rbt_24').show();$('L_duree_rbt_36').hide();
            }
            else if(calc < 24) {
               $('L_duree_rbt_12').show();$('L_duree_rbt_18').show();
               $('L_duree_rbt_24').hide();$('L_duree_rbt_36').hide();
            }
            else {
               $('L_duree_rbt_12').show();$('L_duree_rbt_18').hide();
               $('L_duree_rbt_24').show();$('L_duree_rbt_36').hide();
            }
         }

      });

      new Tip('tip_L_mt_depot_garantie_', 'Montant du dépôt de garantie à financer.');
   }



   if($('colocataire'))
   {
//$('colFieldB').toggle();
      Event.observe('colocataire','click', function(){
         
         if($('colocataire').checked == true)
         {
            $('colFieldB').hide();
            
         }         
         else
         {
            $('colFieldB').show();
            
         }
      });   
   }

   
   /*****************************************************************/
   // verification de l'emploi
   /*****************************************************************/
   if($('data_situation_pro_'))
   {   
      if($('data_situation_pro_').value=='' || $('data_situation_pro_').value>2 )
      {
         $$('span.requis').each(function(obj){obj.hide();});
         
         
      }
      Event.observe('data_situation_pro_','change', function(){
         if($('data_situation_pro_').value=='' || $('data_situation_pro_').value>2) //si pas salarie
         {
               $$('.asterequis').each(function(obj){obj.hide();});
               $$('input.requis').each(function (obj){obj.removeClassName('required')});
               $$('input.radio_requis').each(function(obj){obj.removeClassName('validate-input-radio');});
         }
         else
         {
               // afficher les em contenant (*)
               $$('.asterequis').each(function(obj){obj.show();});
               // ajouter la classe validate-input-radio a un seul champs !         
               var intNbTour = 0;
               $$('input.radio_requis').each(function(obj){
                  if(intNbTour==0)
                  {
                     intNbTour=1;
                     obj.addClassName('validate-input-radio');
                  }
               });
               // ajout de la classe required sur les inputs !
               $$('input.requis').each(function (obj){
                  obj.addClassName('required');
               });
         }
      });
   }
   if($('data_co_situation_pro_'))
   {   
      Event.observe('data_co_situation_pro_','change', function(){
         if($('data_co_situation_pro_').value=='' || $('data_co_situation_pro_').value>2) //si sans emploi
         {
               $$('.coasterequis').each(function(obj){obj.disable();});
               $$('input.corequis').each(function (obj){obj.removeClassName('required')});
               $$('input.radio_corequis').each(function(obj){obj.removeClassName('validate-input-radio');});
         }
         else
         {
               // afficher les em contenant (*)
               $$('.coasterequis').each(function(obj){obj.show();});
               // ajouter la classe validate-input-radio a un seul champs !         
               var intNbTour = 0;
               $$('input.radio_corequis').each(function(obj){
                  if(intNbTour==0)
                  {
                     intNbTour=1;
                     obj.addClassName('validate-input-radio');
                  }
               });
               // ajout de la classe required sur les inputs !
               $$('input.corequis').each(function (obj){
                  obj.addClassName('required');
               });         
         }
      });
   }

         Validation.addAllThese([
         ['validate-tel', 'Veuillez saisir soit un numéro de fixe ou un numéro de portable',
         function(v,elt) {
            var retourne=false;
            $$('input.validate-tel').each(function(obj){
               if(obj.value!='')retourne=true;
            });
            return retourne;
         }]
      ]);
         Validation.addAllThese([
         ['validate-tel-co', 'Veuillez saisir soit un numéro de fixe ou un numéro de portable',
         function(v,elt) {
            var retourne=false;
            $$('input.validate-tel-co').each(function(obj){
               if(obj.value!='')retourne=true;
            });
            return retourne;
         }]
      ]);
}