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'), 'Bold_Heading_on_Tan' );
	
	imageHeadings( $('.quicknav a'), 'Heading_on_Beige' );
	
	//imageHeadings( $('#navbar a'), 'Subheading_on_Tan' );
	imageHeadings( $('#bcbar > .header2:first'), 'Bold_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');
			}
		}
	);
	
	/**
	 * Set external links in the main content area to open in new window
	 */
	var prefix = 'http://' + document.location.host;
	var elms = $('.content_main a');
	elms.each(
		function()
		{
			if (this.href.indexOf(prefix) == 0)
			{
				
			} else {
				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 );
	
	
	/**
	 * VIDEO PLAYER
	 */
	
	initialiseVideoGallery();
	
	/**
	 * FLASH MAP
	 */
	
	initialiseFlashMap();
	
	/**
	 * FLASH PIE
	 */
	
	initialiseFlashPie();
	
	/**
	 * SHARE PRICE
	 */
	
	initialiseSharePrice();
	
	/**
	 * ADD DROP SHADOWS TO THUMBNAILS
	 */
	
	initialisePhotoGallery();
	
	/**
	 * PRINTABLE SUPPORt
	 */
	
	initialisePrintableSupport();
	
	/**
	 * Add support for padding in img[align=left] and img[align=right] cases,
	 * for IE6
	 */
	
	if ($.browser.msie && ($.browser.version.indexOf('6.') == 0))
	{
		$('.content_main > img[@align=right], .content_main > p > img[@align=right]').each(
			function()
			{
				$(this).css('borderLeft', '10px solid white').css('borderBottom', '10px solid white');
			}
		);
		
		$('.content_main > img[@align=left], .content_main > p > img[@align=left]').each(
			function()
			{
				$(this).css('borderRight', '10px solid white').css('borderBottom', '10px solid white');
			}
		);
	}
	
	
	/**
	 * Insert fallback javascript support for min-height, (for IE6)
	 */
	$('#site_background').minmax();

	
	
});


//	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 ( ! ($('#printable').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 initialiseVideoGallery()
{
	var elm = $('#video_player');
	
	if ( ! (elm.length > 0 ) )
	{
		return;
	}
	
	var width = 310;
	var height = 293;
	
	var so = new SWFObject("/tng_video_player.swf", "video_player_swf", width, height, "8", "#ffffff");
	
	so.addParam('scale','noScale');
	so.addParam('menu','false');
	so.addVariable('flv', elm.attr('video_src'));
	
	if ( ! ($('#printable').size() > 0))
	{
		so.write("video_player");
	}
	
	//	Insert behaviours for each in video_list
	elm = $('#video_list a.video_link')
			.click(
				function(event)
				{
					var video_src = $(this).attr('video_src');
					 
					$('#video_player > *')[0].setFLV(video_src);
					
					event.stopPropagation();
					event.preventDefault();
					return false;
					
				}
			);
}


function initialiseFlashMap()
{
	var elm = $('#flashmap');
	
	if ( ! (elm.length > 0 ) )
	{
		return;
	}
	
	var width = 380;
	var height = 340;
	
	var so = new SWFObject("/cms/modules/flashmap/flashmap_2.swf", "flashmap_swf", width, height, "8", "#ffffff");
	
	so.addParam('scale','noScale');
	so.addParam('menu','false');
	so.addParam('quality','best');
	so.addParam("allowScriptAccess", "sameDomain");
	
	if ( ! ($('#printable').size() > 0))
	{
		so.write("flashmap");
	}
}

function initialisePhotoGallery()
{
	var $elm = $('table.photo_gallery');
	
	if ($elm.length > 0)
	{
		$('.thumbnailImg a ', $elm).wrap("<span class='drop_shadow'></span>").wrap("<span class='drop_shadow_invert'></span>");
						
						
	}
}

function initialiseFlashPie()
{
	var elm = $('#flashpie');
	
	if ( ! (elm.length > 0 ) )
	{
		return;
	}
	
	var width = 560;
	var height = 321;
	
	var so = new SWFObject("/flash/share_info.swf", "flashpie_swf", width, height, "8", "#ffffff");
	
	so.addParam('scale','noScale');
	so.addParam('menu','false');
	so.addParam('quality','best');
	so.addParam("allowScriptAccess", "sameDomain");
	
	if ( ! ($('#printable').size() > 0))
	{
		so.write("flashpie");
	}
}


function initialisePrintableSupport()
{
	var elm = $('#printable');
	
	if (elm.length > 0)
	{
		window.print();
	}
}

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 initialiseSharePrice()
{
	var $elm = $('#share_price_content');
	
	
	if ($elm.size() > 0)
	{
		if (LS_Ric)
		{
			$('#share_price_content .code').html(LS_Ric);
		}
		
		if (LS_SharePrice)
		{
			$('#share_price_content .share_price').html('AUD $' + LS_SharePrice);
		}
		
		if (LS_TimeStamp)
		{
			$('#share_price_content .time').html(LS_TimeStamp);
		}
		
		if (LS_DateStamp)
		{	
			$('#share_price_content .date').html(LS_DateStamp);
		}	
			
		$('#share_price_content .panelContentRight').css('visibility','visible');
		
	}
}

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 );
}
*/