// ==UserScript==
// @name           Vox Auto Link
// @namespace      www.vox.com
// @description    Shift+Link button to auto link to first search result for highlighted text. Or, Alt+Link to link to Wikipedia for that text.
// @include        http://www.vox.com/compose
// ==/UserScript==

linkButton = getElementsByClass("command-insert-link toolbar button")[0];
linkButton.setAttribute("onclick", "javascript:specialLink(event);");
voxEditorIFrame = document.getElementById("compose-entry-iframe");
unsafeWindow.urlBox = getElementsByClass("text url")[0];
var b;

unsafeWindow.specialLink = function(event){
	// Find the highlighted text
	highlightedText = voxEditorIFrame.contentWindow.document.getSelection();
	
	if (event.shiftKey==1){
		msnURL = "http://search.live.com/results.aspx?q=" + highlightedText + "&format=xml";
	
		GM_xmlhttpRequest ({	method: 'GET',
						url: msnURL, 
						onreadystatechange: function(responsedetails) {
							if (responsedetails.readyState == 4) {
								if (responsedetails.status == 200) {
									var parser = new DOMParser();
									seResponse = parser.parseFromString(responsedetails.responseText, "application/xhtml+xml");
									writeToUrlBox (seResponse.getElementsByTagName("url")[0].childNodes[0].wrappedJSObject.data);
								} 
								else {
									alert ("Something went wrong");
								}
							}
						}
					});
		}
	else if (event.altKey==1) {
		writeToUrlBox ("http://en.wikipedia.com/wiki/" + highlightedText.replace(/ /g, "_"));
	}
}

function writeToUrlBox (textToWrite) {
	// Wait for the box to appear
	b = setInterval ('if (canSeeUrlDialog()){urlBox.value=\"' + textToWrite + '\";}', 250);
}

unsafeWindow.canSeeUrlDialog = function() {
	urlDialog = document.getElementById("dialog-create-link");
	if (urlDialog.getAttribute("class").indexOf("visible") != 0) {
		// Turn off the timer
		clearInterval(b);
		return true;
	}
	else {
		return false;
	}
}

// Helper function to find elements by class name
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}