var TAction = []

// ====================================      VUES       ===============================
var Vues  = new ClassVues();
var Zones = new ClassZones();

function ClassVues() {
	this.T = [];
	this.nb = 0;
}

ClassVues.prototype.Add = function(Nom) {
	var T
	if ((T=this.T[Nom]))  return T
	T = this.T[Nom] = new ClassVue(Nom)
	return T
}

// --------------------------      VUE      ----------------------------
function ClassVue(Nom) {
	this.Nom = Nom
}


// ====================================      ZONES       ===============================
function ClassZones() {
	this.all = {};
	this.nb = 0;
	this.ZoneDef = 'volet2'
	this.Memo = {CleClic:0, LibClic:'', ZoneAction:''}
}

ClassZones.prototype.Add = function(Nom) {
	var T
	if ((T=this.all[Nom]))  return T
	T = this.all[Nom] = new ClassZone(Nom)
	return T
}

ClassZones.prototype.PutProp = function(Nom, V) {
	var Z, nz
	for (nz in this.all) {
		Z = this.all[nz];
		Z[Nom] = V
	}
}

ClassZones.prototype.Contexte = function() {
	var Z, nz, H='', S, O
	for (nz in this.all) {
		if (nz.indexOf('Bug')>=0)  continue;
		//if (!LID(nz)) { delete(this.all[nz]);  continue; }  cmt car sinon dans le site capeb où menu1 n'E pas encore, la zone est supprimée
		Z = this.all[nz];  if (!Z)  continue;
		//if (S=JSONS(Z.Data))  H+=', "'+nz+'":'+S
		if (Z.Rempli)  H+=', "'+nz+'":{Cle:'+Z.Cle+'}'
	}
	H = H.substr(2);  //if (!H)  return ''
	O = new ObjClone(this.Memo);  O.Zones = eval('({'+H+'})')
	H = JSONS(O, {nonVide:1});		//alert(H)
	return H
}

ClassZones.prototype.toString = function() {
	var Z, nz, S=''
	for (nz in this.all) {
	  Z = this.all[nz]
		S+=Z.Nom+cr
	}
	return S// + crr + JSONS(this.all)
}

ClassZones.prototype.Clear = function() {
	delete(this.all)
}

ClassZones.prototype.toString = function() {
	return JSW(this)
}


// --------------------------      ZONE      ----------------------------
function ClassZone(Nom) {
	this.Nom = Nom
	this.Cle = null
	this.noAction = 0;
	this.Data = {}
	this.Rempli = 0     // rempli actuellement
	this.ReceptH = 0    // rempli sur action
	this.Hist = []
}

ClassZone.prototype.Memo = function(JS) {
	copyObj(this, JS)
}

ClassZone.prototype.toString = function() {
	return JSW(this)
	var Z, nz, S='';  for (nz in this.all) { Z = this.all[nz];  S+=Z.Nom+cr };  return S
}


// ====================================      SS-PGM       ===============================
function ExecAct(Action, Li, fct, Param) {
	//re = ExecAct('LitSql:SELECT SUM(apQuant) AS Tot FROM flux WHERE CodPrd='+V+' AND QUARTER(apDat)=QUARTER(Now())')
	var re, e, Contexte, i, S;		//alert(Action+crr+Li)
	Contexte = Zones.Contexte();  Li += '&Contexte='+escape(Contexte);    //alert(Li)
	XmlPost2(Li, '/SIP/iview/appli.php?Action='+Action+'&BugH='+Bug+AjUrl, fct, Param)
}

function ExAction(Action, OA) {
	MemoAction(OA, Action)
	var Action = Zones.Memo.Action
	ExecAction(Action, LX(OA,'Param'))
}

function MemoAction(O, Action, Opt) {
	var OP, O, AO, M, Action, ActionT, S, V, T
	//if (LVal('Rech')=='a')  alert(aa)
	if (typeof Opt!=='object')  Opt={}
	if (!Action) { Action = LX(O,'Action');  if (!Action) return }		//;alert(Lout(O)+crr+Lout(ElemPAt(O,'ValCle')))
	if (typeof(Action)=="string") {
		ActionT = Action
		if (Action.substr(0,1)=='[') {
				//alert(Action)
			Action = eval('('+Action+')')
		}else{
		  Action = [{}];  AO = Action[0]
		  T = ActionT.split(':')
		  AO.Action = T[0]
		  if (T.length>1) {  AO.TypL = Isole(T[1],',',1);  if ((S=Isole(T[1],',',2)))  AO.ValCle = S; }
		  if (T.length>2) {  AO.Param = T[2] }
		}
	}

	M = Zones.Memo
	M.Action = Action
	if (O) {
		M.CleClic = ElemPAt(O,'!ValCle');
		M.LibClic = Trim(Isole(LText(O),'\n',1))
		AO = ElemPAt(O,'ZoneAction')
		if (AO) {
			M.ZoneAction = LX(AO,'ZoneAction')
			T = new Array()
			while((AO=ElemPAt(AO,'ZoneAction'))) {
			  S = LX(AO,'ZoneAction')
				V = GetActionZone(S)
				T.push(V);			//alert(JSONS(T)+crr+JSONS(V)+crr+Lout(AO))
				AO = AO.parentNode
			}
			M.ZonesParent = T
		}
		Zones.Param = LX(O,'Param')
		if ((S=ElemPAt(O,'!ZoneDef')))  M.ZoneDef = S;  else M.ZoneDef=null
	}
}

function ExecAction(Action, Param, Opt) {
	var ActionT='', T, T2, O, re, e, Contexte, i, S;		//alert(Action+crr+Param)
	if (Param==undefined)  Param=''

	if (typeof Opt!=='object')  Opt={}
	if (App.debAction)  App.debAction()
	
	if (typeof(Action)=='string') {
		MemoAction(null, Action, Opt)
		Action = Zones.Memo.Action
	}
	if (Action) {
		ActionT = JSONS(Action);     //alert(ActionT)
	  O = Action[0]
		if (O.TypAct && O.TypAct=='Win') {
		  var Ad = O.Nom;  if (Ad.indexOf('.')<0)  Ad = 'iview/'+Ad+'.php?'
			//Action.splice(0,1);
			O.TypAct='Dialog';  ActionT = JSONS(Action);
		  Ad+='Action='+ActionT+AjUrl
			window.open(Ad, 'Dialog', "width=850,height=600,titlebar=1,toolbar=1,directories=1,menubar=1,scrollbars=1,resizable=1,status=1");
			return
		}
	}
		//alert(JSONS(Action))
	App.Retour = null
	Contexte = Zones.Contexte();    //alert(Contexte)
	//Contexte = Replace(Contexte,'&','&amp;');  
	Param += '&Contexte='+escape(Contexte);    //alert(ActionT+crr+Param)
	Zones.Memo.Action = Action
	S = '/SIP/iview/appli.php?Action='+ActionT+'&BugH='+Bug+AjUrl
	if (!App.F2 && Opt.Asynch!==0) {
		var Pgm = Opt.CallBack;  if (!Pgm)  Pgm = TraitResult
		XmlPost2(Param, S, Pgm, Opt)
	}else{
		re = XmlPost(Param, S);  //encodeURIComponent
		TraitResult(re, Opt)
		return (re)
	}
    //LID('DivPrim').innerText = re
}

function TraitResult(re, Opt) {
	var O, Z, e, S, JS, JSS, i, NomZ;
	if (!Opt)  Opt={}
	delete(Apg);  Apg = {}
	var Action = Zones.Memo.Action;   if (!Action)  Action = [{}];		//alert(JSONS(Action))
	if (!re) {
		re = LText('DivPrim');  PText('DivPrim','')
	}
	if (re.substr(0,1)=='{') {
		JSS = Isole(re,'|||',1);  re = re.substr(JSS.length);		//alert(JSS+crr+re)
		JS = App.Retour = eval('('+JSS+')')
		if ((S=JS.Sess))  Zones.Memo.Sess = S
		if (JS.Zones) {
			//alert(JSW(JS.Zones))
			for (NomZ in JS.Zones) {
				if (!(O=JS.Zones[NomZ]))  continue;  if (!O.ReceptH)  continue
				O.Rempli = 1
				Z = Zones.Add(NomZ);  Z.Memo(O);				//alert(JSW(Z)+crr+JSW(O))
			}
			//alert(JSW(Zones.all))
		}
		//Action = Zones.Memo.Action = App.Retour.Acts
	}
		//alert(Zones.all.menu1+crr+Zones.all.ssmenu+crr+Zones.all.volet2)
	if (Bug)  LID('TitBug').innerHTML = '<b>Action</b>='+JSONS(Action)+'<br><b>Contexte=</b>'+Zones.Contexte()+cr+'<br>' + '<b>JS=</b>' + JSS
	//if (Bug)  PText('TitBug',S)
	if (re.substr(0,1)!='|') { if (Bug)  LID('DivHBug').innerHTML = re;  return }

	Zones.Memo.ActionZone = O = Action[0]     // ActionZone = dernière action influant sur une zone (LitSql non pris en compte)
	if (O.ValCle)  App.LastActWithCle = Action  // Pour les retours
	//S = Isole(re,'|||',2);			//alert(S+crr+re)
	if (!Opt.noPush && (Action && Action[0] && !Action[0].PosJeu)) {
		S = JSONS(LastAction());  e = JSONS(Zones.Memo);  //alert(JSONS(Action)+crr+S+crr+e);  if (S!=e)  alert('Memo'+crr+JSONS(Zones.Memo))
		if (S!=e)  TAction.push(new ObjClone(Zones.Memo))
	}
	if (Bug==3)  PText('DivBug',re+crr)
	e = TraitRetour(re);  if (!e)  return

	Distrib(re, Opt);			//alert(Zones)
	FinAction(Opt)
	if (App.finAction) { App.finAction();  App.finAction = null }
	if (App.finAction2) setTimeout("App.finAction2()",100)
	if (Action) {
		for (i=0; i<Action.length; i++) {
			O = Action[i];  S = O.Action;  if (Apg['fin_'+S]) { Apg['fin_'+S]();  Apg['fin_'+S] = null }
			S = O.NomR;  if (Apg['fin_'+S]) { Apg['fin_'+S]();  Apg['fin_'+S] = null }
		}
	}
	if (App.Affich) { App.Affich();  App.Affich = null }
	if (Opt.Suite)  Opt.Suite()
		//alert('ExecAction'+crr+TAction.length+crr+AffAction())
}

function Distrib(H, Opt) {
	var TP, T, TD, Z, P, H, Zone, NomZ, NomZR, O, LiAct, i, S, Chaine, D, Act, volet2_fait;
	TP = H.split('|||')
	if (Bug)  PText('DivBug','')
	Zones.PutProp('ReceptH',0)

	for (i=1; i<TP.length-1; i+=2) {
		LiAct = TP[i];  T = null
		H = TP[i+1];
		if (LiAct.indexOf('=')>0) { TD = Tableau1D(LiAct, '=|');  NomZ = TD['Zone']; }
		NomZR = Isole(NomZ,'~',1)
			//alert(LiAct+crr+NomZ+crr+JSON_Encode(TD)+crr+H)
		if (NomZR=='volet2')  volet2_fait=1;
		if (NomZ=='JS') {
			eval('('+H+')');
			continue
		}
		if (H.substr(0,2)=='||') {
			T = H.substr(2).split('||');
			T[0] = Trim(T[0])
			H = T[1]
		}
		H = Trim(H)
		Zone = LID(NomZ);  //if (!Zone) { NomZ = Zones.ZoneDef;  Zone = LID(NomZ); }
		if (Zone) {
			TD.Cle = getContextZone(NomZ, 'Cle');     //alert(Lout(Zone)+crr+H)
			Z = Zones.Add(NomZ);  Z.Data = TD
			if (H || (App.Retour.Zones[NomZ] && App.Retour.Zones[NomZ].HideVide=='!')) { // ! permet de vider le volet si rien en réception (cas de volet (fiche Iris Zone) déclaré mais sans contenu)
				//if (NomZ.indexOf('~')>=0)  D = Zone.parentNode;  else  D = Zone
				if (NomZ.indexOf('~')>=0) { D = Zone.parentNode;  RX(D,'ValCle');  RX(D,'TypDoc'); }

				PVal(Zone, H, true);      //alert(NomZ+crr+H)

				//if (NomZ.indexOf('~')>=0)  alert(NomZ+crr+Lout(Zone))
				/*D = document.createElement('div');  D.innerHTML = H;  LID(Zone).appendChild(D)*/  		//if (NomZ=='volet2')  alert(NomZ+crr+'/'+H+'/')
				if (H)  AdaptZone(Zone)
			}
			Zones.all[NomZ].SiH = (H) ? 1:0
			Zones.all[NomZ].ReceptH = 1
			if (LX(Zone.parentNode,'id')!='DivBugs') {
				Aff(Zone);  //if ((S=LX(Zone,'conteneur')))  Aff(S)
			}
			Act = GetActionZone(NomZ);
			if (!LX(Zone,'ZoneAction'))  PX(Zone,'ZoneAction',NomZ)
			if (App['Zone'+NomZ])  App['Zone'+NomZ]()
			//if ((O=LID(NomZ+'_Act')))  TD.Act = eval('('+LText(O)+')')
		}
		if (T && T[0]) {
			eval(T[0])
		}
		if (Bug && NomZ!='DivHBug') {
		  S = TP[i+1];  if (Bug==1)  S = S.substr(0,1800)
			//PText('DivBug',LText('DivBug') + '\n\n'+LiAct+'\n===========\n'+S)
			LID('DivBug').innerHTML+= wDiv(NomZ, S,1)
		}
		if (H && (Chaine=LVal('ScriptSuppl_'+NomZ))) {
			//PText('ScriptSuppl_'+NomZ,'');
			eval(Chaine);
		}
		if (Act && Act.ParamIn)  ExecParam(Act.ParamIn)  // à placer après de script T.InitChamps (Init)
		if (window['finAction_'+NomZ])  window['finAction_'+NomZ]()
	}
	if (!volet2_fait && !Opt.noPush)  PVal('volet2', '');
	if ((Z=LID('DivScript'))) {
		Chaine = Z.innerHTML;  //PVal('DivScript','');
		//alert(Chaine)
		eval(Chaine);
	}
}

function Decoupe(Div) {
	// Découpe la réponse dans un tableau
	var T = {}, TP, Nom, S, i, re
	if (typeof(Div)=='string' && Div.length>10)  re = Div;  else if ((Div=LID(Div)))  re = Div.innerHTML
	if (re.substr(0,1)=='{') {
		S = Isole(re,'|||',1);  re = re.substr(S.length);		//alert(S+crr+re)
		T.JS = eval('('+S+')')
	}

	TP = re.split('|||')
	for (i=1; i<TP.length-1; i+=2) {
		S = TP[i];  Nom = Isole(S,'=',2);		//alert(S+crr+Nom+crr+TP[i+1])
		T[Nom] = TP[i+1];
	}
  return T
}

function AdaptZone(Zone) {
	var Os, O, X, i, S, Z
	Z = Isole(Zone.id,'~',1)
	
	if (window.YAHOO && YAHOO.util.DD && ElemPAt(Z,'drag')) {
		Os = ElemAt(Z,'ValCle');		//alert(Z+cr+Os.length)
		for (i in Os) {
			O = Os[i]
			X = new YAHOO.util.DD(O);
			X.clickValidator = clickValidator
			X.onDragDrop = onDragDrop
			X.onInvalidDrop = function(e) { Dom.setXY(this.getEl(), this.xy); }
		}
	}
	//if (ElemPAt(Z,'drop')) {  Os = ElemAt(Z,"ValCle");  for (i in Os) { new YAHOO.util.DDTarget(Os[i]); } }
	O = ElemPAt(Zone,'objet')
	if ((S=LX(O,'objet'))) {
		O = eval(S);  if (O.PreparCod)  O.PreparCod()
	}
}

function FinAction(Opt) {
	var S
	if (!Opt.noPush) {
		Hide_Div_Vide()
		if (window.RePosWin)  RePosWin()
	}
}

function Hide_Div_Vide() {
	var TZ, Zone, Z, ZoneP, T, S, ZA
	if (!App.Retour)  return
	TZ = App.Retour.Zones;
	ZA = Zones.Memo.ZoneAction;		//alert(JSONS(TZ))
	for (Zone in TZ) {
		Z = TZ[Zone];  if (!Z)  continue;
		if (Zones.all[Zone] && Zones.all[Zone].ReceptH)  continue;  // si reçu du code
		S = Z.HideVide;  if (!S)  continue;			//alert('Zone='+Zone+crr+'MA='+S+cr+'ZA='+ZA)
		//if (ZA && S!=ZA)  continue;
		if (S!='!' && (!ZA || (S!='*' && S!=ZA)))  continue;
		PVal(Zone, '')   //Si la zone n'a pas reçu et si la provenance de l'action est correcte (HideVide), vider la zone. Ainsi un menu1 sans fils doit vider le volet1
		if ((ZoneP=VoletVide(Zone))) {
			Hide(ZoneP);
			wh("HIDE("+ZoneP+")",'TitBug')
		}
	}
}

function GetActionZone(Zone) {
	var S
  //alert(Lout((Zone+'_Act')))
	S=LText(Zone+'_Act');
	if (!S)  S=LText('LastAct');
	if (S) {
	  if (S.substr(0,1)=='[' && S.substr(S.length-1,1)==']') {
			return eval('('+S+')')
		}//else  alert('mauvais retour'+crr+S)
	}
}

function getContextZone(NomZ, Param) {
	var O
	//if (Param=='Cle')  alert(JSONS(App.Retour.Zones))
	if (App.Retour && App.Retour.Zones)  O = App.Retour.Zones[NomZ];  if (!O)  return
	//alert(NomZ+'='+JSONS(O)+crr+JSONS(App.Retour))
	if (Param)  return O[Param];  else  return O
}

function AffAction() {
	var S='', i
	//if (TAction.length>2)  alert(aa)
	for (i=0; i<TAction.length; i++) {
		S+=JSONS(TAction[i])+crr;
	}
	return S+crr+Zones
}

function LastAction() {
	return TAction[TAction.length-1];
}

function Retour(n, Opt) {
	var O, M, S, i
	if (!n)  n=2;		//alert(n+','+TAction.length+crr+AffAction())
	if (!Opt)  Opt={}
	if (TAction.length<n)  ExecAction('')
  if (TAction.length<n)  return;
	for (i=0; i<n; i++) {
		O = TAction.pop();
	}
	if (!O)  return
	M = Zones.Memo;  M.CleClic = O.CleClic;  M.LibClic = O.LibClic;  M.ZoneAction = O.ZoneAction
	  //alert(TAction.length+crr+JSW(O.Action)+crr+AffAction())
	ExecAction(O.Action,'',Opt.ExecAction)
}

function ExecParam(Param) {
	var NomV, S, V
	for (NomV in Param) {
		V = Param[NomV]
		PVal(NomV,V)
	}
}

function PutParam(Param, TR) {
	var NomCh, NomV, V
	for (NomV in Param) {
		NomCh = Param[NomV]
		V = LX(TR,NomCh);  if (!V)  V = LVal(NomCh)
		Param[NomV] = V
		//Param[NomV] = escape(V)
	}
}

function TraitRetour(re, tjrs) {
	var T, Msg, Msg2, S
	if (re.substr(0,1)=='{') {
		S = Isole(re,'|||',1);  Msg2 = re.substr(S.length);		//alert(S+crr+re)
		T = eval('('+S+')')
		Msg = T.MsgErr;  
	}else if (re.substr(0,1)!='|')
		Msg = re
	else{
		T = re.split('|')
		switch(T[1]) {
			case 'Msg':  Msg = T[2];  break
			default:  if (tjrs) Msg = T[2];  break
		}
	}
	if (Bug && Msg2)  PVal('DivOther',Msg2,1);
	if (Msg) { PVal(Zones.ZoneDef,Msg,1);  return false }  else  return true;
}

App.debAction = function() {
	//App.finSubmit = null
}


// ====================================      prototype       ===============================
TableClass.prototype.SovBack = function(re, Param) {
	if (Bug)  DivOther.innerHTML = wDiv('Sov', re) + wDiv('App.Retour', JSW(App.Retour), 1)
	TraitResult(re);		
	//if (window.FinSubmit)  window.FinSubmit()
	if (App.Retour.backVal) {
		Retour()
	}
	//e = TraitRetour(re);  if (!e)  return;  Retour()
}

TableClass.prototype.SupprBack = function(re, Param) {
	TraitResult(re)
	if (App.Retour.backVal) {
		Retour()
	}
}


// ====================================      DIVERS       ===============================
function Gokey(Cle) {
	ExecAction("Win:SIT," + Cle)
}

function ReIdent(O) {
	var A,B,TR
	if (typeof(O)=="string") {
		A = Isole(O,',',1);  B =  Isole(O,',',2)
	}else if (!isNaN(O)) {
    if (window.ReIdentNum) { ReIdentNum(O);  return }
	}else{
		TR = O.parentNode;  A = LX(TR,'Ident');  B = LX(TR,'mpCo')
	}
	PVal('Ident',A);  PVal('mp',B)
	ValidIdent()
}

function NomAction() {
	var V = Zones.Memo.Action[0].NomR;  if (!V)  V = Zones.Memo.Action[0].TypL
	return V
}

function Fiche(e, Cle, Act) {
	var O, TR, F, Fo, A
	O = EventCtrl(e)
	TR = ElemPAt(O,'ValCle');  if (!TR)  return
	if (Act=='Form') {
		F = LTags(TR,'FORM',0);  Fo = eval(LX(F,'ojs'))
		if (Fo && (A=VerifChamps(Fo.Ctrls))) { alert(A);  return }
	}
	A = [{Action:'Win', ValCle:Cle, ZoneDef:LX(TR.parentNode,'id'), ajoutNiv:LX(TR,'NivLst')}]
	//A = [{Action:'Win', ValCle:Cle, ZoneDef:LX(TR,'id'), ajoutNiv:LX(TR,'NivLst')}]
	ExecAction(A, TR, {noPush:1})
}

MajFiche = function(O, NomT, Mode) {
	var Cle, Ad, width, cl1 = LX(O,'cl1')
	if (NomT && NomT=='base')
		Cle = 'Cle=' + LX(O,'ValCle');
	else
	  if (Mode)  Cle = 'clp=' + cl1;  else  Cle = 'cl1=' + cl1;
	switch(NomT) {
		case 'l_contact':  Ad = '/SIP/iView/form/contact.php?';  width=',width=755,height=500';  break
		default:  Ad = '/SIP/Fich.php?';  width=',width=755,height=600';
	}
	Ad+= Cle + '&id=' + LX(O,'id') + AjUrl
	window.open(Ad, '', 'toolbar=no,menubar=no,scrollbars=yes,resizable=yes,status=yes'+width)
}
AjFiche = function(O,NomT) {
  MajFiche(O,NomT,1)
}

function hashChanged() {
	var T = Tableau1D(location.hash,'=&');  //alert(location.hash+crr+T.Cle)
	if (T.Cle)  ExecAction('Win:,'+T.Cle)
}

