const TABLE =
{
	nom:	" tbl_adresses ",
	
	adressesCategories:" tbl_adresses_categories ",
	categories:" tbl_categories ",
	suivis:	" tbl_adresses_suivis "
};
var G_action, G_id, G_find = "[ Nom - Prénom]";

function Fiche()
{
	this.Init=function()
	{
		G_id=0;
		G_action="insert";
		
		initScreen();
		_init_navigation(TABLE.nom, "");
		
		$('remarqueEditor').contentDocument.designMode='on';
		editorSet("remarqueEditor", "");
		
		setVal($('zCategories'), 'style', 'visibility:hidden');//.collapse=true;
		
		_listboxVider("fk_categories_liste");
		
		$("titre").reset();
		$("nom").reset();
		$("prenom").reset();
		$("nom2").reset();
		
		$("zNom2").hidden=true;
	
	 // modifyDatepicker($('ddn'));
	 
		_datepikerReset($('ddn'));
		$('age').reset();
		$('ddn2').value=0;
	
		$("btn_submit").label = "Ajouter";
		
		with($("type"))
		{
			value="";
			focus();
		}
	}

	this.ScaleInit=function(min, max)
	{
		setVal($('scaleNav'),
					"min", min,
					"max", max);		
	}
	
	this.ScaleImput=function()
	{
		var pos = $('zPositionFiche').value;
		
		$('scaleNav').value = pos;
	}
	
	this.ScaleNav=function()
	{
		var scale = $('scaleNav');
		
		if (scale.value>0)
		{
			var sql = "SELECT adr_id FROM" + TABLE.nom +
								"ORDER BY adr_nom, adr_prenom " +
								"LIMIT "+(scale.value-1)+", 1";
								
			var req = _exec_sql(sql);
			
			var id=0;
			if (req.executeStep())
			{
				var Row=_recupDatas(req);
				
				Record.FicheAffiche(Row['adr_id'], "ASC", 1);
			}
			
			req.reset();
		}
	}

	this.Delete=function(id)
	{
		if (Confirm('Suppression', "Voulez-vous vraiment supprimer cette fiche ?"))
		{
			var sql = "SELECT adr_img1, adr_img2, adr_img3 FROM" + TABLE.nom +
								"WHERE adr_id=?1"
			
			var req = _exec_sql(sql, id);
			
			req.executeStep();
			
			var Row=_recupDatas(req);

			req.reset();
			
			for (i=1; i<=3; i++)
			{
				let imgPath = path("AChrom", imgPathDir, Row['adr_img'+i]);
				
				fileDelete(imgPath);
			}

			var sql = "DELETE FROM" + TABLE.nom +
								"WHERE adr_id=?1";
			
			_exec_sql(sql, id);
			
	
			sql = "DELETE FROM" +TABLE.adressesCategories +
						"WHERE lis_fk_adresses=?1";
			
			_exec_sql(sql, id);
			

			sql = "DELETE FROM" + TABLE.suivis +
						"WHERE sui_fk_adresses=?1";
								
			_exec_sql(sql, id);
	
			
			this.Init();
		}
	}
	
	this.Encodage=function()
	{
		$('remarque').value=editorGet("remarqueEditor");
		
		var Inputs= submitForm();
		
		if (G_action=="insert" || G_action=="modif")
		{	
			var msg_erreur=	"";
			var focus=			"";
			var verif=			true;
			
			if (Inputs['nom']=="")
			{
				msg_erreur+=	"Veuillez remplir le Nom !\n";
				focus=				verif ? "nom" : focus;
				verif=				false;
			}
			
			if (!verif)
			{
				Alert("Problème d'encodage", msg_erreur);
				$(focus).focus();
			}
			else	
			{
				var lastId=G_id;
				
				if (G_action=="insert")
				{
					var sql = "INSERT INTO" + TABLE.nom +
										"(adr_dt_creation, adr_ts_modification, " +
										"adr_type, adr_titre, adr_nom, adr_nom2, adr_prenom, adr_ddn, adr_ddn_afficher, adr_remarque) " +
										"VALUES ('"+_now()+"', '"+_now()+"', " +
										"?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)";
					
					_exec_sql(sql, Inputs['type'], Inputs['titre'], Inputs['nom'], Inputs['nom2'], Inputs['prenom'], Inputs['ddn'], Inputs['ddn2'], Inputs['remarque']);
					
					lastId=SQL.lastInsertRowID;
				}
				else
				{
					var sql = "UPDATE" + TABLE.nom + "SET " +
										"adr_ts_modification='"+_now()+"', adr_revisions=adr_revisions+1, adr_type=?1, adr_titre=?2, adr_nom=?3, adr_nom2=?4, adr_prenom=?5, " +
										"adr_adresse1=?6, adr_cp1=?7, adr_ville1=?8, adr_fk_pays1=?9, adr_etat1=?10, " +
										"adr_adresse2=?11, adr_cp2=?12, adr_ville2=?13, adr_fk_pays2=?14, adr_etat2=?15, " +
										"adr_tel1a=?16, adr_tel1b=?17, adr_tel2a=?18, adr_tel2b=?19, " +
										"adr_gsm1a=?20, adr_gsm1b=?21, adr_gsm2a=?22, adr_gsm2b=?23, adr_faxa=?24, adr_faxb=?25, " +
										"adr_mail1=?26, adr_mail2=?27, adr_web=?28, " +
										"adr_chat1=?29, adr_chat2=?30, adr_voip1=?31, adr_voip2=?32, " +
										"adr_remarque=?33, adr_ddn=?34, adr_ddn_afficher=?35 " +
										"WHERE adr_id=?36";
					
					_exec_sql(sql, Inputs['type'], Inputs['titre'], Inputs['nom'], Inputs['nom2'], Inputs['prenom'],
										Inputs['rue1'], Inputs['cp1'], Inputs['ville1'], Inputs['pays1'], Inputs['etat1'],
										Inputs['rue2'], Inputs['cp2'], Inputs['ville2'], Inputs['pays2'], Inputs['etat2'],
										Inputs['tel1a'], Inputs['tel1b'], Inputs['tel2a'], Inputs['tel2b'],
										Inputs['gsm1a'], Inputs['gsm1b'], Inputs['gsm2a'], Inputs['gsm2b'], Inputs['faxa'], Inputs['faxb'],
										Inputs['mail1'], Inputs['mail2'], Inputs['web'],
										Inputs['chat1'], Inputs['chat2'], Inputs['voip1'], Inputs['voip2'],
										Inputs['remarque'], Inputs['ddn'], Inputs['ddn2'],
										G_id);
				}
				
				this.FicheAffiche(lastId, 'ASC', 1);
/*
	Revérifier cette partie car peut-être exécuté 2x
*/

				Record.ScaleImput();
			}
		}
		else
		if (G_action=="rechercher" || G_action=="rechercher2")
		{
			var order1="adr_nom";
			var order2="adr_prenom";
			var sqlFind=" ";
			if (G_action=="rechercher2")
			{
				order1=Inputs['order1'];
				order2=Inputs['order2'];
				
				if (Inputs['f_type']!=-1)
					sqlFind="AND adr_type='"+Inputs['f_type']+"' ";
			}
			
			var sql = "SELECT adr_id, adr_dt_creation, adr_ts_modification, adr_type, adr_titre, adr_nom, adr_prenom FROM" + TABLE.nom +
								"WHERE (adr_nom LIKE '%"+Inputs['zRecherche']+"%' OR adr_prenom LIKE '%"+Inputs['zRecherche']+"%') " +
								sqlFind +
								"ORDER BY "+order1+", "+order2;
			
			var req=_exec_sql(sql);
			
			var T=0;
			while(req.executeStep())
			{
				T++;		
			}
			
			if (T==0)
			{
				var liste2= $('liste2');
				removeElements(liste2);
	
				$('Tlignes').value=0;
			}
			else
			if (T==1)
			{
				req=_exec_sql(sql);
				
				req.executeStep();
				
				var Row=_recupDatas(req);
		
				this.FicheAffiche(Row['adr_id'], 'ASC', 1);
/*
	Revérifier cette partie car peut-être exécuté 2x
*/
				this.ScaleImput();
			}
			else
			{
				var liste2= $('liste2');
				removeElements(liste2);
		
				$('deck').selectedIndex=	1;
				
				req=_exec_sql(sql);
				
				while(req.executeStep())
				{
					let Row=_recupDatas(req);
					
					tree_remplir(liste2, "", Row['adr_id'], Row['adr_type'], Row['adr_titre'], Row['adr_nom'], Row['adr_prenom'], Row['adr_dt_creation'], Row['adr_ts_modification']);
				}
				
				$('Tlignes').value=T;
			}
			
			req.reset();
		}
	}
	
	this.SuivisListe=function(id)
	{
		var sql = "SELECT sui_id, sui_date, sui_titre FROM" + TABLE.suivis +
							"WHERE sui_fk_adresses=?1 " +
							"ORDER BY sui_date DESC";
		
		var req=_exec_sql(sql, id);
		
		var liste = $('liste_suivis2');
		
		removeElements(liste);
		var c=0;
		while(req.executeStep())
		{
			c++;
			
			let Row=_recupDatas(req);
			
			tree_remplir(liste, "", Row['sui_id'], _date_francais(Row['sui_date']), Row['sui_titre']);
		}

		req.reset();
		
		$('TlignesSuivis').value=c;
	}
	
	this.SuivisAdd=function()
	{
		var params =
		{
			inn:
			{
				id:			G_id,
				action:	'insert',
				liste: 	0
			},
			
			out:null
		};

		popupDialog('dlg_suivis.xul', 1, 1, 1, params);
		
		if (params.out)
			this.SuivisListe(G_id);
	}
	
	this.SuivisModif=function()
	{
		var liste = TreeValue($('liste_suivis'));
		
		if (liste>0)
		{
			var params =
			{
				inn:
				{
					id:			G_id,
					action:	'modif',
					liste: 	liste
				},
				
				out:null
			};
		
			popupDialog('dlg_suivis.xul', 1, 1, 1, params);
			
			if (params.out)
				this.SuivisListe(G_id);
		}
		else
			this.SuivisAdd();
	}
	
	this.SuivisDelete=function()
	{
		var liste = TreeValue($('liste_suivis'));
		
		if (liste>0 && Confirm("Effacement...", "Voulez-vous vraiment effacer le suivi ?"))
		{
			var sql = "DELETE FROM" + TABLE.suivis +
								"WHERE sui_id="+liste;
								
			_exec_sql(sql);
			
			this.SuivisListe(G_id);
		}
	}
	
	this.ImageAdd=function(img)
	{
		var filtres=["Images", "All"];
		var file = filePicker("modeOpen", "", filtres);
		
		if (file)
		{
			var image = _trouve_valeur(TABLE.nom, G_id, "adr_id", "adr_img"+img);
			
			var imgPath = path("AChrom", imgPathDir, image);
			fileDelete(imgPath);
			
			
			imgPath = path("AChrom", imgPathDir);
			if (fileCopy(file.path, imgPath, file.leafName))
			{
				setVal($('img'+img), 'src', imgDir+file.leafName);
				
				var sql = "UPDATE" + TABLE.nom +"SET " +
									"adr_img"+img+"=?1 " +
									"WHERE adr_id=?2";
						
				_exec_sql(sql, file.leafName, G_id);
			}
		}
	}
		
	this.ImageDelete=function(img)
	{
		var image = _trouve_valeur(TABLE.nom, G_id, "adr_id", "adr_img"+img);
		
		setVal($('img'+img), 'src', "");
		
		var imgPath = path("AChrom", imgPathDir, image);
		fileDelete(imgPath);
			
		var sql = "UPDATE" + TABLE.nom +"SET " +
							"adr_img"+img+"='' " +
							"WHERE adr_id=?1";
				
		_exec_sql(sql, G_id);
	}
	
	this.ImageInfos=function(img)
	{
		//var file = $('img_file'+img).value;
		//Alert("Infos", file.leafName+"/"+_format_be(file.fileSize/1024, 2));
	}
	
	this.ImageSave=function(img)
	{
		//var filtres=["Images", "All"];
		//
		//var file = filePicker("modeSave", "", filtres);
	}
	
	this.ImageZoom=function(img)
	{
		
	}
	
	this.FicheAffiche=function(l_id, nav, reload)
	{
		var positions=_fiche_position(TABLE.nom, "adr_id", "adr_nom " + nav + ", adr_prenom", l_id, reload);
		
		var position=	positions[0];
		var total=		positions[1];
		var id=				positions[2];
		
		with(this)
		{
			SuivisListe(id);
			ScaleInit(1, total);
		}
		
		if (nav=="DESC")
			position=total-position+1;
		
		var sql="SELECT * FROM " + TABLE.nom +
						"WHERE adr_id= " + id;
		
		var req=_exec_sql(sql);
		
		req.executeStep();
		
		var Row=_recupDatas(req);
	
		req.reset();
	
		var d_creation=			_date_dt_fr(Row['adr_dt_creation'], "/", " à ");
	
		var date=	Row['adr_dt_creation'].split(" ");
		date=			date[0].split("-");
		var j_creation=		_jour_semaine(date[2], date[1], date[0]);
		
	
		var d_modification=	_date_dt_fr(Row['adr_ts_modification'], "/", " à ");
		
		var date=	Row['adr_ts_modification'].split(" ");
		date=			date[0].split("-");
		var j_modification=		_jour_semaine(date[2], date[1], date[0]);
		
		if (position<=1)
		{
			setVal($('cmd_desc'), 'disabled', true);
			$('tlb_desc').image='img/nav_g2.png';
		}
		else
		{
			setVal($('cmd_desc'), 'disabled', false);
			$('tlb_desc').image='img/nav_g.png';
		}
		
		if (position>=total)
		{
			setVal($('cmd_asc'), 'disabled', true);
			$('tlb_asc').image='img/nav_d2.png';
		}
		else
		{
			setVal($('cmd_asc'), 'disabled', false);
			$('tlb_asc').image='img/nav_d.png';
		}
	
		if (verifDelete(id))
			setVal($('cmd_delete_fiche'), 'disabled', false);
		else
			setVal($('cmd_delete_fiche'), 'disabled', true);
		
		setVal($('zCategories'), 'style', 'visibility:visible');
		
		G_id=	id;
		G_action=							'modif';
		$('deck').selectedIndex=0;
		$('zRecherche').value='';
	
		$('zPositionFiche').value=			position;
		$('lbl_total').value=			total;
		
		document.title=						Row['adr_nom'] + " " + Row['adr_prenom'];
		setVal($('onglets'), 'hidden', false);
			
		categoriesListe();
		$('type').value=				Row['adr_type'];
		typeModif();
		$('titre').value=				Row['adr_titre'];
		$('nom').value=					Row['adr_nom'];	
		$('prenom').value=			Row['adr_prenom'];
		$('nom2').value=				Row['adr_nom2'];
		
		if (!Row['adr_ddn'])
		{
			_datepikerReset($('ddn'));
			$('age').reset();
		}
		else
		{
			$('ddn').value= Row['adr_ddn'];
			
			var age = _calculAge(Row['adr_ddn']);
			
			$('age').value=  _calculAge(Row['adr_ddn']) + _pluriel(age, " an", " ans");
		}
		
		editorSet("remarqueEditor", Row['adr_remarque']);
			
		$('ddn2').value= 				Row['adr_ddn_afficher'];
		$('pays1').value=				Row['adr_fk_pays1'];
		$('rue1').value=				Row['adr_adresse1'];
		$('cp1').value=					Row['adr_cp1'];
		$('ville1').value=			Row['adr_ville1'];
		$('etat1').value=				Row['adr_etat1'];
		
		$('pays2').value=				Row['adr_fk_pays2'];
		$('rue2').value=				Row['adr_adresse2'];
		$('cp2').value=					Row['adr_cp2'];
		$('ville2').value=			Row['adr_ville2'];
		$('etat2').value=				Row['adr_etat2'];
		
		$('tel1a').value=					Row['adr_tel1a'];
		$('tel1b').value=					Row['adr_tel1b'];
		$('tel2a').value=					Row['adr_tel2a'];
		$('tel2b').value=					Row['adr_tel2b'];
		$('gsm1a').value=					Row['adr_gsm1a'];
		$('gsm1b').value=					Row['adr_gsm1b'];
		$('gsm2a').value=					Row['adr_gsm2a'];
		$('gsm2b').value=					Row['adr_gsm2b'];
		$('faxa').value=					Row['adr_faxa'];
		$('faxb').value=					Row['adr_faxb'];
		
		$('mail1').value=					Row['adr_mail1'];
		$('mail2').value=					Row['adr_mail2'];
		$('web').value=						Row['adr_web'];
		$('chat1').value=					Row['adr_chat1'];
		$('chat2').value=					Row['adr_chat2'];
		$('voip1').value=					Row['adr_voip1'];
		$('voip2').value=					Row['adr_voip2'];
		
		setVal($('img1'), 'src',  imgDir+Row['adr_img1']);
		setVal($('img2'), 'src', 	imgDir+Row['adr_img2']);
		setVal($('img3'), 'src',  imgDir+Row['adr_img3']);
	
		$('inf_creation').value=			d_creation+" ("+j_creation+")";
		$('inf_modification').value=	d_modification+" ("+j_modification+")";
		$('inf_revisions').value=			Row['adr_revisions'];
	
		with($('btn_submit'))
		{
			label=				'Modifier';
			disabled=false;
		}
		
		$('zRecherche').focus();
	}
}

var Record= new Fiche();

function Quitter()
{
	if (testQuit())
	{
//		backup();
		
		return true;
	}
	
	return false;
}

function backup()
{
	var newName= "datas-"+date("Y-m-d_H\\hi-s");
	
	var bckPath = path("AChrom", datasPathDir, "bck");
	
	fileCopy(dbPath, bckPath, newName+".sqlite");
}

function navMouse(e)
{
	if (e.detail<0)
		eval($('cmd_desc').getAttribute('oncommand'))
	else
		eval($('cmd_asc').getAttribute('oncommand'))
}

function typeModif()
{
	if ($('type').value.toLowerCase()=="madame")
		$("zNom2").hidden=false;
	else
		$("zNom2").hidden=true;
}

function verifDelete(id)
{
	return true;
}

function openCategories()
{
	var params =
	{
		inn:
		{
			noms:		'Catégories',
			zone:		'fk_categories',
			table: 	TABLE.categories,
			prefix:	'cat_',
			verif:	'verifDeleteCategories'
		}
	};
   
	popupDialog('dlg_listes.xul', 1, 0, 0, params);
	
	$('fk_categories_datas').builder.rebuild();
	$('f_fk_categories_datas').builder.rebuild();
	$('fk_categories').value=$('fk_categories').value;
}

function verifDeleteCategories(val)
{
	var verif = true;
	
	var sql = "SELECT lis_id FROM" +TABLE.adressesCategories +
						"WHERE lis_fk_categories=?1 " +
						"LIMIT 1";
			
	var req=_exec_sql(sql, val);

	if (req.executeStep())
		verif=false;
	
	req.reset();
		
	return verif;
}

function categoriesAdd()
{
	var cat= $('fk_categories').value;
	
	var sql = "SELECT lis_id FROM" +TABLE.adressesCategories +
						"WHERE lis_fk_adresses=?1 AND lis_fk_categories=?2 " +
						"LIMIT 1";
			
	var req=_exec_sql(sql, G_id, cat);

	if (!req.executeStep())
	{
		sql = "INSERT INTO" +TABLE.adressesCategories +
					"(lis_fk_adresses, lis_fk_categories) " +
					"VALUES (?1, ?2)";
		
		_exec_sql(sql, G_id, cat);
		
		categoriesListe();
	}
	
	req.reset();
}

function categoriesDelete()
{
	var cat= $('fk_categories_liste').value;
	
	if (cat>0)
	{
		var sql = "DELETE FROM" +TABLE.adressesCategories +
							"WHERE lis_id=?1";
		
		_exec_sql(sql, cat);
		
		categoriesListe();
	}
}

function categoriesListe()
{
	var sql = "SELECT lis_id, cat_libelle FROM" +TABLE.adressesCategories + ", " + TABLE.categories +
						"WHERE cat_id=lis_fk_categories AND lis_fk_adresses="+ G_id + " " +
						"ORDER BY 2";
	
	_listboxRemplir("fk_categories_liste", sql);
}

function Exporter()
{
	var params =
	{
		inn:
		{
			id:			G_id,
			action:	'insert',
			liste: 	0
		},
		
		out:null
	};

	popupDialog("wiz_exporter.xul", 1, 1, 1, {});
}

function Anniversaires()
{
	printPreview('anniversaires.html', '');
}