/* load */
jQuery.extend(jQuery.validator.messages, {
        required: "Ce champ est obligatoire.",
        remote: "Veuillez remplir ce champ pour continuer.",
        email: "Veuillez entrer une adresse email valide.",
        url: "Veuillez entrer une URL valide.",
        date: "Veuillez entrer une date valide.",
        dateISO: "Veuillez entrer une date valide (ISO).",
        number: "Veuillez entrer un nombre valide.",
        digits: "Veuillez entrer une valeur numérique sans espace ni ponctuation.",
        creditcard: "Veuillez entrer un numéro de carte de crédit valide.",
        equalTo: "Veuillez entrer une nouvelle fois la même valeur.",
        accept: "Veuillez entrer une valeur avec une extension valide.",
        maxlength: jQuery.format("Veuillez ne pas entrer plus de {0} caractères."),
        minlength: jQuery.format("Veuillez entrer au moins {0} caractères."),
        rangelength: jQuery.format("Veuillez entrer entre {0} et {1} caractères."),
        range: jQuery.format("Veuillez entrer une valeur entre {0} et {1}."),
        max: jQuery.format("Veuillez entrer une valeur inférieure ou égale à {0}."),
        min: jQuery.format("Veuillez entrer une valeur supérieure ou égale à {0}.")
});

/*#2963#*/
jQuery.validator.addMethod("digits-space", function(value, element) {
	var exp = new RegExp("^[0-9 ]+$","g");
	return exp.test(value);
}, "Veuillez entrer une valeur numérique sans ponctuation.");
/*fin #2963#*/

/*#4095#*/
jQuery.validator.addMethod("url-nohttp", function(value, element) {
	// Modification de la reg exp utilisé par validate
	var exp = /^((https?|ftp):\/\/)?(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i;
	return (exp.test(value) || value == '');
}, "Veuillez entrer une URL valide.");
/*fin #4095#*/
$(document).ready( function() {

	/* load menu dynamique */
	$('#menu dd').children().each(function(index) {
		$(this).mouseover(	function(){ $(this).parent().children('ul').show(); });
		$(this).mouseout(	function(){ $(this).parent().children('ul').hide(); });

		$(this).parent().children('ul').mouseover(	function(){ $(this).show(); });
		$(this).parent().children('ul').mouseout(	function(){ $(this).hide(); });
	});	

	$('#connect a:first').each(function(index) {
		$(this).mouseover(	function(){ $(this).parent().children('ul').show(); });
		$(this).mouseout(	function(){ $(this).parent().children('ul').hide(); });

		$(this).parent().children('ul').mouseover(	function(){ $(this).show(); });
		$(this).parent().children('ul').mouseout(	function(){ $(this).hide(); });
	});	

	$('#lien-aide a:first').each(function(index) {
		$(this).mouseover(	function(){ $(this).parent().find('ul').show(); });
		$(this).mouseout(	function(){ $(this).parent().find('ul').hide(); });

		$(this).parent().find('ul').mouseover(	function(){ $(this).show(); });
		$(this).parent().find('ul').mouseout(	function(){ $(this).hide(); });
	});	
	
	/* checkbox dans tableaux */
	$('.chkSelectAnnonce').click(function() {
		if ( $(this).is(':checked') ) { 
			$(this).parent().parent().parent().addClass('bg');
		} else {
			$(this).parent().parent().parent().removeClass('bg');
			$('.chkSelectAll').attr('checked', false);
		}
		if( $('.dem-inf-hd dfn span').length > 0) { compteNbCheck(); }
	});

	$('.chkSelectAll').click(function() {
		if ($(this).is(':checked')) {
			$('.chkSelectAll').attr('checked', true);
			$('.chkSelectAnnonce').attr('checked', true);
			$('.chkon tbody tr').addClass('bg');
		} else {
			$('.chkSelectAll').attr('checked', false);
			$('.chkSelectAnnonce').attr('checked', false);
			$('.chkon tbody tr').removeClass('bg');
		}
		if( $('.dem-inf-hd dfn span').length > 0) { compteNbCheck(); }
	});
	
	if( $('.dem-inf-hd dfn span').length > 0) { compteNbCheck(); }
	
	/* fonction gestion onglets */
	$('.blc-ong a.onglet').click(function() {
		var sHref = $(this).attr('href');
		$(this).parent().children('.onglet').removeClass('actif');
		// Gestion spécifique des onglets Perf'Média
		if ($('.perfm').length) {
			$('.ongletContenu').hide();
			if(window.MD_TelDetail){
				if(sHref != '#ongletContactTel'){
					if ($('#MD_ong3_LDetListe2').css('display') != 'none') {
						MD_TelDetail('MD_ong3');
					}
				}else if(sHref != '#ongletContactMail'){
					if($('#MD_ong2_LDetListe2').css('display') != 'none') {
					MD_TelDetail('MD_ong2');
					}
				}else{
					if($('#MD_ong2_LDetListe2').css('display') != 'none') {
					MD_TelDetail('MD_ong2');
					}
					if($('#MD_ong3_LDetListe2').css('display') != 'none') {
						MD_TelDetail('MD_ong3');
					}
				}
			}
		}
		// Gestion spécifique pour les onglets et graphiques de la home
		if ($('.ep-ho').length || $('#detailannonce').length) {
			$('.blc-graph[id|="' + sHref.substr(1,2) + '"]').hide();
		}
		
		//  Gestion spécifique pour les onglets PerfAnnonce
		if($('.perfa').length){
			if($('.bloc-b[id|="' + sHref.substr(1,4) + '"]').length)
				$('.bloc-b[id|="' + sHref.substr(1,4) + '"]').hide();
			else
				$('.blc-graph[id|="' + sHref.substr(1,2) + '"]').hide();
		}

		
		$(this).addClass('actif');
		$(sHref).show();
		return false;
	});
	
	$('a.onglet-cons').click(function() {
		var sHref = $(this).attr('href');
		$(this).parent().children('.onglet-cons').removeClass('actif');
		$(this).closest('.content').find('.bloc-b').hide();
		$(this).addClass('actif');
		$(sHref).show();
		return false;
	});
	$('#blc-ann-cons a.ann-cons-more').click(function() {
		$(this).closest('li').siblings('li.more').show();
		$(this).hide();
		return false;
	});
	
	/* fonctions bulles d'aide */
	$('.btn-aide').mouseover(function() {
		if( $(this).find('.bul-aide').length == 0 )
		{
			$(this).append('<div class="bul-aide">'+$(this).find('span').html()+'</div>');
		}
	});
	$('.btn-aide').mouseout(function() {
		$(this).find('.bul-aide').remove();
	});
});

function compteNbCheck()
{
	$('.dem-inf-hd dfn span').html( $('tbody input:checked').length );
}
/* fin load */


function ann_act(oLink, sIdAnnonce, sContexte) {
	var sVerbe = '';
	var cIdChaine = $('#idChaine').val();
	
	
	if (oLink.hasClass('enlig')) sVerbe = 'publier';
	else if (oLink.hasClass('inact') || oLink.hasClass('broui')) sVerbe = 'désactiver';
	if (sContexte == 'EX') sVerbe = 'prolonger';
	
	if (sVerbe && confirm('Souhaitez-vous ' + sVerbe + ' cette annonce ?')) {
		var sAction = '';
		if (sVerbe == 'publier') { sAction = 'publier'; }
		else if (sVerbe == 'désactiver') { sAction = 'desactiver'; }
		else if (sVerbe == 'prolonger') { sAction = 'prolonger'; }
		
	    var oForm;
	    var hidAction;
		if (sContexte == 'detail') {
		    oForm = $('#detailannonce');
		    hidAction = $('#detailannonce #actionAnnonce');
		} else {
		    oForm = $('#formAffichage');
		    hidAction = $('#formAffichage #actionAnnonce');
		}
        hidAction.val(sAction);
        $.post(
        	oForm.attr('action'),
        	oForm.serialize() + '&a[]=' + sIdAnnonce + '&from_jQuery=1',
        	function (data) {
				//alert(data);
        		data = data.split('###');
        		if (data[0] == 'OK') {
					var oSiblings;
					if (sVerbe == 'publier') {
						if (sContexte == 'detail') { // détail annonce
							$('.visu').show();
							if(cIdChaine == 'V'){
								$('.det-hd-3 strong').text('Reste : 60 jours');
							}else{
								$('.det-hd-3 strong').text('Reste : 90 jours');
							}
							$('#codeEtat').val('VA');
						} else { // liste annonces
							$('#tdAnnonce_' + sIdAnnonce).removeClass('opac');
							if(cIdChaine == 'V'){
								$('#txtJoursRestants_' + sIdAnnonce).text('Reste : 60 j.');
							}else{
								$('#txtJoursRestants_' + sIdAnnonce).text('Reste : 90 j.');
							}
						}
						oLink.attr('class', 'enlig-act');
						oSiblings = oLink.siblings('a.inact-act, dfn.broui-act');
					} else if (sVerbe == 'désactiver') {
						if (sContexte == 'detail') { // détail annonce
							$('.visu').hide();
							$('.det-hd-3 strong').text('Reste : 0 jour');
							$('#codeEtat').val('DE');
						} else { // liste annonces
							$('#tdAnnonce_' + sIdAnnonce).addClass('opac');
							$('#txtJoursRestants_' + sIdAnnonce).text('Reste : 0 j.');
						}
						oLink.attr('class', 'inact-act');
						oSiblings = oLink.siblings('a.enlig-act');
					}
					var sNewClass = oSiblings.attr('class').replace('-act', '');
					oSiblings.attr('class', sNewClass);
				}
				alert(data[1]);
        	}
        );
        hidAction.val('');
	}
	
	return false;
} //end function ann_act()


/* fonctions graphique */
function changeCompteur(obj)
{
	ids = $(obj).attr('href');
	$(ids+'-cpt').parent().find('dfn').each(function() {
		$(this).hide();
	});
	$(ids+'-cpt').show();
}
/* fin fonctions graphique */

function listerDynTypeUrl(url) {
	if( $('#codeFamSelected').val()!='') {
		$('#detailAnnonce').show();
	} else {
		$('#detailAnnonce').hide();
	}
	if( $('#codeFamSelected').val()=='VVO' || $('#codeFamSelected').val()=='VVU') {
		$('#all_arround_Categ').hide();
		$('#saisieAssistee').show();
		$('#flagChangmentRub').val('1');
		$('#form_annonce').submit();
	}
	else{
		$('#saisieAssistee').hide();
		/* ajax */
        $.post(url,
            { 'r': $('#codeFamSelected').val(), 'c': 'type', 'jQuery': true },
            function (data) {
                var str = decodeURI('%3Coption value=""%3EChoisir une sous-rubrique%3C/option%3E');
                if (data) {
                    data = $.parseJSON(data);
					if(data.length) {
						codeCategSelectedOrigine = $('#codeCategSelected').val();
						for (var i = 0; i < data.length; i++) {
							selected = '';
							if(codeCategSelectedOrigine == data[i].c) selected = ' selected=selected ';
							str += decodeURI('%3Coption value="' + data[i].c + '"' + selected + '%3E' + data[i].l + '%3C/option%3E');
						}
						$('#codeCategSelected').html(str);
						$('#all_arround_Categ').show();
					} else {
						$('#all_arround_Categ').hide();
						$('#detailAnnonce').hide();
					}
                }
                else {
                    $('#all_arround_Categ').hide();
                }
            }, "JSON"
        );
    }
      
	$('#div_desc_bien').hide();

	if($('#div_enrichi_options_equ').length>0){
		$('#div_enrichi_options_equ').hide();	
	}
}


/* depose */
function listerDynType()
{	
	if( $('#codeFamSelected').val()!='') {
		$('#detailAnnonce').show();
	} else {
		$('#detailAnnonce').hide();
	}
	
	if( $('#codeFamSelected').val()=='VVO' || $('#codeFamSelected').val()=='VVU') {
		$('#all_arround_Categ').hide();
		$('#saisieAssistee').show();
		$('#flagChangmentRub').val('1');
		$('#form_annonce').submit();
	}
	else{
		$('#saisieAssistee').hide();
		/* ajax */
        $.post(urlListerDynamiquement,
            { 'r': $('#codeFamSelected').val(), 'c': 'type', 'jQuery': true },
            function (data) {
                var str = decodeURI('%3Coption value=""%3EChoisir une sous-rubrique%3C/option%3E');
                if (data) {
                    data = $.parseJSON(data);
                    for (var i = 0; i < data.length; i++) {
                        str += decodeURI('%3Coption value="' + data[i].c + '"%3E' + data[i].l + '%3C/option%3E');
                    }
                    $('#codeCategSelected').html(str);
                    $('#all_arround_Categ').show();
                }
                else {
                    $('#all_arround_Categ').hide();
                }
            }, "JSON"
        );
    }
      
	$('#div_desc_bien').hide();

	if($('#div_enrichi_options_equ').length>0){
		$('#div_enrichi_options_equ').hide();	
	}
}

	/* gestion upload photos */
	currentPos = 0;
	nocheck = true;

	function delPhoto(obj)
	{
	
		if(confirm('Voulez-vous réellement supprimer cette photo ?')){
			var valaction = action = $('#form_annonce').attr('action');
			if(valaction.indexOf('?')!='-1'){
				$('#form_annonce').attr('action', valaction+'&suppPhoto='+obj.replace('photo', '')+'#a_photo');
			}else{
				$('#form_annonce').attr('action', valaction+'?suppPhoto='+obj.replace('photo', '')+'#a_photo');	
			}
				
			$('#form_annonce').submit();
			objForm.submit();
		}else{
			return false;
		}
	
	
		$('#'+obj).replaceWith('<input type="file" onchange="changeMedia(this)" id="'+obj+'" name="'+obj+'" />'); // reset input file
		$('#blcPhoto input[type=file]').hide();
		
		$('#img'+obj).attr('src','/img/epv2/ti_notof.gif');
		$('#img'+obj).parent().children('a').remove();
		if( $('#sel'+obj).is(':checked'))
		{
			$('#sel'+obj).attr('checked',false);
			$('#msg'+obj).html('');
			nocheck=true;
		}
		$('#sel'+obj).attr('disabled',true);

		for(i=0;i < 6; i++)
		{
			if( $('#selphoto'+i).attr('disabled') )
			{
				currentPos = i;
				$('#photo'+currentPos).show();
				break;
			}	
		}
		if(nocheck)
		{
			for(i=0;i < 6; i++)
			{
				if( !$('#selphoto'+i).attr('disabled') )
				{
					$('#selphoto'+i).attr('checked',true);
					$('#msgphoto'+i).html('Photo principale');
					nocheck=false;
					break;
				}	
			}
		}

	}

	function changeMedia(obj){
	
			$('#sel'+$(obj).attr('name')).attr('disabled',false);
			/*if(currentPos == 0 && nocheck)
			{
				$('#sel'+$(obj).attr('name')).attr('checked',true);
				$('#msgphoto0').html('Photo principale');
				nocheck = false;	
			}*/
			
			$('#blcPhoto input[type=file]').hide();
			for(i=0 ; i < 6 ; i++)
			{
				if( $('#selphoto'+i).attr('disabled') )
				{
					currentPos = i;
					$('#photo'+currentPos).show();
					break;
				}
			}		
			
			$('<a href="#1" title="" onclick="delPhoto(\''+$(obj).attr('name')+'\')">x</a>').appendTo( $('#img'+$(obj).attr('name')).parent() );
			action = $('#form_annonce').attr('action');
			$('#form_annonce').attr('action', action+'&ajphoto=1#a_photo');		
			$('#form_annonce').submit();			
	}
	
	function changePrin(obj){
	
		vid = $(obj).attr('id').replace('selphoto','');
		$(obj).parent().parent().children().children().each( function(index) {
			$('#msgphoto'+index).html('&nbsp;');
		});
		$('#msgphoto'+vid).html('Photo principale');
	}
	/* fin gestion upload photos */

/* fin depose */

/* popin */
function openPopin(nom)
{
	$('#'+nom).show();
	$('body').append('<div class="layer-bg" onclick="closePopin(\''+nom+'\')">&nbsp;</div>');

	$('#'+nom+' .layer-hd a').click( function() { closePopin(nom); });
	
	($(window).height() > $(document).height()) ? hauteur = $(window).height() : hauteur = $(document).height();
	$('.layer-bg').css('height',hauteur+'px');
	$('#'+nom).css('top','100px');

}
function closePopin(nom)
{
	$('.layer-bg').remove();	
	$('#'+nom).hide();
}
/* FIN popin */

function openPopinTeteListe(nom, prix)
{
	nbAnn = 0;
	cnt_ref='';
	
	$('tbody input[type=checkbox]:checked').each(function(){
		if($(this).parents('td:first').find('input[name="etatAnn[]"]').val() =='VA') 
		{
			// compte nombre d'annonces "En ligne"
			nbAnn++; 
			
			// Liste des références annonce en ligne
			cnt_ref+='<span>Annonce référence : ' + $(this).parents('td:first').find('input[name="refAnn[]"]').val()+ '</span>';
		}	
	});
	
	switch(nbAnn)
	{
		case 0:
			alert('Veuillez sélectionner au moins une annonce "En ligne"');
			return;
		break;
		
		case 1:
			$('#nb-check').html('cette annonce');
		break;
		
		default:
			$('#nb-check').html('ces ' + nbAnn + ' annonces');
		break;
	}

	$('#tl-ref').html(cnt_ref); // Affichage des références annonce en ligne
	$('#tl-prix').html(prix*nbAnn); // Calcul prix ?
	openPopin(nom);
}
function verificationCGV(sNomForm)
{
	if ($('#acceptCGV').attr('checked') == false) {
		alert('Merci d\'accepter les conditions générales de ventes et les conditions générales d\'utilisation pour valider votre commande');
	} else {
		closePopin('alerte');
		$('#actionAnnonce').val('placertete');
		$('#' + sNomForm).submit();
	}
}
function publicationPapierAnnonce(urlActionPublicationPapier, editions){

	sIdAnnonces = '';
	
	$('tbody input[type=checkbox]:checked').each(function(){
// Mantis 3919 - Mise en commentaire du if
//		if($(this).parents('td:first').find('input[name="etatAnn[]"]').val() =='VA' || document.getElementById("idOffre").value =='364' || document.getElementById("idOffre").value =='365') {
//			sIdAnnonces += '' + $(this).parents('td:first').find('input[name="refAnn[]"]').val()+ '|';
			sIdAnnonces += '' + $(this).val()+ '|';
//		}
	});
	
	if (sIdAnnonces != '') {
		if (editions == 'autres') {
		window.open(urlActionPublicationPapier + '?a=' + sIdAnnonces + '&edition=' + editions, '', 'height=450,width=635,status=no,scrollbars=yes');		
		}else{
		window.open(urlActionPublicationPapier + '?a=' + sIdAnnonces + '&edition=' + editions, '', 'height=450,width=635,status=no,scrollbars=yes');
		}
	}else{
		alert('Veuillez sélectionner au moins une annonce');
		return
	}
	
}//publicationPapierAnnonce

function vdrModif(obj,idt)
{
	$(obj).parents('tr').find('span').hide();
	$(obj).parents('tr').find('input').show();
	$(obj).parents('tr').find('label').show();
	$(obj).parents('tr').find('input[type=text]').addClass('required');
	$(obj).hide();
	$(obj).next().show();
}
/* inscription EP */
	function showHideDiv(idDiv, idSelectPays,idSelectVille,idTxtVille)
	{
		//on teste que ce div existe dans la page
		if( $('#'+idSelectPays).length > 0 )
		{
		
			//si l'option sélectionné dans la liste déroulante est vide
			//on cache le div, sinon on le rend visible.
			if( $('#'+idSelectPays).val()=='' )
			{
				$('#'+idDiv).hide();
			}
			else
			{
				// si c'est le pays sélectionné est la France
				// on affiche une liste pour les villes
				if($('#'+idSelectPays).val()=='FR')
				{
					$('#'+idSelectVille).show();
					$('#'+idTxtVille).hide();
					$('#'+idSelectVille).children().attr('class','required');
					$('#'+idTxtVille).children().attr('class','');
				}
				else
				{
					//sinon on affiche une zone de saisie pour la ville
					$('#'+idSelectVille).hide();
					$('#'+idTxtVille).show();
					$('#'+idSelectVille).children().attr('class','');
					$('#'+idTxtVille).children().attr('class','required');
				}
				$('#'+idDiv).show();
			}
		}
	}//fin showHideDiv
	
	function chargerVillesDansIFrame (idIFrame, idElementCodePostal, idElementPays, idElementListeVilles) 
	{
	   if ( $('#'+idElementCodePostal).val().length >= 5
			&& /^[0-9]{5}$/.test( $('#'+idElementCodePostal).val() )
		) {
		// Recuperation des valeurs des champs passes en parametres
			var codePostal = $('#'+idElementCodePostal).val();
		//      var codePays = document.getElementById(idElementPays).value;
			var codePays = 'FR';
			var element = $('#'+idIFrame);
			var urlChargerVille = element.attr('src');
		// Mise a jour de la source avec les parametres
			urlChargerVille = urlChargerVille.replace(/codePostal=[^&]*/, 'codePostal=' + codePostal);
			urlChargerVille = urlChargerVille.replace(/pays=[^&]*/, 'pays=' + codePays);
			urlChargerVille = urlChargerVille.replace(/element=[^&]*/, 'element=' + idElementListeVilles);
			element.attr('src',urlChargerVille);
	    }
		else 
		{
			//supprimeOption(idElementListeVilles);
			return false;
  	    }
	    return true;
	} //fin chargerVillesDansIFrame

/* FIN inscription EP */

function ajouterDestinataire() {
	var txtEmail = $('#newmaildest');
	var sEmail = $.trim(txtEmail.val());
	
	if ($('#form_parms').validate().element('#newmaildest') && sEmail != '') {
		var hidAutresDest = $('#autresdest');
		var aAutresDest;
		if (hidAutresDest.val() != '') aAutresDest = hidAutresDest.val().split(',');
		else aAutresDest = new Array();
		var iNb = aAutresDest.length + 1;
		// Ajout de la ligne dans le tableau
		$('#tblDestinataires tbody').append('<tr id="AutresDestRow_' + iNb + '"><td>' + sEmail + '</td><td class="lnk">' +
											'<a href="#1" title="" class="pic24 supp" ' +
											'onclick="return supprimerDestinataire(\'AutresDestRow_' + iNb + '\')">Supprimer</a></td></tr>');
		// Mise à jour du champ caché
		aAutresDest.push(sEmail)
		hidAutresDest.val(aAutresDest.join(','));
		// Vidage et focus sur le champ email
		txtEmail.val('').focus();
	}
	
	return false;
}

function supprimerDestinataire(sIdRow) {
	var tblRow = $('#' + sIdRow);
	var sEmail = $.trim($('#' + sIdRow + ' td:first-child').text());
	var hidAutresDest = $('#autresdest');
	var aAutresDest = hidAutresDest.val().split(',');
	var iNb = aAutresDest.length;
	var aNouveau = new Array();
	
	for (var iCount = 0; iCount < iNb; iCount++) {
		if (sEmail != aAutresDest[iCount]) {
			aNouveau.push(aAutresDest[iCount]);
		}
	}
	
	tblRow.remove();
	// Mise à jour du champ caché
	hidAutresDest.val(aNouveau.join(','));
	
	return false;
}

/* Perf'media */

//Affichage de la page de modification de support
function getPageModifSupport(type,valeur,idGifChargement){
	
	params = "type="+type+"&valeur="+valeur;
	
	//	onLoading: gestionChargementEnCours(idGifChargement),
	var ajax_getPageModifier = jQuery.ajax({
		type: "POST",
		async: false,
		data: params,
		url : urlGetPageModifSupport,
		success : function(retour) 
		{
			if($('#'+idGifChargement).length>0){
				$('#'+idGifChargement).html('');
			}
			
			if(retour != ''){
				try {
					$('#MD_ong4_modif').html(retour);
					$('#MD_ong4_Tab').hide();
					$('#MD_ong4_modif').show();
				} 
				catch (e){
				}
			}
		}
	});

}
function getExportListeCSV(typeListe){
	
	//codePro = 
	if( $('#codePro').length > 0 ){
		valPro = $('#codePro').val();
		libPro = 'codePro';
	}
	else{
		valPro = $('#listePros').val();
		libPro = 'listePros';
	}
	
	idSupportMT = $('#idSupportMT').val();
	dtDebut 	= $('#dtDebut').val();
	dtFin 		= $('#dtFin').val();
	
	url = urlgetExportListeCSV+'?typeListe='+typeListe+'&'+libPro+'='+valPro+'&idSupportMT='+idSupportMT+'&dtDebut='+dtDebut+'&dtFin='+dtFin;

	document.location.href = url;

}
function rechargeUneListe(typeFiltre,filtre,libListe){
	
	if(typeFiltre == 'tri'){
		$('#nomTri').val(filtre);
	}
	if(typeFiltre == 'appelNOK' || typeFiltre == 'appelOK' || typeFiltre == 'duree' || typeFiltre == 'localisation'){
		$('#nomFiltre').val(typeFiltre);
		$('#valFiltre').val(filtre);
	}
	if(typeFiltre == 'all'){
		$('#nomFiltre').val('');
		$('#valFiltre').val('');
	}
	
	selectPage 	= '';
	if(libListe == 'listeDetailContactTel' || libListe == 'listeDetailContactMail'){
		selectPage 	= $('#selectPage_'+libListe);
	}
	parms =  $("#formBlocFiltre").serialize()+'&selectPage='+selectPage;
	
	var ajax_formBlocFiltre = jQuery.ajax({
		type: "POST",
		async: false,
		data: parms,
		dataType: 'json',
		url : $('#formBlocFiltre').attr('action'),
		success : function(reponse) 
		{
			if(reponse != ''){
				try {
					majListesMediaTraqueur(reponse)
				} 
				catch (e){
				}
			}
		}
	});
}

function gestionFiltreListe(form){
	
	parms = $("#formBlocFiltre").serialize();
	var ajax_form = jQuery.ajax({
		type: "POST",
		async: false,
		data: parms,
		dataType: 'json',
		url : $(form).attr('action'),
		success : function(reponse) 
		{
			if(reponse != ''){
				try {
					majListesMediaTraqueur(reponse)
				} 
				catch (e){
				}
			}
		}
	});
			
}

function majListesMediaTraqueur(reponse){
	
	if(reponse != ''){
		try {

				$('#listeOngletAccueil').html(reponse.LISTE_ONGLET_ACCUEIL);
				$('#listeContactTel').html(reponse.LISTE_CONTACT_TEL);
				$('#listeDetailContactTel').html(reponse.LISTE_DETAIL_CONTACT_TEL);
				$('#listeLocalisation').html(reponse.LISTE_LOCALISATION);
				$('#listeContactMail').html(reponse.LISTE_CONTACT_MAIL);
				$('#listeDetailContactMail').html(reponse.LISTE_DETAIL_CONTACT_MAIL);
				
				$('#pagination_listeDetailContactTel').html(reponse.PAGINATION_LISTE_TEL);
				$('#pagination_listeDetailContactMail').html(reponse.PAGINATION_LISTE_MAIL);
				$('#listeOngletMesInfos').html(reponse.LISTE_ONGLET_MES_INFOS);
		} 
		catch (e){
		}
	}
	
}

/* FIN Perf'media */

/* popup fiche signalétique */
function prnt()
{
	$('#header').hide();
	$('#infos').hide(); $('#cnt_infos').show();
	$('#txt1').hide(); $('#cnt_txt1').show();
	if( $('input[type=radio][name=vendu]:checked').attr('value')== 'o' ) { $('#vendu').show(); }
	if( $('input[type=radio][name=photo]:checked').attr('value')== 'n' ) { $('#photo').hide(); $('#nophoto').show(); }
	if( $('input[type=radio][name=co2]:checked').attr('value')== 'n' ) { $('#co2').hide(); }
	$('#q').hide();
	$('#btn').hide();
	window.print();
	window.close();
}

/* #3004# */
function prntRadio(){
	if( $('input[type=radio][name=vendu]:checked').attr('value')== 'o' ) { $('#vendu').show(); }
	else{$('#vendu').hide();}
	if( $('input[type=radio][name=photo]:checked').attr('value')== 'n' ) { $('#photo').hide(); $('#nophoto').show(); }
	else{$('#photo').show(); $('#nophoto').hide();}
	if( $('input[type=radio][name=co2]:checked').attr('value')== 'n' ) { $('#co2').hide(); }
	else{ $('#co2').show();}
}
/* FIN popup fiche signalétique */

/* recoupement alertes vendeur */
function showHideRecoup(obj)
{
	robj = 	$(obj).parent().parent().parent().children('.rec-det');
	if( $(robj).is(':visible') )
	{
		$(robj).hide();
		$(obj).html('Afficher détail');
		$(obj).attr('class','pic24 zdt2');
	}
	else
	{
		$(robj).show();
		$(obj).html('Masquer détail');
		$(obj).attr('class','pic24 adt1');
	}
}
/* FIN recoupement alertes vendeur */

function maxChar(obj,lng)
{
	$(obj).val( $(obj).val().substr(0,lng) );
}

/* Fonction de tri */
function tridemande(val, sens)
{
	var url = $('#formModeAffichage').attr('action') + '&triSur=' + val + '&modeDeTri=' + sens;
	$('#formModeAffichage').attr('action', url);
	$('#formModeAffichage').submit();
}

function visibilite(idContenu)
{
	$('#' + idContenu).toggle();
}

/* Change les onglet d'information*/
function changeOngletInfo(obj)
{
	ids = $(obj).attr('href');
	$(ids).parent().find('ul').parent().each(function() {
	$(this).hide();
	});
	$(ids).show(); 
}

function actionVendeur(action, elem){
	var messageConfirm = '';
	switch(action){
		case 'modif':  messageConfirm = 'Souhaitez-vous modifier ce vendeur ?';break;
		case 'supp' :  messageConfirm = 'Souhaitez-vous supprimer ce vendeur ?'; break;
	}
	
	// Récupération des paramètres en fonction de l'action
	var param = null;
	switch(action){
		case 'modif':  
					var ligne = $(elem).closest('tr');
					// Verifie que la ligne validé soit valide
					if(!$(ligne).find('input[name|=civilite]').valid()
						|| !$(ligne).find('input[name!=nom]').valid()
						|| !$(ligne).find('input[name!=prenom]').valid()
						|| !$(ligne).find('input[name!=mel]').valid()
					){
						return false;
					}
					$('#h-act').val('modif');
					$('#h-id').val($(ligne).find('input[name|=idVend]').val());
					$('#h-civ').val($(ligne).find('input[name|=civilite]:checked').val());
					$('#h-nom').val($(ligne).find('input[name|=nom]').val());
					$('#h-prenom').val($(ligne).find('input[name|=prenom]').val());
					$('#h-mail').val($(ligne).find('input[name|=mel]').val());
					$('#h-tel').val($(ligne).find('input[name|=tel]').val());
					break;
		case 'supp' : 
					var ligne = $(elem).closest('tr');
					$('#h-act').val('supp');
					$('#h-id').val($(ligne).find('input[name|=idVend]').val());
					$('#h-civ').val('');
					$('#h-nom').val('');
					$('#h-prenom').val('');
					$('#h-mail').val('');
					$('#h-tel').val('');
					break;
	}
	
	if (confirm(messageConfirm)) {
		$('#form_modifVendeurHidden').submit();
	}else{
		var ligne = $(elem).closest('tr');
		$('#h-act').val('');
		$('#h-id').val('');
		$('#h-civ').val('');
		$('#h-nom').val('');
		$('#h-prenom').val('');
		$('#h-mail').val('');
		$('#h-tel').val('');
	}
}


// CLIC2PAC
function openClic2Pac(){
	var compteur = 0;
	$('#messageErreurClic2Pac').hide();
	$('.chkSelectAnnonce').each(function(i){
		if($('#c2p_photo_'+$(this).val()).length)		$('#c2p_photo_'+$(this).val()).removeAttr('checked');
		if($('#c2p_publ_'+$(this).val()).length)		$('#c2p_publ_'+$(this).val()).removeAttr('checked');
		if($('#c2p_photopubl_'+$(this).val()).length)	$('#c2p_photopubl_'+$(this).val()).removeAttr('checked');
		
		var show = false;
		if($(this).is(':checked')) {
			compteur++;
			show = true;
		}
			
		if($('#clic2pac_'+$(this).val()).length) {
			if(show) $('#clic2pac_'+$(this).val()).show();
			else $('#clic2pac_'+$(this).val()).hide();
		}
	});
	
	if(compteur==0) {
    	alert('Vous devez sélectionner au moins une annonce.');
    } else {
    	// Affichage du div de confirmation de la version "spéciale"
        if($('#cadr_confirm')) $('#cadr_confirm').show();
        if($('#cadr_confirm2')) $('#cadr_confirm2').hide();
        if($('#cadr_confirm3')) $('#cadr_confirm3').hide();
    	openPopin('clic2pac_content');
    }
	return false;		
}

function clic2pacSEND(){
    
    // Controle du formulaire
    $('#messageErreurClic2Pac').hide();
    var erreur = false;
    $('#popinClic2Pac table tbody tr:visible').each(function(){
    	if($(this).find('input:checked').length == 0){
    		erreur = true;
    		return false;
    	}
    });
    
    if(erreur){
    	$('#messageErreurClic2Pac').show();
    	return false;
    }
    
    if($('#cadr_confirm')) $('#cadr_confirm').hide();
    if($('#cadr_confirm2')) $('#cadr_confirm2').hide();
    if($('#cadr_confirm3')) $('#cadr_confirm3').show();
	
	var ajaxData = {'listeIdsAnnoncesPhoto':'', 'listeIdsAnnoncesAutre':'', 'listeIdsAnnoncesPhotoAutre':''},
		elementNameCorresp = {'listeIdsAnnoncesPhoto':'c2p_photo', 'listeIdsAnnoncesAutre':'c2p_publ', 'listeIdsAnnoncesPhotoAutre':'c2p_photopubl'};
	$.each(elementNameCorresp, function(dataIndex,domName){
		var arrayToBrowse = document.getElementsByName(domName);
		ajaxData[dataIndex] = $.map(arrayToBrowse, function(element,index){
			var $element = $(element);
			if($element.is(':checked')) {
				return $element.val();
			}
		}).join('|');
	});
	$.ajax({
		url:urlSendMailClic2Pas,
		method: 'post',
		data: ajaxData,
		async: false,
		success: function(response, xhr) {
			if(response != '') $('#clic2pac_reponse').html(response);
			if($('#cadr_confirm2')) $('#cadr_confirm2').show();
			if($('#cadr_confirm')) $('#cadr_confirm').hide();
			if($('#cadr_confirm3')) $('#cadr_confirm3').hide();
		}
	});
	return false;		
}
// FIN CLIC2PAC

