model {
  for(i in 1:N) {
    #measurement model
    for(j in 1:P) {
      y[i,j]~dnorm(mu[i,j],errorprec[j])
    }
    mu[i,1]<- lam[1]*xi[i,1]
    mu[i,2]<- xi[i,1]
    mu[i,3]<- lam[2]*xi[i,1]
    mu[i,4]<- lam[3]*xi[i,2]
    mu[i,5]<- xi[i,2]
    mu[i,6]<- lam[4]*xi[i,2]
    mu[i,7]<- lam[5]*eta[i]
    mu[i,8]<- eta[i]
    mu[i,9]<- lam[6]*eta[i]
    #structural model
    xi[i,1:2]~dmnorm(u[1:2],latprec[1:2,1:2])
    nu[i] <- gamma[1]*xi[i,1] + gamma[2]*xi[i,2] + gamma[3]*xi[i,1]*xi[i,2] + gamma[4]*z[i]
    eta[i] ~ dnorm(nu[i], preceta) 
  } #end of i
  for(j in 1:6) {  
    # uninformative priors on loadings
    lam[j]~dnorm(1,0.1)
  }
  for(j in 1:P) {  
    # uninformative priors on errors
    errorprec[j] ~ dgamma(1, 1)
    errorvar[j]<-1/errorprec[j]
  }
  #priors on latent errors
  preceta ~ dgamma(1, 1)
  vareta <- 1/preceta
  #priors on latent (co-)variances
  latprec[1:2,1:2] ~ dwish(V[,], 4)
  latcov[1:2,1:2] <- inverse(latprec[,])
  latcor <- latcov[1,2]/(sqrt(latcov[1,1])*sqrt(latcov[2,2]))
  V[1,1] <- 1
  V[1,2] <- 0
  V[2,1] <- 0
  V[2,2] <- 1
  u[1] <- 0
  u[2] <- 0
  #priors on structural coefficients
  gamma[1] ~ dnorm(1, 0.0001)
  gamma[2] ~ dnorm(1, 0.0001)
  gamma[3] ~ dnorm(1, 0.0001)
  gamma[4] ~ dnorm(1, 0.0001)
} #end of model

