Fix logic and convert to jQuery plugin