// Voir O.FireEvent('click') ?

// ====================================      addEventListener       ===============================
// if (!window.addEventListener) {
// 	window.addEventListener = function(type, handler) {
// 		window.attachEvent('on'+type, function(e) {
// 			e.target = e.srcElement;
// 			return handler(e);
// 		});
// 	}
// }

EvtWin = new EventClass()

function EventClass() {
	var OP, Me
	this.ObjSel	= this.oldObjSel = this.ObjOn	= this.oldObjOn = null
	this.On		= this.oldOn	= null
	this.Sel	= this.oldSel = null
	this.busy = 0
	this.Clic = Clic
	this.GetElem = GetElem
	this.okInitClicP = 0
	this.InitClicParent = InitClicParent
	this.EventClicParent = EventClicParent

	if (!document.addEventListener) {
		document.addEventListener = function(type, handler) {
			document.attachEvent('on'+type, function(e) {
				e.target = e.srcElement;
				return handler(e);
			});
		}
	}

	document.addEventListener('keydown', function(e) {
	  if (!e.target) return;  if (!e.target.tagName) return
		EvtWin.GetElem(e.target, '', 'KeyDown');
		var Obj = EvtWin.Obj;  if (!Obj)  return
		if (Obj.KeyDown)  Obj.KeyDown(e)
	}, false)

// 	document.addEventListener('mousemove', function(e) {
// 	  if (!e.target) return;  if (!e.target.tagName) return
// 		EvtWin.GetElem(e.target);
// 		var Obj = EvtWin.Obj;		if (!Obj)  return
// 		if (Obj.MouseMove && Obj.MouseMove(e))  return
// 		//return cancelEvent(e)  ==> inhiber, sinon le drag ne marche+
// 	}, false)

	document.addEventListener('mouseover', function(e) {
	  if (!e.target) return;  if (!e.target.tagName) return
		EvtWin.GetElem(e.target,'On');
		var Obj = EvtWin.Obj;  if (!Obj)  return
		if (Obj.MouseOver && Obj.MouseOver(e.target))  return
    //alert(Obj.Nom)
		return cancelEvent(e)
	}, false)

	document.addEventListener('mouseout', function(e) {
	  if (!e.target) return;  if (!e.target.tagName) return
		EvtWin.GetElem(e.target,'Out');
		var Obj = EvtWin.Obj;		if (!Obj)  return
		if (Obj.MouseOut && Obj.MouseOut(e.target))  return
		return cancelEvent(e)
	}, false)

// 	document.addEventListener('mousedown', function(e) {
// 	  if (!e.target.tagName)  return
// 		EvtWin.GetElem(e.target);
// 		var Obj = EvtWin.Obj;		if (!Obj)  return
// 		if (Obj.MouseDown && Obj.MouseDown())  return
// 		return cancelEvent(e)
// 	}, false)

// 	document.addEventListener('mouseup', function(e) {
//     //alert(Lout(e.target))
// 		EvtWin.GetElem(e.target,"Sel");		EvtWin.Clic(e.target)
// 	}, false);

	document.addEventListener('click', function(e) {
		var re = EvtWin.Clic(e)
		if (re)  return cancelEvent(e)
	}, false);

	document.addEventListener('dblclick', function(e) {
	  if (!e.target) return;  if (!e.target.tagName) return
		EvtWin.GetElem(e.target);
		var Obj = EvtWin.Obj;		if (!Obj)  return
		if (Obj.dblClic && Obj.dblClic(e.target))  return
		return cancelEvent(e)
	}, false);

	function Clic(e) {
		var O
		if (!e)  return;
		if (e.nodeName)  O = e;  else  O = e.target
		EvtWin.GetElem(O,'Sel')
		var Obj = this.ObjSel, oldObj = this.oldObjSel;
		if (oldObj!=Obj) {  // clic ailleurs que dans l'objet (ou peut être plutôt sur un autre objet)
			if (oldObj) { if (oldObj.ClicOutObj)  oldObj.ClicOutObj(O);  else if (oldObj.ClicOut) { oldObj.oldSel = oldObj.Sel;  oldObj.ClicOut(O) } }
			this.oldObjSel = Obj
		}else{  // clic sur un autre él. du même objet
			//alert('Clic'+crr+Lout(Obj.Sel)+crr+Lout(Obj.oldSel))
			if (Obj && Obj.Sel!=Obj.oldSel) { if (Obj.ClicOther) Obj.ClicOther(O); }
		}
		if (Obj && Obj.Clic)  return Obj.Clic(e)
	}

	function GetElem(O, Class, Event) {
		/* Un objet est défini par l'at objet=NomObj et à l'intérieur un ensemble d'éléments définit par obj=CategObj */
		var S, Nom, Old, Me, OClic, Obj, OE, OC, liObj, into, Desactiv=''
		if (this.busy)  return;  this.busy = 1
		if (!Class)  Class='';  else if (Class=='Out') { Class='On';  Desactiv=1; }
		this.Elem = ElemPAt(O,'obj')
		Nom = 'Obj'+Class,  Old = 'oldObj'+Class
		OClic = GetClass(O, Event);
		if (OClic!=this[Nom]) { this[Old] = this[Nom];  this[Nom] = OClic };  if (!OClic) { this.busy = 0; return }
		this.Obj = Obj = this[Nom]
		liObj = '['+Obj.Nom+', '+Class+Desactiv+']'
		OE  = Obj.OE;   		//if (Class=='On') wh(liObj+', '+wobj(OE))
		if ((S=LX(OE,'ElemRepeat')))   Me = ElemPTag(O,S);     
		if (Me && Class) {
			OC = Obj[Class]     // Obj = Objet global, Me = Elément répétitif (TR), OC = ancien Me
		  if (Me!=OC) {
				// Nous sommes sur un autre eldom que OC
				if (OC) {
					OC.className = Replace(OC.className, ' '+Class, '');      wh('----'+liObj+',  Me='+wobj(Me)+', OC='+wobj(OC));
					Obj['old'+Class] = OC;
				}   else  wh('----'+liObj+' Me=' + wobj(Me))
				Me.className += ' '+Class
				Obj[Class] = Me;
				setTimeout(function(){ WhenOutObj(Me,Obj) },800)
			}
		}else if (Class) {
			//if (this.Elem)  Obj[Class] = this.Elem;   // cette ligne conserve this.Sel quand on clic que un élement qui ne contient pas obj et répète l'évènement sur l'avant dernier él cliqué
			Obj[Class] = this.Elem;
// 			if (Class=='On') {
// 				into = ContainsXY(OE,X,Y,-3)
// 				if (!into && Desactiv) {
// 					if ((OC=Obj[Class])) { OC.className = Replace(OC.className, ' '+Class, '');  Obj[Class] = null; }
// 				}
// 				wh('-/-/-'+liObj+', Elem='+wobj(Obj.On)+', Me=' + wobj(Me));
// 			}
		}
		this.busy = 0
	}

	function InitClicParent() {
	  this.okInitClicP = 1
		if (window!=parent) {
			if (document.all) {
				parent.document.attachEvent('onmouseup', this.EventClicParent)
				parent.attachEvent('onbeforeunload',function(e) { parent.document.detachEvent ('onmouseup', EvtWin.EventClicParent) } )
			}else{
				parent.document.addEventListener('mouseup', this.EventClicParent)
				//element.removeEventListener(type, listener, useCapture)
			}
		}
	}

	function EventClicParent(e) {
		EvtWin.ObjSel = EvtWin.On = EvtWin.Sel = null;
		if (document.all)  EvtWin.Clic(parent.event.srcElement);  else  EvtWin.Clic(e.target)
	}

	function cancelEvent(e) {
		if (e.stopPropagation) e.stopPropagation();  if (e.preventDefault) e.preventDefault();
		//e.cancelBubble = true
		e.returnValue = false
		return false
	}
}


// ====================================      Fonctions class      ===============================
function GetClass(O, Event) {
	var OR, Ob    // retourne la classe du eldom O. Si Event est indiqué, retourne la classe qui contient l'objet correspondant
	O = LID(O)
	do {
		Ob = ElemPAt(O,'objet');  //if (Ob)  wb('GetClass\n'+Lout(Ob,80))
		if (Ob) {
			OR = window[LX(Ob,'objet')];		//if (Event)  alert(OR[Event]+crr+Lout(Ob))
			if (Event && !OR[Event])  OR = null
			O = Ob.parentNode;
		}
	}while(Ob && !OR);
	return OR
}

function GoodAt(At, O1, O2, ValDef) {
	var V
	if (!(V=LX(O1,At)))  if (!(V=LX(O2,At)))  V = ValDef
	return V
}


// ====================================      Generic Class       ===============================
function GenClass(Nom, id) {
  if (typeof(id)=='string')  this.OE	=	LID(id);  else  this.OE = id
	if (!this.OE)  return
	this.Nom	= Nom
	this.Tag  = LX(this.OE,"ElemRepeat")
	PX(this.OE,"objet",Nom);
}

GenClass.prototype.Elem = function(no) {
	if (this.Tag)  return LTag(this.OE, this.Tag, no)
}

GenClass.prototype.onOut = function(O) {
	//alert(Lout(O))
	O.className = Replace(O.className, ' On', '');  this.oldOn=this.On;  this.On = null;
}

// ====================================      OnglClass       ===============================
function OnglClass(Nom, id) {
	this.OE	=	LID(id);  if (!this.OE)  return
	this.Nom	= Nom
	this.Tag  = LX(this.OE,"ElemRepeat")
	PX(this.OE,"objet",Nom)
}

OnglClass.prototype.Elem = function(no) {
	if (this.Tag)  return LTag(this.OE, this.Tag, no)
}

OnglClass.prototype.Clic = function(e) {
  //alert(Lout(this.Sel)+crr+Lout(this.OE))
  var OP, O, Os, S, i, D, DP
  OP = this.OE;  O = this.Sel;  if (!O)  return
  switch(LX(OP,'behav')) {
    case 'Inline':
 			DP = ElemNext(OP)		// frère du contenant des onglets => parent des div associées aux onglets
			ElemIn(DP.childNodes, true, false, {Action:'Hide(O)'})
			i = CalcIndex(O)
			D = PosIndex(DP,i)
			Aff(D)
      break
	}
  if ((S=LX(O,"Div"))) {
	}
	if (this.ClicSuite)  return this.ClicSuite(O);  else  return true
}

// ====================================      TableClass       ===============================
function HTableClass(Nom, id) {
	this.OE	=	LID(id);  if (!this.OE)  return
	this.Nom	= Nom
	this.Tag  = LX(this.OE,"ElemRepeat")
	PX(this.OE,"objet",Nom)
}

// ====================================      Tree Class       ===============================
function TreeClass(Nom, id) {
  if (typeof(id)=='string')  this.OE	=	LID(id);  else  this.OE = id
	if (!this.OE)  return
	this.Nom	= Nom;  PX(this.OE,'objet',Nom);  //alert(Lout(this.OE))
	this.Tag  = 'TR'
	this.NomZ	= id;
  this.InitNod()
}

TreeClass.prototype.InitNod = function() {
	this.DivFils = null
	this.TR		= null
	this.cl1	= null
	this.Cle	= null
	this.TypL	= ''
}

TreeClass.prototype.Elem = function(no) {
	if (this.Tag)  return LTag(this.OE, this.Tag, no)
}

TreeClass.prototype.PreparCod = function() {
	var D, Os, O, TR, i, j, S, T, id, L, H, F, idTR, NomZ
	Os = ElemAt(this.OE,'TypDoc','Dia');		//alert(Os.length)
	if (Os.length) {
		if (!App.Modul.Fo)  LoadJS('/SIP/js/Fo.js')
		for (i in Os) {
			TR = Os[i];  S = LX(TR,'Fils');  T = S.split(',');  idTR = Replace(TR.id,'~','_');  NomZ = Isole(TR.id,'~',1)
			L = T.length-1
			for (j=0; j<=L; j++) {
				id = NomZ+'~'+T[j];  if (!(D=LID(id)))  continue;			//alert(Lout(D))
				H=''
				if (j>0)  H+="<INPUT name=Retour type=button value='< Retour' onclick=Fiche(this,"+T[j-1]+",'Form') style='cursor:pointer'>&nbsp;"
				if (j<L)  H+="<INPUT name=Suivant type=button value='Suivant >' onclick=Fiche(this,"+T[j+1]+",'Form') style='cursor:pointer'>"
				if (H && (O=LID(id+'_foot'))) {
					O.innerHTML = "<div align=right><br>"+H+"</div>"
					if ((F=LTags(D,'FORM',0))) {
					  var Ta
						if (!(Ta=Tables[idTR])) { Ta = new TableClass(idTR);  Tables[idTR] = Ta }
						Fo = new FoClass(Replace(id,'~','_'), F, Ta)
						//alert(Tables['volet2_41'].all['Nom'].V+crr+Ta+Fo)
					}
				}
			}
		}
	}
}

TreeClass.prototype.Clic = function(e) {
	var O, S, TA, TR
	this.InitNod()
	if (!(O=this.Sel))  O = EventCtrl(e);			//alert(Lout(O)+crr+Lout(this.Sel))
	TR = ElemPAt(O,'ValCle');  TA = ElemPAt(O,'Table');  if (!TR)  TR = TA  // au - pour IcoMaj Ajout
	if (TR) {
	  this.TR = TR
		this.cl1 = LX(TR,"cl1"), this.Cle = LX(TR,"Cle"), this.TypL = LX(TR,"TypL")
		this.NomZ = Isole(LX(TR,'id'),'~',1);
		this.DivFils = LID(this.NomZ + '~' + this.cl1 + 'P');		//alert(Lout(this.DivFils))
	}
	if ((S=LX(O,'Obj'))) {
		switch(S) {
			case 'TDTreeIco':  this.ClicIco(O);  break
			case 'Titre':  case 'IcoCmt':  this.ClicLib(O);  break
			case 'Menu':  this.ClicMenu(O);  break
			case 'IcoMaj':  this.ClicMaj(O);  break
			case 'IcoAj':  this.ClicMaj(O,1);  break
		}
	}else{
		TA = ElemPAt(O,'Action');
		if ((S=LX(TA,'Action'))) {
		  ExAction(S, TA)
		  return true
		}
	}
}

TreeClass.prototype.ClicIco = function(O) {
	var TR, S, ok, DI, P, V
	TR = this.TR
	DI = ElemIn(TR, "O.className=='DivIn'", true, 0);
	ok=1
	if (this.Cle) {    // Chargement sous-niveau si non chargé
		if ((P=this.DivFils)) {
			if (P.innerHTML=='') {
				P.innerHTML = 'Chargement en cours...'
				if (!(V=LX(TR,'NivLst')))  V=1;  V++
				Aff(DI)
				var Action = [{Action:'Win', ValCle:this.cl1, ZoneDef:P.id, deltaNiv:V, nivAll:1}]
				ExAction(Action, TR)
				ok=0
			}
		}
	}
	if (ok) {	InverseDisplay(DI); }
	this.MajIcos()
}

TreeClass.prototype.ClicLib = function(O) {
	var S, P, X
  if (this.TypL=='SITES') { location = MajListe(location.href, 'Tree', this.cl1, '&', '=', 1);  return	}

	P = ElemIn(this.TR, "O.className=='DivIn'", true);  if (P)  P = P[0]
	X = ElemIn(P, "O.className=='cmtFiche'", true);  if (X)  X = X[0]
	if (SiAff(P))  InverseDisplay(X);	else{ Aff(P);  Aff(X) }
	this.MajIcos()
	if (this.ClicLibSuite)  this.ClicLibSuite(O);  else if ((S=LX(O,'Action')))  ExAction(S, O)
}

TreeClass.prototype.ClicMenu = function(O) {
	var S, P, X
	var Action = LX(O,'Action')
	if (Action)  ExAction(Action,O)
}

TreeClass.prototype.ClicMaj = function(O, Aj) {
	var TA, TR, S, V
	TR = this.TR;  TA = ElemPAt(TR,'Table');
	S = LX(TA,'VueMaj'); if (!S)  S = LX(TA,'Table');  V = LX(TR,'ValCle');
	if (S=='base' || S.substr(0,2)=='l_') {
	  MajFiche(TR, S, Aj);  return
	}
	if (S) {
		var Action = [{Action:'Form', NomR:S, ValCle:V}]
		if ((X=LX(TA,'RDef')))  Action[0].RDef = JSOND(X)
		PX(TR,'Action',JSONS(Action));  Action=null;  //alert(Lout(OA))
		ExAction(Action,TR)
	}else{
		//Action = [{"Action":"Form", "NomR":"SimpleFiche", "NomT":"l_base", "ValCle":cl1, "Bin":"SIP"}];
		if (Aj)  S = 'clp=' + this.cl1;  else    S = 'cl1=' + this.cl1
		X = '/SIP/Fich.php?' + S + '&id=' + LX(TR,'id') + AjUrl
		window.open(X, '', "toolbar=no,menubar=no,scrollbars=yes,resizable=yes,status=yes,width=760,height=600")
	}
}

TreeClass.prototype.ClicAj = function() {
	Action = '[{"Action":"Form", "NomR":"SimpleFiche", "NomT":"l_base", "clp":'+this.cl1+', "Lien":'+this.Cle+', "Bin":"SIP"}]';
	ExecAction(Action,this.TR)
}

TreeClass.prototype.ClicBlog = function() {
	if (Zones.Memo.Sess.CodUser) {
		Action  = 'Form:Identification';
		if (!App.Vars)  App.Vars = {}
		App.Vars.AjBlog_clp = this.cl1;  App.Vars.AjBlog_Lien = this.Cle;
	}else
		Action = '[{"Action":"Form", "NomR":"AjoutBlog", "NomT":"l_base", "clp":'+this.cl1+', "Lien":'+this.Cle+', "Bin":"SIP"}]';
	ExecAction(Action,this.TR)
}

TreeClass.prototype.MajIcos = function() {
	var TR, DV, Ds, TI, i;		//return
  //alert(this.Nom)
	var NomZ = this.NomZ
	if (!(DV=LID(NomZ)))  return
	Ds = ElemIn(DV, "LX(O,'obj')=='TDTreeIco'", true);  if (!Ds)  return;  if (!Ds.length)  return
  if (this.NomZ=='volet2')
		TI = ['Generic.gif','Ico_Page.gif','fldF-bleu.jpg','fldOC.gif','fldOP.gif','fldOD.gif'];
	else
		TI = ['n.jpg','np.jpg','TreeClose.gif','TreeOpen.gif','TreeOpen.gif','TreeOpen.gif'];
	for (i in Ds) {
		TR = ElemPAt(Ds[i],'ValCle')
    this.MajIco(TR, TI)
	}
}

TreeClass.prototype.MajIco = function(TR, TIco) {
	var id, cl1, S, DI, DC, DFils, re=0, I
  if (!(I=LTags(TR,'IMG',0)))  return
	cl1 = LX(TR,'cl1');  id = Isole(LX(TR,'id'),'~',1) + '~'+cl1+'P';  DFils = LID(id)
	if (DFils)  re+=2;
	DI = ElemIn(TR, "O.className=='DivIn'", true, 0);
	DC = ElemIn(TR, "O.className=='cmtFiche'", true, 0);
	if (SiAff(DI)) {
		if (SiAff(DC))  re+=1;
		if (DFils && DFils.innerHTML)  re+=1;
	}
	I.src = '/biblio/img/tree/'+TIco[re];
	//I.parentNode.innerHTML+= re+','+SiAff(DI)+','+SiAff(DC)+'-'
}
