

var x, y;
var rect;
var ctx;
var canvas;

var email = 'me@example.com';
var passwd = 'xxxxxxx';

	function $(id) {
		return document.getElementById(id);
	}

{
function HTTP(){ }
/**	
 * opts
 *		async		returns async input stream.
 *		headers		additional http request headers.
 *		onStartRequest
 *		onDataAvailable
 *		onStopRequest
 *		notificationCallbacks
 */
HTTP.Request = function (uri, opts) {
	var VERSION = '0.0.1';

	this.uri = uri;
	this.opts = opts || {};
//	this.channel = null;
	const CC = Components.classes;
	const CI = Components.interfaces;
	this.ios = CC["@mozilla.org/network/io-service;1"].getService(CI.nsIIOService);

	this.request_channel = null;
	this.response_body = null;

	this.create_string_input_stream = function ( ) {
		return CC["@mozilla.org/io/string-input-stream;1"].
				createInstance(CI.nsIStringInputStream);
	};
	
	var self = this;
	[ 'onStopRequest', 'onDataAvailable', 'onStartRequest' ].forEach( function (n) {
		if ( self.opts[n] )
			self[n] = self.opts[n];
	} );
}
HTTP.Request.boundary = 'DEADBEEF_DEADBEEF';
HTTP.Request.prototype.onDataAvailable = function (req, context, stream, offset, length) {
	var ss = Components.classes['@mozilla.org/scriptableinputstream;1'].
					createInstance(Components.interfaces.nsIScriptableInputStream);
	ss.init(stream);
	this.response_body += ss.read(length);
}
HTTP.Request.prototype.onStartRequest = function () {
	this.response_body = '';
}
HTTP.Request.prototype.onStopRequest = function (request, context, statusCode) {
}

HTTP.Request.prototype.urlencode = function () {
	var pairs = [];
	for (var n in this.params ) {
		pairs.push ( [ n, encodeURIComponent(this.params[n]) ].join('=') );
	}
	return pairs.join("&");
}
HTTP.Request.prototype.set_multipart_params = function () {
	var post_data_stream = Components.classes["@mozilla.org/io/multiplex-input-stream;1"].
	            createInstance(Components.interfaces.nsIMultiplexInputStream);

	var content_type = "multipart/form-data; boundary=" + HTTP.Request.boundary;

	var pairs = [];
	for (var name in this.params ) {
		var streams;
		var value = this.params[name];

		if ( value instanceof Components.interfaces.nsIFile ) {
			streams = this.create_stream_from_file(name, value);
		} else if ( value.stream ) {
			streams = this.create_stream(name, value.stream, value);
		} else {
			var stream = this.create_string_input_stream();
			var chunk = "--" + HTTP.Request.boundary + '\r\n';
			chunk += 'Content-Disposition: form-data; name="' + name + '"' + '\r\n';
			chunk += '\r\n' + value + '\r\n';
			stream.setData(chunk, chunk.length);
			streams = [ stream ];
		}	
		streams.forEach( function (s) {
			post_data_stream.appendStream(s);
		} );
	}

	var chunk = '\r\n--' + HTTP.Request.boundary + '--\r\n';
	var stream = this.create_string_input_stream();
	stream.setData(chunk, chunk.length);
	post_data_stream.appendStream(stream);
	
	var mime_stream = Components.classes["@mozilla.org/network/mime-input-stream;1"]
			.createInstance(Components.interfaces.nsIMIMEInputStream);

	mime_stream.addHeader("Content-Type", content_type);
	mime_stream.addContentLength = true;
	mime_stream.setData(post_data_stream);
	return mime_stream;
}

HTTP.Request.prototype.create_stream = function (param_name, input, stream_params) {
	var buffered_stream = Components.classes["@mozilla.org/network/buffered-input-stream;1"].
				createInstance(Components.interfaces.nsIBufferedInputStream);

	buffered_stream.init(input, 4096);

	var chunk =  "--" + HTTP.Request.boundary + '\r\n';
	chunk += 'Content-Disposition: form-data; name="';
	chunk += param_name + '";';
	if ( stream_params.filename ) {
		chunk += 'filename="' + stream_params.filename + '"' +  '\r\n';
	}
	if ( stream_params.contentType ) {
		chunk += "Content-Type: " + stream_params.contentType + '\r\n';
		chunk += '\r\n';
	}

	var sis = Components.classes["@mozilla.org/io/string-input-stream;1"].
	            createInstance(Components.interfaces.nsIStringInputStream);
	
	sis.setData(chunk, chunk.length);
	return [sis, buffered_stream];
}

HTTP.Request.prototype.create_stream_from_file = function (param_name, file) {
	var uploadfile_uri = this.ios.newFileURI(file);
	var channel = this.ios.newChannelFromURI( uploadfile_uri );
	var input = channel.open();
	return this.create_stream(param_name, input, {filename: file} );
}
HTTP.Request.prototype.setup_channel = function (uri) {
	var uri = this.ios.newURI(this.uri, 'UTF-8', null);
	this.request_channel = this.ios.newChannelFromURI(uri);
}

HTTP.Request.prototype.set_params = {
	GET: function () {
		var query = this.urlencode();
		if ( query != '' ) {
			this.uri += ( ( this.uri.indexOf('?') >= 0) ? '&' : '?' ) + query; 
		}
		this.setup_channel();
	},
	POST: function () {
		var content_type = 'application/x-www-form-urlencoded';
		var post_data_stream;
		if ( this.opts.multipart ) {
			content_type = null;
			post_data_stream = this.set_multipart_params();
		} else {
			var query = this.urlencode();
			post_data_stream = this.create_string_input_stream();
			post_data_stream.setData(query, query.length);
			//post_data_stream = sis;
		}
		this.setup_channel();
		this.request_channel.QueryInterface(Components.interfaces.nsIUploadChannel);
		this.request_channel.setUploadStream(post_data_stream, content_type, -1);
	},
}

HTTP.Request.prototype.send_request = function (method, params) {
	this.params = params;
	var fn = this.set_params[method];
	fn.apply(this);

	this.request_channel.QueryInterface( Components.interfaces.nsIHttpChannel);
	this.request_channel.requestMethod = method;
	this.request_channel.notificationCallbacks = this.opts.notificationCallbacks;
	
	var response_input_stream = ( this.opts.async ) ?
			this.request_channel.asyncOpen(this, this) :
			this.request_channel.open() ;

	if ( ! this.opts.async ) {
		var ss = Components.classes['@mozilla.org/scriptableinputstream;1'].
						createInstance(Components.interfaces.nsIScriptableInputStream);
		ss.init(response_input_stream);
		this.response_body = '';
		var n;
		while ( n = ss.available() ) {
			this.response_body += ss.read(n);
		}
		return this.response_body;
	}
}

HTTP.Request.prototype.get = function (params) {
	return this.send_request('GET', params);
}
HTTP.Request.prototype.post = function (params) {
	return this.send_request('POST', params);
}

HTTP.Request.Util = {
	open_file: function (filename) {
		var file = Components.classes["@mozilla.org/file/local;1"]
							.createInstance(Components.interfaces.nsILocalFile);
		file.initWithPath(filename);
		return file;
	}
}

}

var Tumblr = {
	endpoint: 'http://www.tumblr.com/api/',
	post: function (params, opts) {
		var uri = this.endpoint + 'write';

		opts.multipart = ( params.type.match(/^(audio|video|photo)$/) );
		return new HTTP.Request(uri, opts).post(params);
	},
}

function init() {
	var player = $("playerDiv");
	rect = player.getBoundingClientRect();
	x =  rect.right - rect.left;
	y = rect.bottom - rect.top;

	canvas = document.createElement('canvas');
	canvas.setAttribute("id", "svcanvas");
	canvas.style.display = "inline";
	canvas.width = x;
	canvas.height = y;

	document.body.appendChild(canvas);
	ctx = canvas.getContext("2d");

	ctx.clearRect(0, 0, x, y);

	 ctx.save();
	 ctx.scale(1.0, 1.0);
}


function post(title, bstream) {
try {
		var uri = window.document.location.href;
		log(uri);
		Tumblr.post( {
			email: email,
			password: passwd,
			type: 'photo',
			caption: title.link(uri),
			generator: 'tagiru.tumblr.js (http://ido.nu/kuma/)',
//			source: uri,
			data: {contentType: 'image/png', stream: bstream},
		}, {
			async: true,
			onStopRequest: function (request, context, statusCode) {
				request.QueryInterface(Components.interfaces.nsIHttpChannel);
				log(request, context, statusCode);
				//var text = request.responseStatusText;
				//trace(this.response_body);
				//if ( ImageSaver.conf.id ) {
				//	text = text.fontcolor("white").link(
				//		'http://' + ImageSaver.conf.id + '.tumblr.com/post/' +
				//		this.response_body
				//	);
				//}
				//ImageSaver.close_text_delayed(text);
			}
		} );

} catch (e) {
	log(e);
}

};

function log( ) {
	Firebug.Console.log(arguments);
}

try{
	init();
	var suffix = 0;

	var timerid = window.setInterval( function () {

		var x1 = rect.left + window.pageXOffset;
		var y1 = rect.top  + window.pageYOffset;
		var x2 = x1 + x;
		var y2 = y1 + y;

		ctx.drawWindow(window, x1, y1, x2, y2, "rgb(255,255,255)");
		ctx.restore();

		var url = canvas.toDataURL("image/png");

		const ios = Components.classes['@mozilla.org/network/io-service;1'].getService(Components.interfaces.nsIIOService);
		url = ios.newURI(url, null, null);

		var channel = ios.newChannelFromURI( url );
		var input = channel.open();
		var bstream = Components.classes["@mozilla.org/binaryinputstream;1"]
			.createInstance(Components.interfaces.nsIBinaryInputStream);
		bstream.setInputStream(input);

		var uc = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"]
						.createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
		uc.charset = 'UTF-8';
		var title = uc.ConvertFromUnicode(document.title);

if ( 0 ) {
		post(document.title, bstream);

	//	window.clearInterval(timerid);
	//
	//
} else {
		var f = "/home/kuma/Desktop/miyagi/p"  + suffix + ".png";

		suffix++;

		log(f);

		var aFile = Components.classes["@mozilla.org/file/local;1"]
			.createInstance(Components.interfaces.nsILocalFile);

		aFile.initWithPath( f );

		var wbp = Components.classes['@mozilla.org/embedding/browser/nsWebBrowserPersist;1']
			.createInstance(Components.interfaces.nsIWebBrowserPersist);
		wbp.saveURI(url, null, null, null, null, aFile);
}


	}, 1000);

}catch(e) {
	log(e)
}


