Where did pulling your leg come from?

One of the most common of all phrases and mentall vivid is that of pulling someones leg.

Now this is only in English speaking countries and in some other countries the equivalent is to pull someone's hair meaning the same thing, as in Spain tomar el pelo.

So what is the origin of this interesting little phrase then?

It has a criminal background, and those that used to steal from people in crime ridden London in the olden days... they used to literally have wires to trip people up which pulled on their leg, then someone else took their valuables whilst they were feeling rather compromised on the floor.

Over time this stumbling, mishap and the comical effect of someone falling over came to be adapted slightly to making fun of someone in general, and hence the origin of the phrase.