What causes muscle spasms?
According to wikipedia and MedlinePlus muscle cramps can be caused by muscle overuse or injury or dehydration and lack of minerals (eg. potassium or calcium). In this wikipedia page you can read about the mechanism of muscle contraction. I'd emphasize and quote the most important parts here:


  ATP binds to myosin, allowing it to release actin and be in the weak binding state (a lack of ATP makes this step impossible, resulting in the rigor state characteristic of rigor mortis). The myosin then hydrolyzes the ATP and uses the energy to move into the "cocked back" conformation. In general, evidence (predicted and in vivo) indicates that each skeletal muscle myosin head moves 10–12 nm each power stroke, however there is also evidence (in vitro) of variations (smaller and larger) that appear specific to the myosin isoform.
  Steps 9 and 10 repeat as long as ATP is available and calcium is freely bound within the thin filaments.


As you can see ATP is essential in the release of myosin from actin. In case of muscle overuse and dehydration ATP is depleted from the muscle cells and may cause the muscle to cramp.

Also according to this site it is said that repetitive firing of motor units with high frequency is associated with muscle cramps, although tehe origin of this is yet not clear. It can be either from the central nervous system or the peripherial.