### This is the JAGS code - written in bugs language - to fit the full dynamic occupancy model
### The basic structure is a autologistic formulation for temporal dynamics, a multi-species/area 
### to deal with all time-series simultaneously, and a Bayesian LASSO to select fixed effects for predictors


model {  

	for (h in 1:nsite){
		psi[index[h]] ~ dunif(0,1)  ## initial occupancy was drawn from a uniform distribution for the first year in each time-series
		for (g in (index[h]+1):(index[h+1]-1)) {
		  	logit(psi[g]) <- int[group[g]] + auto[group[g]]*z[g-1] + inprod(beta,CD[g,])   ## the dynamic occupancy model was used to predict occupancy in following years and included the group level intercept, group level autologistic parameter (i.e., the difference between colonization and persistence) and the fixed effects part of the model beta*CD
		}
	}
	for (i in 1:nobs){
		z[i] ~ dbern(psi[i])    #### the true latent occupancy state at each observation 
		P[i] <- p[groupyear[i]]*z[i] ### the probability of detection during a visit 
		D[i] ~ dbin(P[i],N[i])  ### the expected number of detections out of N visits to a site
	}
	for (j in 1:ngroup){
		int[j] ~ dnorm(muint,tauint)   ### random effect for intercept values
		auto[j] ~ dnorm(muauto,tauauto)  ### random effect for autologistic effect
	}
	for (k in 1:ngroupyear){
		det[k] ~ dnorm(mup,taup)	### random effect for group and year specific detection probabilities on a logit scale
		logit(p[k]) <- det[k]		### logit transformation to get the probability of detection given the species was present at the site
	}

 ### PRIORS 
	mp ~ dunif(0,1)
	mint ~ dunif(0,1)
	
	mup <-  log(mp) - log(1-mp) 
	muint <-  log(mint) - log(1-mint) 



	taup <- pow(sigp,-2)
	tauint <- pow(sigint,-2)
	tauauto <- pow(sigauto,-2)
	muauto ~ dnorm(0,0.001)
	sigp ~ dunif(0.01,3)
	sigint ~ dunif(0.01,3)
	sigauto ~ dunif(0.01,3)

### Fixed effects
### intercept values 
  for (a in 1:17){
      beta[a] ~ dnorm(0,0.01)
    }
### interactions between climate and our predictor variables - LASSO used for regularization
  for (a in 18:77){
      beta[a] ~ ddexp(0,lambda)  ### prior for Bayesian LASSO - 
    }

  lambda ~ dunif(0,100)  


}



