// ==UserScript==
// @name           Link Code Insert
// @namespace      http://www.openjs.com/
// @description    Inserts the HTML code for creating a link at the active element location when the user presses Ctrl+Alt+A
// @include        *

//by Binny V A (http://www.openjs.com/)
//Versions : 1.00.A
// ==/UserScript==

function linkCodeInserter(element) {
	// If the selection is empty
	if(element.selectionStart == element.selectionEnd) {
		element.value += '<a href=""></a>';
		element.selectionStart = element.selectionEnd = element.value.length - 6;// The length of ["></a>]
		
	} else {
		// Get the selected text.
		var text_to_selection = element.value.substr(0, element.selectionStart);
		var text_in_selection = element.value.substr(element.selectionStart, element.selectionEnd - element.selectionStart);
		var text_after_selection = element.value.substr(element.selectionEnd);
	
		element.value = text_to_selection + '<a href="">' + text_in_selection + '</a>' + text_after_selection;
		element.selectionStart = element.selectionEnd = text_to_selection.length + 9;// The length of [<a href="]
	}
}

//Call the insertLink function when Ctrl+Shift+M key is pressed
function linkCodeInserterKeyChecker(e) {
	if (e.shiftKey && e.ctrlKey) {
		var element = e.target;
		if(element.tagName == 'TEXTAREA' || (element.tagName == 'INPUT' && element.getAttribute('type') == 'text')) { //Make sure this get only activated in text fields
			if(e.keyCode == 65) {//A
				linkCodeInserter(element);
	
				//Prevent the key to be handled by the browser
				e.stopPropagation();
				e.preventDefault();
				return false;
			}
		}
	}
}
window.addEventListener("keydown", linkCodeInserterKeyChecker, true);
