// $Id: demandbase.js 23401 2010-01-22 16:14:59Z  $

// Demandbase data

// if doubleclick_ads.js didn't create this already (e.g. running in wrong order), do it here
try {		// was seeing inconsistent errors here
	if (! extraAdKeys) var extraAdKeys = Array();
} catch(e) { var extraAdKeys = Array(); }

var dbase_data = null;  // needed for ads and omniture

function dbase_parse(data) {    // callback for demandbase api
  dbase_data = data;
	// console.dir(dbase_data);

	try {		// was seeing inconsistent errors here, this should fix
		if (extraAdKeys) {
			extraAdKeys[extraAdKeys.length] = 'compsz=' + escape(getDbaseVar('company_size'));
			extraAdKeys[extraAdKeys.length] = 'indust=' + escape(getDbaseVar('industry'));
			extraAdKeys[extraAdKeys.length] = 'empcnt=' + escape(getDbaseVar('employee_count'));  // diverts to _dbase_empcnt()
          //console.log("final empcnt: " + extraAdKeys[extraAdKeys.length-1]);
	  }
	} catch(e) {}

	// legacy / hack for externals (relies on doubleclick_ads.js running BEFORE this)
	try {
		if (processAdUrl) {
			_rval = processAdUrl('');
			rval = _rval;
		}
	} catch(e) {}
}

/**
 * get a specific var from the data
 * variable args: pass in cascading options, 1st successful returned
 */
function getDbaseVar() {
	if (! dbase_data) return '';
	for(var i=0; i < arguments.length; i++) {
		arg = arguments[i];
		// if (console) console.log("testing " + arg);
		if (arg != "" && arg != null) {
			if (dbase_data[arg]) {

  		  // special case for employee count -- divert to _dbase_empcnt()
  		  // (doing here to support legacy/outside calls to getDbaseVar('employee_count'))
  		  if (arg == 'employee_count' || arg == 'empcnt') return _dbase_empcnt(dbase_data[arg]);
  		  
				return dbase_data[arg];
			}
		}
	}
	return '';
}

/**
 * special logic for employee count variable
 * convert raw # to range
 * diverted to here from getDbaseVar() to support legacy/outside calls,
 * -- not meant to be called directly --
 * (empcnt passed in to avoid infinite loop)
 */
function _dbase_empcnt(empcnt) {
  try {
	  //alert("empcnt:"+empcnt);
    //console.log("employee count: "+empcnt);
     if (! isNaN(empcnt)) {   // a number
       if (empcnt >= 1000) return '1000+';
       else if (empcnt < 1000 && empcnt >= 500) return '500-999';
       else if (empcnt < 500 && empcnt >= 100) return '100-499';
       else return '1-99';
     }
  } catch(e) {}
 return '';   // invalid or other
}
