// ==UserScript==
// @name		Backpack Note Enhancer
// @namespace	http://*.backpackit.com/
// @description	Adds note-body-visibility toggling persistence to Backpack notes
// @include		http://*.backpackit.com/*
// ==/UserScript==

// By Ben Karel

(function() {

var db_url = 'http://eschew.org/projects/dmd/backpack/';
// normalized path, deals with notes on homepages and anchored URLs
// example: "dmd/pages/12345678" or "eschew/"
var page = document.location.hostname.replace('.backpackit.com', '') + document.location.pathname;
db_url = db_url + '?page=' + page;

var xapply = function(xpath, func) {
  var x = document.evaluate(xpath, document, null, 6, null);
  for(var i = 0; i < x.snapshotLength; i++)
    func(x.snapshotItem(i));
};

xapply('//div[@id="notes"]//span[@class="link_to_edit_container"]/span[@class="link_to_edit_nubbin"]',
  function(node){
	var note = node.id.match( /note_(\d+)/ )[1];
	var t = document.createElement('span');
	t.textContent = '<'; // default to open state
	t.id = "note_"+note+"_toggler";
	t.addEventListener('click', toggle_click, true);
	node.appendChild(t);
  });

function toggle_click(e) {
	var e = this;  e.textContent = (e.textContent == '<') ? '>' : '<';
		// go from clicked widget > onhover-shown edit box > h3 note header
	e = e.parentNode.parentNode.parentNode;

		// go from note header to note content node, skipping text nodes on the way
	while(e.className != 'note_content') { e = e.nextSibling; }
	e.toggle();

		// extract note from edit link id
	var note = this.parentNode.id.match( /note_(\d+)/ )[1];
	if(!note) { return alert('Could not get note ID!\n p.id: ' + this.parentNode.id); note='1448270'; }

		// < means "click to hide", which means "not currently hidden", which means "don't hide next time"
	var state = this.textContent == '<' ? '0' : '1';
	var full_url = db_url + '&note='+note+'&state='+state;

		// we don't need a callback for when we post stuff, we assume it succeeds
		// content-length header required to get past mod_security on apache...
	GM_xmlhttpRequest( { method: 'post', url: full_url, headers: {'Content-Length': '0' } } );
}


		// Fetch the list of notes to hide, then hide them
		// (since everything at this point is visible, toggling hides)
GM_xmlhttpRequest( {
  method: 'get',
  url: db_url,
  onload: function(r) {
	if(/^\s*$/.test(r.responseText)) return; // all whitespace/empty means no saved notes

	var notes = r.responseText.split(',');
	
	for(var i in notes) {
		// create a generic "click" event, once
		var a_click = document.createEvent('MouseEvents');
		a_click.initMouseEvent('click', true, true, window, 0,0,0,0,0, false, false, false, false, 0, null);

		var toggler = document.getElementById('note_'+notes[i]+'_toggler');
		toggler.dispatchEvent(a_click);
	}
  }
});

})();

			

