if (typeof(TWESPHERE) == 'undefined') {
	TWESPHERE		= {};
	TWESPHERE.Default 	= {};
}

TWESPHERE.Default = function() {

	var num_tweets;
	var show_all;
	var show_path;
	var seconds;

	var init = function() {		
		options_events();

		//get init form vars
		
		num_tweets	= $('select#num_tweets option:selected').val();
		seconds		= $('select#refresh_seconds option:selected').val();
		if ($('li.options input#show_all:checked').size() > 0) {
			show_all = '1';
		}
		else {
			show_all = '0';
		}
		if ($('li.options input#show_path:checked').size() > 0) {
			show_path = '1';
		}
		else {
			show_path = '0';
		}
		
		//external links
		
		$('a.external').each(function() {
			$(this).attr('target', '_blank');
		});
	}
	
	var options_events = function() {
		
		$('li.options select#num_tweets option').click(function(e) {
			num_tweets = $(this).val();

			post_session_vars();
		});
		
		
		$('li.options input#show_all').click(function(e) {			
			if ($(this).is(':checked')) {
				show_all = 1;
			}
			else{
				show_all = 0;
			}
			
			post_session_vars();
		});
		
		$('li.options input#show_path').click(function(e) {			
			if ($(this).is(':checked')) {
				show_path = 1;
			}
			else{
				show_path = 0;
			}
			
			post_session_vars();
		});
				
		$('li.options select#refresh_seconds option').click(function(e) {
			seconds = $(this).val();
			
			post_session_vars();
		});
	}
	
	var post_session_vars = function() {
		
		var throbber = '<img src="/img/throbber.gif" />';
		$('div#footer div.throbber').html(throbber);
		
		$('li.prefs_saved_indicator').animate({
			'marginLeft': '-15px'}
		, 400)
		
		var opts = 'num_tweets='+num_tweets+'&show_all='+show_all+'&refresh_seconds='+seconds+'&show_path='+show_path+'&form_posted=ParamsForm';
		
		$.post(window.location.pathname + '.ajax', opts, function(data) {
			if (data == 'true') {
				$('li.prefs_saved_indicator').html('<img src="/img/tick.png" alt="" />');
			}
			else {
				alert('User preferences could not be saved');
			}
			
			setTimeout(function() {
				$('li.prefs_saved_indicator').animate({
					'marginLeft': '-40px'}
				, 400)				
			}, 2000);
			
			setTimeout(function() {
				$('li.prefs_saved_indicator').html('<img src="/img/throbber_small.gif" alt="" />');
			}, 3000);
			
			$('div#footer .throbber img').remove();
			
			api_countdown();
		});		
	}
	
	var api_countdown = function() {
	
		var opts = 'form_posted=APICountForm';
		
		$.post(window.location.pathname + '.ajax', opts, function(data) {
			if (data != 'false') {
				$('#api_calls_remaining').text(data);
			}
			else {
				$('#api_calls_remaining').text('Unknown');
			}
		});
		
	}
	
	return {
		init: init
	}
	
}();

jQuery(function($) { TWESPHERE.Default.init(); });

