/*
 *
 * Twitter parser
 *
 */

/* ME has to parse:
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:georss="http://www.georss.org/georss">
  <channel>
    <title>Twitter / jeroenkeeken</title>
    <link>http://twitter.com/jeroenkeeken</link>
    <atom:link type="application/rss+xml" href="https://twitter.com/statuses/user_timeline/104254488.rss" rel="self"/>
    <description>Twitter updates from jeroen / jeroenkeeken.</description>
    <language>en-us</language>
    <ttl>40</ttl>
  <item>
    <title>jeroenkeeken: stappen @ fiji amersfoort</title>
    <description>jeroenkeeken: stappen @ fiji amersfoort</description>
    <pubDate>Sun, 28 Mar 2010 01:28:22 +0000</pubDate>
    <guid>http://twitter.com/jeroenkeeken/statuses/11171750881</guid>
    <link>http://twitter.com/jeroenkeeken/statuses/11171750881</link>
  </item>
  <item>
    <title>jeroenkeeken: uit eten @ the old pepper mill</title>
    <description>jeroenkeeken: uit eten @ the old pepper mill</description>
    <pubDate>Sat, 27 Mar 2010 20:21:36 +0000</pubDate>
    <guid>http://twitter.com/jeroenkeeken/statuses/11160464530</guid>
    <link>http://twitter.com/jeroenkeeken/statuses/11160464530</link>
  </item>
  <item>
    <title>jeroenkeeken: Koppeling via API, tijd om te testen</title>
    <description>jeroenkeeken: Koppeling via API, tijd om te testen</description>
    <pubDate>Thu, 25 Feb 2010 16:24:34 +0000</pubDate>
    <guid>http://twitter.com/jeroenkeeken/statuses/9632460841</guid>
    <link>http://twitter.com/jeroenkeeken/statuses/9632460841</link>
  </item>
  </channel>
</rss>
*/ 
 
function twitParser( options ) {
	/* TMP TMP TMP */
	this.twit_id = "104254488";
	/* twitterFollow */
	this.twitFollow = null;
	this.twits_max = 5;
	/* twit dir level */
	this.twit_dir_level = 0;
	this.twit_dir_name = "../";
	this.twit_path = "";
	
	/* Option MEEEEEEEEE */
	if( typeof options["twitID"] != "undefined" ) {
		this.twit_id = options["twitID"];
	}
	
	if( typeof options["entries"] != "undefined" ) {
		this.twits_max = options["entries"];
	}
	
	/* Options set dir level */
	if( typeof options["level"] != "undefined" ) {
		this.twit_dir_level = options["level"];
		
		if( this.twit_dir_level > 0 ) {
			for(var d=0;d<this.twit_dir_level;++d)
				this.twit_path += this.twit_dir_name;
		}
	}
	
	/* Twitter path */
	this.twit_path += "../proxy.asp?url=https://twitter.com/statuses/user_timeline/"+this.twit_id+".rss";
	
	if( window.XMLHttpRequest ) {
		this.twit_obj = new XMLHttpRequest()
	} else {
		this.twit_obj = new ActiveXObject("Microsoft.XMLHTTP")
	}
	
	this.twit_obj.open("GET",this.twit_path,false);
	this.twit_obj.send("");
	
	
	if( this.twit_obj.readyState == 4 ) {
		if( this.twit_obj.status != 200 ) {
			this.twit_path = "../"+this.twit_path;
			this.twit_obj.open("GET",this.twit_path,false);
			this.twit_obj.send("");
		}
	}

	this.twitDoc = this.twit_obj.responseText;
	this.twitDoc = this.strToXml( this.twitDoc );
	
//	Shadowbox.open( { content: "http://www.goesenroos.nl", player:"iframe", title:"Het formulier is niet correct ingevuld<br>", height:350, width:500 } );
	
//	alert( this.formatDate("Wed, 19 May 2010 12:24:13") );
	/* validatie timee */
	if( !this.validate() ) {
//		alert( "Er is een fout opgetreden bij het laden van twitter, probeer de pagina te herladen." );
		return;
	}
	
	this.parse();
	
	return this;
}

/*
 * strToXml - Helper functie, voor het converteren van een string naar een dom object.
 */
twitParser.prototype.strToXml = function(str) {
	if(window.DOMParser){
		parser=new DOMParser();
		xmlDoc=parser.parseFromString(str,"text/xml");
	} else {
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async="false";
		xmlDoc.loadXML(str); 
	}
	return xmlDoc;
};

twitParser.prototype.urlToLink = function( url ) {
	return url.replace( /((http|ftp):\/\/[\w-_#.@\/~&%]+)/g, "<a href=\"$1\" target=\"_blank\">$1</a>" );
};

twitParser.prototype.urlMatch = function( url ) {
	if( url.match( /^(http|ftp):\/\/[\w-_#.@%~&]+$/ ) )
		return true;
	else
		return false;
};

twitParser.prototype.stripUsername = function( txt ) {
	// Should never ever happen?
	if( this.twitFollow==null )
		return false;
	
	return txt.substr( this.twitFollow.split("/")[3].length+2, txt.length );
};

twitParser.prototype.userLink = function( txt ) {
	return txt.replace( /@([\w_-]+)/, "<a href=\"http://twitter.com/$1\" target=\"_blank\">$1</a>" );
};

twitParser.prototype.formatDate =  function(str) {
	month_list = ["Mar", "May", "Oct"];
	maand_list = ["Mrt", "Mei", "Okt"];
	day_list = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
	dag_list = ["Ma", "Di", "Wo", "Do", "Vr", "Za", "Zo"];
	
	if( (pos = day_list.indexOf( str.substr(0,3) ))!=-1) {
		str = str.replace( day_list[pos], dag_list[pos] );
	}
	
	for(var m=0;m<month_list.length;++m) {
		month = month_list[m];
		
		if( str.indexOf(month) != -1 ) {
			str = str.replace( month, maand_list[m] );
			break;
		}
	}
	
	return str;
};

/*
 * validate - voor het valideren van het twitter bericht
 */
twitParser.prototype.validate = function() {
	// Helaas, er moet een channel aanwezig zijn.
	if( this.twitDoc.getElementsByTagName("channel").length <= 0 )
		return false;
		
	// Even de channel link doorparsen ;)
	tmp = this.twitDoc.getElementsByTagName("channel")[0];
	if( (tmp=tmp.getElementsByTagName("link")).length <= 0 ) {
		return false;
	}
	
	// Even zeker weten, dat we een goede link te pakken hebben.
	this.twitFollow = tmp[0].childNodes[0].nodeValue;
	if( typeof this.twitFollow != "string" ) 
		return false;
		
	// Even een extra beveiliging inbakken
	if( typeof document.getElementById("twitContainer") == "undefined"||document.getElementById("twitContainer")==null||
		!document.getElementById("twitContainer") ) {
		return false;
	}
		
	return true;
};

/*
time = Math.round(((new Date()).getTime()-Date.UTC(1970,0,1))/1000);
*/
twitParser.prototype.parse = function() {
	var twit, twits = this.twitDoc.getElementsByTagName("item");
	var tmp, content = "<DIV class=\"RssContainer TwitterContainer\">";
	
	//alert( (new Date()).getTime());
	// Tweeeetyyyy`s....
	for(var t=0,l=twits.length;t<l;++t) {
		twit = twits[t];
		
		if(t>this.twits_max-1)break;
		content += "<div class=\"twitter_item\">";
		content += "<div class=\"twitter_link\"><a href=\""+twit.getElementsByTagName("link")[0].childNodes[0].nodeValue+"\">Lees op twitter</a></div>";
		/* handle dates */
		tmp = twit.getElementsByTagName("pubDate")[0].childNodes[0].nodeValue;
		content += "<div class=\"twitter_datum\">"+this.formatDate(tmp.substr( 0, tmp.length-5 ))+"</div>";
		/* handle message */
		tmp = this.stripUsername( twit.getElementsByTagName("title")[0].childNodes[0].nodeValue );
		content += "<div class=\"twitter_tekst\">"+this.urlToLink(tmp)+"</div>";
		content += "</div>";
	}
	
	// Else,, should never happen nor is i required to check this...
	if(this.twitFollow!=null)
		content += "<a href=\""+this.twitFollow+"\" target=\"_blank\"><div class=\"twitter_channellink\"></div></a>";
	
	content += "</div>";
	
	document.getElementById("twitContainer").getElementsByTagName("div")[0].innerHTML += content;
};
