//	Safe Firebug debug call
function debug(obj){
	try{
		console.log(obj)
	}catch(e){}
}

//	Simple JS access to cookies
function createCookie(name,value,days){
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

// Read a cookie
function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
//	Delete a cookie
function eraseCookie(name)
{
	createCookie(name,"",-1);
}


//	Setup Mechanism
//	Initialises all javascript

var largestBody	= 0;
var largestFooter  = 0;
var largestLowerBody  = 0;
var largestLowerFooter  = 0;

function setup(){
	
	//	Top level othersites drop down
	$('#otherSites').unbind().hoverIntent(
		{ sensitivity: 1,
		   interval: 150,
		   over: function(){
		   		$(this).children('ul').find('a').css('height','2.45em');
				$(this).children('ul').slideDown({ duration: 300, easing: 'easeOutCirc',complete:function(){$(this).find('a').css('height','auto');}})},
		   timeout: 150,
		   out: function(){
		   		$(this).children('ul').find('a').css('height','2.45em');
				$(this).children('ul').slideUp({ duration: 300, easing: 'easeInCirc',complete:function(){$(this).find('a').css('height','auto');}});
			}
		}
	)
	
	//	Disable other sites click
	$('#otherSites').click(function(){return false})

	//	Main menu drop downs (overrides css)
	$('#popup div.body').hoverIntent(
		{ sensitivity: 1,
		   interval: 100,
		   over: function(){},
		   timeout: 100,
		   out: function(){
		   		toggleSites()
				$('#popup div.body').slideUp({ duration: 300, easing: 'easeInOutCirc'});
				
				}
		}
	)

	normaliseHeights();

	//	Size switcher
 	$('#styleSize').click(function() {
		   switchSize($(this).html());
            return false;
      });
	

	//	Country clicker
	$('#siteWideNavigation').find('.change').click(toggleSites)

	//	Left column
	lineHeight();


  // Change style size if cookie exists
  var c = readCookie('style');
  if (c) switchSize(c);
}

function setupMainNavigation(){
	//	Main menu drop downs (overrides css)
	$('#mainNavigation').children('li').unbind().hoverIntent(
		{ sensitivity: 1,
		   interval: 100,
		   over: function(){
			   $(this).children('ul').slideDown({ duration: 300, easing: 'easeOutCirc'});
			},//
		   timeout: 100,
		   out: function(){
		   		$(this).children('ul').slideUp({ duration: 100, easing: 'easeOutCirc'});
			}
		}
	)
	
	//	Disable section links
	$('#mainNavigation').children('li').children('a').unbind().click(function(){return false});
	
	// Override Main menu CSS
	$('#mainNavigation').find('ul').css('display','none');

	adjustLinkBehavior();
}

//	changes bahaviour of specified links when js is enabled
function adjustLinkBehavior() {
	adjustBreadcrumbs();
	adjustMainNavigation();
}

// function removes link behavior for breadcrumbs that are only index pages
function adjustBreadcrumbs() {
	//	disable onclick event for specified links
	$('#breadcrumbs a.index').unbind().click(function(){return false});
	
	//	remove link styling
	$('#breadcrumbs a.index').css('cursor', 'text');
	$('#breadcrumbs a.index').css('text-decoration', 'none');
}

//	function that removes link styling from main nav top links
function adjustMainNavigation() {
	//	style mouse pointer for main nav links
	$('#mainNavigation li').css('cursor', 'default');
	$('#mainNavigation li a').css('cursor', 'default');
	$('#mainNavigation ul li a').css('cursor', 'pointer');
}

function lineHeight(){
	h1 = $('#HPWhoAreWe').height();
	h2 = $('#HPNews').height();
	editModeNewsContainer = $('#CQEditMode_NewsListHome');
	if (typeof(editModeNewsContainer) != 'undefined') {
		h2 = Math.max(h2, editModeNewsContainer.height());
	}
	if (h2 > h1) {
		$('#HPWhoAreWe').height(h2);
	}
}

function autoHeights(){
	 largestBody	= 0;
	 largestFooter  = 0;
	 largestLowerBody  = 0;
	 largestLowerFooter  = 0;	
	
	$('.bodyTop').css('height','');
	$('.lowerTop').css('height','');
	$('.bodyFooter').css('height','');
	$('.lowerFooter').css('height','');
	
	lineHeight();
}
//
//$('.bodyTop').each(function(){
//debug($(this).height())
//})

function checkboxFix()
{
	$('div.rememberMe label').css('line-height','100%').hide().show().css('display','inline');
	$('div.rememberMe input').hide().show().css('float','right');
	$('div.rememberMe span').hide();
	$('fieldset label').hide().show();
	$('fieldset label select').css('position','relative');
}

function normaliseHeights(){
	//	Set minimum and normalise appplication box height
	$('.bodyTop').each(
		function(){
			div = $(this)
			vis = div.parents('.hpApplicationBox').css('display') != 'none';
			min = div.attr('min-height');
		
			
			if(!vis)
				div.parents('.hpApplicationBox').show();
				
			height = div.height();

			if(!vis)
				//debug('show next');

			if(div.height() > largestBody)
				largestBody = div.height();

			if(!vis)
				div.parents('.hpApplicationBox').hide();
								

			if(min)
				if(height <min)
					$('.bodyTop').height(min)


		}
	);
	
/*
	if($('.bodyTop').size())
		$('.bodyTop').height((largestBody/11.6)+'em');
*/

	
	//	Set minimum and normalise lower appplication box height
	$('.lowerTop').each(
		function(){
			div = $(this)
			height = div.height();
			min = div.attr('min-height');
		
			if(min)
				if(height <min)
					$('.bodyTop').height(min)
				
			if(div.height() > largestLowerBody)
				largestLowerBody = div.height();
			
		}
	);
/*
	if($('.lowerTop').size())
		$('.lowerTop').height((largestLowerBody/11.6)+'em');
*/

	//	Set minimum footer sizes;
	$('.bodyFooter').each(
		function(){
			div = $(this)
			
			height = div.height();
			target = 'height';

			if(height < 45)
				$('.bodyFooter').css(target,(50/12)+'em');
				
			if(div.height() > largestFooter)
				largestFooter = div.height();
		}
	);
	
	if($('.bodyFooter').size())
		$('.bodyFooter').height((largestFooter/11.5)+'em');
	
	
	//	Set minimum footer size;
	$('.lowerFooter').each(
		function(){
			div = $(this)
			
			height = div.height();
			target = 'height';

			if(height < 45)
				$('.lowerFooter').css(target,(47/12)+'em');
				
			if(div.height() > largestLowerFooter)
				largestLowerFooter = div.height();
			
		}
	);
	if($('.lowerFooter').size())
		$('.lowerFooter').height((Math.round(largestLowerFooter/11.6 * 10)/10)+'em');
	
	lineHeight();
	
}

function toggleSites(){
		//	Shows and loads site list in the popup box
		var link = $('#siteWideNavigation').find('.change');
		var open = link.attr('name').split('-')[0];
		var close = link.attr('name').split('-')[1];

		if(link.attr('isOpen') != 'true'){
			
			// changed 'isOpen' to 'isopen' to fix IE issue with no slideUp
			link.attr('isopen','true');
			link.html(close);
			
			if($('#popup').find('div.countries').size() > 0){
				$('#popup div.body').slideDown({ duration: 400, easing: 'easeInOutCirc'})
				
			}else{

				var loadedHtml = "";
				debug(countriesHtmlUrl());


				try{		
						//loadedHtml = $('#popup div.body').load( countriesHtmlUrl() );
					
					jsonRenderCountries(countriesHtmlUrl());
				}catch(e){debug(e);}


				//$('#popup div.body').html(loadedHtml);
				$('#popup div.body').slideDown({ duration: 400, easing: 'easeInOutCirc'})

				// Load the countries.shtml using ajax.
				//$('#popup div.body').load(
					// this function returns localised url which generates countries menu html
					// function defined in secondaryNavigation/start.jsp
				//	countriesHtmlUrl(),
				//	function(){
						$(this).slideDown({ duration: 400, easing: 'easeInOutCirc'})
				//	}
				//);
		  }
			toggleIFrame();
		}else{
			$('#popup div.body').slideUp({ duration: 400, easing: 'easeInOutCirc'});
			// changed 'isOpen' to 'isopen' to fix IE issue with no slideUp
			link.attr('isopen','false');
			link.html(open)
			toggleIFrame();
		}
		
		return false;
}

//	Simple function to change font size
function switchSize(styleSize)
{

		var large = $('#styleSize').attr('name').split('-')[0];
		var small = $('#styleSize').attr('name').split('-')[1];
		
       if(styleSize ==large){
			$('body').css('font-size','12pt').find('#styleSize').html(small)
			styleSize = large;
			autoHeights();
			$('#siteWideNavigation a.hasMenu').css('padding-bottom','9px');
		}else{
			$('body').css('font-size','10pt').find('#styleSize').html(large)
			styleSize = small;
			autoHeights();
			normaliseHeights();
			$('#siteWideNavigation a.hasMenu').css('padding-bottom','11px');
		}			

        createCookie('style', styleSize, 365);
}

// Show an iFrame uner our country dropdown list.
function toggleIFrame()
{
  // If the user has IE 6 then we need to make sure that selects don't show through.
  if (jQuery.browser.msie == true && jQuery.browser.version < 7) 
  {
    // If the iFrame exists...
		if ($('#iFrameHolder').length > 0)
		{
		  // remove it.
		  $('#iFrameHolder').remove();
		} else {
		  // create a new iframe.
      var popup = $('#popup');
      var popupOffset = popup.offset({ border: true, padding: true });
      // Create an iframe and place it in the siteWideNavigation div.
      $('#siteWideNavigation').append('<iframe id="iFrameHolder" src="#" tabindex="-1" '
	 					              +'style="display:block; position:absolute;'
						              +'z-index:98;filter:Alpha(Opacity=\'0\');"></iframe>');
  	  
  	  // Set the location and width of the item.
      $('#iFrameHolder').width(popup.width()).height($(document).height() - $('#siteWideNavigation').height()-20);
      $('#iFrameHolder').css('left', popupOffset.left).css('top', $('#siteWideNavigation').height());
    }
  }
}

function goURL(url) {
	 location.href=url;
}

// Prep the setup routine
$(document).ready(setup);