$(document).ready( function( ) {
	
	application.filterReady( Globals.previousFilter );
	
	if( $( "#fan_response" ).length )
		setTimeout( function( ) { $( "#fan_response" ).fadeOut( "slow" ); }, 5000 );
	if( $( "#fanremove_response" ).length ) 
		setTimeout( function( ) { $( "#fanremove_response" ).fadeOut( "slow" ); }, 5000 );
	
	$.history.init( application.pageload );
	
	setInterval( application.poll, 5000 );
} );

var application = { };

application = {
	do_page: function( filter, page ) {
		window.location.hash = "#" + filter + ":" + page;
		$( "#" + Globals.previousFilter + "_tab" ).attr( "class", "inactiveNav" );
		$( "#" + filter + "_tab" ).attr( "class", "activeNav" );
		application.hide_fan( );
		Globals.previousFilter = filter;
		$( "#twitbrand_content" ).html( "<div class='ajax_indicator'><img src='" + Globals.application_url + "images/indicator_white_large.gif'/> " + Globals.loading_text + "</div>" );
		$.get( Globals.application_url + 'application_data.php?page=' + page + '&filter=' + filter, function( data ) {
		   $( "#twitbrand_content" ).html( data );
		   application.filterReady( filter );
		} );
	},
	
	show_fan: function( ) {
		$( "#fan_box" ).css( "display", "block" );
	},
	
	hide_fan: function( ) {
		$( "#fan_box" ).css( "display", "none" );
	},
	
	toggle_fan: function( ) {
		if( $( "#fan_box" ).css( "display" ) == "block" )
			application.hide_fan( );
		else
			application.show_fan( );
	},
	
	pageload: function( ) {
		if( window.location.hash ) {
			var hash = window.location.hash.replace( /^.*#/, '').split( ":" );
			if( Globals.previousFilter != hash[ 0 ] )
				application.do_page( hash[ 0 ], hash[ 1 ] );	
		} else {
			window.location.hash = "#" + Globals.previousFilter + ":1";
		}
	},
	
	filterReady: function( filter ) {
		switch( filter ) {
			case "twitpic":
				$( "a.twitpicLightbox" ).lightBox( { fixedNavigation:true } );
				$( "span.twitpic_tweet" ).css( "display", "none" );
			break;
			case "hashtag":
				$( "a.hashtag" ).each( function( ) {
					$( this ).css( "font-size", Globals.minfont + Math.round( ( Globals.maxfont - Globals.minfont ) * $( this ).attr( "weight" ) ) );
				});
			break;
		}	
	}, 
	
	poll: function( ) {
		var status_id = 0;
		switch( Globals.previousFilter ) {
			case "twitpic":
				status_id = Globals.twitpic_id;
			break;
			case "usertweet":
				status_id = Globals.user_id;
			break;
			case "public":
				status_id = Globals.public_id;
			break;
			default: 
				status_id = false;
			break;
		}
		if( status_id ) {
			$.get( Globals.application_url + 'application_poll.php?status_id=' + status_id + '&filter=' + Globals.previousFilter, function( data ) {
				if( data.length > 1 ) {
					$( "<div>" ).css( "display", "none" ).html( data ).prependTo( "#datawrapper" ).slideDown( "slow" ).fadeIn( "slow" );
					application.filterReady( Globals.previousFilter );
				}
			} );
		}
	}
}
