// Gestion centralisé du javascript du dossier PASS-LOCATAIRE
// 

Event.observe(window,'load', gestionLocaPass);

var toUrls20p08='../s20_location/s20p08_personnalisation.php';
var toUrls20p09='../s20_location/s20p09_saisie_dossier.php';

function gestionLocaPass()
{

   // S20P09 : pageVotreLogement 
   if($('pageVotreLogement'))
   {
      Event.observe('data_L_surface_', 'change', function() {$('data_L_surface_').value = $F('data_L_surface_').replace(",",".");}, false);
   }
   
   // PASS-LOCATAIRE
   if($('s20p06Form')) {
      var zeForm = new Validation('s20p06Form', {
         useTitles:true,
         stopOnFirst:true,
         onFormValidate: function() {

            $('todo').value = "testEligibilite";

            $('s20p06Form').action = '../s20_location/s20p06_eligibilite.php';
         }
      });
      
      Event.observe('hlm', 'click', function() {$('complementParcSocial').show();});
      Event.observe('prive', 'click', function() {$('complementParcSocial').hide();});
   }

   // Eligible
   if($('s20p06FormE')) {
      Event.observe('lienEligible', 'click', function() {$('todo').value='pre-perso';
      $('s20p06FormE').action = '/fr/s20_location/s20p07_pre-personnalisation.php';
      $('s20p06FormE').submit();});
   }
   // creation LOCA-PASS
   // saisie du mail 
   if($('s20p08Form')) {
      var zeForm = new Validation('s20p08Form', {
         useTitles:true,
         stopOnFirst:true,
         onFormValidate: function() {
            $('todo').value = "create";
            $('s20p08Form').action = toUrls20p08;
         }
      });

      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:true,
         onFormValidate: function() {
                                       $('todo').value = "next";
                                       $('caseFileForm').action = toUrls20p09;
                                    }
         });
      //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 = toUrls20p09;
                  $('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 = toUrls20p09;
                  $('caseFileForm').submit();
               } else {return false;}
            });
         }
               
         if($('btnEnregistrerComplet')) {
            Event.observe('btnEnregistrerComplet', 'click', function() {
               $('todo').value = "save";
               $('caseFileForm').action = toUrls20p09;
               $('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 = toUrls20p09;
            });
            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 = toUrls20p09;
               $('caseFileForm').submit();
            });
         }
         if($('btnCommencerSaisie')) {
            Event.observe('btnCommencerSaisie', 'click', function() {
               $('todo').value='next';
               $('caseFileForm').action = toUrls20p09; 
               $('caseFileForm').submit();
            });
         }
         if($('errMsg')) {
            if($('errMsg').innerHTML  != '') {
               Element.show('errMsg'); Effect.BlindUp('errMsg', {delay:3});
            }
         }
   }

   /** 1_5 . */
   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) * 12);}
      // 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);
   }


   
   
// 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:true,
         onFormValidate: function() {
            $('todo').value = "begin";
            $('s20p07Form').action = '../s20_location/s20p08_personnalisation.php';
         }
      });
      
      Validation.addAllThese([ // plus utilisé...
         ['validate-PFCA', 'Le montant pris en charge par le COVECOL 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>.');
   }


   // 3_1 . Tooltip
   if($('tip_rib_titulaire_')) {
      new Tip('tip_rib_titulaire_', 'Préciser le nom et le prénom.');
   }
   

// 2_1 . On gere ici le montant du depot de garantie par défaut le montant du loyer hors charge
if($('data_L_mt_depot_garantie_') && $('data_L_mt_hors_charges_')) {
   // Proposition automatique de la liste déroulante, en fonction du montant du depot de garantie
   // on crée des variables globales pour stocker les <option> de duree de remboursement
   var opt3_L_duree_rbt_ = $('L_duree_rbt_').options[3];
   var opt4_L_duree_rbt_ = $('L_duree_rbt_').options[4];
   var opt5_L_duree_rbt_ = $('L_duree_rbt_').options[5];

   setListDuree()

   Event.observe('data_L_mt_charges_','change', setListDuree);
   Event.observe('data_L_mt_hors_charges_','change', setListDuree);
   Event.observe('data_L_mt_depot_garantie_','change', setListDuree);

   new Tip('tip_L_mt_depot_garantie_', 'Montant du dépôt de garantie à financer.');
}


function calcMtDepotGarantie() {
   if($F('data_L_mt_hors_charges_') == '') return;
   if($F('data_L_mt_charges_') == '') $('data_L_mt_charges_').value=0;
   $('data_L_mt_depot_garantie_').value = parseInt($F('data_L_mt_hors_charges_'),10);
}


function setListDuree() {
   // on calcule le dépot de garantie
   calcMtDepotGarantie();
   
   if( $F('data_L_mt_depot_garantie_') != '')
   {
      var mtDG = parseInt($F('data_L_mt_depot_garantie_'),10);

      $('L_duree_rbt_').options[3]=opt3_L_duree_rbt_;
      $('L_duree_rbt_').options[4]=opt4_L_duree_rbt_;
      $('L_duree_rbt_').options[5]=opt5_L_duree_rbt_;

      if(mtDG <540) { $('L_duree_rbt_').options[5] = null;}
      if(mtDG <360) { $('L_duree_rbt_').options[4] = null;}
      if(mtDG <270) { $('L_duree_rbt_').options[3] = null;}
   }
}

   if($('L_duree_rbt_')) {
   
      Event.observe('L_duree_rbt_','change', function(){
            $('data_L_duree_rbt_').value = $F('L_duree_rbt_');
         });
   }



   if($('colocataire'))
   {
      if($('colocataire').checked == true)
      {
         $('colFieldB').show();
         $('data_co_locataire_').value=1;
      }   
      else
      {
         $('colFieldB').hide();
         $('data_co_locataire_').value=0;
      }
      Event.observe('colocataire','click', function(){
         $('colFieldB').toggle();
         if($('colocataire').checked == true)
         {
            $$('#colFieldB input').each(function(obj){
               obj.value='';
            });
            $('data_co_locataire_').value=1;
         }         
         else
         {
            $('data_co_locataire_').value=0;
         }
      });   
   }

   
   /** 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) {
            $('messageNonSalarie').show();
            $$('.requis').each(function(obj){
                  obj.removeClassName('required');
                  obj.removeClassName('radio_requis');
                  obj.disable();
               }); //si pas salarie on cache
               $('data_date_embauche_a_').removeClassName('validate-date-annee');
         }
         else {
            $('messageNonSalarie').hide();
            $$('.requis').each(function(obj){obj.enable();}); // sinon on montre
            
            $$('input[name="data[type_contrat]"]').each(function(elt) {
               elt.addClassName('validate-input-radio');
            });
            // on ajoute les classes de conrôle js
            ['data_nom_employeur_', 'data_address_employeur_', 'data_zipcode_employeur_', 'data_city_employeur_', 'data_date_embauche_j_', 'data_date_embauche_m_', 'data_date_embauche_a_'].each(function(idElt) {
               $(idElt).addClassName('required');
            });

            $('data_date_embauche_a_').addClassName('validate-date-annee');
         }
   }

   if($('data_situation_pro_')) {
      //toogleEmploi('data_situation_pro_');
      enableDisableEmploi('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_');});
   }

   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;
      }]
   ]);
   */
}