 /** WP:
 *
 *  common_ads.js 0.1
 *
 *  Constructor:
 *
 */

function COMMON_AD ( ) {
  this.swap_list = [];
  

  /**
   * getAgeFromRDBCookie returns the age from the RDB cookie based on either the age, or the year of birth
   *
   * @param RDBCookie the cookie string
   * @returns age {number} age from the cookie or 0 if not found
   */
  this.getAgeFromRDBCookie = function(RDBCookie) {
    var age = 0, 
        rdb = RDBCookie, 
        h2d = whitepages.common.hex2dec;
    if (rdb) {
      if (h2d(rdb[9]) > 0) {
        age = h2d(rdb[9]);
      } else if (h2d(rdb[21]) > 0) {
        var now = new Date();
        age = now.getFullYear() - h2d(rdb[21]);
      }
    }
    return age || 0;
  }
  
  /**
   * renderForIE renders the ad position for IE 
   */
  this.renderForIE = function(div_name, code, invObj) {
    document.getElementById(div_name).innerHTML +=
      '<div id="TMP' + div_name + '" style="display:none">' + 
      escape('<body><div id="adDiv">' + code + '</div>') +
      '</div><iframe name="' + invObj + '"width="0" height="0" frameborder="0" ' +
      'onload="javascript: COMMON_AD.relocateAd(this, \'' + div_name + '\');"></iframe>';
      window.frames[invObj].document.location = 
      'javascript:unescape(parent.document.getElementById(\'TMP' + 
      div_name + '\').innerHTML)';
  }

  /**
   * renderForOther renders the ad position for browsers other than IE
   */
  this.renderForOther = function(div_name, code, invObj) {
    document.writeln('<div id="' + invObj + '" style="display:none">' +
                     code + '<script type="text/javascript" defer="true">' +
                     'document.getElementById(\'' + div_name + '\').innerHTML = ' +
                     'document.getElementById(\'' + invObj + '\').innerHTML;' +
                     'document.getElementById(\'' + invObj +
                     '\').innerHTML = \'\';</scr' + 'ipt></div>');
  }

}


/**
 * STATIC METHODS
 */


/**
 * relocateAd is an Atlas method for rendering ads for IE into their appropriate positions on the page.
 * This script is from Atlas but has been stuffed in here for code organization and namespace reasons.
 * 
 */
COMMON_AD.relocateAd = function(iframeObj, divName) {
  var iframeDoc,
  allScripts;
  iframeDoc = iframeObj.contentWindow.document;
  allScripts = iframeDoc.getElementsByTagName('script');
  for (s = 0; s < allScripts.length; s++)
    if (allScripts[s].src)
      allScripts[s].src = '';
  document.getElementById(divName).insertAdjacentElement('beforeEnd', iframeDoc.getElementById('adDiv'));
  // Added to fix display issues, hides the iframe after rendering so nothing is inherited
  iframeObj.style.display = 'none';
}

/**
 * render_interstitial is a special helper to render the interstitial ad with all of its fade-magic.
 */
COMMON_AD.render_interstitial = function(elAdDiv, code, invObj) 
{
  // Only render the interstital if the code from atlas contains an actual ad.
  // Atlas will serve up a blank gif if there is no ad flighted. Use a regex to check for it and don't show interstitial if it's there.
  if (!/AE\d\.gif/.test(code)) {
    // Set a cookie so this doesn't happen again for the duration of the wp_interstitial cookie
        
    // TEMP: 
    whitepages.common.setCookieData('wp_interstitial', 'viewed_interstitial', true);
    
    $('#logo').css('zIndex',10001);
    // Initialize the styles of the interstitial layer and then fade it in.  This is chained to save DOM searches
    $('#interstitial_ad').appendTo('body').css('position', 'absolute').width('100%').height('100%').css('zIndex',10000).hide().css('opacity', 1).fadeIn(1000, function () {
        // once our layer has faded in show the internal parts
        $('#interstitial_close').show();  // close button
        $('#interstitial_instruct').show(); // instructions

        // Close the interstitial layer 15 seconds after it opens.
        setTimeout(function () {
            // TEMP:  
            $('#interstitial_ad').fadeOut(500);
          }, 
          15000
        );
    });
  }
}

/**
 *
 */


/** WP: 
 *
 *  Fields: 
 *
 */
COMMON_AD.prototype.swap_array = {};
COMMON_AD.prototype.listing = {};
COMMON_AD.prototype.attrs = ['href', 'src', 'value']; /** WP: Check these attributes for __TOKEN__ */


COMMON_AD.prototype.render_wpn_ad = function ( div_name, aamb_tag ) {
  var invObj = 'INV' + div_name;
  try {
    var code = eval(aamb_tag);

    if ( this.swap_list[div_name] instanceof Object ) {
      code = this.swap_incode(div_name,code);
    }

    var elAdDiv = document.getElementById(div_name);

    var specialSize = ['text_link',
                       'endemic_panel',
                       'search_module',
                       'top_rail_link',
                       'pop_under',
                       'results_custom_right_rail',
                       'teaser_link',
                       'bresults_link'];

    var exclusionRegex = new RegExp(specialSize.join('|'));
    
    if ((typeof(code) != 'undefined') && (elAdDiv !== null)) {
      if (navigator.userAgent.indexOf('MSIE') != -1) {
        // RENDER FOR IE
        if (div_name.match(exclusionRegex)) {
          document.write('<div id="' + invObj + '" style="display:none">' + code + '</div>');
          elAdDiv.appendChild(document.getElementById(invObj)).style.display = '';
        } else if (div_name.match('interstitial')) {
          this.renderForIE(div_name, code, invObj);
          COMMON_AD.render_interstitial(elAdDiv, code);
        } else {
          this.renderForIE(div_name, code, invObj);
        }
      } else {
        // RENDER FOR OTHER BROWSERS
        if (div_name.match(exclusionRegex)) {
          elAdDiv.innerHTML = code;
          document.write('<div id="' + invObj + '" style="display:none">' + code + '</div>');
        } else if (div_name.match('interstitial')) { 
          this.renderForOther(div_name, code, invObj);
          COMMON_AD.render_interstitial(elAdDiv, code);
        } else {
          this.renderForOther(div_name, code, invObj);
        }
      }

    }
  }
  catch(aamErr) { 
    // alert(aamErr)
  }
}

/** WP:
 *
 * OAS ads are served as the page content is rendered, and Atlas 
 * after the page content is rendered. For backwards compatability
 * with OAS, swap_values() is still called as the page is rendered.
 * This populates this.swap_list which Atlas uses after the 
 * page content is rendered.
 *
 */


/** WP:
 *
 *  Set swap keywords in generated ad content for listing values.
 *
 */
 
COMMON_AD.prototype.swap_values = function ( div_id ) {
  /** WP:
   *
   *  First store the data
   *  (note that the DIV ID is different than the ones we create
   *  normally in this object, this is because multiple ad
   *  positions may be handled within one div):
   *
   */
  this.swap_list[div_id] = {};

  for (var i = 1; i < arguments.length; i += 2) {
    this.swap_list[div_id]['__' + arguments[i] + '__'] = arguments[i+1];
  }
  this.token_replace(div_id);
}

/** WP:
 *
 *  Swap keywords in generated ad content for listing values.
 *
 */
 
COMMON_AD.prototype.swap = function ( div_id ) {
  var div = document.getElementById( div_id );
  listingData = this.swap_list[div_id];
  /** WP: Get children from the DOM */
  this.checkNodeList( div.childNodes, listingData );
}

COMMON_AD.prototype.checkNodeList = function ( nodeList, listingData ) {
  for ( var i=0, len=nodeList.length; i<len; i++ ) {
    this.checkNode( nodeList[i], listingData );
  }
}

/** WP: Swap the listing information inside a very large string (or ad) */
COMMON_AD.prototype.swap_incode = function ( div_name, big_string ) {
  listingData = this.swap_list[div_name];
  for ( key in listingData ) {
    var re = new RegExp("__"+key+"__",'g');
    big_string = big_string.replace(re,listingData[key]);
  }
  return big_string;
}

/** WP: Check the attributes for each element */
COMMON_AD.prototype.checkNode = function ( node, listingData ) {
  if ( node.nodeType == 3 ) {
    for ( key in listingData ) {
      if ( node.nodeValue.match('__' + key + '__') ) {
        node.nodeValue = node.nodeValue.replace( '__' + key + '__', listingData[key] );
      }
    }
  }
  else {
      for ( var k=0, leng=this.attrs.length; k<leng; k++ ) {
        if ( node.attributes[ this.attrs[k] ] ) {
          for ( key in listingData ) {
            if ( node.attributes[this.attrs[k]].value.match('__' + key + '__') ) {
              node.attributes[this.attrs[k]].value = node.attributes[this.attrs[k]].value.replace( '__' + key + '__', listingData[key] );
            }
          }
        }
      }
  }

  if ( node.hasChildNodes() ) {
    this.checkNodeList( node.childNodes, listingData );
  }
  /** WP:
   *
   * If element nodetype = text, check the text
   * If element has children, run the loop again
   */
}

COMMON_AD.prototype.set_swap_object = function ( div_id, obj ) {
  /** WP:
   * 
   * Put comma separated values into an array and build a multidimensional array. Since the ads are rendered
   * after the page content is loaded, __TOKEN__ replacement will need to occur after the page content is
   * rendered also.
   *
   */
  this.swap_list[div_id] = obj;
  return;
}

COMMON_AD.prototype.swap_after_content = function ( ) {
  var swapRegex = new RegExp("resultslink");
  for ( var div_id in this.swap_list ) {
    if ( div_id.match(swapRegex) ) {
      this.token_replace( div_id );
    }
  }
}

COMMON_AD.prototype.token_replace = function ( div_id ) {
  var div = document.getElementById(div_id);

  if(div)
  {
    for (var tag in this.swap_list[div_id])
    {
      var regexp = new RegExp(tag, 'g');
      /** WP:  why not have txt defined inline below??? */
      div.innerHTML = div.innerHTML.replace(regexp, this.swap_list[div_id][tag]);
    }
  }
}

COMMON_AD.prototype.get_quantcast_demo_at_cookie_values = function (){
  try{
    var tag_map = this.create_new_atlas_tag_map();

    var qc_possible_cookies = jQuery.grep(document.cookie.split(";"), function(a){ return a.indexOf("wp_qc_demo_at") > 0; });

    if(qc_possible_cookies.length < 1)
    {
         return tag_map;
    }

    var qc_c = qc_possible_cookies[0];
    var qc_kv_string =  qc_c.split("=")[1].replace(/%3D/g,"=").replace(/%2C/g,",");
    var mapper_func = function(kv){ 
        var vs = kv.split("="); 
        tag_map[vs[0]] = vs[1]; 
    };
    jQuery.map(qc_kv_string.split(","), mapper_func);
    return tag_map;
  } catch(err) {
    if(console && console.log){
      console.log("Error in COMMON_AD.prototype.get_quantcast_demo_at_cookie_values", err);
    }
    return this.create_new_atlas_tag_map();
  }
};

COMMON_AD.prototype.get_atlas_tag_uri_string = function(){
  var qc_params = this.get_quantcast_demo_at_cookie_values();
  var rdb_params = this.get_rdb_params_as_atlas_tag_map();
  /* Merge any rdb_params together with quantcast ignoring rdb data if quantcast has data for that position */
  jQuery.each(['gn','us','connspeed','age','car','chh','hh','edu','zip_code'], function(idx, k){

    if(jQuery.trim(qc_params[k]) !== ""){
      return true; /* we prefer quantcast data over survey data so skip ahead */
    }
    /* use whatever we have from rdb cookie */
    qc_params[k] = (typeof(rdb_params[k]) === 'string') ? jQuery.trim(rdb_params[k]) : "";
    return true;
  });
  return qc_params.to_atlas_query_string();
};

COMMON_AD.prototype.create_new_atlas_tag_map = function () {
 return {
          to_atlas_query_string : function(){
            return "/" + [ 
            'gn=' + this.gn,
            'age=' + this.age,
            'hh='+ this.hh,
            'chh='+ this.chh,
            'edu='+ this.edu,
            'zip_code='+this.zip_code,
            'us='+ this.us,
            'connspeed='+this.connspeed,
            'car='+ this.car
            ].join("/");
          }, 
          zip_code : "",
          gn : "",
          us : "",
          connspeed : "",
          age : "",
          car :"",
          chh : "", 
          hh : "", 
          edu : ""
         };
};

COMMON_AD.prototype.get_rdb_params_as_atlas_tag_map = function () {
  try
  { 
    var tag_map = this.create_new_atlas_tag_map();
    var rdb  = whitepages.common.get_rdb_cookie();

    if( rdb === null)
    {
       return tag_map;
    }
    tag_map.zip_code = (whitepages.common.hex2dec( rdb[2] ) + "") || '';

    tag_map.gn = whitepages.common.hex2dec( rdb[5] )  ? ['','M','F'][whitepages.common.hex2dec( rdb[5] )] : '';
    
    // 0, 1, & 3 are empty or undefined for some reason.  See Common/lib/Common/RDB.pm
    tag_map.us = whitepages.common.hex2dec( rdb[6] )  ? ['', '', 'B', '', 'P'][whitepages.common.hex2dec( rdb[6] )] : '';  
    tag_map.connspeed = whitepages.common.hex2dec( rdb[11] ) ? (whitepages.common.hex2dec( rdb[11] ) + "") : '';
    tag_map.age = (this.getAgeFromRDBCookie(rdb) + "") || ''; /* we use strings for age */

    tag_map.car = rdb[20] || '';
   
    return tag_map;

  } catch(err) {

    if(console && console.log){
      console.log("Error in COMMON_AD.prototype.get_quantcast_demo_at_cookie_values", err);
    }

    return this.create_new_atlas_tag_map();
  }

};

COMMON_AD.prototype.get_rdb_params = function ( rdb ) {
  var rdb_params = '';

  /** WP: Verify this is an array */
  if ( rdb instanceof Array ) {
    var age_regex = /^(\d+\+*)/;
    rdb_params += whitepages.common.hex2dec( rdb[2] )  ? '/zip_code=' + whitepages.common.hex2dec( rdb[2] )  : '';
    rdb_params += whitepages.common.hex2dec( rdb[5] )  ? '/gn=' + ['','M','F'][whitepages.common.hex2dec( rdb[5] )] : '';
    // 0, 1, & 3 are empty or undefined for some reason.  See Common/lib/Common/RDB.pm
    rdb_params += whitepages.common.hex2dec( rdb[6] )  ? '/us=' + ['', '', 'B', '', 'P'][whitepages.common.hex2dec( rdb[6] )] : '';  
    rdb_params += whitepages.common.hex2dec( rdb[11] ) ? '/connspeed=' + whitepages.common.hex2dec( rdb[11] ) : '';
    rdb_params += (age = this.getAgeFromRDBCookie(rdb)) ? '/age=' + age : '';
    rdb_params += rdb[20] ? '/car=' + rdb[20] : '';

    return rdb_params;
  }
  return '';
}
