I usually trust
Wikipedia for this sort of thing. There's a few screenfuls on the etymology of the word 'gay' at the beginning of the article I linked to above. Short answer, "when" was in the 1920s. "Why" is hard to say, but "how" is described in the article.