Code quality improvements

The improvements mostly include fixed warning from JSHint and some refactoring of complex code blocks.