window.BEN = window.BEN || {};

BEN.UI = function() {};
BEN.Util = function() {};


BEN.Util.FeedManager = function() {
	this.feeds = {};
}
BEN.Util.FeedManager.prototype = {
	addFeed: function(id, config, callback, int) {
		if (id != '') {	
			var feed = {};
			var that = this;
			callback = $.isFunction(callback) ? callback : function(){};
			
			feed.control = new BEN.Util.Feed(config, function(o) {
				feed.response = o;
				callback(that.getFeed(id));
			}, int);
			
			if (this.feeds[id] == null) this.feeds[id];
			this.feeds[id] = feed;
		}
	},
	getFeed: function(id) {
		return this.feeds[id].response;
	},
	updateFeed: function(id) {
		this.feeds[id].control.fetch();
	}
}

BEN.Util.Feed = function(feed, callback, int) {
	this.feed = $.extend({}, {type:"GET", data:""}, feed);
	
	var isFn = $.isFunction(callback);
	this.callback = isFn ? callback : function(){};
	
	this.fetch();
	if (int && int > 0) this.startInterval(int);
}
BEN.Util.Feed.prototype = {
	fetch: function() {
		var that = this;
		var feed = this.feed;
		var callback = {
			success: function(d,t,x) {that.parse(d,t,x)},
			failure: function(x,t,e) {that.error(e)}
		}
		$.ajax({
			url:feed.url,
			type:feed.type,
			data:feed.data,
			success:callback.success,
			error:callback.error
		});
	},
	parse: function(data, text, xml) {
		this.callback({data:data, text:text, xml:xml});
	},
	error: function(error) {
		this.callback({error:error});
	},
	stopInterval: function() {
		clearInterval(this.interval);
	},
	startInterval: function(interval) {
		var that = this;
		this.interval = setInterval(function() {that.fetch()}, interval * 1000);
	}
}


// UI Tooltip
BEN.UI.prototype.tooltip = function(e, o) {
	var settings = $.extend({}, {
		position: {
			corner: {
				target: "topMiddle",
				tooltip: "bottomMiddle"
			}
		},
		style: {
			name: "dark",
			tip: {
				corner: "bottomMiddle",
				size: {
					x: 10,
					y: 5
				}
			},
			border: {radius: 5}
		},
		show: {
			effect: {
				type: "fade",
				length: 250
			}
		},
		hide: {
			delay: 250,
			fixed: true
		}
	}, o || {});
	$(e).qtip(settings);
};