// cookie values to be written in this format:
// alreadySurveyed::pageVisits::lastVisited::wantsSurvey
// ...where alreadySurveyed is 0 for false, 1 for true
// ...and pageVisits is an incremental integer
// ...and lastVisisted is a Javascript Date object
// --------------------------------------------------------------------------
// script config
// --------------------------------------------------------------------------
// CONSTANTS...except stupid IE doesn't support const, so they have to be vars
var cookieName = "tekSG";                   // name of the cookie for the Tek SurveyGizmo popup
var sessionCookieName = "tekSGs";           // name of the temp cookie we use for handling resampling
var scAlreadySampled = true;                // session cookie value for "already sampled" this session
var samplingPercentage = 100;                // users liklihood of getting the survey
var pageViewedFactor = 2;                   // number of pages the user must visit before qualifying for the survey
var daysForSurveyToExpire = 90;             // number of days before the survey cookie expires and users will be asked again
var validPaths = new Array("zh",
                           "ja",
						   "en"
                          );                // specify the valid paths for the domain (i.e. tek.com/ja/ would be "ja"), "en" is for testing currently

var surveyURLs = {
					"ja":"http://www.surveygizmo.com/s/236078/satisfaction-ja",
					"zh":"http://www.surveygizmo.com/s/236132/satisfaction-zh"
					};                      // URLs for the survey for each region, indexed by country code

var popupPrefix = 'http://www.tek.com';     // change to http://wwwdev.tek.com for testing
var popupWidth = 820;                       // width of the survey invitation popup window
var popupHeight = 450;                      // height of the survey invitation popup window
var popupDelayCheck = 3000;                 // millisecons to wait before checking parent to see if URL has changed. 1s = 1000ms

var DEBUG = false;                          // set to true for debugging popups
// END CONSTANTS

// --------------------------------------------------------------------------
// logic
// --------------------------------------------------------------------------
var alreadySurveyed = 0;                    // 0 is false, 1 is true
var pagesVisited = 0;                       // incrementing by 1 to pageViewedFactor
var lastVisited = '';                       // date of the last visit for making sure
											// the pageViewedFactor is met on the same day

// this is the "do stuff" method to be called from the actual web page
// lang parameter should be 2-char string of language code, as called by the appropriate header include
function runSurveyCheck(lang)
{
	if(lang == null)                        // allow default value in case we forget to call it with the language code
	{
		lang = "en";                        // default to en
	} // end if test
	
	// check to see if this user has already failed to meet the sampling percentage this session
	if((getSessionCookie(sessionCookieName) != "") || (getSessionCookie(sessionCookieName) == null))
	{
		if(DEBUG) alert("ALREADY SAMPLED THIS SESSION");
		
		return; // bad coding choice, but it keeps this mess cleaner
	} // end if test
	
	// get the cookie
	var storedCookie = readSurveyCookie(cookieName);
	
	if(storedCookie) // does cookie exist?
	{
		// cookie exists
		// unload the cookie data		
		alreadySurveyed = parseInt(storedCookie[0]);
		pagesVisited = parseInt(storedCookie[1]);
		sampleAttempt = new Date(storedCookie[2] == '' ? new Date() : storedCookie[2]); // if there is no sampleAttempt date, make it "now"
	
		if(alreadySurveyed != 0)
		{
			// user has already been surveyed so disregard
			if(DEBUG) alert("ALREADY SURVEYED");
			
			pagesVisited = pagesVisited + 1; // show that we crossed the pages viewed threshold, even though we'll never use this again
			var value = "1::" + pagesVisited + "::" + new Date();
			
			// update cookie			
			writeSurveyCookie(cookieName,
				value,
				getNewExpirationDate(daysForSurveyToExpire),
				getCookiePath(),
				getCookieDomain());
		} // end if test
		else
		{
			// user has not been surveyed so continue with checks
			if(pagesVisited < pageViewedFactor)
			{
				if(DEBUG) alert("UPDATE PAGES VISITED: " + pagesVisited);
				// user hasn't hit the survey threshold yet
				pagesVisited = pagesVisited + 1; // increment one closer to pageViewedFactor
				
				var value = "0::" + pagesVisited + "::" + new Date();
	
				// update cookie
				writeSurveyCookie(cookieName,
					value,
					getNewExpirationDate(daysForSurveyToExpire),
					getCookiePath(),
					getCookieDomain());
			} // end if test
			else
			{
				// user has hit the pages viewed threshold
				// check to see if we fall within the sampling percentage
				if(getSamplingStatus(samplingPercentage))
				{
					if(DEBUG) alert("NEEDS SURVEY");
					// user needs to see the survey invite
					var value = "1::" + pagesVisited + "::" + new Date();
					
					// update cookie
					writeSurveyCookie(cookieName,
						value,
						getNewExpirationDate(daysForSurveyToExpire),
						getCookiePath(),
						getCookieDomain());
					
					// get the region from the URL
					//var region = getCookiePath();
					var region = lang;
					//region = region.replace("/", "");
					
					// check to see if the region from the URL has a valid translated popup
					var i = 0;
					var valid = false;
					
					for(i in validPaths)
					{
						if(validPaths[i] == region) valid = true;
					} // end for loop
					
					// ...in case our region isn't in the translated popups, just give them the english popup
					if(!valid) region = "en";
					
					window.open(popupPrefix + "/_js/surveypopup/" + region + "/sgpopup.html?surveyurl=" + surveyURLs[region],"surveypop","scrollbars=1,menubar=no,width=" + popupWidth + ",height=" + popupHeight + ",toolbar=no");
					// not passing survey URL
					//window.open("sgpopup.html","surveypop","menubar=no,width=" + popupWidth + ",height=" + popupHeight + ",toolbar=no");
				} // end if test
				else
				{
					if(DEBUG) alert("DIDN'T MEET SAMPLING %");
					
					// write session cookie so that we don't try to sample the user again this session
					writeSessionCookie(sessionCookieName, scAlreadySampled);
										
					// reset pages viewed cookie
					var value = "0::0::" + new Date();
					
					// update cookie
					writeSurveyCookie(cookieName,
						value,
						getNewExpirationDate(daysForSurveyToExpire),
						getCookiePath(),
						getCookieDomain());
				} // end else test
			} // end else test
		} // end else test
	} // end if test
	else
	{
		if(DEBUG) alert("CREATING NEW COOKIE");
		
		// cookie doesn't exist so let's create one
		var value = "0::1::" + new Date(); // set pages visited to 1 because we are currently on a page
	
		writeSurveyCookie(cookieName,
					value,
					getNewExpirationDate(daysForSurveyToExpire),
					getCookiePath(),
					getCookieDomain());
	} // end else test
	
	return;
} // end runSurveyCheck function

// --------------------------------------------------------------------------
// functions
// --------------------------------------------------------------------------

// get true if randomly falls within sampling percentage
function getSamplingStatus(samplingPercentage)
{
	var seed = new Date().getSeconds();

	var randomNum = Math.floor(Math.random(seed) * 101); // generate a random number between 0 and 100
	
	if(DEBUG) alert("RANDOM NUMBER FOR SAMPLING: " + randomNum + " (seed: " + seed + ")");
	
	var status = false;                              // default return status is false
	
	// the random number will, in theory, fall on each number in 0-100, 1% of the time
	// therefore, 30 times out of 100, the number will be below or equal to 30
	if(randomNum <= samplingPercentage)
	{
		status = true; // number fell within the sampling percentage
	} // end if test
				
	return status;			
} // end getSamplingStatus

// get the cleaned, usable host name in the format we need
function getCookieDomain()
{
	var hostname = window.location.hostname;                                     // returns something like www.tek.com
	hostname = hostname.substring(hostname.indexOf("tek") - 1, hostname.length); // we want just .tek.com
	
	return hostname;
} // end getCookieDomain function

// get the cleaned, usable path in the format we need
// if called without parameter of some window.location.pathname, then the default window.location.pathname will be used
function getCookiePath(pathname)
{
	if(pathname == null)                                               // allow default value for calling without parameter
	{
		pathname = window.location.pathname;                           // returns something like /ja/forms/response/kctesting
	} // end if test
	                          
	pathname = "/" + pathname.substring(1, pathname.indexOf("\/", 1)); // we want just /ja

	return pathname.toLowerCase();
} // end getCookiePath function
		
// get a date object that is X number of days in the future based on parameter
function getNewExpirationDate(daysToExpire)
{
	var expires = new Date();
	expires.setDate(expires.getDate() + daysToExpire);
	return expires;
} // end getNewExpirationDate function

function writeSurveyCookie(cookieName, value, expires, cookiePath, cookieDomain)
{
	// build up cookie data string
	var cookieData = "";
	cookieData += cookieName + " = " + value + "; ";
	
	if(expires != null)
	{
		// allow for optional expiration, session cookies do not have expiration
		cookieData += "expires = " + expires.toGMTString() + "; ";
	} // end if test
	
	cookieData += "path = " + cookiePath + "; ";
	cookieData += "domain = " + cookieDomain + "; ";
	//cookieData += "secure;"; // not using secure and providing ANYTHING for this value makes it thing that it is secure
	
	// write cookie data
	document.cookie = cookieData;
	
	return;
} // end writeSurveyCookie function

// reads the cookie specified via the parameter, which is a string name
// returns false if cookie not found
function readSurveyCookie(cookieName)
{
	var values = false;                                                // holds cookie data or FALSE if cookie not found
	
	var storedCookie = document.cookie;                                // get the cookie
	var start = storedCookie.indexOf(cookieName, 0);                   // find the beginning of the cookie data we are looking for

	if(start >= 0)
	{
		var end = storedCookie.indexOf(";", start);                     // find the end of this cookie data
		
		// if this is the last cookie, there is no ; to delineate the next cookie
		if(end == -1)
		{
			end = storedCookie.length;
		} // end if test
		
		var data = storedCookie.substring(start, end);                  // get the data block from the cookie
		data = data.substring(data.indexOf("=", 0) + 1, data.length);   // get just the data from the cookie
		
		values = data.split("::");                                      // break the data apart into an array,
																		// we use :: as a data delimiter within the cookie
	} // end if test
	else
	{
		values = false;
	} // end else test
	
	return values;	
} // end readSurveyCookie function

// Get cookie routine by Shelley Powers, slightly modified by Tek
// http://www.javascriptkit.com/javatutors/cookie2.shtml
// just using this to get the session cookie value
function getSessionCookie(sessionCookieName)
{
	var search = sessionCookieName + "="
	var returnvalue = "";
	var offset;
	var end;
	
	if(document.cookie.length > 0)
	{
		offset = document.cookie.indexOf(search)
		// if cookie exists
		
		if(offset != -1)
		{ 
			offset += search.length
			
			// set index of beginning of value
			end = document.cookie.indexOf(";", offset);
			
			// set index of end of cookie value
			if(end == -1) end = document.cookie.length;
			returnvalue = unescape(document.cookie.substring(offset, end))
		} // end if test
	} // end if test
	
	return returnvalue;
} // end getSessionCookie function

// we don't care about specifics, we are just writing a temporary session cookie with a name/value pair
function writeSessionCookie(name, value)
{
	document.cookie = name + "=" + value;
	
	return;
} // end writeSessionCookie function
