/*
 * Popup Campaign Manager provides the objects and methods needed to control multiple popup campaigns
 * It is controlled by popupCampaigns.js; by itself it does nothing that you'll see on a page.
 * It needs one preset variable: thisNode must be set to the node to which the page belongs before importing this javascript source.
 * TO CHANGE THE DOUBLECLICK CAP OR DOUBLECLICK TIMEFRAME, EDIT DClickCap and DClickTimeFrame IN THIS FILE
 */

if ( typeof thisNode == 'undefined' ) thisNode = 'news';

// CONSTANTS
// REGISTERED|NOT_REGISTERED identify whether the user is defined (based on the WPATC cookie).
// To define both user groups, use addition (REGISTERED + NOT_REGISTERED == all users)
var REGISTERED = 1;
var NOT_REGISTERED = 2;

// ARTICLE|FRONT|IMPLICIT|EXPLICIT define the types of pages to which a mapping applies.
// To combine several page types, use addition 
// (FRONT + ARTICLE + IMPLICIT == all section front and articles in this node and all its children)
var ARTICLE = 1;
var FRONT = 2;
var IMPLICIT = 4;
var EXPLICIT = 0;

// These constants make the time conversion to milliseconds easier. Take a number and multiply it by the appropriate constant
var pcm_DAYS = 24 * 60 * 60 * 1000;
var pcm_HOURS = 60 * 60 * 1000;
var pcm_MINUTES = 60 * 1000;
var TWELVE_HOURS = 12 * pcm_HOURS;
var ONE_DAY = 1 * pcm_DAYS;
var ONE_WEEK = 7 * pcm_DAYS;
var ONE_MONTH = 30 * pcm_DAYS;
var pcm_now = new Date();

// The following constants are for internal use
var NA = '';
var SESSION = 0;
var CAMPAIGN_MANAGER = 1;
var INTENSITY = 2;
var SUBSCRIBED = 3;
var DCLICK = 4;
var DCLICK_SESSION_CAP = 5; // new code for v4
var POPUP_WIDTH = 300;
var POPUP_HEIGHT = 400;

var COOKIE_NAME = new Array();
var COOKIE_VALUE = new Array();

COOKIE_NAME[SESSION] = 'wpni_session';
COOKIE_NAME[CAMPAIGN_MANAGER] = 'wpni_campaignmanager';
COOKIE_NAME[INTENSITY] = 'wpni_campaignintensity';
COOKIE_NAME[SUBSCRIBED] = 'WPATC';
COOKIE_NAME[DCLICK] = 'dcCount';
COOKIE_NAME[DCLICK_SESSION_CAP] = 'dcSessionLimit'; // new code for v4

// DClickCap and DClickTimeFrame apply to DoubleClick popup and popunder campaigns
var DClickCap = 5; // Maximum number of DoubleClick popups allowed in timeframe
var DClickTimeFrame = TWELVE_HOURS; // Timeframe applied to DClickCap
var DClickSessionCap = 2; // New variable to control popups per session
var DClickMinTimeBetweenPopups = 60000;
var FORCED_SESSION_EXPIRATON = TWELVE_HOURS; // Must match value in cookie_code.html

var popupUrl = NA;
var pcm_node = thisNode; // thisNode must be defined in the file calling this js file
var isArticle = (location.href.indexOf("/articles/") != -1) ? true : false ;
var popupHasBeenDelivered = false;
var interstitialIsAllowed = true;


// TO DETERMINE IF USER CAME FROM GOOGLE:
var docUrl = document.location.href;
var key = docUrl.indexOf('?');

if (key != -1) // make sure there are parameters
{
  // get the parameter
  var temp = docUrl.substring(key + 1, docUrl.length);
  
  // if just "g" was passed in, set the interstitial to false
  if (temp.length == 1 && (temp == "g" || temp == "G") )
  {
    interstitialIsAllowed = false;
  } 
}
// END GOOGLE LOGIC


// Extract cookies that are not campaign specific 
for (var count = 0; count < COOKIE_NAME.length; count++)
{
  var startAt = 0;
  if ( (startAt = document.cookie.indexOf(COOKIE_NAME[count])) != -1)
  {
    startAt += COOKIE_NAME[count].length + 1;
    var endAt = (document.cookie.indexOf(";", startAt) == -1) ? document.cookie.length : document.cookie.indexOf(";", startAt);
    COOKIE_VALUE[count] = document.cookie.substring(startAt, endAt);
  }
  else
  {
    COOKIE_VALUE[count] = NA;
  }
  //alert ( COOKIE_NAME[count]+'='+COOKIE_VALUE[count] );
}

// New logic to prevent back-to-back interstitials
if ( COOKIE_VALUE[DCLICK_SESSION_CAP].indexOf ("X") != -1 )
{
  interstitialIsAllowed = false; 
  var newCookie = COOKIE_VALUE[DCLICK_SESSION_CAP].substring(0,COOKIE_VALUE[DCLICK_SESSION_CAP].length - 1);
  document.cookie = "dcSessionLimit=" + newCookie + ";path=/;domain=.washingtonpost.com";
}

// New logic to allow for internal timing of DCLICK_SESSION_CAP (v5)
//var dclickTimeBetweenPopups = new Date();
//dclickTimeBetweenPopups.setTime ( dclickTimeBetweenPopups.getTime() + DClickMinTimeBetweenPopups );

if ( COOKIE_VALUE[DCLICK_SESSION_CAP].indexOf ("|") != -1 )
{
  dclickSessionExpiration = COOKIE_VALUE[DCLICK_SESSION_CAP].substring(COOKIE_VALUE[DCLICK_SESSION_CAP].indexOf("|") + 1);
  COOKIE_VALUE[DCLICK_SESSION_CAP] = COOKIE_VALUE[DCLICK_SESSION_CAP].substring(0, COOKIE_VALUE[DCLICK_SESSION_CAP].indexOf("|"));
  var currentDate = new Date();
  var cookieExpiresDate = new Date();
  cookieExpiresDate.setTime( parseInt(dclickSessionExpiration) );

  var cookieSetDate = new Date();
  cookieSetDate.setTime( parseInt(dclickSessionExpiration) - FORCED_SESSION_EXPIRATON );
  
  // If cookie was written in past 15 mins, don't allow interstitial
  if ( currentDate.getTime() - cookieExpiresDate.getTime() < 0 ) // If the cookie was set to expire in the past 15 minutes
  {
    if ( currentDate.getTime() - cookieSetDate.getTime() < DClickMinTimeBetweenPopups )
    {
      interstitialIsAllowed = false;
//      alert ("No ad because it's been less than a minute ("+(currentDate.getTime() - cookieSetDate.getTime())+" < "+DClickMinTimeBetweenPopups+")" );
    }
    if ( COOKIE_VALUE[DCLICK_SESSION_CAP] >= DClickSessionCap )
    {
      interstitialIsAllowed = false;
    }

    //alert ( "Last popup occurred too recently ( "+( currentDate.getTime() - cookieSetDate.getTime() )+"<"+DClickMinTimeBetweenPopups+")" );
  }
// If cookie is older than 15 mins, expire it
  else
  {
    dclickSessionExpiration = new Date();
    dclickSessionExpiration.setTime ( dclickSessionExpiration.getTime() - 100000 );
    document.cookie = COOKIE_NAME[DCLICK_SESSION_CAP] + "=1;expires="+dclickSessionExpiration.toGMTString()+";path=/;domain=.washingtonpost.com"; // new code for v4
    //alert ( "Deleting old cookie" );
  }
}

// if ( COOKIE_VALUE[DCLICK_SESSION_CAP] >= DClickSessionCap ) interstitialIsAllowed=false; // new code for v4
if ( COOKIE_VALUE[DCLICK] >= DClickCap ) interstitialIsAllowed = false;

// logic to abandon Doubleclick call in War node if interstitialisAllowed is false
if ((typeof adTemplate !='undefined') && (typeof thisNode != 'undefined') && (thisNode == 'nation/nationalsecurity/abroad/iraq') &&  (interstitialIsAllowed == false))
		{
		adTemplate = templateConfigs[ OBIT ];
		}

// Extract the campaign-specific cookie
function getCampaignCookie(cn)
{
  var c = NA;
  var temp = document.cookie;
  while (temp.indexOf(cn + ':') != -1) 
    temp = temp.substring(0, temp.indexOf(cn + ':')) 
         + temp.substring(temp.indexOf(cn + ':') + cn.length + 1);
  if (temp.indexOf(cn) != -1)
  {
    var startAt = temp.indexOf(cn) + cn.length + 1;
    var endAt = (temp.indexOf(';', startAt) == -1) ? temp.length : temp.indexOf(';', startAt);
    c = temp.substring(startAt, endAt);
  }
  return c;
}

// Try to deliver a campaign from an Array of campaigns (the Array is the argument to this function)
function deliverCampaign(campaign)
{
  //if ( (typeof debugAdCodeJsp != "undefined") && (debugAdCodeJsp) ) alert(COOKIE_VALUE[DCLICK] + ';' + (popupHasBeenDelivered ? 'true': 'false')); 
  // Abort if another popup already has been deliver on this page
  if ( popupHasBeenDelivered ) 
  {
//    var expires = '';
//    var dcCountExpiration = new Date();
//    dcCountExpiration.setTime(dcCountExpiration.getTime() + (DClickTimeFrame) );
//    if ( ( DClickTimeFrame != SESSION ) && (COOKIE_VALUE[DCLICK] != NA) )
//      expires = ';expires=' + dcCountExpiration.toGMTString();
//    if ( COOKIE_VALUE[DCLICK_SESSION_CAP] != NA ) 
//      COOKIE_VALUE[DCLICK_SESSION_CAP] = parseInt( COOKIE_VALUE[DCLICK_SESSION_CAP] ) + 1; // new code for v4
//    else COOKIE_VALUE[DCLICK_SESSION_CAP] = 1; // new code for v4
//    if ( COOKIE_VALUE[DCLICK] != NA ) 
//      COOKIE_VALUE[DCLICK] = parseInt( COOKIE_VALUE[DCLICK] ) + 1;
//    else COOKIE_VALUE[DCLICK] = 1; 
    //document.cookie = COOKIE_NAME[DCLICK_SESSION_CAP] + "=" + COOKIE_VALUE[DCLICK_SESSION_CAP] + "|" + dclickSessionExpiration + ";path=/;domain=.washingtonpost.com"; // new code for v4
//    document.cookie = COOKIE_NAME[DCLICK] + "=" + COOKIE_VALUE[DCLICK] + expires + ";path=/;domain=.washingtonpost.com";
    return;
  }
  // Abort if the user has exceeded the session limit (defined in popupCampaigns.js)
  if ( (COOKIE_VALUE[SESSION] != NA) && (parseInt(COOKIE_VALUE[SESSION]) >= popupSessionLimit) )
  {
    return;
  }
  
  // Abort if the user has exceeded the intensity limit (defined in popupCampaigns.js)
  if ( (COOKIE_VALUE[INTENSITY] != NA) && (parseInt(COOKIE_VALUE[INTENSITY]) >= popupIntensityLimit) )
  {
    return;
  }

  // Extract possible campaigns from the campaign list by passing each campaign through a bunch of filters
  var validCampaign = new Array();
  var validCampaignCount = 0;

  for (var count = 0; count < campaign.length; count++)
  {
    // Filter one: Check the window during which the campaign is valid
    if ( (campaign[count].timed == false) || ( (pcm_now > campaign[count].startTime) && ((pcm_now < campaign[count].endTime)) ) )
    {
      // Check target
      if (  ( ( (campaign[count].target & NOT_REGISTERED) == NOT_REGISTERED ) && (COOKIE_VALUE[SUBSCRIBED] == NA) )
         || ( ( (campaign[count].target & REGISTERED) == REGISTERED ) && (COOKIE_VALUE[SUBSCRIBED] != NA) )
         )
      {
        // Check to see if this campaign has surpassed its delivery limit
        var campaignCookie = getCampaignCookie(campaign[count].name);
        if (  (campaignCookie == NA) 
           || (parseInt(campaignCookie) < campaign[count].limit)
           )
        {
          // Determine if this node is valid for this campaign
          if (determinePopupUrl(campaign[count]) != NA)
          { 		  
            validCampaign[validCampaignCount++] = campaign[count];
          }
          else{
          }
        }
        else{
        }
      }
      else{
      }
    }
    else{
    }
  }

  // Abort if there are no valid campaigns
  if (validCampaignCount == 0) return;

  
  // Randomize the valid campaigns
  if (validCampaignCount > 1)
  {
    for (var count = 0; count < validCampaignCount; count++)
    {
      var newSpot = Math.floor(Math.random() * validCampaignCount);
      hold = validCampaign[newSpot];
      validCampaign[newSpot] = validCampaign[count];
      validCampaign[count] = hold;
    }
  }
  
  
  
  // Iterate through random list of campaigns, trying to deliver one
  for (var count = 0; count < validCampaignCount; count++)
  {
    var campaignCookie = getCampaignCookie(validCampaign[count].name);
    if ((campaignCookie == NA) || (parseInt(campaignCookie) < validCampaign[count].limit))
    {
      doPopup(validCampaign[count]);
      break;
    }
  }
}

function doPopup(campaign)
{
  // UPDATE COOKIES!
  if (COOKIE_VALUE[SESSION] == NA) COOKIE_VALUE[SESSION] = 1;
  else COOKIE_VALUE[SESSION]++;
  var campaignCookie = getCampaignCookie(campaign.name);
  if (campaignCookie == NA) campaignCookie = 1;
  else campaignCookie = parseInt(campaignCookie) + 1;
  if (COOKIE_VALUE[CAMPAIGN_MANAGER].indexOf(campaign.name + ":") != -1)
  {
    var startAt = COOKIE_VALUE[CAMPAIGN_MANAGER].indexOf(campaign.name + ":") + campaign.name.length + 1;
    var endAt = (COOKIE_VALUE[CAMPAIGN_MANAGER].indexOf("^", startAt) == -1) ? COOKIE_VALUE[CAMPAIGN_MANAGER].length : COOKIE_VALUE[CAMPAIGN_MANAGER].indexOf("^", startAt);
    var temp = parseInt(COOKIE_VALUE[CAMPAIGN_MANAGER].substring(startAt, endAt)) + 1;
    COOKIE_VALUE[CAMPAIGN_MANAGER] = COOKIE_VALUE[CAMPAIGN_MANAGER].substring(0,startAt) 
                                   + temp
                                   + COOKIE_VALUE[CAMPAIGN_MANAGER].substring(endAt);
  }
  else
  {
    COOKIE_VALUE[CAMPAIGN_MANAGER] += campaign.name + ":1^";
  }
  if (COOKIE_VALUE[INTENSITY] == NA) COOKIE_VALUE[INTENSITY] = 1;
  else COOKIE_VALUE[INTENSITY]++;

  // Determine expiration times for different cookies
  var campaignExpiration = new Date();
  var managerExpiration = new Date();
  var intensityExpiration = new Date();
  campaignExpiration.setTime(campaignExpiration.getTime() + (campaign.frequency));
  managerExpiration.setTime(managerExpiration.getTime() + (365 * pcm_DAYS) );
  intensityExpiration.setTime(intensityExpiration.getTime() + (7 * pcm_DAYS) );

  // Write cookies to browser
  document.cookie = COOKIE_NAME[SESSION] + "=" + COOKIE_VALUE[SESSION] + ";path=/";
  document.cookie = campaign.name + "=" + campaignCookie + ";expires=" + campaignExpiration.toGMTString() + ";path=/";
  document.cookie = COOKIE_NAME[CAMPAIGN_MANAGER] + "=" + COOKIE_VALUE[CAMPAIGN_MANAGER] + ";expires=" + managerExpiration.toGMTString() + ";path=/";
  document.cookie = COOKIE_NAME[INTENSITY] + "=" + COOKIE_VALUE[INTENSITY] + ";expires=" + intensityExpiration.toGMTString() + ";path=/";
 
  if (pcm_now.getSeconds()%campaign.mod == 0)
  {
  
  w = window.open(determinePopupUrl(campaign), '', 'width=' + campaign.width + ',height=' + campaign.height + ',scrollbars=yes');
  }
}

function determinePopupUrl(campaign)
{
  var url = NA;
  for (var count = 0; count < campaign.nodeToUrlMapCount; count++)
  {
    var mapping = campaign.nodeToUrlMap[count];
    if ( ((mapping.applies & IMPLICIT) == IMPLICIT) && (pcm_node.indexOf(mapping.node) == 0) )
    {
      if ((((mapping.applies & ARTICLE) == ARTICLE) && (isArticle)) ||
          (((mapping.applies & FRONT) == FRONT) && (!isArticle))
         )
      {
        url = mapping.url;
      }
    }
    else if ( ((mapping.applies & EXPLICIT) == EXPLICIT) && (pcm_node == mapping.node) )
    {
      if ((((mapping.applies & ARTICLE) == ARTICLE) && (isArticle)) ||
          (((mapping.applies & FRONT) == FRONT) && (!isArticle))
         )
      {
        url = mapping.url;
        break;
      }
    }
  }
  return url;
}

// JAVASCRIPT OBJECTS and definitions of their methods
function Campaign()
{
  this.name = '';
  this.timed = false;
  this.startTime = null;
  this.endTime = null;
  this.nodeToUrlMap = new Array();
  this.nodeToUrlMapCount = 0;
  this.target = NOT_REGISTERED;
  this.limit = 1;
  this.frequency = 7 * pcm_DAYS;
  this.width = POPUP_WIDTH;
  this.height = POPUP_HEIGHT;
  this.mod = 1;
  
  this.setName = pcm_setName;
  this.setTime = pcm_setTime;
  this.setTarget = pcm_setTarget;
  this.setLimit = pcm_setLimit;
  this.setFrequency = pcm_setFrequency;
  this.mapNodeToUrl = pcm_mapNodeToUrl;
  this.setDimensions = pcm_setDimensions;
  this.setMod = pcm_setMod;
}

function NodeToUrlMap(n,u,a)
{
  this.node = n;
  this.url = u;
  this.applies = a;
}

function pcm_setDimensions(x,y)
{
  this.width = x;
  this.height = y;
}

function pcm_mapNodeToUrl(u)
{
  this.nodeToUrlMap[this.nodeToUrlMapCount++] = u;
}

function pcm_setName(n)
{
  this.name = n;
}

function pcm_setTime(s,e)
{
  this.startTime = s;
  this.endTime = e;
  this.timed = true;
}

function pcm_setTarget(t)
{
  this.target = t;
}

function pcm_setLimit(l)
{
  this.limit = l;
}

function pcm_setFrequency(f)
{
  this.frequency = f;
}

function pcm_setMod(m)
{
  this.mod = m;
}  


point = 'poe=no;'

// Methods added for POE advertising campaign
// Add into popup campaign classes

function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}

function createTime() {
var cDate = new Date();
var cMil = cDate.getTime();
var e = cMil % (1000 * 60 * 60 * 24);
var r = (1000 * 60 * 60 * 24) - e;
var nr = 2 * 24 * 60 * 60 * 1000;
return(nr);
}

var wpniPOE = new Date();
var interval = 0;

var wpniWeek = wpniPOE.getTime() + createTime();
wpniPOE.setTime(wpniWeek);

point_of_entry = document.referrer.toLowerCase();

if (getCookie("wp_point") == null || getCookie("wp_point") == "false") {
point = 'poe=yes;';
setCookie("wp_point","true",wpniPOE.toGMTString(),"/",".washingtonpost.com",'')

// All pages that are deemed to be "point of entry" are forced to have a certain configuration for advertising leave behind purposes.  - sja
/*
if (typeof commercialNode != 'undefined') {
if (thisNode.indexOf("technology") == -1) {
var adTemplate = templateConfigs[NEWS_SUPER_BANNER];
}
else adTemplate = templateConfigs[TECH_SUPER_BANNER];
}
*/
}

// Logic added to prevent intrusive ad from appearing before or immediately after the registration prompt
// Check to see if registration cookie exists.
if (getCookie("WPATC") != null) {
var array = getCookie("WPATC").split(":");
var temp_hash = new Array();
for (i=0; i<array.length; i++) {
var temp_array = array[i].split("=")
temp_hash[temp_array[0]] = temp_array[1];
}

if (typeof temp_hash["B"] == 'undefined') {
point += 'category=!intrusive;';
}
}

else point += 'category=!intrusive;';

if (getCookie("intrusiveAllowed") != null) {
if (point.indexOf("category=!intrusive") == -1) point += 'category=!intrusive;';
}

