Fix attempt for cordova 3.3+ bugs (#38, #40)

Ported changes suggested by @krtek in issue #40. This code works in
Chrome, hasn't been tested on Cordova yet (sorry, missing time to create
a proper test environment).
Refactored some code to make it easier for future fix attempts.