// ==UserScript==
// @name          Toggle Recent Comments in Flickr Photostream
// @version       0.2.4
// @description	  Shows the five most recent comments
// @namespace     http://flickr.yuan.cc/
// @include       http://flickr.com/photos/*
// @include       http://www*.flickr.com/photos/*

// v0.2.4
// Keep the comments always on
// v0.2.3
// replace GM_xmlhttpRequest to XMLHttpRequest
// version: 0.2.2
// by CK (http://flickr.com/photos/ckyuan/)
// Improvement: toggle the comments on and off
// version: 0.1
// by setre (http://flickr.com/photos/setre/)
// please report any bugs or suggestions to setre3+monkey@gmail.com
// 
//TODO:
//	buddyicons? (need to call people.findByUsername + people.getInfo :(  )
// 	display minutes/hours/days et c since comment was posted
//	be smart about multiple comments to the same image?
// ==/UserScript==

var xmlproxy,xmlhttpproxy,commentsDiv,commentsToggle,commentsLoaded=false;
if( flickr_nsid ) nsid = flickr_nsid;
if( typeof(flickr_jspush) == 'undefined' ) flickr_jspush=false;
if( typeof(flickr_entries) == 'undefined' ) flickr_entries=6;
else { 
	if( flickr_entries > 10 ) flickr_entries=10;
	if( flickr_entries < 0 ) flickr_entries=0;
}

if (typeof DOMParser == "undefined") {
   DOMParser = function () {}
	
   DOMParser.prototype.parseFromString = function (str, contentType) {
      if (typeof ActiveXObject != "undefined") {
         var d = new ActiveXObject("MSXML.DomDocument");
         d.loadXML(str);
         return d;
      } else if (typeof XMLHttpRequest != "undefined") {
         var req = new XMLHttpRequest;
         req.open("GET", "data:" + (contentType || "application/xml") +
                         ";charset=utf-8," + encodeURIComponent(str), false);
         if (req.overrideMimeType) {
            req.overrideMimeType(contentType);
         }
         req.send(null);
         return req.responseXML;
      }
   }
}

function MyXMLHttpRequest(req) {

        var re = /http:\/\/([^\/]+)\//;
        var m = re.exec(document.location);
        var n = re.exec(req.url);
        if( m[1] == n[1] ) {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState==4) {
                    if (xmlhttp.status==200) req.onload(xmlhttp);
                }
            }
            xmlhttp.open(req.method, req.url, true);
            xmlhttp.send(null);
        } else {
            var js = document.createElement('script');
            js.language = 'javascript';
	    js.type = 'text/javascript';
            js.src = 'http://webdev.yuan.cc/flickr/xml_proxy.php?' + req.url;
	    if( flickr_jspush ) {
		jss.push(js);
	    } else {
		if( !IE4 ) document.body.appendChild(js);
		else {
		    if(!xmlhttpproxy) {
			document.write('<script language=Javascript src="' + js.src + '"></script>');
		    }
		}
	    }

            var xmlcount = 0;
            xmlproxy = function() {
                if( xmlcount++ > 20 ) {
                    xmlhttpproxy = new Object();
                    xmlhttpproxy.readyState = 4;
                    xmlhttpproxy.status = 404;
                    xmlhttpproxy.responseText = '';
                    req.onload(xmlhttpproxy);
                    return;
                }
                if( xmlhttpproxy ) req.onload(xmlhttpproxy);
                else window.setTimeout('xmlproxy()', 1000);
            }
            window.setTimeout('xmlproxy()', 1000);
        }
}

function createCommentSpan() {
	var recentCommentsLink = document.createElement('span');
//	recentCommentsLink.innerHTML = '&raquo; ';
	recentCommentsLink.style.marginTop = '5px';
	commentsToggle = document.createElement('a');
	commentsToggle.href = 'javascript:;';
	var tmpFun = function() {
		if( !commentsLoaded ) {
		    commentsToggle.innerHTML = 'Loading...';
		    flickr_open = true;
		    if( !flickr_jspush) fetchFeed();
		    return;
		}
		if( this.parentNode.nextSibling ) this.parentNode.parentNode.insertBefore(commentsDiv, this.parentNode.nextSibling);
		else this.parentNode.parentNode.appendChild(commentsDiv);
		this.onclick = function() { 
			if( commentsDiv ) this.parentNode.parentNode.removeChild(commentsDiv); 
			this.onclick = tmpFun;
		}
	}
	commentsToggle.onclick = tmpFun;
	commentsToggle.innerHTML = flickr_comments;
	recentCommentsLink.appendChild(commentsToggle);
	document.getElementById('flickr_comments').appendChild(recentCommentsLink);
	if(flickr_open) commentsToggle.onclick();
}

var url_str = ''+document.location;
if( url_str.match('www.flickr.com') ) www = 'www.';
else www = '';

// var feedURI = 'http://'+www+'flickr.com/photos_comments_feed.gne?id='+nsid+'&format=atom_03';
var feedURI = 'http://'+www+'flickr.com/recent_comments_feed.gne?id='+nsid+'&format=atom_03';

function fetchFeed() {

MyXMLHttpRequest({
	method: 'GET',
	url: feedURI,
	headers: {
		'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey/0.3',
		'Accept': 'application/atom+xml,application/xml,text/xml'
	},
	onload: function(responseDetails) {
		var parser = new DOMParser();
		var dom = parser.parseFromString(responseDetails.responseText, "application/xml");
		var entries = dom.getElementsByTagName('entry');
		commentsDiv = document.createElement('div');
		var commentList = document.createElement('ul');
		commentList.id = 'commentList';

		for (var i = 0; (i < flickr_entries && i < entries.length); i++) {
			var commentUL = document.createElement('ul');
			var tmpDiv = document.createElement('div');
// alert(entries[0].getElementsByTagName('content')[0].firstChild.data);
//			var commentText = entries[i].getElementsByTagName('content')[0].textContent;
			var commentText = entries[i].getElementsByTagName('content')[0].firstChild.data;
			tmpDiv.innerHTML = commentText;

			var imgAndLink = tmpDiv.getElementsByTagName('a');
			imgAndLink = imgAndLink[(imgAndLink.length -1)];
			commentUL.appendChild(imgAndLink);
			commentUL.appendChild(tmpDiv.getElementsByTagName('p')[1]);
			commentUL.appendChild(document.createTextNode(' - '));
			commentUL.appendChild(tmpDiv.getElementsByTagName('a')[0]);
			commentList.appendChild(commentUL);
			commentsDiv.appendChild(commentList);
			var img = commentUL.getElementsByTagName('img')[0];
			img.removeAttribute('width');
			img.removeAttribute('height');
			img.removeAttribute('style');
		}
		commentsLoaded = true;
		commentsToggle.innerHTML = flickr_comments;
		if(flickr_open) commentsToggle.onclick();
	}
});
}

document.write('<div id="flickr_comments">  </div>');
createCommentSpan();
// fetchFeed();
IE4=(document.all);
if(IE4 || flickr_jspush ) fetchFeed();
