/*
 * Include this file, preferably near the bottom of an HTML source page/template.
 *
 *    Fetch ads from the adserver:           ATLASAds.request(argument_object);
 *    Display the loaded ads:                foreach (ad requested_ads) { 
 *                                             ATLASAds.showAd(ad);
 *                                             ATLASAds.moveAd(ad);
 *                                           }
 *
 * Notes: 
 *  Because ATLASAds.request() uses document.write, you must close the script
 *    tag in which it's called before calling ATLASAds.showAd()/ATLASAds.moveAd().
 *
 *  The argument_object passed to ATLASAds.request can contain these properties:
 *
 *    area       (string)  - page name, like "ridepage", "toprides", etc. 
 *    country    (string)  - country acronym, if available
 *    domain     (string)  - ???
 *    event_name (string)  - an event name (for area="events")
 *    group_id   (number)  - a group id, on groups pages   
 *    group_tags (array)   - a list of groups tag values
 *    member_id  (string)  - a member id
 *    positions  (array)   - a list of ad position names
 *    ride_id    (number)  - a ride(page) id
 *    site       (string)  - always 'cardomain',
 *    sortby     (string)  - for search results
 *    sotw       (string)  - 'true' or 'false', for ride pages
 *    state      (string)  - state/province acronym, if available
 *    url        (string)  - default is 'http://media.cardomain.com/bserver'
 *    vehicle    (string)  - a car make name or make.model, e.g. "ford", "honda.civic"
 *    year       (number)  - a year number
 *
 * NOTE: the string property values and the group_tags array values should be
 *       composed of letter, number, underscore, and '.' characters only. Any
 *       other character values are converted to underscore ('_').
 * 
 * Example:
 *  ATLASAds.request({
 *    area        : "homepage",
 *    member_id   : "dev_a",
 *    group_tags  : ["You WILL","all","need","ReAdInG","glasses"],
 *    positions   : ['top','frame1','position2','x22']
 *  });
 *
 */    
                                         
ATLASAds = {
  specs      : {
    area          : null,
    country       : null,
    domain        : null,
    event_name    : null,
    group_id      : null,
    group_tags    : null,
    member_id     : null,
    pageurl       : null,
    positions     : [],
    ride_id       : null,
    site          : 'cardomain',
    sortby        : null,
    sotw          : null,
    state         : null,
    url           : 'http://media.cardomain.com/bserver',
    vehicle       : null,
    year          : null
  },
  adSrc      : function() {
    var i,positions=[],specs = ATLASAds.specs;                                    
    var components = [],keywords = [],url;
    var rand = (''+Math.random()).slice(2,10);
    var adSize = {
      left1:      '102x88',
      x21:        '88x31',
      x22:        '88x31',
      x23:        '88x31',
      x02:        '728x90',
      topbanner:  '728x90',
      right:      '160x600',
      right3:     '160x600',
      x01:        '160x600',
      x03:        '160x300',
      x04:        '160x300',
      x05:        '160x307',
      left:       '175x225',
      position3:  '175x420',
      right1:     '175x225',
      right2:     '175x225',
      frame2:     '180x150',
      frame1:     '300x250',
      position1:  '300x250',
      position2:  '300x250',
      middle:     '700x600',
      bottom3:    '728x90',
      top:        '728x90',
      top1:       '728x90',
      x10:        '749x60',
      bottom1:    '700x600'
    };

    function specValue(spec) {
      return spec.replace(/^\s+|\s+$/,'').replace(/[^A-Za-z0-9_\.]/g,'_');
    }      
    for (var prop in specs) {
      switch(prop) {
        case 'group_tags':
          if (specs.group_tags) {
            var tags = [];
            for (var ti=0; ti<specs.group_tags.length; ti++) tags.push(specValue(specs.group_tags[ti]));
            components.push('group_tags=' + encodeURIComponent(tags.sort().join(',').toString()));
          }
          break;
        case 'positions':
          for (i=0; i<specs.positions.length; i++) {                // convert ad names to Atlas format
            var specpos = specs.positions[i];
            positions[i] = specpos.replace(/^/,'AAMB_') + '/position=' + specpos;
            if (specpos in adSize) positions[i] += '/aamsz=' + adSize[specpos];
          }
        case 'url':     
          break;
        default: 
          if (specs[prop]) components.push(prop + '=' + encodeURIComponent(specValue(specs[prop])));
      }
    }
      
    url = specs.url + "/AAMALL/acc_random=" + rand + "/pageid=" + rand +
          "/" + components.join('/');
    if (keywords.length) url += '/keyword=' + encodeURIComponent(keywords.join('$'));
    url += '/' + positions.join('/');
    return url;
  },
  request    : function(specArgs) {  
    var specs = ATLASAds.specs;
    for (var prop in specs) {           
      if (prop in specArgs) specs[prop] = specArgs[prop];
      if (specs[prop] instanceof Array) { // ensure lowercase values
        for (var i=0,spec=specs[prop]; i<spec.length; i++) spec[i] = spec[i].toLowerCase();
      } else if (typeof specs[prop] == 'string') specs[prop] = specs[prop].toLowerCase();
    }
    specs.url = specs.url.replace(/\/*$/,'');
    if (specs.positions.length == 0 || specs.url.length == 0) return;   // missing inputs? then don't document.write
    specs.positions.sort();
    if (specs.group_tags) specs.group_tags.sort();
    document.write('<script type="text/javascript" src="' + ATLASAds.adSrc() + '"><\/script>'); 
  },
  showAd     : function(name) {
    var adVar = window['AAMB_' + name];
    if (typeof adVar == 'string') {
      document.writeln('<div id="'+name+'_tmp">'+adVar+'<\/div>');
    }
  },   
  moveAd     : function(name) {
    var homeDiv = document.getElementById(name + '_spacer'),
        fromDiv = document.getElementById(name + '_tmp'),
        child,next,ad_temp_container;
    if (homeDiv && fromDiv) {
      ad_temp_container = fromDiv.parentNode;    // don't depend on id='ad_handling_container'
      for (child = fromDiv.firstChild; child; child = next) {
        next = child.nextSibling;
        homeDiv.appendChild(child);
      }
      fromDiv.parentNode.removeChild(fromDiv);
    }
    // Sometimes (multiply-nested document.writes?) elements break out of the _tmp div.
    // This catches those.
    if (ad_temp_container) {   
      for (child = ad_temp_container.firstChild; child; child = next) {
        next = child.nextSibling;
        if (child.nodeName.toUpperCase() == 'SCRIPT');  // skip moving extra SCRIPTS
        else if (/.*_tmp$/.test(child.id));             // or our own temp div
        else homeDiv.appendChild(child);
      }
    }
  }
};
