CmdUtils.CreateCommand({
	names: ["amplify"],
	description: "Shows the most prominent topics and their polarity in the currently open website or selected text.",
	help: 
		"To analyze a website, make sure you don't have any text selected and run the command.<br/><br/>" + 
		"To analyze a piece of text, select that text and then run the command.<br/><br/>" + 
		"<h3>Definitions:</h3>" + 
		"<strong>topic</strong>: A noun from the text.<br/>" +
		"<strong>prominence</strong>: The weighted rank of a topic in the text.<br/>" +
		"<strong>polarity</strong>: The attitude expressed towards a topic in the text.<br/><br/><br/><br/>" + 
		"Powered by <a href='http://www.openamplify.com'>OpenAmplify</a><br/><br/>" +
		"<!-- Creative Commons License -->" +
		"<a href='http://creativecommons.org/licenses/GPL/2.0/'>" +
		"<img alt='CC-GNU GPL' border='0' src='http://creativecommons.org/images/public/somerights20.png' /></a><br />" +
		"<small>This software is licensed under the <a href='http://creativecommons.org/licenses/GPL/2.0/'>CC-GNU GPL</a> version 2.0 or later.</small>" +
		"<!-- /Creative Commons License -->",
	author: {name: "Natasha Lloyd", email: "nblloyd@gmail.com"},
	license: "CC-GNU GPL",
	homepage: "http://www.natashascorner.com/",
	icon: "http://www.natashascorner.com/ubiquity/img/favicon.ico",
  
	_selection: function() {
		var selection;
		var selectionType;
		if (CmdUtils.getSelection().length > 0) {
			selection = CmdUtils.getSelection();
			selectionType = "inputText";
		}
		else {
			selection = CmdUtils.getWindow().location;
			selectionType = "sourceURL";
		}
		return {type: selectionType, text: selection}; 
	},
	
	_getAmplifyURL: function() {
		var baseURL = "http://portaltnx.openamplify.com/AmplifyWeb_v11/AmplifyThis?";
		var params = {
			apiKey: "nh7phtx9mapckvqfxm2eun66abf6zs5y",
			analysis: "topics",
			outputFormat: "xml"
		};
		
		var selectionType = this._selection()["type"];
		var selectionText = this._selection()["text"];
		var finalURL;
		if (selectionType == "inputText") {
			params[selectionType] = selectionText;
			finalURL = baseURL + $.param(params);
		}
		else {
			finalURL = baseURL + $.param(params) + "&" + selectionType + "=" + selectionText;
		}
		
		return finalURL;
	},
	
	preview: function preview(pblock, args) {
		var url = this._getAmplifyURL();
		var previewHTML = "";
		
		// some basic error checking
		if (this._selection()["type"].toString() == "sourceURL") {
			var selURL = this._selection()["text"].toString();
			var protocol = selURL.substring(0, selURL.indexOf("://"));
		
			if (protocol.toLowerCase() != "http") {
				previewHTML = previewHTML + "Error: Cannot amplify the current selection."
				pblock.innerHTML = previewHTML;
				return;
			}
		}
		
		previewHTML = previewHTML + 
			"<div align='center'><br/><br/>Amplifying...<br/><br/>" + 
			"<img src='http://www.natashascorner.com/ubiquity/img/ajax-loader(3).gif'/></div>";
		pblock.innerHTML = previewHTML;
		
		CmdUtils.previewGet(
			pblock, 
			url, 
			{}, 
			function(xml) {
				var baseChartURL = "http://chart.apis.google.com/chart?";
				var chartData = "t:";
				var chartLabels = "";
				var chartColors = "";
				var topics = [];
				var html = "";
				var maxValue = 0;
				
				$(xml).find("Topics").find("TopTopics").find("Topic").each(function(i) {
					var topic = $(this).find("Name").text();
					var value = $(this).find("Value").text();
					topics[i] = [];
					topics[i]["topic"] = topic;
					topics[i]["value"] = value;
					
					chartData = chartData + parseFloat(value).toFixed(0) + ",";
					
					if (i == 0) maxValue = parseFloat(value).toFixed(0);
				});
				
				$(xml).find("Topics").find("TopTopics").find("Polarity").each(function(i) {
					var polarity = $(this).find("Mean").find("Value").text();
					topics[i]["polarity"] = polarity;
					
					var polVal = parseFloat(polarity).toFixed(2);
					var color = "000000";

					if (polVal < -0.5) {		// strong negative
						color = "EE2E2F";
					}
					else if (polVal < 0.0) {	// weak negative
						color = "F15A5F";
					}
					else if (polVal == 0.0) {	// neutral
						color = "C2D087";
					}
					else if (polVal < 0.5) {	// weak positive
						color = "7AC36A";
					}
					else {						// strong positive
						color = "1E8C48";
					}
					
					chartColors = chartColors + color + "|";
				});
				
				// topics need to be in reverse order from values
				for (var i = topics.length - 1; i >= 0; i--) {
					var topic = topics[i]["topic"];
					var polarity = parseFloat(topics[i]["polarity"]).toFixed(2);
					var sym = "";
					
					if (polarity < 0.0) sym = "&darr;";
					else if (polarity == 0.0) sym = "&ndash;";
					else sym = "&uarr;";
					
					chartLabels = chartLabels + escape(topic) + " " + sym + "|";
				}
				
				chartData = chartData.substring(0, chartData.length - 1);
				chartLabels = chartLabels.substring(0, chartLabels.length - 1);
				chartColors = chartColors.substring(0, chartColors.length - 1);
				
				var chartURL = baseChartURL + 
					"cht=bhs" +					// chart type
					"&chxt=x,y" +					// axis
					"&chs=300x" + (topics.length * (15 + 4) + 16) +	// chart size
					"&chbh=15,4,4" + 			// bar size and spacing
					"&chf=bg,s,FFFFFF00" +		// chart background (transparent)
					"&chm=N,FFFFFF,0,-1,11" +	// data labels
					"&chxs=0,DDDDDD|1,FFFFFF" +			// axis text color
					"&chco=" + chartColors +	// bar colors
					"&chds=0," + maxValue + 	// scale
					"&chd=" + chartData + 		// chart data
					"&chxl=0:| |prominence| |1:|" + chartLabels;	// axis labels
					
				html = html + "Polarity of Top Topics by Prominence<br/><br/>";
				if (topics.length == 0) {
					html = html + "No topics found.";
				}
				else {
					html = html + "<img src='" + chartURL + "' style='vertical-align:top;margin-right:40px'/>";
					html = html + "<img src='http://chart.apis.google.com/chart?cht=bhs&chxt=r&chs=100x130&chma=0,0,0,0&chtt=___ Polarity&chts=DDDDDD,12&chbh=15,4,4&chf=bg,s,FFFFFF00&chxs=0,DDDDDD&chco=ee2e2f|f15a5f|c2d087|7ac36a|1e8c48&chds=0,1&chd=t:1,1,1,1,1&chxl=0:|↑ Very%20Positive|↑ Positive|– Neutral|↓ Negative|↓ Very%20Negative' style='vertical-align:top'/>";
				} 
				pblock.innerHTML = html;
			}
		);		
	},

	execute: function execute(args) {
		//displayMessage("You selected: " +  this._selection()["type"] + "=" + this._selection()["text"], this);
	}
});