var Cookie = {
	read: function(key) {
		var cookie = Cookie.getCookie();return cookie[key];
	},
	write: function(hash) {
		var cookie_string = '';	for(prop in hash) {	var c = prop+'='+hash[prop]+'; '; cookie_string += c;}; document.cookie = cookie_string;
	},
	getCookie: function() {
		var cookie = {}; var cookie_array = document.cookie.split('; ');for(var i=0;i<cookie_array.length;i++) {
			var j = cookie_array[i].indexOf("="); cookie[cookie_array[i].substring(0,j)]=cookie_array[i].substring(j+1, cookie_array[i].length);
		}
		return cookie;
	}
};

var SplitTest = function(options){
	this.options = options;	
	this.load = function(){
		var variantNumber = this.getVariant();
		this.setSegment(variantNumber);
		this.options.variants[variantNumber](this); //execute the variant's function, passing current SplitTest object
	}
	this.getVariant = function(){
		var segment;
		if(typeof(Cookie.read(this.options.testid))=='undefined'){
			var chance = Math.random() * 100; var weighttotal = 0;
			for(i=0;i<this.options.weights.length;i++){
				weighttotal+=this.options.weights[i];
				if(chance<weighttotal){segment = i; break;}
			}
		}
		else segment = eval(Cookie.read(this.options.testid));
		return segment;
	}
	
	this.setSegment = function(segment){
		//cookie
		var expires = new Date(); expires.setDate(expires.getDate()+30);
		sc = {}; sc[this.options.testid]=segment+""; sc["expires"]=expires; sc["path"]="/"; sc["domain"]=this.options.domain;
		Cookie.write(sc);
		//google analytics
		if(this.options.ga){
			if(this.options.ga.gavar=="_gaq" ){
				_gaq = _gaq || [];
				_gaq.push(['_setCustomVar', this.options.ga.slot, this.options.testid, this.options.testid + "-" + segment, 1]);
			}
			else{ 
				pageTracker._setCustomVar(this.options.ga.slot, this.options.testid, this.options.testid + "-" + segment, 1);
			}
		}
		//omniture -- requires Wiley vars collector
		if(this.options.omni && Wiley && Wiley.Vars){
			Wiley.Vars[this.options.omni.evartest]=this.options.testid;
			Wiley.Vars[this.options.omni.evarsegment]=segment;
		}
	}
	

	
	this.incrementPageDepth = function(){
		this.pagedepth = Cookie.read('session_depth') || 0;
		this.pagedepth++;
		Cookie.write({ session_depth: this.pagedepth, path: '/', domain: this.options.domain });	// this cookie records the page depth, so we can execute on x pages in
	}
}
