// ==UserScript==
// @name          Add hCard entries to Y!Trip
// @description	  Finds hCard elements and creates a Y!Trip from them.
// @version		  0.1
// ==/UserScript==

/* hCard to Yahoo! Travel Trip converter */
/* This isn't a "full" hcard parser, and it doesn't handle sub keys all that
   well, but it does the job. and it works on Y!Local. */

/* from Dustin Diaz */
function getElementsByClass(searchClass,node,tag) {
    var classElements = new Array();
    if ( node == null )
        node = document;
    if ( tag == null )
        tag = '*';
    var els = node.getElementsByTagName(tag);
    var elsLen = els.length;
    var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
    for (i = 0, j = 0; i < elsLen; i++) {
        if ( pattern.test(els[i].className) ) {
            classElements[j] = els[i];
            j++;
        }
    }
    return classElements;
}


/* Grab all the hCards */
var cards = getElementsByClass('vcard');
var card;
var tripxref = Array(['tel','phone'],
	['street-address','address1'],
	['locality','city'],
	['region','state'],
	['postal-code','postalcode'],
	['country-name','country']);
var itrip = tripxref.length-1;	

/* Process each hCard */
while (card = cards.shift())
{
	var tripObj = new Object;

	/* If there's no 'org' title, skip it. */
	try {
		tripObj.title = getElementsByClass('org',card)[0].textContent;
	}
	catch (e)
	{
		continue;
	}
	/* build the trip object from the conversion table */
	for(;itrip >=0 ;itrip--)
	{
		var xlate=tripxref[itrip];
		try {
			var element = getElementsByClass(xlate[0],card)[0];
			tripObj[xlate[1]]=element.textContent;
		}
		catch (e)
		{
			continue;
		}
	}

	/* Set the "globals" */
	tripObj.url=document.documentURI;
	tripObj.type='Other';

	/* Build the link */
	var link = document.createElement('a');
	var icon = document.createElement('img');
	icon.src = 'http://us.i1.yimg.com/us.yimg.com/i/us/tr/guides/topchunk_trip_planner_icon.gif';
	icon.title = 'Add to Yahoo! Trips';
	icon.alt = 'Add to Yahoo! Trips';
	link.appendChild(icon);
	link.href='http://travel.yahoo.com/trip?action=add&insert=1&validate=1&cls=poi';
	for (var prop in tripObj)
		link.href += '&' + prop + '=' + escape(tripObj[prop]);

	/* Attach it to the document */
	card.appendChild(link);
}

