
/* text ad skip param, to avoid duplicate ads on pages with more than one text
   ad unit */
var google_skip = 0;

var Ad = function() {
  /* Used to cache and keep track of the next empty adsense unit */
  var nextAdUnit = 0;
  var maxAdUnit  = 10;  // optimization, we will never have more than 10 ad units on one page
  var nextLinkUnit = 0;
  var maxLinkUnit = 3;  // optimization, we will never have more than 3 link units on one page
  var kw_type;
  var textAdCount = 0;  // to give each ad a unique id
  
  /* Records the total number of adsense text ads, so google_skip can be properly
     set for pages with more than two ad units */
  var skipTotal = 0;
  
  /* Assign any google adsense parameters */
  function assignGoogleParams() {
    google_skip = skipTotal;
    return;
  }
  
  /**
   * uses globals nextLinkUnit, maxLinkUnit
   * @return the next link unit element to fill, or false if there are no
   *         available link units (should never happen)
   */
  function getNextLinkUnit() {
    var el;
    for(; nextLinkUnit < maxLinkUnit; nextLinkUnit++) {
      el = document.getElementById('link_unit'+nextLinkUnit);
      if(el) {
        nextLinkUnit++; // get ready for next link unit placement
        return el;
      }
    }
    return false;
  }
  
  /**
   * uses globals nextAdUnit, maxAdUnit.  Checks up to 'maxAdUnit' units, 
   * skipping unused units (ie, could have units 0, 2, 5 and they will be
   * used in order.
   * 
   * @return the next element to fill with an adsense ad, or false if there are no 
   *         available ad units (should never happen)
   */
  function getNextAdUnit() {
    var el, adPlaced = false;
    for(; nextAdUnit < maxAdUnit; nextAdUnit++) {
      el = document.getElementById('ad_unit'+nextAdUnit);
      if(el) {
        nextAdUnit++;  // get ready for next ad request
        return el;
      }
    }
    return false;
  }
  
  function addClasses(el,classes) {
    if(el.className) el.className += ' ' + classes;
    else el.className += classes;
    return el;
  }
  
  
  return {
    /* Google adsense api callback, invoked when either content ads _or_ link
       unit ads are returned.  In the case of link unit ads being returned,
       google_ads.length will be '0' */
    google_ad_request_done: function(google_ads) {
      var i,unit,adClass;
      // ad markup
      var s = '';
      
      // handle keyword ad units
      if(window.kw_type == 'radlink') {
        window.kw_type = null;
        unit = document.getElementById('sponsored_links_unit');
        adClass = 'radlink';
      } else {
        // an ad to display, and no place to put it, should never happen.
        // TODO: perhaps just stick it in a default place?
        if((unit = getNextAdUnit()) === false) return assignGoogleParams();
        else if(unit)
          // determine the ad unit type so we can style properly 
          adClass = unit.className;
      }
      
      // Verify that there are actually ads to display.  This is done after the
      //  ad unit is determined so that in the rare case that no ads are 
      //  returned, any following ad requests are placed in their correct units
      if (google_ads.length == 0) return assignGoogleParams();
      
      // generate html based on the type and count of ad
      if (google_ads[0].type == "image") {
        addClasses(unit,'adUnit mad');
        s += '<div style="display:none" class="'+adClass+'"><a href="' + google_ads[0].url + '" title="go to ' + google_ads[0].visible_url +'">'+
               '<img border="0" src="' + google_ads[0].image_url + '" width="' + google_ads[0].image_width + 
                 '" height="' + google_ads[0].image_height + '"></a><div class="abgi">Ads by Google</div></div>';
        unit.style.margin='0 auto';
      } else if (google_ads[0].type == "flash") {
        addClasses(unit,'adUnit mad');
        s += '<div style="display:none" class="'+adClass+'"><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' +
             ' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"' +
             ' width="' + google_ads[0].image_width +
             '" height="' + google_ads[0].image_height + '">' +
             '<param name="movie" value="' + google_ads[0].image_url + '">' +
             '<param name="quality" value="high">' +
             '<param name="AllowScriptAccess" value="never">' +
             '<embed src="' + google_ads[0].image_url +
             '" width="' + google_ads[0].image_width +
             '" height="' + google_ads[0].image_height +
             '" type="application/x-shockwave-flash"' +
             ' AllowScriptAccess="never" ' +
             ' pluginspace="http://www.macromedia.com/go/getflashplayer"></embed></object><div class="abgi">Ads by Google</div></div>';
         
        unit.style.margin='0 auto';
      } else if (google_ads[0].type == "text") {
       
        // set the ad unit class name based on the number of ads, so that the proper styling is applied
        if(adClass)
          addClasses(unit,'adUnit '+adClass+google_ads.length);
        else addClasses(unit,'adUnit');
       
       skipTotal += google_ads.length;  // don't skip over sponsored links
       
       if(adClass == 'dbl-stacked') {
         // 2x2 table of ads
         s += '<table class="ads">';
         for(i=0; i < google_ads.length; i++) {
           if(!(i%2)) s += '<tr>';
           s += '<td>'+
                  '<div class="ad" onmouseover="Ad.ss(\''+google_ads[i].visible_url+'\')" onfocus="Ad.ss(\''+google_ads[i].visible_url+'\')" onmouseout="Ad.cs()" onclick="Ad.ga(\'aw'+textAdCount+'\')">'+
                    '<a id="aw'+textAdCount+'" href="'+google_ads[i].url+'" class="adt" title="'+google_ads[i].line2+' '+google_ads[i].line3+'">'+
                      '<span>'+google_ads[i].line1+'</span>'+
                    '</a>'+
                    '<div class="adb">'+google_ads[i].line2+(adClass == 'leader' && google_ads.length > 1 ? '<br/>' : '&nbsp;')+google_ads[i].line3+'</div>'+
                    '<div class="adu"><a href="'+google_ads[i].url+'" title="'+google_ads[i].line2+' '+google_ads[i].line3+'">'+google_ads[i].visible_url+'</a></div>'+
                  '</div>'+
                '</td>';
           if((i%2) || i == google_ads.length-1) s += '</tr>';
         }
         s += '<tr><td>Ads by Google</td></tr></table>';
       } else {
         // regular list of ads
         s += '<div class="ads"><ul>';
         for(i=0; i < google_ads.length; ++i) {
            s += '<li onmouseover="Ad.ss(\''+google_ads[i].visible_url+'\')" onfocus="Ad.ss(\''+google_ads[i].visible_url+'\')" onmouseout="Ad.cs()" onclick="Ad.ga(\'aw'+textAdCount+'\')">'+
                   '<div class="ad">'+
                     '<a id="aw'+textAdCount+'" href="'+google_ads[i].url+'" class="adt" title="'+google_ads[i].line2+' '+google_ads[i].line3+'">'+
                       '<span>'+google_ads[i].line1+'</span>'+
                     '</a>'+
                     '<div class="adb">'+google_ads[i].line2+(adClass == 'leader' && google_ads.length > 1 ? '<br/>' : '&nbsp;')+google_ads[i].line3+'</div>'+
                     '<div class="adu"><a href="'+google_ads[i].url+'" title="'+google_ads[i].line2+' '+google_ads[i].line3+'">'+google_ads[i].visible_url+'</a></div>'+
                   '</div>'+
                 '</li>';
            textAdCount++;
          }
          
          // this is where the feedback url would go.  doesn't really fit for the image/flash ads
          s += '</ul></div><div class="abgi">Ads by Google</div>';
        }
      }
      
      // display the ad within the current unit
      unit.innerHTML = s;
      unit.childNodes.item(0).style.display='block';
      
      // set google adsense params for the next (if any) request
      return assignGoogleParams();
    },
    
    /**
     * Track adclicks through analytics
     * to enable this, just add: onclick="Ad.urchinTrack(\''+google_ads[i].visible_url+'\')" to the ad links
     * Then pages such as /adsense/ads/www.telemedicus.com should start 
     * appearing in google analytics top content indicating what people are
     * clicking on.  (not currently used)
     */
    urchinTrack: function(url) {
      if(url && window.urchinTracker) urchinTracker('/adsense/ads/'+escape(url));
    },
    
    /* SetStatus.  really only works on IE6 */
    ss: function(w) {
      window.status = w;
    },
    
    /* ClearStatus.  really only works on IE6 */
    cs: function(){
      window.status='';
    },
    ga: function(id) {
      location.href=document.getElementById(id).href;
    },
    
    /**
     * Google adsense link unit callback 
     * These are the clickable keywords that bring you to the sponsored links result page
     * globals used: 
     *  num_radlinks_per_unit comma-delimited list of integers specifying the number of
     *                        links per ad unit on the page, or undefined if there is a
     *                        single unit
     */
    google_radlink_request_done: function(radlinks) {
      if (radlinks.length < 1) return;
      
      // if num_radlinks_per_unit is not defined, assume one unit with all the links
      if(typeof num_radlinks_per_unit == 'undefined') num_radlinks_per_unit = new Array(radlinks.length+'');
      
      var i,j,el,index = 0;
      for(i = 0; i < num_radlinks_per_unit.length; i++) {
        if(!(el = getNextLinkUnit())) return;  // out of link unit elements... shouldn't happen
        
        var s ='<span id="link_unit_title">Related Ads</span><ul>';
        for(j = 0; j < num_radlinks_per_unit[i] && index < radlinks.length; j++, index++) {
          s += '<li><a target="_top" href="/results.php?kw=' + radlinks[index].url_escaped_term + 
                '&rt=' + radlinks[index].radlink_token + '&page_url=' + window.location + 
                '">' + radlinks[index].term + '</a></li>';
        }
        s += '</ul>';
        
        el.innerHTML += s;
      }
      
      // must keep google parameters assigned through every call
      return assignGoogleParams();
    }
  };
}();

// assign the functions we defined within our 'Ad' namespace to the callbacks required by google
var google_ad_request_done = Ad.google_ad_request_done;
var google_radlink_request_done = Ad.google_radlink_request_done;


function popupWindow(url,width,height,windowName,x,y){
  var windowFeatures = "width="+width+",height="+height+","+"screenX="+x+",screenY="+y+",top="+x+",left="+y;
  windowFeatures+=",scrollbars=no,resizable=no,status=no,menubar=no,toolbar=no,location=no,directories=no,dependent=no";
  var o=window.open(url,windowName,windowFeatures);
  o.focus();  // window.focus();
}
