/* Social: An event handler for user interactions
You can observe any Social.xxx function that doesn't begin with an underscore (except for the observe function) thusly:
	social.observe([function name],handler);
	eg:
	social.observe('quickpost',function(obj){...});
*/
var Social = function(){
	this.quickpost = function(obj) {
	
	}
	
	this.contribute = function(obj) {
		
	}
	
	this.vote = function(obj){
		
	}
	
	this.quiz_result = function(obj) {
		
	}
	
	// Rewrite functions to call social._fire_event when they are invoked.
	// Skip the observe function and any function that begins with an underscore.
	this._init = function(){
		var starts_with_underscore = new RegExp('^_');
		for ( var each in this ) {
			if ( typeof this[each] == 'function' && each != 'observe' && !each.match(starts_with_underscore) ) {
				this['_'+each] = this[each];
				this[each] = Function('obj','social._'+each+'(obj);social._fire_event("'+each+'",obj);');
			}
		}
	}
	
	// Add a listener to an event's queue
	this.observe = function(event, fn){
		if ( typeof this[event] == 'function' ) {
			var observers = typeof this._observers[event] == 'undefined' ? [] : this._observers[event];
			var ok = true;
			observers.each( function(fn2){
				if ( fn == fn2 ) ok = false;
			});
			if ( ok ) {
				observers.push( fn );
				this._observers[event] = observers;
			}
		}
	}
	
	// Invoke each function in an event's queue
	this._fire_event = function(event, args) {
		var observers = typeof this._observers[event] == 'undefined' ? [] : this._observers[event];
		observers.each(function(fn){
			try{
				fn(args);
			} catch(e){
				console.warn(e);
			}
		})
	}
	this._observers = {};
	
	// Pull elements from universal_dom buckets named [type]-[key]
	// eg: <div class="bf_dom" rel:bf_bucket="facebook-logged-in" /> would be pulled like this:
	// social._get_ui_elements('facebook','logged-in');
	this._get_ui_elements = function(type,key,opts) {
		if ( !opts ) opts = {};
		var elements = [];
		if (typeof universal_dom != 'undefined' && typeof universal_dom._bucket[type + '-' + key] != 'undefined' ) {
			universal_dom._bucket[type + '-' + key].elements.each(function(obj){
				if ( opts.with_data ) {
					elements.push(obj);
				}
				else elements.push(obj.element);
			});
		}
		return elements;
	}

}
var social;
if ( typeof BuzzLoader != 'undefined' ) {
BuzzLoader.register(function(){
	social = new Social();
	social._init();
},1)
}
