// ==UserScript==
// @name           Auto Twitter from LDR
// @namespace      http://ma.la/
// @description    Post your current reading feed to Twitter from livedoor Reader.
// @include        http://reader.livedoor.com/reader/*
// ==/UserScript==
/*
 history:
  http://la.ma.la/blog/diary_200704072114.htm
*/
(function(){
	var w = (typeof unsafeWindow == "undefined") ? window : unsafeWindow;
	var freq = 5; //  => random post 1/5
	var interval = 60 * 10; // wait 600 second per post
	var post_after = 2;
	var last_posted = null;
	with (w) {
		function post_twitter(status){
			GM_xmlhttpRequest({
				method : 'POST',
				url	: 'http://twitter.com/statuses/update.json',
				headers: {
					'Content-type': 'application/x-www-form-urlencoded',
				},
				data   : 'status=' + encodeURIComponent(status),
				onload : function(res) {
					message('twittered!');
				},
				onerror: function(res) {
					var err = 'Failed - ' + res.status + ': ' + res.statusText;
					message(err);
				},
			});
		}
		function check_interval(){
			if(!last_posted) return true;
			if((new Date - last_posted) > (interval * 1000)) return true;
			return false;
		}
		register_hook('BEFORE_PRINTFEED', function(feed){
			var tmp = Math.floor(Math.random() * freq);
			if(tmp != 0) return;
			if(!check_interval()) return;
			var id = feed.subscribe_id;
			var task = function(){
				if(id != State.now_reading) return;
				last_posted = new Date() - 0;
				post_twitter("I'm reading " + 
	 				feed.channel.title + "\n" + 
	 				feed.channel.link
				);
			};
			// only post public feed
			if(subs_item(id) && subs_item(id)["public"] == 1){
				setTimeout(task, post_after * 1000);
			}
		});
	};
})();
