/* Initialize Twitter search */
var head = document.getElementsByTagName("head").item(0);
var script = document.createElement('script');
script.setAttribute('src', 'http://search.twitter.com/search.json?rpp=100&q=&callback=tb_json&ors=http%3A%2F%2Fbit.ly%2FZoWLG');
head.appendChild(script);

/* Helper functions */
function strstr( haystack, needle, bool )
{
    var pos = 0;
 
    haystack += '';
    pos = haystack.indexOf( needle );
    if( pos == -1 )
    {
        return false;
    }
    else
    {
        if( bool )
        {
            return haystack.substr( 0, pos );
        }
        else
        {
            return haystack.slice( pos );
        }
    }
}
function stristr( haystack, needle, bool )
{
    var pos = 0;
 
    haystack += '';
    pos = haystack.toLowerCase().indexOf( (needle+'').toLowerCase() );
    if( pos == -1 )
    {
        return false;
    }
    else
    {
        if( bool )
        {
            return haystack.substr( 0, pos );
        }
        else
        {
            return haystack.slice( pos );
        }
    }
}

/* The actual processing and displaying of the tweetbacks */
function tb_json(obj)
{
    tbcontent='';
    var tbcount=0;
    var max = Math.min(5, obj.results.length);

    if(obj.results.length>0)
    {
        for (i=0;i<max;i++)
        {	
            icon = obj.results[i].profile_image_url;
            user = obj.results[i].from_user;
            tweet = obj.results[i].text;
		    addt=true;
		    tbcount++;
		    if(stristr(tweet, 'is.gd', true))
		    {
		        if(strstr(tweet, 'Error: The URL entered was not valid.'))
		        {
			
		        }
		        else
		        {
			        tbcount--;
			        addt=false;
		        }
		    }
		    if(stristr(tweet, 'bit.ly', true))
		    {
			    if(strstr(tweet, ''))
			    {
				
			    }
			    else {
				    tbcount--;			
				    addt=false;
			    }
		    }
		
				
		    tid = obj.results[i].id;
		    twlink ='http://twitter.com/'+user+'/status/'+tid;
            postedAt = obj.results[i].created_at;
	
		    if(addt)
		    {	
			    tbcontent += "<li style='display: block; background-image: url("+icon+"); background-repeat:no-repeat; padding-left:50px; height: 50px; padding-bottom: 10px;'><b><A href='http://twitter.com/"+user+"'>"+user+"</a>:</b> "+tweet+" "+postedAt+"</li>";
			}
	    }	
	}
	if(tbcount>0)
	{
        document.getElementById('tweetbacks').innerHTML = "<h3>Tweetbacks ("+tbcount+")</h3>";
        document.getElementById('tweetbacks').innerHTML += "<ul>";
        document.getElementById('tweetbacks').innerHTML += tbcontent;
	    document.getElementById('tweetbacks').innerHTML += "</ul>";
	}
}

