refactored code according to comments, used _unique and jQuery for cleaner and maintainable code