// Liens externes --------------------------------------------------------------

jQuery().ready(function() {
  if ($('body').attr('class')) {
    var langue = $('body').attr('class');
  } else {
    var langue = 'fr';
  }

  var h = document.getElementsByTagName('base')[0].href + langue + '/';

  $("a[href^='http:']").not("[href*='" + h + "']").attr('target','_blank');
  $('a[href*=.pdf]').attr('target','_blank');
});

// CSS Browser Selector --------------------------------------------------------

var css_browser_selector = function() {
  var ua=navigator.userAgent.toLowerCase(),is=function(t){
    return ua.indexOf(t) != -1;
  },
  h=document.getElementsByTagName('html')[0],b=(!(/opera|webtv/i.test(ua))&&/msie (\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?'gecko ff2':is('firefox/3')?'gecko ff3':is('gecko/')?'gecko':is('opera/9')?'opera opera9':/opera (\d)/.test(ua)?'opera opera'+RegExp.$1:is('konqueror')?'konqueror':is('applewebkit/')?'webkit safari':is('mozilla/')?'gecko':'',os=(is('x11')||is('linux'))?' linux':is('mac')?' mac':is('win')?' win':'';var c=b+os+' js'; h.className += h.className?' '+c:c;
}();

// Survol TR et Button pour IE6 ------------------------------------------------

if (!window.XMLHttpRequest){
  $(document).ready(function(){
    $("table tr").hover(
     function(){
      $(this).addClass("hover");
     },
     function(){
      $(this).removeClass("hover");
     }
    );
    $("button").hover(
     function(){
      $(this).addClass("hover");
     },
     function(){
      $(this).removeClass("hover");
     }
    );
  });
}

// transparence PNG ------------------------------------------------------------

var blank = new Image();
blank.src = 'images/elements/trans.gif';

$(document).ready(function() {
 var badBrowser = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");
 if (badBrowser) {
   $('img[src$=.png]').each(function() {
     if (!this.complete) {
       this.onload = function() { fixPng(this); };
     } else {
       fixPng(this);
     }
   });
 }
});

function fixPng(png) {
 var src = png.src;
 if (!png.style.width) { png.style.width = $(png).width(); }
 if (!png.style.height) { png.style.height = $(png).height(); }
 png.onload = function() { };
 png.src = blank.src;
 png.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
}


jQuery().ready(function() {
  if(jQuery.browser.msie && parseInt(jQuery.browser.version) == 6 && typeof window['XMLHttpRequest'] != "object") {
    $('.infos').each( function() {
      $(this).attr('writing-mode', 'tb-rl');
      $(this).css('background', 'none');
      $(this).css( 'filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="../images/elements/gamme/fl_infos_ie.png",sizingMethod="scale")');
    });
  }
});

// Choix langue ----------------------------------------------------------------

jQuery().ready(function() {
	var currentLangText = $.trim($('#blocLangue .langue a').text());
	$('#blocLangue .select ul li a').each(function() {
		if ($(this).text() == currentLangText) {
			$(this).parent().hide();
			return false;
		}
	});
	$('#blocLangue .langue a').bind('click', function(e) {
		e.stopPropagation();
		e.preventDefault();
		$("#blocLangue .select").animate({height: 'toggle'},'fast');
	});
	$(document).bind('click', function(e) {
		$("#blocLangue .select").slideUp('fast');
	});
});

// Journal ---------------------------------------------------------------------

jQuery().ready(function() {
	$('.journal').click(function(e) {
		e.preventDefault();
		jAlert(tradJournal, tradTitreJournal);

	});
});

// Menu principal --------------------------------------------------------------

jQuery().ready(function() {
	$("#topmenu ul ul").css('display', 'none');
	$("#topmenu ul li").bind('mouseenter mouseleave', function() {
		$(this).find("ul").animate({height: "toggle"},"fast");
	});
});

// Actualités ------------------------------------------------------------------

jQuery().ready(function() {
  $(".blocActus .slider").easySlider({
		loop: true,
		orientation: 'horizontal',
		autoplayDuration: 5000,
		autogeneratePagination: true,
		restartDuration: 1000,
  	controlsBefore:	'<p id="controls">',
  	controlsAfter: '</p>',
		nextId: 'nextBtn',
		prevId: 'prevBtn',
		pauseable: true
  });
});

// Flash -----------------------------------------------------------------------

jQuery().ready(function() {
  if ($('body').attr('class')) {
    var langue = $('body').attr('class');
  } else {
    var langue = 'fr';
  }
  
  $("#blocFlash").flashembed({
      src: 'flash/accueil.swf',
      version: [9, 0],
      wmode: 'transparent',
      quality: 'high',
      width: 1000,
      height: 235
    }, {
      langue: langue,
      xmlPath: 'flash/xml/accueil.xml'  
  });

  /*
  $("#blocFlash.gamme").flashembed({
      src: 'flash/diaporama.swf',
      version: [9, 0],
      wmode: 'transparent',
      quality: 'high',
      width: 1000,
      height: 235
    }, {
        langue: langue,
        modele: modele,
        xmlPath: 'flash/xml/aventura.xml'
    });
    */
});

// Recherche -------------------------------------------------------------------

//$.cookie("state", { expires: -1 });

jQuery().ready(function() {
  //$(".blocRecherche #recherche").after('<p class="recherche active"></p>');
  //$(".blocRecherche #recherche").hide();

  var actif_fr = "<strong>Cliquez ici</strong> pour masquer la recherche";
  var inactif_fr = "<strong>Cliquez ici</strong> pour afficher la recherche";

  var actif_en = "<strong>Click here</strong> to hide the search";
  var inactif_en = "<strong>Click here</strong> to view the search";

  var actif_de = "<strong>Klicken Sie hier</strong>, um den Fahrzeugberater zu verstecken";
  var inactif_de = "<strong>Klicken Sie hier</strong>, um den Fahrzeugberater anzuzeigen";

  var actif_it = "<strong>Clicca qui</strong> per nascondere la ricerca";
  var inactif_it = "<strong>Clicca qui</strong> per visualizzare la ricerca";

  if (!$('body').attr('class')) {
    var actif = actif_fr;
    var inactif = inactif_fr;
  } else {
    var actif = eval('actif_' + ($('body').attr('class')));
    var inactif = eval('inactif_' + ($('body').attr('class')));
  }

  $(".blocRecherche #recherche").after('<p class="recherche"><span><span></span></span></p>');
  function init() {
    if ($.cookie("state") == 'active') {
      $(".blocRecherche #recherche").hide();
      $(".blocRecherche .recherche").removeClass("active");
      $(".blocRecherche .recherche span span").html(inactif);
    } else {
      $(".blocRecherche #recherche").show();
      $(".blocRecherche .recherche").addClass("active");
      $(".blocRecherche .recherche span span").html(actif);
    }
  }

  function activation() {
    if ($(".blocRecherche .recherche").hasClass("active")) {
      $(".blocRecherche .recherche").removeClass("active");
      $(".blocRecherche .recherche span span").html(inactif);
      $.cookie("state", 'active');
    } else {
      $(".blocRecherche .recherche").addClass("active");
      $(".blocRecherche .recherche span span").html(actif);
      $.cookie("state", 'inactive');
    }
  }

  init();

  $('.blocRecherche .recherche').bind('click', function() {
    $('.blocRecherche #recherche').animate({height: 'toggle'},'fast');
    activation();
	});
});

// Leftmenu --------------------------------------------------------------------

jQuery().ready(function() {
  if (!$('#leftmenu ul li.menu').hasClass("active")) {
    $("#leftmenu ul li.menu ul").hide();
    $("#leftmenu ul li.menu").append('<span class="action"></span>');
    if(jQuery.browser.msie && parseInt(jQuery.browser.version) == 6 && typeof window['XMLHttpRequest'] != "object") {
      $('#leftmenu .action').each( function() {
        $(this).attr('writing-mode', 'tb-rl');
        $(this).css('background', 'none');
        $(this).css( 'filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="../images/navigation/fl_leftmenu.png",sizingMethod="scale")');
      });
    }
  }
  function activation() {
    if ($("#leftmenu ul li.menu").hasClass("selected")) {
      $("#leftmenu ul li.menu").removeClass("selected");
      $("#leftmenu .action").removeClass("active");
    } else {
      $("#leftmenu ul li.menu").addClass("selected");
      $("#leftmenu .action").addClass("active");
    }
  }
  activation();
  $('#leftmenu .action').bind('click', function(e) {
		e.stopPropagation();
		e.preventDefault();
		$('#leftmenu ul li.menu ul').animate({height: 'toggle'},'fast');
    activation();
	});
});

// Gamme -----------------------------------------------------------------------

jQuery().ready(function() {
  function init() {
    $('.blocGamme p').css('position', 'static');
    $('.blocInfos').remove();
  }
  $('.blocGamme tr').find('td:last').css('border-right', 'none');
  $('.blocGamme .infos').bind('click', function(e) {
    e.stopPropagation();
		e.preventDefault();
    if (!$(this).prev('.blocInfos').length) {
      init();
      $(this).parent().css('position', 'relative');
      $(this).before('<div class="blocInfos"><div class="contenu"></div><div class="footer"></div></div>').prev().hide();

      // Exemple ---------------------------------------------------------------
      var idCc = $(this).attr('rel');
      $('.blocInfos .contenu').append().load('ajaxsurvol.php', {id_camping_car: idCc});
      // -----------------------------------------------------------------------

      $('.blocInfos').fadeIn();
      $('.blocInfos').bind('mouseenter mouseleave', function() {
        $(this).toggleClass('survol');
          if($(".blocInfos .contenu a").length) {
            $(".blocInfos .contenu a").fancybox({
              'hideOnContentClick': false,
              frameWidth : 640,
              frameHeight : 483
            });
          } else {
            return false;
          }
      });
    } else {
      init();
    }
    $(document).bind('click', function() {
      if (!$('.blocInfos').hasClass('survol')) {
        init();
      }
    });
	});
});

jQuery().ready(function() {
  jQuery(".blocSchema a").fancybox({
    'hideOnContentClick': false,
    frameWidth : 640,
    frameHeight : 483
  });

  jQuery(".vue_360 a").fancybox({
	  'hideOnContentClick': false,
    frameWidth : 640,
    frameHeight : 483
	});
});

// Bulle info ------------------------------------------------------------------

jQuery().ready(function() {
  $('.blocTarifs .bloc').bind('mouseenter mouseleave', function() {
    $(this).toggleClass('survol');
    $('.blocTarifs .bloc').css('position', 'relative');

    var posY = $(this).height() - 10;
    var posX = -($(this).find('.desc').width()/2);

    $(this).find('.desc').css('position', 'absolute');
    $(this).find('.desc').css({
      'bottom' : posY,
      'left' : '50%',
      'margin-left' : posX
    });
    if ($(this).hasClass('survol')) {
      $(this).find('.desc').fadeIn();
    } else {
      $(this).find('.desc').fadeOut();
    }
  });
});

// Galerie / Diaporama ---------------------------------------------------------

jQuery().ready(function() {
  $("#slider").easySlider({
		loop: true,
		orientation: 'vertical',
		autogeneratePagination: true,
  	controlsBefore:	'<p class="controls">',
  	controlsAfter: '</p>',
		nextId: 'nextBtn',
		prevId: 'prevBtn',
		pauseable: true
  });

  var settings = {
    mainContainer: "blocSlider",
    thumbListId: "slider",
    imgViewerId: "apercu",
    msgViewerId: "message",
    activeClass: "active",
    activeTitle: "Loading",
    loaderTitle: "Chargement en cours",
    loaderImage: "images/elements/loader.gif"
  };

  var thumbLinks = $("#"+settings.thumbListId).find("a"),
  firstThumbLink = thumbLinks.eq(0),
  highlight = function(elt){
    thumbLinks.removeClass(settings.activeClass);
    elt.addClass(settings.activeClass);
    $("#"+settings.msgViewerId).html(elt.attr("title"));
  },
  loader = $(document.createElement("img")).addClass("loader").attr({
    alt: settings.loaderTitle,
    title: settings.loaderTitle,
    src: settings.loaderImage
  });

  highlight(firstThumbLink);

  $("#"+settings.mainContainer).after(
    $(document.createElement("p"))
    .attr("id",settings.imgViewerId)
    .append(
      $(document.createElement("img")).attr({
        alt: "",
        src: firstThumbLink.attr("href")
      })
    )
  );

  var imgViewer = $("#"+settings.imgViewerId),
      bigPic = imgViewer.children("img");

  $('#'+settings.imgViewerId).css('position', 'relative');

  thumbLinks.click(function(e){
      e.preventDefault();
      var $this = $(this),
          target = $this.attr("href");
      if (bigPic.attr("src") == target) { return };
      highlight($this);
      imgViewer.html(loader);
      bigPic
        .load(function(){
          imgViewer.html($(this).fadeIn(250));
        })
        .attr("src",target);

      var posY = -($('img.loader').height()/2);
      var posX = -($('img.loader').width()/2);

      $('img.loader').css({
        'position' : 'absolute',
        'top' : '50%',
        'left' : '50%',
        'margin-top' : posY,
        'margin-left' : posX
      });
    });
});

// Saga ------------------------------------------------------------------------

jQuery().ready(function() {
  $('#blocSaga .slider').easySlider({
		loop: true,
		orientation: 'horizontal',
		autogeneratePagination: true,
  	controlsBefore:	'<p class="controls">',
  	controlsAfter: '</p>',
		nextId: 'nextBtn',
		prevId: 'prevBtn',
		pauseable: true
  });

  $('#blocSaga .slider li .bloc').each(function(i) {
    var total = $('#blocSaga .slider li .bloc').length - $('#blocSaga .slider li:first .bloc').length;

    $(this).click(function(e) {
  		e.stopPropagation();
  		e.preventDefault();

      if(!$(this).hasClass('active')) {
        $('#blocSaga #chargement li').removeClass('active');
        if (i >= total) {
          i = i - total;
        }
        var element = $('#blocSaga #chargement li')[i];
        $(element).addClass('active');
        var contenu = $('#blocSaga #chargement li.active').html();

        var src = $(this).find('a').attr('href');

  		  $('#blocSaga .slider li .bloc').removeClass('active');
        $(this).addClass('active');
        $('#blocSaga .detail img').attr('src', src).hide().fadeIn();
        $('#blocSaga .detail .desc').empty().append(contenu);
      }
    });
	});
});

// Savoir-faire ----------------------------------------------------------------

jQuery().ready(function() {
  $('#blocSavoir .liste li a').each(function(i) {
    $(this).click(function(e) {
  		e.stopPropagation();
  		e.preventDefault();

      if(!$(this).hasClass('active')) {
        $('#blocSavoir #chargement li').removeClass('active');
        var element = $('#blocSavoir #chargement li')[i];
        $(element).addClass('active');

        var contenu = $('#blocSavoir #chargement li.active').html();

        var src = $(this).attr('href');

  		  $('#blocSavoir .liste li a').removeClass('active');
        $(this).addClass('active');

        $('#blocSavoir .visuel').css('position', 'relative');
        if (!$('#blocSavoir .visuel .apercu').length) {
          $('#blocSavoir .visuel').append('<div class="apercu"></div>');
          $('#blocSavoir .visuel .apercu').prepend('<img src="" alt="" />').css({
            'position': 'absolute',
            'top': '0',
            'left': '0'
          });
        }

        $('#blocSavoir .visuel .apercu img').attr('src', src);
        $('#blocSavoir .visuel .apercu').hide().slideDown('normal', function() {
          $('#blocSavoir .visuel .amorce img').attr('src', src);
        });
        $('#blocSavoir .detail .desc').empty().append(contenu);
      }
    });
	});
});

// Plan du site ----------------------------------------------------------------

jQuery().ready(function() {
	$("#plan").treeview({
		collapsed: false,
		animated: "medium",
		control: "#blocPlan",
		persist: "location"
	});
});

// Demande de devis ------------------------------------------------------------

jQuery().ready(function() {
	$(".proprietaire").hide();
	$(".proprietaire .checkbox").nextAll("label").hide();
  $('.champRadio .oui').bind('click', function() {
		if ($('.proprietaire').is(':hidden')) {
      $('.proprietaire').show();
    }
	});
  $('.champRadio .non').bind('click', function() {
    $('.proprietaire').hide();
	});
  $('.champRadio .non').bind('click', function() {
    $('.proprietaire').hide();
    $(".proprietaire").find('input').attr('checked', false);
    $('.champRadio .checkbox').nextAll("label").hide();
	});
  $('.champRadio .checkbox').bind('click', function() {
		if ($(this).find('input').is(':checked')) {
      $(this).nextAll("label").show();
    } else {
      $(this).nextAll("label").hide();
    }
	});
});

// Newsletter ------------------------------------------------------------------

function validateAdress(emailAddress) {
  var verif = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
  return verif.test(emailAddress);
}

jQuery().ready(function() {
  $('.blocChoix .champ button').click(function(e) {
		e.preventDefault();
		var input = $("#newsletter");
    var email = input.val();

    if(validateAdress(email)) {
      input.removeClass();
		  $('.blocChoix .confirmation').remove();
  		$.ajax({
        type: "POST",
        url: "ajaxnewsletter.php",
			  data: ({newsletter :$('#newsletter').val()}),
        success: function(msg) {
				$('#newsletter').val('');
        }
      });
      $('.blocChoix form').fadeOut().delay(6000).fadeIn().after('<div class="confirmation"></div>');
      $('.blocChoix .confirmation').hide().text("Votre demande d'inscription a bien été prise en compte").delay(500).fadeIn().delay(5000).fadeOut();
      } else {
        input.addClass("error");
      }
	});

  $('.blocEntete .champ button').click(function(e) {
		e.preventDefault();
		var input = $("#newsletter");
    var email = input.val();

    if(validateAdress(email)) {
      input.removeClass();
  		$('.blocEntete .confirmation').remove();
  		$.ajax({
        type: "POST",
        url: "ajaxnewsletter.php",
        data: ({newsletter : input.val()}),
        success: function(msg) {
      	  input.val('');
        }
      });
      $('.blocEntete form').fadeOut().delay(6000).fadeIn().after('<div class="confirmation"></div>');
      $('.blocEntete .confirmation').hide().text("Votre demande d'inscription a bien été prise en compte").delay(500).fadeIn().delay(5000).fadeOut();
    } else {
      input.addClass("error");
    }
	});
});

// Presse ----------------------------------------------------------------------

jQuery().ready(function() {
  if (!$('body').attr('class')) {
    var langue = 'javascript/langue/fr.txt';
  } else if ($('body').attr('class')) {
    var langue = 'javascript/langue/' + $('body').attr('class') + '.txt';
  } else {
    var langue = 'javascript/langue/fr.txt';
  }

  if ($('#revue_presse').length) {
  oTable = $('#revue_presse').dataTable({
  	"bJQueryUI": true,
  	"sPaginationType": "full_numbers",
		"iDisplayLength": 25,
    "oLanguage": {
			"sUrl": langue
		},
    "aoColumns": [null,null,null,{ "sType": "date"}],
		"aaSorting": [[3,'desc']]
  });
  };
});

// Concessionnaires ------------------------------------------------------------

jQuery().ready(function() {
  var url = window.location.href;
  var current = url.substring(url.lastIndexOf("=")+1);

  if (!$('body').attr('class')) {
    var langue = 'fr';
  } else if ($('body').attr('class')) {
    var langue = $('body').attr('class');
  }

  $("#carte_europe").flashembed({
    src: 'flash/europe.swf',
    version: [8, 0],
    wmode: 'transparent',
    quality: 'high'
  }, {
    langue: langue,
    current: current,
    fichierXML: 'flash/xml/europe.php'
  });

  $("#carte_france").flashembed({
    src: 'flash/france.swf',
    version: [8, 0],
    wmode: 'transparent',
    quality: 'high'
  }, {
    langue: langue,
    current: current,
    fichierXML: 'flash/xml/france.php'
  });
});

// Visite d'usine --------------------------------------------------------------

jQuery().ready(function() {
  jQuery(".champRadio.visite a").fancybox();
});

// Formulaire ------------------------------------------------------------------

jQuery().ready(function() {
	var validator = $("#formulaire form").validate({
		rules : {
			nom : {
				required : true,
				minlength : 2
			},
			adresse : {
				required : true,
				minlength : 2
			},
			code_postal : {
				required : true,
				minlength : 5
			},
			ville : {
				required : true
			},
			email : {
				required : true,
        email : "#email"
			},
			telephone : {
				required : true,
				minlength : 10
			},
			message : {
				required : true,
				minlength : 2
			}
		},
		messages : {
			nom : {
				required: "&nbsp;",
        minlength: jQuery.format("Veuillez entrer au moins {0} caractères")
			},
			adresse : {
				required: "&nbsp;",
				minlength: jQuery.format("&nbsp;")
			},
			code_postal : {
				required: "&nbsp;",
				number: jQuery.format("Veuillez saisir un code postal valide"),
				minlength: jQuery.format("Veuillez saisir un code postal valide")
			},
			ville : {
				required: "&nbsp;",
				minlength: jQuery.format("Veuillez entrer au moins {0} caractères")
			},
			email : {
				required: "&nbsp;",
				email: jQuery.format("Veuillez saisir un email valide")
			},
			telephone : {
				required: "&nbsp;",
				minlength: jQuery.format("Veuillez saisir un numéro de téléphone valide")
			},
			message : {
				required: "&nbsp;",
				minlength: jQuery.format("&nbsp;")
			}
		},
		errorPlacement : function(error, element) {
			error.appendTo( element.parent() );
		},
		success : function(label) {
			label.html("&nbsp;").addClass("checked");
		}
	});
	$("#nom").focus(function() {
		var firstname = $("#nom").val();
		var lastname = $("#prenom").val();
		if(firstname && lastname && !this.value) {
			this.value = firstname + "." + lastname;
		}
	});
});
