keep the popup template inside the viewport

This solves the problem with the popupTemplate overflowing to the right or in the bottom.

It should work most places and it seems to work for me.

Any feedback?

I couldn't figure out how to write tests for this.