CmdUtils.CreateCommand({
	name: "diggthis",
	takes: {"url": noun_arb_text},
	icon: "http://digg.com/favicon.ico",
	homepage: "http://www.gialloporpora.netsons.org",
	author: { name: "Sandro Della Giustina", email: "sandrodll@yahoo.it"},
	license: "MPL,GPL",
	description: 'Submit or vote a story on Digg',
	help: 'If story is already submitted on Digg you can vote for it, votes are shown on preview. If story is not submitted on Digg you can easily submit it',
	_aboutsel: function(sel, no_sel_msg, max_chars){
		var html='';
		if (!no_sel_msg) no_sel_msg='You have not selected text';
		if (sel.length>0) {
				html+='<ul>';
				html+='<li>You  have selected <b>'+sel.length+'</b> characters. </li>';
				html+='<li>You have selected <b>'+sel.match(/\b\w+\b/g).length+'</b> words.</li>';
				if (max_chars)	
					if (sel.length>max_chars) html+='<li><b>'+eval(sel.length-max_chars)+'</b> characters will be truncated.</li>';
					html+='</ul>';
				}
			else html+=no_sel_msg;
		return html;
		},
	execute: function( directObj) {
			var page=context.focusedWindow.document;
		// var selected_text=directObj.text;
		var selected_text=page.getSelection();
		selected_text=selected_text.substring(0,375);
		var params = Utils.paramsToString({
			phase: "2",
			url: page.location,
			title: page.title,
			bodytext: selected_text
		});
		story_url='http://digg.com/submit'+params;
		Utils.openUrlInBrowser(story_url);
	},
	preview: function( pblock, directObj) {
		var page= context.focusedWindow.document;
		// var selected_text=directObj.text;
		var selected_text=page.getSelection();
		about_selection=this._aboutsel(selected_text,'You have selected no text. If you select text it will be used  as description in  of the story on Digg',375);
		var api_url='http://services.digg.com/stories';
		var params = Utils.paramsToString({
			appkey: "http://www.gialloporpora.netsons.org",
			link: page.location
		}); 
		var html='Vote for this page on Digg or submit it.<br/>';
		jQuery.ajax({  
			type: "GET",
			url: api_url+params,
			error: function(){
				pblock.innerHTML=CmdUtils.renderTemplate(html+'<b>WARNING</b>: Digg API is unavailable or the URI is incorrect.<br/>');
			},
			success: function(xml){
				var el = jQuery(xml).find("story");
				var diggs=el.attr("diggs");
				if (diggs==null){ 
					html+='This page has not been submitted to Digg,  press <b>ENTER</b> to submit it now.<br/>';
					html+=about_selection;
				}

					else html+='This story has digged <b>'+diggs+'</b> times. Press <b>ENTER</b> and digg it too.';
					pblock.innerHTML=CmdUtils.renderTemplate(html);
		    }
		        });
		    
		    }
});
