var BORDER_WIDTH = 1;

var LATEST_NEWS_TICKER_TIMEOUT = 7000;
var LATEST_NEWS_FADER_TIMEOUT = 1000;
var timeoutThreadId = 0;


$( document ).ready( function()
{
	/**
	 * MAIN NAV
	 */
	resizeNavElm( "nav_bar", 1 );

	/**
	 * FOOTER LINKS
	 */
	//$('#footer_links > ul').css('padding','0');
	//resizeNavElm( "footer_links" );

	//$('#footer_links ul > li').css('width','24%');
	/*$('#footer_links, #footer_links ul').css('margin','0').css('padding','0');*/
	
	/**
	 * BOTTOM GREYBAR
	 */
	resizeNavElm( "bottom_greybar_mid" );

	/**
	 * SEARCH BUTTON ROLLOVER
	 */
	$( "#search_submit" ).mouseover( function()
	{
		$( "#search_submit" ).attr( "src", "/images/button_go_r.gif" );
	});
	$( "#search_submit" ).mouseout( function()
	{
		$( "#search_submit" ).attr( "src", "/images/button_go.gif" );
	});
	
	/**
	 * CLEAR SEARCH FIELD WHEN CLICKED
	 */
	$( "#search_keywords" ).click( function()
	{
		$( "#search_keywords" ).val( "" );
	});
	
	/**
	*	IMAGE HEADINGS
	*/
	imageHeadings( $('.panelHeader h2'), 'Heading_on_Tan' );
	imageHeadings( $('#content h1'), 'Heading_on_White' );
	
	imageHeadings( $('#search_form > .header2'), 'Heading_on_Tan' );
	imageHeadings( $('#language_box .header2'), 'Heading_on_Beige' );
	imageHeadings( $('.quicknav a'), 'Heading_on_Beige' );
	
	//imageHeadings( $('#navbar a'), 'Subheading_on_Tan' );
	imageHeadings( $('#bcbar > .header2:first'), 'Subheading_on_Beige' );

	
	/**
	 * Set pdf links to open in new window, unless target specified
	 */
	var elms = $('a[@href$=.pdf]');
	elms.each(
		function()
		{
			if (! (this.target.length > 0))
			{
				$(this).attr('target', '_blank');
			}
		}
	);

	/**
	 * LATEST NEWS
	 */
	initialiseLatestNews();
	$( "#prev_news" ).click( getPrevNews );
	$( "#next_news" ).click( getNextNews );
	//timeoutThreadId = setTimeout( cycleNews, LATEST_NEWS_TICKER_TIMEOUT );
	timeoutThreadId = setTimeout( getNextNews, LATEST_NEWS_TICKER_TIMEOUT );
	
});


//	Perform image replacement on elements containing text only.
	//	If the element is contained within  <a href=''></a> then 
	//	the tag is rebuilt inside the elements, to fix the links not
	//	working in IE.
	//
	//	The code handles text-content with <strong></strong> by
	//	assigning them the heading style with 'Bold_' prepended to it.
	//
function imageHeadings(elms, heading_style, bold_heading_style, hover_heading_style, hover_bold_heading)
{
	var heading_style_safe = escape(heading_style);
	
	elms.each(
			function()
			{
				var _this = $(this);
				var replacement_html = '';
				
				
				
				
				
				if (this.childNodes && (this.childNodes.length > 0))
				{
					for (var node_index = 0; node_index < this.childNodes.length; node_index++)
					{
						var node = this.childNodes[node_index];
						
						var node_heading_style_safe;
						var text;
						
						//alert(node.tagName);
						if (node.tagName == "STRONG")
						{
							node_heading_style_safe = 'Bold_' + heading_style_safe;				
							text = node.innerHTML;	
							
						} else {
							node_heading_style_safe = heading_style_safe;
							text = node.nodeValue;							
						}
					
						if (text && text.length > 0)
						{							
							var words = text.split(' ');
							
							for (word_index in words)
							{
								var word = words[word_index];
								
								if (word.length > 0)
								{
									var heading_url = '/cms/modules/image_headings/render_heading.php?text=' + escape(word) + '&amp;stylename=' + node_heading_style_safe;
									replacement_html = replacement_html + "<img class='image_heading' src='" + heading_url + "' alt='' />";
								}
							}
							
						}
					}
					
					if (_this.parent().attr('href') != null)
					{
						var href = _this.parent().attr('href');
						replacement_html = "<a href='" + href + "'>" + replacement_html + "</a>";
					}
					_this.html(replacement_html);
				}
			}
	);
}

function adjustPods()
{
	var leftSidebarHeight = $( '#left_sidebar' ).height();

	/**
	 * CHECK IF BANNER SLIDESHOW EXISTS, IF IT DOES THEN USE ITS HEIGHT ELSE USE CONTENT HEIGHT
	 */
	if( $( "*" ).index( $( '#image_banner' )[0] ) < 0 )
		var midHeight = $( '#mid' ).height();
	else
		var midHeight = bannerImgHeight;
	
	var rightSidebarHeight =  $( '#right_sidebar' ).height();
	
	var stretcherHeight = getMaxHeight( leftSidebarHeight, midHeight, rightSidebarHeight );
	
	var rightPanels = $( '#right_sidebar .panel' );
	rightPanels.each( function()
	{
		//alert( "height: " + $( this ).height() + ", margin-bottom: " + $( this ).css( "margin-bottom" ) );
		stretcherHeight -= parseInt( $( this ).height() ) - parseInt( $( this ).css( "margin-bottom" ) );
	} );

	$( '#stretcher' ).height( stretcherHeight );
}


function getMaxHeight()
{
	var maxHeight = 0;

	if( arguments.length > 0 )
	{
		for( var i = 0; i < arguments.length; i++ )
		{
			if( arguments[i] > maxHeight )
				maxHeight = arguments[i];
		}
	}
	
	return maxHeight;
}

function resizeNavElm( navBarId, withBorder )
{
	if( $( "#" + navBarId ) != undefined )
	{
		var navBarWidth = $( "#" + navBarId ).width();
		var navElms = $( "#" + navBarId + " ul" ).children( "li" );
	
		if( navElms.length > 0 )
		{
			var totalBorderWidth = ( withBorder != undefined ) ? ( navElms.length - 1 ) * BORDER_WIDTH : 0;
			navElmWidth = Math.floor( ( navBarWidth - totalBorderWidth ) / navElms.length );
			$( "#" + navBarId + " ul li" ).width( navElmWidth );
		}
	}
}


function initialiseLatestNews()
{
	
	// @todo Return immediately if print layout or not home page
	//if ( ! ($('#home_page').length > 0)) return;
	//if ( ! ($('#print').length == 0)) return;
	
	
	var $newsPanel = $('.newsPanel');
	
	if ($newsPanel.length > 0)
	{
	
		$('.newsPanel .last_visible').removeClass('last_visible');
		$('.newsPanel .invisible').removeClass('invisible');
			
		$('.newsPanel > .panelContent > ul').innerfade({
			speed:		'slow',
			timeout:	10000
		});
		
	}	
		
		
	/*
	 * Old code
	 */
	
	/*
	var latestNews = $( ".panelNews" );
	if( latestNews.length > 1 )
	{
		var max_height = 0;
		latestNews.each( function()
		{
			if( $( this ).height() > max_height )
				max_height = $( this ).height();
		});
		
		latestNews.height( max_height );
	}
	*/
}


function getPrevNews()
{
	var latestNews = $( ".panelNews" );
	if( latestNews.length > 1 )
	{
		var visibleNewsIdx = -1;
		var i = 0;
		latestNews.each( function()
		{
			if( $( this ).attr( "class" ).indexOf( "panelNewsInvisible" ) < 0 )
				visibleNewsIdx = i;

			i++;
		} );

		if( visibleNewsIdx >= 0 )
		{
			/**
			 * We need to kill the current timeout thread and make a new one.
			 * We also need an extra time to fade out, so add that time in timeout
			 */
			if( timeoutThreadId > 0 )
				clearTimeout( timeoutThreadId );
			timeoutThreadId = setTimeout( getNextNews, LATEST_NEWS_TICKER_TIMEOUT + LATEST_NEWS_FADER_TIMEOUT );

			var visibleNews = latestNews[visibleNewsIdx];

			$( visibleNews ).fadeOut( LATEST_NEWS_FADER_TIMEOUT, function()
			{
				$( visibleNews ).addClass( "panelNewsInvisible" );

				if( visibleNewsIdx > 0 )	// if this is not the first news
				{
					$( visibleNews ).prev().fadeIn( 0, function()
					{
						$( visibleNews ).prev().removeClass( "panelNewsInvisible" );
					} );
				}
				else				// this is the first news hence get the last news
				{
					var lastNews = latestNews[latestNews.length - 1];
					$( lastNews ).fadeIn( 0, function()
					{
						$( lastNews ).removeClass( "panelNewsInvisible" );
					} );
				}
			} );
		}
	}
}


function getNextNews()
{
	var latestNews = $( ".panelNews" );
	if( latestNews.length > 1 )
	{
		var visibleNewsIdx = -1;
		var i = 0;
		latestNews.each( function()
		{
			if( $( this ).attr( "class" ).indexOf( "panelNewsInvisible" ) < 0 )
				visibleNewsIdx = i;

			i++;
		} );

		if( visibleNewsIdx >= 0 )
		{
			/**
			 * We need to kill the current timeout thread and make a new one.
			 * We also need an extra time to fade out, so add that time in timeout
			 */
			if( timeoutThreadId > 0 )
				clearTimeout( timeoutThreadId );
			timeoutThreadId = setTimeout( getNextNews, LATEST_NEWS_TICKER_TIMEOUT + LATEST_NEWS_FADER_TIMEOUT );


			var visibleNews = latestNews[visibleNewsIdx];

			$( visibleNews ).fadeOut( LATEST_NEWS_FADER_TIMEOUT, function()
			{
				$( visibleNews ).addClass( "panelNewsInvisible" );

				if( visibleNewsIdx < ( latestNews.length - 1 ) )	// if this is not the last news
				{
					$( visibleNews ).next().fadeIn( 0, function()
					{
						$( visibleNews ).next().removeClass( "panelNewsInvisible" );
					} );
				}
				else							// this is the last news hence get the first news
				{
					var firstNews = latestNews[0];
					$( firstNews ).fadeIn( 0, function()
					{
						$( firstNews ).removeClass( "panelNewsInvisible" );
					} );
				}
			} );
		}
	}
}


function poppage(mypage,w,h,s){
	var scr = s;
	var winl = (screen.width-w)/2;
	var wint = (screen.height-h)/2;
	settings='height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scr+',toolbar=no,location=no,status=no,menubar=no,resizable=yes,dependent=no'
	windowname = randomString(6);
	win=window.open(mypage,windowname,settings)
	win.focus();
}

/**
 * deprecated, cycle through getNextNews instead
 */
/*
function cycleNews()
{
	getNextNews();
	if( timeoutThreadId > 0 )
		clearTimeout( timeoutThreadId );
	timeoutThreadId = setTimeout( cycleNews, LATEST_NEWS_TICKER_TIMEOUT );
}
*/