// Flickr RSS Widget v 0.3
// Eliot Shepard <eshepard@slower.net>
//
// Initial widget inspiration from "GNE Browser" by Eric Costello (http://glish.com/) for Ludicorp
//
// changelog
// 0.3: reads feed title and displays in button's alt tag
//		intelligently finds absolute URL for rssLocal.php
//		handle layout of feeds with 10 or 20 elements
//      small changes, packaged for release
// 0.2:	fixed to be compatible with latest iteration of Flickr RSS
// 0.1:	added support for 20 elements (per Flickr RSS feed length)
//		added white background for center cell of menu

/////////////////////////////////////
// Adapted from XML import & RSS parse code from work by Mark Wilton-Jones (http://www.howtocreate.co.uk/)

var flickr_photo_info	= [];
var	flickr_feed_title	= '';
var MWJ_ldD = [];

function importXML( oURL, oFunct, oNoRand, oDelay ) {
	//note: in XML importing event handlers, 'this' refers to window
	if( !oNoRand ) { oURL += ( ( oURL.indexOf('?') + 1 ) ? '&' : '?' ) + (new Date()).getTime(); } //prevent cache
	if( window.XMLHttpRequest ) {

		//alternate XMLHTTP request - Gecko, Safari 1.2+ and Opera 7.6+
		MWJ_ldD[MWJ_ldD.length] = new XMLHttpRequest();
		MWJ_ldD[MWJ_ldD.length-1].onreadystatechange = new Function( 'if( MWJ_ldD['+(MWJ_ldD.length-1)+'].readyState == 4 && MWJ_ldD['+(MWJ_ldD.length-1)+'].status < 300 ) { '+oFunct+'(MWJ_ldD['+(MWJ_ldD.length-1)+'].responseXML); }' );
		MWJ_ldD[MWJ_ldD.length-1].open("GET", oURL, true);
		MWJ_ldD[MWJ_ldD.length-1].send(null);
		return true;
	}
	if( !navigator.__ice_version && window.ActiveXObject ) {
		//the Microsoft way - IE 5+/Win (ICE produces errors and fails to use try-catch correctly)
		try { //IE Mac has the property window.ActiveXObject but produces errors if you try and use it
			try { var tho = new ActiveXObject( 'Microsoft.XMLDOM' ); //newer
			} catch(e) { var tho = new ActiveXObject( 'Msxml2.XMLHTTP' ); } //older
			MWJ_ldD[MWJ_ldD.length] = tho;
			MWJ_ldD[MWJ_ldD.length-1].onreadystatechange = new Function( 'if( MWJ_ldD['+(MWJ_ldD.length-1)+'].readyState == 4 ) { '+oFunct+'(MWJ_ldD['+(MWJ_ldD.length-1)+']); }' );
			MWJ_ldD[MWJ_ldD.length-1].load(oURL);
			return true;
		} catch(e) {}
	}
	if( document.createElement && document.childNodes ) {
		//load the XML in an iframe
		var ifr = document.createElement('DIV');
		ifr.style.visibility = 'hidden'; ifr.style.position = 'absolute'; ifr.style.top = '0px'; ifr.style.left = '0px';
		//onload only fires in Opera so I use a timer for all
		if( !window.MWJ_XML_timer ) { window.MWJ_XML_timer = window.setInterval('MWJ_checkXMLLoad();',100); }
		ifr.innerHTML = '<iframe src="'+oURL+'" name="MWJ_XML_loader_'+MWJ_ldD.length+'" height="0" width="0"><\/iframe>';
		MWJ_ldD[MWJ_ldD.length] = oFunct+'MWJ_SPLIT'+(oDelay?oDelay:1)+'';
		document.body.appendChild(ifr);
		return true;
	}
	return false;
}


function MWJ_checkXMLLoad() {
	//check if each imported file is available (huge files may not have loaded completely - nothing I can do - use the delay to help)
	for( var x = 0; x < MWJ_ldD.length; x++ ) { if( MWJ_ldD[x] && window.frames['MWJ_XML_loader_'+x] ) {
		setTimeout( MWJ_ldD[x].split('MWJ_SPLIT')[0] + '(window.frames.MWJ_XML_loader_'+x+'.window.document);', parseInt(MWJ_ldD[x].split('MWJ_SPLIT')[1]) );
		MWJ_ldD[x] = false;
	} }
}


function parseRSS(oDocObj) {

	if (!oDocObj) {
		loadFailure();
//		alert('Could not load RSS feed'); return;
	}
	
	// check if the browser interpreted the XML correctly
	if( oDocObj.documentElement && oDocObj.documentElement.tagName && oDocObj.documentElement.tagName.toUpperCase() == 'HTML' ) {
		setTimeout('loadFailure();',20); return;
	}
	var chanEl		= oDocObj.getElementsByTagName('channel')[0];
	if( !chanEl ) {
		loadFailure();
//		alert('Format was not recognised as a valid RSS feed'); return;
	}
	var RSSversion	= oDocObj.getElementsByTagName('rssSpoof')[0] ? oDocObj.getElementsByTagName('rssSpoof')[0].getAttribute('version') : '';

	flickr_feed_title	= oDocObj.getElementsByTagName('title')[0].firstChild.nodeValue;
	
	//parse each news item
	for(var x=0, y=oDocObj.getElementsByTagName('item'); (x<20 && y[x]); x++ ) {
		flickr_photo_info[x]			= [];
		for (var i=0, j; j=y[x].childNodes[i]; i++) {
			if ('author' == j.tagName) {
				matches	= j.firstChild.nodeValue.match(/(.*\()(.*)(\).*)/);
				if (matches[2].length > 11) {
					sn	= matches[2].substr(0,11) + "...";
				} else {
					sn	= matches[2];
				}
				flickr_photo_info[x]['screenname']	= sn;
			} else if ('link' == j.tagName) {
				matches	= j.firstChild.nodeValue.match(/(^.*)(\/\d+\/$)/);
				if (matches) {
					flickr_photo_info[x]['userlink']		= matches[1] + '/';
				} else {
					flickr_photo_info[x]['userlink']		= '#';
				}
			} else if ('description' == j.tagName) {
				// scrape the image URL from here.
				matches	= j.firstChild.nodeValue.match(/(.*)(src=")([^"]+)(")(.*)/);
				if (matches) {
					flickr_photo_info[x]['img']		= matches[3].replace(/_m.jpg/g,'_s.jpg');
				} else {
					flickr_photo_info[x]['img']		= '#';
				}
			} 
			flickr_photo_info[x][j.tagName]	= j.firstChild ? j.firstChild.nodeValue : '';
		}
	}

	ready();
}


/////////////////////////////////////

var incs		= 9;
var menuShown	= false;

var	imW			= 75;
var imH			= 75;
var	xExtent		= 84;
var yExtent		= 96;

var imageDirPath	= 'http://www.matkailuauto.fi/images';
					 
// cell positions for RSS feeds with 20 items
var	dx20	= new Array(
	-1, 0, 1,
	-2, -1, 0, 1, 2,
	-2, -1, 1, 2,
	-2, -1, 0, 1, 2,
	-1, 0, 1
);

var dy20	= new Array(
	-2, -2, -2,
	-1, -1, -1, -1, -1,
	0, 0, 0, 0,
	1, 1, 1, 1, 1,
	2, 2, 2
);

// cell positions for RSS feeds with 10 items
// biased vertically - because vertical scrolling is more common.
var	dx10	= new Array(
	0,
	-1, 0, 1,
	-1, 1,
	-1, 0, 1,
	0
);

var dy10	= new Array(
	-2,
	-1, -1, -1,
	0, 0,
	1, 1, 1,
	2
);

// determine the absolute URL of rssLocal (ie. the same directory as this script)
var scriptTags = document.getElementsByTagName("script");
for(var i=0; i<scriptTags.length; i++) {
	if(scriptTags[i].src && scriptTags[i].src.match(/flickr_.*\.js$/)) {
		var urlScriptPath = scriptTags[i].src.replace(/flickr_.*\.js$/,'');
	}
}


html		= '\
	<style>\
	#fcbFrame	{position: relative; width: 84px; height: 31px; font-size: 11px;}\
	#fcbButton	{position: relative; z-index: 1000;}\
	#fcbMenu	{position: relative;}\
	.fcbRecord	{position: absolute; width: ' + xExtent + 'px; height: ' + yExtent + 'px; top: 0px; left: 0px; padding-top: 6px; padding-left: 2px; padding-right: 2px; background-color: white;}\
	</style>';
html		+= '<div id="fcbFrame"><a id="fcbLink" href="#"><img id="fcbButton" src="' + imageDirPath + '/flickr_rss_widget.loading.gif" width="84" height="31" border="0" alt="Please wait, loading data from Flickr" /></a><div id="fcbMenu"></div></div>';

document.write(html);
document.close();

var fcbFrame		= document.getElementById('fcbFrame');
var fcbMenu			= document.getElementById('fcbMenu');
var fcbButton		= document.getElementById('fcbButton');
var fcbLink			= document.getElementById('fcbLink');


if (!window.feedURL) {
	alert('Flickr RSS Widget error: You must specify a Flickr RSS 2.0 feed in the variable "feedURL" before invoking this script.');
	loadFailure();
}

importXML('rssLocal.php?feedURL='+escape(feedURL), 'parseRSS', true);  //urlScriptPath + 


function ready() {
	fcbLink.onclick	= toggleMenu;
	fcbButton.alt	= 'Click to see ' + flickr_feed_title.toLowerCase();;
	fcbButton.src	= imageDirPath + '/flickr_rss_widget.up.gif';
	fcbMenu.style.display	= 'none';
}


function loadFailure() {
	fcbButton.src	= imageDirPath + '/flickr_rss_widget.loadfailed.gif';
	fcbButton.alt	= 'Sorry, couldn\'t load data from Flickr';
}


function toggleMenu() {

	fcbLink.blur();

	if (menuShown) {
		fcbButton.src = imageDirPath + '/flickr_rss_widget.up.gif';
		fcbButton.alt	= 'Click to see ' + flickr_feed_title.toLowerCase();
		
		menuShown	= false;
		fcbMenu.style.display	= 'none';
		fcbFrame.style.backgroundColor	= 'transparent';

		for (var i=0; i<flickr_photo_info.length; i++) {
			div = document.getElementById('fcbItem' + i);
			div.style.top	= '0px';
			div.style.left	= '0px';
		}

	} else {
		fcbButton.src	= imageDirPath + '/flickr_rss_widget.down.gif';
		fcbButton.alt	= 'Click here to close';

		fcbFrame.style.backgroundColor	= 'white';
		menuShown	= true;
		setTimeout('showRecords()', 30);
	}

	return false;
};


function showRecords() {

	var	str		= '';
	for (var i=0; i<flickr_photo_info.length; i++) {
		str	+= '<div id="fcbItem' + i + '" class="fcbRecord" style="z-index: ' + (1000 - i) + ';"><a href="' + flickr_photo_info[i]['link'] + '"><img src="' + flickr_photo_info[i]['img'] + '" height="' + imH + '" width="' + imW + '" style="border: 1px solid black;" alt="posted ' + flickr_photo_info[i]['pubDate'] + '" border="0" /></a><br /><a href="' + flickr_photo_info[i]['userlink'] + '">' + flickr_photo_info[i]['screenname'] + '</a></div>';
		if (20 == flickr_photo_info.length) {
			flickr_photo_info[i]['incX'] = (dx20[i] * xExtent) / incs;
			flickr_photo_info[i]['incY'] = (dy20[i] * yExtent) / incs;
		} else {
			flickr_photo_info[i]['incX'] = (dx10[i] * xExtent) / incs;
			flickr_photo_info[i]['incY'] = (dy10[i] * yExtent) / incs;
		}
	}
	str	+= '<div id="fcbItemX" class="fcbRecord"></div>';
	fcbButton.style.zindex	= 1000;

	fcbMenu.innerHTML	= str;

	for (var i=0; i<flickr_photo_info.length; i++) {
		div = document.getElementById('fcbItem' + i);
		div.style.left	= '0px';
		div.style.top	= '0px';
	}

	fcbMenu.style.top			= -((yExtent / 2) + 6) + 'px';
	if (document.all) {
		fcbMenu.style.left		= -((xExtent / 2) + 0) + 'px';
	} else {
		fcbMenu.style.left		= '0px';
	}

	fcbMenu.style.display	= 'block';
	moveRecords(0);
};


function moveRecords(num) {

	if (!num) num = 0;

	num++;
	if (num > incs) return;
	setTimeout('moveRecords(' + num + ')', 15);

	for (var i=0; i<flickr_photo_info.length; i++) {
		div = document.getElementById('fcbItem' + i);
		var	toX	= num * flickr_photo_info[i]['incX'];
		var	toY = num * flickr_photo_info[i]['incY'];

		div.style.left	= toX + 'px';
		div.style.top	= toY + 'px';
	}
};
