I propose to remove function grid_script with a call to drupal_add_js. The result of the function should be placed in a javascript file. I suppose drupal can cache the file more efficiently.

The content of the attached javascript file, contains minor changes. Most of the modifications are stylistic. I have declared the local variables used in functions in order to have local scope.