/*
	-lastUpdate : 25/07/2010
*/

function $(Id)
{
	return document.getElementById(Id);
}

function $$(elementName)
{
	return document.getElementsByTagName(elementName);
}

function openFile(file)
{
	document.location.href=file;
}

var win=null;
function popup_open(fichier, param, hauteur, largeur, ass, modal)
{
	var top=	(screen.height-hauteur)/2;
	var left=	(screen.width-largeur)/2;
	
	if (window.showModalDialog && modal)
		win=showModalDialog(fichier+'?'+param, param,"dialogtop:"+top+";dialogleft:"+left+";dialogwidth:"+largeur+";dialogheight:"+hauteur+";resizable:"+ass+";");
	else
	{
		if (win && !win.closed)
			win.close();
		
		win=open(fichier+"?"+param,"popup","top="+top+",left="+left+",height="+hauteur+",width="+largeur+",innerWidth="+largeur+",innerHeight="+hauteur+",location=no,status=no,scrollbars="+ass);
		win.focus();
	}
		
	return win;
}

function popupDialog(file, modal, dependent, resizable, params)
{
//	resizable=1;
	window.openDialog(file, 'dlg', 'chrome,modal='+modal+',dependent='+dependent+',resizable='+resizable+'',params);
}

function message_tempo(zone, txt, delai)
{
	if (zone.tagName=="description")
		att="value";
	else
		att="label";
	
	eval("zone."+att+"=txt");
	
	setTimeout(function() {eval("zone."+att+"=''")}, delai);
}

function reload_fiche(fiche, param, id)
{
	if (id>0)
	{
		if (param)
			if (!Confirm('Recharger la fiche', "Retablir la version precedemment enregistree et perdre les modifications ?"))
				return false;
		
		fiche.FicheAffiche(id, "ASC", 1);
/*
	Revérifier cette partie car peut-être exécuté 2x
*/

		Record.ScaleImput();
	}

	return false;
}

function createTreeItem()
{
  const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
  var treeitem = document.createElementNS(XUL_NS, "treeitem");
  return treeitem;
}

function createTreeRow(aValue)
{
  const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
  var treerow = document.createElementNS(XUL_NS, "treerow");
  setVal(treerow, "value", aValue)
  return treerow;
}

function createTreeCell(aLabel)
{
  const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
  var item = document.createElementNS(XUL_NS, "treecell");
  setVal(item, "label", aLabel);
  return item;
}

function _listboxVider(listId)
{
	var listB= $(listId);
	
	for (var i=0, T=listB.getRowCount(); i<T; i++)
	{
		listB.removeItemAt(0);
	}

	if ($('T'+listId))
		$('T'+listId).value=0;
}

function _listboxRemplir(listId, sql)
{
	var listB= $(listId);
	
	var req=_exec_sql(sql);
	var cols = req.columnCount;
	
	_listboxVider(listId);
	
	var i=0;
	var lc = null;
	while (req.executeStep())
	{
		let li = newEl('listitem', 'value', req.getInt64(0));

		for (var col=1; col<cols; col++)
		{
			let txt = req.getUTF8String(col);
			
			if (txt.indexOf('_|_')>-1)
			{
				let args=txt.split('_|_');
				
				lc= newEl('listcell',
							'label', args[0],
							'style', args[1]
						);
			}
			else
			{
				lc= newEl('listcell',
							'label', txt
						);
			}
			
			li.appendChild(lc);
		}
		
		listB.appendChild(li);

		i++;
	}
	
	req.reset();
	
	if ($('T'+listId))
		$('T'+listId).value=i;
}

function listbox_remplirOld()
{//0-element, 1-value, 2...-champs_|_style
	var li = newEl('listitem', 'value', arguments[1]);
	
	var lc = null;
	for (var i=2, T=arguments.length; i<T; i++)
	{
		if (String(arguments[i]).indexOf('_|_')>-1)
		{
			var args=arguments[i].split('_|_');
			
			lc= newEl('listcell',
						'label', args[0],
						'style', args[1]
					);
		}
		else
		{
			lc= newEl('listcell',
						'label', arguments[i]
					);
		}

		li.appendChild(lc);
	}
	
	arguments[0].appendChild(li);
}

function tree_remplir()
{//0-element, 1-container[open(t/f)], 2-[xXx__properties__]value, 3...-champs
	
	var niv1 = newEl("treeitem");
	var niv2 = newEl("treerow");
	
	if (arguments[1]!="")
	{//container
		setVal(niv1, "container", true,
								"open", arguments[1]);
	}
	
	if (String(arguments[2]).indexOf("__properties__")>-1)
	{
		var treerow = arguments[2].split("__properties__");
		
		setVal(niv2,
					 "properties", treerow[0],
					 "value", treerow[1]);
	}
	else
		setVal(niv2, "value", arguments[2]);
		
	
	niv1.appendChild(niv2);
	
	for (var i=3, T=arguments.length; i<T; i++)
	{
		var cell =	document.createElement("treecell");
		
		if (arguments[i].indexOf("__checkbox__")>-1)
		{//<treecol type="checkbox"
			setVal(cell, 'value', true);
		}
		else
		if (arguments[i].indexOf("__properties__")>-1)
		{//<treecell properties="xXx"
			var args=arguments[i].split("__properties__");
			
			setVal(cell,
						 'properties', args[0],
						 'label', args[1]);
		}
		else
	    setVal(cell, "label", arguments[i]);

		niv2.appendChild(cell);
	}
	
	arguments[0].appendChild(niv1);
	
	return niv1;
}

function submitForm()
{//v1.00 15/04/2010
	var Params= [];
	var Tags=		['textbox', 'timepicker', 'menulist', 'radiogroup'];
	
	for(var i=0, T0=Tags.length; i<T0; i++)
	{
		for (var j=0, TagN=$$(Tags[i]), T=TagN.length; j<T; j++)
		{
			Params[TagN[j].id] = TagN[j].value.trim();
		}
	}
	
	for (var i=0, TagN=$$('datepicker'), T=TagN.length; i<T; i++)
	{
		Params[TagN[i].id] = $(TagN[i].id).value;
		
		if (
				$(TagN[i].id).dateField.value=="" ||
				$(TagN[i].id).monthField.value=="" ||
				$(TagN[i].id).yearField.value==""
				)
		{
			Params[TagN[i].id] = null;
		}
	}

	for (var i=0, TagN=$$('checkbox'), T=TagN.length; i<T; i++)
	{
		Params[TagN[i].id] = TagN[i].checked ? 1 : 0;
	}

	for (var i=0, TagN=$$('colorpicker'), T=TagN.length; i<T; i++)
	{
		Params[TagN[i].id] = TagN[i].color;
	}
	
	return Params;
}

function newEl()
{//el, attrib0, val0, attrib1...
	var el = document.createElement(arguments[0]);
	
	with(el)
	{
		for (var i=1, T=arguments.length; i<T; i+=2)
		{
			setAttribute(arguments[i], arguments[i+1]);
		}
	}
	
	return el;
}

function setVal()
{//el, attrib0, val0, attrib1...
	var el = arguments[0];

	with(el)
	{
		for (var i=1, T=arguments.length; i<T; i+=2)
		{
			setAttribute(arguments[i], arguments[i+1]);
		}
	}
	
	return el;
}

function TreeValue(tree)
{
	if (tree.currentIndex==-1)
		return false;
	else
	{
		var selection = tree.contentView.getItemAtIndex(tree.currentIndex);
		
		if (selection.firstChild)//Obligé sinon, génère une erreur lors d'un dblclick sur un separator
			return selection.firstChild.getAttribute('value');
		else
			return "";
	}
}

function createElement(element, attribut, value)
{
  const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
  var el = document.createElementNS(XUL_NS, element);
  
	setVal(el, attribut, value);
  
  return el;
}

function removeElements(el)
{
	while (el.firstChild)
	{
		el.removeChild(el.firstChild);
	}	
}

function testQuit()
{
	if (!Confirm("Quitter ?", "Voulez-vous vraiment quitter le programme ?"))
		return false;
	
	return true;
}

function initScreen()
{
	setVal($('cmd_desc'), 'disabled', true);
	$('tlb_desc').image=			'img/nav_g2.png';
	
	with($('btn_submit'))
	{
		label=				'Ajouter';
		disabled=false;
	}
	
	$('deck').selectedIndex=	0;
	
	setVal($('cmd_delete_fiche'), 'disabled', true);
	$('zPositionFiche').value=	0;
	
	$('onglets').hidden=			true;
}

function _init_navigation(table, where)
{
	var total= _total_lignes(table, where);
	
	Record.ScaleInit(0, total);
	$('scaleNav').value=0;
	
	$('lbl_total').value= number_format(total, 0);
	
	if (total>0)
	{
		$('cmd_asc').setAttribute('disabled', false);
		$('tlb_asc').image='img/nav_d.png';
	}
	else
	{
		$('cmd_asc').setAttribute('disabled', true);
		$('tlb_asc').image='img/nav_d2.png';
	}
}

function printPreview(file, options)
{
	var params =
	{
		inn:
		{
			file:	file,
			file_options:options
		},
		
		out:null
	};
		
	popupDialog('dlg_print.xul', 0, 1, 1, params);
}

function _datepikerReset(dp)
{
	with(dp)
	{
		dateField.value=	null;
		monthField.value=	null;
		yearField.value=	null;
	}
}

function _dateReset()
{
	var d= new Date();
	
	return d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate();
}

function _timeReset()
{
	var d= new Date();
	
	return d.getUTCHours.getHours()+':'+d.getMinutes();
}

function _now()
{
	var d= new Date();
	
	var m= d.getMonth()+1;
	m= (m<10 ? '0' : '')+m;
	
	var j= d.getDate();
	j= (j<10 ? '0' : '')+j;
	
	var h= d.getHours();
	h= (h<10 ? '0' : '')+h;
	
	var mi= d.getMinutes();
	mi= (mi<10 ? '0' : '')+mi;
	
	var s= d.getSeconds();
	s= (s<10 ? '0' : '')+s;
	
	return d.getFullYear()+'-'+m+'-'+j+' '+h+':'+mi+':'+s;	
}

function _exec_sql(sql)
{
/*
req.parameterCount //donne le nombre de paramètre
req.numEntries // ???
SQL.lastInsertRowID;				
*/

	try
	{
		var req = SQL.createStatement(sql);
		
		for (var i=1, T=arguments.length; i<T; i++)
		{
			req.bindUTF8StringParameter((i-1), arguments[i]);
		}
	
		if (req.columnCount>0)
		{
			
		}
		else
		{
			req.execute();
		}
	}
	catch(e)
	{
		Alert("Erreur SQLite!!!", "SQL :\n" + sql + "\n\nMESSAGE :\n" + SQL.lastErrorString + "\n\n" + e);
		
		return false;
	}
	finally
	{
		
	}
	
	return req;
}

function _recupDatas(req)
{
	var cols = req.columnCount;
	var row = new Array();
	
	for(var col=0; col<cols; col++)
	{
		let value=null;
		
		if (req.getTypeOfIndex(col)==0)
			value = null;
		else
		if (req.getTypeOfIndex(col)==1)
			value = req.getInt64(col);
		else
		if (req.getTypeOfIndex(col)==2)
			value = req.getDouble(col);
		else
		if (req.getTypeOfIndex(col)==3)
			value = req.getUTF8String(col);
		else
		if (req.getTypeOfIndex(col)==4)
			value = req.getBlob(col);
		else
			value = req.getString(col);
		
		row[req.getColumnName(col)] = value;
	}
	
	return row;
}

function _total_lignes(table)
{
	var where = !arguments[1] ? 1 : arguments[1];
	
	var sql = "SELECT COUNT(*) AS total FROM " + table + " " +
						"WHERE " + where;
		
	var req = _exec_sql(sql);
	
	var total = 0;
	if (req.executeStep())
	{
		var Rows=_recupDatas(req);
		
		total= Rows['total'];
	}
	
	req.reset();
	
	return total;
}

function _menulistRemplir(menulist, sql, val)
{
	with(menulist)
	{
		removeAllItems();
		appendItem('-', 0);
	}
	
	var req=_exec_sql(sql);
	
	while(req.executeStep())
	{
		let Rows=_recupDatas(req);
		
		menulist.appendItem(Rows['LIBELLE'], Rows['ID'], Rows['LIBELLE2']);
	}
	
	req.reset();
	
	menulist.value=val;
}

function _setup(table, field)
{
	var sql="SELECT " + field + " FROM " + table + " LIMIT 1";
	var req=_exec_sql(sql);
	
	var Rows= null;
	req.executeStep();
	
	Rows=_recupDatas(req);
	
	req.reset();
	
	return Rows[field];
}

function _fiche_position(table, champ_id, champ_order, id, reload)
{//reload est utiliser dans le cas de rechargement de la même fiche, pour connaitre sa position
	
	var where = !arguments[5] ? 1 : arguments[5];

	var verif=false, position=1, new_id=0;
	
	var sql = "SELECT " + champ_id + " FROM " + table +
						"WHERE " + where + " " +
						"ORDER BY " + champ_order;

	var req=_exec_sql(sql);

	while(req.executeStep())
	{
		let Rows=_recupDatas(req);
		
		if (verif || id==0)
		{//prend la première fiche si id==0
			new_id=Rows[champ_id];
			break;
		}
		
		if (id==Rows[champ_id])
		{
			verif=true;
			
			if (reload>0)
			{
				new_id=Rows[champ_id];
				break;
			}
		}

		position++;
	}
	
	if (new_id==0)
	{//si fin de liste sans rien trouvé
		new_id=	id;
		position--;
	}
	
	req.reset();

	return [position, _total_lignes(table), new_id];
}

function _trouve_valeur(table, id, champ_id, champ_nom, valeur_vide)
{
	var sql = "SELECT " + champ_nom + " FROM " + table + " " +
						"WHERE " + champ_id + "=?1 " +
						"LIMIT 1";

	var req=_exec_sql(sql, id);
	
	if (req.executeStep())
	{
		var Row=_recupDatas(req);
		
		req.reset();
		
		return Row[champ_nom];
	}
	else
	if (id=="" || id==0)
		return valeur_vide;
	else
		return "?";
}

function _format_be(nombre, dec)
{
	dec = !dec ? 0 : dec;

	return number_format(nombre, dec, ",", ".");
}

function _date_francais(date, separateur)
{//aaaa-MM-jj
	separateur = !separateur ? "/" : separateur;
	
	date = date.split("-");
	
	return date[2] + separateur + date[1] + separateur + date[0];
}

function _date_dt_fr(date, separateur, espace)
{//aaaa-MM-jj hh:mm:ss
	date = date.split(" ");
	
	return _date_francais(date[0], separateur) + espace + date[1];
}

function _jour_semaine(d, m, y)
{
	if (!checkdate(m, d,y))
	{
		return "-";
	}

	var jour=date("N", mktime(0, 0, 0, m, d, y));
	
	return _les_jours(jour-1);
}

function _les_jours(j)
{
	var Jours = ["lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche"];
	
	return Jours[j];
}

function _les_mois(m)
{
	var Mois = ["janvier", "f&eacute;vrier", "mars", "avril", "mai", "juin", "juillet", "ao&ucirc;t", "septembre", "octobre", "novembre", "d&eacute;cembre"];
	
	return Mois[m];
}	

function _calculAge(aDate)
{//aaaa-MM-jj
	var date = aDate.split("-");
	
	var toDay=new Date();
	
	var age = toDay.getFullYear() - date[0];
	
	var toDay2= new Date(toDay.getFullYear(), date[1]-1, date[2]-0);
	
	age-= (toDay<toDay2) ? 1 : 0;
	
	return age;
}

function _pluriel(n, singulier, pluriel)
{
	if (n>1)
		return pluriel;
	
	return singulier;
}

function isWindows()
{
	var os = navigator.platform.toLowerCase();
	
	if (os.substr(0, 3)=="win")
		return true;
	
	return false;
}
