Question: Do publishers give you an advance as some sort of earnest money for your manuscript? If your work doesn't sell very well do you have to give the advance back to them?

Do they ever just buy your work and you get some money plus royalties?

thanks.

Answer: 
It ***really, really depends on your contract***. There may be some situations, such as you refuse to edit the book or make requested changes and the publisher cancels the contract. The best idea? Negotiate with your publisher so that the advance (against royalties) is yours. If you're contract isn't clear enough about this, press for it to be made more clear.
As someone else stated, it depends on your contract. I had a situation where I received an advance for a book proposal, but personal issues and family matters caused me to miss my deadline, and the publisher requested the money back. I hadn't spent any of it and felt it was the right thing to do because I hadn't delivered as promised. (I was aware beforehand that if I wasn't able to finish the book within a certain time range I would have to refund the advance, which is why I still had it!)

In general, though, once the publisher has accepted the book and you have delivered, the advance is yours to keep. If the book doesn't sell well enough, then the publisher takes a loss. That's one of the reasons why new writers get smaller advances: they are a bigger risk. By the same token, you don't receive another penny from the publisher until the book makes enough money to pay the advance back to the publisher. Only then do you start collecting royalties.