Alot of blocking code with these for loops.  I bet there is probably a better way to do this. Always try to write you JS as asynchronous and module as possible. Look into a better way.  I will take a further look and provide some suggestions.