Use a map to record modalilty for each individual window instead of a global variable.
Also prevent the browser window from closing when there is a JS modal dialog showing.