$('html').addClass('js');
Shadowbox.init({
  // Ajoute un lien Retour sous l'overlayer
    onOpen:function(obj){
      if( $(".dossiertaux").length && !$('span.retour').length)
        $("#sb-nav-close").append('<span class="retour">Retour</span>');
    }
});

var is_IE = $.browser.msie;

// Border-radius plugin
;(function($){

  if($.browser.msie && document.namespaces["v"] == null) {
    document.namespaces.add("v", "urn:schemas-microsoft-com:vml");
    var ss = document.createStyleSheet().owningElement;
    ss.styleSheet.cssText = "v\\:*{behavior:url(#default#VML);}"
  }

  $.fn.borderRadius = !$.browser.msie ? function() {} : function(options){

     var options = options || {}

      return this.each(function() {
        var opts = {}
          if (this._border_radius_opts) {
            opts = this._border_radius_opts
           $(this).find(".ie_border_radius").remove();
         } else {
            opts.strokeColor = this.currentStyle.borderColor;
            opts.strokeWeight = this.currentStyle.borderWidth;

            opts.fillColor = this.currentStyle.backgroundColor;
            opts.fillSrc = this.currentStyle.backgroundImage.replace(/^url\("(.+)"\)$/, '$1');

            this.style.border = 'none'; // perhaps add onto padding?
            this.style.background = 'transparent';
            this._border_radius_opts = opts
         }

         var r = options.radius || parseInt( this.currentStyle['-ie-border-radius'] ||  this.currentStyle['-moz-border-radius'] || this.currentStyle['moz-border-radius'] );

         opts.width = (!options.width) ? $(this).outerWidth() : options.width;
         opts.height = (!options.height) ? $(this).outerHeight() : options.height;

         opts.arcSize = Math.min( r / Math.min(opts.width, opts.height), 1);

        var html = '<div class="ie_border_radius" style="position: absolute; left: 0px; top: 0px; z-index: -1; width:' + (opts.width) + "px;height:" + (opts.height) + 'px;">'
        html += '<v:roundrect arcsize="' + opts.arcSize + '" strokecolor="' + opts.strokeColor + '" strokeweight="' + opts.strokeWeight + '" style="behavior: url(#default#VML); position:absolute;  antialias: true; width:' + (opts.width) + "px;height:" + (opts.height) + 'px;' + "" + '" >';
        html += '<v:fill color="' + opts.fillColor + '" src="' + opts.fillSrc + '" type="tile" style="behavior: url(#default#VML);" />';
        html += '</v:roundrect>';
        html += "</div>"

        this.innerHTML += html ;

        if(this.currentStyle.position != "absolute")
          this.style.position = "relative";

        this.style.zoom = 1; // give it a layout
      });
    }
})(jQuery);


// Gestion du jeu mosaïque
shuffle = function(o){ //v1.0
  for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
  return o;
};
function init_game()
{
  if( $("#game").length == 0 )
    return;

  // Options
  var max_clics = 5;    // Nombre maximum de clicks
  var rand_nb   = 50; // Nombre d'images à retourner
  var rand_ecart  = 10; // Nombre max d'images retournées en même temps
  var rand_delay  = 20; // Interval de temps (ms) entre chaque retournement d'image
  var qui = new Array(); for (var i=0; i< 50; i++) qui[i]=i; qui = shuffle(qui);
  var current_clics = 0;
  var load_compteur = 0;

  // On cache le formulaire s'il n'a pas été validé
  if (!$("#form_final").hasClass("errors") ){
    $("#form-jeu").css('opacity', 0.40).find("input").attr("disabled","disabled");
  }

  // On cache le jeu s'il le formulaire a été validé
  if ($("#game").hasClass("errors"))
    $("#game").css('opacity', 0.30);

  $(window).load(function(){
    current_clics = max_clics;
    $('#game .load').remove();
    $('#game img').css("display","block");

    // On anime les images si pas d'erreur
    if (!$("#game").hasClass("errors")){
    var compteur = 0;
    var rand_timeout = setInterval(function(){

      if( compteur >= rand_nb+rand_ecart ){
        clearTimeout(rand_timeout);
        current_clics = 0;
        return;
      }

      // On cache la courante
      if( compteur < rand_nb ){
        $("#game img").eq(qui[compteur])
          .attr("rel",$("#game img").eq(qui[compteur]).attr("src"))
          .attr("src","/medias/mosaique/jpg-272x272-q100/mystere.gif");
      }

      // On raffiche la plus ancienne
      if( compteur-rand_ecart >= 0)
        $("#game img").eq(qui[compteur-rand_ecart]).attr("src",$("#game img").eq(qui[compteur-rand_ecart]).attr("rel"));

      compteur++;
    },rand_delay);

    }
  });

  $("#game img"
    ).live("mouseover",function(){
      // Si le nbr max de clics a été dépassé, on ne fait plus de hover
      if (current_clics >= max_clics)
        return;
      $(this).addClass("hover");
      $(this).css({
        top: parseInt($(this).css("top"))-2 + "px",
        left: parseInt($(this).css("left"))-2 + "px"
      });
    }).live("mouseout",function(){
      if (current_clics >= max_clics)
        return;
      $(this).removeClass("hover")
      $(this).css({
        top: parseInt($(this).css("top"))+2 + "px",
        left: parseInt($(this).css("left"))+2 + "px"
      });
    }).live("click", function(){
       if (current_clics == 1)
          $('#game').css("background","url(/medias/mosaique/bg-cache.gif) no-repeat 50% 50%");
      if (current_clics >= max_clics){
        alert("Vous ne pouvez plus dévoiler de case supplémentaire.");
        return;
      }
      current_clics++;
      $(this).css("display", "none");
      if (current_clics >= max_clics){
        $("#game").fadeTo("slow",0.40);
        $("#form-jeu").fadeTo("slow",1).find("input").attr("disabled","");
        $(".nextstep").fadeTo("slow",1);
      }
    });

}
// Gestion très très basique des erreurs de formulaire en js.
function init_contact_form(){
  if( $("#formviral").length == 0 )
    return

  $("#formsubmit").live("click",function(){
    var champs = ["nom", "prenom", "adresse1", "codepostal", "ville", "email","demande"];
    var error = 0;

    for (var i=0; i<champs.length; i++){
      if($("#formviral").find("*[name="+champs[i]+"]").val().length == 0){
         if ($("#formviral").find("*[name="+champs[i]+"]").closest("p").find(".error").length == 0) {
            $("#formviral").find("*[name="+champs[i]+"]").addClass('error').closest("p").append('<span class="error">* Champ obligatoire</span>');
         }
        error++;
      }
      else
        $("#formviral").find("*[name="+champs[i]+"]").removeClass('error').closest("p").find(".error").remove();
    }

    if (error > 0)
      return false;
    return true;
  });
}


/* Tracking unica */

function unica_trackEvent(elem,typeEvent) {
   if (typeEvent == 'file' && (typeof ntptAddPair != 'undefined' || typeof ntptEventTag != 'undefined')) {
      ntptAddPair("lien", elem);
      ntptEventTag("ev="+typeEvent);
   } else if (typeEvent == 'external' && typeof ntptLinkTag != 'undefined') {
      ntptLinkTag(elem);
   }
}


function openShadowbox(url,sizes,player) {
   var sizesSplit = sizes.split(';');
   var attr = [];
   var height,width;

   for (i=0; i<sizesSplit.length; i++) {
      attrSplit = sizesSplit[i].split('=');
      attr[attrSplit[0]] = attrSplit[1]
   }
   Shadowbox.open({
      content: url,
      player: player,
      width:      attr['width'],
      height:     attr['height']
   });
}



function random(x,y) {
  return Math.round(Math.random()*(y-x))+x;
}

function close_prehome() {
   $('#prehome').fadeOut('slow', function() {
      if (typeof animate != 'undefined')
         clearInterval(animate);
   });
}


function showPreHomeFaces() {
  var prehome = $('#prehome')
  prehome.find('img.loading').hide()
  prehome.find('ul,#souriez-les-amis,#logo-prehome,#overlay-prehome').show()

  var animate = setInterval(function() {
    prehome.find('li.colored').removeClass('colored')
    for (i=0; i<=3; i++) {
      var not_colored = prehome.find('li:not(.colored)')

      not_colored.eq(random(0, not_colored.length-1)).addClass('colored')
    }
   }, 300);

   _close_prehome = setTimeout(close_prehome, 5000);
}

function checkPrehomeLoaded() {
  var _checkPreHome = setInterval(function() {
    if ($('#access_site').length != 0) {
     showPreHomeFaces();
     clearInterval(_checkPreHome);
   }
  }, 200)
}

function customize() {
  Cufon.replace('#menu ul li', {
    textShadow: '1px 1px #000',
    hover: true, hoverables: { a: true }
  })('.fantasy');
  $('h2.fantasy').css('display', 'inline-block');
  $(".rounded,.emphasized").borderRadius();
  $('.loading-content').removeClass('loading-content').prev('img').remove();
}

/***** Main *****/

$(document).ready(function() {

  $("<div/>", { 'class': "submit next", text: "Question suivante >" }).appendTo("#quizz fieldset:not(:last)");

  $(".quiz").live('click',function(e) {
    var $target = $(e.target);
    if ($target.is('input[type=radio]'))
      $target.closest('fieldset').find('.submit').fadeIn();
    else if ($target.is('.next'))
      $target.parent('fieldset').fadeOut(function() { $(this).next('fieldset').fadeIn(); });
  });


  $("form label.inlined").each(function() {
    $(this).css({position:'absolute',top:-9999,left:-9999}).next(':input').val($(this).text());
  });

  $("form").live("focus", function(e){
   $target = $(e.target);
   $target.addClass("focus");
   if ($target.val() == $target.prev('label.inlined').text())
     $target.val('');
  });

  $("form").live("keypress", function(e){
    $target = $(e.target);
    $target.addClass("has-text").removeClass("focus");
    if ($target.val() == $target.prev('label.inlined').text())
       $target.val('');
  });

  $("label.inlined + .input-text").blur(function () {
    if ($(this).val() == "")
       $(this).val($(this).prev("label.inlined").text()).removeClass("has-text").removeClass("focus");
  });

   // Initialisation du jeu mosaïque
  init_game();

  // on initialise google analytics

  var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); // renseigne le type d'hôte à google
  $.getScript(gaJsHost + "google-analytics.com/ga.js", function(){
    try {
      var pageTracker = _gat._getTracker("UA-3327859-1"); // insertion de l'identifiant client analytics
      if ($('.client_session').length)
        pageTracker._setVar('Clients');
      else if ($('.prospect_session').length)
        pageTracker._setVar('Prospects');
      pageTracker._trackPageview(); // lancement du tracker principal google analytics
    } catch(err) {}

    var filetypes = /\.(zip|exe|pdf|doc*|xls*|ppt*|mp3)$/i; // type de fichier que l'on souhaite surveiller d'un point de vue statistique
    // gestionnaire d'évenement sur les clics dans le DOM
    $('body').live('click',function(e){
      var $this; // initialisation de l'objet

      if ($(e.target).is('a')) // si l'élement sur lequel on a cliqué est un lien
         $this = $(e.target);
      else // sinon on cherche l'élement lien le plus proche
         $this = $(e.target).closest('a');

      var href = $this.attr('href'); // attribut href du lien

      if ($this.is('a')) {
         // on tracke que le clic sur les liens externe
         if ((href.match(/^https?\:/i)) && (!href.match(document.domain))){
            var extLink = href.replace(/^https?\:\/\//i, ''); // on supprime le prefixe http:// de l'url pour plus de compréhension
            unica_trackEvent($this,'external'); // tracker unica
            pageTracker._trackEvent('Externe', 'Clic', extLink); // tracker google analytics
            if (!$this.is('[rel^=overlayer]'))
               $this.attr("target","_blank"); // on ouvre le lien dans une fenêtre externe
         }
         // on checke les clics sur les liens de type email
         else if (href.match(/^mailto\:/i)){
            var mailLink = href.replace(/^mailto\:/i, ''); // on supprime le prefixe mailto: de l'url pour plus de compréhension
            pageTracker._trackEvent('Email', 'Clic', mailLink); // tracker google analytics
         }
         // on checke les clics sur les médias (pdf, doc, etc...)
         else if (href.match(filetypes)){
           var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined; // on récupère l'extension du fichier
           var filePath = href.replace(/^(http:\/\/)(www.)?((epargnegmf\.fr)|(gmfepargnedurable\.fr)|(192\.168\.1\.13\/epargnegmf))\//i, '');
           var lastSlashPosition = filePath.lastIndexOf('/');
           if (lastSlashPosition > 0) {
             var fileName = (filePath.substr(lastSlashPosition+1,filePath.length)).toLowerCase(); // nom du fichier
             unica_trackEvent(fileName,'file'); // tracker unica
           }
           pageTracker._trackEvent('Download', 'Clic - ' + extension, filePath); // tracker google analytics
         }

         // Si c'est un lien à ouvrir dans une nouvelle fenêtre
         if ($this.is("a[rel=popup]") && $this.attr('blank') != '_blank' && !$this.is('[rel^=overlayer]'))
           $this.attr("target","_blank"); // on ouvre le lien dans une fenêtre externe
      }

      if ($this.is('[rel^=overlayer]')) {
        openShadowbox($this.attr('href'),$this.attr('data-size'),$this.attr('data-type'));
        return false;
      }
    });
  });

  // Gestion du formulaire de contact
  init_contact_form();

  if (is_IE && typeof unica_imod != 'undefined') {
    setInterval(function() {
      var old_unica_imod_applyChanges = unica_imod.applyChanges;
      unica_imod.applyChanges = function(a, b, c, d, e) {
        old_unica_imod_applyChanges(a, b, c, d, e);
        customize();
      }
    }, 200);
  } else {
    setInterval(customize, 200);
  }


  ///////////////////// Slides Dossier du moment - Avril 2010 /////////////////////
  var slides = $('body.dossiertaux #content article'),
      bubbles = $('#bubble-1,#bubble-2,#bubble-3');
  
  if (slides.length) {

    slides.hide().first().show();

    $('.dossiertaux #slide-1 .suite a, .dossiertaux #slide-2 .suite').click(function(){next_slide()});

    function next_slide() {
      var current = slides.filter(':visible'),
          next = current.next()
      if (next)
        current.fadeOut('slow', function() {
          next.fadeIn('slow')
        })
    }

    //// Gestion des bulles ////
    var bubble_index = 0;
    $("#bubble-2,#bubble-3").animate({opacity: 0.5},0);
    
    function show_bubble(bubble_to_show) {
      // On veut afficher la bulle courante ou une une mauvasie bulle ? On abandonne
      if (bubble_to_show == bubble_index || bubble_to_show < 0)
        return;

      // On fait le fadeIn de la bulle demandée
      $("#bubble-"+(bubble_to_show+1)).animate({opacity:1},300);

      // On fait le fadeOut de l'ancienne bulle active
      $("#bubble-"+(bubble_index+1)).animate({opacity:0.5},300);

      bubble_index = bubble_to_show;

      // Enfin, on demande à afficher le bon content. Cas particulier iside ! :)
      if( bubble_index == 0 )
        show_content(0);
      else if( bubble_index == 1 )
        show_content(1);
      else if( bubble_index == 2 )
        show_content(3);
    }

    // gestion des événements
    $("#slide-2 h2").live("click",function(){
      // quelle bulle cliquée ?
      var bubble_offset = parseInt($(this).attr("id").charAt(7))-1;
      show_bubble(bubble_offset);
    })

    //// Gestion des petits écrans .content ////
    var content_index = 0;
    var contents = $(".content");
    $(".content").css("display","none").eq("0").css("display","block");

    function show_content(content_to_show){
      if (content_to_show == content_index || content_to_show < 0)
        return;

      // On fait le fadeOut de l'ancien content
      $(contents[content_index]).fadeOut();

      // On fait le fadeIn du content demandé
      $(contents[content_to_show]).fadeIn();

      content_index = content_to_show;

      // On demande à afficher la bulle correspondante
      var bubble_to_show = parseInt($(contents[content_index]).attr("id").charAt(8))-1;
      show_bubble(bubble_to_show);
    }

    // gestion des événements
    $(".content .prev, .content .next").live("click",function(){
      var asked_parent_id = $(this).attr("href").substr(1);
      for( var i= 0; i < contents.length; i++){
        if( $(contents[i]).attr("id") == asked_parent_id){
          show_content(i);
          return false;
        }
      }
    });
  }






  /////////////////////  Ajout du lien de téléchargement des PDF dans la ShadowBox

  $(".dossiertaux #article-mvsa").click(function(){
    Shadowbox.open({
      player: 'img',
      content: $(this).attr("href"),
      options:{
        onFinish:function(){
          $("#sb-counter").append("<a id='pdf-dl' href='medias/pdf/article-mvsa.pdf'>Télécharger l'article</a>");
        }
      }
    });
    return false;
  });

  $(".dossiertaux #article-revenu").click(function(){
    Shadowbox.open({
      player: 'img',
      content: $(this).attr("href"),
      options:{
        onFinish:function(){
          $("#sb-counter").append("<a id='pdf-dl' href='medias/pdf/article-revenu.pdf'>Télécharger l'article</a>");
        }
      }
    });
    return false;
  });

}); // fin $(document).ready()


$(window).load(function() {
   var urlFlash = $('#faq').attr('data-flashuri');
   if ($.browser.msie) { // pour les navigateurs de seconde classe
      flashTimeout = setInterval(function() {
         if ($('.questionsreponses #content article.rounded .ie_border_radius').length && typeof $.fn.flash != 'undefined') {
            $('#faq').flash({ src: urlFlash, height: 592, width: 663},{ version: 9 });
            clearInterval(flashTimeout);
         }
      },200)
   } else { // pour les navigateurs qui déchirent tout !
      if (typeof $.fn.flash != 'undefined')
         $('#faq').flash({ src: urlFlash, height: 592, width: 663},{ version: 9 });
   }
   $("#menu ul").borderRadius({height:32});

});

