The structure and electronic density of states in layered LnFeAsO$_{1-x}$F$_x$ (Ln=La,Sm; $x$=0.0, 0.125, 0.25) are investigated using density functional theory. For the $x$=0.0 system we predict a complex potential energy surface, formed by close-lying single-well and double-well potentials, which gives rise to the tetragonal-to-orthorhombic structural transition, appearance of the magnetic order, and an anomaly in the specific heat capacity observed experimentally at temperatures below $sim$140--160 K. We propose a mechanism for these transitions and suggest that these phenomena are generic to all compounds containing FeAs layers. For $x>$0.0 we demonstrate that transition temperatures to the superconducting state and their dependence on $x$ correlate well with the calculated magnitude of the electronic density of states at the Fermi energy.