Survey = Class.create();
Object.extend(Survey.prototype, {

	options: null,

	/*
	* configurators: Collection of configuration objects of which one will 
	* be randomly selected and used to configure the page appropriately
	* 
	* Each configuration object needs a name property for tracking purposes 
	* and a run function reference which is called when the configuration 
	* is chosen
	* 
	* record: the function executed after the configuration is run. It should
	* expect the selected configuration as its first argument
	* 
	* options: hashtable of options
	* 	cookieName: the name of a cookie if you want to save a particular 
	* 	configuration for the visitor's session
	* 
	* 	onStart: function to execute once the survey is started
	* 	if none is specified the default tracking will be used.
	* 
	* 	The configuration used is passed as the first parameter to onStart
	* 
	* 	NOTE you will need to provide your own tracking in onStart if you 
	* 	specify an onStart callback
	*/
	initialize: function(configurators, record, options) {
		this.options = options || {};
		
		var config = this.decide(configurators);
		this.start(config);
		
		if (typeof(record) == 'function') {
			record(config);
		}
	},
	
	//Retrieve the name of the configuration cookied for this session if available
	getSettings: function() {
		
		if (!this.options.cookieName) {
			return null;
		}
		
		var config = null;
		var cookies = document.cookie.split(';');

		var pattern = new RegExp(this.options.cookieName + '=(.*)');

		for(var i = 0; i < cookies.length; i++) {
			var match = cookies[i].match(pattern);
			if (match) {
				config = match[1];
			}
		}
		return config;
	},
	
	//Save the name of a configuration to use during this session
	saveSettings: function(config) {
		if (!this.options.cookieName) {
			return;
		}
		
		var expires = '';
		if (typeof(this.options.expires) != 'undefined') {
			expires = 'expires=' + this.options.expires + ';';
		}
		
		document.cookie = this.options.cookieName + '=' + config.name  + '; ' + expires + ' path=/; domain=apple.com';
	},
	
	//Choose a configuration from those available to execute
	decide: function(configurators) {
		var savedSettings = this.getSettings();
		if (savedSettings) {
			for (var i = configurators.length - 1; i >= 0; i--){
				if (savedSettings == configurators[i].name) {
					return configurators[i];
				}
			}
		}
		
		var option = Math.floor(Math.random() * configurators.length);
		return configurators[option];
	},
	
	//Start the survey with the specified configuration
	start: function(config) {
		if (!config) {
			return;
		}
		config.run(config);
		
		this.saveSettings(config);
		
		if (typeof(this.options.onStart) == 'function') {
			this.options.onStart(config);
		} else {
			var title = document.title + ' - ' + config.name;
			AC.Tracking.trackClick({prop3: title}, this, 'o', title);
		}
	}
	
});