		var twyrics = [];
		var twyriclinks = [];
		var lasttwyric=-1;
		var lastdiv=2;		
		var twyrictype=0;
		var startup=true;
		var curtwpage=1;
		var flickr_cache=[];
		var curimg=0;
		var thetweet ="";
		var thetweetkeywords="";
		var twyricversion="Beta 1.3";
		var slashesonly=false;
		var para_speed=""; // speed in parameter
		var para_hash=[]; // hash tag as RESTful parameter
		var para_tweet="";
		var para_flickr="";
		var cur_tweet="";
        var cur_flickr="";
        var para_user=""; // user in URL?
        var last_rounds_tweets = -1;
        var stopsearch=false;
		
		var settings = { nexttwyric: 10000 };	    
	
		function gettwyrics()
		{
			if(DEBUG) console.log("Get new tweets ... ");
			 
			var ttypes = gethashtags();
			st=ttypes[twyrictype];
			if(DEBUG) console.log("current tag: "+st);
			twyrictype=(twyrictype+1)%ttypes.length;
			if(twyrictype == 0) {				
			    if(DEBUG) console.log("*** last round vs. tw.len = " + last_rounds_tweets + "__" + twyrics.length);			
			    if(last_rounds_tweets < twyrics.length) {
			        last_rounds_tweets = twyrics.length;
			        stopsearch=false;
			    } else {
			        stopsearch=true;
			    }
			} 
			
			if(twyrictype==0) curtwpage++; 
			
			$("#divttype").html(st);
					
	        if(!stopsearch) {
		        var query=st;
		        if(para_user!="" && para_user!=null) {
		            query+=" from:"+para_user;
		        }
    			
		        query = encodeURIComponent(query);
    			
		        $.ajax({
			        url: "http://search.twitter.com/search.json?q="+query+"&page="+curtwpage,
			        type: 'GET',
			        dataType: 'jsonp',
			        timeout: 1500,				
		        success: function(json) { callback(json); }});
		    }
		    else {	
		        if(twyrics.length==0) { // defined user has absolutly no tweets matching the query
		            document.location="/"; // restart twyric
		        } else {
                    updatecounter();
                    displaytwyrics();	
                }                        
	        }
		}
		
		function updateflickrimg(json)
		{
			res=eval(json);
			//console.log(res);		
			// { src: 'http://farm4.static.flickr.com/3033/2952349578_2a33520121_m.jpg', flickr_url: 'http://www.flickr.com/photos/64479867@N00/2952349578/', owner_url: 'http://www.flickr.com/people/64479867@N00/', owner_name: 'Ela2007', owner_icon: 'http://farm2.static.flickr.com/1211/buddyicons/64479867@N00.jpg'}
			if(DEBUG) console.log("flickr img: "+res[0].src);	
			$("#flickrimg").html('<br/><a href="'+res[0].flickr_url+'"><img src="'+res[0].src+'"></a>');
			
			$("#divf").html('<span class="author"><img class="icon" src="'+res[0].owner_icon+'" align="left" id="THEflickrimage">flickr picture by<br/><a href="'+res[0].owner_url+'" target="flickrwin">'+res[0].owner_name+'</a></span>');
			return true;
		}
		
		function getkeywords(tweet)
		{
			var stopwords = [ "just", "it's", "was", "were", "and", "fun", "i'll", "fucking", "fuck", "sex", "ever", "there", "you", "all", "two", "the", "out", "i'm", "not","big", "get", "back", "but", "can't", "can", "they", "about","are","com","for","from","how","that","this","was","what","when","where","who","will","with","und","the","www","und","ist","für","ja","nein","bin","ich","wird","will","der","die","das","wer","was","haben","sollen","wollen","können","kann","du","er","sie","es","wir","ihr","und","oder","wenn","aber", "there","where" ];

			var txt="";
			var tmp = tweet.split(" ");
			for(var t=0; t<tmp.length && t<3; t++) {
				if(tmp[t].length>2 && jQuery.inArray(tmp[t].toLowerCase(), stopwords)==-1)
					txt+=tmp[t] + " ";
			}
			if(txt=="") txt="rain drop flower";
			if(DEBUG) console.log("txt for flickr search: "+txt);			
			return txt;
		}
		
		function displaytwyrics2()
		{							
			$("#div1").fadeOut(1000, function()	{
				
				displaytwyrics();
			});			
		}
		
		function displaytwyrics()
		{
			if(twyrics=="undefined" || !twyrics || twyrics==null || twyrics.length==0) setTimeout("displaytwyrics()",1000); // are there any tweets?

			lasttwyric++; // next tweet
			if(lasttwyric>=twyrics.length) lasttwyric=0; // start at the beginning of there are no new tweets
			if(lasttwyric==twyrics.length-1) gettwyrics(); // get more tweets if you have used all current ones
				
			if(DEBUG) console.log("Current tweet index: "+lasttwyric);			
			thetweet = getridofhastags(getridofatreplies(getridofurls(twyrics[lasttwyric].text))).replace('RT ','');
			if(thetweet.indexOf(": ")==0) thetweet.replace(": ", "");
			
			updatecounter();
			
			thetweetkeywords=getkeywords(thetweet);
			
			if(flickr_cache.length==0) {			
					fetchflickrimg();
			}
			else {		
				var ind=-1;
				for(var i=0; i<flickr_cache.length; i++) {
					if (flickr_cache[i].keywords==thetweetkeywords)
						ind=i;
				}
				if(ind==-1) 
					fetchflickrimg();				
				else
					displaynow(flickr_cache[ind].flickr);				
			}			
			
		}
	
		function fetchflickrimg()
		{
			$.ajax({
					url: "/phpFlickr-2.3.0.1/example.php?keywords="+escape(thetweetkeywords),
					type: 'GET',				
					timeout: 8000,				
					success: function(json) {
						flickr_cache.push({ keywords: thetweetkeywords, flickr: json })
						displaynow(json)
					},
					error: function(er) { displaytwyrics();}
				});
		}
	
		function displaynow(json)
		{
			if(DEBUG) console.log(json);	
			updateflickrimg(json); 

            cur_flickr=eval(json)[0]; // remember current ID
            cur_tweet=twyrics[lasttwyric]; 
            
			if(DEBUG) console.log('Update text');	
			$("#divt").html(getcontent(thetweet,twyrics[lasttwyric])); // get html content for displaying
			$("#div1").fadeIn(3000, function() { // fade in			   
				setTimeout("displaytwyrics2()",settings.nexttwyric); // and fade out after 10 seconds
			});
		}
			
		function updateimages()
		{
			var img="";			
			for(var i=lasttwyric;i<lasttwyric+5;((i++)%(lasttwyric.length-1)))
			{
				img+='<img class="icon" src="'+twyrics[i].profile_image_url+'">';
			};
			$("#mover").html(img);
		};
		
		function callback(json)
		{
			oldl=twyrics.length;
			if(json.results.length===undefined || json.results.length===null || json.results.length==0) gettwyrics();
			//console.log(json);
			for(var z=0;z<json.results.length;z++) {
				if((slashesonly && json.results[z].text.indexOf("/")>-1) || !slashesonly) {
					if(DEBUG)console.log($.inArray(json.results[z].id, twyriclinks));
					if($.inArray(json.results[z].id, twyriclinks)==-1) {
						twyrics.push(json.results[z]);
						twyriclinks.push(json.results[z].id);
					}}
			};
								
			if(oldl==twyrics.length) {
				gettwyrics();
			} else {				
				if(DEBUG)console.log("New number of tweets: "+twyrics.length);
				updatecounter();
				if(startup) {
				  startup=false;
				  displaytwyrics();
				};
			}
		}
		
		function updatecounter()
		{
			$("#divc").html("Displaying "+(lasttwyric+1)+"/"+twyrics.length+"<br/>Version: "+ twyricversion);
		};
		
		function getcontent(thetweet,tweet)
		{
			var res="";
			res=getlines(thetweet);
			res+="<br/>";			
			res+='<span class="author"><a target="newwin" href="http://twitter.com/'+tweet.from_user+'"><img class="icon" src="'+tweet.profile_image_url+'" align="left"/></a>';
			res+='tweet by <a target="newwin" href="http://twitter.com/'+tweet.from_user+'">'+tweet.from_user+'</a><br/> at ' + tweet.created_at.replace(" +0000"," ") + ' <a target="newwin" href="http://twitter.com/'+tweet.from_user+'/status/'+tweet.id+'">#</a></span>';
			return res;
		}
		
		function getlines(txt)
		{
			var mystr="";
			res = txt.split('/');
			//res = getridofhastags(getridofatreplies(getridofurls(txt))).replace('RT ','').split('/');
			for(var i=0;i<res.length;i++)  mystr+=res[i]+"<br/>";
				//mystr+="original: <b>"+json.feed.entry[z].title+"</b>";
				return mystr;
		}
		
		function getridofhastags(txt)
		{
			return getridofanything(txt,"#");
		}
		
		function getridofurls(txt)
		{
			return getridofanything(txt,"http://");			
		}
		
		function getridofatreplies(txt)
		{
			return getridofanything(txt,"@");			
		}
		
		function getridofescapes(txt)
		{
			return getridofanything(getridofanything(getridofanything(txt,'\t'),'\r'),'\n');			
		}
		
		function getridofanything(txt,tag)
		{
			var ind = txt.indexOf(tag);
			if(ind>-1)
			{				
				while(ind>-1)
				{
					var nextspace=txt.indexOf(" ", ind);
					if (nextspace>-1)
						txt = txt.substr(0,ind-1)+txt.substr(nextspace,txt.length);
					else
					    txt = txt.substr(0,ind-1);
						
					ind = txt.indexOf(tag);
				}
			}
			
			return txt;
		}

// create bookmark / permalink to current combination of tweet and image		
function bookmarkCurrent() {       
    
    if(DEBUG)console.log("cur_tweet = " + cur_tweet.id);
    if(DEBUG)console.log("cur_flickr = " + cur_flickr.photoid);
    
    var resurl=document.location;
    resurl+="?tweet="+encodeURIComponent(cur_tweet.id);
    resurl+="&flickr="+cur_flickr.photoid;
       
    prompt("This is the permalink to this combination of Tweet and Flickr-Image",resurl);
    
    createBookmarkLink("twyric.com - "+cur_tweet.text, resurl);
}

// create bookmark, basic cide found at http://labnol.blogspot.com/2006/01/add-to-favorites-ie-bookmark-firefox.html
function createBookmarkLink(btitle,bURL) 
{ 
	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(btitle, bURL,"");
	} else if( window.external ) { // IE Favorite
		window.external.AddFavorite( bURL, btitle); }
	else if(window.opera && window.print) { // Opera Hotlist
		return true; }
 }
 
 // display permalink without starting all the timer functions
 // sequence of thre functions!
 function displayPermaLink()
 {
    if(DEBUG) console.log("Display Permalink ... ");
    
    $("#setting").css("visibility","hidden");
    $("#divttype").html("Permalink ...");
    
    if(DEBUG) console.log("Retrieve tweet ... " + "http://search.twitter.com/search.json?q="+encodeURIComponent(para_tweet));    

    $.ajax({
	    url: "http://twitter.com/statuses/show/"+para_tweet+".json",
	    type: 'GET',
	    dataType: 'jsonp',
	    timeout: 1500,				
    success: function(json) { displayPermaLink2(json); }});
 }
 
 function displayPermaLink2(permatweet)
 {
    if(DEBUG) console.log(permatweet);	
    if(permatweet===undefined || permatweet===null || permatweet=="")
    {
        alert("An Error occured when retrieving the tweet. Please check your URL");        
    }
    else
    {
        tt=permatweet;
        thetweet = getridofhastags(getridofatreplies(getridofurls(tt.text))).replace('RT ','');
			if(thetweet.indexOf(": ")==0) thetweet.replace(": ", "");
        			
	    $.ajax({
			url: "/phpFlickr-2.3.0.1/example.php?flickr="+escape(para_flickr),
			type: 'GET',				
			timeout: 8000,				
			success: function(json) {				
				displayPermaLink3(json,thetweet,tt)
			},
			error: function(er) { alert("An Error occured when retrieving the flickr image. Please check your URL"); }
		});
			
    }
 }
 
 function displayPermaLink3(theflickr,thetweet,tt)
 {
    if(DEBUG) console.log('displayPermaLink3');	
    updateflickrimg(theflickr); 
	$("#divt").html(getcontent(thetweet,tt)); // get html content for displaying
	$("#div1").fadeIn(3000); // and fade out after 10 seconds	
 }
 
 // activate hints 
function activateHints()
{
    $("#sitename").hover(
      function () {
        displayHint("Click here to restart twyric.com", $(this).position().left);
      }, 
      function () {
        hideHint();
      }
    );

    $("#divc").hover(
      function () {
        displayHint("Click here to bookmark this pair of tweet + image", $(this).position().left);
      }, 
      function () {
        hideHint();
      }
    );
    
    $("#setting").hover(
      function () {
        displayHint("You can also set the speed by a ?speed= parameter in milliseconds", $(this).position().left);
      }, 
      function () {
        hideHint();
      }
    );
    
    $("#divttype").hover(
      function () {
        displayHint("last hash tag used for retrieving tweets", $(this).position().left);
      }, 
      function () {
        hideHint();
      }
    );
    
    $("#sitediv").hover(
      function () {
        displayHint("Check out these links and learn more about twyric", $(this).position().left);
      }, 
      function () {
        hideHint();
      }
    );
}

// display a hint
function displayHint(mtext, cssleft)
{
    $("#hint").css("left",cssleft);
    $("#hint").html(mtext);
    $("#hint").css("visibility","visible");
}

// hide a hint
function hideHint()
{
    $("#hint").css("visibility","hidden");
}

// startup sequence with jQ
$(document).ready(function() { 

    activateHints();

	slashesonly=getslashesonly();
	
	getURLParameter();
	
	// if permalink is coming in, display it
	if(para_tweet!="" && para_flickr!="")
	{
	    displayPermaLink();
	}
	else // no permalink? then start typicl behavior
	{	
	    $("#speedslider").slider(
	    {
		    value: settings.nexttwyric,
		    min: 5000,
		    max: 40000,
		    step: 1000,
		    slide: function(event, ui) {
			    settings.nexttwyric = ui.value;
			    $("#displayspeed").html((settings.nexttwyric/1000) + " sec");
		    }
	    });
    	
	    $("#displayspeed").html((settings.nexttwyric/1000) + " sec");
    	
	    $("#divc").click(function (event) { bookmarkCurrent(); });
    	
	    try {
		    $.ajax({
			    url: "/cache/flickr_cache.json",
			    type: 'GET',			
			    async: false,
			    timeout: 8000,				
			    success: function(json) 
			    { 				
				    if(DEBUG) console.log(json);	
				    flickr_cache = eval("["+json+"]");
				    if(DEBUG)console.log(flickr_cache);
			    }
		    });
	    }
	    catch(e) {
		    if(DEBUG) console.log(e);
	    }
    	
	    gettwyrics(); 
	}
});
