
/** Vider/remplir les champs */
function vider(input_text, msg){
	if (input_text.value == msg) {
		input_text.value = '';
	}
}
function remplir(input_text, msg){
	if (input_text.value=='' || input_text.value==msg){
		input_text.value=msg;
	}
}
function jQvider(input_text, msg){
	if (input_text.val() == msg) {
		input_text.val('');
	}
}
function jQremplir(input_text, msg){
	if (input_text.val()=='' || input_text.val()==msg){
		input_text.val(msg);
	}
}
function jQsetViderRemplirChamp(input_text, texte_initial) {
	$(document).ready(function() {
		input_text.focus(function() {
			jQvider(input_text, texte_initial);
		});
		input_text.blur(function() {
			jQremplir(input_text, texte_initial);
		});
	});
}

/** Recherche */
$(document).ready(function() {
	$("#field_autocomplete").autocomplete("/macsf/site/ajax/auto_complete_for_recherche.jspz", {"minChars":3, "width":135, "selectFirst":false});
	
	$("#field_autocomplete").click(function() { 
			vider(this, 'Rechercher');
		} 
	).blur(function() { 
			remplir(this, 'Rechercher');
		} 
	); 
});

/** Acces societaire */
$(document).ready(function() {
	if($("#acces-societaire-submit-link").length) {
		$("#acces-societaire-submit-link").click(function() {
			$.modal(modalAccesSocietaire, {overlayClose:true});
		});
	}
	/** Acces societaire ajax */
	if($("#acces-societaire-form-guidance").length) {
		$("#acces-societaire-form-guidance").click(function() { 
			$.modal(modalAccesSocietaire, {overlayClose:true});
		});
		$("#deconnexion-link").click(function() {
			deconnecterAccesSocietaire(); return(false);
		});	
		$("#votre-compte-link").click(function() {
			customTrackPageAnalytics('https://www.espacemembre.macsf.fr/');
		});
	}
	if($("#numsocinput").length) {
		$("#numsocinput").blur(function() { 
			remplir(this,'N° de sociétaire');
		})
		.focus(function() { 
				vider(this,'N° de sociétaire');
			} 
		);
	}
	if($("#cleinput").length) {
		$("#cleinput").blur(function() { 
			remplir(this,'Clé');
		})
		.focus(function() { 
			vider(this,'Clé');
		});
	}
	

	function connecterAccesSocietaire(numsocStr, cleStr) {
		$('#acces_societaire_form').html('<div class="encours">Connexion en cours...</div>');
		$.post('/macsf/site/ajax/acces_societaire_connexion.jspz',
			{numsoc:numsocStr, cle:cleStr},
			function(resp){
				if(resp.substring(0,2)=='OK') {
					customTrackPageAnalytics('https://www.espacemembre.macsf.fr/');
					document.location = 'https://www.espacemembre.macsf.fr/?act=login-redir&nosoc='+numsocStr+'&cle='+cleStr;
				}
				else $('#acces_societaire_form').html(resp);
			}
		);
	}
	function deconnecterAccesSocietaire() {
		$('#acces_societaire_form').html('<div class="encours">D&eacute;connexion en cours...</div>');
		customTrackPageAnalytics('/deconnexion-acces-societaire.html');
		$.post('/macsf/site/ajax/acces_societaire_deconnexion.jspz',
			{},
			function(resp){
				$('#acces_societaire_form').html(resp);
			}
		);
	}
	if($("#acces-societaire-submit").length) {
		$("#acces-societaire-submit").click(function() {
			customTrackPageAnalytics('/soumission-acces-societaire.html');
			connecterAccesSocietaire(document.getElementById('numsocinput').value, document.getElementById('cleinput').value);
			return false;
		});
	}
	if($("#acces-societaire-form-submit-deco").length) {
		$("#acces-societaire-form-submit-deco").click(function() { 
			connecterAccesSocietaire(document.getElementById('numsocinput').value, document.getElementById('cleinput').value);
			customTrackPageAnalytics('/soumission-acces-societaire.html');
			return (false);
		});
	}
	if($("#acces-societaire-form-submit-deco").length) {
		$("#acces-societaire-form-submit").click(function() { 
			customTrackPageAnalytics('/soumission-acces-societaire.html');
			connecterAccesSocietaire(document.getElementById('numsocinput').value, document.getElementById('cleinput').value);
			return false;
		});
	}
	if($("#deconnexion-link").length) {
		$("#deconnexion-link").click(function() {
			deconnecterAccesSocietaire(); return(false);
		});
	}
	if($("#votre-compte-link").length) {
		$("#votre-compte-link").click(function() {
			customTrackPageAnalytics('https://www.espacemembre.macsf.fr/');
		});
	}
});

/* Defilement progressif */
$(document).ready(function() {
	if($("#commentaires").length) {
		if (goToByScrollComment!="") {
			goToByScroll(goToByScrollComment);
		}
	}
});
function goToByScroll(id){
	$('html,body').animate({scrollTop: $("#"+id).offset().top},'medium');
}

function checkOptionLink(idSelect, form_name, messageerreur){
	if ($(idSelect+' option:selected').hasClass('nolink')) {
		alert(messageerreur);
	}
	else {
		$(form_name).submit();
	}
	
}

function desactiverFilsDe(id) {
	var pere = document.getElementById(id);
	
	for(var i=0; i<pere.childNodes.length; i++) {
		var el = pere.childNodes[i];
		// consider html elements only (nodes of type 1)
		if (el.nodeType == 1) {
			el.className = "nonactive";
		}
	}
}

var formOK = 'true';
function formEmailTarget(elementNom, target) {
	var element = document.getElementById(elementNom);
	if (element.value != '') {
		var regexp = /.+@.+\.[a-z]+/;
		if (element.value.search(regexp) == -1) {
			var alert = document.getElementById("alert");
			$("#"+elementNom).addClass("alert");
			alert.className = "alert";
			alert.innerHTML = "<p>Adresse e-mail invalide</p>";
			formOK = 'false';
			if ($('#'+target).length>0) goToByScroll(target);
			else { document.location.href = '#'+target; }
		}
	}
}
function formEmail(elementNom) {
	formEmailTarget(elementNom, '');
}

function removeAccent(s){
	var r=s.toLowerCase();
	r = escape(r);
	r = r.replace(/%E9/g,"e");
	r = r.replace(/%20/g,"-");
    r = r.replace(/\W/g,"");
    r = r.replace(/nB0de/g,"numero");
    return r;
}

function formObligatoireTarget(elementNom, target) {
	if ($("#"+elementNom).val() == '') {
		$("#"+elementNom).addClass("alert");
		var alert = document.getElementById("alert");
		alert.className = "alert";
		alert.innerHTML = "<p>Vous n'avez pas rempli certains champs obligatoires</p>";
		formOK = 'false';
		if ($('#'+target).length>0) goToByScroll(target);
		else { document.location.href = '#'+target; }
	}
}

function formObligatoire(elementNom) {
	formObligatoireTarget(elementNom, '');
}

function formObligatoireEtPositif(elementNom) {
	var element = document.getElementById(elementNom);
	if (element.value == '' || element.value <= 0) {
		$("#"+elementNom).addClass("alert");
		var alert = document.getElementById("alert");
		alert.className = "alert";
		alert.innerHTML = "<p>Vous n'avez pas rempli certains champs obligatoires</p>";
		formOK = 'false';
		if ($('#'+target).length>0) goToByScroll(target);
		else { document.location.href = '#'+target; }
	}
}
/* elementId : id de l'�l�ment � passer en "alert"
   nomForm : le nom du formulaire
   nomAttribut : le nom de l'attribut
   EXEMPLE : formRadioObligatoire('input-radio-type', 'formulaireNavigationForm', 'typeBateau'); */
function formRadioObligatoire(elementId, nomForm, nomAttribut) {
	isRadioCocheFunc(nomForm, nomAttribut);
	if (isRadioCoche == 'false') {
		$("#"+elementId).addClass("alert");
		var alert = document.getElementById("alert");
		alert.className = "alert";
		alert.innerHTML = "<p>Vous n'avez pas rempli certains champs obligatoires</p>";
		formOK = 'false';
		if ($('#'+nomForm).length>0) goToByScroll(nomForm);
		else { document.location.href = '#'+nomForm; }
	}
}

function formFichierObligatoire(elementId) {
	var element = $("#"+elementId+" input");
	if (element.val() == '') {
		$("#"+elementId).addClass("alert");
		var alert = $("#alert");
		alert.addClass("alert");
		alert.html("<p>Vous n'avez pas rempli certains champs obligatoires</p>");
		formOK = 'false';
		if ($('#'+target).length>0) goToByScroll(target);
		else { document.location.href = '#'+target; }
	}
}
/* Fonction qui vérifie à partir du nom du formulaire et du nom de l'attribut radio, s'il est renseigné ou non */
var isRadioCoche = 'false';
function isRadioCocheFunc(nomForm, nomAttribut) {
	isRadioCoche = 'false';
	for (var i=0; i<document.forms[nomForm].length; i++) {
		if (document.forms[nomForm].elements[i].type == 'radio'
			&& document.forms[nomForm].elements[i].checked
			&& document.forms[nomForm].elements[i].name == nomAttribut) {
			isRadioCoche = 'true';
		}
	}
}

function formCheckboxObligatoire(elementId) {
	var elements = $('#'+elementId+' input');
	var inputOk = false;
	for(i=0; i<elements.length; i++)
		if(elements.get(i).checked) inputOk = true;
	if (!inputOk) {
		$("#"+elementId).addClass("alert");
		var alert = $("#alert");
		alert.addClass("alert");
		alert.html("<p>Vous n'avez pas rempli certains champs obligatoires</p>");
		formOK = 'false';
		if ($('#'+target).length>0) goToByScroll(target);
		else { document.location.href = '#'+target; }
	}
}

function formSelectDateClean(elementId) {
	$("#"+elementId+" > [class^='select-'] > [class='select-div'] > select").removeClass("alert");
}

function formClean(elementNom) {
	$("#"+elementNom).removeClass("alert");
}

function formSelectDateCorrectlyFilled(elementId)
{
	// Cette variable détermine le nombre de combo box du sélecteur de date qui ont été renseignés
	var comboBoxSelectedCount = 0;

	$("#"+elementId+" > [class^='select-'] > [class='select-div'] > select option:selected").each(
		function(){
			if($(this).text() != '')
			{
				comboBoxSelectedCount = comboBoxSelectedCount + 1;
			}
		}
	)

	// Si la date n'est que partiellement renseignée
	if((comboBoxSelectedCount != 0) && (comboBoxSelectedCount != 3))
	{
		$("#"+elementId+" > [class^='select-'] > [class='select-div'] > select").addClass("alert");
		var alert = document.getElementById("alert");
		alert.className = "alert";
		alert.innerHTML = "<p>La date n'est pas correctement remplie</p>";
		formOK = 'false';
		document.location.href = '#';
	}
}

$(document).ready(function() {
		$("a[rel=external]").each(
			function() { $(this).attr("target", "_blank"); }
		)
		$('#close_device_redirection').show();
	}
)

/* =========================================================================================================== */
/* L'animation de la boite grille produit */
/* =========================================================================================================== */
if(!window.BoiteGrilleProduit)
	BoiteGrilleProduit=new Object();

BoiteGrilleProduit.setFocus = function(event)
{
	// RAZ du focus
	BoiteGrilleProduit.RAZ();

	if($(this).hasClass("second-col") || $(this).hasClass("first-formule"))
	{
		$("td.second-col").addClass("activated");
		$("th.second-col").addClass("activated");
		$("a.first-formule").addClass("activated");
		$("div.first-formule").show();
		$("td.subtitle.second-col .text").addClass("activated");
	}
	if($(this).hasClass("third-col") || $(this).hasClass("second-formule"))
	{
		$("td.third-col").addClass("activated");
		$("th.third-col").addClass("activated");
		$("a.second-formule").addClass("activated");
		$("div.second-formule").show();
		$("td.subtitle.third-col .text").addClass("activated");
	}
	if($(this).hasClass("fourth-col") || $(this).hasClass("third-formule"))
	{
		$("td.fourth-col").addClass("activated");
		$("th.fourth-col").addClass("activated");
		$("a.third-formule").addClass("activated");
		$("div.third-formule").show();
		$("td.subtitle.fourth-col .text").addClass("activated");
	}
	if($(this).hasClass("fifth-col") || $(this).hasClass("fourth-formule"))
	{
		$("td.fifth-col").addClass("activated");
		$("th.fifth-col").addClass("activated");
		$("a.fourth-formule").addClass("activated");
		$("div.fourth-formule").show();
		$("td.subtitle.fifth-col .text").addClass("activated");
	}
	if($(this).hasClass("sixth-col") || $(this).hasClass("fifth-formule"))
	{
		$("td.sixth-col").addClass("activated");
		$("th.sixth-col").addClass("activated");
		$("a.fifth-formule").addClass("activated");
		$("div.fifth-formule").show();
		$("td.subtitle.sixth-col .text").addClass("activated");
	}
}

BoiteGrilleProduit.RAZ = function(event)
{
	// RAZ du contenu du tableau
	$("td.second-col").removeClass("activated");
	$("td.third-col").removeClass("activated");
	$("td.fourth-col").removeClass("activated");
	$("td.fifth-col").removeClass("activated");
	$("td.sixth-col").removeClass("activated");
	
	// RAZ des lignes de soustitres
	$("td.subtitle .text").removeClass("activated");
	
	// RAZ de la ligne de titre
	$("th.second-col").removeClass("activated");
	$("th.third-col").removeClass("activated");
	$("th.fourth-col").removeClass("activated");
	$("th.fifth-col").removeClass("activated");
	$("th.sixth-col").removeClass("activated");
	
	// RAZ du r�sum� des formules
	$("a.first-formule").removeClass("activated");
	$("a.second-formule").removeClass("activated");
	$("a.third-formule").removeClass("activated");
	$("a.fourth-formule").removeClass("activated");
	$("a.fifth-formule").removeClass("activated");
	
	$("div.first-formule").hide();
	$("div.second-formule").hide();
	$("div.third-formule").hide();
	$("div.fourth-formule").hide();
	$("div.fifth-formule").hide();
}

function initBoiteProduitGrille(garderLaBoiteOuverte){
	// Bind pour les boites grilles produit
	$('a.dt').bind('mouseenter', BoiteGrilleProduit.setFocus);
	$('table#box-tabs-product-examples th.second-col').bind('mouseenter', BoiteGrilleProduit.setFocus);
	$('table#box-tabs-product-examples th.third-col').bind('mouseenter', BoiteGrilleProduit.setFocus);
	$('table#box-tabs-product-examples th.fourth-col').bind('mouseenter', BoiteGrilleProduit.setFocus);
	$('table#box-tabs-product-examples th.fifth-col').bind('mouseenter', BoiteGrilleProduit.setFocus);
	$('table#box-tabs-product-examples th.sixth-col').bind('mouseenter', BoiteGrilleProduit.setFocus);
	
	$('#detail-formule').parent().parent().show();
	
	// On fixe la hauteur de la partie sup�rieure � la plus grande hauteur des d�tails des formules
	var maxHeight = 0;
	var detailsFormules = $('#detail-formule div');
	for(i=0 ; i<detailsFormules.length ; i++)
	{
		var aDetailFormule = $(detailsFormules[i]);
		
		if(aDetailFormule.height() > maxHeight)
		{
			maxHeight = aDetailFormule.height();
		}
	}
	
	$('#detail-formule').height(maxHeight);
	if (garderLaBoiteOuverte != 'true') { $('div div #detail-formule').parent().parent().hide(); }
}

/* =========================================================================================================== */
/* La homepage */
/* =========================================================================================================== */
function initHomepage(){
	$(document).ready(function(){
		$('div#defilement-devis-bas').trigger('click');
	});
};

/* =========================================================================================================== */
/* Les d�l�gations */
/* =========================================================================================================== *//** Google Map */
$(document).ready(function() {
	if ($('#type.docdelegationsite').length) {
		$("#svClose a").click(function() {
				return closeST();
			}
		);
		closeST();
	}
	if($('#formulaire-recherche-delegation').length) {
		$("#A a").click(function() {
			swapPanels();
			return false;
		});
	}
	function remplirVille(codepostal) {
		$.post('/macsf/site/ajax/auto_complete_for_cp.jspz',
			{cp:codepostal},
			function(resp){
				$('#input-line-ville').html(resp);
			});
	}
	$("#codePostal").keyup(function() {
		remplirVille(this.value);
	})
	.change(function() {
		remplirVille(this.value);
	});
	$("#findDelegation").submit(function() {
		findDelegation();
		return false;
	});
	$(".find-delegation-link").click(function() {
		findDelegation(this.id.substring(21));
		return false;
	});
	
});
function findDelegation(delegId) {
	var formulaire = $("#findDelegation");

	if($("#ville", formulaire).val()!="" || $("#codePostal", formulaire).val()!="") {
		// On va concat�ner les champs saisis par l'utilisateur pour obtenir son adresse
		var cp = $("#codePostal", formulaire).val();
		if(cp*1 == cp && cp.length < 3 && $("#ville", formulaire).val()==""){
			if(cp.length == 1){
				cp = "0" + cp;
			}
			getDepartement(cp, delegId);
			return;
		}
		
		var fromAddress = $("#rue", formulaire).val() + " " + cp + " " + $("#ville", formulaire).val() + " france";
		
		// L'objet qui va chercher l'agence MACSF la plus proche
		retriveAgencies(fromAddress, delegId);
	}
}

function getDepartement(cp, delegId){
	$.post('/macsf/site/ajax/getDepartement.jspz?cp=' + cp,
		function(resp){
			if(resp)retriveAgencies(resp, delegId);
		});
}

function retriveAgencies(fromAddress, delegId){
	var geocoder = new GClientGeocoder();
	if(delegId) {
		markerId=-1;
		for(i=0; i<marker.length && markerId==-1;i++) if(marker[i].id==delegId) markerId=i;
		geocoder.getLocations(fromAddress, getAgency);
	}
	else geocoder.getLocations(fromAddress, getNearestAgency);
}

function getNearestAgency(response) {
	if(response.Status.code!=200) return;
	var place = response.Placemark[0];
	var nbAgences = 5;
	if(place.Point.coordinates[0] < -5) {
		nbAgences = 2;
	}
	fromCoordinates = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
	var styleSwap;
	
	var nearest; var nearestPos;

	var nearest2 = new Array();
	var tabMax=1;
	nearest2[0] = {dist:fromCoordinates.distanceFrom(marker[0].latlng),pos:0};
	
	//on recherche les 2 plus proche
	for(i=1; i<marker.length; i++) {
		tmp = fromCoordinates.distanceFrom(marker[i].latlng);
		ok=false;
		for(j=tabMax-1; !ok && j>=0; j--) {
			if(nearest2[j].dist<=tmp) {
				for(k=tabMax; k>j+1; k--) nearest2[k]=nearest2[k-1];
				nearest2[j+1] = {dist:tmp, pos:i};
				if(tabMax<nbAgences) tabMax++;
				ok=true;
			}
		}
		if(!ok) {
			for(k=tabMax; k>0; k--) nearest2[k]=nearest2[k-1];
			nearest2[0] = {dist:tmp, pos:i};
			if(tabMax<nbAgences) tabMax++;
		}
	}

	//Affichage des 2 d�l�g les plus proche
	$("#delegations-list .nearest").removeClass("nearest");
	var delegationsList = $("#delegations-list");
	var cadre = {minLat:100, maxLat:-100, minLng:100, maxLng:-100};
	for(i=0; i<nbAgences; i++) {
		$("#fichedeleg"+marker[nearest2[i].pos].id, delegationsList).addClass("nearest");
	}
	nearest = nearest2[0].dist;
	nearestPos = nearest2[0].pos;

	// il n'y a de rue de saisie, On place la carte sur l es 5 deleg les plus proche
	if($("#rue").val().replace(/^\s+/g,'').replace(/\s+$/g,'') =="") {

		//Affichage des 2 d�l�g les plus proche
		var cadre = {minLat:100, maxLat:-100, minLng:100, maxLng:-100};
		var myMarker;
		for(i=0; i<nbAgences; i++) {
			myMarker = marker[nearest2[i].pos];
			if(myMarker.latlng.lat()<cadre.minLat) cadre.minLat = myMarker.latlng.lat();
			if(myMarker.latlng.lat()>cadre.maxLat) cadre.maxLat = myMarker.latlng.lat();
			if(myMarker.latlng.lng()<cadre.minLng) cadre.minLng = myMarker.latlng.lng();
			if(myMarker.latlng.lng()>cadre.maxLng) cadre.maxLng = myMarker.latlng.lng();
		}

		var zoom;
		var distLat = cadre.maxLat - cadre.minLat;
		var distLng = cadre.maxLng - cadre.minLng;
		if(distLat<0.085369779 && distLng<0.151714325) zoom=12;
		else if(distLat<0.170701029 && distLng<0.30342865) zoom=11;
		else if(distLat<0.340799402 && distLng<0.607615871) zoom=10;
		else if(distLat<0.689183019 && distLng<1.212197456) zoom=9;
		else if(distLat<1.394510199 && distLng<2.427429199) zoom=8;
		else if(distLat<2.797585885 && distLng<4.860926971) zoom=7;
		else if(distLat<5.553312032 && distLng<9.709716797) zoom=6;
		else  zoom=5;
		var oldZoom = map.getZoom();
		if(oldZoom<=6 && zoom>=7) changeFlag(iconB);
		else if(oldZoom>=7 && zoom<=6) changeFlag(iconS);
		map.setCenter(new GLatLng((cadre.maxLat + cadre.minLat)/2,(cadre.maxLng + cadre.minLng)/2), zoom);

		styleSwap = 'nearest';

	} else {
		//On affiche la deleg la plus proche
		styleSwap = 'one';
		markerId = nearestPos;
		displayAgency(response.Placemark[0].address);
	}
	
	swapPanels(styleSwap);
	$('span#nbagences').html(nbAgences);
}

function getAgency(response) {
	if(response.Status.code!=200) return;
	var place = response.Placemark[0];
	fromCoordinates = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
	displayAgency(response.Placemark[0].address);
	swapPanels('one');
}
function displayAgency(address) {
	// L'objet qui va tracer le chemin sur la carte
	if(markerId!=undefined && markerId>=0) {
		if(gdir==undefined) gdir = new GDirections(map, null);
		gdir.clear();
		gdir.load("from: " + fromCoordinates + " to: " + marker[markerId].latlng, { "locale": "fr_FR", "getSteps":false});
	
		//on afiche les info du points
		$("#B").html($("#fichedeleg"+marker[markerId].id).html());
/*		var textA = $("#rue").val();
		if(textA!="") textA+="<br />";
		textA+=$("#codePostal").val()+" "+$("#ville").val();*/
		var tabA = address.split(", ");
		var textA = tabA[0];
		for(i=1;i<tabA.length;i++) if(tabA[i]!="France") textA += "<br />"+tabA[i];
		$("#affichage-votre-adresse").html("<span class=\"adresse\">"+textA+"</span>");
	}
}
function sortGLatLng(a, b){
	return fromCoordinates.distanceFrom(a.latlng) - fromCoordinates.distanceFrom(b.latlng);
}

function swapPanels(style){
	var delegationsList = $("#delegations-list");
	if(style=='one') {
		$('#formulaire-recherche-delegation').css('display', 'none');
		$('#resultat-recherche-delegation').css('display', 'block');
		delegationsList.addClass("onlyFive");
		delegationsList.addClass("showTrajet");
	}
	else if(style=='nearest') {
		$('#formulaire-recherche-delegation').css('display', 'block');
		$('#resultat-recherche-delegation').css('display', 'none');
		delegationsList.addClass("onlyFive");
		delegationsList.addClass("showTrajet");
		if(gdir!=undefined) gdir.clear();
	}
	else {
		$('#formulaire-recherche-delegation').css('display', 'block');
		$('#resultat-recherche-delegation').css('display', 'none');
		delegationsList.removeClass("onlyFive");
		delegationsList.removeClass("showTrajet");
		if(gdir!=undefined) gdir.clear();
	}
}

/* =========================================================================================================== */
/* Le formulaire de navigation de plaisance */
/* =========================================================================================================== */
function commaToDot(elementNom){
	var element = document.getElementById(elementNom);
	element.value = element.value.replace(/,/g, '.');
}

function initDisableUnavailableInput(){

	// Pour le moteur principal
	var checkboxMoteurPrincipal = $("input#moteurPrincipal");
	checkboxMoteurPrincipal.bind('click', disableUnavailableInput);
	
	// Pour le moteur amovible annexe
	var checkboxMoteurAmovible = $("input#moteurAmovible");
	checkboxMoteurAmovible.bind('click', disableUnavailableInput);

	// Pour la remorque
	var checkboxRemorque = $("input#remorque");
	checkboxRemorque.bind('click', disableUnavailableInput);
}

function disableUnavailableInput(){

	// Pour le moteur principal
	var checkboxMoteurPrincipal = $("input#moteurPrincipal");
	if(checkboxMoteurPrincipal.attr('checked') == true)
	{
		$('input#marqueMoteurPrincipal').removeAttr("disabled");
		$('input#typeMoteurPrincipal1').removeAttr("disabled");
		$('input#typeMoteurPrincipal2').removeAttr("disabled");
		$('input#carburantMoteurPrincipal1').removeAttr("disabled");
		$('input#carburantMoteurPrincipal2').removeAttr("disabled");
		$('input#puissanceMoteurPrincipal').removeAttr("disabled");
		$('select#anneeMoteurPrincipal').removeAttr("disabled");
	}
	else
	{
		$('input#marqueMoteurPrincipal').attr("disabled","disabled");
		$('input#typeMoteurPrincipal1').attr("disabled","disabled");
		$('input#typeMoteurPrincipal2').attr("disabled","disabled");
		$('input#carburantMoteurPrincipal1').attr("disabled","disabled");
		$('input#carburantMoteurPrincipal2').attr("disabled","disabled");
		$('input#puissanceMoteurPrincipal').attr("disabled","disabled");
		$('select#anneeMoteurPrincipal').attr("disabled","disabled");
	}
	
	// Pour le moteur amovible annexe
	var checkboxMoteurAmovible = $("input#moteurAmovible");
	if(checkboxMoteurAmovible.attr('checked') == true)
	{
		$('input#typeMoteurAmovible1').removeAttr("disabled");
		$('input#typeMoteurAmovible2').removeAttr("disabled");
		$('input#puissanceMoteurAmovible').removeAttr("disabled");
		$('select#anneeMoteurAmovible').removeAttr("disabled");
	}
	else
	{
		$('input#typeMoteurAmovible1').attr("disabled","disabled");
		$('input#typeMoteurAmovible2').attr("disabled","disabled");
		$('input#puissanceMoteurAmovible').attr("disabled","disabled");
		$('select#anneeMoteurAmovible').attr("disabled","disabled");
	}

	// Pour la remorque
	var checkboxRemorque = $("input#remorque");
	if(checkboxRemorque.attr('checked') == true)
	{
		$('input#immatriculation').removeAttr("disabled");
		$('input#valeurRemorque').removeAttr("disabled");
		$('select#jourMiseEnCirculation').removeAttr("disabled");
		$('select#moisMiseEnCirculation').removeAttr("disabled");
		$('select#anneeMiseEnCirculation').removeAttr("disabled");
	}
	else
	{
		$('input#immatriculation').attr("disabled","disabled");
		$('input#valeurRemorque').attr("disabled","disabled");
		$('select#jourMiseEnCirculation').attr("disabled","disabled");
		$('select#moisMiseEnCirculation').attr("disabled","disabled");
		$('select#anneeMiseEnCirculation').attr("disabled","disabled");
	}
}
/* =========================================================================================================== */
/* Formulaire dynamique */
/* =========================================================================================================== */
function initTooltips(){
	$(document).ready(function(){
		$("#form-dynamique .tooltip").tooltip({
			track: false,
			delay: 0,
			showURL: false,
			showBody: " - ",
			extraClass: "pretty",
			fixPNG: true,
			left: -120
		});
	});
}

/* =========================================================================================================== */
/* Formulaire pas à pas */
/* =========================================================================================================== */
var pasapas_questioncourante = 1;

function pasapas_Suite() {

	checkedRadio = $('form#formulaire-pasapas input[id^=q' + pasapas_questioncourante + ']:checked');
	checkedRadioValue = $(checkedRadio).val();

	if (!checkedRadioValue) {
		$('#erreur').show();
	}
	else {
		$('#erreur').hide();
		if (checkedRadioValue == 'no') {
			$('#q' + pasapas_questioncourante).hide();
			$('#pasapas-echec-' + pasapas_questioncourante).show();
		}
		else if (pasapas_questioncourante == $('.bloc-question[id^=q]').length) {
			$('#q' + pasapas_questioncourante).hide();
			$('#pasapas-reussite').show();
		}
		else {
			$('#q' + pasapas_questioncourante).hide();
			pasapas_questioncourante++;
			$('#q' + pasapas_questioncourante).show();
		}
	}
}

function pasapas_RetourDebut() {
	// Retour aux valeurs d'origine
	$('form#formulaire-pasapas').clearForm();
	
	// Retour a l'affichage d'origine
	$('#erreur').hide();
	$('#pasapas-reussite').hide();
	$('#pasapas-echec-' + pasapas_questioncourante).hide();
	$('#q' + pasapas_questioncourante).hide();
	pasapas_questioncourante = 1;
	$('#q' + pasapas_questioncourante).show();
}

function pasapas_Retour() {
	// Retour a l'affichage d'origine
	$('#erreur').hide();
	$('#pasapas-reussite').hide();
	$('#pasapas-echec-' + pasapas_questioncourante).hide();
	$('#q' + pasapas_questioncourante).hide();
	pasapas_questioncourante--;
	$('#q' + pasapas_questioncourante).show();
}

$.fn.clearForm = function() {
  // iterate each matching form
  return this.each(function() {
    // iterate the elements within the form
    $(':input', this).each(function() {
      var type = this.type, tag = this.tagName.toLowerCase();
      if (type == 'text' || type == 'password' || tag == 'textarea')
        this.value = '';
      else if (type == 'checkbox' || type == 'radio')
        this.checked = false;
      else if (tag == 'select')
        this.selectedIndex = -1;
    });
  });
};
/* =========================================================================================================== */
/* Formulaire contact pour un devis */
/* =========================================================================================================== */
function initDatePicker(){
		$.datepicker.setDefaults($.extend({showMonthAfterYear: false}, $.datepicker.regional['']));
		$("#dateRappel").datepicker({showOn: 'both', buttonImage: '/file/resources/macsf/site/images/financier/calendrier.png', buttonImageOnly: true});
		$("#dateRappel").datepicker('option', {dateFormat: 'dd/mm/yy', minDate: 0, maxDate: '+6M'});
		$('#dateRappel').datepicker('option', $.extend({showMonthAfterYear: false}, $.datepicker.regional['fr']));
}

function openProfilSoft(idOffer, idPartenaire) {
	var ifr = document.createElement('iframe');
	var src = "http://macsf.profilsearch.com/recrute/fo_form_cand.php";
	if(idOffer!=undefined) {
		src+="?id="+idOffer;
		if(idPartenaire!=undefined && idPartenaire!='') src+="&amp;idpartenaire="+idPartenaire;
	}
	ifr.src= src;

	ifr.style.width = '755px';
	ifr.style.height = ''+($(window).height()-100)+'px';
	ifr.style.top = ifr.style.left = 0;
	ifr.style.border = 0;
	$.modal(ifr, {containerId:'modalContainerRh', overlayClose:true});
}

function openCallback(urlComplete) {
	$(document).ready(function(){
		var ifr = document.createElement('iframe');
		ifr.src= urlComplete;
	
		ifr.style.width = '755px';
		ifr.style.height = '600px';
		ifr.style.top = ifr.style.left = 0;
		ifr.style.border = 0;
		$.modal(ifr, {containerId:'modalContainerCallback', overlayClose:true});
	});
}

function openRetraite(urlComplete) {
	$(document).ready(function(){
		var ifr = document.createElement('iframe');
		ifr.src= urlComplete;
	
		ifr.style.width = '600px';
		ifr.style.height = '540px';
		ifr.style.top = ifr.style.left = 0;
		ifr.style.border = 0;
		$.modal(ifr, {containerId:'modalContainerRetraite', overlayClose:true});
	});
}

function openRetraiteUrl() {
	openRetraite('http://efuturisweb.macsf.harvest.fr/');
}

/* =========================================================================================================== */
/* Pagination dans les docs standard
/* =========================================================================================================== */
function changePageDoc(num) {
	$("#docparagraphes .pagination").removeClass("firstpage");
	$("#docparagraphes .pagination").removeClass("lastpage");
	if( $("#docparagraphes .pagination .docpage"+(num-1)).size()==0)
		$("#docparagraphes .pagination").addClass("firstpage");
	else if( $("#docparagraphes .pagination .docpage"+(num+1)).size()==0)
		$("#docparagraphes .pagination").addClass("lastpage");
	$("#docparagraphes .pagination .thispage").removeClass("thispage");
	$("#docparagraphes .pagination .docpage"+num).addClass("thispage");
	$("#docparagraphes .docparagraphe").hide();
	$("#docparagraphes .docparagraphe"+num).show();
}
function previousPageDoc(num) {
	changePageDoc(parseInt($("#docparagraphes .pagination .thispage").html())-1);
}
function nextPageDoc(num) {
	changePageDoc(parseInt($("#docparagraphes .pagination .thispage").html())+1);
}

/* =========================================================================================================== */
/* Formulaires sinistres auto et habitation */
/* =========================================================================================================== */
function initFormulaires() {
	$(document).ready(function(){
		$('.block#accident-declare').hide();
		
		$('input#followingSequence1')
		.bind(
			'click',
			function(event) {
				$('.block#accident-question').hide();
				$('.block#accident-declare').show();
			}
		);
		$('input#followingSequence2')
		.bind(
				'click',
				function(event) {
					$('.block#accident-question').show();
					$('.block#accident-declare').hide();
				}
		);

		$('.inputs-line#towingPhoneNumber').hide();
		$('input#wreck1, input#wreck2')
		.bind(
				'click',
				function(event) {
					if($('input#wreck2').is(':checked')) {
						$('.inputs-line#towingPhoneNumber').show();
					}
					else {
						$('.inputs-line#towingPhoneNumber').hide();
					}
				}
		);
	});
}

/** TRACKING GOOGLE E-COMMERCE **/
function googleECommerceTracking(transactionId, productId, productName, productCategory) {
	try {
		var pageTracker = _gat._getTracker("UA-7392033-3"); 
		pageTracker._trackPageview(); 
		pageTracker._addTrans(
				transactionId,
				"Macsf.fr",
				"0.00",
				"0.00",
				"0.00",
				"",
				"",
				""
		); 
		pageTracker._addItem(
				transactionId,
				productId,
				productName,
				productCategory,
				"0.00",
				"1"
		); 
		pageTracker._trackTrans();
	} catch(err) {}
}

function customTrackPageAnalytics(url) {
	if(url.substring(0,26)=='/nos-produits-et-services/') {
		_gaq.push(['_trackPageview', url]);
	} else {
		_gaq.push(['_trackEvent', 'Actions JS', url]);
	}
}

/** VOIR LA SUITE COMMENTAIRES */
function voirlasuiteCommentaires() {
	$('#voirlasuitecommentaires').css('background-image', 'none');
	$('.comment-loading').css('visibility', 'visible');
	$.get('/macsf/site/ajax/voirlasuite_commentaires.jspz',
			{begin:commentStart, end:commentEnd, docType:commentType, docId:commentDocId},
			function(resp){
				$('#voirlasuitecommentaires').before(resp);
				commentStart = commentEnd+1;
				commentEnd = commentStart+commentStep-1;
				$('#voirlasuitecommentaires').css('background-image', 'url("/file/resources/macsf/site/images/docsite/comment_voirlasuite_arrow.png")');
				$('.comment-loading').css('visibility', 'hidden');
				cacherLienPlusDeComs();
			});
}
function cacherLienPlusDeComs() {
	if(plusDeComs == true) {
		$("#voirlasuitecommentaires").css('display', 'none');
	}
}
$(document).ready(function() {
	if($("#voirlasuitecommentaires a").length) {
		$("#voirlasuitecommentaires a").click(function() {
			voirlasuiteCommentaires();
			return false;
		});
	}
});

/** Le controleur etoiles pour les produits (note de 1 a 5) **/
function showStarsWithScore(score) {
	$('#starGradingField').attr('class', 'grade'+score);
}
function cancelScore() {
	$('#starHiddenInput').val('0');
	$('#starGradingField').attr('class', 'grade0');
	$('#starCancel').removeClass('active');
}
function showStarsHowItIsRecorded() {
	showStarsWithScore($('#starHiddenInput').val());
}
function getRecordedScore() {
	return $('#starGradingField').attr('class').substring(5);
}
function recordScore(score) {
	$('#starHiddenInput').val(score);
	$('#starGradingField').attr('class', 'grade'+score);
	$('#starCancel').addClass('active');
}
function initStarScores() {
	$(document).ready(function(){
		$('#starCancel').click(cancelScore);
		$('#starGradingField .star').mouseout(showStarsHowItIsRecorded);
		$('#starGradingField .star').each( function() {
			var nbStar = $(this).attr('id').substring(4);
			$(this).mouseover(function(){showStarsWithScore(nbStar)});
			$(this).click(function(){recordScore(nbStar)});
		});
	});
}

function closeDeviceRedirection(){
	$.get('/macsf/site/ajax/close_device_redirection.jspz?ajax=1', function(data) {
		$('div.device-redirection').hide();
		});
	return false;
}
$(document).ready(function() {
	if($('#close_device_redirection').length) {
		$("#close_device_redirection").click(function() {
				closeDeviceRedirection();
				return false;
			}
		);
	}
});

/** JS deporte depuis lien quelconque */
$(document).ready(function(){
	if ($('a.addAnalyticsCall').length) {
		$('a.addAnalyticsCall').click(function () {
			// pageTracker._trackPageview($(this).attr("href"));
			customTrackPageAnalytics($(this).attr("href"));
		});
	}
});
$(document).ready(function(){
	if ($('a.clickLienDevis').length) {
		$('a.clickLienDevis').click(function () {
			customTrackPageAnalytics('/click-lien-devis');
		});
	}
});

$(document).ready(function(){
	if ($('a.trackConv').length) {
		$('a.trackConv').click(function () {
			var google_conversion_id =1032297207; 
			var google_conversion_label = "hU35CIO8oAEQ97We7AM"; 
			image = new Image(1,1); 
			image.src = "http://www.googleadservices.com/pagead/conversion/"+google_conversion_id+"/?label="+google_conversion_label+"&amp;script=0"; 
		});
	}
});
$(document).ready(function(){
	if ($('a.lienProduitALaVolee').length) {
		$('a.lienProduitALaVolee').click(function () {
			var longlink = $(this).attr("href");
			var shortlink;
			if (longlink.indexOf("?", 0)>0) {
				shortlink = longlink.substring(0, longlink.indexOf("?", 0));
				longlink = shortlink+'?category='+category+'&statutproselect='+$('#statutproselect').val();
				if (rubriquemere!='') {longlink = longlink+'&rubriquemere='+rubriquemere;}
				if (prodId!='') {longlink = longlink+'&prodId='+prodId;}
			}
			$(this).attr("href", longlink);
		});
	}
});

$(document).ready(function(){
	if ($('a.googleECommerce').length) {
		$('a.googleECommerce').click(function () {
			var metaECommerce = $(this).metadata();
			var time = (new Date()).getTime();
			googleECommerceTracking(time, metaECommerce.productId, metaECommerce.productName, metaECommerce.productCategory);
		});
	}
});

/** JS pour le changement de page sur les documents standards */
$(document).ready(function() {
	if ($('#first-page-link').length) {
		$("#first-page-link").click(function() {
				changePageDoc(1);
				return false;
			}
		);
		$(".previouspage").click(function() {
				previousPageDoc();
				return false;
			}
		);
		$(".nextpage").click(function() {
				nextPageDoc();
				return false;
			}
		);
		$(".adocpage").click(function() {
				changePageDoc($(this).html());
				return false;
			}
		);
		//if(nbPages>0) {
//			$(".item-sommaire").click(function() {
//					changePageDoc($(this).attr("rel"));
//					return false;
//				}
//			);
		//}
	}
});

/** Navigation produits sur les pages de gamme */
$(document).ready(function() {
	if ($('#situation-link').length) {
		$("#situation-link").click(function() {
			$('#content-left-menu-sort-by-category').addClass('besoins');
			$('#content-left-menu-sort-by-category').removeClass('situation');
			category='besoins';
			return (false);
		});
		$("#besoins-link").click(function() {
			$('#content-left-menu-sort-by-category').addClass('situation');
			$('#content-left-menu-sort-by-category').removeClass('besoins');
			category='situation';
			return (false);
		});
		$("#statutproselect").change(function() {
			document.getElementById('content').className= 'sort'+this.value;
			customTrackPageAnalytics('/profession-change');
		});
		$("#statut-professionnel .contenu-modal").click(function() { 
			$.modal(statutProfessionnelContenuModal, {overlayClose:true});
		});
	}
});

/** Home produits */
// Cette méthode est appellée lors du survol de la partie inférieure et supérieure de la home produit
function homeProdRetourCacheOriginal() {
	derniereImage = '_statut_pro_' + statutSelected;
	dernierLeftOrRight = '';
}
function homeProdRetourImagePrincipale() {
	document.getElementById('content-contener').className = '';
	document.getElementById('contener-center-center').className = 'showhomeimage_statut_pro_' + statutSelected;
	document.getElementById('content-contener-liactif').className = '';
}

// Cette méthode est appelée lorsque un item est sélectionné dans le menu de gauche ou droite
function homeProdChangement(leftOrRight, idRubrique) {
	
	// On sauvegarde le coté et la rubrique qui vient d'être sélectionné
	derniereImage = idRubrique;
	dernierLeftOrRight = leftOrRight;
	
	// On détermine quel est le coté sélectionné
	document.getElementById('content-contener').className = leftOrRight;
	
	// On affiche l'image liée à la rubrique sélectionnée
	document.getElementById('contener-center-center').className = 'showhomeimage'+idRubrique;
	
	// On définit quel est le lien actif (bleu ciel + flèche blanche)
	document.getElementById('content-contener-liactif').className = 'actif'+idRubrique;
}
function homeProdDernierEtat() {
	document.getElementById('content-contener').className = dernierLeftOrRight;
	document.getElementById('contener-center-center').className = 'showhomeimage'+derniereImage;
}
function homeProdStatutSelected(indexStatutSelected) {
	statutSelected = indexStatutSelected;
}

$(document).ready(function() {
	if ($('#homeprod').length) {
		homeProdRetourImagePrincipale();
		$("#content-form").mouseover(function() {
				homeProdRetourCacheOriginal();
			}
		);
		$("#content-bottom").mouseover(function() {
			homeProdRetourCacheOriginal();
		});
		$("#statut-professionnel-link").click(function() {
				$.modal(modalProduits, {overlayClose:true});
			}
		);
		$("#contener-center-left ul").mouseover(function() {
				homeProdDernierEtat();
			}
		).mouseout(function() {
				homeProdRetourImagePrincipale();
			}
		);
		$("#contener-center-right ul").mouseover(function() {
				homeProdDernierEtat();
			}
		).mouseout(function() {
				homeProdRetourImagePrincipale();
			}
		);
		$("#contener-center-center").mouseover(function() {
			homeProdDernierEtat();
		})
		.mouseout(function() {
			homeProdRetourImagePrincipale();
		});
		
		$("#statutproselect").change(function() {
				document.getElementById('content-contener-sort').className= 'sort'+this.value;
				homeProdRetourCacheOriginal();
				homeProdStatutSelected(this.value);
				homeProdRetourImagePrincipale();
				customTrackPageAnalytics('/profession-change');
			}
		);
		

		$("li.actifBesoin").mouseover(function() {
				var idBesoin = $(this).attr('id').substring(5);
				homeProdChangement('left', idBesoin);
			}
		).mouseout(function() {
				homeProdRetourImagePrincipale();
			}
		);
		$("li.actifBesoin a").click(function() {
			var questionMarkPosition = $(this).attr('href').indexOf('?', 0);
			$(this).attr('href', $(this).attr('href').substring(0, questionMarkPosition)+'?category=besoins&statutproselect='+document.getElementById('statutproselect').value);
		});
		
		$("li.actifSituation").mouseover(function() {
			var idBesoin = $(this).attr('id').substring(5);
			homeProdChangement('right', idBesoin);
		})
		.mouseout(function() {
				homeProdRetourImagePrincipale();
			}
		);
		$("li.actifSituation a").click(function() {
			var questionMarkPosition = $(this).attr('href').indexOf('?', 0);
			$(this).attr('href', $(this).attr('href').substring(0, questionMarkPosition)+'?category=besoins&statutproselect='+document.getElementById('statutproselect').value);
		});
	}
});

/** Bloc contact avec callback */
$(document).ready(function() {
	if($('#bloc-contact-2').length) {
		$("#button-panel a").click(function() {
				$("#phone-callback").animate({height: '98px'});
				$("#button-panel").hide("fast");
				$("#form-panel").show("fast");
				return false; 
			} 
		);
		$("#form-panel button").click(function() {
			$('input#telephoneNumberCallbackInput').addClass('loading');
			var telephoneNumber = $("#form-panel input").val();
			$.post('/macsf/site/ajax/askCallback.jspz',
				{telephoneNumber : telephoneNumber},
				function(resp){
					$("#message-panel-success span").html(resp)
					$("#form-panel").hide("fast");
					$("#message-panel-success").show("fast");
					$("#phone-callback").animate({height: '60px'});
				}
			);
			return false;
		});
	}
});

/** Retraite simulateur Harvest */
$(document).ready(function(){
	if (harvestSimulator=='on') {
		openRetraite(harvestUrl);
	}
});

/** Parametre callback */
$(document).ready(function(){
	if (callbackParam=='on') {
		if (callbackHours=='true') {
			openCallback(callbackGeneralUrl);
		}
		else {
			$.modal('<div id="callbacklatermodal">'+callbackLightbox+'</div>', {containerId:'modalContainerCallback', overlayClose:true});
		}
	}
});

/** Fleche menu */
$(document).ready(function(){
	if($('.content-left-menu').length) {
		if (itemList!='') {
			setMenuPosition(itemList);
		}
	}
});

/** Affichage tout article par profession ou theme */
$(document).ready(function() {
	if($('#profession-contenu-modal').length) {
		if (professionContenuModal!='') {
			$("#profession-contenu-modal a").click(function() {
					$.modal(professionContenuModal, {overlayClose:true});
				}
			);
		}
	}
	if($('#theme-contenu-modal').length) {
		if (themeContenuModal!='') {
			$("#theme-contenu-modal a").click(function() {
					$.modal(themeContenuModal, {overlayClose:true});
				}
			);
		}
	}
	if($('#voirtouslesarticles-nojs').length) {
		$('#voirtouslesarticles-nojs').css('display', 'none');
	}
	if($('#voirtouslesarticles-selectboxes').length) {
		$('#voirtouslesarticles-selectboxes').css('display', 'block');
	}
});

/** Ellipse */
$(document).ready(function() {
	if($('#ellipse-top').length) {
		for ( var int = 0; int < ellipse.length; int++) {
			if ($("#ellipse-image-link-"+ellipse[int]["tempImagesID"]).length) {
				$("#ellipse-image-link-"+ellipse[int]["tempImagesID"]).click(function() {
						var id = $(this).attr('id').substring($(this).attr('id').lastIndexOf("-") + 1);
						Ellipse.displayText(id);
						customTrackPageAnalytics(ellipse[0]["url"]+'?societe'+id);
						return false;
					}
				);
			}
			if ($("#ellipse-image-"+ellipse[int]["tempImagesID"]).length) {
				$("#ellipse-image-"+ellipse[int]["tempImagesID"]).mouseover(function() {
						Ellipse.setFocus(this,ellipse[0]["zoomRatio"]);
					}
				);
			}
		}
	}
});

/** Agenda */ 
function afficherEvenementsDate(anneeStr, moisStr, jourStr) {
	$('#events').html('<span class="encours">Recherche en cours...</span>');
	$.get('/macsf/site/ajax/event_for_agenda.jspz',
		{annee:anneeStr,mois:moisStr,jour:jourStr,urlThis:tempUrlThis,preview:tempPreview,filtrId:tempFiltrId,filtrType:tempFiltrType},
		function(resp){
			$('#events').html(resp);
		});
}

$(document).ready(function() {
	if($('#agendaparannee').length) {
		for (var int = 0; int < dates.length; int++) {
			$("a#day-"+dates[int]["annee"]+"-"+dates[int]["mois"]+"-"+dates[int]["jour"]).click(function() {
					var annee = $(this).attr('id').substring(4,8);
					var mois = $(this).attr('id').substring(9,$(this).attr('id').lastIndexOf("-"));
					var jour = $(this).attr('id').substring($(this).attr('id').lastIndexOf("-") + 1);
					afficherEvenementsDate(annee, mois, jour);
					document.location='#eventsTarget';
					return false;
				}
			);
		}
	}
});

/** Historique */
$(document).ready(function() {
	if($('#historique').length) {
		$(".historique").each(function() {
			var metaHistorique = $(this).metadata();
			$("#periodetitre-"+metaHistorique.id+" a").click(function() {
					desactiverFilsDe('periodecontents');
					desactiverFilsDe('periodetitres');
					document.getElementById('periodetitre-'+metaHistorique.id).className = 'active';
					document.getElementById('periodecontent-'+metaHistorique.id).className = 'active';
					return (false);
				}
			);
		});
	}
});

/** Page 404 */
$(document).ready(function() {
	if($('#field_autocomplete2').length) {
		$("#field_autocomplete2").blur(function() {
				remplir(this,'Rechercher');
			}
		).click(function() {
				vider(this, 'Rechercher');
			}
		);
		$("#field_autocomplete2").autocomplete("/macsf/site/ajax/auto_complete_for_recherche.jspz", {"minChars":3, "width":135, "selectFirst":false});
	}
});

/** Recrutement */
function showOption(papa, fiston, table) {
	if(table.length==0) {
		var i = 0;
		$("#"+fiston+" option").each(function(){table[i]={classe:$(this).attr('class'), value:$(this).val(), texte:$(this).html()}; i++;});
	}
	var val = $("#"+papa).val();
	var fistonObj = $("#"+fiston);
	var valFiston = fistonObj.val();
	fistonObj.html("");
	for(i=0;i< table.length; i++)
		if(val=='' || table[i].classe=='' || table[i].classe=="p"+val) fistonObj.append('<option value="'+table[i].value+(table[i].value==valFiston?'" selected="selected':'')+'">'+table[i].texte+'</option>');
	fistonObj.parent().css('text-align','left');
	fistonObj.parent().css('text-align','right');
}

$(document).ready(function() {
	var myDepartement = new Array();
	if($("#region").length){
		if($("#region").val()!='') showOption('region', 'departement', myDepartement);
	}
	if($("#recrut-offres").length){
		$(".contrat").each(function() {
			var metaContrat = $(this).metadata();
			$("#tab"+metaContrat.count+" a").click(function() {
				showTab(metaContrat.count);return false;
			});
		});
	}
	if($("#job-container").length){
		myLoc = ''+document.location;
		locPos = myLoc.indexOf("#");
		if(locPos>0) showTab(myLoc.substr(locPos+8));
		else showTab(1);
		
		$(".recrut-demande a").click(function() {
				openProfilSoft(1);
				return false;
			}
		);
		$("#region").change(function() { 
				showOption('region', 'departement', myDepartement);
			} 
		);
	}
});

/** Societes */
$(document).ready(function() {
	if($('#ellipse-top').length) {
		Ellipse.setFocus($("#ellipse-image-"+idVisible)[0], 1);
	}
});

/** Valeurs mutualistes */
$(document).ready(function(){
	if($('#arbre-complet').length) {
		initArbre();
	}
});

/** Formulaires pas a pas */
$(document).ready(function() {
	if($('#formulaire-pasapas').length) {
		$(".jsQuestion").each(function() {
			var metaQuestion = $(this).metadata();
			$("#q"+metaQuestion.indexQuestion+" .bouton-suite input").click(function() {
				pasapas_Suite();
				return false;
			});
			if(metaQuestion.indexQuestion != 1) {
				$("#q"+metaQuestion.indexQuestion+" .bouton-suite a").click(function() {
					pasapas_Retour();
					return false;
				});
			}
			$("#pasapas-echec-"+metaQuestion.indexQuestion+" a").click(function() {
				pasapas_RetourDebut();
				return false;
			});
		});
		$("#back-button").click(function() {
				pasapas_RetourDebut();
				return false;
			}
		);
	}
});

/** Home */
$(document).ready(function() {
	if ($('#avt').length) {
		$('#avt').cycle({ fx: 'fade', pause: 1, timeout: timeout, startingSlide: startingSlide });
	}
	if ($('#groupe').length) {
		initHomepage();
		$('#devis-list').cycle({
			fx:'scrollVert',
			speed: 400,
			next:'#defilement-devis-haut',
			prev:'#defilement-devis-bas',
			timeout: 0
		});
		$('#defilement-devis-bas').click();
		$('#info-caroussel').cycle({ fx:    'scrollUp', pause:  1 });
	}
});

/** Form Recherche */
$(document).ready(function() {
	if($('#form-dynamique')) {
		$("#search-input-text").click(function() {
				vider(this, keywords);
			}
		).blur(function() {
				remplir(this,keywords);
			}
		);
		$(".keywords").autocomplete("/macsf/site/ajax/auto_complete_for_recherche.jspz", {"minChars":3, "width":219, "matchSubset":false});
	}
	if($('#paramsSet').length || $('#paramsNotSet').length) {
		$("#votre-profession-select").change(function() {
			checkOptionLink('#votre-profession-select','#votre-profession', JSmessage);
		});
		$("#votre-theme-select").change(function() {
			checkOptionLink('#votre-theme-select','#choisissez-theme', JSmessage);
		});
	}
});

/** Form Accident voiture */
$(document).ready(function() {
	if($('#carAccidentForm').length) {
		initFormulaires();
		$("#zipCode").keyup(function() {
			remplirVille(this.value);
		}).change(function() { 
			remplirVille(this.value);
		});
		$(".submit-envoyer input").click(function() {
			formOK = 'true';
			$('#alert').removeClass('alert').removeClass('info');
			formClean('lastname');
			formClean('firstname');
			formClean('contractNumber');
			formClean('address');
			formClean('zipCode');
			formClean('city');
			formClean('personalPhoneNumber');
			formClean('mail');
			formEmail('mail');
			formObligatoire('lastname');
			formObligatoire('firstname');
			formObligatoire('contractNumber');
			formObligatoire('address');
			formObligatoire('zipCode');
			formObligatoire('city');
			formObligatoire('personalPhoneNumber');
			formObligatoire('mail');
			if (formOK == 'true') {
				document.getElementById('alert').innerHTML = '<p>Envoi en cours...</p>';
				document.getElementById('alert').className = 'info';
				_gaq.push(['_trackEvent', 'Validation Formulaire', 'Accident voiture']);
				$('#carAccidentForm').submit();
			}
			return false;
		});
	}
});

function remplirVille(codepostal) {
	$.get(urlAjaxVille,
		{cp:codepostal},
		function(resp){
			$('#ajax_body_ville').html(resp);
		});
}

/** Formulaire demande de devis */
$(document).ready(function() {
	if($('#contactDevisForm').length) {
		initDatePicker();
		$("#datenaissance").mask("99/99/9999");
		$("#societaire1, #societaire2").click(function() {
			activeNum(this, $('#contactDevisForm'));
		});
		$(".submit-envoyer input").click(function() {
			formOK = 'true';
			document.getElementById('alert').className = '';
			formClean('nom');
			formClean('prenom');
			formClean('codePostal');
			formClean('ville');
			formClean('telephone');
			formClean('mail');
			formEmail('mail');
			formObligatoire('nom');
			formObligatoire('prenom');
			formObligatoire('codePostal');
			formObligatoire('ville');
			formObligatoire('telephone');
			formObligatoire('mail');
			if (document.forms['contactDevisForm'].societaire[0].checked) {
				formObligatoire('numeroSocietaire');
				document.getElementById('profession').className='';
				document.getElementById('statut').className='';
			}
			else {
				formObligatoire('profession');
				formObligatoire('statut');
				document.getElementById('numeroSocietaire').className='';
			}
			if (formOK == 'true') {
				document.getElementById('alert').innerHTML = '<p>Envoi en cours...</p>';
				document.getElementById('alert').className = 'info';
				_gaq.push(['_trackEvent', 'Validation Formulaire', 'Contact Devis']);
				$('#contactDevisForm').submit();
			}
			return(false);
		});
		$("#codePostal").keyup(function() {
			remplirVille(this.value);
		}).change(function() { 
			remplirVille(this.value);
		});
	}
});

function activeNum(champ, form) {
	var numSoc = document.getElementById('cache_numSoc');
	var profession = document.getElementById('cache_profession');
	if (champ.value == "true") {
		$('#profession', form).val('');
		if($('#statut').length) {
			$('#statut', form).val('');
		}
		profession.style.display="none";
		numSoc.style.display = "inline";
	} else {
		$('#numeroSocietaire', form).val('');
		numSoc.style.display = "none";
		profession.style.display="inline";
	}
}

/** Formulaire de contact */
$(document).ready(function() {
	if($('#contactForm').length) {
		$("#societaire1, #societaire2").click(function() {
			activeNum(this, $('#contactForm'));
		});
		$(".submit-envoyer input").click(function() {
			formOK = 'true';
			document.getElementById('alert').className = '';
			formClean('sujet');
			formClean('votre-commentaire');
			formClean('nom');
			formClean('prenom');
			formClean('adresse');
			formClean('codePostal');
			formClean('ville');
			formClean('mail');
			formEmail('mail');
			formObligatoire('sujet');
			formObligatoire('votre-commentaire');
			formObligatoire('nom');
			formObligatoire('prenom');
			formObligatoire('adresse');
			formObligatoire('codePostal');
			formObligatoire('ville');
			formObligatoire('mail');
			if (document.forms['contactForm'].societaire[0].checked) {
				formObligatoire('numeroSocietaire');
				document.getElementById('profession').className='';
			}
			else {
				formObligatoire('profession');
				document.getElementById('numeroSocietaire').className='';
			}
			if (formOK == 'true') {
				document.getElementById('alert').innerHTML = '<p>Envoi en cours...</p>';
				document.getElementById('alert').className = 'info';
				_gaq.push(['_trackEvent', 'Validation Formulaire', 'Contact']);
				document.forms['contactForm'].submit();
			}
			return(false);
		});
		$("#codePostal").keyup(function() {
			remplirVille(this.value);
		}).change(function() {
			remplirVille(this.value);
		});
	}
});

/** Formulaire de désinscription newsletter */
$(document).ready(function() {
	if($('#deinscrire').length) {
		$("#deinscrire").click(function() {
			formOK = 'true';
			document.getElementById('alert').className = '';
			formClean('reductionEmail');
			formClean('desinscriptionEmail');
			formEmail('desinscriptionEmail');
			formObligatoire('desinscriptionEmail');
			if (formOK == 'true') {
				document.getElementById('alert').innerHTML = '<p>Envoi en cours...</p>';
				document.getElementById('alert').className = 'info';
				_gaq.push(['_trackEvent', 'Validation Formulaire', 'Désinscription newsletter']);
				document.forms['formulaire-desinscription-newsletter'].submit();
			}
			return(false);
		});
	}
	if($('#reduire').length) {
		$("#reduire").click(function() {
			formOK = 'true';
			document.getElementById('alert').className = '';
			formClean('reductionEmail');
			formClean('desinscriptionEmail');
			formEmail('reductionEmail');
			formObligatoire('reductionEmail');
			if (formOK == 'true') {
				document.getElementById('alert').innerHTML = '<p>Envoi en cours...</p>';
				document.getElementById('alert').className = 'info';
				_gaq.push(['_trackEvent', 'Validation Formulaire', 'Réduction envoi newsletter']);
				document.forms['formulaire-desinscription-newsletter'].submit();
			}
			return(false);
		});
	}
});

/** Formulaire Fondation */
$(document).ready(function() {
	if($('#formulaireFondationSiteForm').length) {
		$(".buttons .submit-envoyer input").click(function() {
				formOK = 'true';
				document.getElementById('alert').className = '';
				formClean('nom');
				formClean('prenom');
				formClean('fonction');
				formClean('organisme');
				formClean('intitule');
				formClean('codePostal');
				formClean('ville');
				formClean('mail');
				formClean('telephone');
				formEmail('mail');
				formObligatoire('nom');
				formObligatoire('prenom');
				formObligatoire('fonction');
				formObligatoire('organisme');
				formObligatoire('intitule');
				formObligatoire('codePostal');
				formObligatoire('ville');
				formObligatoire('mail');
				formObligatoire('telephone');
				if (formOK == 'true') {
					document.getElementById('alert').innerHTML = '<p>Envoi en cours...</p>';
					document.getElementById('alert').className = 'info';
					_gaq.push(['_trackEvent', 'Validation Formulaire', 'Fondation']);
					document.forms['formulaireFondationSiteForm'].submit();
				}
				return(false);
			}
		);
		$("#codePostal").keyup(function() {
			remplirVille(this.value);
		}).change(function() {
			remplirVille(this.value);
		});
	}
});

/** Formulaire habitat */
$(document).ready(function () {
	if($('#formulaireHabitatSiteForm').length) {
		$("#telephoneDomicile").mask("99 99 99 99 99");
		$("#telephoneProfessionnel").mask("99 99 99 99 99");
		$("#telephonePortable").mask("99 99 99 99 99");
		$("#noSoc").mask("9999999");
		
		$('#form-category input').click(updateVotreDemande);
		updateVotreDemande();
	}
});

function updateVotreDemande() {
	/* Mise a jour des boutons radio "prestation" */
	if ($('#form-category input#diagnosticsTechniques:checked').length>0) {
		$('#form-ta').hide('slow'); $('#form-tg').hide('slow'); $('#form-dt').show('slow');
		$('#form-ta-title').css('display', 'none'); $('#form-tg-title').css('display', 'none'); $('#form-dt-title').css('display', 'inline');
	}
	if ($('#form-category input#travauxAmenagement:checked').length>0) {
		$('#form-tg').hide('slow'); $('#form-dt').hide('slow'); $('#form-ta').show('slow');
		$('#form-tg-title').css('display', 'none'); $('#form-dt-title').css('display', 'none'); $('#form-ta-title').css('display', 'inline');
	}
	if ($('#form-category input#travauxGrosOeuvres:checked').length>0) {
		$('#form-ta').hide('slow'); $('#form-dt').hide('slow'); $('#form-tg').show('slow');
		$('#form-ta-title').css('display', 'none'); $('#form-dt-title').css('display', 'none'); $('#form-tg-title').css('display', 'inline');
	}
	/* Mise a jour des boutons radio "financement" */
	if ($('#form-category input#financementOui:checked').length>0) {
		$('#horaireFinancement1').hide(); $('#horaireFinancement2').hide();
	}
	if ($('#form-category input#financementNon:checked').length>0) {
		$('#horaireFinancement1').show(); $('#horaireFinancement2').show();
	}
}

/** Formulaire navigation */
$(document).ready(function() {
	/** Nav part 1*/
	if($('#form-proposant').length) {
		$("#form-proposant .submit-suivant a").click(function() {
			sauterVers(2);
			return false;
		});
	}
	/** Nav part 2*/
	if($('#form-bateau').length) {
		$("#form-bateau .submit-suivant a").click(function() {
			sauterVers(3);
			return false;
		});
	}
	/** Nav part 3*/
	if($('#form-bateau-suite').length) {
		$("#form-bateau-suite .submit-suivant a").click(function() {
			sauterVers(4);
			return false;
		});
	}
	/** Nav part 4*/
	if($('#form-garantie').length) {
		$("#form-garantie .submit-suivant input").click(function() {
			validateForm4();
			if (formOK == 'true') {
				validateForm1();
				if (formOK == 'true') {
					validateForm2();
					if (formOK == 'true') {
						validateForm3();
						if (formOK == 'true') {
							document.getElementById('alert').innerHTML = '<p>Envoi en cours...</p>';
							document.getElementById('alert').className = 'info';
							_gaq.push(['_trackEvent', 'Validation Formulaire', 'Navigation']);
							document.forms['formulaireNavigationForm'].submit();
						} else { sauterVers(3); }
					} else { sauterVers(2); }
				} else { sauterVers(1); }
			}
			return (false);
		});
	}
	if($('#formulaireNavigationForm').length) {
		$("#onglet1").click(function() {
			sauterVers(1);
			return (false);
		});
		$("#onglet2").click(function() {
			sauterVers(2);
			return (false);
		});
		$("#onglet3").click(function() {
			sauterVers(3);
			return (false);
		});
		$("#onglet4").click(function() {
			sauterVers(4);
			return (false);
		});
		initDisableUnavailableInput();
		disableUnavailableInput();
	
		document.getElementById('form-bateau').style.display = 'none';
		document.getElementById('form-bateau-suite').style.display = 'none';
		document.getElementById('form-garantie').style.display = 'none';
		var formOK = 'true';
	}

});

function cacherTousLesOnglets() {
	document.getElementById('form-proposant').style.display = 'none';
	document.getElementById('form-bateau').style.display = 'none';
	document.getElementById('form-bateau-suite').style.display = 'none';
	document.getElementById('form-garantie').style.display = 'none';
	document.getElementById('onglet1').className = '';
	document.getElementById('onglet2').className = '';
	document.getElementById('onglet3').className = '';
	document.getElementById('onglet4').className = '';
}

function afficherOnglet(ongletIndex) {
	if(ongletIndex == 1)
	{
		document.getElementById('form-proposant').style.display = 'block';
		document.getElementById('onglet1').className = 'actif';
	}
	else if(ongletIndex == 2)
	{
		document.getElementById('form-bateau').style.display = 'block';
		document.getElementById('onglet2').className = 'actif';
	}
	else if(ongletIndex == 3)
	{
		document.getElementById('form-bateau-suite').style.display = 'block';
		document.getElementById('onglet3').className = 'actif';
	}
	else if(ongletIndex == 4)
	{
		document.getElementById('form-garantie').style.display = 'block';
		document.getElementById('onglet4').className = 'actif';
	}
}

function sauterVers(formId) {

	// On reinitialise tout
	cacherTousLesOnglets();

	// On determine si on recule ou on avance dans le parcours des onglets
	if(currentForm > formId)
	{
		var avance = false;
	}
	else
	{
		var avance = true;
	}
	
	// Si on avance
	if(avance == true)
	{
		// Pour tous les onglets qui separent l'onglet courant de l'onglet souhaite
		var errorFound = false;
		for(i=currentForm ; i < formId && errorFound == false ; i++){
			formOK = true;
			cacherTousLesOnglets();
			currentForm = i;
			
			if(i == 1)
			{
				validateForm1();
				afficherOnglet(1);

				if (formOK == 'false') {
					errorFound = true;
				}
			}
			else if(i == 2)
			{
				validateForm2();
				afficherOnglet(2);

				if (formOK == 'false') {
					errorFound = true;
				}
			}
			else if(i == 3)
			{
				validateForm3();
				afficherOnglet(3);

				if (formOK == 'false') {
					errorFound = true;
				}
			}
			else if(i == 4)
			{
				validateForm4();
				afficherOnglet(4);

				if (formOK == 'false') {
					errorFound = true;
				}
			}
		}
		
		// Si aucune erreur n'a ete rencontree
		if(errorFound == false)
		{
			cacherTousLesOnglets();
			afficherOnglet(formId);
			currentForm = formId;
		}
	}
	// Sinon, si on recule
	else
	{
		// On affiche l'onglet souhaite
		afficherOnglet(formId);
		
		// On reaffecte l'index de l'onglet courant
		currentForm = formId;
	}

}

function validateForm1() {
	formOK = 'true';
	formClean('alert');
	formClean('nom');
	formClean('prenom');
	formClean('adresse');
	formClean('email');
	formEmail('email');
	formObligatoire('nom');
	formObligatoire('prenom');
	formObligatoire('adresse');
	formObligatoire('email');
}

function validateForm2() {
	formOK = 'true';
	formClean('alert');
	formClean('input-radio-type');
	formClean('input-radio-utilisation');
	formClean('input-radio-navigation');
	formClean('port');
	formClean('marqueBateau');
	formClean('modele');
	formClean('longueur');
	formClean('anneeConstructionBateau');
	formRadioObligatoire('input-radio-type', 'formulaireNavigationForm', 'typeBateau');
	formRadioObligatoire('input-radio-utilisation', 'formulaireNavigationForm', 'utilisation');
	formRadioObligatoire('input-radio-navigation', 'formulaireNavigationForm', 'zoneNavigation');
	formObligatoire('port');
	formObligatoire('marqueBateau');
	formObligatoire('modele');
	commaToDot('longueur');
	formObligatoireEtPositif('longueur');
	formObligatoire('anneeConstructionBateau');
}

function validateForm3() {
	formOK = 'true';
	formClean('alert');
	formClean('moteurPrincipalCheckbox');
	formClean('marqueMoteurPrincipal');
	formClean('radio-carburantMoteurPrincipal');
	formClean('puissanceMoteurPrincipal');
	formClean('anneeMoteurPrincipal');
	formClean('radio-typeMoteurAmovible');
	formClean('puissanceMoteurAmovible');
	formClean('anneeMoteurAmovible');
	formClean('immatriculation');
	formClean('valeurRemorque');
	formClean('jourMiseEnCirculation');
	formClean('moisMiseEnCirculation');
	formClean('anneeMiseEnCirculation');
	if (document.forms['formulaireNavigationForm'].moteurPrincipal.checked) {
		formObligatoire('marqueMoteurPrincipal');
		formRadioObligatoire('radio-carburantMoteurPrincipal', 'formulaireNavigationForm', 'carburantMoteurPrincipal');
		formObligatoire('puissanceMoteurPrincipal');
		formObligatoire('anneeMoteurPrincipal');
	}
	if (document.forms['formulaireNavigationForm'].moteurAmovible.checked) {
		formRadioObligatoire('radio-typeMoteurAmovible', 'formulaireNavigationForm', 'typeMoteurAmovible');
		formObligatoire('puissanceMoteurAmovible');
		formObligatoire('anneeMoteurAmovible');
	}
	if (document.forms['formulaireNavigationForm'].remorque.checked) {
		formObligatoire('immatriculation');
		formObligatoire('valeurRemorque');
		formObligatoire('jourMiseEnCirculation');
		formObligatoire('moisMiseEnCirculation');
		formObligatoire('anneeMiseEnCirculation');
	}
	/* Cas special : Moteur principal doit etre assure si bateau e moteur */
	if (document.forms['formulaireNavigationForm'].typeBateau[2].checked
		|| document.forms['formulaireNavigationForm'].typeBateau[3].checked
		|| document.forms['formulaireNavigationForm'].typeBateau[4].checked
		|| document.forms['formulaireNavigationForm'].typeBateau[5].checked) {
		if (!document.forms['formulaireNavigationForm'].moteurPrincipal.checked) {
			var alert = document.getElementById("alert");
			document.getElementById('moteurPrincipalCheckbox').className = "alert";
			alert.className = "alert";
			alert.innerHTML = "<p>L'assurance du moteur est obligatoire pour tout bateau &agrave; moteur</p>";
			formOK = 'false';
		}
	}
}

function validateForm4() {
	formOK = 'true';
	formClean('alert');
	formClean('garantieMontant0');
	formObligatoire('garantieMontant0');
}

/** Formulaire Newsletter */
$(document).ready(function() {
	$("#form-inscription-newsletter .submit-inscription input").click(function() {
			formOK = 'true';
			document.getElementById('alert').className = '';
			formClean('nom');
			formClean('prenom');
			formClean('statut');
			formClean('email');
			formClean('type-newsletter');
			formEmail('email');
			formObligatoire('nom');
			formObligatoire('prenom');
			formObligatoire('statut');
			formObligatoire('email');
			formRadioObligatoire('type-newsletter', 'form-inscription-newsletter', 'html');
			if (formOK == 'true') {
				document.getElementById('alert').innerHTML = '<p>Envoi en cours...</p>';
				document.getElementById('alert').className = 'info';
				_gaq.push(['_trackEvent', 'Validation Formulaire', 'Inscripiton newsletter']);
				document.forms['form-inscription-newsletter'].submit();
			}
			return(false);
		}
	);
});

/** Doc parag fin site */
$(document).ready(function(){
	if($('#detail_vl').length) {
		var metaValeurs = $('.jsValeurs').metadata();
		$("#detail_vl").tablevl(metaValeurs.url,metaValeurs.isin,metaValeurs.firstDateVl,metaValeurs.lastDateVl);
	}
});

/** Boite produit grille */
$(document).ready(function(){
	if($('#liste-formule').length) {
		initBoiteProduitGrille(garderLaBoiteOuverte);
		$('#liste-formule a.dt').each(function() {
			$(this).click(function() {
				return false;
			});
		});
	}
});

/** Boite produit tableau */
$(document).ready(function() {
	if($('#revenu-form').length) {
		$("#revenu-form").submit(function() { 
			submitRevenus();
			return false;
		});
		$("#revenu").change(function() { 
			submitRevenus();
		});
	}
});

function submitRevenus() {
	document.forms['revenu'].elements['statutproselect'].value = document.getElementById('statutproselect').value;
	document.forms['revenu'].submit();
}

/** Docproduitsite content top */
$(document).ready(function() {
	if($('#top-produitsite').length) {
		$("li#bookmark a").click(function() {
			CreateBookmarkLink();
		});
		if ($.browser.msie || $.browser.opera || $.browser.mozilla){
			$('#bookmark').show();
		} 
	}
});

function CreateBookmarkLink() {
	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(produitSiteTitle, produitSiteUrl,"");
	} else if( window.external ) { // IE Favorite
		window.external.AddFavorite( produitSiteUrl, produitSiteTitle);
	}
	else if(window.opera && window.print) { // Opera Hotlist
		return true;
	}
}

/** Docproduitsite */
$(document).ready(function() {
	if($('#choixprocaisse').length) {
		$("#profession a#profession-link").click(function() {
			$.modal(contenuModal);
		});
		if(autresCaissesRetraites == 'false') {
			document.getElementById('autrescaissesretraites').style.display='none';
		}
		$("#profession_id").change(function() {
			submitChoixprocaisse();
		});
		$("#caisseretraite").change(function() {
			submitChoixprocaisse();
		});
	}
	if($('#box-tab').length) {
		$('.onglets').each(function() {
			var metaOnglets = $(this).metadata();
			$("#box-tab-"+metaOnglets.boxid+" a").click(function() {
				boiteproduit(metaOnglets.boxid);
				customTrackPageAnalytics(metaOnglets.url+'?p='+metaOnglets.titre);
				return (false);
			});
		});
	}
});

function submitChoixprocaisse () {
	document.forms['choixprocaisse'].elements['statutproselect'].value = document.getElementById('statutproselect').value;
	document.forms['choixprocaisse'].elements['boxid'].value = boxCourante;
	document.forms['choixprocaisse'].elements['category'].value = category;
	document.forms['choixprocaisse'].submit();
}

// Javascript pour basculer les onglets
function boiteproduit(nomboite) {
	boxCourante = nomboite;
	$('#contener-box > div').css('display', 'none');
	$('div#'+nomboite).css('display', 'block');
	$('#box-tab > li').removeClass('actif');
	$('#box-tab-'+nomboite).addClass('actif');
}

/** Recrutement */
$(document).ready(function() {
	if($('#job-container').length) {
		$(".submit-post-offre a").click(function() {
				openProfilSoft(recrutementIdps,recrutementIdpartemaire);
				return false;
			}
		);
	}
});

/** Docsite */
$(document).ready(function() {
	if($('#top-docsite').length) {
		$("#bookmark-link").click(function() {
			CreateBookmarkLink();
		});
		//Display the bookmark option only if supported by the browser
		if ($.browser.msie || $.browser.opera || $.browser.mozilla){
			$('#bookmark').show();
		}
		$("#print-link").click(function() {
			print();
		});
		$("#opt-link").click(function() {
			Opt(docsiteId);
		});
	}
	if($('#docsiteprive_formulaire').length) {
		$("#numsocinput").blur(function() {
			remplir(this,'N° de sociétaire');
		}).focus(function() {
			vider(this,'N° de sociétaire');
		});
		$("#cleinput").blur(function() { 
			remplir(this,'Clé');
		}).focus(function() {
			vider(this,'Clé');
		});
		$("#modal-aide-acces-societaire-link").click(function() {
			$.modal(contenuModal, {overlayClose:true});
		});
	}
});

function CreateBookmarkLink() {
	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url,"");
	} else if( window.external ) { // IE Favorite
		window.external.AddFavorite( url, title);
	}
	else if(window.opera && window.print) { // Opera Hotlist
		return true;
	}
}

function Opt(id){
	$.ajax({
		url: "/macsf/site/ajax/docsiteopts.jspz",
		data: "type=docsite&id="+id,
		success: Opt_callback
	});	
}

function Opt_callback(count){
	$("span#opts").html('(' + $.trim(count) + ')');	
}

/** Formualires dynamiques */
$(document).ready(function() {
	if($('#form-dynamique').length) {
		initTooltips();
		$("#formulaires .submit-envoyer input").click(function() {
			formOK = 'true';
			document.getElementById('alert').className = '';
			$(".typeDynamique").each(function() {
				var metaChamps = $(this).metadata();
				if(metaChamps.obligatoire == '1'){
					formClean(metaChamps.id);
					if(metaChamps.type == 'email'){
						formEmail(metaChamps.id);
					}
					switch(metaChamps.type) {
					case 'radio':
						formRadioObligatoire(metaChamps.id,'form-dynamique',metaChamps.nomRadio);
						break;
					case 'fichier':
						formFichierObligatoire(metaChamps.id);
						break;
					case 'checkbox':
						formCheckboxObligatoire(metaChamps.id);
						break;
					default:
						formObligatoire(metaChamps.id);
					}
				}
			});
			if (formOK == 'true') {
				document.getElementById('alert').innerHTML = '<p>Envoi en cours...</p>';
				document.getElementById('alert').className = 'info';
				_gaq.push(['_trackEvent', 'Validation Formulaire', 'Dynamique']);
				document.forms['form-dynamique'].submit();
			}
			return(false);
		});
		$("#formulaires .submit-annuler a").click(function() {
			history.go(-1);
			return false;
		});
	}
});

/** Formulaire dynamique tempete*/
$(document).ready(function() {
	if($('#form-dynamique-tempete').length) {
		initTooltips();
		$("#formulaires .submit-envoyer input").click(function() {
			formOK = 'true';
			document.getElementById('alert').className = '';
			$(".typeDynamique").each(function() {
				var metaChamps = $(this).metadata();
				if(metaChamps.obligatoire == '1'){
					formClean(metaChamps.id);
					if(metaChamps.type == 'email'){
						formEmail(metaChamps.id);
					}
					switch(metaChamps.type) {
					case 'radio':
						formRadioObligatoire(metaChamps.id,'form-dynamique-tempete',metaChamps.nomRadio);
						break;
					case 'fichier':
						formFichierObligatoire(metaChamps.id);
						break;
					case 'checkbox':
						formCheckboxObligatoire(metaChamps.id);
						break;
					default:
						formObligatoire(metaChamps.id);
					}
				}
			});
			if (formOK == 'true') {
				document.getElementById('alert').innerHTML = '<p>Envoi en cours...</p>';
				document.getElementById('alert').className = 'info';
				_gaq.push(['_trackEvent', 'Validation Formulaire', 'Dynamique tempete']);
				document.forms['form-dynamique-tempete'].submit();
			}
			return(false);
		});
		$("#formulaires .submit-annuler a").click(function() {
			history.go(-1);
			return false;
		});
	}
});

/** Tracking Callback */
$(document).ready(function(){
	if($('#form-panel').length) {
		$('#bouton_callback').click(function(){
			_gaq.push(['_trackEvent', 'Callback', 'demande de Callback']);
		});
	}
});

/** Form sinistre risques divers */
$(document).ready(function() {
	if($('#realEstateSinisterForm').length) {
		initFormulaires()
		$(".submit-envoyer input").click(function() {
			formOK = 'true';
			$('#alert').removeClass('alert').removeClass('info');
			formClean('lastname');
			formClean('firstname');
			formClean('contractNumber');
			formClean('address');
			formClean('zipCode');
			formClean('city');
			formClean('personalPhoneNumber');
			formClean('mail');
			formEmail('mail');
			formObligatoire('lastname');
			formObligatoire('firstname');
			formObligatoire('contractNumber');
			formObligatoire('address');
			formObligatoire('zipCode');
			formObligatoire('city');
			formObligatoire('personalPhoneNumber');
			formObligatoire('mail');
			if (formOK == 'true') {
				document.getElementById('alert').innerHTML = '<p>Envoi en cours...</p>';
				document.getElementById('alert').className = 'info';
				_gaq.push(['_trackEvent', 'Validation Formulaire', 'Sinistres risques divers']);
				document.forms['contactForm'].submit();
			}
			return(false);
		});
		$("#zipCode").keyup(function() {
			remplirVille(this.value);
		}).change(function() {
			remplirVille(this.value);
		});
	}
});


$(document).ready(function(){
	if($('#accesSocietaireCarte').length) {
		$('#accesSocietaireCarte').click(function(){
			customTrackPageAnalytics(urlCarte);
		});
	}
	if($('#accesSocietairePei').length) {
		$('#accesSocietairePei').click(function(){
			customTrackPageAnalytics(urlPei);
		});
	}
});


$(document).ready(function(){
	if($('#docnewsletter').length) {
		$('.analyticsNewsletter').each(function(){
			var metaNewsletter = $(this).metadata();
			customTrackPageAnalytics(metaNewsletter.urlBloc);
		});
	}
});


$(document).ready(function(){
	if($('#fichiers-simpletab').length || $('#fichiers-tableau').length) {
		$('.trackEvent').each(function(){
			var metaFile = $(this).metadata();
			$(this).click(function() {
				pageTracker._trackEvent('Telechargement', 'Fichier', metaFile.fichier);
			});
		});
	}
});


$(document).ready(function(){
	if($('#printdoc').length) {
		$('#printdoc a').click(function() {
			print();
			return false;
		});
	}
});


$(document).ready(function(){
	if($('#docsiteprive_formulaire').length) {
		$('#submit').click(function() {
			var metaDoc = $(this).metadata();
			customTrackPageAnalytics('/soumission-acces-societaire.html');
			if(metaDoc.type != 'docsite' || metaDoc.prive != '1') {
				connecterAccesSocietaire(document.getElementById('numsocinput').value, document.getElementById('cleinput').value);
				return false;
			}
		});
	}
});

$(document).ready(function(){
	if($('#formulaireNavigationForm').length) {
		$("#form-proposant .submit-annuler a").click(function() {
			history.go(-1);
			return false;
		});
	}
	if($('#formulaireNavigationForm').length) {
		$("#form-bateau .submit-annuler a").click(function() {
			history.go(-1);
			return false;
		});
	}
	if($('#formulaireNavigationForm').length) {
		$("#form-bateau-suite .submit-annuler a").click(function() {
			history.go(-1);
			return false;
		});
	}
	if($('#formulaireNavigationForm').length) {
		$("#form-garantie .submit-annuler a").click(function() {
			history.go(-1);
			return false;
		});
	}
});

$(document).ready(function(){
	if($('#carAccidentForm').length) {
		$("#carAccidentForm .submit-annuler a").click(function() {
			history.go(-1);
			return false;
		});
	}
});

$(document).ready(function(){
	if($('#contactDevisForm').length) {
		$("#contactDevisForm .submit-annuler a").click(function() {
			history.go(-1);
			return false;
		});
	}
});

$(document).ready(function(){
	if($('#contactForm').length) {
		$("#contactForm .submit-annuler input").click(function() {
			history.go(-1);
			return false;
		});
	}
});

$(document).ready(function(){
	if($('#formulaireFondationSiteForm').length) {
		$("#formulaireFondationSiteForm .submit-annuler a").click(function() {
			history.go(-1);
			return false;
		});
	}
});

$(document).ready(function(){
	if($('#job-container').length) {
		$("#job-container .submit-annuler a").click(function() {
			history.go(-1);
			return false;
		});
	}
});

$(document).ready(function(){
	if($('#realEstateSinisterForm').length) {
		$("#realEstateSinisterForm .submit-annuler a").click(function() {
			history.go(-1);
			return false;
		});
	}
});

$(document).ready(function(){
	if($('#prod-and-serv').length) {
		$("#prod-and-serv a").click(function() {
			if (document.getElementById('statutproselect')!=null) {
				this.href = href+'?statutproselect='+document.getElementById('statutproselect').value;
			}
		});
	}
});

$(document).ready(function(){
	if($('#content-left-menu-sort-by-category').length) {
		$(".jsNiv3").each(function() {
			var metaNiv3 = $(this).metadata();
			$(this).click(function() {
				this.href = metaNiv3.url+'?category='+metaNiv3.category+'&statutproselect='+document.getElementById('statutproselect').value;
			});
		});
		$(".jsNiv4").each(function() {
			var metaNiv4 = $(this).metadata();
			$(this).click(function() {
				this.href = metaNiv4.url+'?rubriquemere='+metaNiv4.rubriquemere+'&category='+metaNiv4.category+'&statutproselect='+document.getElementById('statutproselect').value;
			});
		});
		$(".jsNiv5").each(function() {
			var metaNiv5 = $(this).metadata();
			$(this).click(function() {
				this.href = metaNiv5.url+'?rubriquemere='+metaNiv4.rubriquemere+'&category='+metaNiv4.category+'&statutproselect='+document.getElementById('statutproselect').value;
			});
		});
	}
	others('#pre-page dl');
	
});

/* -------------------------------------------------------------------------- */
function others(selector){
	if(!jQuery(selector).length) return;
	
	var active = 'active';
	
	jQuery(selector).find('dt').find('span').wrapInner('<button />');	
	jQuery(selector).find('button').click(function(e){
		if(jQuery(selector).hasClass(active)){
			jQuery(selector).removeClass(active);
		}else{
			jQuery(selector).addClass(active);		
		}
	});
	jQuery(document).click(function(){
		jQuery(selector).removeClass(active);
	});
	jQuery(selector).click(function(e){
		e.stopPropagation();
	});
}
