//Namespace for all spectrum functions
var SDNA 	= SDNA || {};

//Event publisher/subscriber system that hooks into jQuery for its functionality

//  create/trigger model: 
//      - create/bind an event to a callback
//      - trigger that callback on-demand anywhere in the code
//        passing context-specific options
//  subscribe/publish model:
//      - subscribe/listen for an event with a custom callback
//      - publish/broadcast that event to all subscribers

//  what's the diff? with create/trigger you generally
//  have one callback you want triggered from multiple locations,
//  with subscribe/publish you generally have (potentially) many
//  subscribers/listeners who each do their own thing and 
//  one or (sometimes) many publishers who broadcast to these listeners

SDNA.Event = {
	
	subscribe : function(name,fn,opts){
	
	  jQuery().bind(name, function(e, data){
         
         //If this subscriber is bound to an event WITHIN a dom var
         //check to see if it has happened within that selector
         if( data.target && opts && opts.within ){
            if( jQuery( data.target).parents(opts.within).length > 0 ){
               fn(e,data);
            }
         }else{
            fn(e,data);
         }
     });
	   
	},

	unsubscribe : function(name,fn){
		jQuery().unbind(name, fn);
	},
	
	publish : function( name, data ){
		jQuery().trigger( name, data );
	},
	
	trigger : function(name,data){
		jQuery().trigger( name + '_handler', data );
	}, 

	create: function(name,fn){
		fn = fn || function( e, data){
			jQuery().trigger(name,data);
		};		
		jQuery().bind( name + '_handler',fn);		
	},

	destroy: function(name,fn){
		jQuery().unbind(name + '_handler',fn);
	}

};