The Talmud teaches that at the beginning of the Sabbath, the
special sanctification (Kiddush) is recited  and after the termination
of the Sabbath the Havdalah ("distinction") benediction
signifying the separation of the Sabbath from the weekday
is recited . Both are recited over a cup of wine.
Detail from medieval manuscript,
c14th century, Spain
The Babylonian Talmud elaborates that the "distinction" blessing was
originally inserted in the "'Amidah" prayer at the evening service
of a day following one of greater holiness; the prevailing custom, however,
was to recite the Havdalah ceremony at home over a cup of wine, while only making
mention of it in the Amidah. 
At a later date, it became customary to recite the Havdalah
over a cup of wine in the synagogue as well, in order to exempt those who
had no wine in their home: "when [the people] became richer
they instituted that it should be said over the cup of wine; when they became
poor again they inserted it again into the prayer."
 Today the ceremony is generally recited at home.
Havdalah over a cup of wine is also customary when the Sabbath
is immediately followed by a festival, since the festival's stringency is
less than that of the Sabbath.  Combined in this case with the festival
Kiddush, the blessing distinguishes "between holy and holy" as opposed
to "between holy and profane." The order of this Kiddush-Havdalah
is indicated by the well-known acrostic yaknehaz
yayin (wine), Kiddush, ner
(candle), Havdalah, zeman (season=she'heheyanu).  When the
end of the festival is followed by a working day, Havdalah is recited wine
wine only, i.e., without candle or spices.
There are several customs involving the wine: pouring of some
of the wine on the ground as an omen of blessing, overfilling the cup as an
omen of plenty and prosperity, passing the last drop of wine in the cup over
the eyes; and extinguishing the lamp with the remaining drops.