/* ******************************* *
 *  Cars.com ad tag generator
 *  Created: 10 SEP 2010
 *  Version: 0.1
 *  This file creates consistent
 *  ad logic for generated DFP
 *  tags for Cars.com ad serving
 * ******************************* */

/* helper for building namespaces
 * accepts period-separated string
 */
addNamespace = function(name){
  var ns = name.split('.');
  var c = window;
  for (var i in ns) {
    if (!c[ns[i]]) { c[ns[i]] = {}; }
    c = c[ns[i]];
  }
};
// build namespaces
addNamespace('CARS.adtag');

// helper function to get top level domain value - should move to common lib
CARS.getTLD = function() {
  return window.location.host.match(/[^\.]+\.\w{2,3}$/)[0];
};
// helper function to get web property name - should move to common lib
CARS.getPropertyName = function() {
  return window.location.host.match(/(www\.)?(.*)/i)[2];
};

// NS for ad logic
CARS.adtag = {
//http://ad.doubleclick.net/adj/cdn.cars.buy.used/results;site=cars.com;sz=1x1;detail=fdm;aff=boston;zc=02458;make=acura;catret1=luxury;catret2=midsize;catret3=crossover;area=buy.used.all.results/lang=en;tile=1;ord=1284393079073?
  adRootURL: 'http://ad.doubleclick.net/adj/',
  // function for generating/retrieving ORD value
  // returns: ord (int)
  getORD: function() {
    this._ord = this._ord || new Date().getTime();
    return this._ord;
  },
  // function for generating/retrieving tile value
  // returns: tile value (int)
  getTile: function() {
    this._tile = this._tile || 0;
    this._tile += 1;
    return this._tile;
  },
  // function for calculating site/zone information from current page
  // returns: object with site and zone properties
    getSiteZone: function() {
    var sz = { site: 'cdn.cars.other', zone: 'default' };
    switch(CARS.getPropertyName()) {
      case 'motherproof.com':
        sz.site = 'cdn.motherproof';
        break;
      case 'blogs.cars.com': 
        sz.site = 'cdn.blogs';
        sz.zone = 'kickingtires';
        break;
	case 'ask.cars.com': 
        sz.site = 'cdn.blogs';
        sz.zone = 'askblog';
      break;
      case 'repairpal.com':
        sz.site = 'cdn.repairpal';
        break;
      default:
        break;
    }
    switch(CARS.getTLD()) {
      case 'pickuptrucks.com': 
        sz.site = 'cdn.pickuptrucks';
        break;
    default:
      break;
    }
   return sz;
  },
  // function for generating ad tag request URL
  // 'kv': bundle of key/values
  // 'debug': activates console.log output of URL
  // returns: url (string)
  generateRequestURL: function(kv,debug) {
    var tvalues = '';
	siteZone = this.getSiteZone();  //or this.siteZone || this.getSiteZone();
    // clean up size-less tag drops
    if (kv.sz === undefined) {
      kv.sz = '1x1';
    }
    // append sent in targeting values
    for (var i in kv) {
      switch (i) {
        case 'site':
          siteZone.site = kv[i];
          break;
        case 'zone':
          siteZone.zone = kv[i];
          break;
        default:
          tvalues += i + '=' + kv[i] + ';';
          break;
      }
    }
    // create root url
    var myURL = this.adRootURL + siteZone.site + '/' + siteZone.zone + ';';
    // append additional targeting values
    myURL += tvalues.replace(/\s/gi,'');
	
		/*****	u= param is for Yieldex.  
					The position of the vals are the key map...pipes hold order !it must follow this pattern:
		aamsz | adPos | adAffiliate | lzone | dlid | RAID | make | model | cat | catRetNames | accdetail | area | priceBand | milesBand | year | zip | lang
		lowerCase, no spaces, dashes or characters 	
		*****/
    // append u/tile/ord values (must be last)
    myURL += 'u=' + kv.sz + '||||||||||||||||;tile=' + this.getTile() + ';ord=' + this.getORD() + '?';
    // debug output
    if (debug && window.console) { console.log('ad call: ' + myURL.toLowerCase()); }
    return myURL.toLowerCase();
  },
  // function for dropping ad tag
  // executes a document.write of script ad tag
  // 'j': json-formatted params
  //    params: site,zone,sz,etc
  // 'd': array of dom IDs to drop ad tags into
  // returns: null
  drop: function(kv,d) {
    kv = (typeof kv == 'object') ? kv : {};
    var el = [];
    // use script container if container not defined
    if (!d) {
      var scripts = document.getElementsByTagName("script");
      d = scripts[scripts.length-1].parentNode;
      d.id = d.id || 'cad' + new Date().getTime();
      el.push(d);
    } else {
      // check if it's just one id
      if (typeof d == 'string') {
        el.push(document.getElementById(d));
      }
      // check for array of ids
      if (typeof d == 'object') {
        for (var i=0; i < d.length; i++) {
          el.push(document.getElementById(d[i]));
        }
      }
    }
    // console.log(el);
    for (var j=0; j < el.length; j++) {
      document.write('<scr'+'ipt'+' type="text/javascript" '+'src="'+this.generateRequestURL(kv)+'"'+'></scr'+'ipt>');
    }
  }
}
