Index: google_admanager.module
===================================================================
--- google_admanager.module	(revision 248)
+++ google_admanager.module	(working copy)
@@ -100,10 +100,9 @@ function google_admanager_admin_settings
  * @return google admanager slot script 
  */ 
 function theme_google_admanager_block($id, $ad_slot) {
-
-  google_admanager_add_js('GA_googleAddSlot("' . $id . '", "' . $ad_slot . '");');
-    
-  return '<script type="text/javascript">GA_googleFillSlot("' . $ad_slot . '");</script>';
+  google_admanager_add_js();
+  drupal_add_js('GA_googleAddSlot("'. $id .'", "'. $ad_slot .'");', 'inline');
+  return '<script type="text/javascript">GA_googleFillSlot("'. $ad_slot .'");</script>';
 }
 
 /**
@@ -115,26 +114,36 @@ function theme_google_admanager_block($i
  * @param $ad_slot string with the addSlot script
  * @return google admanager code 
  */ 
-function google_admanager_add_js($ad_slot = NULL) {
-  static $google_admanager_slots;
+function google_admanager_add_js($fetch_ads = FALSE) {
+  static $header_sent = FALSE;
  
-  if (isset($ad_slot)) {
-    $google_admanager_slots .= $ad_slot;
+  if ($header_sent === FALSE) {
+    //drupal_add_js can't load externaljs in 6, but it will in 7. this is a workaround.
+    $external_js = 'http://partner.googleadservices.com/gampad/google_service.js';
+    drupal_add_js('document.write(unescape("%3Cscript src=\''. $external_js . '\' type=\'text/javascript\'%3E%3C/script%3E"));', 'inline');
+
+    $id = variable_get('google_admanager_account', '');
+    drupal_add_js('GS_googleAddAdSenseService("'. $id .'"); GS_googleEnableAllServices();', 'inline');
+    $header_sent = TRUE;
   }
-  else {
-    if (isset($google_admanager_slots)) {
-      $id = variable_get('google_admanager_account', '');
-      // javascript which is supposed to come in the header
-      $js = '<script type="text/javascript" src="http://partner.googleadservices.com/gampad/google_service.js"></script>' . "\n";
-      $js .= '<script type="text/javascript">GS_googleAddAdSenseService("' . $id . '"); GS_googleEnableAllServices();</script>' . "\n";
-      $js .= '<script type="text/javascript">' . $google_admanager_slots . '</script>' . "\n";
-      $js .= '<script type="text/javascript">GA_googleFetchAds();</script>' . "\n";
-      return $js;
-    }
+
+  if ($header_sent === TRUE && $fetch_ads === TRUE) {
+    drupal_add_js('GA_googleFetchAds();', 'inline');
   }
 }
 
 /**
+ * Implementation of hook_preprocess_page().
+ */
+function google_admanager_preprocess_page(&$vars) {
+  //add fetch ads js
+  google_admanager_add_js(TRUE);
+ 
+  //this doesn't have any effect if another module/theme later overides it. 
+  $vars['scripts'] =  drupal_get_js();
+}
+
+/**
  * Implementation of hook_filter().
  *
  * Filter option to enable Google Admanager filter [google_ad:ad_slot]
