Some serious refactoring on template editor JS