var WhoDat = function(){
	
	var store = {};
	var data = {};
	var best = {};
	var done = false;
	var recorder = new Image();
	var promo_buzz = [];
	var clicked = {};

	var run = function() {
		
		data.set = new Date();
		set_source();

		set_buzz_profile();
		
		_gaq.push(['_setCustomVar', 1, 'Sexy', get_best('nsfw'), 1],
		['_setCustomVar', 2, 'Emotion', get_best('emotion'), 1],
		['_setCustomVar', 3, 'Category', get_best('category'), 1],
		['_setCustomVar', 4, 'Source', get_best('source'), 1]);

		// we're done with the bit that must be done syncronously
		done = true;
		
		
		store.set('profile', Object.toJSON(data) );

		
		
	}
	
	var get_best = function( dimension ) {
		return (typeof best[dimension] == 'undefined') ? 'none' : best[dimension];
	}
	
	var set_source = function() {

		var domains = $H(ActiveHistory.links).values().uniq();

		if (typeof data['source'] == 'undefined' )
			data['source'] = {};
		
		// start off with a baseline of the users current active history
		domains.each(function(domain){
			// if there's no setting for the domain, set it
			// otherwise, a value 2 or more would indicate that the user has 
			// a referrer from the domain which we'll hold on to
			if ( typeof data.source[domain] == 'undefined' || data.source[domain] < 2 )
			{
				data.source[domain] = (ActiveHistory.visited[domain]) ? 1 : 0;
			}
		});
		
		var exp = new RegExp( '(' + domains.join('|') + ')\\.com' );
		
		// check our refer to see if it's a domain we check active history for
		// if so, bump up that data bucket
		var ref_match = exp.exec(document.referrer.toString());
		if (ref_match && ref_match[1] && typeof data.source[ref_match[1]] != 'undefined')
		{
			if (data.source[ref_match[1]] == 0)
				data.source[ref_match[1]] = 2;
			else
				data.source[ref_match[1]]++;
		}		

		var max_domain = 0;
		domains.each(function(domain){
			if (data.source[domain] > max_domain) 
			{
				best['source'] = domain;
				max_domain = data.source[domain];			
			}
		});
		
		
	}
	
	var set_buzz_profile = function() {

		if (typeof data['emotion'] == 'undefined' )	data['emotion'] = {};
		if (typeof data['category'] == 'undefined' ) data['category'] = {};
		if (typeof data['nsfw'] != 'object' ) data['nsfw'] = {nsfw:0,sfw:0};
		if (typeof data['uid'] != 'number' ) data['uid'] = Math.random();
		
		// on a permalink page this variable will be defined
		if ( typeof buzz_profile != 'undefined' )
		{
			if (buzz_profile.category)
			{
				// set our category
				if ( data.category[ buzz_profile.category ] )
					data.category[ buzz_profile.category ]++;
				else
					data.category[ buzz_profile.category ] = 1;
			}

			var max_cat = 0;
			$H(data.category).each(function(pair){
				if (pair.value > max_cat) 
				{
					best['category'] = pair.key;
					max_cat = pair.value;			
				}
			});

			if (buzz_profile.badges)
			{
				buzz_profile.badges.each(function(b){
					// set our category
					if ( data.emotion[b] )
						data.emotion[b]++;
					else
						data.emotion[b] = 1;
				});
			}

			var max_emotion = 0;
			$H(data.emotion).each(function(pair){
				if (pair.value > max_emotion) 
				{
					best['emotion'] = pair.key;
					max_emotion = pair.value;			
				}
			});

			// quickposts do not consistently have the nsfw flag
			// set correctly (it defaults to nsfw) so do not include
			// them in the count
			if (buzz_profile.category != 'QuickPost' && buzz_profile.category != 'Feeds')
			{
				if (buzz_profile.nsfw)
					data.nsfw.nsfw++;
				else
					data.nsfw.sfw++;				
			}
				
			if (data.nsfw.nsfw >= data.nsfw.not)
				best['nsfw'] = 'nsfw';

		}
		
	}
	
	var flatten_buzz_profile = function( buzz ) {
		var buzz_els = [];

		if (buzz['category_name'])
			buzz_els.push('c:' + buzz['category_name']);

		if (buzz['badge_type'])
			buzz_els.push('e:' + buzz['badge_type']);

		if (buzz['age'])
			buzz_els.push('age=' + buzz['age']);

		if (buzz['category_name'] && buzz['category_name'] != 'QuickPost' && buzz['category_name'] != 'Feeds')
		{
			var fw = (buzz['nsfw'] && buzz['nsfw'] == 'true') ? 'nsfw' : 'sfw';
			buzz_els.push('n:' + fw)
			
		}

		return buzz_els.join(';');
		
	}
	
	return {
		init: function() {
			// oh hai
			store = new Persist.Store('WhoDat');
			store.get('profile',function(ok,stored_data){
				if (ok && stored_data && stored_data.isJSON())
					data = stored_data.evalJSON();
				
				try{ run(); } catch(e) { done = true; }
			},this);

			// record an impression later if there is a header promo on this page
			// which we are tracking
			if (typeof hb == 'object' && hb.all_random)
				Element.observe(window,'beforeunload',WhoDat.record);	

			while(!done) {	1;	}
		},
		toString: function() {

			var str = '';
			var els = [];
			['nsfw','emotion','category','source'].each(function(place) {
				var prefix = place.substring(0,1);
				$H(data[place]).each(function(pair){
					els.push(prefix+':'+pair.key+'='+pair.value);
				});
			});
			els.push('uid=' + data.uid );
			return els.join(';');

		},
		debug: function() {
			console.log(data);
			console.log(best);
		},
		click: function( track ) {
			if (typeof hb == 'object' && hb.all_random && hb.page_one_buzz)
				clicked = hb.page_one_buzz.find(function(el){
					return (el.uri == track.buzz);
				});
		},
		record: function(ev) {
			var buzzes = hb.page_one_buzz.map(function(el){
				return flatten_buzz_profile(el);
			});

			var url = "http://174.129.100.53/?" +
				"profile=" + WhoDat.toString() +
				"&impressions=" + buzzes.join(',') +
				"&clicked=" + flatten_buzz_profile(clicked) +
				"&uid=" + data.uid;

			recorder.src = url;
		},
		clear: function() {
			store.remove('profile');
		}
	}
}();
