/*  Le Phare JavaScript library - (c) 2007
/*--------------------------------------------------------------------------*/

Event.handler = {
   register: function(element) {
      if($(element)) {
         switch (element) {
            case 'pageClassementMC':
            case 'pageDocumentsMC':
            case 'pageNewsMC':
            case 'pageBestLapsMC':
               // recupére le classement !                           
               //get_classement();
               //get_news()
            break;
            default:
               new Fabtabs('tabs');
               navManager();
               new Slideshow('slideShow', 3000);
               my_glider = new Glider('zoneScroll', {duration:0.5});
         }
         
         switch (element) {

            case 'pageContacts':
            case 'pageListeActualites':
                initForm();
            break;

            case 'pageFicheVoiture':
            case 'pageFichePilote':
               new Fabtabs('tabsPilotes');
            break;

            case 'pageMediatheque':
               initFormMediatheque();
               myLightbox = new Lightbox('../../ml/s10_mediatheque/_get_infos_photos.php');
            break;
            
            case 'pageConcurrents':
               initFormConcurrents();
               
            break;
            case 'pageAccesPhotos':
               initFormAccreditation(); // fonction pour gerer le module d'accréditation...
            break;
            case 'pageCommuniques':
               Event.observe('team','change',initLstDeroulante);
            break;
            case 'pageFormAccreditation':
               initAccreditation();
            break;
         }
      }
   } // register
}
   function image_transition(image,tab,tmp)
   {
      oTransition = new Transition( 'holder', image,tab ,tmp);
   }  
// la liste deroulante dans les communiqué de presse Team s09p03
function initLstDeroulante()
{
   if($F('team')=='')$('team').name='';
   
   $('formPresse').submit();
}
// load
Event.observe(window, 'load', function() {
      Event.handler.register(document.body.id);
});

function navManager() {

   $$('li.btnNavLevel1 a').each(function(item){   
     Event.observe(item, 'click', function() {
         var ulId = item.id.camelize();
         
         if ($(ulId)) $(ulId).toggle();
      });
   });

   if($('pageConcept') || $('pageProduitsDerives') || $('pageMichelin') || $('pageCategories') || $('pageConcept') || $('pageOffresPromo')|| $('pageReglement')|| $('pageDrapeaux')) {var ulId = $('u-p2').id.camelize(); $(ulId).toggle();}
   //if($('pageListeActualites') || $('pageDetailActualite')) {var ulId = $('u-p3').id.camelize(); $(ulId).toggle();}
   if($('pageListeParticipants') || $('pageListeTeams') || $('pageListeVoitures') || $('pageListePilotes') || $('pageFicheTeam') || $('pageFicheVoiture') || $('pageFichePilote')) {var ulId = $('u-p4').id.camelize(); $(ulId).toggle();}
   if($('pageAccueilCircuits') || $('pageBilletterie') || $('pageProgramme') || $('pageResultats') || $('pageTV')) {var ulId = $('u-p5').id.camelize(); $(ulId).toggle();}
}

function Slideshow(slideshow, timeout) {
	this.slides = [];
    var nl = $(slideshow).getElementsByTagName('div');
    for (var i = 0; i < nl.length; i++) {
      if (Element.hasClassName(nl[i], 'slide')) {
        this.slides.push(nl[i]);
      }
    }
    for (var i = 0; i < this.slides.length; i++) {
      this.slides[i].style.zIndex = this.slides.length - i;
    }
	this.timeout = timeout;
    this.current = 0;

    Element.show(slideshow);
    setTimeout((function(){this.next();}).bind(this), this.timeout + 850);
  }
Slideshow.prototype = {
    next: function() {
      for (var i = 0; i < this.slides.length; i++) {
        var slide = this.slides[(this.current + i) % this.slides.length];
        slide.style.zIndex = this.slides.length - i;
      }
Effect.Fade(this.slides[this.current], {
afterFinish: function(effect) {
          effect.element.style.zIndex = 0;
          Element.show(effect.element);
          Element.setOpacity(effect.element, 1);
        }
      });
	  this.current = (this.current + 1) % this.slides.length;
      setTimeout((function(){this.next();}).bind(this), this.timeout + 850);
    }
}

function initForm()
{
   if($('zeForm'))
   {
         var zeForm = new Validation('zeForm', {
            useTitles:true, stopOnFirst:true, onFormValidate: function() {$('todo').value = "submit_quest";}
         });

         if($('searchSubmitter')) {
            Event.observe('searchSubmitter', 'click', function() {$('searchTodo').value = "email-subscribe"; $('searchEmailForm').submit();});
         }

         if($('errMsg')) {
            if($('errMsg').innerHTML  != '') {
               Element.show('errMsg'); Effect.BlindUp('errMsg', {delay:3});
            }
         }
   }
   if($('platinium'))
      {
         initFormEligibility();
      }
   }
   function initFormEligibility()
   {
// platinium      
//          Event.observe('platinium','click',function(){
//             $$('.jsCategories').each(function(obj){obj.hide();});
//             $('categoryA').show();
//          });   
// gold
//          Event.observe('gold','click',function(){
//             $$('.jsCategories').each(function(obj){obj.hide();});
//             $('categoryB').show();
//          });
// silver
//          Event.observe('silver','click',function(){
//             $$('.jsCategories').each(function(obj){obj.hide();});
//             $('categoryC').show();
//          });                  
// bronze
//          Event.observe('bronze','click',function(){
//             $$('.jsCategories').each(function(obj){obj.hide();});
//             $('categoryD').show();
//          });                
         
         $$('input[type="radio"]').each(function(obj){
            Event.observe(obj,'click',function(){
               tableau = obj.id.split('_');
               reponse = tableau[0];
               id = 'js';
               for(i=1;i<tableau.length;i++) id += '_'+tableau[i];      
               if($(id))
               {
                  if(reponse == 'yes')
                     $(id).show();
                  else
                     $(id).hide();
               }
            });
            
         });
         gestPlus();         
   }
// fonction qui initialise les boutons plus !
   function gestPlus()
   {
      $$('.jsPlus').each(function(obj){
         Event.observe(obj,'click',function(){
            nb = obj.id.replace('plus_','');
            addChrono(nb);
         })
      });
   }
   function addChrono(id)
   {
      var pars = 'data[cpt]='+id+'&todo=add_chrono';
      var uri = '../s04_contact/s04p05_drivers_eligibility.php';
      var myAjax = new Ajax.Request(uri, {
      method: 'post'
         , parameters: pars
         , onSuccess:function(transport) {
             object=transport.responseText.evalJSON();
             $('plus_'+id).hide();
             
             new Insertion.Bottom('js_ChronoOrder', object.tableau);
             gestPlus();
         }
      });
   }
function initFormMediatheque()
{
         if($('ValidFiltre')) {
            Event.observe('ValidFiltre', 'click', function() {$('FormMediatheque').submit();});
         }

         if($('ValidLog')) {
            Event.observe('ValidLog', 'click', function() {$('FormMediathequeLog').submit();});
         }
         if($('id_annee')){
            Event.observe('id_annee','change', function (){
                  AjaxCircuit()
            });
         }

}
function reportError() {alert('Une erreur est survenue, merci de réessayer ultérieurement.')}
function hideWaitCarac() {$('wait_caract').hide();}

function AjaxCircuit()
{
   var pars =  '?id=1&id_annee=' + $('id_annee').value;
   var uri = '../../ml/s10_mediatheque/_s10p01_ajax.php';
 
   $('wait_caract').show();
   
   var myAjax = new Ajax.Request( uri, 
                                 {
                                    method: 'post'
                                    , parameters: pars
                                    , onFailure: reportError
                                    , onComplete: hideWaitCarac
                                    , onSuccess:function(t) {
                                       var collEnfants = $('id_circuit').childNodes;
                                       // on retire les noeuds enfants existant !
                                       var nb = collEnfants.length;
                                       for(o=nb-1; o>0 ; o--) 
                                       {
                                          if(collEnfants[o].value!="")
                                          {
                                             $('id_circuit').removeChild(collEnfants[o]);
                                          }

                                       }  
                                       
                                       var tampon = eval('(' + t.responseText+ ')');
                                       
                                       for(p=0;p<tampon.length;p++)
                                       {
                                          var opt = document.createElement("option");
                                          tampon[p] = tampon[p].evalJSON();  
                                          opt.value = tampon[p].id;
                                          opt.innerHTML = tampon[p].title;
                                          $('id_circuit').appendChild(opt);
                                       }   
                                    }

                                    
                                 }
                                );
}// AjaxGRL
function initFormConcurrents()
{
         if($('ValidConcurrent')) {
            Event.observe('ValidConcurrent', 'click', function() {$('FormConcurrents').submit();});
         }

}

function showCurPartenaire(id_partenaire)
{
   url = "../../fr/s16_partenaires/s16p02_fiche_partenaire.php?partenaire=" + id_partenaire;
   window.location.href = url;
}
/*
* function initFormAccreditation()
* - Gestion de la confirmation du mail
* - initialisation validate 
*/
function initFormAccreditation()
{
   var zeForm = new Validation('monform', {
      useTitles:true, 
      stopOnFirst:true, 
      onFormValidate:valideFormulaire
   });
   
   Validation.addAllThese([
      ['min-len', 'nb de caractere insuffisante', function(v,elt) {
				var limitmin = elt.getAttribute('min');
				if(elt.value.length>=limitmin)
				return true;
				else
				return false;
			}],
      ['validate-conf-email', 'Incohérence entre votre mot de passe et sa confirmation',
         function(v,elt) {
            var ret = (v == $F('motdepasse'));
            if(!ret) {
               $('motdepasse').value='';
               $('confMotdepasse').value='';
            }
            return (ret);
         }]
         ]);
//   confMotdepasse
}

function valideFormulaire(){
   $('todo').value = "submit_quest";
}

function open_popup_course()
{
   url = "../../en/s54_courses/s54p01_classement.php";
   window.open(url, "race", "width=967,height=800,scrollbars=yes");
}

function goto_annee()
{
   annee = $('menu_annee').value;
   $('saison_encours').value = annee;
   document.frm_archive.submit();
}

function initAccreditation()
{
   if($('jsFreeLance'))
   {
         Event.observe('jsFreeLance','click',function(){
            $("wait_caract").show();
            if($('jsFreeLance').checked)
            { // Si c'est cocher c'est que s'est un freelance
               pageAccreditation(2);
            }
            else
            { //
               pageAccreditation(1);
            }
         });
   }


   initForm_Accreditation();
}

function initForm_Accreditation()
{

   initForm();

    if($('visitor_activite_'))
   {
      Event.observe('visitor_activite_','change',function(){
         if($('visitor_activite_').value==6) $('jsAudience').show();
         else $('jsAudience').hide();
      });

   }

   // gestion de la fonction 
   if($('visitor_fonction_'))
   {
      Event.observe('visitor_fonction_','change',function(){
         if($('visitor_fonction_').value==3) $('jsAutreFonction').show();
         else $('jsAutreFonction').hide();
      });
   }

   // gestion du secteur 
   if($('visitor_secteur_'))
   {
      Event.observe('visitor_secteur_','change',function(){
         if($('visitor_secteur_').value==5) $('jsAutreSecteur').show();
         else $('jsAutreSecteur').hide();
      });
   }

   // gestion des tableaux de course :)
   gest_tableauCourse();
}
// fonction d'ajax permettant de permuter les blocks
function pageAccreditation(pars)
{

   var uri = '../s04_contact/s04p04_accreditation.php?mode='+pars;
   var myAjax = new Ajax.Request(uri, {
   method: 'post'
      , parameters: pars
      , onSuccess:function(transport) {
          Formulaire=transport.responseText;
          $('zeForm').replace(Formulaire);
          $("wait_caract").hide();
          initForm_Accreditation();
         }
   });

}function gest_tableauCourse()
{
   if($('jsTableauCourse'))
   {
      Event.observe('jsTableauCourse','click',function(){
         if($('jsTableauCourse').checked)
         {
            $('jsTouteSaison').show();
            $('choixAcc').hide();
         }
         else
         {
            $('jsTouteSaison').hide();
            $('choixAcc').show();
         }
      });
   }
   if($('jsCheckPiste'))Event.observe('jsCheckPiste','click',function(){checkPiste('jsCheckPiste')});
   if($('jsCheckPitLane'))Event.observe('jsCheckPitLane','click',function(){checkPitLane('jsCheckPitLane')});
   var ladate = new Date()
   var date_Du_Jour = ladate.getFullYear()+''+(ladate.getMonth()+1)+''+ladate.getDate();
   $$('.jsCourse').each(function(obj){
         dateCourse = obj.id.replace('js','');
         if(parseInt(dateCourse,10)<parseInt(date_Du_Jour,10))obj.hide();
   });
}
