CmdUtils.CreateCommand({
	name: "shorturl",
	homepage: "http://www.erikvold.com/tools/ubiquity/shorturl/shorturl.cfm",
	icon:"",
	description:'Replaces the selected URL with a <a title="RevCanonical URL" href=\"http://revcanonical.appspot.com/\">Rev-Canonicalized URL</a> of less than 44 characters or else a <a title="TinyURL" href=\"http://www.tinyurl.com\">TinyUrl</a>.',
	help:"",
	author: { name: "Erik Vold", email: "erikvvold@gmail.com"},
	contributors: ["Erik Vold"],
	license: "MPL",
	version: "0.1",
	takes: {"word": noun_arb_text},
	preview: function (pblock, directObject) {
		// Display immediate preview message.
		pblock.innerHTML = "Replaces the selected url with ..";

		// get selected url
		var selectedURL=jQuery.trim(directObject.text);
		if(selectedURL==""){
			selectedURL=context.focusedWindow.document.location;
		}

		// get revcanonical url or tinyurl
		jQuery.ajax({
			type:"GET",
			dataType:"text",
			url:"http://revcanonical.appspot.com/api?url="+selectedURL,
			error:function(){
				displayMessage("There was an error.");
			},
			success:function(response){				
				var shortURLString = jQuery.trim(response+"");
				
				displayMessage(shortURLString.length);
				
				if(shortURLString.length>44){
					jQuery.get( "http://tinyurl.com/api-create.php?url="+selectedURL,
								function( tinyUrl ) {
									if (tinyUrl != "Error") {
										// display the tinyURL
										pblock.innerHTML = "Replaces the selected url with "+tinyUrl;
									}
									else{
										displayMessage("There was an error.");
									}
								}
					);
					
					return;
				}

				// display the revcanonical url
				pblock.innerHTML = "Replaces the selected url with "+shortURLString;

				return;
			}
		});

		return;
	},
	execute: function( directObject ) {
		// get selected url
		var selectedURL=jQuery.trim(directObject.text);
		if(selectedURL==""){
			selectedURL=context.focusedWindow.document.location;
		}

		// get revcanonical url
		jQuery.ajax({
			type:"GET",
			dataType:"text",
			url:"http://revcanonical.appspot.com/api?url="+selectedURL,
			error:function(){
				displayMessage("There was an error.");
			},
			success:function(response){
				var shortURLString = jQuery.trim(response+"");

				if(shortURLString.length>44){
					jQuery.get( "http://tinyurl.com/api-create.php?url="+selectedURL,
								function( tinyUrl ) {
									if (tinyUrl != "Error") {
										// set the selection to the tinyURL
										CmdUtils.setSelection(tinyUrl);	
									}
									else{
										displayMessage("There was an error.");
									}
								}
					);
					
					return;
				}

				// set the selection to the revcanonical url
				CmdUtils.setSelection(shortURLString);

				return;
			}
		});

		return;
	}
});

