/*
 * Javascript AB Tester
 * Randomizes multiple content blocks
 * Thomas Crummett, Dec 31, 2007
 */
/*
 * Modified Javascript AB Tester
 * Now Stores Data in two cookies webex_abTest_C , webex_abTest_S
 * Lakshmi Alapati, June 13, 2008 
 */
 
/*** begin: ABTESTER OBJECT ***/
function AbTester(testID)
{
	this.cookieMode = 1; //2 for 30 day life, 1 for EoS, 0 for disabled
	this.force = null; //ID to force display
	this.trackingCookieName = "TrackID"; //Name of the cookie set for Tracking. Maybe used to set origination trackID
	var caseList = new Array(); //List of cases to use
	var selectedID = null; //which layer is selected
	
	//Adds blocks to show
	this.addCase = function(testValue, TrackID, rate){
		var newCase = new Array(testValue, TrackID, rate);
		caseList.push(newCase);
	}
	
	// Returns the selected test ID
	this.getSelected = function(){
		return selectedID;
	}
	
	//Switches out the blocks with new one
	var switchCase = function (id){
		selectedID = id;
		for (var i = 0; i < caseList.length; i++){
			var dom = document.getElementById(caseList[i][0]);
			if(dom !=null){
				dom.style.display = 'none';
			}
		}
		
		if (isNaN(parseInt(id))){
			var block = document.getElementById(id);
			if (block != null){
				block.style.display = 'block';
			} else {
				document.getElementById(caseList[0][0]).style.display = 'block';
			}
		} else {
			if (caseList[id] != null){
				var block = document.getElementById(caseList[id][0]);
				if(block!=null){
					block.style.display = 'block';
				} else {
					document.getElementById(caseList[0][0]).style.display = 'block'
				}
			} else {
				document.getElementById(caseList[0][0]).style.display = 'block';
			}
		}
	}
	
	//selects a random integer
	var randomInteger = function(low, high){
		var num = Math.floor ((Math.random() * (high)) + low);
		return num;
	}
	
	//Runs the rotator and switches out content
	this.run = function(){
		var selectedIndex = 0;
		var url = window.location.href;
		var querystring = url.split("?");
		ce = new AbCookieWrapper();
		
		//Read data stored in the cookie
		var cookieContents = ce.getCookieField(this.cookieMode,testID);
		
		//checks whether the test_value from cookie is valid, element has properties and is in case list or not
		if(cookieContents){
			var tempFlag = false;
			if (document.getElementById(cookieContents)!=null){
				for (var i=0; i<caseList.length; i++){
					if (caseList[i][0] == cookieContents){
						tempFlag = true;  //id element is present and is in case list
						selectedIndex = i;
						break;
					}
				}
			}
			
			if (!tempFlag){
				ce.deleteCookieField(2, testID, 30);
				ce.deleteCookieField(1, testID, null);
				cookieContents = null;
			}
		}
		
		//shows the test from the url
		if (querystring[1]){
			var urlTemp = querystring[1].split("&");
			for(i=0; i<urlTemp.length; i++){
				urlTempSplit =  urlTemp[i].split("=");
				if (testID == urlTempSplit[0]){
					if (!isNaN(urlTempSplit[1]) && urlTempSplit[1]>=0 && urlTempSplit[1]<caseList.length){
						this.force = caseList[urlTempSplit[1]][0];
						selectedIndex = urlTempSplit[1];
					}
					break;
				}
			}
			
			if (this.force){
				switchCase(this.force);
			}
		}
		
		//Use value stored in cookie, if there is a value
		if (this.force == null){
			if (cookieContents && this.cookieMode != 0){
				switchCase(cookieContents);
			} else {
				var ratio = 0; //Sum of all rates
				var offsets = new Array(); //Offsets of each case
				var winner = 0; //Lucky winner!
				var randomNumber = 0; //Random Number, duh!
				
				//Calculate total of ratios
				for (var i = 0; i < caseList.length; i++){
					ratio += caseList[i][2];
					offsets.push(ratio);
				}
				
				var low = 1;
				var high = offsets[offsets.length - 1];
				randomNumber = randomInteger(low, high);
				var i = -1;
				
				do{
					i++;
					winner = i;
				} while (randomNumber > offsets[i]);
				
				switchCase(caseList[winner][0]);
				selectedIndex = winner;
			}
		}
		
		if (this.cookieMode != 0){
			if (this.cookieMode == 2){
				var time = 30;
			} else {
				var time = null;
			}
			ce.appendToCookie(this.cookieMode,testID, caseList[selectedIndex][0], time);
			if (parseInt(caseList[selectedIndex][1])){
				var trackID_days = 365;
				var expdate = new Date();
				expdate.setDate(expdate.getDate() + trackID_days);
				cookie_string = this.trackingCookieName + "=" + escape(caseList[selectedIndex][1]) + ";expires=" + expdate.toGMTString() + ";domain=webex.com;path=/";
			}
			document.cookie = cookie_string;
			ce.document_cookie = document.cookie;
		} else {
			ce.deleteCookieField(2, testID,30);
			ce.deleteCookieField(1, testID,null);
		}
	}
}
/*** end: ABTESTER OBJECT ***/


/*** begin: ABCOOKIEWRAPPER OBJECT ***/
function AbCookieWrapper()
{
	var C_MAIN = ""; //cookie name
	var COOKIE_NAME_PERSISTENT = "webex_abTest_C"; //name of persistent cookie
	var COOKIE_NAME_SESSION = "webex_abTest_S"; //name of session cookie
	var document_cookie = document.cookie; //stores the value from the cookie
	
	// function to set cookie
	var setCookie = function(cookieMode, cookieData, c_expiredays){
		var pickCookie = cookieMode==2 ? COOKIE_NAME_PERSISTENT : COOKIE_NAME_SESSION;
		if (c_expiredays != null){
			var expdate = new Date();
			expdate.setDate(expdate.getDate() + c_expiredays);
			cookie_string = pickCookie + "=" + escape(cookieData) + ";expires=" + expdate.toGMTString() + ";domain=webex.com;path=/";
		} else {
			cookie_string = pickCookie + "=" + escape(cookieData) + ";domain=webex.com;path=/";
		}
		document.cookie = cookie_string;
		document_cookie = document.cookie;
	}
	
	//function to get the value of the cookie depending upon the cookie mode
	var getCookieData = function(cookieMode){
		var cookieParameters = unescape(document_cookie).split(";");
		cookieData = "";
		if(cookieMode !=0){
			if (cookieMode == 2){
				C_MAIN = COOKIE_NAME_PERSISTENT;
			} else {
				C_MAIN = COOKIE_NAME_SESSION;
			}
		} else {
			return null;
		}
		for(i=0; i<cookieParameters.length; i++){
			tempCookieData = cookieParameters[i];
			tempUnEscapeStr = tempCookieData;
			cookieDataInd = tempUnEscapeStr.indexOf(C_MAIN + "=");
			if(cookieDataInd==-1) continue;
			cookieDataInd = cookieDataInd + C_MAIN.length + 1;
			cookieData = tempUnEscapeStr.substring(cookieDataInd,tempUnEscapeStr.length);
			break;
		}
		return cookieData;
	}
	
	//appends test id, test value to the cookie depending upon cookie mode
	this.appendToCookie = function(cookieMode, testID, testValue, c_expiredays){
		if(cookieMode==0){
			return;
		}
		if(document_cookie && document_cookie.length >0){
			cookieData = getCookieData(cookieMode);
			var curCookieFieldValue = this.getCookieField(cookieMode, testID);
			
			//cookie field already exists. dont do anything and return
			if(curCookieFieldValue!=null){
				this.deleteCookieField(cookieMode, testID, c_expiredays);
			}
		}
		
		//cookie field does not exist append it to cookie data
		cookieData = getCookieData(cookieMode);
		fieldStr =  testID+ "=" + testValue;
		if(cookieData.length >0){
			cookieData += "&" + fieldStr;
		} else {
			cookieData = fieldStr;
		}
		setCookie(cookieMode, cookieData, c_expiredays);
		
		if(cookieMode==1){
			this.deleteCookieField(2, testID, 30);
		} else if(cookieMode==2){
			this.deleteCookieField(1, testID, null);
		}
	}
	
	//gets the value of the test id given
	this.getCookieField = function(cookieMode,testID){
		if(cookieMode==0) return null;
		cookieData = getCookieData(cookieMode);
		if (cookieData.length>0){
			var value = cookieData;
			var c_start= value.indexOf(testID+ "=");
			if (c_start != -1){
				c_start = c_start + testID.length+1;
				var c_end = value.indexOf("&", c_start);
				if (c_end == -1){
					c_end=cookieData.length;
				}
				return (value.substring(c_start,c_end));
			}
		}
		return null;
	}
	
	//deletes the id and value pair from cookie depending upon the change in the cookieMode
	this.deleteCookieField = function(cookieMode, testID, c_expiredays){
		cookieDataTemp = getCookieData(cookieMode);
		if(cookieDataTemp.length==0) return;
		
		// loop through each pair and remove the ones that match
		var arrayPairs = cookieDataTemp.split("&");
		var arrayNewPairs = new Array();
		for (var j=0; j<arrayPairs.length; j++){
			arrayPair = arrayPairs[j].split("=");
			if (arrayPair[0] && arrayPair[0] != testID){
				arrayNewPairs.push(arrayPairs[j]);
			}
		}
		if (arrayNewPairs.length == 0){
			if (cookieMode == 2){
				setCookie(2, "", 0);
			} else {
				setCookie(1, "", 0);
			}
		} else {
			setCookie(cookieMode, arrayNewPairs.join("&"), c_expiredays);
		}
	}
	
	// deletes all values from a cookie
	this.deleteAllFields = function(){
		setCookie(1, "", 0);
		setCookie(2, "", 0);
	}
}
/*** end: ABCOOKIEWRAPPER OBJECT ***/


// Globally available function to clean test cookies
function expireABTest(testID){
	abcookie = new AbCookieWrapper();
	if(testID){
		if (testID == "*"){
			abcookie.deleteAllFields();
		} else {
			abcookie.deleteCookieField(2, testID, 30);
			abcookie.deleteCookieField(1, testID, null);
		}
	}
}