// DeliciousToDelicious
// v0.1
// Copyright (c) 2005, Wayne Burkett 
// Released under the GPL license
// http://www.gnu.org/copyleft/gpl.html

// This is a Greasemonkey (0.3 or later) user script. 
// http://greasemonkey.mozdev.org/

// ==UserScript==
// @name          DeliciousToDelicious
// @namespace     http://dionidium.com/projects/greasemonkey/
// @description   Post to any tool that implements the del.icio.us API using the del.icio.us interface
// @include       http://del.icio.us*
// ==/UserScript==

function submitForm(e) {
    var url, params; 
    var form = e.target;
    if (!form.sync.checked) { return; }
    params = [
        'url=' + form.url.value,
        'description=' + form.description.value,
        'tags=' + form.tags.value,
        'extended=' + form.extended.value
    ];
    url = configuration() + encodeURI(params.join('&'));
    GM_xmlhttpRequest({
        method: 'GET',
    	url: url,
    	headers: { 'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey (DeliciousToDelicious/0.1)' },
	onload: function(responseDetails) {
	    var xml = responseDetails.responseText;
	    if (/something went wrong/.test(xml)) {
	        alert('Something went wrong! (Note: Scuttle requires at least one tag.)');
	    }
	},
    	onerror: function(responseDetails) {
	    alert("Couldn't post to weblog: " + responseDetails.status + " " + responseDetails.statusText);
    	}
    });
}

function configuration() {
    var url = GM_getValue('delApiUrl', 'DNE');
    if (url == 'DNE') { 
        var msg = "Where is the posts/add function of your del.icio.us API?\n" +
	          "Examples:\n" + 
		  "http://del.icio.us/api/posts/add\n" +
		  "http://127.0.0.1/scuttle/api/posts_add.php\n";
	url = prompt(msg, '');
	GM_setValue('delApiUrl', url);
    }
    return url + '?';
}

var xpath, node, button; 
var checkbox, nextcell, postmsg;
xpath = '//input[contains(@value, "save")]';
node = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
if (!(button = node.singleNodeValue)) { return; }

// prompt user for settings, if necessary
configuration();
window.addEventListener('submit', submitForm, true);

checkbox = document.createElement("input");
checkbox.setAttribute("type", "checkbox");
checkbox.setAttribute("id", "sync");
checkbox.setAttribute("checked", "checked");

// use the 'save' button as a reference point
nextcell = button.parentNode.nextSibling.nextSibling;
postmsg = document.createTextNode("sync");
nextcell.align = '';
nextcell.insertBefore(postmsg, nextcell.firstChild);
nextcell.insertBefore(checkbox, postmsg);

// 2005-06-22 - 0.1 - released
