/*!
MinPubSub, modified for use on Kalendae
Copyright(c) 2011 Daniel Lamb <daniellmb.com>
https://github.com/daniellmb/MinPubSub
MIT Licensed
function(d){

	if (!d) d = this;

	// the topic/subscription hash
	var cache = d.c_ || {}; //check for "c_" cache for unit testing

	d.publish = function(/* String */ topic, /* Object */ target, /* Array? */ args){
		// summary:
		//		Publish some data on a named topic.
		// topic: String
		//		The channel to publish on
		// args: Array?
		//		The data to publish. Each array item is converted into an ordered
		//		arguments on the subscribed functions.
		//
		// example:
		//		Publish stuff on '/some/topic'. Anything subscribed will be called
		//		with a function signature like: function(a,b,c){ ... }
		//
		//		publish("/some/topic", ["a","b","c"]);

		var subs = cache[topic],
			len = subs ? subs.length : 0,
			r;

		//can change loop or reverse array if the order matters
		while(len--){
			r = subs[len].apply(target, args || []);
			if (typeof r === 'boolean') return r;
		}
	};

	d.subscribe = function(/* String */ topic, /* Function */ callback, /* Boolean */ topPriority){
		// summary:
		//		Register a callback on a named topic.
		// topic: String
		//		The channel to subscribe to
		// callback: Function
		//		The handler event. Anytime something is publish'ed on a
		//		subscribed channel, the callback will be called with the
		//		published array as ordered arguments.
		//
		// returns: Array
		//		A handle which can be used to unsubscribe this particular subscription.
		//
		// example:
		//		subscribe("/some/topic", function(a, b, c){ /* handle data */ });

		if(!cache[topic]){
			cache[topic] = [];
		}
		if (topPriority)
			cache[topic].push(callback);
		else
			cache[topic].unshift(callback);
		return [topic, callback]; // Array
	};

	d.unsubscribe = function(/* Array */ handle){
		// summary:
		//		Disconnect a subscribed function for a topic.
		// handle: Array
		//		The return value from a subscribe call.
		// example:
		//		var handle = subscribe("/some/topic", function(){});
		//		unsubscribe(handle);

		var subs = cache[handle[0]],
			callback = handle[1],
			len = subs ? subs.length : 0;

		while(len--){
			if(subs[len] === callback){
				subs.splice(len, 1);
			}
		}
	};

}