why do dogs wag their tails when they are happy?

I have been searching all day. Anytime I come home, my lovely dog wags his tail when happy.

i will like to know why do dogs wag their tails when they are happy ?