$(document).ready(function(){

	/* xhtml valid target=_blank alternative */
	$('.popup').click(function(){
		window.open($(this).attr('href'));
		return false;
	});

   	// Cycle
   	$('#Promo').cycle({ 
    	fx:    'fade', 
    	speed: 1500,
    	timeout: 8000,
    	pause: 1
	});

	// Get currently playing
	var JsonUrl = 'http://tools.lunchboxradio.com/shoutcasts/get_stats/1/2.json?jsoncallback=?';
	$.getJSON(JsonUrl, function(result){
		$('#CurrentlyPlayingLoader').hide();
		if (result.stream_error)
		{
			$('#StreamError').show();
		}
		else
		{
			$('#CurrentlyPlaying').fadeIn();
			$('#CurrentlyPlaying').html('<p><strong>Currently Playing:</strong><br /><a href="http://lunchboxradio.com/LunchBoxRadio.pls">'+result.currently_playing+'</a></p>');

			$('#RecentlyPlayed').fadeIn();
			$('#RecentlyPlayed').html('<p><strong>Recently Played:</strong></p>'+result.history);
		}
	});

	// Request Form

	$('#contactForm').submit(function(){
		$('#Error').hide();
		$('#Success').hide();
		
		var dataString = $('#contactForm').serializeArray();
		
		$.post('/radio.php/contact/request_form/json', dataString, function(data){
			if (data.error == 'true')
			{
				$('#Error').empty();
				$('#Error').fadeIn('slow');
				$('#Error').append(data.content);
			}
			else
			{
				$('#Success').empty();
				$('#Success').fadeIn('slow');
				$('#Success').append(data.content);
				$('#contactForm').each(function(){
					this.reset();
				});
			}
		}, 'json');
		return false;
	});

	// ToolTips!
	$('a.tooltip').tooltip({ 
		track: true, 
		delay: 0, 
		showURL: false, 
		showBody: " - ", 
		fade: 250 
	});
});


/**
 * getStreamStats grabs the stats data for a particular stream. Currently only sets currently playing, 
 * but all stats are available (history, bitrate, etc) 
 */
(function($) {

jQuery.fn.getStreamStats = function(settings){
	// setup defaults
	var config = {
		'stream': 'lbr',
		'limit': '2',
		'target': 'myTarget'
	};
	if (settings) $.extend(config, settings);
	
	var elem = $(this);

	var JsonUrl = 'http://tools.lunchboxradio.com/shoutcasts/get_stats/'+config['stream']+'/'+config['limit']+'.json?jsoncallback=?';
	$.getJSON(JsonUrl, function(result){
		if (result.stream_error)
		{
			elem.find('.'+config['target']).html(result.stream_error);
		}
		else
		{
			elem.find('.'+config['target']).html('<strong>Currently Playing:</strong> '+result.currently_playing);
		}
	});
}

})(jQuery);