// this first section grabs the tweets as soon as the page loads - there might be a way to do this within the timer section
var kw='Neu-Ulm+OR+Ulm+OR+Lindau+OR+Bodensee+OR+Schwaben+OR+google+OR+microsoft+OR+from%3Apcwelt+OR+from%3Aheiseonline';
var current='';
var myInterval=0;

function disableTwitter(baseurl) {
	if (baseurl!='') {
	  $.ajax({
	    url: baseurl+"/setting/?name=twitter&value=off",	
	    type: "GET",
	    data: ""
	    });
	}

	if (myInterval!=0) {
	  window.clearInterval(myInterval);
	}
	$("#twitter-box").slideUp("fast");
	$("#twitter-on").fadeIn(600);
}

function enableTwitter(baseurl) {
	if (baseurl!='') {
	  $.ajax({
	    url: baseurl+"/setting/?name=twitter&value=on",	
	    type: "GET",
	    data: ""
	    });
	}

	current='';
	$("#twitter-on").hide();
	$("#twitter-box").slideDown("fast");
	gettweets();
	myInterval=window.setInterval("gettweets()", 10000);
}

$(document).ready(function(){
	if (twitter==1) enableTwitter('');
	//$('#refresh').bind("click",function(){gettweets();return false;});
});

String.prototype.parseURL = function() {
	return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function(url) {
		return '<a href="'+url+'" target="_blank">'+url+'</a>'; //return url.link(url);
	});
};

String.prototype.parseUsername = function() {
	return this.replace(/[@]+[A-Za-z0-9-_]+/g, function(u) {
		var username = u.replace("@","")
		return '<a href="http://twitter.com/'+username+'" target="_blank">'+u+'</a>'; //return u.link("http://twitter.com/"+username);
	});
};

String.prototype.parseHashtag = function() {
	return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) {
		var tag = t.replace("#","%23")
		return '<a href="http://search.twitter.com/search?q='+tag+'" target="_blank">'+t+'</a>'; //return t.link("http://search.twitter.com/search?q="+tag);
	});
};

function gettweets(){
	$.getJSON("http://search.twitter.com/search.json?q="+kw+"&rpp=1&lang=de&page=1&callback=?",
	  function(data){
	    var html = "";
	    $.each(data.results, function(i,item){

		// check to see if this particular string of html already exists in the "stream"
		// and append it if it doesn't (i.e. it's new!)
		// build html string
		html += "<div id=\""+item.id+"\" class=\"tweet\">";
		html += "<img style=\"margin-right:5px;width:48px;height:48px;\" src=\""+item.profile_image_url+"\" alt=\"\" />";
		html += "<p style=\"margin-top:-50px;margin-left:50px;height:50px;\"><strong><a href=\"http://www.twitter.com/"+item.from_user+"\" target=\"_blank\">"+item.from_user+"</a></strong><br />"+ item.text.parseURL().parseUsername().parseHashtag() +"</p>";
		//html += "<p class=\"info\">"+item.created_at+"</p>";
		//html += "<p class=\"info\">"+item.id+"</p>";
		html += "</div>";

	    });

	  if(current!=html){	
		current=html;
		$("#twitter").fadeOut(600, function() {
			$("#twitter").html(html);
			$("#twitter").fadeIn(600);
			});
	  }

	})

}


