Simplified the JQuery logic and made it more robust.