// Définition des constantes
var _NOTMODIFIED = 0;
var _DATAMODIFIED = 1;
var _NEW = 2;
var _NEWMODIFIED = 3;

//FR Fonctions commune à bailbail EN common function on bailbail

// FR gestion des messages
// EN messages management
// --------------------------------------------------------------------------------------------
// FR Gestion des messages applicatifs, d'erreur, de confirmation et de succès
// EN Management of the messages (applicative, errors, confirmation, success)
var MsgBox = {
	degrise_close : true, 
	// FR indique si la page doit être dégriser quand la MsgBoX est close 
	// (est à false quand la MsgBox est appellée quand la page est déjà grisée) (C'est pour éviter de dégriser une page qui ne devrait pas l'être.)
	// EN indicate if the page must be unGrey when the MsgBoX is close 
	// (is at false when the MsgBox is called when the page is still grey) (It's to avoid to disGrey a page which should'nt)
	num_error : 0,

	// FR construit le div de gestion des message
	// EN build the div of message management
	// FR contrainte : le div MsgBox doit exister dans la page
	// EN constraint : the div MsgBox must exist in the page
	build : function() {
		Debug.Log('MsgBox.build');
		$('MsgBox').className = 'MsgBox';
		$('MsgBox').style.display = 'none';
		div_barre = document.createElement("div");
		div_barre.className = 'div_barre_msgbox';
		img_close = document.createElement("img");
		img_close.className = 'MsgBoxClose';
		if (dossier_appli!='')
		{	var chem_img=dossier_appli;}
		else
		{	var chem_img='..';}
		chem_img+='/theme/' + theme + '/img/close_big.gif';
		img_close.src = chem_img;
		img_close.id = 'MsgBoxClose';
		div_barre.appendChild(img_close);
		div_ContMsgBox = document.createElement("div");
		div_ContMsgBox.id = 'ContMsgBox';
		$('MsgBox').appendChild(div_barre);
		$('MsgBox').appendChild(div_ContMsgBox);
		var myDrag = new Drag($('MsgBox'));
	},

	place_msgbox : function() {
		// Debug.Log('MsgBox.place_msgbox '+get_pageYOffset());
		if ($('header_ban_menu'))
		{	var a_ajouter=300;}
		else
		{	var a_ajouter=190;}
		$('MsgBox').style.top = get_pageYOffset() + a_ajouter + 'px';
	},

	// FR affiche une erreur
	// EN display an error
	error : function(num_error, msg_error) {
		Debug.Log('MsgBox.error');
		MsgBox.num_error = num_error;
		msg_error = MsgBox.num_error + ' : ' + msg_error;
		MsgBox.msg(msg_error, 'error', '');
	},

	// FR affiche le message passe en parametre
	// FR type : erreur, applicatif, confirm, succès
	// FR (si type='confirm', execute action si acceptation, action_refus si refus)
	// EN display the message give in parameter
	// EN type : error, applicative, confirm, success
	// EN (if type='confirm', execute action if acceptation, action_refus if refused)

	msg : function(msg, type, action, action_refus) {
		Debug.Log('MsgBox.msg');
		 
		if ($('grise_tout').className == 'grise_tout' && MsgBox.num_error != -99) 
		// FR -99 est le code erreur qui permet d'avoir degrise_close à true dans tous les cas
		// EN -99 is the error code which permit to have degrise_close at true in all case
		{
			MsgBox.degrise_close = false;
		} else {
			MsgBox.degrise_close = true;
			$('grise_tout').className = 'grise_tout';
			$('grise_tout').style.height=document.body.scrollHeight+'px';	//maj hauteur
		}
		 
		MsgBox.num_error = 0;
		// FR action et action_refus sont des paramètres facultatifs
		// EN action and acrion_refus are facultative parameters
		if (!action) {
			action = "";
		}
		if (!action_refus) {
			action_refus = "";
		}
		res = false;

		if (!document.getElementById('ContMsgBox')) {
			MsgBox.build();
		}

		$('ContMsgBox').innerHTML = '';

		if (type!='iframe')
		{
			divMsgBoxTxt = document.createElement("div");
			divMsgBoxTxt.id = 'MsgBoxTxt';
			if (type == 'error') {
				var class_txt = 'MsgBoxTxt_error';
			} else {
				var class_txt = 'MsgBoxTxt';
			}
			divMsgBoxTxt.className = class_txt;
			divMsgBoxTxt.innerHTML = msg;
			$('MsgBox').className = 'MsgBox';
		}
		else
		{
			$('MsgBox').className = 'MsgBox_iframe';
		}
		
		switch (type) {
			case 'confirm' :
				div_ImgAfter = document.createElement("div");
				div_ImgAfter.id = 'div_ImgAfter';

				img_ok = document.createElement("img");
				img_ok.className = 'MsgBoxBtn';
				if (dossier_appli!='')
				{	var chem_img=dossier_appli;}
				else
				{	var chem_img='..';}
				chem_img += '/theme/' + theme + '/img/symbol_OK.gif';
				img_ok.src = chem_img;
				img_ok.id = 'MsgBoxOK';

				img_cancel = document.createElement("img");
				img_cancel.className = 'MsgBoxBtn';
				if (dossier_appli!='')
				{	var chem_img=dossier_appli;}
				else
				{	var chem_img='..';}
				chem_img += '/theme/' + theme + '/img/symbol_CANCEL.gif';
				img_cancel.src = chem_img;
				img_cancel.id = 'MsgBoxRST'

				div_ImgAfter.appendChild(img_ok);
				div_ImgAfter.appendChild(img_cancel);

				$('ContMsgBox').appendChild(divMsgBoxTxt);
				$('ContMsgBox').appendChild(div_ImgAfter);

				$('MsgBoxRST').onclick = new Function("$('MsgBoxTxt').innerHTML='';$('MsgBox').style.display='none';$('grise_tout').className='display_none';" + action_refus);
				$('MsgBoxOK').onclick = new Function("$('MsgBoxTxt').innerHTML='';$('MsgBox').style.display='none';$('grise_tout').className='display_none';" + action);
				break;
			case 'error' :
				img_error = document.createElement("img");
				img_error.className = 'MsgBoxBtn';
				if (dossier_appli!='')
				{	var chem_img=dossier_appli;}
				else
				{	var chem_img='..';}
				chem_img += '/theme/' + theme + '/img/error.png';
				img_error.src = chem_img;

				$('ContMsgBox').appendChild(img_error);
				$('ContMsgBox').appendChild(divMsgBoxTxt);
				break;
			case 'success' :
				img_error = document.createElement("img");
				img_error.className = 'MsgBoxBtn';
				if (dossier_appli!='')
				{	var chem_img=dossier_appli;}
				else
				{	var chem_img='..';}
				chem_img += '/theme/' + theme + '/img/symbol_check.gif';
				img_error.src = chem_img;

				$('ContMsgBox').appendChild(img_error);
				$('ContMsgBox').appendChild(divMsgBoxTxt);
				break;
			case 'iframe' : //l'url est dans msg
				//FR on monte tout en haut
				//EN we scroll on the top of the page
				window.scrollTo(0, 0);
			
				var iframe=document.createElement("iframe");
				iframe.id='iframe_msgbox';
				iframe.src=msg;
				iframe.style.height='478px'; //% doesn't work
				iframe.style.width='100%';
				iframe.style.border='0px inset';
				$('ContMsgBox').appendChild(iframe);
				break;
			default : // (applicatif)
				$('ContMsgBox').appendChild(divMsgBoxTxt);
				break;
		}

		$('MsgBoxClose').onclick = new Function("MsgBox.hide();");
		// clic msg => le msg disparaît
		if ($('MsgBoxTxt')) {
			$('MsgBoxTxt').onclick = new Function("MsgBox.hide();");
		}

		MsgBox.place_msgbox();
		window.onscroll = function() {
			MsgBox.place_msgbox();
		}

		$('MsgBox').style.display = 'block';
		if (type!='iframe')
		{	return res;}
	},

	hide : function() {
		Debug.Log('MsgBox.hide');
		$('ContMsgBox').innerHTML = '';
		$('MsgBox').style.display = 'none';
		if (MsgBox.degrise_close) {
			$('grise_tout').className = 'display_none';
		}
		window.onscroll = function() {
		}
	}
};

var connexion = {
	connexion : function()
	{
		if (dossier_appli)
		{	var url=dossier_appli;}
		else
		{	var url='..';}
		Aj = new Request({
			url : url+'/utilisateur/request_utilisateur.php',
			method : 'post',
			async : false, // synchrone
			data : {
					'mode' : 'connexion',
					'login' : $('login_connexion').value,
					'mpasse' : $('mpass_connexion').value
					},
		
			onRequest : function() {
				ajaxloader.show();
			},
		
			onComplete : function(response) {
				ajaxloader.hide();
			
				var tab = JSON.decode(response);
				if (tab['code_ret'] > 0 || tab['code_ret']==-2) {// succès
					if (tab['code_ret']==-2)
					{	//FR c'est un compte où l'email n'est pas validé, l'utilisateur est averti mais la connexion n'est pas refusé
						//EN it is an unvalidate email account, user get a message but the connection is allowed
						alert(tab['msg']);
					}
					
					//FR on redirige vers la page d'accueil - EN redirect to home page
					if (dossier_appli)
					{	var url=dossier_appli;}
					else
					{	var url='..';}
					
					if (window.location.href.indexOf('etail_bien_annonce.php')>0 || window.location.href.indexOf('onnecte_iframe.php')>0)
					{	
						window.location.href=window.location.href;
						window.parent.location.href=window.parent.location.href;
					}
					else
					{	window.location.href=url+'/utilisateur/accueil_menu_compte.php';}
				} else {// erreur EN error
					$('mpass_connexion').value='';
					MsgBox.msg(tab['msg'], 'error');
				}
			},
		
			onFailure : function() {
				alert('erreur ajax');
			}
		
		}).send();
		
	},
	
	deconnexion : function()
	{
		if (dossier_appli)
		{	var url=dossier_appli;}
		else
		{	var url='..';}
		Aj = new Request({
			url : url+'/utilisateur/request_utilisateur.php',
			method : 'post',
			async : false, // synchrone
			data : {'mode' : 'deconnexion'},
		
			onRequest : function() {
				ajaxloader.show();
			},
		
			onComplete : function(response) {
				ajaxloader.hide();
			
				var tab = JSON.decode(response);
				if (tab['code_ret'] > 0) {// succès
					//FR on redirige vers la page d'accueil - EN redirect to home page
					if (dossier_appli)
					{	var url=dossier_appli;}
					else
					{	var url='..';}
					window.location.href=url+'/index.php?url=/bailbail/Accueil_bailbail.php';
				} else {// erreur EN error
					MsgBox.msg(tab['msg'], 'error');
				}
			},
		
			onFailure : function() {
				alert('erreur ajax');
			}
		
		}).send();		
	}
};

var ajaxloader = {
	img : '../theme/' + theme + '/img/ajax-loader.gif',
	chgmt_multiple : false, // FR boolean, indique si il y a un chargement multiple (plusieurs req ajax pour un chargement)
							// EN boolean, indicate if there is a multiple load (several ajax requests for a loading)

	show : function() {
		
		if (!ajaxloader.chgmt_multiple) {
			if ($('div_ajaxloader')) {
				$('div_ajaxloader').style.display = 'inline';
				$('grise_tout').className = 'grise_tout';
			} else {
				var div_al = document.createElement("div");
				div_al.id = 'div_ajaxloader';
				div_al.className = 'ajaxloader';

				var img_al = document.createElement("img");
				img_al.src = ajaxloader.img;
				img_al.id = 'img_ajaxloader';

				div_al.appendChild(img_al);
				$('grise_tout').className = 'grise_tout';
				$('body').appendChild(div_al);
			}
		}
	},

	hide : function() {
		if ($('div_ajaxloader') && !ajaxloader.chgmt_multiple) {
			$('div_ajaxloader').style.display = 'none';
			$('grise_tout').className = 'display_none';
		}
	},

	start_chargement : function() { 
		// FR commence un chargement qui peut comporter plusieurs requêtes ajax
		// EN begin a loading which can contains several ajax request
		ajaxloader.show();
		ajaxloader.chgmt_multiple = true;
	},

	stop_chargement : function() { 
		// FR fin de chargement retour option par défaut
		// EN end of charging, return default option
		ajaxloader.chgmt_multiple = false;
		ajaxloader.hide();
	}
}

var processingloader = {
	img : '../theme/' + theme + '/img/processing.gif',

	show : function() {
		if ($('div_processingloader')) {
			$('div_processingloader').style.display = 'inline';
		} else {
			var div_al = document.createElement("div");
			div_al.id = 'div_processingloader';
			div_al.className = 'ajaxloader';

			var img_al = document.createElement("img");
			img_al.src = processingloader.img;
			img_al.id = 'img_processingloader';

			div_al.appendChild(img_al);
			$('body').appendChild(div_al);
		}
	},

	hide : function() {
		if ($('div_processingloader')) {
			$('div_processingloader').style.display = 'none';
		}
	}
}

var Debug = {
	// debugage
	ActiveDebug : activ_debug, // 1 => FR affichage des infos de debug EN display debug informations

	Log : function(as_message, type_aff) {
		if (!type_aff) {
			var type_aff = 1;
		}
		if (Debug.ActiveDebug == 1) {
			$('debug').ondblclick = new Function("$('debug').innerHTML='';");
			switch (type_aff) {
				case 1 :
					$('debug').innerHTML = $('debug').innerHTML + '<br>'
							+ as_message;
					break;
				case 2 :
					$('debug').innerHTML = $('debug').innerHTML + '<br><b>'
							+ as_message + '</b>';
					break;
				case 3 :
					$('debug').innerHTML = $('debug').innerHTML + '<br><b><i>'
							+ as_message + '</i></b>';
					break;
			}
		}
	}
};

function delete_all_child(id) 
// FR n'est plus utilisés pour le moment
// EN is not use for the moment
{
	var enf = '';
	while (enf = $(id).firstChild) {
		$(id).removeChild(enf);
	}
}

function select_option(id, value) {
	for (var i = 0; i < $(id).options.length; i++) {
		if ($(id).options[i].value == value) {
			$(id).options[i].selected = true;
			i = $(id).options.length;
		}
	}
}

function clic_menu(url) { // FR clic sur un lien du menu
	// EN clic on a link from the menu
	// FR si on est sur la page bien_annonce, on vérifie qu'il n'y a pas de données non enregistrés
	// EN if we are on the page asset_ad, we erify that there are no data which aren't saved
	var confirm_chargement = '';
	if (window['bien'] != null && bien.status) {
		confirm_chargement = bien.quitte_page();
		var action_refus = '';
	} else if ($('onglet_annonce') && $('div_annonce') && ba)// on est dans bien_annonce
	{
		var tab_form_non_enr = ba.tab_form_non_enr();
		if (tab_form_non_enr.length > 0) {
			confirm_chargement = infos_non_enr + tab_form_non_enr.join(', ') + quitter_ss_enr;
		}
		var action_refus = 'ba.msg_quitte_ss_enr=true;';
	}

	if (confirm_chargement != '') {
		MsgBox.msg(confirm_chargement, 'confirm', 'redirigee("' + url + '")',
				action_refus);
	} else {
		redirigee(url);
	}
	
	return false;
}

function redirigee(url) { // FR est utilisé quand le fait de quitter sans enregistrer est confirmé
	// EN is used when the fact of quit without save is confirmed
	if ($('onglet_annonce') && $('div_annonce') && ba)// on est dans bien_annonce
	{
		ba.msg_quitte_ss_enr = false;
	} // cas bien_annonce
	window.location.href = url;
}

function a_iframe_msgbox()
{	//FR indique si la page a une iframe d'ouverte au niveau du msgbox
	//EN indicate if the page has opened iframe in the msgbox
	return ($('iframe_msgbox') && $('iframe_msgbox').src!='')
}

function ferme_msgbox(msg_succes)
{	//FR ferme la msgbox, peut être utiliser dans les iframe "ipopup" pour se fermer
	//EN close the msgbox, can be used for closing "ipopup" iframee in the ipopup
	try {	
			MsgBox.hide();
			if (msg_succes!='')
			{	//FR affiche un msg de succès
				//EN view a success message
				MsgBox.msg(msg_succes, 'success');
			}
		} catch (e) {}
}

function set_main_content(url) {
	url_red=url;
	/*
	//avant l'utilisation de l'url_rewritting
	// si /index.php est contenu dans l'url actuel, on est dans dossier racine
	
	var url_actu = window.location.href;
	var url_red = '';
	if (url_actu.indexOf('index.php') == -1) {
		url_red += '../';
	}
	
	if (url!='/bailbail/Accueil_bailbail.php')
	{	url_red += 'index.php?url=' + encodeURI(url);}
	*/
	if (url_red=='')
	{	url_red='index.php';}
	
	if (window.onbeforeunload)
	{
		if (window.bien && bien.status)
		{	//FR form bien non enregistré - EN property form not saved
			bien.ok_quitte_ss_enr("window.location.href = '"+url_red+"';");
		}
		else if (window.ba && ba.annonce)
		{	//FR un form annonce non enregistré - EN an ad form is not saved
			ba.ok_quitte_ss_enr("window.location.href = '"+url_red+"';");
		}
		else
		{	window.location.href = url_red;}
	}
	else
	{	window.location.href = url_red;}
	return false;
}

function is_numeric(num) {
	var exp = new RegExp("^[0-9-.]*$", "g");
	return exp.test(num);
}

function ok_mail(a)
{
	var valide = false;
	
	for(var j=1;j<(a.length);j++)
	{
		if(a.charAt(j)=='@'){
			if(j<(a.length-4)){
				for(var k=j;k<(a.length-2);k++){
					if(a.charAt(k)=='.') valide=true;
				}
			}
		}
	}
	return valide;
}

function reload_page()
{	
	window.location.href=window.location.href;
}

function get_pageYOffset()
{
  var scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
  }
  return scrOfY;
}

function cache_part_histo_rech()
{
	if ($('div_histo_rech'))
	{	$('div_histo_rech').style.display='none';}
}

function to_url(str)
{
	//FR Transforme un texte pour qu'il soit utilisable en url rewritting
	//EN Change a text so that it is useable in url rewritting
	var norm = new Array('_', ' ', '.', '?', '<', '>', ',', ';', '!', '&', '%', '$', '#', '@', '/', '\\', '*', '+', '=', '(', ')', '"', "'");
	var spec = new Array('-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-' , '-', '-', '-', '-', '-', '-', '-');
	for (var i = 0; i < spec.length; i++)
	{	str = replaceAll(str, norm[i], spec[i]);}
	return NoAccent(str);
}

function NoAccent(str) {
	//FR Remplace les caractères accentués
	//EN Replace accented characters
	var norm = new Array('À','Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï', 'Ð','Ñ','Ò','Ó','Ô','Õ','Ö','Ø','Ù','Ú','Û','Ü','Ý','Þ','ß', 'à','á','â','ã','ä','å','æ','ç','è','é','ê','ë','ì','í','î','ï','ð','ñ', 'ò','ó','ô','õ','ö','ø','ù','ú','û','ü','ý','ý','þ','ÿ');
	var spec = new Array('A','A','A','A','A','A','A','C','E','E','E','E','I','I','I','I', 'D','N','O','O','O','0','O','O','U','U','U','U','Y','b','s', 'a','a','a','a','a','a','a','c','e','e','e','e','i','i','i','i','d','n', 'o','o','o','o','o','o','u','u','u','u','y','y','b','y');
	for (var i = 0; i < spec.length; i++)
	{	str = replaceAll(str, norm[i], spec[i]);}
	return str;
}

function replaceAll(str, search, repl) {
	//FR Remplace toutes les occurences d'une chaine
	//EN Replaces all occurrences of a string
	while (str.indexOf(search) != -1)
	{	str = str.replace(search, repl);}
	return str;
}

function set_var_global(nom_var, val)
{
	window[nom_var] = val;
}






var partenaires = {
	list_type_bien : new Array(),	
	ind_aff : 0,				//indice du partenaire actuellement affiché
	ind_a_aff : 1,				//indice du partenaire à afficher, 1 par défaut (0+1)
	duree_transition : 3000, 	//en milliseconde
	duree_affichage : 6000,  //en milliseconde, durée de l'affichage avant le changement
	tab_el : new Array(),
	nb_partenaires : 0,
	obj_settimeout : null,
	
	constructor : function() {
		//FR on cherche à savoir le nombre de partenaire
		Debug.Log('partenaires.constructor()');
		partenaires.tab_el = $('partenaires').getChildren();
		partenaires.nb_partenaires=partenaires.tab_el.length;
		
		$('part_prec').onclick = new Function("Debug.Log('part_prec fct');window.clearTimeout(partenaires.obj_settimeout);partenaires.ind_a_aff--;if (partenaires.ind_a_aff<1){ partenaires.ind_a_aff=partenaires.nb_partenaires; }partenaires.changer();");//on ajoute partenaires.nb_partenaires pour éviter d'avoir un nombre négatif, comme c'est le modulo qui est utilisé dans la fonction changer, ça fonctionne
		$('part_suiv').onclick = new Function("Debug.Log('part_suiv fct');window.clearTimeout(partenaires.obj_settimeout);partenaires.ind_a_aff++;partenaires.changer();"); //le modulo est utilisé dans changer donc ça fonctionne toujours
		partenaires.obj_settimeout=setTimeout("partenaires.changer()",partenaires.duree_affichage);
	},

	changer : function(){
		//Debug.Log('partenaires.changer('+partenaires.ind_aff+'->'+partenaires.ind_a_aff+')'); //est appellé trop souvent pout être mis dans le debug

		partenaires.ind_a_aff=Math.abs(partenaires.ind_a_aff % partenaires.nb_partenaires) ;

		//FR traitement des cas ou il y a clic sur suivant ou précédent avant le premier changer
		if (partenaires.ind_aff==0 && partenaires.ind_a_aff==2)
		{	partenaires.ind_a_aff=1;}
		else if (partenaires.ind_aff==0 && partenaires.ind_a_aff==0)
		{	partenaires.ind_a_aff=partenaires.nb_partenaires-1;}
		
		//on enlève l'ancien
		partenaires.enleve(partenaires.tab_el[partenaires.ind_aff]);
		//on met le nouveau
		partenaires.affiche(partenaires.tab_el[partenaires.ind_a_aff]);
		
		partenaires.ind_aff=partenaires.ind_a_aff;
		//FR on lance le prochain time out
		partenaires.obj_settimeout=setTimeout("partenaires.ind_a_aff++;partenaires.changer()",partenaires.duree_affichage);
	},
	
	enleve : function(el){
		//Debug.Log('partenaires.enleve()'); //est appellé trop souvent pout être mis dans le debug
		el.style.display='inline';	
		transFx = new Fx.Tween(el.id, {
			property: 'opacity',
			duration: Math.floor(partenaires.duree_transition/2), 
			transition: Fx.Transitions.Quart.easeInOut,
			link: 'chain'
		});
		transFx.start(1,0);
		el.style.display='none';
	},	

	affiche : function(el){
		//Debug.Log('partenaires.affiche()'); //est appellé trop souvent pout être mis dans le debug
		el.style.display='inline';	
		transFx = new Fx.Tween(el.id, {
			property: 'opacity',
			duration: Math.floor(partenaires.duree_transition/2), 
			transition: Fx.Transitions.Quart.easeInOut,
			link: 'chain'
		});
		transFx.start(0,1);  
		el.style.display='inline';
		$('img_'+el.id).style.display='block';
		$('img_'+el.id).style.opacity=1;
	}
}//fin partenaires
