POLLER_CALLBACK_LOOKUP = new Object();

function poller_call_back(key, args) {
	var callback_data = POLLER_CALLBACK_LOOKUP[key];
	var callback = callback_data.callback;
	if(! callback_data || ! callback_data.callback) {
		console.error("no poller callback function defined with key: %s", key);
		return;
	} else {
		callback_data.poller.stop_polling();
		callback_data.callback(args);		
	}
}

function set_poller_trigger() {
	var seconds = 5000; // five seconds
   	var d = new Date();
   	d.setTime( d.getTime() + seconds );
   	var expire = '';
   	expire = '; expires=' + d.toGMTString();
   	var cook = 'BUZZ_POLLER_COOKIE=true' + expire + '; domain=.buzzfeed.com; path=/static/js/poller';
	document.cookie = cook;		
}

cookie_poller = function() {
	this.active = false;
	this.count = 0;
	this.start = function( args ) {
		this.active = true;
		this.count = 0;
		cookie_poller_active = true;				
		if(! args || ! args.callback_string || ! args.poll_url || ! args.pollid) {
			this.usage(); return;
		}
		this.callback_string = args.callback_string;
		this.callback_arguments = args.arguments;
		this.poll_url = args.poll_url;
		this.pollid = args.pollid;
		this.poll();
	}
	
	this.add_poller_callback = function(key, callback, poller) {
		POLLER_CALLBACK_LOOKUP[key] = {callback: callback, poller: this};		
	}
	
	this.poll = function(id) {
		this.count++;
		// quit after 10 minutes
		if((this.count * 500) > (1000 * 10 * 60)) {
			this.active = false;
		}
		if(this.active == true) {			
			var src =  this.poll_url;
			src += '?version=' + (new Date()).getTime();
			src += '&callback=' + escape(this.callback_string);
			src += '&pollid=' + this.pollid;
			if(this.callback_arguments) {
				var args = escape( Object.toJSON( this.callback_arguments ) );
				src += '&args=' + args;			
			}
			var script = document.createElement('script');
			script.src = src;
			var body = document.getElementsByTagName('body')[0];
			if(body) {
				body.appendChild(script);
			}
			var sto = function() { this.poll() }.bind(this);
			setTimeout(sto, 500);
		}
	} 	
	
	this.stop_polling = function() {
		this.active = false;
		this.count = 0;
	}
	
	this.usage = function() {
		var usage = "usage: cookie_poller.poll( {callback_string: 'afunction', poll_url: 'http://example/js/poll.js, pollid: 'a_unique_id', [ arguemnts: {} ] } )"
		console.error(usage);		
		console.error('cookie_poller.poll() needs a callback_string, a XSS poller url, a unique id and an optional arguments hash');		

	} 
}