A variational principle for the dynamics and thermal behavior of viscous media