var postes;
var types;
var lieux;
var site_poste;
var nonsp = false;

var qfuncs = {
 "Eq" : function(a,b) { return a == b; },
 "Or" : function(a,b) { return a || b; },
 "And" : function(a,b) { return a && b; },
 "Find" : function(lst,val)
  {
	for(var i in lst)
	 if(lst[i] == val)
	  return i;
	 
	return false;
  },
 "ValueOf" : function(objid) { var lst = document.getElementById(objid);
 							   return lst.options[lst.selectedIndex].value },
 "Lookup" : function(lst,key,idx) {  return lst[key]?lst[key][idx]:[]; } 
 							
};

function MakeEvents(evt)
{
 var evstr = "";
 
 for(e in evt)
  {
   evstr += e + "='" + evt[e] + "' ";
  }
  
 return evstr;
}

function MakePulldown(divid,id,dat,idf,textf,changeevent,style)
  {
	var div = document.getElementById(divid);
	
	var pd = '<SELECT id="' + id + '" name="' + id + '">\n';
	
	if(!nonsp)
	 pd += '<OPTION value="-1">Ne sais pas / N\'importe quel</OPTION>';
	
	for(var d in dat)
	 pd += '<OPTION value="' + (idf?dat[d][idf]:dat[d]) + '"' + (style?"style='" + style + "'":"") + '>' + (textf?dat[d][textf]:dat[d]) + '</OPTION>\n';
	 
	pd += "</SELECT>\n";
	
	div.innerHTML = pd;
	
	document.getElementById(id).onchange = changeevent;
  }

function MakeCheckBoxes(divid,dat,id,events,numline)
{
 var dv = document.getElementById(divid);
 
 var cb = "";
 var num = 0;
 
 for(d in dat)
  {
	cb += '<input type="checkbox" id="' + id + "_" + d + '" ' + MakeEvents(events) + '>&nbsp;&nbsp;' + dat[d][0];

	if(++num % numline == 0)
	 cb += "<br>";
	else
	 cb += "&nbsp;&nbsp;&nbsp;";
  }
 
 dv.innerHTML = cb;
}
	
function EvalQueryExpr(expr,funcs,idx,dat)
{
 var fun;
 var parms = Array();
 
 for(var i=0;i < expr.length;i++)
  {
	if(i==0)
	 fun = expr[i];
	else
	 {
	  if(expr[i] instanceof Array)
	   {
		 parms.push(EvalQueryExpr(expr[i],funcs,idx,dat));
       }
      else if(expr[i].constructor == String)
       {
	     if(expr[i][0] == "$")
	      {
		    var vref = expr[i].substr(1);
		    
		    if(vref == "k")
		     parms.push(idx);
		    else
		     {
			   var iref = parseInt(vref);
			   
			   if(iref != NaN)
			    parms.push(dat[idx][iref]);
			   else
			    parms.push(expr[i]);
		     }
	      }
	     else
	      parms.push(expr[i]);
       }
      else
	   parms.push(expr[i]);
     }
  }
 return funcs[fun].apply(null,parms);
}
	  
function GenericFilterQuery(dat,funcs,expr)
{
  var dest = {};
  
  for(k in dat)
   if(EvalQueryExpr(expr,funcs,k,dat))
    dest[k] = dat[k];
   
  return dest;
}

function SetDiv(div,value)
{
 document.getElementById(div).innerHTML = value;
}

function SetResponsable()
{
 var poste;
 
 $.getJSON("http://www.defisportif.com/fr/volunteers/2010/ajax.php?action=getresponsable&poste=" + qfuncs.ValueOf("postes") + 
           "&lieu=" +  qfuncs.ValueOf("lieux") + "&type=" + qfuncs.ValueOf("types"),function(dat)
             { 
              SetDiv("resp",dat);
             });
}

function SetDescription()
{
 var poste;
 
 $.getJSON("http://www.defisportif.com/fr/volunteers/2010/ajax.php?action=getdescription&poste=" + qfuncs.ValueOf("postes") + 
           "&lieu=" +  qfuncs.ValueOf("lieux") + "&type=" + qfuncs.ValueOf("types"),function(dat)
             { 
	          if(!dat['empty'])
	           {
	             var txt = "<dt>Dates:</dt>" +dat['dates'] + "<dt>Description:</dt>" +  dat['desc'] + "<dt>Qualités recherchées:</dt>" + dat['qualites']; 
                 SetDiv("PosteDesc",txt);
               }
             });
}

function Matches(row,crit)
{
 
 for(c in crit)
  {
   if(crit[c] != -1 && row[c] != crit[c])
    return false;
  }

 return true;
}

function HasRecord(table,crit)
{
 for(row in table)
  if(Matches(table[row],crit))
   return true;

 return false;
}	 
	 
function UpdateLieux()
{
 var destdat = [];
 
 if(qfuncs.ValueOf("types") == -1)
  destdat = lieux;
 else
  { 
   for(l in lieux)
    {
	 if(HasRecord(site_poste,{"id_site" : lieux[l]["id_lieu"],"type" : qfuncs.ValueOf("types")}))
	  destdat.push(lieux[l]);
    }
  }
  
 MakePulldown("divlieux","lieux",destdat,"id_lieu","nom",LieuChange);
}
 
function UpdatePoste()
{
 var destdat = [];

  for(p in postes)
    { 
	 if(HasRecord(site_poste,{"id_poste" : postes[p]["id_poste"],"id_site" : qfuncs.ValueOf("lieux"),"type" : qfuncs.ValueOf("types")}))
	  destdat.push(postes[p]);
    }
  
 MakePulldown("divpostes","postes",destdat,"id_poste","nom",PosteChange);
}
  
function TypeChange()
{
UpdateLieux();
UpdatePoste();
SetDescription()
}

function LieuChange()
{
UpdatePoste();
SetDescription()
}

function PosteChange()
{ 
SetDescription()	
}

function InitPosteSel()
{
 $.getJSON("http://www.defisportif.com/fr/volunteers/2010/ajax.php?action=getposte",function (dat)
   {
    postes = dat;
	  
    $.getJSON("http://www.defisportif.com/fr/volunteers/2010/ajax.php?action=getsite",function (dat)
     {
	  lieux = dat;
		  
      $.getJSON("http://www.defisportif.com/fr/volunteers/2010/ajax.php?action=gettype",function (dat)
        {
          types = dat;
	        
          $.getJSON("http://www.defisportif.com/fr/volunteers/2010/ajax.php?action=getsiteposte",function (dat)
           {
            site_poste = dat;
            
         	MakePulldown('divtypes','types',types,"id_type","nom",TypeChange);
         	UpdateLieux();
            UpdatePoste();
           });
        });
     });
   });
}

