Used as a minced oath for the word damn on tv, its been defined as "Expressing frustration at the realization that things have turned out badly or not as planned, or that one has just said or done something foolish. Also (usu. mildly derogatory): implying that another person has said or done something foolish"
Id the phrase, origins and its connection to the question.