jQuery(document).ready(function($) {
	
	// Do we have configuration object?
	if(typeof tweetwall_options == 'object')
	{
		// Create variable for this scope.
		var o = tweetwall_options;
	}
	
	// All new tweets will be stored here.
	var local_storage = obj();
	
	// ---------------------------------------------------------------------------
	
	if (o.is_branded_avatar_bg) {
		$('#ukn-tweetwall').addClass('ukn-branded-avatar-bg');
	}
	if (o.is_branded_takeover) {
		$('body').append('<div id="ukn-branded-takeover"></div>').everyTime(900000, function(){
			$('#ukn-branded-takeover').fadeIn(2500).delay(10000).fadeOut(2500);
		});
	}
	if (o.show_time) {
		$('body').append('<div id="ukn-clock"></div>');
		$('#ukn-clock').jclock();
	}
	if (o.show_stats_link) {
		$('a.ukn-stats-link').show();
	}
	if (o.show_tweet_history) {
		$('body').append('<div id="ukn-tweet-history"></div>');
		tweet_history();
	}
	if (o.show_tweet_graphs) {
		$('body').append('<ul id="ukn-tweet-graphs"></ul>');
		tweet_graphs();
	}
	
	// Build/start cycle.
	$(o.cycle_selector).before('<div id="ukn-tweetwall-nav"></div><a id="ukn-tweetwall-prev" href="#"><span>&lt; </span>Prev</a><a id="ukn-tweetwall-next" href="#">Next<span> &gt;</span></a>');	
	$(o.cycle_selector).addClass('ukn-cycle').cycle({
		fx: o.cycle_fx,
		speed:500,
		timeout: o.cycle_slide_change_period * 1000,
		pause:1,
		pauseOnPagerHover:1,
		sync:1,
		randomizeEffects:0,
		//pager:'#ukn-widget-tweetwall-nav',
		before: update_slide_data,
		next: '#ukn-tweetwall-next',
		prev: '#ukn-tweetwall-prev'
	});
	
	var fadeCatcher = 0;
	$('#ukn-tweetwall').hover(function() {
		if (fadeCatcher == 0) {
			$('a#ukn-tweetwall-prev, a#ukn-tweetwall-next').fadeIn(1000, function() {
				fadeCatcher = 1;
			});
			$('#ukn-tweet-avatars').fadeTo(1000, 0.7);
		}
	}, function() {
		if (fadeCatcher == 1) {
			$('a#ukn-tweetwall-prev, a#ukn-tweetwall-next').fadeOut(1000, function() {
				fadeCatcher = 0;
			});
			$('#ukn-tweet-avatars').fadeTo(1000, 0.5);
		}
	});
	
	// Set interval for periodical AJAX calls. 
	setInterval(function() {
		call();
	}, o.ajax_call_period * 1000);
	
	// Set interval for periodical image switch.
	if (o.bg_image_switch_on) {
		//*
		setInterval(function() {
			image_switch();
		}, o.bg_image_switch_period * 1000);
		//*/
		//image_switch();
	}

	
	/**
	 * 
	 */
	function update_slide_data(currSlideElement, nextSlideElement, options, forwardFlag)
	{
		var do_not_update = true;
		
		$('li', o.cycle_selector).each(function(i, el) {
			
			if($(el).attr('class') === $(nextSlideElement).next().attr('class'))
			{
				do_not_update = false;
			}	
			
			// Do we need to update current element?
			if( ! do_not_update)
			{
				var data = shift_item();
				
				if(data)
				{
					$('p q', el).text(data.tweet);
					$('a.ukn-tweet-user', el)
						.attr('href', 'http://twitter.com/'+ data.from_user +'/status/'+ data.id)
						.text(data.from_user);
					$('a.ukn-tweet-time', el).text(data.create_ad);
					
					$('a.ukn-tweet-image-wrap', el).attr('href', 'http://twitter.com/'+ data.from_user);
					$('a.ukn-tweet-image-wrap img', el)
						.attr('src', 'http://img.tweetimag.es/i/'+ data.from_user +'_n')
						.attr('alt', data.from_user +"'s Avatar");

					$(o.bg_image_selector).prepend(
						$('<li />').append(
							$('<img />').attr('src', data.image)
						)
					);
					$(o.since_id_selector).text(data.id);
				}
			}
		});
		
		// Remove image from end, if they hit a limit.
		$(o.bg_image_selector +' li:gt('+ o.bg_image_limit +')').remove();
		
		// Truncate leftovers.
		local_storage = obj();
	}
	
	/**
	 * get
	 */
	function shift_item()
	{
		if( ! $.isEmptyObject(local_storage))
		{
			return local_storage.shift();
		}
		
		return false;
	}
	
	function obj()
	{
		return new Object({});
	}
	
	/**
	 * 
	 */
	function call()
	{
		$.ajax({
			type: 'POST',
			dataType: 'json',
			url: o.ajax_call_url,
			data: {
				since_id: $(o.since_id_selector).text()
			},
			success: function(r)
			{
				// Save new tweets to local storage.
				if($.isEmptyObject(local_storage))
				{
					local_storage = r;
				}
				else
				{
					for(var i in r)
					{
						local_storage.push(r[i]);
					}
				}
			}
		 });
	}
	
	function image_switch()
	{
		var max         = $('#ukn-tweetwall ul li img').length - o.bg_image_switch_count - 1;
		var not_visible = $('#ukn-tweetwall ul li img:gt('+ max +')').fadeOut('slow');
		
		// Remove style from all li's and add background: none to last ones.
		$(o.bg_image_selector +' li').removeAttr('style');
		$(o.bg_image_selector +' li:gt('+ max +')').css('background', 'none');
		
		var bg_images     = $(o.bg_images); 
		var rand_picked   = new Array();
		var rand_pick_cnt = o.bg_image_switch_count > max ? max : o.bg_image_switch_count;
		
		for(var i = 0; i < rand_pick_cnt; i++)
		{
			var index = rand(0, max);
			
			if($.inArray(index, rand_picked) === -1)
			{
				rand_picked.push(index);
			}
			else
			{
				//console.log('go back');
				i = i - 1;
			}
		}
		
		var i = j = 0;
		
		for(i = 0; i < rand_picked.length; i++)
		{
			$(bg_images[rand_picked[i]]).fadeOut(1500, function(){
				//console.log(j);
				
				var save_src    = $(this).attr('src');
				var switch_with = $(not_visible[j]);
				
				$(this).attr('src', switch_with.attr('src')).fadeIn(1500, function(){
					
					switch_with.attr('src', save_src);	
				});
				
				j++;

			});
		}
	}
	
	function rand(min, max)
	{
		return Math.round(min + Math.random() * (max - min));
	}
	
});

function tweet_history(){
	$.getJSON('/ajax/tweet_history?window=10&max_history=50', function(data){
		if (data.length > 0) {
			$('#ukn-tweet-history').sparkline(data, {
				type: 'line',
				defaultPixelsPerValue: 1,
				lineColor: '#333',
				fillColor: '#000000',
				minSpotColor: '#ffffff',
				maxSpotColor: '#000000',
				spotRadius: 0,
				lineWidth: 1,
				width: '100%',
				height: '50px'
			});
		}
	});
	setTimeout('tweet_history()', 60000);
}

function tweet_graphs(){
	var cats = new Array();
	$.getJSON('/ajax/cat_stats_relative', function(data){
		if (data.length > 0) {
			$('ul#ukn-tweet-graphs').html('');
			for (var x = 0; x < data.length; x++) {
				// data[x].rel_percent
				// data[x].tweet_percent
				$('ul#ukn-tweet-graphs').append('<li class="p' + data[x].rel_percent + ' ' + data[x].cat_css_name + '"><div class="ukn-graph-bar"><span title="Percentage of all Tweets">' + data[x].tweet_percent + '%</span></div><div class="ukn-graph-query">' + data[x].cat_query + '</div><!--<span class="stat-tweet-count">' + data[x].total_tweets + '</span>--></li>');
				
				if (cats[data[x].cat_id] < data[x].total_tweets) {
					if (data[x].id > since_id) 
						since_id = data[x].id;
				//$('#updates').append('Updated: ' + data[x].cat_name + ' - ' + (data[x].total_tweets - cats[data[x].cat_id]) + ' New Tweets<br/>');
				}
				
				cats[data[x].cat_id] = data[x].total_tweets;
			}
		}
	});
	setTimeout('tweet_graphs()', 10000);
}
