/*
 * PLEASE NOTE: This file relies on the "cookieClass.js" and "/si/site-tracker.js" files also being included
 */



/*
 * CONFIGURATION
 * - These variables are contained within 'common_pre-main.js'
 *
var ALLOW_MULTIPLE_COOKIE_VALUES = false;
var BYPASS_SPLIT_USING_QUERYSTRING = "splittest";
var CENTRAL_SPLIT_TEST_VISIBLE_COOKIE = "splitTestExecuted";
var CENTRAL_SPLIT_TEST_VISIBLE_COOKIE_VALUE = "Y";
 */


/*
 * When a new split test is added (addTest) 2 sets of arguments are supplied:
 * - 1) The unique ID for the split test
 * - 2a) The unique flag to determine which option to display (first option should be the control)
 * - 2b) The percentage split (Please note: These should all add up to 100% otherwise an error is outputted)
 */
function SwitchSplitSetup() {

	this.addTest = function(uniqueTestID, options) {

		// Should we be using our split test code?
		if(DISABLE_ALL_SPLIT_TEST !== false) {
			return "";
		}

		// Check to see if we want to see a specific test...
		var currentSplitTestResult = false;
		var qsValueUsed = false;
		if(BYPASS_SPLIT_USING_QUERYSTRING != "") {
			// Fetch the value of the querystring variable
			var currentSplitTestResult = fetchQS(BYPASS_SPLIT_USING_QUERYSTRING);
			if(currentSplitTestResult == "") {
				currentSplitTestResult = false;
			} else {
				outputDebug('Using QS value: ' + currentSplitTestResult);
				qsValueUsed = true;
			}
		}
		// ...otherwise check for a cookie
		if(currentSplitTestResult === false) {
			// Check to see if this split test has already been decided
			var currentSplitTestResult = this.returnSplitTest(uniqueTestID);
		}

		if(currentSplitTestResult !== false) {
			// Make sure the cookie value exists
			for(k in options) {
				if(k == currentSplitTestResult) {
					outputDebug( ((qsValueUsed)?'QS':'Current') + ' tag returned: ' + currentSplitTestResult);
					return currentSplitTestResult;
				}
			}
			// Delete cookie (value does not exist) and continue
			outputDebug("Current tag NOT found: " + currentSplitTestResult + "\n'" + uniqueTestID + "' cookie deleted");
			this.deleteSplitTestResult(uniqueTestID);
		}

		// Is the user allowed to see more than one split test?
		if(!ALLOW_MULTIPLE_COOKIE_VALUES) {
			// Check to see if at least one test has been viewed
			var splitTestExecuted = this.returnSplitTest(CENTRAL_SPLIT_TEST_VISIBLE_COOKIE);
			if(splitTestExecuted == CENTRAL_SPLIT_TEST_VISIBLE_COOKIE_VALUE) {
				// Return default/ first option (backup result)
				var defaultControl = this.returnDefaultControl(options);
				outputDebug("Return default/ control: " + defaultControl);
				return defaultControl;
			}
		}

		// Check to see if this split test is disabled (a percentage is set to 100%)
		for(var i in options) {
			if(parseInt(options[i]) == 100) {
				outputDebug("Split test disabled (" + options[i] + "): " + uniqueTestID);
				return "";
			}
		}

		// Make sure all possible options add up to 100%
		if(reviewPercentages(options, uniqueTestID) === false) {
			// Return default/ first option (backup result)
			return this.returnDefaultControl(options);
		}

		// Calculate a random number, used to determine which item to display
		var randomNum = returnRandomNum();
		var randomOpt = returnRandomOption(options, randomNum);
		

		if(randomOpt !== false) {
			// Store and then return split test result
			this.storeSplitTest(uniqueTestID, randomOpt);
			return k;
		}

		// Return default/ first option (backup result)
		var defaultControl = this.returnDefaultControl(options);
		outputDebug("FAILOVER - Return default/ control: " + defaultControl);
		return defaultControl;
	}
	
	
	this.returnDefaultControl = function(options) {
		for(k in options) {
			return k;
		}
		return false;
	}
	this.setupCookie = function(uniqueTestID) {
		return new Cookie(document, uniqueTestID, null, "/");
	}
	this.storeSplitTest = function(uniqueTestID, splitTestChosen) {
		// Update the internal tracking cookies
		this.storeCentralSplitTest();
		var cookieData = this.setupCookie(uniqueTestID);
		cookieData.store(splitTestChosen);
		// Update the SI tracking cookie
		storeSplitTestSI(uniqueTestID, splitTestChosen);
	}
	this.storeCentralSplitTest = function() {
		var cookieData = this.setupCookie(CENTRAL_SPLIT_TEST_VISIBLE_COOKIE);
		cookieData.store(CENTRAL_SPLIT_TEST_VISIBLE_COOKIE_VALUE);
	}
	this.returnSplitTest = function(uniqueTestID) {
		var cookieData = this.setupCookie(uniqueTestID);
		return cookieData.get(uniqueTestID);
	}
	this.deleteSplitTestResult = function(uniqueTestID) {
		var cookieData = this.setupCookie(uniqueTestID);
		cookieData.remove(uniqueTestID);
	}

	// Check to see if the query string has been provided prompting us that a split test was run on a different domain
	var splitTestExecutedElseWhere = fetchQS(CENTRAL_SPLIT_TEST_VISIBLE_COOKIE_QS);
	if(splitTestExecutedElseWhere == CENTRAL_SPLIT_TEST_VISIBLE_COOKIE_VALUE) {
		// Setup the central cookie
		this.storeCentralSplitTest();
	}

}



/*
 * When a new split test is added (addAnchor) 2 sets of arguments are supplied:
 * - 1) The ID of the link we're working with
 * - 2a) The URL to navigate to
 * - 2b) The percentage split (Please note: These should all add up to 100% otherwise an error is outputted)
 *
 * PLEASE NOTE: This function works differently to that above because this one does not store the
 * route chosen so the user could end-up going to different places each time they click the link!
 *
 */
function LinkSplitSetup() {
	this.addAnchor = function(id, options) {
		var anchor = $(id);
		if(anchor) {
			if(reviewPercentages(options, '#'+id) === false) {
				return false;
			}

			anchor.observe('click', function(e) {
				var randomNum = returnRandomNum();
				var randomOpt = returnRandomOption(options, randomNum);
				if(randomOpt !== false) {
					// redirect
					Event.stop(e);
					window.location = randomOpt;
					return false;
				}
				// Use default 'href'
				return true;
			});
		}
	}
}



/*
 * Common code/ helper functions for each of the above split test functions
 */
function reviewPercentages(options, uniqueID) {
	var total = 0;
	for(var i in options) {
		total += parseInt(options[i]);
	}
	if(total === 100) {
		return true;
	}
	alert("The totals for the '" + uniqueID + "' split test do not equal 100 but '" + total + "' - Setup cancelled!");
	return false;
}
function returnRandomNum() {
	var randomNumOrig = Math.random();
	if(randomNumOrig == 0) randomNumOrig = 1;
	var randomNum = Math.ceil(randomNumOrig * 100);
	outputDebug('Random number generated: ' + randomNum + ' (' + randomNumOrig + ')');
	return randomNum;
}
function returnRandomOption(options, randomNum) {
	var counter = 1;
	for(k in options) {
		if(counter <= randomNum && randomNum < (counter + parseInt(options[k]))) {
			return k;
		} else {
			counter += parseInt(options[k]);
		}
	}
	return false;
}
function outputDebug(msg) {
	if(typeof console != 'object') {
		return false;
	}
	if(typeof console.log != 'function') {
		return false;
	}
	if(location.href.indexOf('.monitormedia.local') == -1  &&  location.href.indexOf('.directlineforbusiness.local') == -1) {
		return false;
	}
	console.log(msg);
	return true;
}
function fetchQS(qsVar) {
	var qsVarsStr = window.location.search.substring(1);
	if(qsVarsStr == "") {
		return "";
	}
	var qsVarsArr = qsVarsStr.split("&");
	for (i=0; i<qsVarsArr.length; i++) {
		var qsVarPair = qsVarsArr[i].split("=");
		if (qsVarPair[0] == qsVar) {
			return qsVarPair[1];
		}
	}
	return "";
}



/*
 * Site Intelligence integration code
 */
function storeSplitTestSI(uniqueTestID, splitTestResult) {
	// Make sure the SI functions we want to use exist
	if( (typeof sitracker != 'object')  ||  (typeof sitracker.addTrackParam != 'function')  ||  (typeof sitracker.sendTrackParams != 'function') ) {
		var debugMsg = "SI function does not exist!";
		if(typeof sitracker != 'object') {
			debugMsg += "\n- sitracker (" + (typeof sitracker) + ")";
		}
		if(typeof sitracker.addTrackParam != 'function') {
			debugMsg += "\n- addTrackParam (" + (typeof sitracker.addTrackParam) + ")";
		}
		if(typeof sitracker.sendTrackParams != 'function') {
			debugMsg += "\n- sendTrackParams (" + (typeof sitracker.sendTrackParams) + ")";
		}
		outputDebug(debugMsg);
		return false;
	}
	var uniqueSplitTestResult = uniqueTestID + "-" + splitTestResult;
	sitracker.addTrackParam("splitversion", uniqueSplitTestResult);
	sitracker.sendTrackParams();
	outputDebug('SI tag stored: ' + uniqueSplitTestResult);
	return true;
}
