
var DownloadManager = {
	filenameHash: {},
	addDownload: function (url, title) {
		var ios =  Components.classes["@mozilla.org/network/io-service;1"]
						.getService(Components.interfaces.nsIIOService);
		var dm =  Components.classes["@mozilla.org/download-manager;1"]
						.getService(Components.interfaces.nsIDownloadManager);

		var path = dm.userDownloadsDirectory.path;
		var sourceUri = ios.newURI(url, null, null);

		var file;
		do {
			file = Components.classes["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsILocalFile);
			file.initWithPath( path );
			var filename = title.replace(/["\\\*\:\?\<\>\/\|]/, '');
			var ext = sourceUri.path.match( /\.gif\b/i ) ? ".gif" :
					sourceUri.path.match( /\.jpe?g\b/i ) ? ".jpg" :
					sourceUri.path.match( /\.png\b/i ) ? ".png" :
					sourceUri.path.match( /\.tiff?\b/i ) ? ".tiff" : "";
			if ( this.filenameHash[filename] ) {
				var suffix = ++this.filenameHash[filename];
				filename += "-" + suffix;
			} else {
				this.filenameHash[filename] = 1;
			}
			file.append( filename + ext );
		} while ( file.exists() );

		var persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
			.createInstance(Components.interfaces.nsIWebBrowserPersist);

		var targetUri = ios.newFileURI(file);
		download = dm.addDownload(0, sourceUri, targetUri, title, null, null, null, persist);
		persist.progressListener = download;
		persist.saveURI(sourceUri, null, null, null, null, file);
	},
	post : function(params){
		this.addDownload(params.source, params.title);
		return succeed();
	},
}

DownloadManager.Photo = {
	convertToForm : function(m){
		return {
			title : m.title,
			url : m.source
		};
	}
}

Tombloo.Service.posters['DownloadManager'] = function (ctx, params) {
	if ( params.type == 'photo' ) {
		return DownloadManager.post(params);
	} else {
		return succeed();
	}
}


