// ==UserScript==
// @name          Add hCard entries to Y!Trip
// @namespace     http://ycoolthing.com
// @description	  Finds hCard elements and creates a Y!Trip from them.
// @version		  0.1
// ==/UserScript==
/* Be nice, this is my first greasemonkey script, and it needs a LOT of love.

   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 getId=0;
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';
	
	var pickTrip = function (e) {
		var h2yt = document.getElementById('h2yt_sel');
		this.href += '&pid=' + h2yt.value;
		return false;
		};

	
	var link = document.createElement('a');
	link.id="h2yt_link";
	link.href='http://travel.yahoo.com/trip?action=add&insert=1&validate=1&cls=poi';
	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.addEventListener('click',pickTrip,false);
	for (var prop in tripObj)
		link.href += '&' + prop + '=' + escape(tripObj[prop]);

	/* Attach it to the document */
	card.appendChild(link);
	/* Build the link */
    /* Wait, is there a stored Yahoo! ID? */
	if (GM_getValue('h2yt_ID') == null)
	{
        /* No, build the mini-form. */
		var yid = document.createElement('input');
		var yidl = document.createTextNode('Your Yahoo ID:');
		var yidblur = function(){
			GM_setValue('h2yt_ID',this.value);
			this.parentNode.removeChild(yidl);
			this.parentNode.removeChild(yid);
			return false;
            /* Should either refresh the page or draw the list */
			}
		
		yid.type = 'text';
		card.appendChild(yidl);
		card.appendChild(yid);
		yid.addEventListener('blur',yidblur,true);
	}
	else
	{
        /* Get the stored Yahoo ID */
		var yid = GM_getValue('h2yt_ID');
		var selDiv = document.createElement('div');
		selDiv.id = 'h2yt';
		card.appendChild(selDiv);
		
		GM_xmlhttpRequest({
			method:'GET',
			url:'http://api.travel.yahoo.com/TripService/V1/tripSearch?appid=ycoolthing&yahooid='+yid,
			onload: function(responseDetails) {
				var resp = responseDetails.responseText;
				var parser = new DOMParser();
				var presp= parser.parseFromString(resp,'application/xml');
				var results = presp.getElementsByTagName('Result');
				var lr = results.length;
				var tsel = document.createElement('select');
				tsel.title='Select the trip to add this to.';
				tsel.id='h2yt_sel';
				for (var i=0;i<lr;i++)
				{
					var result = results[i];
					var opt = document.createElement('option');
					opt.value = result.attributes[0].nodeValue;
					opt.text= result.getElementsByTagName('Title')[0].textContent;
					tsel.appendChild(opt);
				}
				document.getElementById('h2yt').appendChild(tsel);
			}
			});
		
/*		var yidl = document.createTextNode(GM_getValue('h2yt_ID'));
		card.appendChild(yidl);
*/
	}
}
