// ==UserScript==
// @name           WordPress autosave
// @namespace      fcc
// @description    Autosave the content field in WordPress
// @include        http://*/wp-admin/post.php*
// ==/UserScript==

if (!window.fcc) window.fcc = {};
window.fcc.getElements = function(tag,props) {
	var elms = document.getElementsByTagName(tag);
	var arr = [];
	for (var i=0,j=elms.length;i<j;i++) {
		var add = true;
		for (var p in props) {
			if (elms[i][p]!=props[p]) add = false;
		}
		if (add) arr.push(elms[i]);
	}
	return arr;
};
window.fcc.getLocation = function() {
	var l = window.location.hostname + window.location.pathname.replace("/wp-admin/post.php","").replace(/\//,".");
	return l;
};
window.addEventListener('load',function() {
	var elm = window.fcc.getElements('input',{type:'hidden',name:'post_ID'});
	if (elm.length>0) {
		var pid = elm[0].value;
		var s = GM_getValue('fcc.wp.'+window.fcc.getLocation()+'.'+pid+'.value', null);
		var c = document.getElementById('content');
		if (s!=null && c.value!=s && s.length!=c.value.length) {
			var b = confirm('Autosaved content different from saved content. Do you want to replace the content with this?\n\n"'+s.substr(0,100)+'..."');
			if (b) {
				c.value = s;
				GM_setValue('fcc.wp.'+pid+'.value','');
			}
		}
	}
},true);
window.addEventListener('unload',function() {
	var elm = window.fcc.getElements('input',{type:'hidden',name:'post_ID'});
	if (elm.length>0) {
		var pid = elm[0].value;
		GM_setValue('fcc.wp.'+window.fcc.getLocation()+'.'+pid+'.value', document.getElementById('content').value);
	}
},true);
