/* Valtira Embed Survey Popups */
/* author Benjamin Wilson ben.wilson@valtira.net */

/*
Cookies with description of each:

vlt_firstEntrance - set only if choosen survey has the type set to true and it's the user's first visit (expires @ session end)
vlt_entranceVariation - set if choosen survey has type set to true (expires @ session end)
vlt_entranceOffer - set when the entrance survey offer has been made, we only show entrance once (expires never, it's sticky)
vlt_entranceTaken - set if the visitor opts-in to the survey, used to not bother them afterwards (expires never)
vlt_exitVariation - set if choosen survey has type set to false (expires @ session end)
vlt_exitOffer - set when the exit survey offer has been made (!Important expires @ session end)
vlt_exitTaken - set if the visitor opts-in to the survey, used to not bother them on subsequent visits (expires never)
vlt_pageViews - keeps count of how many pages have been viewed, at a specific number the survey is shown (expires @ session end)
vlt_pageCount - set by the selected survey

vlt_surveyId - vlt_ratio1 and vlt_ratio2 are used to determine the survey selected, the survey id is stored here (expires only if it doesn't match current surveyIds)
vlt_surveyType - surveyType is either true (entrance) or false (exit)

*/

/* Global Vars
vlt_oldY - var is used to determine mouse direction, this is used to track and trigger the exit popup
vlt_externalPath - stores the href of a link that's offsite and will redirect the visitor after the survey popup is presented
vlt_refUrl - is passed to the survey to track what website lead the visitor to the current site
vlt_surveyPath - destination path to the survey used via the popup anchor tag
vlt_pageViews - set via cookie to tally how many pages have been viewed before the survey popup is shown

NOTE: To bump the page view number but not show the survey popup set vlt_noPopup on a page by page basis.

*/

var vlt_oldY = 0;
var vlt_externalPath = "";  //set empty at global level, functions will fill it in
var vlt_refUrl = "";  //set empty at global level, functions will fill it in
var vlt_surveyPath = "";  // set empty either exitoffer or enteranceoffer will assign value
var vlt_pageViews = 0;
var vlt_pageCount = 0;
var vlt_currentSurvey = new Object();

/* Functions

vlt_offerEntrance - brings a thickbox up, allowing the visitor to opt-in for entrance survey
vlt_offerExit - brings a thickbox up, allowing the visitor to opt-in for exit survey
vlt_listenForExit - sets mouse and external link listeners to bring up thickbox for exit survey
vlt_redirectExternalLink - takes a path and redirects browser to the path provided
vlt_openSurvey - creates a new window where the visitor can take the survey
vlt_initThickboxSurveyLink - sets up links in thickbox to open survey

vlt_surveyInit - check for cookies, determine next steps (First function called on load)
vlt_ratioLogic - takes both survey ratios and chooses a survey

--- Provided from http://techpatterns.com/downloads/javascript_cookies.php
vlt_Get_Cookie
vlt_Set_Cookie
vlt_Delete_Cookie

*/

function vlt_surveyInit() {
  // check if survey has been taken, if not
  // check for vlt_surveyId cookie, match to current surveyIds
  // if it matches run logic based on survey otherwise reset and run ratioLogic
  // finally if vlt_surveyId cookie doesn't exist run ratioLogic
  if (vlt_Get_Cookie('vlt_entranceOffer') || vlt_Get_Cookie('vlt_exitTaken') || vlt_Get_Cookie('vlt_exitOffer') || vlt_Get_Cookie('vlt_exitOffer')) {
    //do nothing

  } else if (vlt_Get_Cookie('vlt_surveyId')) {
    // check that it matches current surveyId1 or surveyId2
    // if not erase it and start ratio logic new
    var vlt_cookieSurveyId = vlt_Get_Cookie('vlt_surveyId');

    if (vlt_cookieSurveyId == vlt_survey1.surveyId) {
      // determine type and call exit or entrance init
      if (vlt_survey1.surveyType == "true" && vlt_pageViews >= vlt_pageCount) {
        vlt_offerEntrance(vlt_survey1);
      } else if (vlt_survey2.surveyType == "true" && vlt_pageViews >= vlt_pageCount) {
        vlt_initExitPopup(vlt_survey1);
      }

    } else if (vlt_cookieSurveyId == vlt_survey2.surveyId) {
      // determine type and call exit or entrance init
      if (vlt_survey2.surveyType == "true" && vlt_pageViews >= vlt_pageCount) {
        vlt_offerEntrance(vlt_survey2);
      } else if (vlt_survey2.surveyType == "false" && vlt_pageViews >= vlt_pageCount) {
        vlt_initExitPopup(vlt_survey2);
      }
    } else {
      // the optimizer has changed, delete cookies and run ratio logic
      vlt_ratioLogic();
    }
  } else {
    // 1st time visiting, run ratio logic
    vlt_ratioLogic();
  }
}

function vlt_ratioLogic() {

  // determine the smaller ratio to calculate against random
  if (vlt_survey1.ratio <= vlt_survey2.ratio) {
    if (Math.random() <= (vlt_survey1.ratio / 100)) {
      // set cookies for vlt_survey1
      vlt_Set_Cookie('vlt_surveyId', vlt_survey1.surveyId, '1000', '/', '', '');
      vlt_Set_Cookie('vlt_surveyType', vlt_survey1.surveyType, '1000', '/', '', '');
      vlt_Set_Cookie('vlt_pageCount', vlt_survey1.pageCount, '1000', '/', '', '');

      // if surveyType true, run entrance offer otherwise init exit offer
      if (vlt_survey1.surveyType == "true" && vlt_pageViews >= vlt_survey1.pageCount) {
        vlt_offerEntrance(vlt_survey1);
      } else if (vlt_survey1.surveyType == "false" && vlt_pageViews >= vlt_survey1.pageCount) {
        vlt_initExitPopup(vlt_survey1);
      }
    } else {
      // set cookies for vlt_survey2
      vlt_Set_Cookie('vlt_surveyId', vlt_survey2.surveyId, '1000', '/', '', '');
      vlt_Set_Cookie('vlt_surveyType', vlt_survey2.surveyType, '1000', '/', '', '');
      vlt_Set_Cookie('vlt_pageCount', vlt_survey2.pageCount, '1000', '/', '', '');
      // if surveyType true, run entrance offer otherwise init exit offer
      if (vlt_survey2.surveyType == "true" && vlt_pageViews >= vlt_survey2.pageCount) {
        vlt_offerEntrance(vlt_survey2);
      } else if (vlt_survey2.surveyType == "false" && vlt_pageViews >= vlt_survey2.pageCount) {
        vlt_initExitPopup(vlt_survey2);
      }
    }
  } else {
    // evaluate if vlt_survey2.ratio is lower than random
    if (Math.random() <= (vlt_survey2.ratio / 100)) {
      // set cookies for vlt_survey2
      vlt_Set_Cookie('vlt_surveyId', vlt_survey2.surveyId, '1000', '/', '', '');
      vlt_Set_Cookie('vlt_surveyType', vlt_survey2.surveyType, '1000', '/', '', '');
      vlt_Set_Cookie('vlt_pageCount', vlt_survey2.pageCount, '1000', '/', '', '');
      // if surveyType true, run entrance offer otherwise init exit offer
      if (vlt_survey2.surveyType == "true" && vlt_pageViews >= vlt_survey2.pageCount) {
        vlt_offerEntrance(vlt_survey2);
      } else if (vlt_survey2.surveyType == "false" && vlt_pageViews >= vlt_survey2.pageCount) {
        vlt_initExitPopup(vlt_survey2);
      }
    } else {
      // set cookies for vlt_survey1
      vlt_Set_Cookie('vlt_surveyId', vlt_survey1.surveyId, '1000', '/', '', '');
      vlt_Set_Cookie('vlt_surveyType', vlt_survey1.surveyType, '1000', '/', '', '');
      vlt_Set_Cookie('vlt_pageCount', vlt_survey1.pageCount, '1000', '/', '', '');
      // if surveyType true, run entrance offer otherwise init exit offer
      if (vlt_survey1.surveyType == "true" && vlt_pageViews >= vlt_survey1.pageCount) {
        vlt_offerEntrance(vlt_survey1);
      } else if (vlt_survey1.surveyType == "false" && vlt_pageViews >= vlt_survey1.pageCount) {
        vlt_initExitPopup(vlt_survey1);
      }
    }
  }

}

function vlt_listenForExit(vlt_selectedSurvey) {

  /* If visitor leaves page, show exit survey */
  $(document).mousemove(function (e) {

    // figure out the offset if they visitor has scrolled
    var vlt_scrOfY = 0;
    if (typeof (window.pageYOffset) == 'number') {
      //Netscape compliant
      vlt_scrOfY = window.pageYOffset;
    } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
      //DOM compliant
      vlt_scrOfY = document.body.scrollTop;
    } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
      //IE6 standards compliant mode
      vlt_scrOfY = document.documentElement.scrollTop;
    }

    var vlt_offSetTop = e.pageY - vlt_scrOfY;

    if (vlt_offSetTop <= 5 && e.pageY < vlt_oldY && !vlt_Get_Cookie('vlt_exitOffer')) {
      vlt_offerExit(vlt_selectedSurvey);
    }
    //set new position for next check
    vlt_oldY = e.pageY;
  });

  /* Find all external links and offer exit survey before redirect */
  $('a').filter(function () {
    return this.hostname && this.hostname !== location.hostname;
  }).click(function () {
    if (!vlt_Get_Cookie('vlt_exitOffer')) {
      vlt_offerExit(vlt_selectedSurvey);
      vlt_externalPath = this.href;
      var vlt_path = this.href;
      setTimeout('vlt_redirectExternalLink("' + vlt_path + '");', 8000);
      return false;
    } else {
      return true;
    }
  });
}

function vlt_initExitPopup(vlt_selectedSurvey) {

  if (vlt_pageViews >= vlt_pageCount) {

    vlt_listenForExit(vlt_selectedSurvey);

    vlt_currentSurvey = vlt_selectedSurvey;

  }
}

function vlt_setReferralUrl() {
  if (vlt_Get_Cookie('vlt_refUrl')) {
    // var is passed into the survey call
    return vlt_Get_Cookie('vlt_refUrl');
  } else {
    vlt_refUrl = document.referrer;
    vlt_Set_Cookie('vlt_refUrl', vlt_refUrl, '', '/', '', '');
    return vlt_refUrl;
  }
}

function vlt_noPopupInit() {
  if (typeof (vlt_noPopup) == 'Undefined' || typeof (vlt_noPopup) == 'undefined') {
    return false;
  } else {
    return true;
  }
}

function vlt_redirectExternalLink(path) {
  location.href = path;
}

function vlt_openSurvey(pageURL, title, w, h) {
  var vlt_left = (screen.width / 2) - (w / 2);
  var vlt_top = (screen.height / 2) - (h / 2);
  var vlt_pUrl = pageURL + "&referringUrl=" + vlt_refUrl + "&lastPage=" + document.title;
  var vlt_targetWin = window.open(vlt_pUrl, '', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width=' + w + ', height=' + h + ', top=' + vlt_top + ', left=' + vlt_left);
  // close popup
  tb_remove();
}

function vlt_initThickboxSurveyLink() {
  // setup link for either enterance or exit survey
  $("a#surveyLink").click(function () {
    // set survey taken cookie based on entranceVariation or exitVariation cookie
    if (vlt_Get_Cookie('vlt_surveyType') == "true") {

      vlt_Set_Cookie('vlt_entranceTaken', 'true', '1000', '/', '', '');

    } else {

      vlt_Set_Cookie('vlt_exitTaken', 'true', '1000', '/', '', '');

    }

    vlt_openSurvey(this.href, "Survey", vlt_surveyWindowWidth, vlt_surveyWindowHeight);

    return false;
  });
  $("a#redirectNow").click(function () {
    $(this).attr('href', vlt_externalPath);
  });
}

function vlt_offerEntrance(vlt_selectedSurvey) {
  vlt_surveyPath = vlt_odsUrl + "?surveyId=" + vlt_selectedSurvey.surveyId;
  // Launch MODAL BOX
  var t = setTimeout("tb_show('Welcome', vlt_pathToPopup+'?height=180&width=300&svyPath='+vlt_surveyPath, '')", 1000);
  /* Set vlt_entranceOffer cookie - don't expire only shown once,
  all subsequent visits exit survey only */
  vlt_Set_Cookie('vlt_entranceOffer', 'true', '1000', '/', '', '');
  /* Set vlt_entranceOffer cookie - don't expire only shown once,
  all subsequent visits exit survey only */
  vlt_Set_Cookie('vlt_firstEntrance', 'true', '', '/', '', '');
}


function vlt_offerExit(vlt_selectedSurvey) {
  // vlt_odsUrl created in valtira-config.js
  vlt_surveyPath = vlt_odsUrl + "?surveyId=" + vlt_selectedSurvey.surveyId;
  // Launch MODAL BOX
  tb_show("", vlt_pathToPopup + "?height=180&width=300&svyPath=" + vlt_surveyPath, "");
  /* Set vlt_exitOffer cookie - expires at end of session */
  vlt_Set_Cookie('vlt_exitOffer', 'true', '', '/', '', '');
}

function vlt_pageViewCount() {
  // get cookie and raise count, if it doesn't exist create it
  if (vlt_Get_Cookie('vlt_pageViews')) {
    vlt_pageViews = parseInt(vlt_Get_Cookie('vlt_pageViews'));
    vlt_pageCount = parseInt(vlt_Get_Cookie('vlt_pageCount'));
    vlt_pageViews = vlt_pageViews + 1;
    vlt_Set_Cookie('vlt_pageViews', vlt_pageViews, '', '/', '', '');
    return vlt_pageViews;
  } else {
    // create cookie and set pageViews to 1
    vlt_Set_Cookie('vlt_pageViews', '1', '', '/', '', '');
    var vlt_pageViews = 1;
    return vlt_pageViews;
  }
}

function vlt_Set_Cookie(name, value, expires, path, domain, secure) {
  // set time, it's in milliseconds
  var today = new Date();
  today.setTime(today.getTime());
  /*
  if the expires variable is set, make the correct
  expires time, the current script below will set
  it for x number of days, to make it for hours,
  delete * 24, for minutes, delete * 60 * 24
  */
  if (expires) {
    expires = expires * 1000 * 60 * 60 * 24;
  }
  var expires_date = new Date(today.getTime() + (expires));

  document.cookie = name + "=" + escape(value) +
  ((expires) ? ";expires=" + expires_date.toGMTString() : "") +
  ((path) ? ";path=" + path : "") +
  ((domain) ? ";domain=" + domain : "") +
  ((secure) ? ";secure" : "");
}


function vlt_Get_Cookie(check_name) {
  // first we'll split this cookie up into name/value pairs
  // note: document.cookie only returns name=value, not the other components
  var a_all_cookies = document.cookie.split(';');
  var a_temp_cookie = '';
  var cookie_name = '';
  var cookie_value = '';
  var b_cookie_found = false; // set boolean t/f default f

  for (i = 0; i < a_all_cookies.length; i++) {
    // now we'll split apart each name=value pair
    a_temp_cookie = a_all_cookies[i].split('=');


    // and trim left/right whitespace while we're at it
    cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

    // if the extracted name matches passed check_name
    if (cookie_name == check_name) {
      b_cookie_found = true;
      // we need to handle case where cookie has no value but exists (no = sign, that is):
      if (a_temp_cookie.length > 1) {
        cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
      }
      // note that in cases where cookie is initialized but no value, null is returned
      return cookie_value;
      break;
    }
    a_temp_cookie = null;
    cookie_name = '';
  }
  if (!b_cookie_found) {
    return null;
  }
}


// this deletes the cookie when called
function vlt_Delete_Cookie(name, path, domain) {
  if (vlt_Get_Cookie(name)) document.cookie = name + "=" +
  ((path) ? ";path=" + path : "") +
  ((domain) ? ";domain=" + domain : "") +
  ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

/*  Runtime Code

*/

$(document).ready(function () {

  /* check for vlt_noPopup */
  /* var used to determine when to show a popup if all other criteria is met */
  vlt_noPopup = vlt_noPopupInit();

  /* check for referral URL */
  /* this code is to provide the referral url from the first page of the site
  if not from an off-site link, then it's set to the first page
  */
  vlt_refUrl = vlt_setReferralUrl();

  vlt_pageViews = vlt_pageViewCount();

  // only init if vlt_noPopup is false
  if (!vlt_noPopup) {
    vlt_surveyInit();
  }

});
