// ==UserScript==
// @name          TaskToy Insert Timestamp
// @namespace     http://www.cs.ucf.edu/~cmillward/
// @description   Hit CTRL+SHIFT+T to insert a timestamp into notes textarea at cursor.
// @include       http://tasktoy.com/TaskDetails*
// @include       http://*.tasktoy.com/TaskDetails*
// ==/UserScript==
// Author: Chris Millward <chris.millward@gmail.com>
// insertAtCursor - modified from http://www.alexking.org/index.php?content=software/javascript/content.php
//
// ==Version 0.2 - Bugfix: now positions the cursor after the inserted timestamp
// ==Version 0.1 - original

(function () {

    function insertAtCursor(myField, myValue) {
	var startPos = myField.selectionStart;
	var endPos = myField.selectionEnd;
	myField.value = myField.value.substring(0, startPos)
	    + myValue 
	    + myField.value.substring(endPos, myField.value.length);

	// this sets the cursor position at the end of the inserted value
	var cursorPos = endPos+myValue.length;
	myField.setSelectionRange(cursorPos, cursorPos);
    }

    function keyPressHandler(event)
	{
	    // following line set the key sequence to trigger command
	    if (event.charCode == 84 && event.ctrlKey && event.shiftKey)
		{
		    var allTAs, myTA;
		    allTAs = document.evaluate(
					       "//textarea[@name='notes']",
					       document,
					       null,
					       XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
					       null);
		    if ( 1 <= allTAs.snapshotLength ) {
			myTA = allTAs.snapshotItem(0);
		    }
      
		    if (myTA != null)
			{
			    // the timestamp string
			    var timestamp = "\n"+(new Date()).toLocaleString()+" ";
			    insertAtCursor(myTA, timestamp); 
			    myTA.focus();
			}
		}
	}

    // this sets up the listener
    document.addEventListener("keypress", keyPressHandler, true);


})();
