/*
 * @author yann ducrocq - la cooperative de communication
 * @date 28/07/2008
 */


function global_onload() {	
	$('#loadingAnimation').hide();
	$('#contenu').show();
	launchPageCustomObjects();	
	partenariat_load();
	sticker_tv();
	$('#CNIL-link').click(function() {		
		$('#CNIL-text').toggleClass('hide');
		return false;
	});
}

function pages_onload() {
	global_onload();
	
	$('.mail').each(function() {
		$(this).decrypter();		
		var mailto = $(this).text();				
		$(this).html('<a href="mailto:' + mailto + '">' + mailto + '</a>');
		$(this).show();
	})	
	
	form_equinoxe();
	
	show_partenaire();
}

function form_equinoxe() { 
	$('#btn-equinoxe-form').click(function() {
		$('#form-equinoxe-handler').toggleClass('hide');	
		return false;
	});
	
	$('#form-equinoxe').submit(function() {
		var id 			= $(this).attr('id');
		var nom 		= $.trim($(this).find('#'+id+'-nom').val());
		var mail 		= $.trim($(this).find('#'+id+'-mail').val());
		var mobile 		= $.trim($(this).find('#'+id+'-mobile').val());
		var errors='';
		
		if ( nom == '' )
			errors +='<li>Le nom ne doit pas être vide</li>';
		
		if ( mail == '' )
			errors +='<li>L\'e-mail ne doit pas être vide</li>';
		else if ( !form_validate_email( mail ) ) 
			errors +='<li>E-mail est incorrect (format attendu : nom@domaine.ext)</li>';
		
		if ( mobile == '' )
			errors +='<li>Le téléphone ne doit pas être vide</li>';
		else if ( !form_validate_numbers( mobile ) ) 
			errors +='<li>Le téléphone est incorrect (format attendu : 0123456789)</li>';
		
		if ( errors != '' ) {
			$('#'+id+'-errors').html('<ul>' + errors + '</ul>');
			$('#'+id+'-errors').removeClass('hide');				
		} else {
			$.post('/Pages/asyncEquinoxe',{'nom':nom,'mail':mail,'mobile':mobile},function(data) {
				if ( data.error ) {
					$('#form-equinoxe-errors').html('<ul><li>'+data.error+'</li></ul>');
				} else 
					$('#form-equinoxe-errors').addClass('hide');
				
				if ( data.confirm ) {
					$('#btn-equinoxe-form').addClass('hide');
					$('#form-equinoxe-handler .intro').addClass('hide');
					$('#form-equinoxe').addClass('hide');
					$('#form-equinoxe-confirm').html(data.confirm);
					$('#form-equinoxe-confirm').removeClass('hide');
				}
			}, 'json');
		}
			
		return false;
	});
}

function accueil_onload() {
	
	$('#form_inscription').submit(function(){
			return callbackBeforeSubmitForm('form_inscription');
		}
	);
	
	$('#password').keydown(showConfirmPwd);	
	$('#password').click(showConfirmPwd);
	$('#bt_inscrire').click(showConfirmPwd);
	$('.et_idealement').click(function(){
		//$('#form_inscription').submit();
		//return false;
	});
	
	global_onload();	
	launchCustomObjects('#form_inscription');
	
}

function showConfirmPwd() {
	$('#confirm_password').show();
}

function sticker_tv() {
	$('.sticker_tv').click(function() {
		popup_stickerTV();
		return false;
	});	
}

//indexer les formulaires en ajax
var aCcAjaxFormsRegistry = new Array();
var aElementsRequired = new Array();
var aElementsPattern = new Array();

function acheteur_onload() {
	var modeDemo 	= $('.body_bg').is('.modeDemonstration');
	var msgDemo		= 'Veuillez remplir le formulaire "Mon profil" pour pouvoir continuer.';
	
	if ( modeDemo ) {
		$('#col_gauche').append( '<div id="layerDemo"></div>' );
		$('#layerDemo').height( 2000 );
		$('#layerDemo').click(
			function() {
				popup_alert(msgDemo, '#form_profil');
				return false;
			}
		);
	}
		
	//gestion Barre Onglets
	$('.op_border span').click( function() {
		$('.op_border span').each(function() {
			//changement de la classe du LI parent
			$(this).parents('li').attr('class',''); 
		});
		
		$(this).parents('li').attr('class','active');
	});

		/* evenements onglets projets */
	$('.bt_projet_next').click(function(){
		$('#form_projet_next').show();					
	});	
		
	if (modeDemo) {
		$('#form_projet_next').submit(function() {
			popup_alert(msgDemo, '#form_profil');
			return false;
		});
	}
	
	$('#formOngletProjet_setTitle .bt').click(function(){
		$(this).parent().hide();
		var input_associe = $(this).siblings('.text');	
		var onglet_associe = $(this).parents('li').find('a');
		
		$(this).parents('li').css('width','auto')
		
		var val = input_associe.val();
		
		if ($.trim(val) != '' && !modeDemo) {
			$.ajax({
				type: "POST",
				url: "/MonProjet/asyncModifierTitreProjet",
				data: "titre=" + encodeURI(val),
				success: function(msg){
					if (msg.substring(0, 2) == 'OK') 
						onglet_associe.text(val);
				}
			});
		}
	});
		
	/* 
	 * FORMS asynchrones ;-)
	 */ 	
	//init de tous les forms
	for (var idForm in aCcAjaxFormsRegistry) {
		aCcAjaxFormsRegistry[idForm].init();
	}
	
	$('.modeDemo').unbind('submit').submit(function(){
		popup_alert(msgDemo, '#form_profil');
		return false;
	});
	
	/* bouton envoi agences */
	$('#bt_envoi_agences').click(function() {
		$(this).addClass('loaded');
		monprojet_envoiAgences();
		return false;
	});
	
	global_onload();
	
	setTimeout('bGlobalAutoSave = true;',10000);
}

function monprojet_envoiAgences() {	
	var $_parent 	= $('.envoi_agences');
	var $_loading	= $('.envoi_agences').find('.ajaxLoading');
	var $_label	 	= $('.envoi_agences').find('.msg_projet_statut');
	var $_bouton	= $('#bt_envoi_agences');
	var $_boutonImg	= $_bouton.children();
	
	var msgDemo		= 'Veuillez remplir le formulaire "Mon profil" pour pouvoir continuer.';
	
	if ($('.body_bg').is('.modeDemonstration')) {
		popup_alert(msgDemo);
	}
	else {
		
		forms_globalAutoSave('bt_envoi_agences');
		
		if ($_bouton.is('.loaded')) {		
			$_bouton.hide();
			$_loading.show();
			$_label.text('Veuillez patienter...');
		}
		
		$.ajax({
			type: 'GET',
			url: '/MonProjet/asyncEnvoiAgences',
			data: 'init=' + $_bouton.is('.loaded') ? 1 : 0,
			success: function(msg){
				if (msg.indexOf('id="jsResponse') >= 0) { //erreur
					$_bouton.html(msg);
					eval($('#jsResponse').text());
				}
				else {
					if (msg == 'NOK') {
						$_bouton.removeClass('projetOK');
						$_boutonImg.attr('src', '/images/envoyer_agences.png');
						$_label.text('Votre projet est pr\352t ?');
					}
					else 
						if (msg == 'OK') {
							$_bouton.addClass('projetOK');
							$_label.text('Projet envoy\351 aux professionnels');
							popup_alert(							
								'<strong>Votre projet a \351t\351 transmis aux professionnels</strong><br/>'							
							+	'Ils vous contactent ainsi d\350s qu\'un bien se rapproche ou correspond id\351alement \340 votre projet<br>'
							+	'Un autre id\351al en t\352te, n\'h\351sitez pas \340 cr\351er un nouveau projet'
							);
						}
					
					if ($_bouton.is('.loaded')) {
						if (msg == 'NOK')
							$_bouton.show();
						$_loading.hide();
					}
				}
			}
		});
	}
}

function professionnels_onload() {
	/*** bloc rechercher ****/	
		
	//module pourcentage
	$('#form_rechercher .pourcentage .bt_pourcent').click(function() {
		
		var oper 	= $(this).attr('rel');
		var text 	= $(this).parents('.pourcentage').find('.text_pourcent');
		var real_val= text.val();
		real_val	= real_val.substring(0,real_val.length-1);
		
		if ( oper == '+' && real_val<= 25 )
			text.val((parseInt(real_val)+5)+'%');
		if ( oper == '-' && real_val>= 5 )
			text.val((parseInt(real_val)-5)+'%');
			
		return false;
	});
	
	/*
	 * BLOCS asynchrones
	 */
	//blockAsyncLoad('resultats_recherche', '/Professionnels/asyncResultatsRecherche');
	blockAsyncLoad('googlemap', '/Professionnels/asyncGooglemap');		
	blockAsyncLoad('listeProfils', '/Professionnels/asyncListeProfils');	
	
	
	
	/* 
	 * FORMS asynchrones ;-)
	 */ 	
	//le form de recherche est different car il provoque le rafraichissement du flexigrid
	
	
	$('#form_rechercher').submit(function(){		
		reglette_beforeSubmit('#form_rechercher');
		
		/*
		 * envoi du formulaire au flexigrid
		 */
		if (callbackBeforeSubmitForm('form_rechercher')) {	
			var sData = $(this).formSerialize();			
			loadFlexigrid(sData, false);
			/*
	 		* le flexigrid lance le rafraichissement du googlemap	*
	 		*/
		} 
		
		
		return false;
	});
	
	$('#form_rechercher .lBudget').each(function(){
		var texte = $.trim( $(this).text() );
		
		switch(texte) {
			case 'Budget max': $(this).text('Budget'); break;
			case 'Surface min': $(this).text('Surface'); break;			
		}
	});		
	
	//init de tous les forms
	for (var idForm in aCcAjaxFormsRegistry) {
		aCcAjaxFormsRegistry[idForm].init();
	}	
	
	global_onload();
	launchCustomObjects('#form_rechercher');
	
	
	//champs code postal
	$('#form_rechercher #f_latsop_edoc_elliv').keydown(cp_clean).blur(cp_clean);
	
	/* 
	 * -------- doit se trouver apres le layout_bloc (@global_onload) ----------- 
	 * 
	 */
	$('#form_rechercher .bt_enregistrer_profil_recherche').click(function() {
		$(this).siblings('.form_profil_recherche').show();
		return false;
	});
	
	//enregistrement d'un profil
	$('#form_rechercher input[@name=submit_enregistrer_profil_recherche]').click(function(){
		var sData 	= $('#form_rechercher').formSerialize();
		var sId		= 'listeProfils';
		$('#'+sId).find('.ajaxLoading').show();	
		
		$.ajax({
	  	type: 		'POST',
	  	url: 		'/Professionnels/asyncListeProfils',
		data:		sData+'&insertProfil=1',
		success: 	function(msg) {											
						$('#'+sId).find('.bContenu').html(msg);
						$('#'+sId).find('.bContenu').show();
						$('#'+sId).find('.ajaxLoading').hide();	
						$('#form_rechercher .form_profil_recherche').hide();						
						launchCustomObjects('#' + sId);
						callbackSuccessForm('form_'+sId,false);
					}
		});
	});
	
	/*
	 * Mode demo : desactivation de certains modules
	 */	

	$('.modeDemonstration .modifier').unbind('click').click(function() {
		window.location.href = '/Pages/AdhesionPro';
		return false;
	});	
	
	$('.modeDemonstration #form_rechercher [@name=submit_enregistrer_profil_recherche]').unbind('click').click(function() {
		window.location.href = '/Pages/AdhesionPro';
		return false;
	});	
	
	$('.modeDemonstration #listeProfils .delete_profil_recherche').unbind('click').click(function() {
		window.location.href = '/Pages/AdhesionPro';
		return false;
	});
}

function cp_clean() {
	var value = $(this).val().toString();
	
	if (value.length > 5)
		value = value.substring(0,5);
		
	var value_propre='';	
		
	for( var i=0; i<value.length; i++ ) {
		if (/^\d$/.test(value.charAt(i))) {
			value_propre+=value.charAt(i);
		}
	}
	
	$(this).val(value_propre);
}

function blockAsyncLoad(sId, sUrl) {
		//bloc resultats
	$('#'+sId).find('.ajaxLoading').show();
	
	$.ajax({
	  	type: 		'GET',
	  	url: 		sUrl,
		success: 	function(msg) {											
						$('#'+sId).find('.bContenu').html(msg);
						$('#'+sId).find('.bContenu').show();
						$('#'+sId).find('.ajaxLoading').hide();	
						
						
						launchCustomObjects('#' + sId);
						callbackSuccessForm('form_'+sId,false);
					}
		});
}


/* gestion des fleches de blocs */

function initFleche() {
	var nContenu = $(this).parents('.bHeader').siblings('.bContenu');
	$(this).attr('class', nContenu.css('display') == 'none' ? 'png bFleche' : 'png bFleche active' );
}

function eventFleche() {		
	var nContenu = $(this).parents('.bHeader').siblings('.bContenu');
	$(this).toggleClass('active');
	
		
	if ( $(this).is('.active') ) {
		nContenu.siblings('.bDescriptif').hide();				
		nContenu.slideDown("slow");				
	}
	else {		
		nContenu.slideUp("fast");	
		nContenu.siblings('.bDescriptif').show();	
	}
}
/* fin gestion des fleches*/

/* nb de chambres */

/* fin nb de chambres */

function eventChambre() {
	var bt = $(this).attr('button');
	var change = true;
	
	var input_associe = $(this).parent().prev('.nb_chambres_radios').find('input');
	
	$(this).parent().find('.btChambre').each(function() {
		var bt2 = $(this).attr('button');
		
		if ($(this).is('.nb'+bt2+'_active') ) {
			$(this).toggleClass('nb'+bt2+'_active');
			
			if ( bt == bt2 ) {
				input_associe.val(0);
				change=false;
			}
		}
	});
	
	if (change) {		
		$(this).toggleClass('nb'+bt+'_active');
		input_associe.val(bt);
	}
}

/*
 * @param String idForm
 * @param String asyncUrl
 * @param String mode
 */

function ccAjaxForm(idForm, asyncUrl, defautMode) {
	var _this			= this;
	_this.id			= idForm;
	_this.real_id		= _this.id.substring(5,_this.id.length);
	_this.jqId			= '#'+_this.id;
	_this.url			= asyncUrl;
	_this.mode			= defautMode;
	_this.target 		= '#' + _this.id + ' .bContenu';
	_this.pk			= 0;
	
	_this.options 		= {
		beforeSubmit: function(){
			if ( callbackBeforeSubmitForm(_this.id) ) {				
				$(_this.jqId).find('.ajaxLoading').show();
				$(_this.jqId).find('.enregistrer').attr('disabled', 'true');			
				$(_this.jqId).find('.bFleche').click();
			}else {
				return false;
			}
		},
		success: function(msg){			
			$(_this.jqId).find('.ajaxLoading').hide();	
			$(_this.jqId).find('.enregistrer').removeAttr('disabled');
			
			$(_this.target).html(msg);
			
			if ( _this.mode == 'affichage'  ) {
				$(_this.jqId).find('.enregistrer').hide();
				$(_this.jqId).find('.modifier').show();
			}
			
			$(_this.jqId).find('.bFleche').click();					
			launchCustomObjects(_this.jqId);			
			callbackSuccessForm(_this.id, false);	
		},
		url: _this.url,
		type: 'post'
	};
		
	this.init	= function() {	
		var options = _this.options;		
		
		$(_this.jqId).submit(function() {	
			form_beforeAjaxSubmit(_this.jqId);
							
			$(this).ajaxSubmit(options);
			return false;
		});
			
		//ajax pour initialiser l'objet				
		$.ajax({
	  	type: 		'GET',
		data:		'mode=' + _this.mode,
	  	url: 		_this.url,
		success: 	function(msg) {											
						$(_this.target).html(msg);
						
						$(_this.jqId).find('.ajaxLoading').hide();
						
						if (_this.mode == 'affichage') {
							$(_this.jqId).find('.enregistrer').hide();
							$(_this.jqId).find('.modifier').show().click(
																	function() {
																		var pk = $(_this.jqId).find('#selectProfil').val();
																		if (pk>0)
																			_this.pk = pk;
																			
																		_this.modeEdition();
																	});
						}
						else 
							$(_this.jqId).find('.enregistrer').show();
							
						launchCustomObjects(_this.jqId);						
						callbackSuccessForm(_this.id, true);
					}
		, 
		error: function(msg) {
					$(_this.jqId).find('.modifier').hide();
					$(_this.jqId).find('.enregistrer').hide();
				}
		});	
	}
	
	this.modeEdition = function() {			
		var jqForm 	= $('#' + _this.id);
		var target 	= _this.target;		
		$(_this.jqId).find('.ajaxLoading').show();
		$(_this.jqId).find('.modifier').attr('disabled','true');	
		
		$.ajax({
	  	type: 		'GET',
		data:		'mode=edition' + ( _this.pk > 0 ? '&pk=' + _this.pk : ''),
	  	url: 		_this.url,
		success: 	function(msg) {											
						$(target).html(msg);
						$(_this.jqId).find('.ajaxLoading').hide();
						$(_this.jqId).find('.modifier').removeAttr('disabled');
						$(_this.jqId).find('.modifier').hide();
						$(_this.jqId).find('.enregistrer').show();
						$(_this.jqId).find('.bDescriptif').hide();
						$(_this.jqId).find('.bContenu').show();
						
						launchCustomObjects(_this.jqId);					
						callbackSuccessForm(_this.id, false);
					}
		});
	}
}

function form_beforeAjaxSubmit(id) {
	reglette_beforeSubmit(id);
}


var bGlobalAutoSave=false; 
//enregistrement de TOUS les formulaires, qd on clique sur 1 des boutons enregistrer

function callbackSuccessForm(id,init) {
	switch(id) {
		case 'form_googlemap':
			googlemap_reload(false, init);
		break;
		
		case 'form_agence':
			$('#form_agence .bDescriptif').text($('#form_agence_nom_societe .info').text());
		break;
		
		case 'form_collaborateur':
			$('#form_collaborateur .bDescriptif').text($('#form_collaborateur_prenom .info').text()+' '+$('#form_collaborateur_nom .info').text());
		break;
		
		case 'form_projet':
		//mettre a jour les codes postaux du bloc googlemap
		//avec ceux du bloc mon_projet
			monProjet_miseajour_cp();		
		break;	
		
		case 'form_profil':
			var modeDemo 	= $('.body_bg').is('.modeDemonstration');
			var userIsActive = parseInt($('#user-active').val()) > 0;
				
			if (userIsActive) {
				var $btActivateAccount = $('<a href="MonProjet/desactiver?compte" class="bt_supprimer">Désactiver mon compte</a>');
				$btActivateAccount.click(function() {
					return confirm('Souhaitez-vous vraiment désactiver votre compte ?');						
				});
			} else {
				var $btActivateAccount = $('<a href="MonProjet/activer?compte" class="bt_supprimer">Réactiver mon compte</a>');				
			}
			
			var $jqForm = $('#form_profil');
			
			if ( !modeDemo ) 
				$jqForm.find('.bFooter .bHtml').append($btActivateAccount);
			
		break;
	}	
	
	forms_globalAutoSave(id);
}

function forms_globalAutoSave(id) {
	if (bGlobalAutoSave) {
		bGlobalAutoSave = false;
		var i=0;
		
		for (var idForm in aCcAjaxFormsRegistry) {
			if (idForm == id || aCcAjaxFormsRegistry[idForm].mode == 'affichage') {
				continue;
			}				
			else {
				setTimeout('$("#' + idForm + '").submit();', i*1000);
			}
			
			i++;
		}
		
		//attente de 10 secondes pour remettre le flag d'enregistrement 
		setTimeout('bGlobalAutoSave=true;', 10000);
		
		if (id != 'bt_envoi_agences')
			monProjet_resetBoutonEnvoi();
	}
}

function monProjet_resetBoutonEnvoi() {
	if ($('#bt_envoi_agences').is('.projetOK') && $('#bt_envoi_agences').is('.loaded'))
		$('#bt_envoi_agences').click();
}

function googlemap_reload(isInThickbox, init) {
	var sParent = !isInThickbox ? '.body_bg' : '#TB_window';
	var oSpan = $(sParent + ' .jsGoogleCircles');
	var cM, rM;
	
	if ($.trim(oSpan.text()) != '') {				
		eval(oSpan.text());
	}	
	
	if (init) {
		if (cM && rM) {
			for (var i = 0; i < cM.length; i++) {
				var point1 = new GLatLng(cM[i].x, cM[i].y);
				var point2 = new GLatLng(rM[i].x, rM[i].y);
				googlemap_createCircleInput(point1, point2);
			}
		}
	}
}

function callbackBeforeSubmitForm(sFormName){
	
	
	var msg='';	
	
	switch(sFormName) {
		case 'form_projet':
		case 'form_projet_precisement':
		case 'form_googlemap':
			msg += checkChampsObligatoires();		
			$('#bt_envoi_agences').addClass('loaded');			
		break;
		case 'form_rechercher':
			var cp = $.trim($('#form_rechercher [@name=f_latsop_edoc_elliv]').val() );
			
			if ( cp < 10 && cp.length == 1 )
				$('#form_rechercher [@name=f_latsop_edoc_elliv]').val('0'+cp);				
			/*else
				msg += '<li>Le code postal est incorrect</li>';*/
		break;
		case 'form_inscription':
			var bdg = $('#f_xam_tegdub').val();
			if (bdg <= 0 ) {
				msg += '<li>Le budget maximum doit \352tre sup\351rieur a z\351ro</li>';
			}
			// on test la validite du code postal 
			cp = $("input[name='f_1_latsop_edoc']").val();
			regex = new RegExp("^[0-9]{5}$");
			if ( cp.search( regex ) == -1 )	msg += '<li>Le code postal doit comporter 5 chiffres</li>';
		break;
	}
	
	
	
	if (typeof(aElementsRequired[sFormName]) != 'undefined' && aElementsRequired[sFormName].length > 0) {
		for (var i = 0; i < aElementsRequired[sFormName].length; i += 2) {			
			if ($.trim($('[@name=' + aElementsRequired[sFormName][i] + ']').val()) == '') {
				msg += '<li>Le champ ' + aElementsRequired[sFormName][i + 1] + ' ne doit pas \352tre vide</li>';
			}
		}
	}
	
	if (typeof(aElementsPattern[sFormName]) != 'undefined' && aElementsPattern[sFormName].length > 0) {
		for (var i = 0; i < aElementsPattern[sFormName].length; i += 4) {
			if ($.trim($('[@name=' + aElementsPattern[sFormName][i] + ']').val()).match(aElementsPattern[sFormName][i + 1])) {
				msg += '<li>Le champ ' + aElementsPattern[sFormName][i + 2] + ' doit \352tre au format ' + aElementsPattern[sFormName][i + 3] + '</li>';
			}
		}
	}
	
	msg += validateEmail();
	msg += validatePasswords();
		
	
	
	if (msg != '') {		
		popup_alert('<ul>' + msg + '</ul>');
		return false;		
	}
	else 
		return true;
}

function checkChampsObligatoires() {
	var msg='';
	var cp1 = $('#form_projet [@name=f_1_latsop_edoc]').val();
	var cp2 = $('#form_projet [@name=f_2_latsop_edoc]').val();
	var cp3 = $('#form_projet [@name=f_3_latsop_edoc]').val();
	var regCP = new RegExp(/^\d{5,5}$/);
	
	
	
	if (cp1.indexOf('Choix')>=0)
		$('#form_projet [@name=f_1_latsop_edoc]').val('');
	if (cp2.indexOf('Choix')>=0)
		$('#form_projet [@name=f_2_latsop_edoc]').val('');	
	if (cp3.indexOf('Choix')>=0)
		$('#form_projet [@name=f_3_latsop_edoc]').val('');
		
	if (!cp1.match(regCP) && !cp2.match(regCP) && !cp3.match(regCP) ) {
		msg += '<li>Le code postal doit comporter 5 chiffres</li>';
	}
	
	var bdg = $('#f_xam_tegdub').val();
	if (bdg <= 0 ) {
		msg += '<li>Le budget maximum est requis</li>';
	}
	
	return msg;
}

function launchPageCustomObjects() {
	
	//layout des blocs
	$('.bloc').each(function(){
		layout_bloc($(this));
	});

	//ajout des fleches de bloc
	$(' .bHeader h3').each(function() {		
		if (! $(this).parents('.bloc').is('.noFleche'))		
			$(this).html( $(this).html() + '<span class="bFleche"></span>' );
	});
	
	$(' .bFleche').each( initFleche );	
	$(' .bFleche').click( eventFleche );	
	
	//blocs : on check si le bloc est dans un form
	//sinon calage du loading a droite
	//placement des boutons enregistrer ou modifier en bas des blocs
	$('.bloc').each(function() {	
		var formId = $(this).parents('form').attr('id');
	
		if ( $(this).parents('form') && aCcAjaxFormsRegistry[formId] ) {		
			var jqForm 		= $(this).parents('form');	
			var oForm		= aCcAjaxFormsRegistry[formId];		
			var sButton 	= oForm.mode == 'edition' ? 'enregistrer' : 'modifier';
			
			if (sButton == 'enregistrer') {
				/*
				 * TODO : bouton 'modifier' a implementer : il faudrait appeler la fonction de l'objet ccAjaxForm
				 */
				
				jqForm.find('.bFooter .bHtml').append('<a href="#" class="bt_enregistrer_alias">Enregistrer</a>');
				jqForm.find('.bFooter').find('.bt_enregistrer_alias').click(function(){
					jqForm.submit();
					return false;
				});
			}
		}	
		else {
			$(this).find('.ajaxLoading').addClass('right30');
		}
	});
	
	$('#onglets_projets .active a').click(function() {
		ongletProjet_setTitle();
		return false;
	});
	
	//messagerie	
	messagerie_init('.body_bg .messagerie');
}

function launchCustomObjects(sParent) {		
	monProjet_miseajour_cp();

	//nb_chambres
	for (var i=1; i<6; i++) {
		if ($(sParent+' .nb_chambres_buttons').children().is('.nb'+i)) 
			break;
		$(sParent+' .nb_chambres_buttons').append('<span class="btChambre nb'+i+'" button="'+i+'"></span>');
	}	
	
	$(sParent+' .btChambre').click( eventChambre );	
	
	//si le champs hidden des chambres a une valeur, on met a jour les boutons
	$(sParent+' .nb_chambres_radios :hidden').each(function(){		
		if ($(this).val() > 0 )
			$(this).parents('.nb_chambres_radios').siblings('.nb_chambres_buttons').find('.btChambre[button='+$(this).val()+']').click();
	});
	
	/**
	 * objets reglette
	 */
	
	$(sParent+' .budget').each(function(){		
		reglette($(this))
	});
	
	/* -- fin reglette -- */
	
	/* priorites */
	/*$(sParent+' .priorite').each(function() {
		if ($.trim($(this).val()) == '')
			$(this).val(1);
	});*/
	
	champsImportants_reload(sParent);
	
	//select collaborateurs
	$(sParent+' #selectProfil').change(function() {
		var jqForm = $(sParent);
		
		jqForm.find('.ajaxLoading').show();
		jqForm.find('.modifier').attr('disabled','true');
		
		$.ajax({
	  	type: 		'GET',
		data:		'mode=affichage&pk=' + $(this).val(),
	  	url: 		'/Professionnels/asyncFormCollaborateur',
		success: 	function(msg) {											
						jqForm.find('.bContenu').html(msg);
						jqForm.find('.ajaxLoading').hide();
						jqForm.find('.modifier').show();
						jqForm.find('.enregistrer').hide();
						jqForm.find('.modifier').removeAttr('disabled');
						
						launchCustomObjects(parent);					
						callbackSuccessForm(parent);
					}
		});
	});
	
	//bouton nouveau collaborateur	
	$(sParent+' .bt_nouveau_collaborateur').click(function(){
		var jqForm = $(sParent);
		
		jqForm.find('.ajaxLoading').show();
		jqForm.find('.modifier').attr('disabled','true');
		
		$.ajax({
	  	type: 		'GET',
		data:		'mode=edition&ajouter=collaborateur',
	  	url: 		'/Professionnels/asyncFormCollaborateur',
		success: 	function(msg) {											
				jqForm.find('.bContenu').html(msg);
				jqForm.find('.ajaxLoading').hide();
				jqForm.find('.modifier').removeAttr('disabled');
				jqForm.find('.modifier').hide();
				jqForm.find('.enregistrer').show();
				jqForm.find('.bt_nouveau_collaborateur').hide();
				
				launchCustomObjects(parent);					
				callbackSuccessForm(parent);
			}
		});
	});
	
	
	
	//bloc liste des profils
	$(sParent+ ' .profil_recherche').click(function(){		
		var strJS = $(this).siblings('.profil_js_datas').text();
			
		if (strJS) {
			$('#form_rechercher').resetForm();			
			var arDatas = eval('(' + strJS + ')');
			
			if (arDatas) {
				for (var i in arDatas) {
					$('#form_rechercher [@name=' + i + ']').val(arDatas[i]);
				
					//console.log(i + ':' + arDatas[i]);
				}
			}
			
			//submit_recherche requis pour lancer la bonne action cote serveur			
			$('#form_rechercher').submit();
			launchCustomObjects('#form_rechercher');
		}	
				
		return false;
	});
	
	if (!$('.body_bg').is('.modeDemonstration')) {
		$(sParent + ' .delete_profil_recherche').click(function(){
			var tmp = $(this).attr('class').split(' ');
			id = tmp[1].substring(3, tmp[1].length);
			
			if (id > 0) {
				$(sParent + ' .ajaxLoading').show();
				
				$.ajax({
					type: "GET",
					url: "/Professionnels/asyncListeProfils",
					data: "delete=1&id_profil=" + id,
					
					success: function(msg){
						$(sParent + ' .bContenu').html(msg);
						launchCustomObjects(sParent);
						$(sParent + ' .ajaxLoading').hide();
					}
				});
			}
			
			return false;
		});
	}
	
	$(sParent+ ' .bt_loadGmap').click(function() {
		var sCP = $(this).prev('span').text();
		
		if (map && $.trim(sCP)!='') 
			showAddress(sCP+', France', map);
	});
	
	$(sParent + ' .disabled').each(function() {
		$(this).find('input').attr('readonly','true');
	});
	
	//val par defaut monprojet>projet>CP
	var iCP = 1;
	
	$(sParent + ' .jqCP').each(function() {
		var jqInput = $(this).find('input');
		
		if ( $.trim( jqInput.val() ) == '') {
			jqInput.click(function(){
				$(this).val('');
			}).val('Choix ' + iCP);
		}
			
		iCP++;
	});	
	
	
	/** mode demo **/
	//vider l'input email du form_profil en mode edition (mode demo)
	$('.profil_modeDemo .text').val('');
	
	
	
	//eval de span#JsResponse s'il est present
	$('#JsResponse').each(function() {
		eval($(this).text());
	});				
	
	$(sParent + ' .multicheckbox').each(
		function(){
			multicheckbox($(this))
		}
	);
	
	$('#form_projet [@name=f_1_latsop_edoc], #form_projet [@name=f_2_latsop_edoc], #form_projet [@name=f_3_latsop_edoc]').keydown(cp_clean).blur(cp_clean);
	
}

function champsImportants_reload(sParent) {
	//champs prioritaire/redhibitoire
	$(sParent+' .priorite').each(function() {
		var inputH 		= $(this);
		var iNbLevels 	= 4;		
		
		inputH.wrap('<span class="wrapPriorite"></span>');
		var value		=  inputH.val();			
			
		$(this).parents('.wrapPriorite').append('<span class="btPriorite' + (value>=1 ? ' on' : '' ) + '" nb="1" title="Souhait\351"></span>');	
		$(this).parents('.wrapPriorite').append('<span class="btPriorite' + (value>=2 ? ' on' : '' ) + '" nb="2" title="Important"></span>');
		$(this).parents('.wrapPriorite').append('<span class="btPriorite' + (value>=3 ? ' on' : '' ) + '" nb="3" title="Tr\350s important"></span>');
		$(this).parents('.wrapPriorite').append('<span class="btPriorite max' + (value==4 ? ' on' : '' ) + '" nb="4" title="Obligatoire"></span>');				
		$(this).parents('.wrapPriorite').append('<span class="clear"></span>');
		
		//en mode edition cet objet est cliquable				
		if ($(this).parents('.bContenu').children('div').attr('class') == 'edition') {
			$(this).siblings('.btPriorite').css('cursor','pointer');
			
			$(this).siblings('.btPriorite').click(function(){
				inputH.val(0);
				
				var nb = $(this).attr('nb');
				
				//bouton priorite
				if (nb > 0) {
					$(this).toggleClass('on');
					var $$_class = $(this).attr('class');
					var $$_on = $$_class.substring($$_class.length - 2, $$_class.length) == 'on';
					
					for (var i = 1; i <= iNbLevels; i++) {
						if ($$_on && i < nb) {
							$(this).siblings('[@nb=' + i + ']').addClass('on');
						}
						else {
							$(this).siblings('[@nb=' + i + ']').removeClass('on');
						}
					}
					
					if ($$_on) 
						inputH.val(nb);
				}
			});
		}
	});
}

/**
 * 
 * @param {Object} sForm
 * @param {Object} sSubmit
 */
function form_js_submit(sForm, sSubmit) {
	var oForm = $('#'+sForm);	
	if (!oForm) 
		oForm = $('[@name='+sForm+']');			
	oForm.find('[@name='+sSubmit+']').click();
	
	return false;
}

function ongletProjet_setTitle() {
	var f = $('#formOngletProjet_setTitle');	
	var oOngletAssocie = $('#onglets_projets li.active');
	var iInputWidth = oOngletAssocie.width()-50;
	var iOngletWidth = oOngletAssocie.width();
	
		if (iInputWidth < 70) {
			iInputWidth = 70
			iOngletWidth= 107
		}
	
	oOngletAssocie.css({textAlign:'left', width:iOngletWidth});
	f.find('.text').click(function(){$(this).val('')}).css('width',(iInputWidth)+'px');
	
	oOngletAssocie.append(f);	
	
	f.show().find('.text').focus();
}

/* flexigrid */

function loadFlexigrid(sQuery, bInit) {	
	if (bInit) 
		$("#flex1").flexigrid({
			url: '/Demandes/async',
			dataType: 'json',
			resizable:false,
			colModel: [
					{
						display: 'Type bien',
						name: 't_bien',
						width: 50,
						sortable: true,
						align: 'left'
					},
					
					{
						display: 'Date',
						name: 't_projet',
						width: 50,
						sortable: true,
						align: 'left'
					},					
										
					{
						display: 'Ech.',
						name: 'echeance',
						width: 20,
						sortable: true,
						align: 'right'
					},
															
					{
						display: 'CP',
						name: 'ville_code_postal',
						width: 100,
						sortable: true,
						align: 'right'
					},
					
					{
						display: 'Budget max',
						name: 'budget_max',
						width: 50,
						sortable: true,
						align: 'right'
					},
					
					{
						display: 'Surface',
						name: 'surface',
						width: 40,
						sortable: true,
						align: 'right'
					},
					
					{
						display: 'Pieces',
						name: 'nb_pieces',
						width: 35,
						sortable: true,
						align: 'left'
					},
					
					{
						display: 'Chambres',
						name: 'nb_chambres',
						width: 45,
						sortable: true,
						align: 'left'
					},
					
					{
						display: 'Sdb',
						name: 'nb_sdb',
						width: 20,
						sortable: true,
						align: 'left'
					},
					
					{
						display: 'Douches',
						name: 'nb_douche',
						width: 35,
						sortable: true,
						align: 'left'
					},
					
					{
						display: 'WC',
						name: 'nb_wc',
						width: 20,
						sortable: true,
						align: 'left'
					},
					
					{
						display: 'Cuisine',
						name: 't_cuisine',
						width: 40,
						sortable: true,
						align: 'left'
					},
					
					{
						display: 'Etage',
						name: 't_etage',
						width: 30,
						sortable: true,
						align: 'left'
					},
					
					{
						display: 'Terrasse',
						name: 'surface_terrasse',
						width: 40,
						sortable: true,
						align: 'left'
					}, 
					
					{
						display: 'GoogleMap',
						name: 'google_circles',
						width: 5,
						sortable: false,
						align: 'left',
						hide:true						
					}		
			
			],
			searchitems: false,
			sortname: "date",
			sortorder: "desc",
			autoload: false,
			query: '',
			usepager: true,
			title: '',
			useRp: true,
			rp: 15,
			showTableToggleBtn: true,
			width: ($.browser.msie ? 618 : 620),
			height: 300			
		});
	else {		
		$('#flex1').flexOptions({
			//reset du choix de la page du flexigrid
			page: 1,
			qtype: '',
			query: sQuery,
			autoload: true
		});
			
		$("#flex1").flexReload();
	}
}



function flexigrid_callbackSuccess() {
	if ($('#googlemap').find('#map_pro').is('div'))
		googlemap_pro_getCircles()
}

function flexigrid_callbackSelectLine(jqTr) {
	if (jqTr.parents('table').is('#flex1')) {
		var idProjet = jqTr.find('.idProjet').text();
		var idUser = jqTr.find('.idUser').text();		
		
		googlemap_reset_map();
		popup_FicheDemandeur(idProjet, idUser);
	}
	else if (jqTr.parents('.bloc').is('.messagerie')) {		
		messagerie_lecture_msg(jqTr);
	}
	
	jqTr.removeClass('trSelected');	
}

function monProjet_miseajour_cp() {
	$('#googlemap .googlecp .info').each(function() {
		var name 	= $(this).attr('name');
		var value 	= $('#form_projet [@name='+name+']').val();
		
		$(this).text(value);				
	})
}

function thickbox_callbackSuccess() {
	$('#TB_ajaxWindowTitle').text('Projet d\'achat de ' + $('.TB_Window_title').text());
	champsImportants_reload('#TB_window');	
	$('#TB_window .lBudget').each(function(){
		reglette_refreshUnits($(this));
	});
	googlemap_reload(true,false);	
	messagerie_init('#TB_window .messagerie');	
	
	$('#TB_ajaxContent').each(function(){
		layout_bloc($(this));
	})	
}

function thickbox_callbackClose() {	
	if (	$('.body_bg').is('professionnels') )
		googlemap_pro_getCircles();
}

function popup_alert(sMsg, sFocus) {
	if (!document.getElementById('hiddenModalContent'))
		$('body').append('<div class="hide" id="hiddenModalContent"><p class="alertMsg"></p><p class="alertBtOK"><input type="submit" onclick="tb_remove()" value="  Ok  " id="Login"/></p></div>');
	
	if (sFocus != '') {		
		$(sFocus).focus();
	}	
		
	$('#hiddenModalContent .alertMsg').html(sMsg);	
	tb_show('Alerte','#TB_inline?height=150&width=300&inlineId=hiddenModalContent&modal=true','');
}

function popup_FicheDemandeur(p,u) {	
	tb_show('', '/FicheDemandeur/async?width=990&height=600&projet=' + p + '&user=' + u, '');
}

function popup_stickerTV() {
	if (!document.getElementById('hiddenModalContent'))
		$('body').append('<div class="hide" id="hiddenModalContent"><p class="alertMsg"></p><p class="alertBtOK"><input type="submit" onclick="tb_remove()" value="Fermer" id="Login"/></p></div>');
	
	$('#hiddenModalContent .alertMsg').html(
		'<object width="480" height="381"><param name="movie" value="http://www.dailymotion.com/swf/k5Rq7JB2q4HLjuRHbS&related=1"></param><param name="allowFullScreen" value="true"></param><param name="allowScriptAccess" value="always"></param><embed src="http://www.dailymotion.com/swf/k5Rq7JB2q4HLjuRHbS&related=1" type="application/x-shockwave-flash" width="480" height="381" allowFullScreen="true" allowScriptAccess="always"></embed></object>'
	);	
	tb_show('Alerte','#TB_inline?height=420&width=480&inlineId=hiddenModalContent&modal=true','');
	$('#TB_window').css({top:'170px',left:'20px'});
	$('#TB_window .alertBtOK').attr('style','margin-top:0;margin-bottom:0;padding:0');
}

function validateEmail() {
	var sRet = '';
	
	var reg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]{2,}[.][a-zA-Z0-9]{2,4}$/;
    var reg2 = /[.@]{2,}/;
	
	$('#email').find('input').each(function() {
		var email 		= $.trim($(this).val());
		
		if (email=='') {
			sRet = '<li>Le champ E-mail ne doit pas \352tre vide</li>';
		}
		else if ( ((reg.exec(email)==null) || (reg2.exec(email)!=null)) ) 
			sRet = '<li>Le champ E-mail doit \352tre au format : adresse@domaine.tld</li>';
	});
	
	return sRet;
}

function validatePasswords() {
	var sRet = '';
	
	$('#password').find('input').each(function() {
		var password = $.trim($(this).val());
		var c_password = $.trim($('#confirm_password input').val());		
		var required 	= $(this).attr('required') == 1;
		
		if (password=='' && required) 
			sRet = '<li>Le champ Mot de passe ne doit pas \352tre vide</li>';
		else if ( password != c_password ) 
			sRet = '<li>Les mots de passe sont diff\351rents</li>';	
	});
	
	return sRet;
}

function form_validate_email( email ) {
	var reg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]{2,}[.][a-zA-Z0-9]{2,4}$/;
    var reg2 = /[.@]{2,}/;    
    return !(reg.exec(email)==null || reg2.exec(email)!=null);
}

function form_validate_numbers( nb ) {
	var reg = /^\d+$/;
	return reg.exec(nb);
}

var globalSWFTarget;

function partenariat_load() {
	var r = Math.ceil(Math.random()*aBannieres['skycraper'].length);		
	var skycraper = aBannieres['skycraper'][r-1][0];
	
	if (skycraper.type!='swf') {
		$('#col_pub').html('<a href="'+skycraper.link+'"><img src="' + skycraper.src + '" width="120" height="600" /></a>');			
	} else {
		$('#col_pub').flash({
			swf: skycraper.src + '.swf',
			width: 120,
			height: 600
			//,params:{wmode:'transparent'}
		});
	}
	$('#col_pub').css('margin-left', $('.body_bg').is('.accueil') ? '60px' : '10px');
	
	r = Math.ceil(Math.random()*aBannieres['carre'].length); 
	
	var carre = aBannieres['carre'][r-1][0];
	
	//eviter d'avoir 2 bannieres de la meme source dans la page
	if (carre.from==skycraper.from) {
		if (r==aBannieres['carre'].length)
			r=0;			
		carre = aBannieres['carre'][r][0];
	}
	
	if (carre.type!='swf') {
		$('#pub_carre').html('<a href="'+carre.link+'"><img src="' + carre.src + '" width="300" height="250" /></a>');			
	} else {
		$('#pub_carre').flash({
			swf: carre.src + '.swf',
			width: 300,
			height: 250
		});
	}
}


function show_partenaire(){

	$('.Partenariat').click(function(){
		if ($.browser.msie){
			$(this).parent().find('.repaire').toggleClass("none");
		}else{
			$('~',this).slideToggle("slow");
		}
		
	});
}

