// this script implements the survey strategy. After number of pages visited is equal to or
// greater than 'stickFactor' apply the 'samplePercentage' rule to determine if this visitor
// gets the survey.
// Customer : Forbes

// ************* configuration variables - change the values, NOT THE NAMES **************
// minimum number of pages viewed before we survey the user
var stickFactor = 2;// will act as 3

// percentage of visitors to randomly sample
var samplePercentage = 1;

// number of minutes the persistent cookie should last - this prevents a user from
// getting multi-surveyed in this time period 
var resampleWait = 129600; // 90 days

// this variable will override resampleWait in the event that persistent cookies
// are not allowed by the client
var noPersistentCookies = 0;

// this variable when set to 1 will prevent the trigger from performing its
// function
var disableTrigger = 0;

// this is the base URL to the survey engine
var popUpURL = "http://www.foreseeresults.com/survey/display";

// this is our customer's unique customer id
var customerId = "Q8+EG6AmSqT80/hyFPzeDQ==";

// this is out customer's unique model instance id for this survey's model
var modelInstanceId = "3UHqNwcy4zp0zP9UKes28Q==";

// the name of the pop up window
var popUpWinName = "survey";

// if this variable is set to 1,the window pops under rather than up
var popUnder = 1;

// these are the dimensions of the pop up window
var popUpWidth = 410;
var popUpHeight = 500;

// the name of the persistent or session cookie to prevent multi-surveying in a given time period
var ckAlreadyShown = "foreseeSurveyShown";

// the name of the cookie that counts the minimum pages viewed with the trigger code in them
var ckStickyCount = "foreseePagesViewed";

// the name of the cookie that implements the surveying 'sample-percentage' algorithm
var ckSamplePercentage = "foreseeSamplePerc";

// if we are using customer passed parameters, they will be included elsewhere in the page after
// this script is included, overriding the following variable
var customerParams = null;

// ************ don't modify below this line *************
// set persistent cookie expiration if we are using it, otherwise it is a session cookie
var expDate = new Date();
var now = new Date();
var persistentExpires = new Date();
persistentExpires.setTime(persistentExpires.getTime() + (resampleWait*60*1000));

function GetCookie (name) {
   var arg = name + "=";
   var alen = arg.length;
   var clen = document.cookie.length;
   var i = 0;
   while (i < clen) {
       var j = i + alen;
       if (document.cookie.substring(i, j) == arg)
           return getCookieVal (j);
       i = document.cookie.indexOf(" ", i) + 1;
       if (i == 0) break;
   }
   return null;
}

function SetCookie (name, value) {
   var argv = SetCookie.arguments;
   var argc = SetCookie.arguments.length;
   var expires = (argc > 2) ? argv[2] : null;
   var path = (argc > 3) ? argv[3] : null;
   var domain = (argc > 4) ? argv[4] : null;
   var secure = (argc > 5) ? argv[5] : false;
   document.cookie = name + "=" + escape (value) +
   ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
   ((path == null) ? "" : ("; path=" + path)) +
   ((domain == null) ? "" : ("; domain=" + domain)) +
   ((secure == true) ? "; secure" : "");
}

function DeleteCookie (name) {
   var exp = new Date();
   exp.setTime (exp.getTime() - 1);
   var cval = GetCookie (name);
   document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}

function getCookieVal(offset) {
   var endstr = document.cookie.indexOf (";", offset);
   if (endstr == -1)
       endstr = document.cookie.length;
   return unescape(document.cookie.substring(offset, endstr));
}

// check whether or not this browser supports focus() on windows
function supportsFocus() {
	// get user agent string
	var userAgent = navigator.userAgent;
	// find IE version label in user agent string if it exists
	var realMSVersionAt = userAgent.indexOf("MSIE");

	if (realMSVersionAt == -1) {
		// must be netscape
		return true;
	} else {
		// IE browser, see which one
		var nameAndVersion = userAgent.substring(realMSVersionAt, realMSVersionAt + 6);
		var realMSVersion = nameAndVersion.charAt(5);
		if(realMSVersion >= 5) {
			return true;
		} else {
			return false;
		}
	}
}

// special URL escapes for chars which don't escape using built-in
// escape() function in JavaScript. Currently these are '+', '/', '?', '='
// which are part of the Base64 character set
function specialEscape(s) {
	var encoded = "";
	
	// escape '+' characters
	var tokens = s.split('+');
	for(var i = 0; i < tokens.length; i++) {
		encoded += tokens[i];
		if(i < (tokens.length - 1)) {
			encoded += "%2B"; // %2B is the hex escape for '+'
		}
	}
	
	var t = encoded;
	encoded = "";
	// escape '/' characters
	var tokens = t.split('/');
	for(var i = 0; i < tokens.length; i++) {
		encoded += tokens[i];
		if(i < (tokens.length - 1)) {
			encoded += "%2F"; // %2F is the hex escape for '/'
		}
	}
	
	var t = encoded;
	encoded = "";
	// escape '?' characters
	var tokens = t.split('?');
	for(var i = 0; i < tokens.length; i++) {
		encoded += tokens[i];
		if(i < (tokens.length - 1)) {
			encoded += "%3F"; // %3F is the hex escape for '?'
		}
	}
	
	var t = encoded;
	encoded = "";
	// escape '=' characters
	var tokens = t.split('=');
	for(var i = 0; i < tokens.length; i++) {
		encoded += tokens[i];
		if(i < (tokens.length - 1)) {
			encoded += "%3D"; // %3D is the hex escape for '='
		}
	}
	
	return encoded;
}

function Poll() { // catch onUnload or onLoad event, set in page BODY tag

   if(disableTrigger == 1) {
       return;
   }

   var stickyCounter = GetCookie(ckStickyCount); // check counter cookie
   var alreadyShown = GetCookie(ckAlreadyShown); // check if we already have shown survey
   var pageCount;

   var randNum = Math.random();
   randNum *= 100;
   SetCookie(ckSamplePercentage, randNum); // only for diagnostics

   if (stickyCounter == null) {
       // no cookie, create a new one and set it to 1. We use this to monitor
       // stickiness
       pageCount=1;
       SetCookie(ckStickyCount, pageCount);
   } else {
       // already a cooke - see if we have reached the pages viewed requirement
       pageCount = stickyCounter;
       if(pageCount >= stickFactor) {
           // apply the samplingPercentage algorithm
           if(alreadyShown == null) {
           	// only if we haven't already served them a survey
               if(randNum <= samplePercentage) {
   	    	    var winOptions = "width=" + popUpWidth + ",height=" + popUpHeight + ",resizable=no,scrollbars=yes";
   	    	    var fullURL = popUpURL + "?" + "cid=" + specialEscape(customerId) + "&mid=" + specialEscape(modelInstanceId);
   	    	    if(customerParams != null) {
   	    	        fullURL += customerParams;
   	    	    }
	            var myPopUp = window.open(fullURL, popUpWinName, winOptions);
		    if(supportsFocus()){
			    // handle pop-under functionality
			    if(popUnder == 1) {
				self.focus();
			    } else {
				myPopUp.focus();
			    }
		    }
	            // insure that we only pop up once during the lifetime of the cookie
	            if(noPersistentCookies == 1) {
	            	SetCookie(ckAlreadyShown, 'true',null,'/');
	            } else {
	            	SetCookie(ckAlreadyShown, 'true', persistentExpires,'/');
	            }
	        }
	    }
        }
        // increment it and set the new cookie value    
        pageCount++;
        SetCookie(ckStickyCount, pageCount);
    }


}

