var tweet_count_monitor = {}; // used to count tweets per searchterm
var banner_interval = 20;	  // number of tweets between banners
// define your banners here
var banners = [
	'<div STYLE=\"font-size: 8pt; text-align: center; height:100px; margin-left: 1px; margin-top: 0px; margin-bottom: 2px; margin-right: 1px; color: black; background-color: #ffffff;\"><img src="img/banneruwbannerhier.png" border="0"></div>',
		'<div STYLE=\"font-size: 8pt; text-align: center; height:75px; margin-left: 1px; margin-top: 8px; margin-bottom: 2px; margin-right: 1px; color: black; background-color: #ffffff;\"><iframe src=\"adsense.htm\" width=\"234px\" height=\"60px\" frameborder=\"0\" marginwidth =\"0px\" marginheight=\"0px\" scrolling=\"no\"></iframe></div>',
				'<div STYLE=\"font-size: 8pt; text-align: center; height:120px; margin-left: 1px; margin-top: 8px; margin-bottom: 2px; margin-right: 1px; color: black; background-color: #ffffff;\"><img src="img/giro555234.png" border="0"></div>',
	'<div STYLE=\"font-size: 8pt; text-align: center; height:75px; margin-left: 1px; margin-top: 8px; margin-bottom: 2px; margin-right: 1px; color: black; background-color: #ffffff;\"><a href="http://www.twitter.com/onesitenl"><img src="img/bannervolgons.png" border="0"></A></div>'
];
function getRandomBanner()
{
	return banners[Math.round(Math.random() * (banners.length - 1))];
}

function getLocation(mycolumn)
{
	var column = jQuery(mycolumn);

	if(column.css('display') == 'none')
		return false;
		
	var locationstr 	= column.find('input.loc').val();
	var locationradius 	= column.find('select.radius').val();
	var locationunits 	= column.find('select.units').val();
	
	column.find('div.title small.location').html(locationstr);	
	
	if(locationstr != '' && window.geocodes[locationstr] != 'loading' && !window.geocodes[locationstr])
	{
		window.geocodes[locationstr] = 'loading';
		column.data('locationstr',locationstr);
		column.find('div.stream').prepend('<div class="changed">Location changed: '+locationstr+'</div>');	
		column.find('div.title small.location').html(locationstr);			
		column.data('paused',true);
		column.addClass('paused');
		$('div.pausedmessage span.msg',column).text('Geocoding...');
		window.geocoder.getLatLng(locationstr,function(point)
		{
			var locationstr =  column.find('input.loc').val();
//					console.log(locationstr);
			if (point) 
			{
				window.geocodes[locationstr] = point;	
				restartAllColumns();								
			}
			else
			{
				window.locationfail = 'YES';					
			}
		});
	}
	if(column.data('locationstr') != locationstr && locationstr != '' && locationstr != undefined)
	{
		//console.log(locationstr);
		column.data('locationstr', locationstr);	
		searchkey = column.attr('id')+'-'+locationstr;
		
		window.tweetstack[searchkey] = [];
		column.find('div.stream').prepend('<div class="changed">Location changed: '+locationstr+'</div>');
		column.find('div.title small.location').html(locationstr);
	}
}
function getLocations()
{
	if (GBrowserIsCompatible()) 
	{	
		$('div.column').each(function()
		{
			getLocation(this);
				
		});
	}
	
}
String.prototype.linkusers = function() 
{
  return this.replace(/[@]+[A-Za-z0-9-_]+/g, function(us) 
  {
    var username = us.replace("@","");
    
    us = us.link("http://twitter.com/"+username);
  	us = us.replace('href="','target="_blank"  title="'+username+'"  href="');
    return us;
  });
};

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

}; 

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

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


function sizeColumns()
{

	var columns = $('div.column',$('#column-manager'));
	var w = Math.floor($(window).width()/columns.length);
	columns.width(w);
	var h = Math.floor($(window).height()-$('#toolbar').outerHeight());
	//columns.height(h);
	//$('div.column div.stream').height(h);
}

function addColumn(search,thelocation)

	
		
	


{
			
			
			
			

			
			
			
		var column = $('#columntemplate div.column').clone();
		$('#welcome').fadeOut();
		var titlehtml = search+' <small class="location"></small>'
		
		column.find('div.title').html(titlehtml);
		column.attr('id',search);
		column.data('search',search);

		//console.log('add: '+thelocation);
		if(thelocation != false)
		{
			column.find('input.loc').val(thelocation);
			column.data('locationstr',thelocation);
		}
		$('#column-manager').append(column);	
		
		sizeColumns();
		getLocations();
		
		updateHashes();
		
		column.oneTime(1,'firstloader',getTweets);	
		column.everyTime(10000,'loader',getTweets);		
		try
		{
			var clicky_pause_timer = 200;
			clicky.log('#ADD COLUMN','TERM: '+search);
			var clicky_pause_timer = 500;			
		} catch(e){}	
}
OnesiteColumns = $.klass(
{
	initialize: function()
	{
		this.columns = [];
//		this.element.append('');
		manager = this;
		$('#addcolumn',this.element).click(function()
		{
			var search = $('#search').val();
			manager._addColumn(search,false);
			return(false);
		});
		$(window).resize(this._sizeColumns);
		
		this.element.sortable({axis:'x',scroll:false,tolerance: 'pointer',handle:'div.title',items:'div.column' });
	},
	_sizeColumns: function()
	{
		sizeColumns();
	},
	_addColumn: function(search)
	{
		addColumn(search,false);
	},
});







function getTweets()
{
	var column = $(this);	
	if($(this).data('search') == undefined)
		$(this).data('search',$(this).attr('id'));
		
	var locationurl = '';
	var locationstr = column.data('locationstr');
	if(window.geocodes[locationstr] == 'loading')
	{
		column.data('paused',true);
		column.addClass('paused');
		$('div.pausedmessage span.msg',column).text('Geocoding...');
		return false;
	}
	
	var search = $(this).data('search');
	if(locationstr ==undefined) locationstr = '';
	var searchkey = search+'-'+locationstr;
	since = 0;
	if(!window.tweetstack[searchkey])
		window.tweetstack[searchkey] = [];

	column.addClass('loading');
	

	rpp = '&rpp=100';
	
	if(!window.tweeturls[searchkey])
	{
		window.tweeturls[searchkey] = '?q='+search.replace('#','%23');
		rpp = '&rpp=20';
	}
	searchstr = window.tweeturls[searchkey];

	if(window.geocodes[locationstr] != undefined && window.geocodes[locationstr] != 'loading')
	{
		point = window.geocodes[locationstr];
		locationurl = '&geocode='+point.lat()+','+point.lng()+','+$('select.radius',column).val()+$('select.units',column).val();		
	}
	
	var url = "http://search.twitter.com/search.json"+searchstr+rpp+locationurl+"&lang=nl&callback=?";
	
	// create a counter for the specified searchkey
	// if it doesn't already exist
	if (!tweet_count_monitor[searchkey]) {
		tweet_count_monitor[searchkey] = 0;
	}
	$.getJSON(url, function(json)
	{		
		window.tweeturls[searchkey] = json.refresh_url;
		
		adjustSpeeds();
		
		$(json.results).each(function() 
		{
			window.tweetstack[searchkey].push(this);
		});	
		
		
		column.everyTime(500,'drawer',drawTweets);	
	});	
	
	
	
}





function adjustSpeeds(column)
{
		var column = jQuery(column);
		if(column.data('search') == undefined)
			column.data('search',column.attr('id'));
		
		var search = column.data('search');
		var locationstr = column.find('input.loc').val();
		var searchkey = search+'-'+locationstr;
		var queue_length = 1;
		if(window.tweetstack[searchkey] != undefined)
		{
			 queue_length = window.tweetstack[searchkey].length+1;
		}	
		
		var time = 400+(10000/queue_length);	
			
		column.data('speed',time);
		//console.log(search+ ' speed: '+time);
		
}

function resizeBlockout()
{
	var w = jQuery(window).width();
	var h = jQuery(window).height();
	
	var boxtop = h/2-(140);
	$('#tweetblockout').css({width:w,height:h});
	$('#profile').css('top',boxtop)
}
function drawTweets()
{

	if($(this).data('prevspeed') != $(this).data('speed'))
	{
		$(this).stopTime('drawer');
		$(this).everyTime($(this).data('speed'), 'drawer',drawTweets);
	}
	
	$(this).data('prevspeed',$(this).data('speed'));
	
	if($(this).data('search') == undefined)
		$(this).data('search',$(this).attr('id'));
		
	var search = $(this).data('search');
	var locationstr = $(this).find('input.loc').val();
	var searchkey = search+'-'+locationstr;
	
	$(this).removeClass('loading');
	
	$('div.pausedmessage div.counter',this).text(window.tweetstack[searchkey].length+' nieuwe tweets');
	if(!$(this).data('paused'))
	{		
		if(window.tweetstack[searchkey].length > 0)
		{
			var tweet = window.tweetstack[searchkey].pop();
			
			var thedate = new Date(Date.parse(tweet.created_at));
			var hourstr = thedate.getHours();
			var minustr = new String(thedate.getMinutes());
			if(minustr.length<=1)
				minustr = '0'+minustr;
			var thedatestr = hourstr+':'+minustr;
			var locstr = '';
			//console.log(tweet);
			src = tweet.source.replace(/&gt;/gi,'>').replace(/&lt;/gi,'<');
			
			if(tweet.location != undefined)
				locstr = ' <span class="locstr">@ '+tweet.location+'</span>';
			var divstr = '<div id="tw'+tweet.id+'" class="tweet"> <a class="profile_button twitter-anywhere-user"  title="'+tweet.from_user+'" href="http://www.twitter.com/'+tweet.from_user+'"> <img class="profile" title="'+tweet.from_user+'" width="48" height="48" src="'+tweet.profile_image_url+'"> </a><div class="text"><p class="text">'+tweet.text.linkify().linkusers().linktags()+'<br>door: <a class="profile_button twitter-anywhere-user" href="http://www.twitter.com/'+tweet.from_user+'"> '+tweet.from_user+'</a> om:<a href="http://twitter.com/'+tweet.from_user+'/status/'+tweet.id+'" target="_blank">'+thedatestr+'</a></b>'+locstr+' : <a href="http://twitter.com/?status=RT: via http://onesite.nl @'+tweet.from_user+'&nbsp;'+tweet.text+'">retweet</a> : <a href="http://twitter.com/?status=@'+tweet.from_user+' RE: via http://onesite.nl :" target="_blank">reply</a></span><div style="display:none" class="rawtweettext">'+tweet.text+'</div></div></div>';
			
			if (tweet_count_monitor[searchkey] >= banner_interval) {
				$('div.stream',this).prepend(getRandomBanner());
				tweet_count_monitor[searchkey] = 0;
			} else {
				tweet_count_monitor[searchkey]++;
			}
			
			$('div.stream',this).prepend(divstr);
			sizeColumns();
			$('div.stream #tw'+tweet.id,this).show(window.animmode,window.animoptions,window.animspeed);			
		}
	}
	
	$('div.column').each(function()
	{ 
		$('div.stream div.tweet:gt(100)',$(this)).remove();
	});
}
function restartAllColumns()
{
	$('div.column').each(function()
	{
		var column = $(this);
		
		column.stopTime('drawer');
		column.stopTime('loader');		
		
		
		column.data('paused',false);
		column.removeClass('paused');
		
		column.oneTime(1,'firstloader',getTweets);	
		column.everyTime(10000,'loader',getTweets);	
	});
}
jQuery(document).ready(function($)
{

	$('#toolbarform').live('submit',function(e)
	{
		$(this).find('a#addcolumn').click();
		return(false);
	});
	$('#column-manager').attach(OnesiteColumns);
	
	window.geocoder =  new GClientGeocoder();	
	window.geocodes = {};
	 getLocations();
	 
	$('input.geocode').live('click',function()
	{
		$(this).next().toggle();
	});
	$('a.closer').click(function()
	{
		$('#tweetblockout').fadeOut();
		$('#tweetbox').fadeOut();
		return(false);
	});
	$('div.column div.controls a.close').live('click',function()
	{
		var column = $(this).parent().parent();
		
		column.stopTime('drawer');
		column.stopTime('loader');		
		
		column.remove();
		updateHashes();		
		sizeColumns();
	});
	$('div.column div.settings-panel div.hide-settings').live('click',function()
	{
		var column = $(this).parent().parent();
		
		getLocations();
		
		search = column.data('search');
		var locationstr = column.find('input.loc').val();
		var searchkey = search+'-'+locationstr;

		window.tweetstack[searchkey] = [];
		window.tweeturls[searchkey] = '';
		
		column.find('div.settings-panel').slideToggle();		
	});
	$('div.column div.controls a.settings').live('click',function()
	{
		var column = $(this).parent().parent();
		
		$('div.settings-panel',column).slideToggle();
	});
	$('div.column div.controls a.pause').live('click',function()
	{
		var column = $(this).parent().parent();
		
		column.data('paused',true);
		column.addClass('paused');	
		column.fadeTo('fast',0.6);	
		
		$('div.pausedmessage span.msg',column).text('gepauzeerd');
		$(this).addClass('play').removeClass('pause');
	});
	$('div.column div.controls a.play').live('click',function()
	{
		var column = $(this).parent().parent();
		
		column.data('paused',false);
		column.removeClass('paused'); // voorbeeld voor remove class
		column.fadeTo('fast',1.0)		;	
		$(this).addClass('pause').removeClass('play');
	});
	
	$('#tweetblockout').click(function()
	{
		$(this).fadeOut();
		$('#tweetbox').fadeOut();
	});
	$('div.column a.profile_button').live('click',function()
	{
		var username = $(this).attr('title');
		
		loadProfile(username);
		
		return(false);
	});
	
	$('#share a.tweet').click(function()
	{
		var msg = 'Using @onesitenl to watch twitter: ';
		var terms = [];
		$('div.column div.title').each(function()
		{
			terms.push($(this).text());
		});
			
		msg += terms.join(', ');
		msg += ' - ';
		
		urlstring = 'http://www.onesite.nl/?'+jQuery.cookie('onesite-search');

		window.twitterstatus = msg;

		BitlyClient.call('shorten', {'longUrl': urlstring}, 'announce');		
		
		return(false);
	});
	
	$('div.settings-panel input,div.settings-panel select').live('change',function()
	{
		getLocations();
	});
	
	var init = '';
	if(window.location.href.indexOf('#')> 0)
	{
		init = window.location.href.substring(window.location.href.indexOf('#')+1)
	}
	else if(window.location.href.indexOf('?')> 0)
	{
		init = unescape(window.location.search.substring(1));
	}
	else
	{
		if(jQuery.cookie('onesite-search'))
			init = jQuery.cookie('onesite-search');
	}
	if(init != '')
	{
		//console.log(init);
		var searches = init.split('&');
		loc = false;
		for(var i in searches)
		{
			var search = searches[i];
			;
			if(search.indexOf('((') > 0)
			{
				search = search.replace('))','');
				var bits  = search.split('((');
				search = bits[0];
				loc = bits[1];
			}
			
			addColumn(search,loc);
		}
	}
});	
function updateHashes()
{
	window.newhashes = [];
	$('div.column:visible').each(function(i,col)
	{
		col = $(col);
		var search = col.data('search');
		var loc = col.data('locationstr');
		
		var key = search;
		
		if(loc != '' && loc != undefined)
			key += '%28%28'+loc+'%29%29';
			
		window.newhashes.push(key);
	});
	hash = window.newhashes.join('&');
	window.newhashes = [];
	
	jQuery.cookie('onesite-search',hash,999);
}
function announce(data)
{
    var first_result;
    // Results are keyed by longUrl, so we need to grab the first one.
    for     (var r in data.results) {
            first_result = data.results[r]; break;
    }
    //console.log(first_result);
    var url = first_result.shortUrl;
	window.twitterstatus += url;
	tweet(window.twitterstatus);
}
function tweet(defaulttext,data)
{
	T = window.anywhere;
	var w = jQuery(window).width();
	var h = jQuery(window).height();
	var boxtop = h/2-(140);
	$('#tweetblockout').css({width:w,height:h}).fadeTo('fast',0.8);
	
	if(data != undefined && data['in_reply_to_status_id'] != undefined)
	{
		the_tweet = $('#'+data['in_reply_to_status_id']);
		the_copy = the_tweet.clone();
		
		$('#tweetbox div.reply').html(the_copy);
		$('#tweetbox div.title').html('Replying to tweet..');
	}
	else if(data != undefined && data['retweet'] != undefined)
	{
		the_tweet = $('#'+data['retweet']);
		the_copy = the_tweet.clone();
		
		data = {};
		
		$('#tweetbox div.reply').html(the_copy);
		$('#tweetbox div.title').html('Retweeting tweet..');		
	}
	else
	{
		$('#tweetbox div.reply').html('');
		$('#tweetbox div.title').html('Send a tweet..');
	}
	$('#tweetbox div.frame').html('');
	$('#tweetbox').css('top',boxtop).fadeIn();
	T('#tweetbox div.frame').tweetBox({
	    label: "Send a tweet..",
	      height: 100,
	      width: 400,
	      defaultContent: defaulttext,
	      data: data
	    });	
}
$(window).resize(function()
{
	var w = jQuery(window).width();
	var h = jQuery(window).height();
	var boxtop = h/2-(140);
	$('#tweetblockout').css({width:w,height:h});
	$('#tweetbox').css('top',boxtop);
	resizeBlockout();
});

/**
 * Trigger a click on the specified element
 * @param target The element
 */
function fireElement(target) {
	if(document.dispatchEvent) { // W3C
		var oEvent = document.createEvent( "MouseEvents" );
		oEvent.initMouseEvent("click", true, true,window, 1, 1, 1, 1, 1, false, false, false, false, 0, target);
		target.dispatchEvent( oEvent );
	}
	else if(document.fireEvent) { // IE
		target.fireEvent("onclick");
	} 
}

/**
 * Trigger a click on the specified element
 * @param objID The element's ID attribute
 */
function fireElementById(objID) {
	var target=document.getElementById(objID);
	fireElement(target);
}

/**
 * Trigger the addcolumn by passing in a search term
 */
function addColumnFromSearch(searchTerm) {
	// Get the input with id="search"
	var el = document.getElementById('search');
	// And set its value to the value of the link
	el.value = searchTerm.toLowerCase();
	// Get the submit button
	var button = document.getElementById('addcolumn');
	// And fire a "click" event for the button
	fireElement(button);
el.value = "brekend";
}

/**
 * Adds a column thru a <a href="#" onclick="addColumnFromLink(this)">SEARCH-TERM</a>
 */
function addColumnFromLink(e) {
	addColumnFromSearch(e.innerHTML);
}

/**
 * Adds some default columns.
"nieuws",
		"sport"

 * NOTE: this function is called by <body onload="addSomeColumns()">
 */
function addSomeColumns() {
	var columns = [
		"brekend"
		
	];

	for (var i = 0; i < columns.length; i++) {
		addColumnFromSearch(columns[i]);
	}
}
