Prioritize top groups when choosing template

When choosing the right template for displaying an instance
the system just took the first appropriate one returned from db.
This behavior is altered such that top groups and groups with better/lower
weights are preferred.