Refactor of shameful js code