There are number of factors that go into deciding who is going to have legal custody of the minor child. The most important item and determining factor is the best interest of the child standard. The court will also utilize experts to evaluate the situation and to report back to the court. These individuals include guardians ad litem, child representatives, social workers, and psychologists.
The video below talks in general terms about how custody is decided in a contested matter.