// ==UserScript==
// @name		page_clipper
// @description		take a selection and log it, maybe with a category
// @include		*
// ==/UserScript==

// eek. just got:
// Error: uncaught exception: Permission denied to call method HTMLDocument.evaluate
// on http://www.useit.com/alertbox/wysiwyg.html
// which makes no sense at all...
function clip_current_selection(tag) {
  // post the url
  if (tag == undefined) { tag = "unknown"; }
  var txt1 = document.evaluate("//text()", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  var txt1_accum = "";
  for (var txt_i = 0; txt_i < txt1.snapshotLength; txt_i++) {
  	val = txt1.snapshotItem(txt_i).nodeValue;
	// possible alternative: bad-chars replacement
	// \u00a9 = &copy;
	// \u00ae = &reg;
	// \u2014 = &mdash; &#8212; (hex vs. decimal)
	// also look at diveintogreasemonkey-2005-05-09/examples/dumbquotes.user.js
	try {
	   btoa(val);
	   txt1_accum += val;
	   txt1_accum += " ";
        } catch (error) {
	   alert("bad chars in segment " + txt_i + " value " + val);
	   txt1_accum += " <badness removed> ";
	}
  }

  var txt2 = document.documentElement.innerHTML;
  GM_xmlhttpRequest(   {
     method: 'POST',
     url: 'http://localhost:3382/clip_this',
     headers: {
       'Content-type': 'application/x-www-form-urlencoded',
	 'ClipURL': window.location.href, // or document.URL, document.documentURI
	 'ClipCategory': tag,
	 'ClipSelection': encodeURIComponent(window.getSelection()),
	 'ClipTitle': document.title,
	 'ClipReferrer': document.referrer,
	 },
     data: btoa(txt1_accum), // full HTML
     onerror: function(detail) { alert(detail.statusText + ": got " + detail.responseText); },
		       });
  
}


// this set up Tools->UserScriptCommands->... items.
// I *want* context menu items, though.

GM_registerMenuCommand("Clip This", function() { clip_current_selection() ; });
// hmmm, add categories by querying the server for them?

// helper function needed to provide a scope to
// hold the closure; block scope *doesn't* do it...
function add_one_menu_item(thistag) {
   if (thistag) {
      GM_registerMenuCommand("Clip " + thistag,
           function() { clip_current_selection(thistag) ; }); 
   }
}

GM_xmlhttpRequest(   {
     method: 'GET',
     url: 'http://localhost:3382/tags',
     data: '',
     onerror: function(detail) { alert(detail.statusText + ": tags got " + detail.responseText); },
     onload: function (detail) {
	if (detail.status == 200) {
	    tags = detail.responseText.split(/\n/);
            for (tagno in tags) {
		add_one_menu_item(tags[tagno]);
	    }
	}
     },
});