var nav_finished = true;
var nav_current_item = 'tagcloud';
//nav_current_item = 'nav-secteurs';
//nav_current_item = 'nav-metiers';
var queue = false;

/**
 * Quick tabs
 */
var Qtab = {
    id: 'quicktab-container',
    prefix: 'quicktab-',
    $ctn: null,
    duration: 500,

    init: function() {
        // Nothing to do here
        this.$ctn = $('#'+this.id);
    },

    show: function(id) {
        $id = $('#'+ this.prefix + id);

        // Clic sur l'element affiche actuel : on le cache
        if (this.$ctn.find('#'+ this.prefix + id + ':visible').length) {
            this.$ctn.find('.qtab:visible').slideUp(this.duration);
            $('#tabs .on').removeClass('on');
        } else {
            // Element actuellement affiche
            this.$ctn.find('.qtab:visible').not('#'+ this.prefix + id).slideUp(this.duration);
            $('#tabs .on').removeClass('on');
            // Affichage de l'element demande
            if ($id.length) {
                $id.slideDown(this.duration);
                $('#tab-'+id).addClass('on');
            }
        }
    }
};

$.fn.fixHover = function() {
    return this.mouseover(function(){
        $(this).addClass('hover');
    }).mouseout(function() {
        $(this).removeClass('hover');
    });
}

/**
 * INSCRIPTION RAPIDE
 */
function UserValidationInscriptionRapide(theForm) {
    if (jQuery('#insc_rapide_part_prse_id').val() == '') {
        alert("Vous devez sélectionner une formation");
        return false;
    }
    if (!TesteChaine(theForm.elements['part_nom'], 'Nom', 255, true)) {
        return false;
    }
    if (!TesteChaine(theForm.elements['part_prenom'], 'Prénom', 255, true)) {
        return false;
    }
    if (!TesteEMail(theForm.elements['part_email'], 'Email', true)) {
        return false;
    }
    if (!TesteChaine(theForm.elements['part_telephone'], 'Téléphone', 20, true)) {
        return false;
    }
    return true;
}

jQuery(document).ready(function() {
    /*jQuery('.example_text').example(function() {
        return $(this).attr('title');
    }, {className: 'example_text'});*/

    jQuery('#btn_inscription_rapide').click(function() {

        if (UserValidationInscriptionRapide(document.theFormInscRapide)) {
            if (EN_PROD) {
                alert("Fonctionnalité en cours de dev");
                jQuery('#tab-inscription').click();
                document.theFormInscRapide.reset();
            } else {
                jQuery.ajax({
                    type: "POST",
                    url: BASE_URL+"ajax/ef/inscription_rapide.php",
                    data: jQuery('form[name="theFormInscRapide"]').serialize(),
                    success: function(msg) {
                        if (msg == 'ok') {
                            alert('Votre pré-inscription a bien été prise en compte');
                            jQuery('#tab-inscription').click();
                            document.theFormInscRapide.reset();
                        } else {
                            alert('Une erreur s\'est produite lors de votre pré-inscription.');
                        }
                    }
                });
            }
        }
    });

    jQuery("#insc_rapide_search_reference").autocomplete(BASE_URL+"ajax/ef/inscription_rapide.php", {
        width: 650,
        extraParams: {type_recherche: 'reference'},
        selectFirst: false,
        max: 20,
        minChars: 2
    }).result(function(event, item) {
        jQuery('#insc_rapide_search_full_text').val(item[0]).removeClass('example_text');
        jQuery('#insc_rapide_part_prse_id').val(item[1]);
        jQuery('#insc_rapide_search_reference').val(item[2]);
        jQuery('#cate_id').val(item[3]);
        jQuery('#ref').val(item[4]);
        jQuery('#prod_pere_id').val(item[5]);
    });

    jQuery("#insc_rapide_search_full_text").autocomplete(BASE_URL+"ajax/ef/inscription_rapide.php", {
        width: 650,
        extraParams: {type_recherche: 'full_text'},
        selectFirst: false,
        max: 20,
        cacheLength: 1,
        minChars: 2
    }).result(function(event, item) {
        jQuery('#insc_rapide_search_full_text').val(item[0]);
        jQuery('#insc_rapide_part_prse_id').val(item[1]);
        jQuery('#insc_rapide_search_reference').val(item[2]).removeClass('example_text');
        jQuery('#cate_id').val(item[3]);
        jQuery('#ref').val(item[4]);
        jQuery('#prod_pere_id').val(item[5]);
    });
});
/**
 * Inscription Rapide /END
 */

/**
 * RECHERCHE AVANCEE
 * @David
 */
 function cocher() {
     var nb = $('.ui-helper-hidden-accessible:checked').length;
     if (nb > 0 ) {
         $('.ui-helper-hidden-accessible').each(function() {
             $(this).attr('checked',false);
             $(this).parent().removeClass('on');
             var cheched = $(this).parent().find('.ui-checkbox_on');
             $(cheched).removeClass('ui-checkbox_on');
             $(cheched).addClass('ui-checkbox_off');
         });
         $('#tous-aucun').attr('checked', false);
     } else {
         $('.ui-helper-hidden-accessible').each(function() {
             $(this).attr('checked',true);
             $(this).parent().addClass('on');
             var cheched = $(this).parent().find('.ui-checkbox_off');
             $(cheched).addClass('ui-checkbox_on');
             $(cheched).removeClass('ui-checkbox_off');
         });
         $('#tous-aucun').attr('checked', true);
     }
  }
  function on_checkbox_click() {
      if ($(this).hasClass('ui-checkbox_off')) {
          $(this).parent().find('.ui-helper-hidden-accessible').attr('checked',true);
          $(this).removeClass('ui-checkbox_off');
          $(this).addClass('ui-checkbox_on');
          $(this).parent().addClass('on');
      } else {
          $(this).parent().find('.ui-helper-hidden-accessible').attr('checked',false);
          $(this).removeClass('ui-checkbox_on');
          $(this).addClass('ui-checkbox_off');
          $(this).parent().removeClass('on');
      }
  }

  $(document).ready(function () {
      $('span.ui-checkbox_on').click(on_checkbox_click);
  });

  function checkbox_mot_click(id) {
      if ($('#'+id).hasClass('ui-checkbox_off')) {
          $('#'+id).parent().find('.ui-helper-hidden').attr('checked',true);
          $('#'+id).removeClass('ui-checkbox_off');
          $('#'+id).addClass('ui-checkbox_mot_on');
          $('#'+id).parent().parent().find('.ui-helper-hidden').each(function() {
              if ( $(this).val() != id) {
                  $(this).parent().find('span').removeClass('ui-checkbox_mot_on');
                  $(this).parent().find('span').addClass('ui-checkbox_off');
              }
          });
      }
  }

  function validation(form) {
      var tab_checked_niv1 = '';
      var tab_mot_checked = '';
      var date = form.date.value;
      var duree = form.duree.value;
      var mot_cle = form.mot_cle.value
      $('#sectorielle ul li .ui-helper-hidden-accessible:checked').each(function() {
          tab_checked_niv1 += (tab_checked_niv1 ? ',' : '') + this.value;
      });
      $('#metiers ul li .ui-helper-hidden-accessible:checked').each(function() {
          tab_checked_niv1 += (tab_checked_niv1 ? ',' : '') + this.value;
      });
      $('.selecteur_mot_cle .ui-helper-hidden-accessible:checked').each(function() {
          tab_mot_checked += (tab_mot_checked ? ',' : '') + this.value;
      });
      jQuery.ajax({
          dataType : 'json',
          type: "POST",
          url:  BASE_URL+'ajax/ef/script_recherche_avance.php',
          data :  'todo=recherche_avance&tab_niv1='+tab_checked_niv1+'&date='+date+'&duree='+duree+'&mot_cle='+mot_cle+'&tab_mot_cle='+tab_mot_checked,
          success : function(data) {
               $('.resultat_recherche').empty();
               $('.resultat_recherche').append('<div class="titre_resultat"><h3 class="recherche_avancee">Résultats de  votre recherche</h3><div class="type_recherche"></div></div><br class="clearfloat" /><table class="recherche_avancee"><tr><th style="width:525px;padding-left:10px">Les formations Inter</th><td width="42px">&nbsp;</td><th style="width:362px;padding-left:10px;">Les formations Intra</th></tr><tr><td valign="top" width="535px">'+data['formation']+'</td><td></td><td valign="top" width="362px" style="padding: 5px 0 0 15px">'+data['formation_intra']+'</td></tr></table>');
               $('#pleine').css({'width' : (100 - data['nb'])+'%'});
               if (tab_mot_checked == 'un_mot') {
                   $('.type_recherche').append('<span class="ui-checkbox_mot_on" id="un_mot"></span><label class="label_checkbox">Un des mots</label>');
               } else if (tab_mot_checked == 'mots') {
                   $('.type_recherche').append('<span class="ui-checkbox_mot_on" id="un_mot"></span><label class="label_checkbox">Tous les mots</label>');
               } else if (tab_mot_checked == 'expression') {
                   $('.type_recherche').append('<span class="ui-checkbox_mot_on" id="un_mot"></span><label class="label_checkbox">Expression exacte</label>');
               }
               var reg=new RegExp("[  ]+", "g");
               var mot_cle = $('#mot_cle').val().split(reg);
               if ($('#mot_cle').val() != "") {
                   for(var i = 0;i < mot_cle.length; i++) {
                       $('.recherche_avancee td').highlight(mot_cle[i]);
                   }
               }

          }
       });

      return false;
  }
/**
 * RECHERCHE AVANCEE /END
 */

/**
 * Recherche
 */
  jQuery(document).ready(function() {
      jQuery("#search").autocomplete(BASE_URL+"ajax/ef/recherche_autocompletion.php", {
          width: 650,
          extraParams: {type_recherche: 'full_text'},
          selectFirst: false,
          max: 50,
          cacheLength: 1,
          minChars: 2
      }).result(function(event, item) {
          jQuery('#search').val(item[0]);
          document.location.href = item[1];
      });
  });
  function ouvreRechercheAvancee() {
      $('#tab-recherche').addClass('on');
      $('#quicktab-container').find('#quicktab-recherche').slideDown('500');
      $('#mot_cle').attr('value',$('#search').val());
      $('#button_recherche_avancer').click();
      return false;
  }
/**
 * Recherche /END
 */

$(function(){
    Qtab.init();
    $('#'+nav_current_item).show();

    $('#tab-calendrier, #tab-formation, #tab-inscription, #tab-recherche').click(function() {
        if ($(this).attr('id') == 'tab-calendrier') {

            var str_print_calendar = '<style media="print" id="css_calendar"> #main, #calendrier-cat {display:none} </style>';

            if ($(this).hasClass('on')) {
                // On souhaite refermer le menu
                $('#css_calendar').remove();
            } else {
                // On souhaite ouvrir le menu
                $(str_print_calendar).appendTo('head');
            }
        }
        Qtab.show($(this).attr('id').replace('tab-', ''));
    });

    $('.slider').uSlider();
//    $('.pngfix').pngFix();
    $('#syndication a').fixHover();

    // Hover sur les onglets
    $('#tabs .tab').mouseover(function(){
        $(this).addClass('mouseover');
    }).mouseout(function() {
        $(this).removeClass('mouseover');
    });

    // Gestion de la navigation
    /*$('#nav-btn-secteurs').hover(function() {
        navItemHover('nav-secteurs');
    });
    $('#nav-btn-metiers').hover(function() {
        navItemHover('nav-metiers');
    });
    $('#nav-btn-intra').hover(function() {
        navItemHover('nav-intra');
    });*/

    $("#nav-menu .bouton img").hover(function() {
        $("#nav-menu .bouton img").each(function() {
            // on reinitialise le off sur  tous les boutons
            this.src = this.src.replace("-on","-off");
            jQuery(this).removeClass('active_button');
        })
        // on active le on sur le bouton
        this.src = this.src.replace("-off","-on");
        jQuery(this).addClass('active_button');
        // on recharge la partie de droite dependante du bouton actif
        if (jQuery(this).parent().attr('id') == 'nav-btn-secteurs') {
            navItemHover('nav-secteurs');
        } else if (jQuery(this).parent().attr('id') == 'nav-btn-metiers') {
            navItemHover('nav-metiers');
        } else if (jQuery(this).parent().attr('id') == 'nav-btn-intra') {
            navItemHover('nav-intra');
        }
    });

    // delai du timer
    //lancement du timer de mise à jour
    setTimeout("checkExpertise()", 1000);

    $("#header-phone").hover(function() {
        $("#header-phone img.num").each(function() {
            this.src = this.src.replace(".png","_over.png");
        })
    }, function() {
        $("#header-phone img.num").each(function() {
            this.src = this.src.replace("_over.png",".png");
        })
    });

    /* Rollover sur les encarts formations "En savoir +" */
    $('.produit-infos').mouseover(function() {
        var prod_id = $(this).attr('prod_id');
        $('#apercu_produit_'+prod_id).show();
    }).mouseout(function() {
        var prod_id = $(this).attr('prod_id');
        $('#apercu_produit_'+prod_id).hide();
    });

    Calendrier.init();
});

function navItemHover(element) {
    if (nav_finished && element != nav_current_item) {
        nav_finished = false;
        $('#tagcloud', '#nav-secteurs', '#nav-metiers', '#nav-intra').hide();
        $('#'+nav_current_item).slideUp(200, function() {
            $('#'+element).slideDown(200, function() {
                nav_finished = true;
                nav_current_item = element;
            });
        });
    }
}

function Close() {
    $('#tabs .on').removeClass('on');
    $('#quicktab-container').find('.qtab:visible').slideUp('500');
}

function checkExpertise() {
    $("#nav-menu .bouton img.active_button").each(function() {
        if (jQuery(this).parent().attr('id') == 'nav-btn-secteurs' && !jQuery('#nav-secteurs').is(":visible")) {
            navItemHover('nav-secteurs');
        } else if (jQuery(this).parent().attr('id') == 'nav-btn-metiers' && !jQuery('#nav-metiers').is(":visible")) {
            navItemHover('nav-metiers');
        } else if (jQuery(this).parent().attr('id') == 'nav-btn-intra' && !jQuery('#nav-intra').is(":visible")) {
            navItemHover('nav-intra');
        }
    });
    setTimeout("checkExpertise()", 1000);
}


