model{
    for(i in 1:nsentinels){  
       for(j in 1:nperiods){      
          O[i,j]~dpois(expected[i,j])
#We add the 0.0001 term in the following line in order to avoid crashes when the
#surveilled population for a sentinel and week is 0 (missing value). 
      	  log(expected[i,j])<-log(p[i,j]+0.0001)+m+t[j]+s[i]+ST[i,j]
          ST[i,j]<-inprod(kernel[i,],theta[,j])
       }
    }

		#contribution of every point of the grid to every observation
    for (i in 1:nsentinels){
       for (k in 1:ngrid){
#the kernel function depends on the distances between sentinels and points of the
#grid. Those will be data in our model.
          kernel[i,k]<-exp(-pow(d[i,k],2)/(2*pow(sdk,2)))/(2.506628*sdk)
       }
    }
    sdk<-40 

		#Prior distribution for the mean risk
		m~dflat()

		#Prior distribution for sentinel effect
		for(i in 1:nsentinels){s[i]~dnorm(0,precs)}
    precs<-pow(sds,-2)
    sds~dunif(0,5)
		
		#prior distribution for the temporal term
		t[1:nperiods]~car.normal(adjt[], weightst[], numt[],prect)
    prect<-pow(sdt,-2)
    sdt~dunif(0,5)

		#prior structure for theta.
#The autoregressive structure has been defined condition both in past and
#future as it seems to yield better convergence properties.
    for(k in 1:ngrid){
			#First Period
      theta[k,1]~dnorm(mean.theta[k,1],prectheta)
      mean.theta[k,1]<-ro*(theta[k,2])

			#Last Period
      theta[k,nperiods]~dnorm(mean.theta[k,nperiods],prectheta)
      mean.theta[k,nperiods]<-ro*(theta[k,nperiods-1])

			#Mid Periods
      for(j in 2:(nperiods-1)){
        theta[k,j]~dnorm(mean.theta[k,j],prec1)
        mean.theta[k,j]<-ro*(theta[k,j-1]+theta[k,j+1])/(1+ro*ro)
      }
    }
    ro~dunif(-1,1)
    prec1<-prectheta*(1+ro*ro)    
    prectheta<-pow(sdtheta,-2)
#The value 100 in the following distribution is appropriate for our implementation
#(it does not condition the posterior distribution of sdtheta). This limit should 
#be chosen with care in new implementations.
    sdtheta~dunif(0,100)	
}