var tmpMainheight = 0;

function updateColumnHeight()
{
	// Get main column height
	var mainheight = jQuery( "#main-column-height" ).height();

	// Fallback
	if( !mainheight ) {
		mainheight = jQuery( "#maincolumnheight" ).height();
	}

	// Fallback
	if( !mainheight ) {
		mainheight = jQuery( "#wide-column-height" ).height();
	}

	// Fail safe for scroll adjustment
	if( tmpMainheight < mainheight + 100 ) {
		return;
	}

	// Get other column heights
	var columnswrapper = jQuery( "#columns-wrapper-height" );
	var rightcolumn = jQuery( "#right-column-height" );
	var middlecolumn = jQuery( "#middle-column-height" );
	var newsletter = jQuery( "#newsletter-height" );

	var diff = 0;

	// Calculate the diff between the main and the middle or right column
	if( columnswrapper.length > 0 ) {
		if( rightcolumn.height() >= middlecolumn.height() ) {
			diff = columnswrapper.height() - rightcolumn.height();
		}
		else {
			diff = columnswrapper.height() - middlecolumn.height();
		}
	}

	var indexheight = 0;

	// Set the largest total height
	if( mainheight >= columnswrapper.height() && mainheight >= rightcolumn.height() ) {
		indexheight = mainheight;
	}
	else if( columnswrapper.height() >= mainheight && columnswrapper.height() >= rightcolumn.height() ) {
		indexheight = columnswrapper.height();
	}
	else {
		indexheight = rightcolumn.height();
	}

	// Update the right column (if it exists)
	if( rightcolumn.length > 0 ) {
		rightcolumn[0].style.minHeight = ( newsletter.length > 0 ? indexheight - diff : indexheight ) + "px";
	}
	// Update the middle column (if it exists)
	if( columnswrapper.length > 0 ) {
		columnswrapper[0].style.minHeight = indexheight + "px";
	}
}
jQuery( window ).load( updateColumnHeight );
jQuery( window ).scroll( updateColumnHeight );

// Sticky ad scroll
var menuIsFixed = false;

jQuery( document ).ready( function(){
	// Calculate offset of the ad
	if( jQuery( "#sticky-ad" ).length > 0 )
	{
		var menuOffsetTop = jQuery( "#sticky-ad" ).offset().top;

		jQuery( document ).bind( "scroll", function() {
			// Take proper action
			if( window.scrollY > menuOffsetTop )
			{
				jQuery( "#sticky-ad" ).addClass( 'fixed-ad' );

				menuIsFixed = true;
			}
			else
			{
				jQuery( "#sticky-ad" ).removeClass( 'fixed-ad' );

				menuIsFixed = false;
			}
		} );
	}
});
