
var stalk = function ()
{
	var next 		= $( '<a id="next-button" href="#next">Next</a>' );
	var mainSizes 	= [312,104];
	var narrowSizes = [299,96];
	var use;
	
	if( $( '#works-at' ).height() == 104 )
	{
		use = mainSizes;
	}
	else if( $( '#works-at' ).height() == 96 )
	{
		use = narrowSizes;
	}
	
	$( next ).insertAfter( '#stalk' ).click( function ( e )
		{
			e.preventDefault();
			
			if( $( '#works-at' ).height() == 104 )
			{
				use = mainSizes;
			}
			else if( $( '#works-at' ).height() == 96 )
			{
				use = narrowSizes;
			}
			
			var margin = parseInt( $( '#works-at' ).css( 'margin-top' ) ) || 0; 
			var newMargin = margin - use[1];
			
			if( newMargin < ( use[0] * -1 ) )
			{
				$( '#works-at' ).css( { marginTop: '0px' } );	
			}
			else
			{
				$( '#works-at' ).css( { marginTop: newMargin + 'px' } );	
			}
		}
	);
	
	$( '#works-at' ).css( { marginTop: ( Math.round( Math.random() * ( 3 ) ) ) * ( use[1] * -1 ) + 'px' } );
	
	$( window ).bind( 'resize', function()
		{
			$( '#next-button' ).trigger( 'click' );
			$( '#next-button' ).trigger( 'click' ); 
			$( '#next-button' ).trigger( 'click' ); 
			$( '#next-button' ).trigger( 'click' );	
		}
	);
}

var fixBG = function()
{
	$( window ).unbind( 'resize', fixBG );
	
	$( 'body' ).css( { minHeight: $( window ).height() } );
	
	$( window ).bind( 'resize', fixBG );
};

var setImageResize = function ()
{
	$( window ).bind( 'fiximages', function ()
		{
			$( '.post img' ).each( function ()
				{
					//get rhythm
					var rhythm = $( '.post p.first' ).css( 'line-height' );
					rhythm = rhythm.replace( 'px', '' );
					
					// fix height
					$( this ).css( { height: 'auto' } );
					
					var height = $( this ).height();
					
					if( ( height + 10 ) % rhythm != 0 )
					{
						height = ( Math.round( height / rhythm ) * rhythm ) - 10;

						$( this ).css( { height: height + 'px' } );
					}
					
					// fix width
					$( this ).css( { width: 'auto' } );
				}
			);	
		} 
	)
	.bind( 'resize', function()
		{ 
			$( window ).trigger( 'fiximages' ); 
		} 
	);
	
	window.onorientationchange = function()
	{ 
		$( window ).trigger( 'fiximages' ); 
	};
	
	$( window ).trigger( 'fiximages' );
};

$( document ).ready( function ()
	{
		stalk();	
		fixBG();
		setImageResize();
	}
);

