Refactored popup JavaScript