var Survey = {
  AdResearch: {
    active: true, // Turns the survey on and off
    surveys: [] // listing of surveys
  },
  ShowResearch: {
    active: true,
    surveys: []
  },
  debug: false,
  debugLog: ""
};


//
// Listing of running ad surveys, will be tested for eligibility
// in random order until one is eligible or all possible surveys are exhausted
//
Survey.AdResearch.surveys = [
  {
    cookie: "fma09041",  // cookie id for preventing multiple survey takes
    active: true, // Turns the survey on and off

    // Full url for PREWAVE surveys; Domain and path for TARGETED surveys
    // this is Fidelity-only post wave
    url: "http://d.surveysonline.com/survey/fma/fma09041/survey.html",

    // include SWID cookie value as swid=XXX when invoking URL?
    includeSWID: true,

    percentage: 1.0, // capture rate for this ad survey; 0 to 1.0 scale
    targeted: true, // for prewave = false, postwave = true

    // listing of active advertisers
    // can be empty for PREWAVE surveys
    activeAds: 
    [
      "Fidelity"
    ],

    // move ads from active to inactive when closed
    // can be empty for PREWAVE surveys
    inactiveAds: 
    [
    ],

    // allow renaming of advertiser in survey
    // can be empty for PREWAVE surveys
    adRenames: 
    [
    ]
  },
  {
    cookie: "fma10002",  // cookie id for preventing multiple survey takes
    active: true, // Turns the survey on and off

    // Full url for PREWAVE surveys; Domain and path for TARGETED surveys
    // this is post wave 13
    url: "http://d.surveysonline.com/survey/fma/fma10002/survey.html",

    // include SWID cookie value as swid=XXX when invoking URL?
    includeSWID: true,

    percentage: 1.0, // capture rate for this ad survey; 0 to 1.0 scale
    targeted: true, // for prewave = false, postwave = true

    // listing of active advertisers
    // can be empty for PREWAVE surveys
    activeAds:
    [
      "Acura",
      "Advair",
      "AquafreshWT",
      "Spinbrush",
      "Brita",
      "DelMonte",
      "DiscoverCard",
      "FreshStep",
      "HillshireFarms",
      "KayJewelers",
      "Lexus",
      "NatureMade",
      "LovelyBones",
      "RoyalCaribbean",
      "Sensodyne",
      "SensodyneIsoActive",
      "SensodynePronamel",
      "Target",
      "Toyota",
      "DisneyParksResorts"
    ],

    // move ads from active to inactive when closed
    // can be empty for PREWAVE surveys
    inactiveAds: 
    [
      "BlackBerry",
      "DisneyParksPortfolio",
      "Allstate",
      "Mitsubishi",
      "Enterprise",
      "FDOC",
      "Sprint",
      "MercedesBenz",
      "Honda",
      "Suave",
      "Verizon",
      "Alli"
    ],

    // allow renaming of advertiser in survey
    // can be empty for PREWAVE surveys
    adRenames: 
    [
    ]
  }
];


//
// Listing of shows and their survey URLs
//
// show/episode combinations here are mutually exclusive
//
// i.e. you can't list one show in two different surveys
// where the list of episodes overlaps (including the case
// of not specifying any episodes which in turn matches all
// episodes).
//
// the list of shows is checked in order for the first match
// of show name and episode so specifying overlapping combinations
// of show + episode means that the second and subsequent overlapping
// show + episode combinations will never be matched or used.
//
Survey.ShowResearch.surveys = [
  // example of surveying on a single episode
  {
    name: "show1",
    active: false, 
    cookie: "show1_101",  // cookie id for preventing multiple survey takes
    percentage: 0.5, // intercept rate for this show survey; 0.0 to 1.0 scale
    url: "show1_101",

    // include SWID cookie value as swid=XXX when invoking URL?
    includeSWID: true,
    episodes: ["101"]
  },

  // example of surveying on multiple episodes
  {
    name: "show1",
    active: false, 
    cookie: "show1_106_107",  // cookie id for preventing multiple survey takes
    percentage: 0.5, // intercept rate for this show survey; 0.0 to 1.0 scale
    url: "show1_106_107",

    // include SWID cookie value as swid=XXX when invoking URL?
    includeSWID: true,
    episodes: ["106","107"]
  },

  // example of surveying on all episodes
  {
    name: "show2",
    active: false, 
    cookie: "show2",  // cookie id for preventing multiple survey takes
    percentage: 0.5, // intercept rate for this show survey; 0.0 to 1.0 scale

    // include SWID cookie value as swid=XXX when invoking URL?
    includeSWID: true,
    url: "show2"
  }
];

///////////////////////////////////////////////////////////////////////////////
// Do not edit below this line
///////////////////////////////////////////////////////////////////////////////

Survey.Popup = {

  getSWID: function() {
    var results = document.cookie.match ( '(^|;)?SWID=([^;]*)(;|$)' );
    if ( results ) {
      return ( unescape ( results[ 2 ] ) );
    } else {
      return null;
    }
  },

  run: function() {
    var finalURL = "";
    var cookieId = "";
    var containsActive = false;
    
    // determines if cookie w/ particular id has been set
    var alreadyOffered = function(id) {
      if ( Survey.debug ) { return false; }

      var cookies = document.cookie;
      if (cookies.indexOf(id, 0) >= 0) {
        return true;
      }
      return false;
    };
    
    if (typeof abcdm === "undefined" ||
        typeof abcdm.abc === "undefined" ||
        typeof abcdm.abc.vp2 === "undefined" ||
        typeof abcdm.abc.vp2.AdResearch === "undefined") {
      return;
    }
    
    
    //
    // show surveys take precedence
    //
    if (Survey.ShowResearch.active == true) {

      var showData = abcdm.abc.vp2.AdResearch.getShowData();

      if (showData != null && 
          showData.hasOwnProperty("show") && 
          showData.hasOwnProperty("episode")) {

        // find matching show + episode if any
        // see comments above about not supporting overlapping
        // show + episode combinations
        for ( var i = 0; i < Survey.ShowResearch.surveys.length; i++ ) {
          var survey = Survey.ShowResearch.surveys[ i ];
          var random = Math.random();

// WScript.Echo( "1: random: " + random + ", percentage = " + survey.percentage + ", i = " + i );

          if ( typeof survey != "undefined" && 
               survey.name == showData.show &&
               survey.active == true &&
               random <= survey.percentage &&
               alreadyOffered( survey.cookie ) == false ) {

            // person saw a show that has an active survey
            // and hasn't seen that survey before
            // and is within percentage of people we wish to invite
          
            // see if we need to test for specific episodes
            if (typeof survey.episodes != "undefined") {

              for ( var j = 0; j < survey.episodes.length; j++) {
                if (survey.episodes[ j ] == showData.episode) {

                  // matched specific episode so stop loop
                  break;
                }
              }

              // see if we matched a specific episode
              if ( j < survey.episodes.length ) {
  
if ( Survey.debug ) { 
  Survey.debugLog += "choose episode specific show survey"; 
  debugSurveyCount[ survey.url ]++;
}
                // matched specific episode so do invite

                // save cookieId so we can set cookie during invite
                cookieId = survey.cookie;

                finalURL = survey.url;
                if ( survey.includeSWID ) {
                  finalURL += "?swid=" + escape( Survey.Popup.getSWID() );
                }
                break;
              }
            } else {

              // not testing for specific episodes, so just do invite

if ( Survey.debug ) { 
  Survey.debugLog += "choose episode independent show survey"; 
  debugSurveyCount[ survey.url ]++;
}
              // save cookieId so we can set cookie during invite
              cookieId = survey.cookie;

              finalURL = survey.url;
              if ( survey.includeSWID ) {
                finalURL += "?swid=" + escape( Survey.Popup.getSWID() );
              }
              break;
            }
          } // found matching show
        } // loop over all show/episode combinations
      }
    }
    
    
    // test for targeted ad surveys
    if (finalURL == "" && // not serving a show survey
        Survey.AdResearch.active == true) {

      // loop through active surveys starting at random one
      var surveyCount = Survey.AdResearch.surveys.length;
      var randomOffset = Math.floor( Math.random() * surveyCount );

      for ( var i = randomOffset; i < (surveyCount + randomOffset); i++ ) {
        var surveyIndex = i % surveyCount;

        var survey = Survey.AdResearch.surveys[ surveyIndex ];
        var random = Math.random();

// WScript.Echo( "2: random: " + random + ", percentage = " + survey.percentage + ", i = " + i + ", randomOffset = " + randomOffset + ", surveyCount = " + surveyCount );

        // see if eligible for this survey
        // only do targeted surveys in this first pass
        if (survey.active == true &&
            survey.targeted == true &&
            random <= survey.percentage &&
            alreadyOffered(survey.cookie) == false) {

          // since its targeted, must test each ad to see if we're 
          // tracking it and append to query string accordingly
          var data = abcdm.abc.vp2.AdResearch.getAdData();
        
          var adData = "";
          if (data !== null && data.length > 0) {
            for ( var j = 0; j < data.length; j++ ) {
              var ad = data[ j ];
              var adName = ad.name;

              // see if this ad is found as an active ad
              var adFound = false;
              var adIsActive = false;
              for ( var k = 0; k < survey.activeAds.length; k++ ) {
                if (survey.activeAds[ k ] == adName) {
                  adFound = true;
                  adIsActive = true;
                  break;
                }
              }

              // if not found, see if its an inactive ad
              if ( ! adFound ) {
                for ( var k = 0; k < survey.inactiveAds.length; k++ ) {
                  if (survey.inactiveAds[ k ] == adName) {
                    adFound = true;
                    adIsActive = false;
                    break;
                  }
                }
              }

              // only track ads that we're interested in passing to survey
              // regardless of whether they're currently active or closed
              if ( adFound ) {

                // rename ad if necessary
                if ( ! ( typeof survey.adRenames === "undefined" ) ) {
                  for ( var k = 0; k < survey.adRenames.length; k++ ) {
                    if ( survey.adRenames[ k ].originalName == adName ) {
                      adName = survey.adRenames[ k ].newName;
                      break;
                    }
                  }
                }
                
                // append ad info to query string
                adData += 
                  ad.pos + 
                  ":" + 
                  adName + 
                  ":" + 
                  adIsActive +
                  ",";
              }
            }
          }
          // strip trailing comma
          if ( adData.length > 0 ) {
            adData = adData.slice(0, adData.length - 1);
          }

          // only invite if we have at least one active targeted ad
          if (adData.indexOf("true") != -1) {
            containsActive = true;
            cookieId = survey.cookie;
            finalURL = survey.url + "?ad_data=" + escape(adData);
            if ( survey.includeSWID ) {
              finalURL += "&swid=" + escape( Survey.Popup.getSWID() );
            }

if ( Survey.debug ) { 
  Survey.debugLog += "choose targeted ad survey"; 
  debugSurveyCount[ survey.url ]++;
}
            break; // stop testing for eligible surveys since we found one
          }

        } // end if this survey was eligible
      } // for each survey
    } // end if targeted ad surveys are active


    // test for untargeted ad surveys
    if (finalURL == "" && // not serving a show survey
        Survey.AdResearch.active == true) {

      // loop through active surveys starting at random one
      var surveyCount = Survey.AdResearch.surveys.length;
      var randomOffset = Math.floor( Math.random() * surveyCount );

      for ( var i = randomOffset; i < (surveyCount + randomOffset); i++ ) {
        var surveyIndex = i % surveyCount;

        var survey = Survey.AdResearch.surveys[ surveyIndex ];
        var random = Math.random();

// WScript.Echo( "3: random: " + random + ", percentage = " + survey.percentage + ", i = " + i );

        // see if eligible for this survey
        // do targeted surveys in this first pass
        if (survey.active == true &&
            survey.targeted == false &&
            random <= survey.percentage &&
            alreadyOffered(survey.cookie) == false) {

          // since not targeted, then just invite
          cookieId = survey.cookie;
          finalURL = survey.url;
          if ( survey.includeSWID ) {
            finalURL += "?swid=" + escape( Survey.Popup.getSWID() );
          }

if ( Survey.debug ) { 
  Survey.debugLog += "choose untargeted ad survey"; 
  debugSurveyCount[ survey.url ]++;
}
          break;

        } // end if this survey was eligible
      } // for each survey
    } // end if untargeted ad surveys are active

    if (finalURL != "" && cookieId != "") {
      
      if ( Survey.debug == true ) {
        Survey.debugLog = finalURL + ", " + Survey.debugLog;
      } else {
        
        var win = 
          window.open(
            finalURL,
            'intercept',
            'width=1000,height=450,screenX=175,screenY=75,top=75,left=175,resizable=yes,scrollbars=yes'
          );
        if(win) {
          var expDate = new Date ();
          var msecOneYear = (365 * 24 * 60 * 60 * 1000);
          expDate.setTime (expDate.getTime() + msecOneYear);
          document.cookie = 
            cookieId + 
            "=" + 
            "alreadyOffered; expires=" + 
            expDate.toGMTString() + 
            "; path=/; domain=abc.go.com";
        }
      }
    } else {

      // if no invite, record that for debugging
      if ( Survey.debug == true ) {
        debugSurveyCount[ "noInvite" ]++;
        Survey.debugLog = "noInvite" + ", " + Survey.debugLog;
      }
    }
  }
};

